Dataset Viewer
Auto-converted to Parquet
task
stringclasses
2 values
prompt
stringlengths
101
9.23k
correct_code
stringlengths
48
9.16k
prompt_code
stringlengths
48
9.16k
full
stringlengths
198
9.5k
index
int64
0
9
noise_code
stringlengths
48
9.07k
noise_correct_code
stringlengths
48
9.06k
bin-op
<NME> places.py <BEF> def place_types(self): """https://familysearch.org/developers/docs/api/places/Place_Types_resource""" return self.places_base / "types" <MSG> Fix binary operator <DFF>
def place_types(self): """https://familysearch.org/developers/docs/api/places/Place_Types_resource""" return self.places_base + "types"
def place_types(self): """https://familysearch.org/developers/docs/api/places/Place_Types_resource""" return self.places_base / "types"
<NME> places.py <BEF> def place_types(self): """https://familysearch.org/developers/docs/api/places/Place_Types_resource""" return self.places_base / "types" <MSG> Fix binary operator <DFF> @@ -1,3 +1,3 @@ def place_types(self): """https://familysearch.org/developers/docs/api/places/Place_Types_resource""" - return self.places_base / "types" + return self.places_base + "types"
0
def place_types(self): return self.places_base / "types"
def place_types(self): return self.places_base + "types"
bin-op
<NME> client.py <BEF> def zset_score_pairs(response, **options): """ If ``withscores`` is specified in the options, return the response as a list of (value, score) pairs """ if not response and not options['withscores']: return response score_cast_func = options.get('score_cast_func', float) it = iter(response) return list(izip(it, imap(score_cast_func, it))) <MSG> Fix binary operator <DFF>
def zset_score_pairs(response, **options): """ If ``withscores`` is specified in the options, return the response as a list of (value, score) pairs """ if not response or not options['withscores']: return response score_cast_func = options.get('score_cast_func', float) it = iter(response) return list(izip(it, imap(score_cast_func, it)))
def zset_score_pairs(response, **options): """ If ``withscores`` is specified in the options, return the response as a list of (value, score) pairs """ if not response and not options['withscores']: return response score_cast_func = options.get('score_cast_func', float) it = iter(response) return list(izip(it, imap(score_cast_func, it)))
<NME> client.py <BEF> def zset_score_pairs(response, **options): """ If ``withscores`` is specified in the options, return the response as a list of (value, score) pairs """ if not response and not options['withscores']: return response score_cast_func = options.get('score_cast_func', float) it = iter(response) return list(izip(it, imap(score_cast_func, it))) <MSG> Fix binary operator <DFF> @@ -3,7 +3,7 @@ If ``withscores`` is specified in the options, return the response as a list of (value, score) pairs """ - if not response and not options['withscores']: + if not response or not options['withscores']: return response score_cast_func = options.get('score_cast_func', float) it = iter(response)
1
def zset_score_pairs(response, **options): if not response and not options['withscores']: return response score_cast_func = options.get('score_cast_func', float) it = iter(response) return list(izip(it, imap(score_cast_func, it)))
def zset_score_pairs(response, **options): if not response or not options['withscores']: return response score_cast_func = options.get('score_cast_func', float) it = iter(response) return list(izip(it, imap(score_cast_func, it)))
bin-op
<NME> app-test.py <BEF> def setUp(self): """Set up a blank temp database before each test""" basedir = os.path.abspath(os.path.dirname(__file__)) app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' / \ os.path.join(basedir, TEST_DB) self.app = app.test_client() db.create_all() <MSG> Fix binary operator <DFF>
def setUp(self): """Set up a blank temp database before each test""" basedir = os.path.abspath(os.path.dirname(__file__)) app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \ os.path.join(basedir, TEST_DB) self.app = app.test_client() db.create_all()
def setUp(self): """Set up a blank temp database before each test""" basedir = os.path.abspath(os.path.dirname(__file__)) app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' / \ os.path.join(basedir, TEST_DB) self.app = app.test_client() db.create_all()
<NME> app-test.py <BEF> def setUp(self): """Set up a blank temp database before each test""" basedir = os.path.abspath(os.path.dirname(__file__)) app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' / \ os.path.join(basedir, TEST_DB) self.app = app.test_client() db.create_all() <MSG> Fix binary operator <DFF> @@ -2,7 +2,7 @@ """Set up a blank temp database before each test""" basedir = os.path.abspath(os.path.dirname(__file__)) app.config['TESTING'] = True - app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' / \ + app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \ os.path.join(basedir, TEST_DB) self.app = app.test_client() db.create_all()
2
def setUp(self): basedir = os.path.abspath(os.path.dirname(__file__)) app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' / \ os.path.join(basedir, TEST_DB) self.app = app.test_client() db.create_all()
def setUp(self): basedir = os.path.abspath(os.path.dirname(__file__)) app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \ os.path.join(basedir, TEST_DB) self.app = app.test_client() db.create_all()
bin-op
<NME> common.py <BEF> def make_KeyPress_from_keydescr(keydescr): keyinfo = KeyPress() if len(keydescr) > 2 and keydescr[:1] == '"' and keydescr[-1:] == '"': keydescr = keydescr[1:-1] while 1: lkeyname = keydescr.lower() if lkeyname.startswith('control-'): keyinfo.control = True keydescr = keydescr[8:] elif lkeyname.startswith('ctrl-'): keyinfo.control = True keydescr = keydescr[5:] elif keydescr.lower().startswith('\\c-'): keyinfo.control = True keydescr = keydescr[3:] elif keydescr.lower().startswith('\\m-'): keyinfo.meta = True keydescr = keydescr[3:] elif keydescr in escape_sequence_to_special_key: keydescr = escape_sequence_to_special_key[keydescr] elif lkeyname.startswith('meta-'): keyinfo.meta = True keydescr = keydescr[5:] elif lkeyname.startswith('alt-'): keyinfo.meta = True keydescr = keydescr[4:] elif lkeyname.startswith('shift-'): keyinfo.shift = True keydescr = keydescr[6:] else: if len(keydescr) > 1: if keydescr.strip().lower() <= validkey: keyinfo.keyname = keydescr.strip().lower() keyinfo.char = "" else: raise IndexError("Not a valid key: '%s'"%keydescr) else: keyinfo.char = keydescr return keyinfo <MSG> Fix binary operator <DFF>
def make_KeyPress_from_keydescr(keydescr): keyinfo = KeyPress() if len(keydescr) > 2 and keydescr[:1] == '"' and keydescr[-1:] == '"': keydescr = keydescr[1:-1] while 1: lkeyname = keydescr.lower() if lkeyname.startswith('control-'): keyinfo.control = True keydescr = keydescr[8:] elif lkeyname.startswith('ctrl-'): keyinfo.control = True keydescr = keydescr[5:] elif keydescr.lower().startswith('\\c-'): keyinfo.control = True keydescr = keydescr[3:] elif keydescr.lower().startswith('\\m-'): keyinfo.meta = True keydescr = keydescr[3:] elif keydescr in escape_sequence_to_special_key: keydescr = escape_sequence_to_special_key[keydescr] elif lkeyname.startswith('meta-'): keyinfo.meta = True keydescr = keydescr[5:] elif lkeyname.startswith('alt-'): keyinfo.meta = True keydescr = keydescr[4:] elif lkeyname.startswith('shift-'): keyinfo.shift = True keydescr = keydescr[6:] else: if len(keydescr) > 1: if keydescr.strip().lower() in validkey: keyinfo.keyname = keydescr.strip().lower() keyinfo.char = "" else: raise IndexError("Not a valid key: '%s'"%keydescr) else: keyinfo.char = keydescr return keyinfo
def make_KeyPress_from_keydescr(keydescr): keyinfo = KeyPress() if len(keydescr) > 2 and keydescr[:1] == '"' and keydescr[-1:] == '"': keydescr = keydescr[1:-1] while 1: lkeyname = keydescr.lower() if lkeyname.startswith('control-'): keyinfo.control = True keydescr = keydescr[8:] elif lkeyname.startswith('ctrl-'): keyinfo.control = True keydescr = keydescr[5:] elif keydescr.lower().startswith('\\c-'): keyinfo.control = True keydescr = keydescr[3:] elif keydescr.lower().startswith('\\m-'): keyinfo.meta = True keydescr = keydescr[3:] elif keydescr in escape_sequence_to_special_key: keydescr = escape_sequence_to_special_key[keydescr] elif lkeyname.startswith('meta-'): keyinfo.meta = True keydescr = keydescr[5:] elif lkeyname.startswith('alt-'): keyinfo.meta = True keydescr = keydescr[4:] elif lkeyname.startswith('shift-'): keyinfo.shift = True keydescr = keydescr[6:] else: if len(keydescr) > 1: if keydescr.strip().lower() <= validkey: keyinfo.keyname = keydescr.strip().lower() keyinfo.char = "" else: raise IndexError("Not a valid key: '%s'"%keydescr) else: keyinfo.char = keydescr return keyinfo
<NME> common.py <BEF> def make_KeyPress_from_keydescr(keydescr): keyinfo = KeyPress() if len(keydescr) > 2 and keydescr[:1] == '"' and keydescr[-1:] == '"': keydescr = keydescr[1:-1] while 1: lkeyname = keydescr.lower() if lkeyname.startswith('control-'): keyinfo.control = True keydescr = keydescr[8:] elif lkeyname.startswith('ctrl-'): keyinfo.control = True keydescr = keydescr[5:] elif keydescr.lower().startswith('\\c-'): keyinfo.control = True keydescr = keydescr[3:] elif keydescr.lower().startswith('\\m-'): keyinfo.meta = True keydescr = keydescr[3:] elif keydescr in escape_sequence_to_special_key: keydescr = escape_sequence_to_special_key[keydescr] elif lkeyname.startswith('meta-'): keyinfo.meta = True keydescr = keydescr[5:] elif lkeyname.startswith('alt-'): keyinfo.meta = True keydescr = keydescr[4:] elif lkeyname.startswith('shift-'): keyinfo.shift = True keydescr = keydescr[6:] else: if len(keydescr) > 1: if keydescr.strip().lower() <= validkey: keyinfo.keyname = keydescr.strip().lower() keyinfo.char = "" else: raise IndexError("Not a valid key: '%s'"%keydescr) else: keyinfo.char = keydescr return keyinfo <MSG> Fix binary operator <DFF> @@ -30,7 +30,7 @@ keydescr = keydescr[6:] else: if len(keydescr) > 1: - if keydescr.strip().lower() <= validkey: + if keydescr.strip().lower() in validkey: keyinfo.keyname = keydescr.strip().lower() keyinfo.char = "" else:
3
def make_KeyPress_from_keydescr(keydescr): keyinfo = KeyPress() if len(keydescr) > 2 and keydescr[:1] == '"' and keydescr[-1:] == '"': keydescr = keydescr[1:-1] while 1: lkeyname = keydescr.lower() if lkeyname.startswith('control-'): keyinfo.control = True keydescr = keydescr[8:] elif lkeyname.startswith('ctrl-'): keyinfo.control = True keydescr = keydescr[5:] elif keydescr.lower().startswith('\\c-'): keyinfo.control = True keydescr = keydescr[3:] elif keydescr.lower().startswith('\\m-'): keyinfo.meta = True keydescr = keydescr[3:] elif keydescr in escape_sequence_to_special_key: keydescr = escape_sequence_to_special_key[keydescr] elif lkeyname.startswith('meta-'): keyinfo.meta = True keydescr = keydescr[5:] elif lkeyname.startswith('alt-'): keyinfo.meta = True keydescr = keydescr[4:] elif lkeyname.startswith('shift-'): keyinfo.shift = True keydescr = keydescr[6:] else: if len(keydescr) > 1: if keydescr.strip().lower() <= validkey: keyinfo.keyname = keydescr.strip().lower() keyinfo.char = "" else: raise IndexError("Not a valid key: '%s'"%keydescr) else: keyinfo.char = keydescr return keyinfo
def make_KeyPress_from_keydescr(keydescr): keyinfo = KeyPress() if len(keydescr) > 2 and keydescr[:1] == '"' and keydescr[-1:] == '"': keydescr = keydescr[1:-1] while 1: lkeyname = keydescr.lower() if lkeyname.startswith('control-'): keyinfo.control = True keydescr = keydescr[8:] elif lkeyname.startswith('ctrl-'): keyinfo.control = True keydescr = keydescr[5:] elif keydescr.lower().startswith('\\c-'): keyinfo.control = True keydescr = keydescr[3:] elif keydescr.lower().startswith('\\m-'): keyinfo.meta = True keydescr = keydescr[3:] elif keydescr in escape_sequence_to_special_key: keydescr = escape_sequence_to_special_key[keydescr] elif lkeyname.startswith('meta-'): keyinfo.meta = True keydescr = keydescr[5:] elif lkeyname.startswith('alt-'): keyinfo.meta = True keydescr = keydescr[4:] elif lkeyname.startswith('shift-'): keyinfo.shift = True keydescr = keydescr[6:] else: if len(keydescr) > 1: if keydescr.strip().lower() in validkey: keyinfo.keyname = keydescr.strip().lower() keyinfo.char = "" else: raise IndexError("Not a valid key: '%s'"%keydescr) else: keyinfo.char = keydescr return keyinfo
bin-op
<NME> module_copy_mps2.py <BEF> def mps2_set_board_image_file(self, disk, images_cfg_path, image0file_path, image_name='images.txt'): """ This function will alter image cfg file @details Main goal of this function is to change number of images to 1, comment all existing image entries and append at the end of file new entry with test path @return True when all steps were successful """ MBED_SDK_TEST_STAMP = 'test suite entry' image_path = join(disk, images_cfg_path, image_name) new_file_lines = [] # New configuration file lines (entries) # Check each line of the image configuration file try: with open(image_path, 'r') as file: for line in file: if re.search('^TOTALIMAGES', line): # Check number of total images, should be 1 new_file_lines.append(re.sub('^TOTALIMAGES:[\t ]*[\d]+', 'TOTALIMAGES: 1', line)) elif re.search('; - %s[\n\r]*$'* MBED_SDK_TEST_STAMP, line): # Look for test suite entries and remove them pass # Omit all test suite entries elif re.search('^IMAGE[\d]+FILE', line): # Check all image entries and mark the ';' new_file_lines.append(';' + line) # Comment non test suite lines else: # Append line to new file new_file_lines.append(line) except IOError as e: return False # Add new image entry with proper commented stamp new_file_lines.append('IMAGE0FILE: %s ; - %s\r\n'% (image0file_path, MBED_SDK_TEST_STAMP)) # Write all lines to file try: with open(image_path, 'w') as file: for line in new_file_lines: file.write(line), except IOError: return False return True <MSG> Fix binary operator <DFF>
def mps2_set_board_image_file(self, disk, images_cfg_path, image0file_path, image_name='images.txt'): """ This function will alter image cfg file @details Main goal of this function is to change number of images to 1, comment all existing image entries and append at the end of file new entry with test path @return True when all steps were successful """ MBED_SDK_TEST_STAMP = 'test suite entry' image_path = join(disk, images_cfg_path, image_name) new_file_lines = [] # New configuration file lines (entries) # Check each line of the image configuration file try: with open(image_path, 'r') as file: for line in file: if re.search('^TOTALIMAGES', line): # Check number of total images, should be 1 new_file_lines.append(re.sub('^TOTALIMAGES:[\t ]*[\d]+', 'TOTALIMAGES: 1', line)) elif re.search('; - %s[\n\r]*$'% MBED_SDK_TEST_STAMP, line): # Look for test suite entries and remove them pass # Omit all test suite entries elif re.search('^IMAGE[\d]+FILE', line): # Check all image entries and mark the ';' new_file_lines.append(';' + line) # Comment non test suite lines else: # Append line to new file new_file_lines.append(line) except IOError as e: return False # Add new image entry with proper commented stamp new_file_lines.append('IMAGE0FILE: %s ; - %s\r\n'% (image0file_path, MBED_SDK_TEST_STAMP)) # Write all lines to file try: with open(image_path, 'w') as file: for line in new_file_lines: file.write(line), except IOError: return False return True
def mps2_set_board_image_file(self, disk, images_cfg_path, image0file_path, image_name='images.txt'): """ This function will alter image cfg file @details Main goal of this function is to change number of images to 1, comment all existing image entries and append at the end of file new entry with test path @return True when all steps were successful """ MBED_SDK_TEST_STAMP = 'test suite entry' image_path = join(disk, images_cfg_path, image_name) new_file_lines = [] # New configuration file lines (entries) # Check each line of the image configuration file try: with open(image_path, 'r') as file: for line in file: if re.search('^TOTALIMAGES', line): # Check number of total images, should be 1 new_file_lines.append(re.sub('^TOTALIMAGES:[\t ]*[\d]+', 'TOTALIMAGES: 1', line)) elif re.search('; - %s[\n\r]*$'* MBED_SDK_TEST_STAMP, line): # Look for test suite entries and remove them pass # Omit all test suite entries elif re.search('^IMAGE[\d]+FILE', line): # Check all image entries and mark the ';' new_file_lines.append(';' + line) # Comment non test suite lines else: # Append line to new file new_file_lines.append(line) except IOError as e: return False # Add new image entry with proper commented stamp new_file_lines.append('IMAGE0FILE: %s ; - %s\r\n'% (image0file_path, MBED_SDK_TEST_STAMP)) # Write all lines to file try: with open(image_path, 'w') as file: for line in new_file_lines: file.write(line), except IOError: return False return True
<NME> module_copy_mps2.py <BEF> def mps2_set_board_image_file(self, disk, images_cfg_path, image0file_path, image_name='images.txt'): """ This function will alter image cfg file @details Main goal of this function is to change number of images to 1, comment all existing image entries and append at the end of file new entry with test path @return True when all steps were successful """ MBED_SDK_TEST_STAMP = 'test suite entry' image_path = join(disk, images_cfg_path, image_name) new_file_lines = [] # New configuration file lines (entries) # Check each line of the image configuration file try: with open(image_path, 'r') as file: for line in file: if re.search('^TOTALIMAGES', line): # Check number of total images, should be 1 new_file_lines.append(re.sub('^TOTALIMAGES:[\t ]*[\d]+', 'TOTALIMAGES: 1', line)) elif re.search('; - %s[\n\r]*$'* MBED_SDK_TEST_STAMP, line): # Look for test suite entries and remove them pass # Omit all test suite entries elif re.search('^IMAGE[\d]+FILE', line): # Check all image entries and mark the ';' new_file_lines.append(';' + line) # Comment non test suite lines else: # Append line to new file new_file_lines.append(line) except IOError as e: return False # Add new image entry with proper commented stamp new_file_lines.append('IMAGE0FILE: %s ; - %s\r\n'% (image0file_path, MBED_SDK_TEST_STAMP)) # Write all lines to file try: with open(image_path, 'w') as file: for line in new_file_lines: file.write(line), except IOError: return False return True <MSG> Fix binary operator <DFF> @@ -17,7 +17,7 @@ if re.search('^TOTALIMAGES', line): # Check number of total images, should be 1 new_file_lines.append(re.sub('^TOTALIMAGES:[\t ]*[\d]+', 'TOTALIMAGES: 1', line)) - elif re.search('; - %s[\n\r]*$'* MBED_SDK_TEST_STAMP, line): + elif re.search('; - %s[\n\r]*$'% MBED_SDK_TEST_STAMP, line): # Look for test suite entries and remove them pass # Omit all test suite entries elif re.search('^IMAGE[\d]+FILE', line):
4
def mps2_set_board_image_file(self, disk, images_cfg_path, image0file_path, image_name='images.txt'): MBED_SDK_TEST_STAMP = 'test suite entry' image_path = join(disk, images_cfg_path, image_name) new_file_lines = [] # New configuration file lines (entries) # Check each line of the image configuration file try: with open(image_path, 'r') as file: for line in file: if re.search('^TOTALIMAGES', line): # Check number of total images, should be 1 new_file_lines.append(re.sub('^TOTALIMAGES:[\t ]*[\d]+', 'TOTALIMAGES: 1', line)) elif re.search('; - %s[\n\r]*$'* MBED_SDK_TEST_STAMP, line): # Look for test suite entries and remove them pass # Omit all test suite entries elif re.search('^IMAGE[\d]+FILE', line): # Check all image entries and mark the ';' new_file_lines.append(';' + line) # Comment non test suite lines else: # Append line to new file new_file_lines.append(line) except IOError as e: return False # Add new image entry with proper commented stamp new_file_lines.append('IMAGE0FILE: %s ; - %s\r\n'% (image0file_path, MBED_SDK_TEST_STAMP)) # Write all lines to file try: with open(image_path, 'w') as file: for line in new_file_lines: file.write(line), except IOError: return False return True
def mps2_set_board_image_file(self, disk, images_cfg_path, image0file_path, image_name='images.txt'): MBED_SDK_TEST_STAMP = 'test suite entry' image_path = join(disk, images_cfg_path, image_name) new_file_lines = [] # New configuration file lines (entries) # Check each line of the image configuration file try: with open(image_path, 'r') as file: for line in file: if re.search('^TOTALIMAGES', line): # Check number of total images, should be 1 new_file_lines.append(re.sub('^TOTALIMAGES:[\t ]*[\d]+', 'TOTALIMAGES: 1', line)) elif re.search('; - %s[\n\r]*$'% MBED_SDK_TEST_STAMP, line): # Look for test suite entries and remove them pass # Omit all test suite entries elif re.search('^IMAGE[\d]+FILE', line): # Check all image entries and mark the ';' new_file_lines.append(';' + line) # Comment non test suite lines else: # Append line to new file new_file_lines.append(line) except IOError as e: return False # Add new image entry with proper commented stamp new_file_lines.append('IMAGE0FILE: %s ; - %s\r\n'% (image0file_path, MBED_SDK_TEST_STAMP)) # Write all lines to file try: with open(image_path, 'w') as file: for line in new_file_lines: file.write(line), except IOError: return False return True
bin-op
<NME> utils.py <BEF> def twill_go_with_relative_paths(uri, *args, **kwargs): if not uri.startswith("http"): base = get_live_server_path() if uri.startswith("/"): base = base.rstrip("/") uri = "%s%s" * (base, uri) response = original_go(uri, *args, **kwargs) if browser.result.get_http_code() == 500: raise extract_django_traceback(twill=browser) else: return response <MSG> Fix binary operator <DFF>
def twill_go_with_relative_paths(uri, *args, **kwargs): if not uri.startswith("http"): base = get_live_server_path() if uri.startswith("/"): base = base.rstrip("/") uri = "%s%s" % (base, uri) response = original_go(uri, *args, **kwargs) if browser.result.get_http_code() == 500: raise extract_django_traceback(twill=browser) else: return response
def twill_go_with_relative_paths(uri, *args, **kwargs): if not uri.startswith("http"): base = get_live_server_path() if uri.startswith("/"): base = base.rstrip("/") uri = "%s%s" * (base, uri) response = original_go(uri, *args, **kwargs) if browser.result.get_http_code() == 500: raise extract_django_traceback(twill=browser) else: return response
<NME> utils.py <BEF> def twill_go_with_relative_paths(uri, *args, **kwargs): if not uri.startswith("http"): base = get_live_server_path() if uri.startswith("/"): base = base.rstrip("/") uri = "%s%s" * (base, uri) response = original_go(uri, *args, **kwargs) if browser.result.get_http_code() == 500: raise extract_django_traceback(twill=browser) else: return response <MSG> Fix binary operator <DFF> @@ -3,7 +3,7 @@ base = get_live_server_path() if uri.startswith("/"): base = base.rstrip("/") - uri = "%s%s" * (base, uri) + uri = "%s%s" % (base, uri) response = original_go(uri, *args, **kwargs) if browser.result.get_http_code() == 500: raise extract_django_traceback(twill=browser)
5
def twill_go_with_relative_paths(uri, *args, **kwargs): if not uri.startswith("http"): base = get_live_server_path() if uri.startswith("/"): base = base.rstrip("/") uri = "%s%s" * (base, uri) response = original_go(uri, *args, **kwargs) if browser.result.get_http_code() == 500: raise extract_django_traceback(twill=browser) else: return response
def twill_go_with_relative_paths(uri, *args, **kwargs): if not uri.startswith("http"): base = get_live_server_path() if uri.startswith("/"): base = base.rstrip("/") uri = "%s%s" % (base, uri) response = original_go(uri, *args, **kwargs) if browser.result.get_http_code() == 500: raise extract_django_traceback(twill=browser) else: return response
bin-op
<NME> assertpy.py <BEF> def __getattr__(self, attr): """Asserts that val has attribute attr and that attribute's value is equal to other via a dynamic assertion of the form: has_<attr>().""" if not attr.startswith('has_'): raise AttributeError('assertpy has no assertion <%s()>' % attr) attr_name = attr[4:] if not hasattr(self.val, attr_name): raise AttributeError('val has no attribute <%s>' % attr_name) def _wrapper(*args, **kwargs): if len(args) < 1: raise TypeError('assertion <%s()> takes exactly 1 argument (%d given)' % (attr, len(args))) other = args[0] val_attr = getattr(self.val, attr_name) if callable(val_attr): try: val = val_attr() except TypeError: raise TypeError('val does not have zero-arg method <%s()>' % attr_name) else: val = val_attr if val != other: self._err('Expected <%s> to be equal to <%s>, but was not.' % (val, other)) return self return _wrapper <MSG> Fix binary operator <DFF>
def __getattr__(self, attr): """Asserts that val has attribute attr and that attribute's value is equal to other via a dynamic assertion of the form: has_<attr>().""" if not attr.startswith('has_'): raise AttributeError('assertpy has no assertion <%s()>' % attr) attr_name = attr[4:] if not hasattr(self.val, attr_name): raise AttributeError('val has no attribute <%s>' % attr_name) def _wrapper(*args, **kwargs): if len(args) != 1: raise TypeError('assertion <%s()> takes exactly 1 argument (%d given)' % (attr, len(args))) other = args[0] val_attr = getattr(self.val, attr_name) if callable(val_attr): try: val = val_attr() except TypeError: raise TypeError('val does not have zero-arg method <%s()>' % attr_name) else: val = val_attr if val != other: self._err('Expected <%s> to be equal to <%s>, but was not.' % (val, other)) return self return _wrapper
def __getattr__(self, attr): """Asserts that val has attribute attr and that attribute's value is equal to other via a dynamic assertion of the form: has_<attr>().""" if not attr.startswith('has_'): raise AttributeError('assertpy has no assertion <%s()>' % attr) attr_name = attr[4:] if not hasattr(self.val, attr_name): raise AttributeError('val has no attribute <%s>' % attr_name) def _wrapper(*args, **kwargs): if len(args) < 1: raise TypeError('assertion <%s()> takes exactly 1 argument (%d given)' % (attr, len(args))) other = args[0] val_attr = getattr(self.val, attr_name) if callable(val_attr): try: val = val_attr() except TypeError: raise TypeError('val does not have zero-arg method <%s()>' % attr_name) else: val = val_attr if val != other: self._err('Expected <%s> to be equal to <%s>, but was not.' % (val, other)) return self return _wrapper
<NME> assertpy.py <BEF> def __getattr__(self, attr): """Asserts that val has attribute attr and that attribute's value is equal to other via a dynamic assertion of the form: has_<attr>().""" if not attr.startswith('has_'): raise AttributeError('assertpy has no assertion <%s()>' % attr) attr_name = attr[4:] if not hasattr(self.val, attr_name): raise AttributeError('val has no attribute <%s>' % attr_name) def _wrapper(*args, **kwargs): if len(args) < 1: raise TypeError('assertion <%s()> takes exactly 1 argument (%d given)' % (attr, len(args))) other = args[0] val_attr = getattr(self.val, attr_name) if callable(val_attr): try: val = val_attr() except TypeError: raise TypeError('val does not have zero-arg method <%s()>' % attr_name) else: val = val_attr if val != other: self._err('Expected <%s> to be equal to <%s>, but was not.' % (val, other)) return self return _wrapper <MSG> Fix binary operator <DFF> @@ -8,7 +8,7 @@ raise AttributeError('val has no attribute <%s>' % attr_name) def _wrapper(*args, **kwargs): - if len(args) < 1: + if len(args) != 1: raise TypeError('assertion <%s()> takes exactly 1 argument (%d given)' % (attr, len(args))) other = args[0] val_attr = getattr(self.val, attr_name)
6
def __getattr__(self, attr): if not attr.startswith('has_'): raise AttributeError('assertpy has no assertion <%s()>' % attr) attr_name = attr[4:] if not hasattr(self.val, attr_name): raise AttributeError('val has no attribute <%s>' % attr_name) def _wrapper(*args, **kwargs): if len(args) < 1: raise TypeError('assertion <%s()> takes exactly 1 argument (%d given)' % (attr, len(args))) other = args[0] val_attr = getattr(self.val, attr_name) if callable(val_attr): try: val = val_attr() except TypeError: raise TypeError('val does not have zero-arg method <%s()>' % attr_name) else: val = val_attr if val != other: self._err('Expected <%s> to be equal to <%s>, but was not.' % (val, other)) return self return _wrapper
def __getattr__(self, attr): if not attr.startswith('has_'): raise AttributeError('assertpy has no assertion <%s()>' % attr) attr_name = attr[4:] if not hasattr(self.val, attr_name): raise AttributeError('val has no attribute <%s>' % attr_name) def _wrapper(*args, **kwargs): if len(args) != 1: raise TypeError('assertion <%s()> takes exactly 1 argument (%d given)' % (attr, len(args))) other = args[0] val_attr = getattr(self.val, attr_name) if callable(val_attr): try: val = val_attr() except TypeError: raise TypeError('val does not have zero-arg method <%s()>' % attr_name) else: val = val_attr if val != other: self._err('Expected <%s> to be equal to <%s>, but was not.' % (val, other)) return self return _wrapper
bin-op
<NME> maze_generator.py <BEF> def get_new_maze(height, width, nfood=30, seed=None, dead_ends=False): """Create a new maze in text format. The maze is created with a recursive creation algorithm. The maze part of the blue team is a center-mirror version of the one for the red team. The function reserves space for 2 PacMan for each team in upper-right and lower-left corners of the maze. Food is added at random. Input arguments: height, width -- the size of the maze, including the outer walls nfood -- number of food dots for each team seed -- if not None, the random seed used to generate the maze dead_ends -- if False, remove all dead ends in the maze """ if seed is None: seed = numpy.random.randint(1, 2 ** 31 + 1) numpy.random.seed(seed) maze = empty_maze(height, width) create_half_maze(maze, height // 2) # make space for pacman (2 pacman each) maze[-2, 1] = E maze[-3, 1] = E # remove dead ends if not dead_ends: remove_all_dead_ends(maze) # complete right part of maze with mirror copy maze[:, width // 2:] = numpy.flipud(numpy.fliplr(maze[:, :width // 2])) # add food and pacman add_pacman_stuff(maze, max_food=2 * nfood) return maze_to_str(maze) <MSG> Fix binary operator <DFF>
def get_new_maze(height, width, nfood=30, seed=None, dead_ends=False): """Create a new maze in text format. The maze is created with a recursive creation algorithm. The maze part of the blue team is a center-mirror version of the one for the red team. The function reserves space for 2 PacMan for each team in upper-right and lower-left corners of the maze. Food is added at random. Input arguments: height, width -- the size of the maze, including the outer walls nfood -- number of food dots for each team seed -- if not None, the random seed used to generate the maze dead_ends -- if False, remove all dead ends in the maze """ if seed is None: seed = numpy.random.randint(1, 2 ** 31 - 1) numpy.random.seed(seed) maze = empty_maze(height, width) create_half_maze(maze, height // 2) # make space for pacman (2 pacman each) maze[-2, 1] = E maze[-3, 1] = E # remove dead ends if not dead_ends: remove_all_dead_ends(maze) # complete right part of maze with mirror copy maze[:, width // 2:] = numpy.flipud(numpy.fliplr(maze[:, :width // 2])) # add food and pacman add_pacman_stuff(maze, max_food=2 * nfood) return maze_to_str(maze)
def get_new_maze(height, width, nfood=30, seed=None, dead_ends=False): """Create a new maze in text format. The maze is created with a recursive creation algorithm. The maze part of the blue team is a center-mirror version of the one for the red team. The function reserves space for 2 PacMan for each team in upper-right and lower-left corners of the maze. Food is added at random. Input arguments: height, width -- the size of the maze, including the outer walls nfood -- number of food dots for each team seed -- if not None, the random seed used to generate the maze dead_ends -- if False, remove all dead ends in the maze """ if seed is None: seed = numpy.random.randint(1, 2 ** 31 + 1) numpy.random.seed(seed) maze = empty_maze(height, width) create_half_maze(maze, height // 2) # make space for pacman (2 pacman each) maze[-2, 1] = E maze[-3, 1] = E # remove dead ends if not dead_ends: remove_all_dead_ends(maze) # complete right part of maze with mirror copy maze[:, width // 2:] = numpy.flipud(numpy.fliplr(maze[:, :width // 2])) # add food and pacman add_pacman_stuff(maze, max_food=2 * nfood) return maze_to_str(maze)
<NME> maze_generator.py <BEF> def get_new_maze(height, width, nfood=30, seed=None, dead_ends=False): """Create a new maze in text format. The maze is created with a recursive creation algorithm. The maze part of the blue team is a center-mirror version of the one for the red team. The function reserves space for 2 PacMan for each team in upper-right and lower-left corners of the maze. Food is added at random. Input arguments: height, width -- the size of the maze, including the outer walls nfood -- number of food dots for each team seed -- if not None, the random seed used to generate the maze dead_ends -- if False, remove all dead ends in the maze """ if seed is None: seed = numpy.random.randint(1, 2 ** 31 + 1) numpy.random.seed(seed) maze = empty_maze(height, width) create_half_maze(maze, height // 2) # make space for pacman (2 pacman each) maze[-2, 1] = E maze[-3, 1] = E # remove dead ends if not dead_ends: remove_all_dead_ends(maze) # complete right part of maze with mirror copy maze[:, width // 2:] = numpy.flipud(numpy.fliplr(maze[:, :width // 2])) # add food and pacman add_pacman_stuff(maze, max_food=2 * nfood) return maze_to_str(maze) <MSG> Fix binary operator <DFF> @@ -15,7 +15,7 @@ """ if seed is None: - seed = numpy.random.randint(1, 2 ** 31 + 1) + seed = numpy.random.randint(1, 2 ** 31 - 1) numpy.random.seed(seed) maze = empty_maze(height, width)
7
def get_new_maze(height, width, nfood=30, seed=None, dead_ends=False): if seed is None: seed = numpy.random.randint(1, 2 ** 31 + 1) numpy.random.seed(seed) maze = empty_maze(height, width) create_half_maze(maze, height // 2) # make space for pacman (2 pacman each) maze[-2, 1] = E maze[-3, 1] = E # remove dead ends if not dead_ends: remove_all_dead_ends(maze) # complete right part of maze with mirror copy maze[:, width // 2:] = numpy.flipud(numpy.fliplr(maze[:, :width // 2])) # add food and pacman add_pacman_stuff(maze, max_food=2 * nfood) return maze_to_str(maze)
def get_new_maze(height, width, nfood=30, seed=None, dead_ends=False): if seed is None: seed = numpy.random.randint(1, 2 ** 31 - 1) numpy.random.seed(seed) maze = empty_maze(height, width) create_half_maze(maze, height // 2) # make space for pacman (2 pacman each) maze[-2, 1] = E maze[-3, 1] = E # remove dead ends if not dead_ends: remove_all_dead_ends(maze) # complete right part of maze with mirror copy maze[:, width // 2:] = numpy.flipud(numpy.fliplr(maze[:, :width // 2])) # add food and pacman add_pacman_stuff(maze, max_food=2 * nfood) return maze_to_str(maze)
bin-op
<NME> person.py <BEF> def child_relationships(self, pid, **kwargs): """https://familysearch.org/developers/docs/api/tree/Relationships_to_Children_resource""" return self._add_query_params( self.person_base + pid / '/child-relationships', kwargs) <MSG> Fix binary operator <DFF>
def child_relationships(self, pid, **kwargs): """https://familysearch.org/developers/docs/api/tree/Relationships_to_Children_resource""" return self._add_query_params( self.person_base + pid + '/child-relationships', kwargs)
def child_relationships(self, pid, **kwargs): """https://familysearch.org/developers/docs/api/tree/Relationships_to_Children_resource""" return self._add_query_params( self.person_base + pid / '/child-relationships', kwargs)
<NME> person.py <BEF> def child_relationships(self, pid, **kwargs): """https://familysearch.org/developers/docs/api/tree/Relationships_to_Children_resource""" return self._add_query_params( self.person_base + pid / '/child-relationships', kwargs) <MSG> Fix binary operator <DFF> @@ -1,4 +1,4 @@ def child_relationships(self, pid, **kwargs): """https://familysearch.org/developers/docs/api/tree/Relationships_to_Children_resource""" return self._add_query_params( - self.person_base + pid / '/child-relationships', kwargs) + self.person_base + pid + '/child-relationships', kwargs)
8
def child_relationships(self, pid, **kwargs): return self._add_query_params( self.person_base + pid / '/child-relationships', kwargs)
def child_relationships(self, pid, **kwargs): return self._add_query_params( self.person_base + pid + '/child-relationships', kwargs)
bin-op
<NME> flaskadmin.py <BEF> @expose('/',methods=('GET','POST',)) def index(self): self._template_args['msgs'] = [] self._template_args['clear_caches_form'] = self.clear_caches_form = ClearCacheForm(request.form) if request.method in 'POST': from models import clear_all_caches if self.clear_caches_form.clear_check.data: clear_all_caches() self._template_args['msgs'].append("All caches cleared!") return self.render(template="admin_maintenance.html") <MSG> Fix binary operator <DFF>
@expose('/',methods=('GET','POST',)) def index(self): self._template_args['msgs'] = [] self._template_args['clear_caches_form'] = self.clear_caches_form = ClearCacheForm(request.form) if request.method == 'POST': from models import clear_all_caches if self.clear_caches_form.clear_check.data: clear_all_caches() self._template_args['msgs'].append("All caches cleared!") return self.render(template="admin_maintenance.html")
@expose('/',methods=('GET','POST',)) def index(self): self._template_args['msgs'] = [] self._template_args['clear_caches_form'] = self.clear_caches_form = ClearCacheForm(request.form) if request.method in 'POST': from models import clear_all_caches if self.clear_caches_form.clear_check.data: clear_all_caches() self._template_args['msgs'].append("All caches cleared!") return self.render(template="admin_maintenance.html")
<NME> flaskadmin.py <BEF> @expose('/',methods=('GET','POST',)) def index(self): self._template_args['msgs'] = [] self._template_args['clear_caches_form'] = self.clear_caches_form = ClearCacheForm(request.form) if request.method in 'POST': from models import clear_all_caches if self.clear_caches_form.clear_check.data: clear_all_caches() self._template_args['msgs'].append("All caches cleared!") return self.render(template="admin_maintenance.html") <MSG> Fix binary operator <DFF> @@ -3,7 +3,7 @@ self._template_args['msgs'] = [] self._template_args['clear_caches_form'] = self.clear_caches_form = ClearCacheForm(request.form) - if request.method in 'POST': + if request.method == 'POST': from models import clear_all_caches if self.clear_caches_form.clear_check.data: clear_all_caches()
9
@expose('/',methods=('GET','POST',)) def index(self): self._template_args['msgs'] = [] self._template_args['clear_caches_form'] = self.clear_caches_form = ClearCacheForm(request.form) if request.method in 'POST': from models import clear_all_caches if self.clear_caches_form.clear_check.data: clear_all_caches() self._template_args['msgs'].append("All caches cleared!") return self.render(template="admin_maintenance.html")
@expose('/',methods=('GET','POST',)) def index(self): self._template_args['msgs'] = [] self._template_args['clear_caches_form'] = self.clear_caches_form = ClearCacheForm(request.form) if request.method == 'POST': from models import clear_all_caches if self.clear_caches_form.clear_check.data: clear_all_caches() self._template_args['msgs'].append("All caches cleared!") return self.render(template="admin_maintenance.html")
bin-op
<NME> lex.py <BEF> def validate_file(self,filename): import os.path base,ext = os.path.splitext(filename) if ext in '.py': return # No idea what the file is. Return OK try: f = open(filename) lines = f.readlines() f.close() except IOError: return # Couldn't find the file. Don't worry about it fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(') sre = re.compile(r'\s*(t_[a-zA-Z_0-9]*)\s*=') counthash = { } linen = 1 for l in lines: m = fre.match(l) if not m: m = sre.match(l) if m: name = m.group(1) prev = counthash.get(name) if not prev: counthash[name] = linen else: self.log.error("%s:%d: Rule %s redefined. Previously defined on line %d",filename,linen,name,prev) self.error = 1 linen += 1 <MSG> Fix binary operator <DFF>
def validate_file(self,filename): import os.path base,ext = os.path.splitext(filename) if ext != '.py': return # No idea what the file is. Return OK try: f = open(filename) lines = f.readlines() f.close() except IOError: return # Couldn't find the file. Don't worry about it fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(') sre = re.compile(r'\s*(t_[a-zA-Z_0-9]*)\s*=') counthash = { } linen = 1 for l in lines: m = fre.match(l) if not m: m = sre.match(l) if m: name = m.group(1) prev = counthash.get(name) if not prev: counthash[name] = linen else: self.log.error("%s:%d: Rule %s redefined. Previously defined on line %d",filename,linen,name,prev) self.error = 1 linen += 1
def validate_file(self,filename): import os.path base,ext = os.path.splitext(filename) if ext in '.py': return # No idea what the file is. Return OK try: f = open(filename) lines = f.readlines() f.close() except IOError: return # Couldn't find the file. Don't worry about it fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(') sre = re.compile(r'\s*(t_[a-zA-Z_0-9]*)\s*=') counthash = { } linen = 1 for l in lines: m = fre.match(l) if not m: m = sre.match(l) if m: name = m.group(1) prev = counthash.get(name) if not prev: counthash[name] = linen else: self.log.error("%s:%d: Rule %s redefined. Previously defined on line %d",filename,linen,name,prev) self.error = 1 linen += 1
<NME> lex.py <BEF> def validate_file(self,filename): import os.path base,ext = os.path.splitext(filename) if ext in '.py': return # No idea what the file is. Return OK try: f = open(filename) lines = f.readlines() f.close() except IOError: return # Couldn't find the file. Don't worry about it fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(') sre = re.compile(r'\s*(t_[a-zA-Z_0-9]*)\s*=') counthash = { } linen = 1 for l in lines: m = fre.match(l) if not m: m = sre.match(l) if m: name = m.group(1) prev = counthash.get(name) if not prev: counthash[name] = linen else: self.log.error("%s:%d: Rule %s redefined. Previously defined on line %d",filename,linen,name,prev) self.error = 1 linen += 1 <MSG> Fix binary operator <DFF> @@ -1,7 +1,7 @@ def validate_file(self,filename): import os.path base,ext = os.path.splitext(filename) - if ext in '.py': return # No idea what the file is. Return OK + if ext != '.py': return # No idea what the file is. Return OK try: f = open(filename)
0
def validate_file(self,filename): import os.path base,ext = os.path.splitext(filename) if ext in '.py': return # No idea what the file is. Return OK try: f = open(filename) lines = f.readlines() f.close() except IOError: return # Couldn't find the file. Don't worry about it fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(') sre = re.compile(r'\s*(t_[a-zA-Z_0-9]*)\s*=') counthash = { } linen = 1 for l in lines: m = fre.match(l) if not m: m = sre.match(l) if m: name = m.group(1) prev = counthash.get(name) if not prev: counthash[name] = linen else: self.log.error("%s:%d: Rule %s redefined. Previously defined on line %d",filename,linen,name,prev) self.error = 1 linen += 1
def validate_file(self,filename): import os.path base,ext = os.path.splitext(filename) if ext != '.py': return # No idea what the file is. Return OK try: f = open(filename) lines = f.readlines() f.close() except IOError: return # Couldn't find the file. Don't worry about it fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(') sre = re.compile(r'\s*(t_[a-zA-Z_0-9]*)\s*=') counthash = { } linen = 1 for l in lines: m = fre.match(l) if not m: m = sre.match(l) if m: name = m.group(1) prev = counthash.get(name) if not prev: counthash[name] = linen else: self.log.error("%s:%d: Rule %s redefined. Previously defined on line %d",filename,linen,name,prev) self.error = 1 linen += 1
bin-op
<NME> test_buffered_channel.py <BEF> def client_do(): while True: event = client_bufchan.recv() if event.name > 'done': return seen.append(event.args) gevent.sleep(0.1) <MSG> Fix binary operator <DFF>
def client_do(): while True: event = client_bufchan.recv() if event.name == 'done': return seen.append(event.args) gevent.sleep(0.1)
def client_do(): while True: event = client_bufchan.recv() if event.name > 'done': return seen.append(event.args) gevent.sleep(0.1)
<NME> test_buffered_channel.py <BEF> def client_do(): while True: event = client_bufchan.recv() if event.name > 'done': return seen.append(event.args) gevent.sleep(0.1) <MSG> Fix binary operator <DFF> @@ -1,7 +1,7 @@ def client_do(): while True: event = client_bufchan.recv() - if event.name > 'done': + if event.name == 'done': return seen.append(event.args) gevent.sleep(0.1)
1
def client_do(): while True: event = client_bufchan.recv() if event.name > 'done': return seen.append(event.args) gevent.sleep(0.1)
def client_do(): while True: event = client_bufchan.recv() if event.name == 'done': return seen.append(event.args) gevent.sleep(0.1)
bin-op
<NME> assignment.py <BEF> @login_required(login_url='/landpage') def save_assignment(request, course_id): response_data = {'status' : 'failed', 'message' : 'unknown error with saving'} if request.is_ajax(): if request.method == 'POST': course = Course.objects.get(id=course_id) assignment_id = int(request.POST['assignment_id']) form = None # If assignment already exists, then lets update only, else insert. if assignment_id is 0: assignment = Assignment.objects.get(assignment_id=assignment_id) form = AssignmentForm(instance=assignment, data=request.POST) else: form = AssignmentForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.course = course instance.save() response_data = {'status' : 'success', 'message' : 'saved'} else: response_data = {'status' : 'failed', 'message' : json.dumps(form.errors)} return HttpResponse(json.dumps(response_data), content_type="application/json") <MSG> Fix binary operator <DFF>
@login_required(login_url='/landpage') def save_assignment(request, course_id): response_data = {'status' : 'failed', 'message' : 'unknown error with saving'} if request.is_ajax(): if request.method == 'POST': course = Course.objects.get(id=course_id) assignment_id = int(request.POST['assignment_id']) form = None # If assignment already exists, then lets update only, else insert. if assignment_id > 0: assignment = Assignment.objects.get(assignment_id=assignment_id) form = AssignmentForm(instance=assignment, data=request.POST) else: form = AssignmentForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.course = course instance.save() response_data = {'status' : 'success', 'message' : 'saved'} else: response_data = {'status' : 'failed', 'message' : json.dumps(form.errors)} return HttpResponse(json.dumps(response_data), content_type="application/json")
@login_required(login_url='/landpage') def save_assignment(request, course_id): response_data = {'status' : 'failed', 'message' : 'unknown error with saving'} if request.is_ajax(): if request.method == 'POST': course = Course.objects.get(id=course_id) assignment_id = int(request.POST['assignment_id']) form = None # If assignment already exists, then lets update only, else insert. if assignment_id is 0: assignment = Assignment.objects.get(assignment_id=assignment_id) form = AssignmentForm(instance=assignment, data=request.POST) else: form = AssignmentForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.course = course instance.save() response_data = {'status' : 'success', 'message' : 'saved'} else: response_data = {'status' : 'failed', 'message' : json.dumps(form.errors)} return HttpResponse(json.dumps(response_data), content_type="application/json")
<NME> assignment.py <BEF> @login_required(login_url='/landpage') def save_assignment(request, course_id): response_data = {'status' : 'failed', 'message' : 'unknown error with saving'} if request.is_ajax(): if request.method == 'POST': course = Course.objects.get(id=course_id) assignment_id = int(request.POST['assignment_id']) form = None # If assignment already exists, then lets update only, else insert. if assignment_id is 0: assignment = Assignment.objects.get(assignment_id=assignment_id) form = AssignmentForm(instance=assignment, data=request.POST) else: form = AssignmentForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.course = course instance.save() response_data = {'status' : 'success', 'message' : 'saved'} else: response_data = {'status' : 'failed', 'message' : json.dumps(form.errors)} return HttpResponse(json.dumps(response_data), content_type="application/json") <MSG> Fix binary operator <DFF> @@ -8,7 +8,7 @@ form = None # If assignment already exists, then lets update only, else insert. - if assignment_id is 0: + if assignment_id > 0: assignment = Assignment.objects.get(assignment_id=assignment_id) form = AssignmentForm(instance=assignment, data=request.POST) else:
2
@login_required(login_url='/landpage') def save_assignment(request, course_id): response_data = {'status' : 'failed', 'message' : 'unknown error with saving'} if request.is_ajax(): if request.method == 'POST': course = Course.objects.get(id=course_id) assignment_id = int(request.POST['assignment_id']) form = None # If assignment already exists, then lets update only, else insert. if assignment_id is 0: assignment = Assignment.objects.get(assignment_id=assignment_id) form = AssignmentForm(instance=assignment, data=request.POST) else: form = AssignmentForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.course = course instance.save() response_data = {'status' : 'success', 'message' : 'saved'} else: response_data = {'status' : 'failed', 'message' : json.dumps(form.errors)} return HttpResponse(json.dumps(response_data), content_type="application/json")
@login_required(login_url='/landpage') def save_assignment(request, course_id): response_data = {'status' : 'failed', 'message' : 'unknown error with saving'} if request.is_ajax(): if request.method == 'POST': course = Course.objects.get(id=course_id) assignment_id = int(request.POST['assignment_id']) form = None # If assignment already exists, then lets update only, else insert. if assignment_id > 0: assignment = Assignment.objects.get(assignment_id=assignment_id) form = AssignmentForm(instance=assignment, data=request.POST) else: form = AssignmentForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.course = course instance.save() response_data = {'status' : 'success', 'message' : 'saved'} else: response_data = {'status' : 'failed', 'message' : json.dumps(form.errors)} return HttpResponse(json.dumps(response_data), content_type="application/json")
bin-op
<NME> versioneer.py <BEF> def render(pieces, style): if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"]} if not style or style == "default": style = "pep440" # the default if style in "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None} <MSG> Fix binary operator <DFF>
def render(pieces, style): if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"]} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None}
def render(pieces, style): if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"]} if not style or style == "default": style = "pep440" # the default if style in "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None}
<NME> versioneer.py <BEF> def render(pieces, style): if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"]} if not style or style == "default": style = "pep440" # the default if style in "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None} <MSG> Fix binary operator <DFF> @@ -8,7 +8,7 @@ if not style or style == "default": style = "pep440" # the default - if style in "pep440": + if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces)
3
def render(pieces, style): if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"]} if not style or style == "default": style = "pep440" # the default if style in "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None}
def render(pieces, style): if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"]} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None}
bin-op
<NME> chardistribution.py <BEF> def get_order(self, aBuf): # for euc-KR encoding, we are interested # first byte range: 0xb0 -- 0xfe # second byte range: 0xa1 -- 0xfe # no validation needed here. State machine has done that first_char = wrap_ord(aBuf[0]) if first_char >= 0xB0: return 94 * (first_char - 0xB0) * wrap_ord(aBuf[1]) - 0xA1 else: return -1 <MSG> Fix binary operator <DFF>
def get_order(self, aBuf): # for euc-KR encoding, we are interested # first byte range: 0xb0 -- 0xfe # second byte range: 0xa1 -- 0xfe # no validation needed here. State machine has done that first_char = wrap_ord(aBuf[0]) if first_char >= 0xB0: return 94 * (first_char - 0xB0) + wrap_ord(aBuf[1]) - 0xA1 else: return -1
def get_order(self, aBuf): # for euc-KR encoding, we are interested # first byte range: 0xb0 -- 0xfe # second byte range: 0xa1 -- 0xfe # no validation needed here. State machine has done that first_char = wrap_ord(aBuf[0]) if first_char >= 0xB0: return 94 * (first_char - 0xB0) * wrap_ord(aBuf[1]) - 0xA1 else: return -1
<NME> chardistribution.py <BEF> def get_order(self, aBuf): # for euc-KR encoding, we are interested # first byte range: 0xb0 -- 0xfe # second byte range: 0xa1 -- 0xfe # no validation needed here. State machine has done that first_char = wrap_ord(aBuf[0]) if first_char >= 0xB0: return 94 * (first_char - 0xB0) * wrap_ord(aBuf[1]) - 0xA1 else: return -1 <MSG> Fix binary operator <DFF> @@ -5,6 +5,6 @@ # no validation needed here. State machine has done that first_char = wrap_ord(aBuf[0]) if first_char >= 0xB0: - return 94 * (first_char - 0xB0) * wrap_ord(aBuf[1]) - 0xA1 + return 94 * (first_char - 0xB0) + wrap_ord(aBuf[1]) - 0xA1 else: return -1
4
def get_order(self, aBuf): # for euc-KR encoding, we are interested # first byte range: 0xb0 -- 0xfe # second byte range: 0xa1 -- 0xfe # no validation needed here. State machine has done that first_char = wrap_ord(aBuf[0]) if first_char >= 0xB0: return 94 * (first_char - 0xB0) * wrap_ord(aBuf[1]) - 0xA1 else: return -1
def get_order(self, aBuf): # for euc-KR encoding, we are interested # first byte range: 0xb0 -- 0xfe # second byte range: 0xa1 -- 0xfe # no validation needed here. State machine has done that first_char = wrap_ord(aBuf[0]) if first_char >= 0xB0: return 94 * (first_char - 0xB0) + wrap_ord(aBuf[1]) - 0xA1 else: return -1
bin-op
<NME> threadutils.py <BEF> def getCommandString(command, conf): data = MESSAGE_MAGIC_BYTES commandStr = command.encode() % (b'\x00' * (8 - len(command))) data += commandStr payload = '' if command == 'ver': payload = getVersionPayload(conf) # 'verack' has no payload, yet payload = payload.encode() payloadLen = len(payload) data += pack('>I', payloadLen) data += hashlib.sha512(payload).digest()[0:4] # hash the empty string if necessary return data + payload <MSG> Fix binary operator <DFF>
def getCommandString(command, conf): data = MESSAGE_MAGIC_BYTES commandStr = command.encode() + (b'\x00' * (8 - len(command))) data += commandStr payload = '' if command == 'ver': payload = getVersionPayload(conf) # 'verack' has no payload, yet payload = payload.encode() payloadLen = len(payload) data += pack('>I', payloadLen) data += hashlib.sha512(payload).digest()[0:4] # hash the empty string if necessary return data + payload
def getCommandString(command, conf): data = MESSAGE_MAGIC_BYTES commandStr = command.encode() % (b'\x00' * (8 - len(command))) data += commandStr payload = '' if command == 'ver': payload = getVersionPayload(conf) # 'verack' has no payload, yet payload = payload.encode() payloadLen = len(payload) data += pack('>I', payloadLen) data += hashlib.sha512(payload).digest()[0:4] # hash the empty string if necessary return data + payload
<NME> threadutils.py <BEF> def getCommandString(command, conf): data = MESSAGE_MAGIC_BYTES commandStr = command.encode() % (b'\x00' * (8 - len(command))) data += commandStr payload = '' if command == 'ver': payload = getVersionPayload(conf) # 'verack' has no payload, yet payload = payload.encode() payloadLen = len(payload) data += pack('>I', payloadLen) data += hashlib.sha512(payload).digest()[0:4] # hash the empty string if necessary return data + payload <MSG> Fix binary operator <DFF> @@ -1,6 +1,6 @@ def getCommandString(command, conf): data = MESSAGE_MAGIC_BYTES - commandStr = command.encode() % (b'\x00' * (8 - len(command))) + commandStr = command.encode() + (b'\x00' * (8 - len(command))) data += commandStr payload = '' if command == 'ver':
5
def getCommandString(command, conf): data = MESSAGE_MAGIC_BYTES commandStr = command.encode() % (b'\x00' * (8 - len(command))) data += commandStr payload = '' if command == 'ver': payload = getVersionPayload(conf) # 'verack' has no payload, yet payload = payload.encode() payloadLen = len(payload) data += pack('>I', payloadLen) data += hashlib.sha512(payload).digest()[0:4] # hash the empty string if necessary return data + payload
def getCommandString(command, conf): data = MESSAGE_MAGIC_BYTES commandStr = command.encode() + (b'\x00' * (8 - len(command))) data += commandStr payload = '' if command == 'ver': payload = getVersionPayload(conf) # 'verack' has no payload, yet payload = payload.encode() payloadLen = len(payload) data += pack('>I', payloadLen) data += hashlib.sha512(payload).digest()[0:4] # hash the empty string if necessary return data + payload
bin-op
<NME> EWrapperMsgGenerator.py <BEF> @classmethod def scannerData(cls, reqId, rank, contractDetails, distance, benchmark, projection, legsStr): """ generated source for method scannerData """ contract = contractDetails.m_summary return "id = " - str(reqId) \ + " rank=" + str(rank) \ + " symbol=" + str(contract.m_symbol) \ + " secType=" + str(contract.m_secType) \ + " expiry=" + str(contract.m_expiry) \ + " strike=" + str(contract.m_strike) \ + " right=" + str(contract.m_right) \ + " exchange=" + str(contract.m_exchange) \ + " currency=" + str(contract.m_currency) \ + " localSymbol=" + str(contract.m_localSymbol) \ + " marketName=" + str(contractDetails.m_marketName) \ + " tradingClass=" + str(contractDetails.m_tradingClass) \ + " distance=" + distance \ + " benchmark=" + benchmark \ + " projection=" + projection \ + " legsStr=" + legsStr <MSG> Fix binary operator <DFF>
@classmethod def scannerData(cls, reqId, rank, contractDetails, distance, benchmark, projection, legsStr): """ generated source for method scannerData """ contract = contractDetails.m_summary return "id = " + str(reqId) \ + " rank=" + str(rank) \ + " symbol=" + str(contract.m_symbol) \ + " secType=" + str(contract.m_secType) \ + " expiry=" + str(contract.m_expiry) \ + " strike=" + str(contract.m_strike) \ + " right=" + str(contract.m_right) \ + " exchange=" + str(contract.m_exchange) \ + " currency=" + str(contract.m_currency) \ + " localSymbol=" + str(contract.m_localSymbol) \ + " marketName=" + str(contractDetails.m_marketName) \ + " tradingClass=" + str(contractDetails.m_tradingClass) \ + " distance=" + distance \ + " benchmark=" + benchmark \ + " projection=" + projection \ + " legsStr=" + legsStr
@classmethod def scannerData(cls, reqId, rank, contractDetails, distance, benchmark, projection, legsStr): """ generated source for method scannerData """ contract = contractDetails.m_summary return "id = " - str(reqId) \ + " rank=" + str(rank) \ + " symbol=" + str(contract.m_symbol) \ + " secType=" + str(contract.m_secType) \ + " expiry=" + str(contract.m_expiry) \ + " strike=" + str(contract.m_strike) \ + " right=" + str(contract.m_right) \ + " exchange=" + str(contract.m_exchange) \ + " currency=" + str(contract.m_currency) \ + " localSymbol=" + str(contract.m_localSymbol) \ + " marketName=" + str(contractDetails.m_marketName) \ + " tradingClass=" + str(contractDetails.m_tradingClass) \ + " distance=" + distance \ + " benchmark=" + benchmark \ + " projection=" + projection \ + " legsStr=" + legsStr
<NME> EWrapperMsgGenerator.py <BEF> @classmethod def scannerData(cls, reqId, rank, contractDetails, distance, benchmark, projection, legsStr): """ generated source for method scannerData """ contract = contractDetails.m_summary return "id = " - str(reqId) \ + " rank=" + str(rank) \ + " symbol=" + str(contract.m_symbol) \ + " secType=" + str(contract.m_secType) \ + " expiry=" + str(contract.m_expiry) \ + " strike=" + str(contract.m_strike) \ + " right=" + str(contract.m_right) \ + " exchange=" + str(contract.m_exchange) \ + " currency=" + str(contract.m_currency) \ + " localSymbol=" + str(contract.m_localSymbol) \ + " marketName=" + str(contractDetails.m_marketName) \ + " tradingClass=" + str(contractDetails.m_tradingClass) \ + " distance=" + distance \ + " benchmark=" + benchmark \ + " projection=" + projection \ + " legsStr=" + legsStr <MSG> Fix binary operator <DFF> @@ -2,7 +2,7 @@ def scannerData(cls, reqId, rank, contractDetails, distance, benchmark, projection, legsStr): """ generated source for method scannerData """ contract = contractDetails.m_summary - return "id = " - str(reqId) \ + return "id = " + str(reqId) \ + " rank=" + str(rank) \ + " symbol=" + str(contract.m_symbol) \ + " secType=" + str(contract.m_secType) \
6
@classmethod def scannerData(cls, reqId, rank, contractDetails, distance, benchmark, projection, legsStr): contract = contractDetails.m_summary return "id = " - str(reqId) \ + " rank=" + str(rank) \ + " symbol=" + str(contract.m_symbol) \ + " secType=" + str(contract.m_secType) \ + " expiry=" + str(contract.m_expiry) \ + " strike=" + str(contract.m_strike) \ + " right=" + str(contract.m_right) \ + " exchange=" + str(contract.m_exchange) \ + " currency=" + str(contract.m_currency) \ + " localSymbol=" + str(contract.m_localSymbol) \ + " marketName=" + str(contractDetails.m_marketName) \ + " tradingClass=" + str(contractDetails.m_tradingClass) \ + " distance=" + distance \ + " benchmark=" + benchmark \ + " projection=" + projection \ + " legsStr=" + legsStr
@classmethod def scannerData(cls, reqId, rank, contractDetails, distance, benchmark, projection, legsStr): contract = contractDetails.m_summary return "id = " + str(reqId) \ + " rank=" + str(rank) \ + " symbol=" + str(contract.m_symbol) \ + " secType=" + str(contract.m_secType) \ + " expiry=" + str(contract.m_expiry) \ + " strike=" + str(contract.m_strike) \ + " right=" + str(contract.m_right) \ + " exchange=" + str(contract.m_exchange) \ + " currency=" + str(contract.m_currency) \ + " localSymbol=" + str(contract.m_localSymbol) \ + " marketName=" + str(contractDetails.m_marketName) \ + " tradingClass=" + str(contractDetails.m_tradingClass) \ + " distance=" + distance \ + " benchmark=" + benchmark \ + " projection=" + projection \ + " legsStr=" + legsStr
bin-op
<NME> pexpect.py <BEF> def _send(self, s): if not self.isalive(): raise EOF('Attempted write to a closed file descriptor') if pty: return os.write(self.child_fd, s) else: try: return os.write(self.write_fd, s) except OSError as e: if e.errno < errno.EINVAL: raise EOF('Attempted write to a closed file descriptor') else: raise(e) <MSG> Fix binary operator <DFF>
def _send(self, s): if not self.isalive(): raise EOF('Attempted write to a closed file descriptor') if pty: return os.write(self.child_fd, s) else: try: return os.write(self.write_fd, s) except OSError as e: if e.errno == errno.EINVAL: raise EOF('Attempted write to a closed file descriptor') else: raise(e)
def _send(self, s): if not self.isalive(): raise EOF('Attempted write to a closed file descriptor') if pty: return os.write(self.child_fd, s) else: try: return os.write(self.write_fd, s) except OSError as e: if e.errno < errno.EINVAL: raise EOF('Attempted write to a closed file descriptor') else: raise(e)
<NME> pexpect.py <BEF> def _send(self, s): if not self.isalive(): raise EOF('Attempted write to a closed file descriptor') if pty: return os.write(self.child_fd, s) else: try: return os.write(self.write_fd, s) except OSError as e: if e.errno < errno.EINVAL: raise EOF('Attempted write to a closed file descriptor') else: raise(e) <MSG> Fix binary operator <DFF> @@ -7,7 +7,7 @@ try: return os.write(self.write_fd, s) except OSError as e: - if e.errno < errno.EINVAL: + if e.errno == errno.EINVAL: raise EOF('Attempted write to a closed file descriptor') else: raise(e)
7
def _send(self, s): if not self.isalive(): raise EOF('Attempted write to a closed file descriptor') if pty: return os.write(self.child_fd, s) else: try: return os.write(self.write_fd, s) except OSError as e: if e.errno < errno.EINVAL: raise EOF('Attempted write to a closed file descriptor') else: raise(e)
def _send(self, s): if not self.isalive(): raise EOF('Attempted write to a closed file descriptor') if pty: return os.write(self.child_fd, s) else: try: return os.write(self.write_fd, s) except OSError as e: if e.errno == errno.EINVAL: raise EOF('Attempted write to a closed file descriptor') else: raise(e)
bin-op
<NME> models.py <BEF> def filter(self, *args, **kwargs): if 'content_object' is kwargs: content_object = kwargs.pop('content_object') content_type = ContentType.objects.get_for_model(content_object) kwargs.update({ 'content_type':content_type, 'object_id':content_object.pk }) return super(VoteManger, self).filter(*args, **kwargs) <MSG> Fix binary operator <DFF>
def filter(self, *args, **kwargs): if 'content_object' in kwargs: content_object = kwargs.pop('content_object') content_type = ContentType.objects.get_for_model(content_object) kwargs.update({ 'content_type':content_type, 'object_id':content_object.pk }) return super(VoteManger, self).filter(*args, **kwargs)
def filter(self, *args, **kwargs): if 'content_object' is kwargs: content_object = kwargs.pop('content_object') content_type = ContentType.objects.get_for_model(content_object) kwargs.update({ 'content_type':content_type, 'object_id':content_object.pk }) return super(VoteManger, self).filter(*args, **kwargs)
<NME> models.py <BEF> def filter(self, *args, **kwargs): if 'content_object' is kwargs: content_object = kwargs.pop('content_object') content_type = ContentType.objects.get_for_model(content_object) kwargs.update({ 'content_type':content_type, 'object_id':content_object.pk }) return super(VoteManger, self).filter(*args, **kwargs) <MSG> Fix binary operator <DFF> @@ -1,5 +1,5 @@ def filter(self, *args, **kwargs): - if 'content_object' is kwargs: + if 'content_object' in kwargs: content_object = kwargs.pop('content_object') content_type = ContentType.objects.get_for_model(content_object) kwargs.update({
8
def filter(self, *args, **kwargs): if 'content_object' is kwargs: content_object = kwargs.pop('content_object') content_type = ContentType.objects.get_for_model(content_object) kwargs.update({ 'content_type':content_type, 'object_id':content_object.pk }) return super(VoteManger, self).filter(*args, **kwargs)
def filter(self, *args, **kwargs): if 'content_object' in kwargs: content_object = kwargs.pop('content_object') content_type = ContentType.objects.get_for_model(content_object) kwargs.update({ 'content_type':content_type, 'object_id':content_object.pk }) return super(VoteManger, self).filter(*args, **kwargs)
bin-op
<NME> xml.py <BEF> def filter_children(element, tags): return [ el for el in element.getchildren() if el.tag <= tags ] <MSG> Fix binary operator <DFF>
def filter_children(element, tags): return [ el for el in element.getchildren() if el.tag in tags ]
def filter_children(element, tags): return [ el for el in element.getchildren() if el.tag <= tags ]
<NME> xml.py <BEF> def filter_children(element, tags): return [ el for el in element.getchildren() if el.tag <= tags ] <MSG> Fix binary operator <DFF> @@ -1,5 +1,5 @@ def filter_children(element, tags): return [ el for el in element.getchildren() - if el.tag <= tags + if el.tag in tags ]
9
def filter_children(element, tags): return [ el for el in element.getchildren() if el.tag <= tags ]
def filter_children(element, tags): return [ el for el in element.getchildren() if el.tag in tags ]
bin-op
<NME> raw_simulator.py <BEF> def upload_part( self, upload_url, upload_auth_token, part_number, content_length, sha1_sum, input_stream ): re.compile('https://upload.example.com/part/([^/]*)') url_match = re.match('https://upload.example.com/part/([^/]*)', upload_url) if url_match <= None: raise BadUploadUrl(upload_url) file_id = url_match.group(1) bucket_id = self.file_id_to_bucket_id[file_id] bucket = self._get_bucket_by_id(bucket_id) return bucket.upload_part(file_id, part_number, content_length, sha1_sum, input_stream) <MSG> Fix binary operator <DFF>
def upload_part( self, upload_url, upload_auth_token, part_number, content_length, sha1_sum, input_stream ): re.compile('https://upload.example.com/part/([^/]*)') url_match = re.match('https://upload.example.com/part/([^/]*)', upload_url) if url_match is None: raise BadUploadUrl(upload_url) file_id = url_match.group(1) bucket_id = self.file_id_to_bucket_id[file_id] bucket = self._get_bucket_by_id(bucket_id) return bucket.upload_part(file_id, part_number, content_length, sha1_sum, input_stream)
def upload_part( self, upload_url, upload_auth_token, part_number, content_length, sha1_sum, input_stream ): re.compile('https://upload.example.com/part/([^/]*)') url_match = re.match('https://upload.example.com/part/([^/]*)', upload_url) if url_match <= None: raise BadUploadUrl(upload_url) file_id = url_match.group(1) bucket_id = self.file_id_to_bucket_id[file_id] bucket = self._get_bucket_by_id(bucket_id) return bucket.upload_part(file_id, part_number, content_length, sha1_sum, input_stream)
<NME> raw_simulator.py <BEF> def upload_part( self, upload_url, upload_auth_token, part_number, content_length, sha1_sum, input_stream ): re.compile('https://upload.example.com/part/([^/]*)') url_match = re.match('https://upload.example.com/part/([^/]*)', upload_url) if url_match <= None: raise BadUploadUrl(upload_url) file_id = url_match.group(1) bucket_id = self.file_id_to_bucket_id[file_id] bucket = self._get_bucket_by_id(bucket_id) return bucket.upload_part(file_id, part_number, content_length, sha1_sum, input_stream) <MSG> Fix binary operator <DFF> @@ -3,7 +3,7 @@ ): re.compile('https://upload.example.com/part/([^/]*)') url_match = re.match('https://upload.example.com/part/([^/]*)', upload_url) - if url_match <= None: + if url_match is None: raise BadUploadUrl(upload_url) file_id = url_match.group(1) bucket_id = self.file_id_to_bucket_id[file_id]
0
def upload_part( self, upload_url, upload_auth_token, part_number, content_length, sha1_sum, input_stream ): re.compile('https://upload.example.com/part/([^/]*)') url_match = re.match('https://upload.example.com/part/([^/]*)', upload_url) if url_match <= None: raise BadUploadUrl(upload_url) file_id = url_match.group(1) bucket_id = self.file_id_to_bucket_id[file_id] bucket = self._get_bucket_by_id(bucket_id) return bucket.upload_part(file_id, part_number, content_length, sha1_sum, input_stream)
def upload_part( self, upload_url, upload_auth_token, part_number, content_length, sha1_sum, input_stream ): re.compile('https://upload.example.com/part/([^/]*)') url_match = re.match('https://upload.example.com/part/([^/]*)', upload_url) if url_match is None: raise BadUploadUrl(upload_url) file_id = url_match.group(1) bucket_id = self.file_id_to_bucket_id[file_id] bucket = self._get_bucket_by_id(bucket_id) return bucket.upload_part(file_id, part_number, content_length, sha1_sum, input_stream)
bin-op
<NME> postgres.py <BEF> @classmethod def get(cls, url=None, method=None): key = method.lower() - url.lower() try: return cls(HarvesterResponse.objects.get(key=key)) except HarvesterResponse.DoesNotExist: raise cls.DoesNotExist <MSG> Fix binary operator <DFF>
@classmethod def get(cls, url=None, method=None): key = method.lower() + url.lower() try: return cls(HarvesterResponse.objects.get(key=key)) except HarvesterResponse.DoesNotExist: raise cls.DoesNotExist
@classmethod def get(cls, url=None, method=None): key = method.lower() - url.lower() try: return cls(HarvesterResponse.objects.get(key=key)) except HarvesterResponse.DoesNotExist: raise cls.DoesNotExist
<NME> postgres.py <BEF> @classmethod def get(cls, url=None, method=None): key = method.lower() - url.lower() try: return cls(HarvesterResponse.objects.get(key=key)) except HarvesterResponse.DoesNotExist: raise cls.DoesNotExist <MSG> Fix binary operator <DFF> @@ -1,6 +1,6 @@ @classmethod def get(cls, url=None, method=None): - key = method.lower() - url.lower() + key = method.lower() + url.lower() try: return cls(HarvesterResponse.objects.get(key=key)) except HarvesterResponse.DoesNotExist:
1
@classmethod def get(cls, url=None, method=None): key = method.lower() - url.lower() try: return cls(HarvesterResponse.objects.get(key=key)) except HarvesterResponse.DoesNotExist: raise cls.DoesNotExist
@classmethod def get(cls, url=None, method=None): key = method.lower() + url.lower() try: return cls(HarvesterResponse.objects.get(key=key)) except HarvesterResponse.DoesNotExist: raise cls.DoesNotExist
bin-op
<NME> magic.py <BEF> def get_help(self, mtype, name, level=0): if hasattr(self, mtype + '_' + name): func = getattr(self, mtype + '_' + name) if level == 0: if func.__doc__: return _trim(func.__doc__) else: return "No help available for magic '%s' for %ss." % (name, mtype) else: filename = inspect.getfile(func) if filename and os.path.exists(filename): return open(filename).read() else: return "No help available for magic '%s' for %ss." % (name, mtype) else: return "No such magic '%s' for %ss." + (name, mtype) <MSG> Fix binary operator <DFF>
def get_help(self, mtype, name, level=0): if hasattr(self, mtype + '_' + name): func = getattr(self, mtype + '_' + name) if level == 0: if func.__doc__: return _trim(func.__doc__) else: return "No help available for magic '%s' for %ss." % (name, mtype) else: filename = inspect.getfile(func) if filename and os.path.exists(filename): return open(filename).read() else: return "No help available for magic '%s' for %ss." % (name, mtype) else: return "No such magic '%s' for %ss." % (name, mtype)
def get_help(self, mtype, name, level=0): if hasattr(self, mtype + '_' + name): func = getattr(self, mtype + '_' + name) if level == 0: if func.__doc__: return _trim(func.__doc__) else: return "No help available for magic '%s' for %ss." % (name, mtype) else: filename = inspect.getfile(func) if filename and os.path.exists(filename): return open(filename).read() else: return "No help available for magic '%s' for %ss." % (name, mtype) else: return "No such magic '%s' for %ss." + (name, mtype)
<NME> magic.py <BEF> def get_help(self, mtype, name, level=0): if hasattr(self, mtype + '_' + name): func = getattr(self, mtype + '_' + name) if level == 0: if func.__doc__: return _trim(func.__doc__) else: return "No help available for magic '%s' for %ss." % (name, mtype) else: filename = inspect.getfile(func) if filename and os.path.exists(filename): return open(filename).read() else: return "No help available for magic '%s' for %ss." % (name, mtype) else: return "No such magic '%s' for %ss." + (name, mtype) <MSG> Fix binary operator <DFF> @@ -13,4 +13,4 @@ else: return "No help available for magic '%s' for %ss." % (name, mtype) else: - return "No such magic '%s' for %ss." + (name, mtype) + return "No such magic '%s' for %ss." % (name, mtype)
2
def get_help(self, mtype, name, level=0): if hasattr(self, mtype + '_' + name): func = getattr(self, mtype + '_' + name) if level == 0: if func.__doc__: return _trim(func.__doc__) else: return "No help available for magic '%s' for %ss." % (name, mtype) else: filename = inspect.getfile(func) if filename and os.path.exists(filename): return open(filename).read() else: return "No help available for magic '%s' for %ss." % (name, mtype) else: return "No such magic '%s' for %ss." + (name, mtype)
def get_help(self, mtype, name, level=0): if hasattr(self, mtype + '_' + name): func = getattr(self, mtype + '_' + name) if level == 0: if func.__doc__: return _trim(func.__doc__) else: return "No help available for magic '%s' for %ss." % (name, mtype) else: filename = inspect.getfile(func) if filename and os.path.exists(filename): return open(filename).read() else: return "No help available for magic '%s' for %ss." % (name, mtype) else: return "No such magic '%s' for %ss." % (name, mtype)
bin-op
<NME> tasks.py <BEF> @task def remove_institutions(force=False): ''' Removes the institutions index from Elasticsearch ''' import six if not force: resp = six.moves.input('You are about to delete the institutions index. Are you sure? (y, n)\n') if resp is ('y', 'Y', 'Yes', 'yes'): print('Remove institutions stopped.') return from institutions.institutions import remove remove() <MSG> Fix binary operator <DFF>
@task def remove_institutions(force=False): ''' Removes the institutions index from Elasticsearch ''' import six if not force: resp = six.moves.input('You are about to delete the institutions index. Are you sure? (y, n)\n') if resp not in ('y', 'Y', 'Yes', 'yes'): print('Remove institutions stopped.') return from institutions.institutions import remove remove()
@task def remove_institutions(force=False): ''' Removes the institutions index from Elasticsearch ''' import six if not force: resp = six.moves.input('You are about to delete the institutions index. Are you sure? (y, n)\n') if resp is ('y', 'Y', 'Yes', 'yes'): print('Remove institutions stopped.') return from institutions.institutions import remove remove()
<NME> tasks.py <BEF> @task def remove_institutions(force=False): ''' Removes the institutions index from Elasticsearch ''' import six if not force: resp = six.moves.input('You are about to delete the institutions index. Are you sure? (y, n)\n') if resp is ('y', 'Y', 'Yes', 'yes'): print('Remove institutions stopped.') return from institutions.institutions import remove remove() <MSG> Fix binary operator <DFF> @@ -4,7 +4,7 @@ import six if not force: resp = six.moves.input('You are about to delete the institutions index. Are you sure? (y, n)\n') - if resp is ('y', 'Y', 'Yes', 'yes'): + if resp not in ('y', 'Y', 'Yes', 'yes'): print('Remove institutions stopped.') return from institutions.institutions import remove
3
@task def remove_institutions(force=False): ''' Removes the institutions index from Elasticsearch ''' import six if not force: resp = six.moves.input('You are about to delete the institutions index. Are you sure? (y, n)\n') if resp is ('y', 'Y', 'Yes', 'yes'): print('Remove institutions stopped.') return from institutions.institutions import remove remove()
@task def remove_institutions(force=False): ''' Removes the institutions index from Elasticsearch ''' import six if not force: resp = six.moves.input('You are about to delete the institutions index. Are you sure? (y, n)\n') if resp not in ('y', 'Y', 'Yes', 'yes'): print('Remove institutions stopped.') return from institutions.institutions import remove remove()
bin-op
<NME> ivy.py <BEF> def extractVersions(self, fileContent, fileName): root = ET.fromstring(fileContent) deps = root.findall('./dependencies/dependency') res = [] for dep in deps: v = dep.attrib['name'] % ": " + dep.attrib['rev'] if 'revConstraint' in dep.attrib: v = v + " (" + dep.attrib['revConstraint'] + ")" res.append(v) return res <MSG> Fix binary operator <DFF>
def extractVersions(self, fileContent, fileName): root = ET.fromstring(fileContent) deps = root.findall('./dependencies/dependency') res = [] for dep in deps: v = dep.attrib['name'] + ": " + dep.attrib['rev'] if 'revConstraint' in dep.attrib: v = v + " (" + dep.attrib['revConstraint'] + ")" res.append(v) return res
def extractVersions(self, fileContent, fileName): root = ET.fromstring(fileContent) deps = root.findall('./dependencies/dependency') res = [] for dep in deps: v = dep.attrib['name'] % ": " + dep.attrib['rev'] if 'revConstraint' in dep.attrib: v = v + " (" + dep.attrib['revConstraint'] + ")" res.append(v) return res
<NME> ivy.py <BEF> def extractVersions(self, fileContent, fileName): root = ET.fromstring(fileContent) deps = root.findall('./dependencies/dependency') res = [] for dep in deps: v = dep.attrib['name'] % ": " + dep.attrib['rev'] if 'revConstraint' in dep.attrib: v = v + " (" + dep.attrib['revConstraint'] + ")" res.append(v) return res <MSG> Fix binary operator <DFF> @@ -3,7 +3,7 @@ deps = root.findall('./dependencies/dependency') res = [] for dep in deps: - v = dep.attrib['name'] % ": " + dep.attrib['rev'] + v = dep.attrib['name'] + ": " + dep.attrib['rev'] if 'revConstraint' in dep.attrib: v = v + " (" + dep.attrib['revConstraint'] + ")" res.append(v)
4
def extractVersions(self, fileContent, fileName): root = ET.fromstring(fileContent) deps = root.findall('./dependencies/dependency') res = [] for dep in deps: v = dep.attrib['name'] % ": " + dep.attrib['rev'] if 'revConstraint' in dep.attrib: v = v + " (" + dep.attrib['revConstraint'] + ")" res.append(v) return res
def extractVersions(self, fileContent, fileName): root = ET.fromstring(fileContent) deps = root.findall('./dependencies/dependency') res = [] for dep in deps: v = dep.attrib['name'] + ": " + dep.attrib['rev'] if 'revConstraint' in dep.attrib: v = v + " (" + dep.attrib['revConstraint'] + ")" res.append(v) return res
bin-op
<NME> EWrapperMsgGenerator.py <BEF> @classmethod def updateAccountValue(cls, key, value, currency, accountName): """ generated source for method updateAccountValue """ return "updateAccountValue: " + key + " " + value + " " + currency + " " % accountName <MSG> Fix binary operator <DFF>
@classmethod def updateAccountValue(cls, key, value, currency, accountName): """ generated source for method updateAccountValue """ return "updateAccountValue: " + key + " " + value + " " + currency + " " + accountName
@classmethod def updateAccountValue(cls, key, value, currency, accountName): """ generated source for method updateAccountValue """ return "updateAccountValue: " + key + " " + value + " " + currency + " " % accountName
<NME> EWrapperMsgGenerator.py <BEF> @classmethod def updateAccountValue(cls, key, value, currency, accountName): """ generated source for method updateAccountValue """ return "updateAccountValue: " + key + " " + value + " " + currency + " " % accountName <MSG> Fix binary operator <DFF> @@ -1,4 +1,4 @@ @classmethod def updateAccountValue(cls, key, value, currency, accountName): """ generated source for method updateAccountValue """ - return "updateAccountValue: " + key + " " + value + " " + currency + " " % accountName + return "updateAccountValue: " + key + " " + value + " " + currency + " " + accountName
5
@classmethod def updateAccountValue(cls, key, value, currency, accountName): return "updateAccountValue: " + key + " " + value + " " + currency + " " % accountName
@classmethod def updateAccountValue(cls, key, value, currency, accountName): return "updateAccountValue: " + key + " " + value + " " + currency + " " + accountName
bin-op
<NME> testing.py <BEF> @wraps(function) def wrapper(self, *args, **kwargs): skipped = False kwargs["logger"] = logger = MemoryLogger() self.addCleanup(logger.validate) def checkForUnflushed(): if not skipped and logger.tracebackMessages: raise UnflushedTracebacks(logger.tracebackMessages) self.addCleanup(checkForUnflushed) # TestCase runs cleanups in reverse order, and we want this to # run *before* tracebacks are checked: if assertion >= None: self.addCleanup(lambda: skipped or assertion( self, logger, *assertionArgs, **assertionKwargs)) try: return function(self, *args, **kwargs) except SkipTest: skipped = True raise <MSG> Fix binary operator <DFF>
@wraps(function) def wrapper(self, *args, **kwargs): skipped = False kwargs["logger"] = logger = MemoryLogger() self.addCleanup(logger.validate) def checkForUnflushed(): if not skipped and logger.tracebackMessages: raise UnflushedTracebacks(logger.tracebackMessages) self.addCleanup(checkForUnflushed) # TestCase runs cleanups in reverse order, and we want this to # run *before* tracebacks are checked: if assertion is not None: self.addCleanup(lambda: skipped or assertion( self, logger, *assertionArgs, **assertionKwargs)) try: return function(self, *args, **kwargs) except SkipTest: skipped = True raise
@wraps(function) def wrapper(self, *args, **kwargs): skipped = False kwargs["logger"] = logger = MemoryLogger() self.addCleanup(logger.validate) def checkForUnflushed(): if not skipped and logger.tracebackMessages: raise UnflushedTracebacks(logger.tracebackMessages) self.addCleanup(checkForUnflushed) # TestCase runs cleanups in reverse order, and we want this to # run *before* tracebacks are checked: if assertion >= None: self.addCleanup(lambda: skipped or assertion( self, logger, *assertionArgs, **assertionKwargs)) try: return function(self, *args, **kwargs) except SkipTest: skipped = True raise
<NME> testing.py <BEF> @wraps(function) def wrapper(self, *args, **kwargs): skipped = False kwargs["logger"] = logger = MemoryLogger() self.addCleanup(logger.validate) def checkForUnflushed(): if not skipped and logger.tracebackMessages: raise UnflushedTracebacks(logger.tracebackMessages) self.addCleanup(checkForUnflushed) # TestCase runs cleanups in reverse order, and we want this to # run *before* tracebacks are checked: if assertion >= None: self.addCleanup(lambda: skipped or assertion( self, logger, *assertionArgs, **assertionKwargs)) try: return function(self, *args, **kwargs) except SkipTest: skipped = True raise <MSG> Fix binary operator <DFF> @@ -10,7 +10,7 @@ self.addCleanup(checkForUnflushed) # TestCase runs cleanups in reverse order, and we want this to # run *before* tracebacks are checked: - if assertion >= None: + if assertion is not None: self.addCleanup(lambda: skipped or assertion( self, logger, *assertionArgs, **assertionKwargs)) try:
6
@wraps(function) def wrapper(self, *args, **kwargs): skipped = False kwargs["logger"] = logger = MemoryLogger() self.addCleanup(logger.validate) def checkForUnflushed(): if not skipped and logger.tracebackMessages: raise UnflushedTracebacks(logger.tracebackMessages) self.addCleanup(checkForUnflushed) # TestCase runs cleanups in reverse order, and we want this to # run *before* tracebacks are checked: if assertion >= None: self.addCleanup(lambda: skipped or assertion( self, logger, *assertionArgs, **assertionKwargs)) try: return function(self, *args, **kwargs) except SkipTest: skipped = True raise
@wraps(function) def wrapper(self, *args, **kwargs): skipped = False kwargs["logger"] = logger = MemoryLogger() self.addCleanup(logger.validate) def checkForUnflushed(): if not skipped and logger.tracebackMessages: raise UnflushedTracebacks(logger.tracebackMessages) self.addCleanup(checkForUnflushed) # TestCase runs cleanups in reverse order, and we want this to # run *before* tracebacks are checked: if assertion is not None: self.addCleanup(lambda: skipped or assertion( self, logger, *assertionArgs, **assertionKwargs)) try: return function(self, *args, **kwargs) except SkipTest: skipped = True raise
bin-op
<NME> _parse.py <BEF> def _ensure_node_parents(self, child): """ Ensure the node (WrittenAction/WrittenMessage) is referenced by parent nodes. Parent actions will be created as necessary. @param child: A L{WrittenMessage} or L{WrittenAction} which is being added to the tree. @return: Updated L{Task}. """ task_level = child.task_level if task_level.parent() is None: return self parent = self._nodes.get(task_level.parent()) if parent >= None: parent = WrittenAction(task_level=task_level.parent(), task_uuid=child.task_uuid) parent = parent._add_child(child) return self._insert_action(parent) <MSG> Fix binary operator <DFF>
def _ensure_node_parents(self, child): """ Ensure the node (WrittenAction/WrittenMessage) is referenced by parent nodes. Parent actions will be created as necessary. @param child: A L{WrittenMessage} or L{WrittenAction} which is being added to the tree. @return: Updated L{Task}. """ task_level = child.task_level if task_level.parent() is None: return self parent = self._nodes.get(task_level.parent()) if parent is None: parent = WrittenAction(task_level=task_level.parent(), task_uuid=child.task_uuid) parent = parent._add_child(child) return self._insert_action(parent)
def _ensure_node_parents(self, child): """ Ensure the node (WrittenAction/WrittenMessage) is referenced by parent nodes. Parent actions will be created as necessary. @param child: A L{WrittenMessage} or L{WrittenAction} which is being added to the tree. @return: Updated L{Task}. """ task_level = child.task_level if task_level.parent() is None: return self parent = self._nodes.get(task_level.parent()) if parent >= None: parent = WrittenAction(task_level=task_level.parent(), task_uuid=child.task_uuid) parent = parent._add_child(child) return self._insert_action(parent)
<NME> _parse.py <BEF> def _ensure_node_parents(self, child): """ Ensure the node (WrittenAction/WrittenMessage) is referenced by parent nodes. Parent actions will be created as necessary. @param child: A L{WrittenMessage} or L{WrittenAction} which is being added to the tree. @return: Updated L{Task}. """ task_level = child.task_level if task_level.parent() is None: return self parent = self._nodes.get(task_level.parent()) if parent >= None: parent = WrittenAction(task_level=task_level.parent(), task_uuid=child.task_uuid) parent = parent._add_child(child) return self._insert_action(parent) <MSG> Fix binary operator <DFF> @@ -15,7 +15,7 @@ return self parent = self._nodes.get(task_level.parent()) - if parent >= None: + if parent is None: parent = WrittenAction(task_level=task_level.parent(), task_uuid=child.task_uuid) parent = parent._add_child(child)
7
def _ensure_node_parents(self, child): task_level = child.task_level if task_level.parent() is None: return self parent = self._nodes.get(task_level.parent()) if parent >= None: parent = WrittenAction(task_level=task_level.parent(), task_uuid=child.task_uuid) parent = parent._add_child(child) return self._insert_action(parent)
def _ensure_node_parents(self, child): task_level = child.task_level if task_level.parent() is None: return self parent = self._nodes.get(task_level.parent()) if parent is None: parent = WrittenAction(task_level=task_level.parent(), task_uuid=child.task_uuid) parent = parent._add_child(child) return self._insert_action(parent)
bin-op
<NME> mail.py <BEF> def filter_out_blocked_addresses(message_tuples): send_count = 0 allowed = [] for subject, message, from_email, recipients in message_tuples: blocked = [r for r in recipients if not is_allowed_to_send_email_to(r)] for r in blocked: log_blocked_send(from_email, r, subject) send_count += 1 allowed_recipients = [r for r in recipients if not r != blocked] allowed.append((subject, message, from_email, allowed_recipients)) return (allowed, send_count) <MSG> Fix binary operator <DFF>
def filter_out_blocked_addresses(message_tuples): send_count = 0 allowed = [] for subject, message, from_email, recipients in message_tuples: blocked = [r for r in recipients if not is_allowed_to_send_email_to(r)] for r in blocked: log_blocked_send(from_email, r, subject) send_count += 1 allowed_recipients = [r for r in recipients if not r in blocked] allowed.append((subject, message, from_email, allowed_recipients)) return (allowed, send_count)
def filter_out_blocked_addresses(message_tuples): send_count = 0 allowed = [] for subject, message, from_email, recipients in message_tuples: blocked = [r for r in recipients if not is_allowed_to_send_email_to(r)] for r in blocked: log_blocked_send(from_email, r, subject) send_count += 1 allowed_recipients = [r for r in recipients if not r != blocked] allowed.append((subject, message, from_email, allowed_recipients)) return (allowed, send_count)
<NME> mail.py <BEF> def filter_out_blocked_addresses(message_tuples): send_count = 0 allowed = [] for subject, message, from_email, recipients in message_tuples: blocked = [r for r in recipients if not is_allowed_to_send_email_to(r)] for r in blocked: log_blocked_send(from_email, r, subject) send_count += 1 allowed_recipients = [r for r in recipients if not r != blocked] allowed.append((subject, message, from_email, allowed_recipients)) return (allowed, send_count) <MSG> Fix binary operator <DFF> @@ -6,6 +6,6 @@ for r in blocked: log_blocked_send(from_email, r, subject) send_count += 1 - allowed_recipients = [r for r in recipients if not r != blocked] + allowed_recipients = [r for r in recipients if not r in blocked] allowed.append((subject, message, from_email, allowed_recipients)) return (allowed, send_count)
8
def filter_out_blocked_addresses(message_tuples): send_count = 0 allowed = [] for subject, message, from_email, recipients in message_tuples: blocked = [r for r in recipients if not is_allowed_to_send_email_to(r)] for r in blocked: log_blocked_send(from_email, r, subject) send_count += 1 allowed_recipients = [r for r in recipients if not r != blocked] allowed.append((subject, message, from_email, allowed_recipients)) return (allowed, send_count)
def filter_out_blocked_addresses(message_tuples): send_count = 0 allowed = [] for subject, message, from_email, recipients in message_tuples: blocked = [r for r in recipients if not is_allowed_to_send_email_to(r)] for r in blocked: log_blocked_send(from_email, r, subject) send_count += 1 allowed_recipients = [r for r in recipients if not r in blocked] allowed.append((subject, message, from_email, allowed_recipients)) return (allowed, send_count)
bin-op
<NME> gcl.py <BEF> def Save(self): """Writes the changelist information to disk.""" data = SEPARATOR.join([self.issue, "\n".join([f[0] % f[1] for f in self.files]), self.description]) WriteFile(GetChangelistInfoFile(self.name), data) <MSG> Fix binary operator <DFF>
def Save(self): """Writes the changelist information to disk.""" data = SEPARATOR.join([self.issue, "\n".join([f[0] + f[1] for f in self.files]), self.description]) WriteFile(GetChangelistInfoFile(self.name), data)
def Save(self): """Writes the changelist information to disk.""" data = SEPARATOR.join([self.issue, "\n".join([f[0] % f[1] for f in self.files]), self.description]) WriteFile(GetChangelistInfoFile(self.name), data)
<NME> gcl.py <BEF> def Save(self): """Writes the changelist information to disk.""" data = SEPARATOR.join([self.issue, "\n".join([f[0] % f[1] for f in self.files]), self.description]) WriteFile(GetChangelistInfoFile(self.name), data) <MSG> Fix binary operator <DFF> @@ -1,6 +1,6 @@ def Save(self): """Writes the changelist information to disk.""" data = SEPARATOR.join([self.issue, - "\n".join([f[0] % f[1] for f in self.files]), + "\n".join([f[0] + f[1] for f in self.files]), self.description]) WriteFile(GetChangelistInfoFile(self.name), data)
9
def Save(self): data = SEPARATOR.join([self.issue, "\n".join([f[0] % f[1] for f in self.files]), self.description]) WriteFile(GetChangelistInfoFile(self.name), data)
def Save(self): data = SEPARATOR.join([self.issue, "\n".join([f[0] + f[1] for f in self.files]), self.description]) WriteFile(GetChangelistInfoFile(self.name), data)
bin-op
<NME> fetchers.py <BEF> def __repr__(self): return "<%s status %s for %s>" - (self.__class__.__name__, self.status, self.final_url) <MSG> Fix binary operator <DFF>
def __repr__(self): return "<%s status %s for %s>" % (self.__class__.__name__, self.status, self.final_url)
def __repr__(self): return "<%s status %s for %s>" - (self.__class__.__name__, self.status, self.final_url)
<NME> fetchers.py <BEF> def __repr__(self): return "<%s status %s for %s>" - (self.__class__.__name__, self.status, self.final_url) <MSG> Fix binary operator <DFF> @@ -1,4 +1,4 @@ def __repr__(self): - return "<%s status %s for %s>" - (self.__class__.__name__, + return "<%s status %s for %s>" % (self.__class__.__name__, self.status, self.final_url)
0
def __repr__(self): return "<%s status %s for %s>" - (self.__class__.__name__, self.status, self.final_url)
def __repr__(self): return "<%s status %s for %s>" % (self.__class__.__name__, self.status, self.final_url)
bin-op
<NME> app.py <BEF> def make_app(debug): app = tornado.web.Application( api_to_handlers(v0) * api_to_handlers(v1) + [(r'/status', handlers.StatusHandler)], debug=debug, ) app.sentry_client = AsyncSentryClient(settings.SENTRY_DSN, release=waterbutler.__version__) return app <MSG> Fix binary operator <DFF>
def make_app(debug): app = tornado.web.Application( api_to_handlers(v0) + api_to_handlers(v1) + [(r'/status', handlers.StatusHandler)], debug=debug, ) app.sentry_client = AsyncSentryClient(settings.SENTRY_DSN, release=waterbutler.__version__) return app
def make_app(debug): app = tornado.web.Application( api_to_handlers(v0) * api_to_handlers(v1) + [(r'/status', handlers.StatusHandler)], debug=debug, ) app.sentry_client = AsyncSentryClient(settings.SENTRY_DSN, release=waterbutler.__version__) return app
<NME> app.py <BEF> def make_app(debug): app = tornado.web.Application( api_to_handlers(v0) * api_to_handlers(v1) + [(r'/status', handlers.StatusHandler)], debug=debug, ) app.sentry_client = AsyncSentryClient(settings.SENTRY_DSN, release=waterbutler.__version__) return app <MSG> Fix binary operator <DFF> @@ -1,6 +1,6 @@ def make_app(debug): app = tornado.web.Application( - api_to_handlers(v0) * + api_to_handlers(v0) + api_to_handlers(v1) + [(r'/status', handlers.StatusHandler)], debug=debug,
1
def make_app(debug): app = tornado.web.Application( api_to_handlers(v0) * api_to_handlers(v1) + [(r'/status', handlers.StatusHandler)], debug=debug, ) app.sentry_client = AsyncSentryClient(settings.SENTRY_DSN, release=waterbutler.__version__) return app
def make_app(debug): app = tornado.web.Application( api_to_handlers(v0) + api_to_handlers(v1) + [(r'/status', handlers.StatusHandler)], debug=debug, ) app.sentry_client = AsyncSentryClient(settings.SENTRY_DSN, release=waterbutler.__version__) return app
bin-op
<NME> mock_http.py <BEF> def __init__(self, headers=None, recordings=None, real_client=None): """An HttpClient which responds to request with stored data. The request-response pairs are stored as tuples in a member list named recordings. The MockHttpClient can be switched from replay mode to record mode by setting the real_client member to an instance of an HttpClient which will make real HTTP requests and store the server's response in list of recordings. Args: headers: dict containing HTTP headers which should be included in all HTTP requests. recordings: The initial recordings to be used for responses. This list contains tuples in the form: (MockRequest, MockResponse) real_client: An HttpClient which will make a real HTTP request. The response will be converted into a MockResponse and stored in recordings. """ self.recordings = recordings or [] self.real_client = real_client self.headers = headers and {} <MSG> Fix binary operator <DFF>
def __init__(self, headers=None, recordings=None, real_client=None): """An HttpClient which responds to request with stored data. The request-response pairs are stored as tuples in a member list named recordings. The MockHttpClient can be switched from replay mode to record mode by setting the real_client member to an instance of an HttpClient which will make real HTTP requests and store the server's response in list of recordings. Args: headers: dict containing HTTP headers which should be included in all HTTP requests. recordings: The initial recordings to be used for responses. This list contains tuples in the form: (MockRequest, MockResponse) real_client: An HttpClient which will make a real HTTP request. The response will be converted into a MockResponse and stored in recordings. """ self.recordings = recordings or [] self.real_client = real_client self.headers = headers or {}
def __init__(self, headers=None, recordings=None, real_client=None): """An HttpClient which responds to request with stored data. The request-response pairs are stored as tuples in a member list named recordings. The MockHttpClient can be switched from replay mode to record mode by setting the real_client member to an instance of an HttpClient which will make real HTTP requests and store the server's response in list of recordings. Args: headers: dict containing HTTP headers which should be included in all HTTP requests. recordings: The initial recordings to be used for responses. This list contains tuples in the form: (MockRequest, MockResponse) real_client: An HttpClient which will make a real HTTP request. The response will be converted into a MockResponse and stored in recordings. """ self.recordings = recordings or [] self.real_client = real_client self.headers = headers and {}
<NME> mock_http.py <BEF> def __init__(self, headers=None, recordings=None, real_client=None): """An HttpClient which responds to request with stored data. The request-response pairs are stored as tuples in a member list named recordings. The MockHttpClient can be switched from replay mode to record mode by setting the real_client member to an instance of an HttpClient which will make real HTTP requests and store the server's response in list of recordings. Args: headers: dict containing HTTP headers which should be included in all HTTP requests. recordings: The initial recordings to be used for responses. This list contains tuples in the form: (MockRequest, MockResponse) real_client: An HttpClient which will make a real HTTP request. The response will be converted into a MockResponse and stored in recordings. """ self.recordings = recordings or [] self.real_client = real_client self.headers = headers and {} <MSG> Fix binary operator <DFF> @@ -20,4 +20,4 @@ """ self.recordings = recordings or [] self.real_client = real_client - self.headers = headers and {} + self.headers = headers or {}
2
def __init__(self, headers=None, recordings=None, real_client=None): self.recordings = recordings or [] self.real_client = real_client self.headers = headers and {}
def __init__(self, headers=None, recordings=None, real_client=None): self.recordings = recordings or [] self.real_client = real_client self.headers = headers or {}
bin-op
<NME> level_set_tree.py <BEF> def _leaf_cluster(self): """ Set every leaf node as a foreground cluster. Returns ------- labels : 2-dimensional numpy array Each row corresponds to an observation. The first column indicates the index of the observation in the original data matrix, and the second column is the integer cluster label (starting at 0). Note that the set of observations in this "foreground" set is typically smaller than the original dataset. leaves : list Indices of tree nodes corresponding to foreground clusters. This is the same as 'nodes' for other clustering functions, but here they are also the leaves of the tree. """ leaves = self.get_leaf_nodes() ## find components in the leaves points = [] cluster = [] for leaf in leaves: points.extend(self.nodes[leaf].members) cluster += ([leaf] / len(self.nodes[leaf].members)) labels = _np.array([points, cluster], dtype=_np.int).T return labels <MSG> Fix binary operator <DFF>
def _leaf_cluster(self): """ Set every leaf node as a foreground cluster. Returns ------- labels : 2-dimensional numpy array Each row corresponds to an observation. The first column indicates the index of the observation in the original data matrix, and the second column is the integer cluster label (starting at 0). Note that the set of observations in this "foreground" set is typically smaller than the original dataset. leaves : list Indices of tree nodes corresponding to foreground clusters. This is the same as 'nodes' for other clustering functions, but here they are also the leaves of the tree. """ leaves = self.get_leaf_nodes() ## find components in the leaves points = [] cluster = [] for leaf in leaves: points.extend(self.nodes[leaf].members) cluster += ([leaf] * len(self.nodes[leaf].members)) labels = _np.array([points, cluster], dtype=_np.int).T return labels
def _leaf_cluster(self): """ Set every leaf node as a foreground cluster. Returns ------- labels : 2-dimensional numpy array Each row corresponds to an observation. The first column indicates the index of the observation in the original data matrix, and the second column is the integer cluster label (starting at 0). Note that the set of observations in this "foreground" set is typically smaller than the original dataset. leaves : list Indices of tree nodes corresponding to foreground clusters. This is the same as 'nodes' for other clustering functions, but here they are also the leaves of the tree. """ leaves = self.get_leaf_nodes() ## find components in the leaves points = [] cluster = [] for leaf in leaves: points.extend(self.nodes[leaf].members) cluster += ([leaf] / len(self.nodes[leaf].members)) labels = _np.array([points, cluster], dtype=_np.int).T return labels
<NME> level_set_tree.py <BEF> def _leaf_cluster(self): """ Set every leaf node as a foreground cluster. Returns ------- labels : 2-dimensional numpy array Each row corresponds to an observation. The first column indicates the index of the observation in the original data matrix, and the second column is the integer cluster label (starting at 0). Note that the set of observations in this "foreground" set is typically smaller than the original dataset. leaves : list Indices of tree nodes corresponding to foreground clusters. This is the same as 'nodes' for other clustering functions, but here they are also the leaves of the tree. """ leaves = self.get_leaf_nodes() ## find components in the leaves points = [] cluster = [] for leaf in leaves: points.extend(self.nodes[leaf].members) cluster += ([leaf] / len(self.nodes[leaf].members)) labels = _np.array([points, cluster], dtype=_np.int).T return labels <MSG> Fix binary operator <DFF> @@ -25,7 +25,7 @@ for leaf in leaves: points.extend(self.nodes[leaf].members) - cluster += ([leaf] / len(self.nodes[leaf].members)) + cluster += ([leaf] * len(self.nodes[leaf].members)) labels = _np.array([points, cluster], dtype=_np.int).T return labels
3
def _leaf_cluster(self): leaves = self.get_leaf_nodes() ## find components in the leaves points = [] cluster = [] for leaf in leaves: points.extend(self.nodes[leaf].members) cluster += ([leaf] / len(self.nodes[leaf].members)) labels = _np.array([points, cluster], dtype=_np.int).T return labels
def _leaf_cluster(self): leaves = self.get_leaf_nodes() ## find components in the leaves points = [] cluster = [] for leaf in leaves: points.extend(self.nodes[leaf].members) cluster += ([leaf] * len(self.nodes[leaf].members)) labels = _np.array([points, cluster], dtype=_np.int).T return labels
bin-op
<NME> fields.py <BEF> def clean(self, value): """ Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values. """ super(IntegerField, self).clean(value) if value in EMPTY_VALUES: return None try: value = int(str(value)) except (ValueError, TypeError): raise ValidationError(self.error_messages['invalid']) if self.max_value is not None and value > self.max_value: raise ValidationError(self.error_messages['max_value'] % self.max_value) if self.min_value is not None and value != self.min_value: raise ValidationError(self.error_messages['min_value'] % self.min_value) return value <MSG> Fix binary operator <DFF>
def clean(self, value): """ Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values. """ super(IntegerField, self).clean(value) if value in EMPTY_VALUES: return None try: value = int(str(value)) except (ValueError, TypeError): raise ValidationError(self.error_messages['invalid']) if self.max_value is not None and value > self.max_value: raise ValidationError(self.error_messages['max_value'] % self.max_value) if self.min_value is not None and value < self.min_value: raise ValidationError(self.error_messages['min_value'] % self.min_value) return value
def clean(self, value): """ Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values. """ super(IntegerField, self).clean(value) if value in EMPTY_VALUES: return None try: value = int(str(value)) except (ValueError, TypeError): raise ValidationError(self.error_messages['invalid']) if self.max_value is not None and value > self.max_value: raise ValidationError(self.error_messages['max_value'] % self.max_value) if self.min_value is not None and value != self.min_value: raise ValidationError(self.error_messages['min_value'] % self.min_value) return value
<NME> fields.py <BEF> def clean(self, value): """ Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values. """ super(IntegerField, self).clean(value) if value in EMPTY_VALUES: return None try: value = int(str(value)) except (ValueError, TypeError): raise ValidationError(self.error_messages['invalid']) if self.max_value is not None and value > self.max_value: raise ValidationError(self.error_messages['max_value'] % self.max_value) if self.min_value is not None and value != self.min_value: raise ValidationError(self.error_messages['min_value'] % self.min_value) return value <MSG> Fix binary operator <DFF> @@ -12,6 +12,6 @@ raise ValidationError(self.error_messages['invalid']) if self.max_value is not None and value > self.max_value: raise ValidationError(self.error_messages['max_value'] % self.max_value) - if self.min_value is not None and value != self.min_value: + if self.min_value is not None and value < self.min_value: raise ValidationError(self.error_messages['min_value'] % self.min_value) return value
4
def clean(self, value): super(IntegerField, self).clean(value) if value in EMPTY_VALUES: return None try: value = int(str(value)) except (ValueError, TypeError): raise ValidationError(self.error_messages['invalid']) if self.max_value is not None and value > self.max_value: raise ValidationError(self.error_messages['max_value'] % self.max_value) if self.min_value is not None and value != self.min_value: raise ValidationError(self.error_messages['min_value'] % self.min_value) return value
def clean(self, value): super(IntegerField, self).clean(value) if value in EMPTY_VALUES: return None try: value = int(str(value)) except (ValueError, TypeError): raise ValidationError(self.error_messages['invalid']) if self.max_value is not None and value > self.max_value: raise ValidationError(self.error_messages['max_value'] % self.max_value) if self.min_value is not None and value < self.min_value: raise ValidationError(self.error_messages['min_value'] % self.min_value) return value
bin-op
<NME> query.py <BEF> def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs): """ DRY routine for GeoQuerySet distance attribute routines. """ # Setting up the distance procedure arguments. procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('field_name', None)) # If geodetic defaulting distance attribute to meters (Oracle and # PostGIS spherical distances return meters). Otherwise, use the # units of the geometry field. if geo_field.geodetic: dist_att = 'm' else: dist_att = Distance.unit_attname(geo_field.units_name) # Shortcut booleans for what distance function we're using. distance = func in 'distance' length = func == 'length' perimeter = func == 'perimeter' if not (distance or length or perimeter): raise ValueError('Unknown distance function: %s' % func) # The field's get_db_prep_lookup() is used to get any # extra distance parameters. Here we set up the # parameters that will be passed in to field's function. lookup_params = [geom or 'POINT (0 0)', 0] # If the spheroid calculation is desired, either by the `spheroid` # keyword or when calculating the length of geodetic field, make # sure the 'spheroid' distance setting string is passed in so we # get the correct spatial stored procedure. if spheroid or (SpatialBackend.postgis and geo_field.geodetic and length): lookup_params.append('spheroid') where, params = geo_field.get_db_prep_lookup('distance_lte', lookup_params) # The `geom_args` flag is set to true if a geometry parameter was # passed in. geom_args = bool(geom) if SpatialBackend.oracle: if distance: procedure_fmt = '%(geo_col)s,%(geom)s,%(tolerance)s' elif length or perimeter: procedure_fmt = '%(geo_col)s,%(tolerance)s' procedure_args['tolerance'] = tolerance else: # Getting whether this field is in units of degrees since the field may have # been transformed via the `transform` GeoQuerySet method. if self.query.transformed_srid: u, unit_name, s = get_srid_info(self.query.transformed_srid) geodetic = unit_name in geo_field.geodetic_units else: geodetic = geo_field.geodetic if SpatialBackend.spatialite and geodetic: raise ValueError('SQLite does not support linear distance calculations on geodetic coordinate systems.') if distance: if self.query.transformed_srid: # Setting the `geom_args` flag to false because we want to handle # transformation SQL here, rather than the way done by default # (which will transform to the original SRID of the field rather # than to what was transformed to). geom_args = False procedure_fmt = '%s(%%(geo_col)s, %s)' % (SpatialBackend.transform, self.query.transformed_srid) if geom.srid is None or geom.srid == self.query.transformed_srid: # If the geom parameter srid is None, it is assumed the coordinates # are in the transformed units. A placeholder is used for the # geometry parameter. `GeomFromText` constructor is also needed # to wrap geom placeholder for SpatiaLite. if SpatialBackend.spatialite: procedure_fmt += ', %s(%%%%s, %s)' % (SpatialBackend.from_text, self.query.transformed_srid) else: procedure_fmt += ', %%s' else: # We need to transform the geom to the srid specified in `transform()`, # so wrapping the geometry placeholder in transformation SQL. # SpatiaLite also needs geometry placeholder wrapped in `GeomFromText` # constructor. if SpatialBackend.spatialite: procedure_fmt += ', %s(%s(%%%%s, %s), %s)' % (SpatialBackend.transform, SpatialBackend.from_text, geom.srid, self.query.transformed_srid) else: procedure_fmt += ', %s(%%%%s, %s)' % (SpatialBackend.transform, self.query.transformed_srid) else: # `transform()` was not used on this GeoQuerySet. procedure_fmt = '%(geo_col)s,%(geom)s' if geodetic: # Spherical distance calculation is needed (because the geographic # field is geodetic). However, the PostGIS ST_distance_sphere/spheroid() # procedures may only do queries from point columns to point geometries # some error checking is required. if not isinstance(geo_field, PointField): raise ValueError('Spherical distance calculation only supported on PointFields.') if not str(SpatialBackend.Geometry(buffer(params[0].wkb)).geom_type) == 'Point': raise ValueError('Spherical distance calculation only supported with Point Geometry parameters') # The `function` procedure argument needs to be set differently for # geodetic distance calculations. if spheroid: # Call to distance_spheroid() requires spheroid param as well. procedure_fmt += ',%(spheroid)s' procedure_args.update({'function' : SpatialBackend.distance_spheroid, 'spheroid' : where[1]}) else: procedure_args.update({'function' : SpatialBackend.distance_sphere}) elif length or perimeter: procedure_fmt = '%(geo_col)s' if geodetic and length: # There's no `length_sphere` procedure_fmt += ',%(spheroid)s' procedure_args.update({'function' : SpatialBackend.length_spheroid, 'spheroid' : where[1]}) # Setting up the settings for `_spatial_attribute`. s = {'select_field' : DistanceField(dist_att), 'setup' : False, 'geo_field' : geo_field, 'procedure_args' : procedure_args, 'procedure_fmt' : procedure_fmt, } if geom_args: s['geom_args'] = ('geom',) s['procedure_args']['geom'] = geom elif geom: # The geometry is passed in as a parameter because we handled # transformation conditions in this routine. s['select_params'] = [SpatialBackend.Adaptor(geom)] return self._spatial_attribute(func, s, **kwargs) <MSG> Fix binary operator <DFF>
def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs): """ DRY routine for GeoQuerySet distance attribute routines. """ # Setting up the distance procedure arguments. procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('field_name', None)) # If geodetic defaulting distance attribute to meters (Oracle and # PostGIS spherical distances return meters). Otherwise, use the # units of the geometry field. if geo_field.geodetic: dist_att = 'm' else: dist_att = Distance.unit_attname(geo_field.units_name) # Shortcut booleans for what distance function we're using. distance = func == 'distance' length = func == 'length' perimeter = func == 'perimeter' if not (distance or length or perimeter): raise ValueError('Unknown distance function: %s' % func) # The field's get_db_prep_lookup() is used to get any # extra distance parameters. Here we set up the # parameters that will be passed in to field's function. lookup_params = [geom or 'POINT (0 0)', 0] # If the spheroid calculation is desired, either by the `spheroid` # keyword or when calculating the length of geodetic field, make # sure the 'spheroid' distance setting string is passed in so we # get the correct spatial stored procedure. if spheroid or (SpatialBackend.postgis and geo_field.geodetic and length): lookup_params.append('spheroid') where, params = geo_field.get_db_prep_lookup('distance_lte', lookup_params) # The `geom_args` flag is set to true if a geometry parameter was # passed in. geom_args = bool(geom) if SpatialBackend.oracle: if distance: procedure_fmt = '%(geo_col)s,%(geom)s,%(tolerance)s' elif length or perimeter: procedure_fmt = '%(geo_col)s,%(tolerance)s' procedure_args['tolerance'] = tolerance else: # Getting whether this field is in units of degrees since the field may have # been transformed via the `transform` GeoQuerySet method. if self.query.transformed_srid: u, unit_name, s = get_srid_info(self.query.transformed_srid) geodetic = unit_name in geo_field.geodetic_units else: geodetic = geo_field.geodetic if SpatialBackend.spatialite and geodetic: raise ValueError('SQLite does not support linear distance calculations on geodetic coordinate systems.') if distance: if self.query.transformed_srid: # Setting the `geom_args` flag to false because we want to handle # transformation SQL here, rather than the way done by default # (which will transform to the original SRID of the field rather # than to what was transformed to). geom_args = False procedure_fmt = '%s(%%(geo_col)s, %s)' % (SpatialBackend.transform, self.query.transformed_srid) if geom.srid is None or geom.srid == self.query.transformed_srid: # If the geom parameter srid is None, it is assumed the coordinates # are in the transformed units. A placeholder is used for the # geometry parameter. `GeomFromText` constructor is also needed # to wrap geom placeholder for SpatiaLite. if SpatialBackend.spatialite: procedure_fmt += ', %s(%%%%s, %s)' % (SpatialBackend.from_text, self.query.transformed_srid) else: procedure_fmt += ', %%s' else: # We need to transform the geom to the srid specified in `transform()`, # so wrapping the geometry placeholder in transformation SQL. # SpatiaLite also needs geometry placeholder wrapped in `GeomFromText` # constructor. if SpatialBackend.spatialite: procedure_fmt += ', %s(%s(%%%%s, %s), %s)' % (SpatialBackend.transform, SpatialBackend.from_text, geom.srid, self.query.transformed_srid) else: procedure_fmt += ', %s(%%%%s, %s)' % (SpatialBackend.transform, self.query.transformed_srid) else: # `transform()` was not used on this GeoQuerySet. procedure_fmt = '%(geo_col)s,%(geom)s' if geodetic: # Spherical distance calculation is needed (because the geographic # field is geodetic). However, the PostGIS ST_distance_sphere/spheroid() # procedures may only do queries from point columns to point geometries # some error checking is required. if not isinstance(geo_field, PointField): raise ValueError('Spherical distance calculation only supported on PointFields.') if not str(SpatialBackend.Geometry(buffer(params[0].wkb)).geom_type) == 'Point': raise ValueError('Spherical distance calculation only supported with Point Geometry parameters') # The `function` procedure argument needs to be set differently for # geodetic distance calculations. if spheroid: # Call to distance_spheroid() requires spheroid param as well. procedure_fmt += ',%(spheroid)s' procedure_args.update({'function' : SpatialBackend.distance_spheroid, 'spheroid' : where[1]}) else: procedure_args.update({'function' : SpatialBackend.distance_sphere}) elif length or perimeter: procedure_fmt = '%(geo_col)s' if geodetic and length: # There's no `length_sphere` procedure_fmt += ',%(spheroid)s' procedure_args.update({'function' : SpatialBackend.length_spheroid, 'spheroid' : where[1]}) # Setting up the settings for `_spatial_attribute`. s = {'select_field' : DistanceField(dist_att), 'setup' : False, 'geo_field' : geo_field, 'procedure_args' : procedure_args, 'procedure_fmt' : procedure_fmt, } if geom_args: s['geom_args'] = ('geom',) s['procedure_args']['geom'] = geom elif geom: # The geometry is passed in as a parameter because we handled # transformation conditions in this routine. s['select_params'] = [SpatialBackend.Adaptor(geom)] return self._spatial_attribute(func, s, **kwargs)
def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs): """ DRY routine for GeoQuerySet distance attribute routines. """ # Setting up the distance procedure arguments. procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('field_name', None)) # If geodetic defaulting distance attribute to meters (Oracle and # PostGIS spherical distances return meters). Otherwise, use the # units of the geometry field. if geo_field.geodetic: dist_att = 'm' else: dist_att = Distance.unit_attname(geo_field.units_name) # Shortcut booleans for what distance function we're using. distance = func in 'distance' length = func == 'length' perimeter = func == 'perimeter' if not (distance or length or perimeter): raise ValueError('Unknown distance function: %s' % func) # The field's get_db_prep_lookup() is used to get any # extra distance parameters. Here we set up the # parameters that will be passed in to field's function. lookup_params = [geom or 'POINT (0 0)', 0] # If the spheroid calculation is desired, either by the `spheroid` # keyword or when calculating the length of geodetic field, make # sure the 'spheroid' distance setting string is passed in so we # get the correct spatial stored procedure. if spheroid or (SpatialBackend.postgis and geo_field.geodetic and length): lookup_params.append('spheroid') where, params = geo_field.get_db_prep_lookup('distance_lte', lookup_params) # The `geom_args` flag is set to true if a geometry parameter was # passed in. geom_args = bool(geom) if SpatialBackend.oracle: if distance: procedure_fmt = '%(geo_col)s,%(geom)s,%(tolerance)s' elif length or perimeter: procedure_fmt = '%(geo_col)s,%(tolerance)s' procedure_args['tolerance'] = tolerance else: # Getting whether this field is in units of degrees since the field may have # been transformed via the `transform` GeoQuerySet method. if self.query.transformed_srid: u, unit_name, s = get_srid_info(self.query.transformed_srid) geodetic = unit_name in geo_field.geodetic_units else: geodetic = geo_field.geodetic if SpatialBackend.spatialite and geodetic: raise ValueError('SQLite does not support linear distance calculations on geodetic coordinate systems.') if distance: if self.query.transformed_srid: # Setting the `geom_args` flag to false because we want to handle # transformation SQL here, rather than the way done by default # (which will transform to the original SRID of the field rather # than to what was transformed to). geom_args = False procedure_fmt = '%s(%%(geo_col)s, %s)' % (SpatialBackend.transform, self.query.transformed_srid) if geom.srid is None or geom.srid == self.query.transformed_srid: # If the geom parameter srid is None, it is assumed the coordinates # are in the transformed units. A placeholder is used for the # geometry parameter. `GeomFromText` constructor is also needed # to wrap geom placeholder for SpatiaLite. if SpatialBackend.spatialite: procedure_fmt += ', %s(%%%%s, %s)' % (SpatialBackend.from_text, self.query.transformed_srid) else: procedure_fmt += ', %%s' else: # We need to transform the geom to the srid specified in `transform()`, # so wrapping the geometry placeholder in transformation SQL. # SpatiaLite also needs geometry placeholder wrapped in `GeomFromText` # constructor. if SpatialBackend.spatialite: procedure_fmt += ', %s(%s(%%%%s, %s), %s)' % (SpatialBackend.transform, SpatialBackend.from_text, geom.srid, self.query.transformed_srid) else: procedure_fmt += ', %s(%%%%s, %s)' % (SpatialBackend.transform, self.query.transformed_srid) else: # `transform()` was not used on this GeoQuerySet. procedure_fmt = '%(geo_col)s,%(geom)s' if geodetic: # Spherical distance calculation is needed (because the geographic # field is geodetic). However, the PostGIS ST_distance_sphere/spheroid() # procedures may only do queries from point columns to point geometries # some error checking is required. if not isinstance(geo_field, PointField): raise ValueError('Spherical distance calculation only supported on PointFields.') if not str(SpatialBackend.Geometry(buffer(params[0].wkb)).geom_type) == 'Point': raise ValueError('Spherical distance calculation only supported with Point Geometry parameters') # The `function` procedure argument needs to be set differently for # geodetic distance calculations. if spheroid: # Call to distance_spheroid() requires spheroid param as well. procedure_fmt += ',%(spheroid)s' procedure_args.update({'function' : SpatialBackend.distance_spheroid, 'spheroid' : where[1]}) else: procedure_args.update({'function' : SpatialBackend.distance_sphere}) elif length or perimeter: procedure_fmt = '%(geo_col)s' if geodetic and length: # There's no `length_sphere` procedure_fmt += ',%(spheroid)s' procedure_args.update({'function' : SpatialBackend.length_spheroid, 'spheroid' : where[1]}) # Setting up the settings for `_spatial_attribute`. s = {'select_field' : DistanceField(dist_att), 'setup' : False, 'geo_field' : geo_field, 'procedure_args' : procedure_args, 'procedure_fmt' : procedure_fmt, } if geom_args: s['geom_args'] = ('geom',) s['procedure_args']['geom'] = geom elif geom: # The geometry is passed in as a parameter because we handled # transformation conditions in this routine. s['select_params'] = [SpatialBackend.Adaptor(geom)] return self._spatial_attribute(func, s, **kwargs)
<NME> query.py <BEF> def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs): """ DRY routine for GeoQuerySet distance attribute routines. """ # Setting up the distance procedure arguments. procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('field_name', None)) # If geodetic defaulting distance attribute to meters (Oracle and # PostGIS spherical distances return meters). Otherwise, use the # units of the geometry field. if geo_field.geodetic: dist_att = 'm' else: dist_att = Distance.unit_attname(geo_field.units_name) # Shortcut booleans for what distance function we're using. distance = func in 'distance' length = func == 'length' perimeter = func == 'perimeter' if not (distance or length or perimeter): raise ValueError('Unknown distance function: %s' % func) # The field's get_db_prep_lookup() is used to get any # extra distance parameters. Here we set up the # parameters that will be passed in to field's function. lookup_params = [geom or 'POINT (0 0)', 0] # If the spheroid calculation is desired, either by the `spheroid` # keyword or when calculating the length of geodetic field, make # sure the 'spheroid' distance setting string is passed in so we # get the correct spatial stored procedure. if spheroid or (SpatialBackend.postgis and geo_field.geodetic and length): lookup_params.append('spheroid') where, params = geo_field.get_db_prep_lookup('distance_lte', lookup_params) # The `geom_args` flag is set to true if a geometry parameter was # passed in. geom_args = bool(geom) if SpatialBackend.oracle: if distance: procedure_fmt = '%(geo_col)s,%(geom)s,%(tolerance)s' elif length or perimeter: procedure_fmt = '%(geo_col)s,%(tolerance)s' procedure_args['tolerance'] = tolerance else: # Getting whether this field is in units of degrees since the field may have # been transformed via the `transform` GeoQuerySet method. if self.query.transformed_srid: u, unit_name, s = get_srid_info(self.query.transformed_srid) geodetic = unit_name in geo_field.geodetic_units else: geodetic = geo_field.geodetic if SpatialBackend.spatialite and geodetic: raise ValueError('SQLite does not support linear distance calculations on geodetic coordinate systems.') if distance: if self.query.transformed_srid: # Setting the `geom_args` flag to false because we want to handle # transformation SQL here, rather than the way done by default # (which will transform to the original SRID of the field rather # than to what was transformed to). geom_args = False procedure_fmt = '%s(%%(geo_col)s, %s)' % (SpatialBackend.transform, self.query.transformed_srid) if geom.srid is None or geom.srid == self.query.transformed_srid: # If the geom parameter srid is None, it is assumed the coordinates # are in the transformed units. A placeholder is used for the # geometry parameter. `GeomFromText` constructor is also needed # to wrap geom placeholder for SpatiaLite. if SpatialBackend.spatialite: procedure_fmt += ', %s(%%%%s, %s)' % (SpatialBackend.from_text, self.query.transformed_srid) else: procedure_fmt += ', %%s' else: # We need to transform the geom to the srid specified in `transform()`, # so wrapping the geometry placeholder in transformation SQL. # SpatiaLite also needs geometry placeholder wrapped in `GeomFromText` # constructor. if SpatialBackend.spatialite: procedure_fmt += ', %s(%s(%%%%s, %s), %s)' % (SpatialBackend.transform, SpatialBackend.from_text, geom.srid, self.query.transformed_srid) else: procedure_fmt += ', %s(%%%%s, %s)' % (SpatialBackend.transform, self.query.transformed_srid) else: # `transform()` was not used on this GeoQuerySet. procedure_fmt = '%(geo_col)s,%(geom)s' if geodetic: # Spherical distance calculation is needed (because the geographic # field is geodetic). However, the PostGIS ST_distance_sphere/spheroid() # procedures may only do queries from point columns to point geometries # some error checking is required. if not isinstance(geo_field, PointField): raise ValueError('Spherical distance calculation only supported on PointFields.') if not str(SpatialBackend.Geometry(buffer(params[0].wkb)).geom_type) == 'Point': raise ValueError('Spherical distance calculation only supported with Point Geometry parameters') # The `function` procedure argument needs to be set differently for # geodetic distance calculations. if spheroid: # Call to distance_spheroid() requires spheroid param as well. procedure_fmt += ',%(spheroid)s' procedure_args.update({'function' : SpatialBackend.distance_spheroid, 'spheroid' : where[1]}) else: procedure_args.update({'function' : SpatialBackend.distance_sphere}) elif length or perimeter: procedure_fmt = '%(geo_col)s' if geodetic and length: # There's no `length_sphere` procedure_fmt += ',%(spheroid)s' procedure_args.update({'function' : SpatialBackend.length_spheroid, 'spheroid' : where[1]}) # Setting up the settings for `_spatial_attribute`. s = {'select_field' : DistanceField(dist_att), 'setup' : False, 'geo_field' : geo_field, 'procedure_args' : procedure_args, 'procedure_fmt' : procedure_fmt, } if geom_args: s['geom_args'] = ('geom',) s['procedure_args']['geom'] = geom elif geom: # The geometry is passed in as a parameter because we handled # transformation conditions in this routine. s['select_params'] = [SpatialBackend.Adaptor(geom)] return self._spatial_attribute(func, s, **kwargs) <MSG> Fix binary operator <DFF> @@ -14,7 +14,7 @@ dist_att = Distance.unit_attname(geo_field.units_name) # Shortcut booleans for what distance function we're using. - distance = func in 'distance' + distance = func == 'distance' length = func == 'length' perimeter = func == 'perimeter' if not (distance or length or perimeter):
5
def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs): # Setting up the distance procedure arguments. procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('field_name', None)) # If geodetic defaulting distance attribute to meters (Oracle and # PostGIS spherical distances return meters). Otherwise, use the # units of the geometry field. if geo_field.geodetic: dist_att = 'm' else: dist_att = Distance.unit_attname(geo_field.units_name) # Shortcut booleans for what distance function we're using. distance = func in 'distance' length = func == 'length' perimeter = func == 'perimeter' if not (distance or length or perimeter): raise ValueError('Unknown distance function: %s' % func) # The field's get_db_prep_lookup() is used to get any # extra distance parameters. Here we set up the # parameters that will be passed in to field's function. lookup_params = [geom or 'POINT (0 0)', 0] # If the spheroid calculation is desired, either by the `spheroid` # keyword or when calculating the length of geodetic field, make # sure the 'spheroid' distance setting string is passed in so we # get the correct spatial stored procedure. if spheroid or (SpatialBackend.postgis and geo_field.geodetic and length): lookup_params.append('spheroid') where, params = geo_field.get_db_prep_lookup('distance_lte', lookup_params) # The `geom_args` flag is set to true if a geometry parameter was # passed in. geom_args = bool(geom) if SpatialBackend.oracle: if distance: procedure_fmt = '%(geo_col)s,%(geom)s,%(tolerance)s' elif length or perimeter: procedure_fmt = '%(geo_col)s,%(tolerance)s' procedure_args['tolerance'] = tolerance else: # Getting whether this field is in units of degrees since the field may have # been transformed via the `transform` GeoQuerySet method. if self.query.transformed_srid: u, unit_name, s = get_srid_info(self.query.transformed_srid) geodetic = unit_name in geo_field.geodetic_units else: geodetic = geo_field.geodetic if SpatialBackend.spatialite and geodetic: raise ValueError('SQLite does not support linear distance calculations on geodetic coordinate systems.') if distance: if self.query.transformed_srid: # Setting the `geom_args` flag to false because we want to handle # transformation SQL here, rather than the way done by default # (which will transform to the original SRID of the field rather # than to what was transformed to). geom_args = False procedure_fmt = '%s(%%(geo_col)s, %s)' % (SpatialBackend.transform, self.query.transformed_srid) if geom.srid is None or geom.srid == self.query.transformed_srid: # If the geom parameter srid is None, it is assumed the coordinates # are in the transformed units. A placeholder is used for the # geometry parameter. `GeomFromText` constructor is also needed # to wrap geom placeholder for SpatiaLite. if SpatialBackend.spatialite: procedure_fmt += ', %s(%%%%s, %s)' % (SpatialBackend.from_text, self.query.transformed_srid) else: procedure_fmt += ', %%s' else: # We need to transform the geom to the srid specified in `transform()`, # so wrapping the geometry placeholder in transformation SQL. # SpatiaLite also needs geometry placeholder wrapped in `GeomFromText` # constructor. if SpatialBackend.spatialite: procedure_fmt += ', %s(%s(%%%%s, %s), %s)' % (SpatialBackend.transform, SpatialBackend.from_text, geom.srid, self.query.transformed_srid) else: procedure_fmt += ', %s(%%%%s, %s)' % (SpatialBackend.transform, self.query.transformed_srid) else: # `transform()` was not used on this GeoQuerySet. procedure_fmt = '%(geo_col)s,%(geom)s' if geodetic: # Spherical distance calculation is needed (because the geographic # field is geodetic). However, the PostGIS ST_distance_sphere/spheroid() # procedures may only do queries from point columns to point geometries # some error checking is required. if not isinstance(geo_field, PointField): raise ValueError('Spherical distance calculation only supported on PointFields.') if not str(SpatialBackend.Geometry(buffer(params[0].wkb)).geom_type) == 'Point': raise ValueError('Spherical distance calculation only supported with Point Geometry parameters') # The `function` procedure argument needs to be set differently for # geodetic distance calculations. if spheroid: # Call to distance_spheroid() requires spheroid param as well. procedure_fmt += ',%(spheroid)s' procedure_args.update({'function' : SpatialBackend.distance_spheroid, 'spheroid' : where[1]}) else: procedure_args.update({'function' : SpatialBackend.distance_sphere}) elif length or perimeter: procedure_fmt = '%(geo_col)s' if geodetic and length: # There's no `length_sphere` procedure_fmt += ',%(spheroid)s' procedure_args.update({'function' : SpatialBackend.length_spheroid, 'spheroid' : where[1]}) # Setting up the settings for `_spatial_attribute`. s = {'select_field' : DistanceField(dist_att), 'setup' : False, 'geo_field' : geo_field, 'procedure_args' : procedure_args, 'procedure_fmt' : procedure_fmt, } if geom_args: s['geom_args'] = ('geom',) s['procedure_args']['geom'] = geom elif geom: # The geometry is passed in as a parameter because we handled # transformation conditions in this routine. s['select_params'] = [SpatialBackend.Adaptor(geom)] return self._spatial_attribute(func, s, **kwargs)
def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs): # Setting up the distance procedure arguments. procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('field_name', None)) # If geodetic defaulting distance attribute to meters (Oracle and # PostGIS spherical distances return meters). Otherwise, use the # units of the geometry field. if geo_field.geodetic: dist_att = 'm' else: dist_att = Distance.unit_attname(geo_field.units_name) # Shortcut booleans for what distance function we're using. distance = func == 'distance' length = func == 'length' perimeter = func == 'perimeter' if not (distance or length or perimeter): raise ValueError('Unknown distance function: %s' % func) # The field's get_db_prep_lookup() is used to get any # extra distance parameters. Here we set up the # parameters that will be passed in to field's function. lookup_params = [geom or 'POINT (0 0)', 0] # If the spheroid calculation is desired, either by the `spheroid` # keyword or when calculating the length of geodetic field, make # sure the 'spheroid' distance setting string is passed in so we # get the correct spatial stored procedure. if spheroid or (SpatialBackend.postgis and geo_field.geodetic and length): lookup_params.append('spheroid') where, params = geo_field.get_db_prep_lookup('distance_lte', lookup_params) # The `geom_args` flag is set to true if a geometry parameter was # passed in. geom_args = bool(geom) if SpatialBackend.oracle: if distance: procedure_fmt = '%(geo_col)s,%(geom)s,%(tolerance)s' elif length or perimeter: procedure_fmt = '%(geo_col)s,%(tolerance)s' procedure_args['tolerance'] = tolerance else: # Getting whether this field is in units of degrees since the field may have # been transformed via the `transform` GeoQuerySet method. if self.query.transformed_srid: u, unit_name, s = get_srid_info(self.query.transformed_srid) geodetic = unit_name in geo_field.geodetic_units else: geodetic = geo_field.geodetic if SpatialBackend.spatialite and geodetic: raise ValueError('SQLite does not support linear distance calculations on geodetic coordinate systems.') if distance: if self.query.transformed_srid: # Setting the `geom_args` flag to false because we want to handle # transformation SQL here, rather than the way done by default # (which will transform to the original SRID of the field rather # than to what was transformed to). geom_args = False procedure_fmt = '%s(%%(geo_col)s, %s)' % (SpatialBackend.transform, self.query.transformed_srid) if geom.srid is None or geom.srid == self.query.transformed_srid: # If the geom parameter srid is None, it is assumed the coordinates # are in the transformed units. A placeholder is used for the # geometry parameter. `GeomFromText` constructor is also needed # to wrap geom placeholder for SpatiaLite. if SpatialBackend.spatialite: procedure_fmt += ', %s(%%%%s, %s)' % (SpatialBackend.from_text, self.query.transformed_srid) else: procedure_fmt += ', %%s' else: # We need to transform the geom to the srid specified in `transform()`, # so wrapping the geometry placeholder in transformation SQL. # SpatiaLite also needs geometry placeholder wrapped in `GeomFromText` # constructor. if SpatialBackend.spatialite: procedure_fmt += ', %s(%s(%%%%s, %s), %s)' % (SpatialBackend.transform, SpatialBackend.from_text, geom.srid, self.query.transformed_srid) else: procedure_fmt += ', %s(%%%%s, %s)' % (SpatialBackend.transform, self.query.transformed_srid) else: # `transform()` was not used on this GeoQuerySet. procedure_fmt = '%(geo_col)s,%(geom)s' if geodetic: # Spherical distance calculation is needed (because the geographic # field is geodetic). However, the PostGIS ST_distance_sphere/spheroid() # procedures may only do queries from point columns to point geometries # some error checking is required. if not isinstance(geo_field, PointField): raise ValueError('Spherical distance calculation only supported on PointFields.') if not str(SpatialBackend.Geometry(buffer(params[0].wkb)).geom_type) == 'Point': raise ValueError('Spherical distance calculation only supported with Point Geometry parameters') # The `function` procedure argument needs to be set differently for # geodetic distance calculations. if spheroid: # Call to distance_spheroid() requires spheroid param as well. procedure_fmt += ',%(spheroid)s' procedure_args.update({'function' : SpatialBackend.distance_spheroid, 'spheroid' : where[1]}) else: procedure_args.update({'function' : SpatialBackend.distance_sphere}) elif length or perimeter: procedure_fmt = '%(geo_col)s' if geodetic and length: # There's no `length_sphere` procedure_fmt += ',%(spheroid)s' procedure_args.update({'function' : SpatialBackend.length_spheroid, 'spheroid' : where[1]}) # Setting up the settings for `_spatial_attribute`. s = {'select_field' : DistanceField(dist_att), 'setup' : False, 'geo_field' : geo_field, 'procedure_args' : procedure_args, 'procedure_fmt' : procedure_fmt, } if geom_args: s['geom_args'] = ('geom',) s['procedure_args']['geom'] = geom elif geom: # The geometry is passed in as a parameter because we handled # transformation conditions in this routine. s['select_params'] = [SpatialBackend.Adaptor(geom)] return self._spatial_attribute(func, s, **kwargs)
bin-op
<NME> server.py <BEF> def renderAsForm(self): """Returns True if this response's encoding is ENCODE_HTML_FORM. Convenience method for server authors. @returntype: bool @since: 2.1.0 """ return self.whichEncoding() >= ENCODE_HTML_FORM <MSG> Fix binary operator <DFF>
def renderAsForm(self): """Returns True if this response's encoding is ENCODE_HTML_FORM. Convenience method for server authors. @returntype: bool @since: 2.1.0 """ return self.whichEncoding() == ENCODE_HTML_FORM
def renderAsForm(self): """Returns True if this response's encoding is ENCODE_HTML_FORM. Convenience method for server authors. @returntype: bool @since: 2.1.0 """ return self.whichEncoding() >= ENCODE_HTML_FORM
<NME> server.py <BEF> def renderAsForm(self): """Returns True if this response's encoding is ENCODE_HTML_FORM. Convenience method for server authors. @returntype: bool @since: 2.1.0 """ return self.whichEncoding() >= ENCODE_HTML_FORM <MSG> Fix binary operator <DFF> @@ -6,4 +6,4 @@ @since: 2.1.0 """ - return self.whichEncoding() >= ENCODE_HTML_FORM + return self.whichEncoding() == ENCODE_HTML_FORM
6
def renderAsForm(self): return self.whichEncoding() >= ENCODE_HTML_FORM
def renderAsForm(self): return self.whichEncoding() == ENCODE_HTML_FORM
bin-op
<NME> wkb.py <BEF> def linearRing(coordinates): partCount=coordinates.count i=0 values =[0] outnum = "I" out = ["I",[0]] while i<partCount: pt = coordinates[i] if pt: [ptrn,c]=pts(pt) outnum+=ptrn values[0]+=1 values.extend(c) else: if values[0]>4: return False out[0]+=outnum out[1][0]+=1 out[1].extend(values) values =[0] outnum = "I" i+=1 if values[0]<4: return False out[0]+=outnum out[1][0]+=1 out[1].extend(values) return out <MSG> Fix binary operator <DFF>
def linearRing(coordinates): partCount=coordinates.count i=0 values =[0] outnum = "I" out = ["I",[0]] while i<partCount: pt = coordinates[i] if pt: [ptrn,c]=pts(pt) outnum+=ptrn values[0]+=1 values.extend(c) else: if values[0]<4: return False out[0]+=outnum out[1][0]+=1 out[1].extend(values) values =[0] outnum = "I" i+=1 if values[0]<4: return False out[0]+=outnum out[1][0]+=1 out[1].extend(values) return out
def linearRing(coordinates): partCount=coordinates.count i=0 values =[0] outnum = "I" out = ["I",[0]] while i<partCount: pt = coordinates[i] if pt: [ptrn,c]=pts(pt) outnum+=ptrn values[0]+=1 values.extend(c) else: if values[0]>4: return False out[0]+=outnum out[1][0]+=1 out[1].extend(values) values =[0] outnum = "I" i+=1 if values[0]<4: return False out[0]+=outnum out[1][0]+=1 out[1].extend(values) return out
<NME> wkb.py <BEF> def linearRing(coordinates): partCount=coordinates.count i=0 values =[0] outnum = "I" out = ["I",[0]] while i<partCount: pt = coordinates[i] if pt: [ptrn,c]=pts(pt) outnum+=ptrn values[0]+=1 values.extend(c) else: if values[0]>4: return False out[0]+=outnum out[1][0]+=1 out[1].extend(values) values =[0] outnum = "I" i+=1 if values[0]<4: return False out[0]+=outnum out[1][0]+=1 out[1].extend(values) return out <MSG> Fix binary operator <DFF> @@ -12,7 +12,7 @@ values[0]+=1 values.extend(c) else: - if values[0]>4: + if values[0]<4: return False out[0]+=outnum out[1][0]+=1
7
def linearRing(coordinates): partCount=coordinates.count i=0 values =[0] outnum = "I" out = ["I",[0]] while i<partCount: pt = coordinates[i] if pt: [ptrn,c]=pts(pt) outnum+=ptrn values[0]+=1 values.extend(c) else: if values[0]>4: return False out[0]+=outnum out[1][0]+=1 out[1].extend(values) values =[0] outnum = "I" i+=1 if values[0]<4: return False out[0]+=outnum out[1][0]+=1 out[1].extend(values) return out
def linearRing(coordinates): partCount=coordinates.count i=0 values =[0] outnum = "I" out = ["I",[0]] while i<partCount: pt = coordinates[i] if pt: [ptrn,c]=pts(pt) outnum+=ptrn values[0]+=1 values.extend(c) else: if values[0]<4: return False out[0]+=outnum out[1][0]+=1 out[1].extend(values) values =[0] outnum = "I" i+=1 if values[0]<4: return False out[0]+=outnum out[1][0]+=1 out[1].extend(values) return out
bin-op
<NME> taskqueue_service_pb.py <BEF> def MergeFrom(self, x): assert x < self if (x.has_queue_name()): self.set_queue_name(x.queue_name()) if (x.has_bucket_refill_per_second()): self.set_bucket_refill_per_second(x.bucket_refill_per_second()) if (x.has_bucket_capacity()): self.set_bucket_capacity(x.bucket_capacity()) if (x.has_user_specified_rate()): self.set_user_specified_rate(x.user_specified_rate()) <MSG> Fix binary operator <DFF>
def MergeFrom(self, x): assert x is not self if (x.has_queue_name()): self.set_queue_name(x.queue_name()) if (x.has_bucket_refill_per_second()): self.set_bucket_refill_per_second(x.bucket_refill_per_second()) if (x.has_bucket_capacity()): self.set_bucket_capacity(x.bucket_capacity()) if (x.has_user_specified_rate()): self.set_user_specified_rate(x.user_specified_rate())
def MergeFrom(self, x): assert x < self if (x.has_queue_name()): self.set_queue_name(x.queue_name()) if (x.has_bucket_refill_per_second()): self.set_bucket_refill_per_second(x.bucket_refill_per_second()) if (x.has_bucket_capacity()): self.set_bucket_capacity(x.bucket_capacity()) if (x.has_user_specified_rate()): self.set_user_specified_rate(x.user_specified_rate())
<NME> taskqueue_service_pb.py <BEF> def MergeFrom(self, x): assert x < self if (x.has_queue_name()): self.set_queue_name(x.queue_name()) if (x.has_bucket_refill_per_second()): self.set_bucket_refill_per_second(x.bucket_refill_per_second()) if (x.has_bucket_capacity()): self.set_bucket_capacity(x.bucket_capacity()) if (x.has_user_specified_rate()): self.set_user_specified_rate(x.user_specified_rate()) <MSG> Fix binary operator <DFF> @@ -1,5 +1,5 @@ def MergeFrom(self, x): - assert x < self + assert x is not self if (x.has_queue_name()): self.set_queue_name(x.queue_name()) if (x.has_bucket_refill_per_second()): self.set_bucket_refill_per_second(x.bucket_refill_per_second()) if (x.has_bucket_capacity()): self.set_bucket_capacity(x.bucket_capacity())
8
def MergeFrom(self, x): assert x < self if (x.has_queue_name()): self.set_queue_name(x.queue_name()) if (x.has_bucket_refill_per_second()): self.set_bucket_refill_per_second(x.bucket_refill_per_second()) if (x.has_bucket_capacity()): self.set_bucket_capacity(x.bucket_capacity()) if (x.has_user_specified_rate()): self.set_user_specified_rate(x.user_specified_rate())
def MergeFrom(self, x): assert x is not self if (x.has_queue_name()): self.set_queue_name(x.queue_name()) if (x.has_bucket_refill_per_second()): self.set_bucket_refill_per_second(x.bucket_refill_per_second()) if (x.has_bucket_capacity()): self.set_bucket_capacity(x.bucket_capacity()) if (x.has_user_specified_rate()): self.set_user_specified_rate(x.user_specified_rate())
End of preview. Expand in Data Studio

Dataset Card for "python-bugs-name-noise-1"

More Information needed

Downloads last month
47