Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Continue the code snippet: <|code_start|> 'nethz': 'user%i' % next(counter), 'password': 'pass', 'gender': random.choice(['male', 'female']), 'firstname': 'Pablo%i' % next(counter), 'lastname': 'AMIV%i' % next(counter), 'membership': random.choice(['none', 'regular', ...
'time_register_start': datetime(1970, 1, 1).strftime(DATE_FORMAT),
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- # # license: AGPLv3, see LICENSE for details. In addition we strongly encourage # you to buy us beer if we meet and you like the software. """Group settings. Contains models for groups and group mmeberships. """ class GroupAuth...
user_id == str(get_id(item['moderator'])))
Given snippet: <|code_start|> }, 'receive_from': { 'description': 'Email addresses from which the group will ' 'receive mails. Must only contain a local ' 'address (everything before the @), as the ' ...
'regex': EMAIL_REGEX
Given snippet: <|code_start|> 'type': 'string', 'readonly': True, } }, } } # Login Hook def process_login(items): """Hook to add token on POST to /sessions. Attempts to first login via LDAP (if enabled), then login via database. If the login is suc...
ldap.authenticate_user(username, password)):
Here is a snippet: <|code_start|>def verify_password(user, plaintext): """Check password of user, rehash if necessary. It is possible that the password is None, e.g. if the user is authenticated via LDAP. In this case default to "not verified". Args: user (dict): the user in question. ...
@periodic(datetime.timedelta(days=1))
Here is a snippet: <|code_start|> # Add token (str) and user_id (ObejctId) item['user'] = user_id item['token'] = token def verify_password(user, plaintext): """Check password of user, rehash if necessary. It is possible that the password is None, e.g. if the user is authenticated via LDAP. I...
with admin_permissions():
Given snippet: <|code_start|># -*- coding: utf-8 -*- # # license: AGPLv3, see LICENSE for details. In addition we strongly encourage # you to buy us beer if we meet and you like the software. """Sessions endpoint.""" # Change when we drop python3.5 support try: except ImportError: class SessionAuth(AmivT...
return user_id == str(get_id(item['user']))
Using the snippet: <|code_start|># -*- coding: utf-8 -*- # # license: AGPLv3, see LICENSE for details. In addition we strongly encourage # you to buy us beer if we meet and you like the software. """Test that additional fields are projected for events. These are: - events.signup_count - eventsignups.email - ev...
class EventProjectionTest(WebTestNoAuth):
Given snippet: <|code_start|># -*- coding: utf-8 -*- # # license: AGPLv3, see LICENSE for details. In addition we strongly encourage # you to buy us beer if we meet and you like the software. """Authorization for events and eventsignups resources""" class EventAuth(AmivTokenAuth): """Auth for events.""...
user_id == str(get_id(item['moderator'])))
Predict the next line after this snippet: <|code_start|> Includes item and field permissions as well as password hashing. """ class PasswordHashing(utils.WebTestNoAuth): """Tests password hashing.""" def assertVerify(self, plaintext, hashed_password): """Assert the hash matches the password.""" ...
hash_on_insert(items)
Based on the snippet: <|code_start|> self.assertTrue(pbkdf2_sha256.verify(plaintext, hashed_password)) def test_hash_on_insert(self): """Test Hash insert function. Because of how Eve handles hooks, they all modify the input arguments. Need app context to find config. """ ...
hash_on_update(data, None)
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- # # license: AGPLv3, see LICENSE for details. In addition we strongly encourage # you to buy us beer if we meet and you like the software. """Test that expired group memberships are deleted.""" class GroupMembershipExpiry(WebTe...
run_scheduled_tasks()
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- # # license: AGPLv3, see LICENSE for details. In addition we strongly encourage # you to buy us beer if we meet and you like the software. """Test Media handling.""" lenaname = "lena.png" lenapath = join(dirname(__file__), "fixtures", lenaname) wi...
class MediaTest(WebTestNoAuth):
Based on the snippet: <|code_start|> There is another file, "ldap_integration.py", which can be used to test integration with the real ldap. More info there. """ class LdapTest(WebTestNoAuth): """Tests for LDAP with a mock connection.""" def setUp(self, *args, **kwargs): """Extended setUp, enable ...
ldap.init_app(self.app)
Given the code snippet: <|code_start|> self.app.config['LDAP_DEPARTMENT_MAP'] = {'a': 'itet'} expected_query = '(& (ou=VSETH Mitglied) (| (departmentNumber=*a*)) )' search_results = (i for i in [1, 2]) search = 'amivapi.ldap._search' create = 'amivapi.ldap._create_or_update_user' ...
class LdapIntegrationTest(WebTest):
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- # # license: AGPLv3, see LICENSE for details. In addition we strongly encourage # you to buy us beer if we meet and you like the software. """LDAP Tests. Mock the actual ldap responses, since we can only access ldap...
class LdapTest(WebTestNoAuth):
Predict the next line for this snippet: <|code_start|> self.assertEqual(result, None) mock_create.assert_not_called() def test_sync_all(self): """Test if sync_all builds the query correctly and creates users.""" # Shorten ou list self.app.config['LDAP_DEPARTME...
requires_credentials = skip_if_false(LDAP_USERNAME and LDAP_PASSWORD,
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # # license: AGPLv3, see LICENSE for details. In addition we strongly encourage # you to buy us beer if we meet and you like the software. """Email formatting. Needed when users are notified about their event signups. """ def not...
s = URLSafeSerializer(get_token_secret())
Based on the snippet: <|code_start|>"""Email formatting. Needed when users are notified about their event signups. """ def notify_signup_accepted(event, signup): """Send an email to a user that his signup was accepted""" id_field = current_app.config['ID_FIELD'] if signup.get('user'): lookup = ...
mail([email],
Given the following code snippet before the placeholder: <|code_start|> id_field = current_app.config['ID_FIELD'] lookup = {id_field: event_id} event = current_app.data.find_one('events', None, **lookup) accepted_ids = [] if event['selection_strategy'] == 'fcfs': lookup = {'event': event_id...
notify_signup_accepted(event, new_accepted)
Using the snippet: <|code_start|> else: std.SetProp("Standardized", "True") except: errors += 1 utils.log("Error standardizing", sys.exc_info()[0]) std = mol std.SetProp("Standardized", "Error") c...
enumerated = enumerateStereoIsomers(m)
Given the following code snippet before the placeholder: <|code_start|> inputCanSmiles = Chem.MolToSmiles(mol, isomericSmiles=True, canonical=True) try: std = getStandardMolecule(mol) outputCanSmiles = Chem.MolToSmiles(std, isomericSmiles=True, canonical=True) ...
results = enumerateTautomers(mol)
Given snippet: <|code_start|> def write_out(mols,count,writer,mol_format,file_format): for mol in mols: count += 1 if mol is None: continue if mol_format == 'mol_3d': AllChem.EmbedMolecule(mol,AllChem.ETKDG()) fmt = 'mol' elif mol_format == 'mol_2d': ...
parser.add_argument('-stm','--standardize_method', default="molvs",choices=STANDARD_MOL_METHODS.keys(),help="Choose the method to standardize.")
Using the snippet: <|code_start|> def enumerateMol(mol, fragment): """ Enumerate a single molecule :param mol: :param fragment The fragmentation method, 'hac' or 'mw'. If not specified the whole molecules is passed to Dimorphite :return: """ if fragment: mol = mol_utils.fragment(m...
protonated_mols = run_with_mol_list(inputmol)
Given the code snippet: <|code_start|> # If subtag=HmacKeyTag: # props = keyLengthBytes:uint32_t, hashId:uint32_t # If subtag=RsaHashedKeyTag: # props = algorithmId:uint32_t, type:uint32_t, # modulusLengthBits...
return ccl_v8_value_deserializer.read_le_varint(stream)[0]
Given the following code snippet before the placeholder: <|code_start|> self.artifacts_display = {} if self.preferences is None: self.preferences = [] if self.origin_hashes is None: self.origin_hashes = {} @staticmethod def format_processing_output(name, ite...
conn = utils.open_sqlite_db(self, path, database)
Given the code snippet: <|code_start|> self._f = file.open("rb") self._f.seek(-LdbFile.FOOTER_SIZE, os.SEEK_END) self._meta_index_handle = BlockHandle.from_stream(self._f) self._index_handle = BlockHandle.from_stream(self._f) self._f.seek(-8, os.SEEK_END) magic, = struct...
raw_block = ccl_simplesnappy.decompress(buff)
Predict the next line after this snippet: <|code_start|> cat = SourceCatalog3FGL(filename='input_data/3fgl.fits.gz') sources = get_selected_sources(cat, sources) for idx in sources: source = cat[idx] data = source._data_python_dict data['source_id'] = data['catalog_row_index'] ...
list_of_dict = table_to_list_of_dict(table.filled())
Given snippet: <|code_start|> 'make_tev_catalog_data', 'make_tev_source_data', 'make_3fhl_catalog_data', 'make_3fhl_source_data', 'make_3fgl_catalog_data', 'make_3fgl_source_data', 'make_snrcat_catalog_data' ] TO_JSON_KWARGS = dict(orient='split', double_precision=5) def make_3fhl_catalog_...
dump_to_json(data, filename)
Using the snippet: <|code_start|>] TO_JSON_KWARGS = dict(orient='split', double_precision=5) def make_3fhl_catalog_data(): click.secho('Making 3FHL catalog data...', fg='green') out_dir = DATA_DIR / 'cat/3fhl' out_dir.mkdir(parents=True, exist_ok=True) cat = SourceCatalog3FHL(filename='input_data/3...
sources = get_selected_sources(cat, sources)
Based on the snippet: <|code_start|>""" Prepare catalog data for the website. """ __all__ = [ 'make_tev_catalog_data', 'make_tev_source_data', 'make_3fhl_catalog_data', 'make_3fhl_source_data', 'make_3fgl_catalog_data', 'make_3fgl_source_data', 'make_snrcat_catalog_data' ] TO_JSON_KWARGS =...
out_dir = DATA_DIR / 'cat/3fhl'
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- handlers = [] handlers.extend(account.handlers) handlers.extend(topic.handlers) <|code_end|> with the help of current file imports: from handlers import account, topic, node, member, tool and context from other file...
handlers.extend(node.handlers)
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- handlers = [] handlers.extend(account.handlers) handlers.extend(topic.handlers) handlers.extend(node.handlers) <|code_end|> , continue by predicting the next line. Consider current file imports: from handlers import account, topic, node, memb...
handlers.extend(member.handlers)
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- handlers = [] handlers.extend(account.handlers) handlers.extend(topic.handlers) handlers.extend(node.handlers) handlers.extend(member.handlers) <|code_end|> , continue by predicting the next line. Consider current file imports: from handlers ...
handlers.extend(tool.handlers)
Predict the next line after this snippet: <|code_start|>major = sys.version_info[0] if major < 3: reload(sys) sys.setdefaultencoding('utf-8') define('port', default=8888, help='run on the given port', type=int) class Application(tornado.web.Application): def __init__(self): #Use Qiniu to store a...
self.db = db
Given the following code snippet before the placeholder: <|code_start|>if major < 3: reload(sys) sys.setdefaultencoding('utf-8') define('port', default=8888, help='run on the given port', type=int) class Application(tornado.web.Application): def __init__(self): #Use Qiniu to store avatars ...
self.async_db = async_db
Given the code snippet: <|code_start|>""" Provides a easy way for accessing all needed database functions """ __author__ = 'Jesse' class server_stats(object): @staticmethod def failures_in_x_minutes_ago(last_x_minutes_of_failures): """ Returns list of failures from variable""" <|code_end|> , genera...
conn, cur = db_controller.db_access().open_connection()
Here is a snippet: <|code_start|> __author__ = 'Jesse Laptop' class email_actions(): def __init__(self): pass @staticmethod def send_alert(server_info_object): logging.debug(server_info_object) subj = server_info_object.sl_service_type + " @ " + server_info_object.sl_host + ' ...
db_helpers.email_log.log_email_sent(''.join(msg))
Predict the next line after this snippet: <|code_start|> __author__ = 'Jesse Laptop' class email_actions(): def __init__(self): pass @staticmethod def send_alert(server_info_object): logging.debug(server_info_object) subj = server_info_object.sl_service_type + " @ " + server_i...
email_controller.send_gmail().send(subject=subj, text=''.join(msg))
Given snippet: <|code_start|> action="store_true", help="Debug Mode Logging") args = parser.parse_args() if args.debug: logging.basicConfig(format="[%(asctime)s] [%(levelname)8s] --- %(message)s (%(filename)s:%(lineno)s)", level...
db_controller.db_helper().configure()
Based on the snippet: <|code_start|> generate_report() print('*NOTE: If report is empty, that just means nothing has failed since we sent an email, ' 'run -m to "fix" it*') if args.monitor: db_controller.db_helper().test_db_setup() email_controller.send_gmail().test_log...
self.server_list = db_helpers.monitor_list.get_server_list()
Given snippet: <|code_start|> > db_helpers.monitor_list.get_time_from_last_failure(): # Are we spamming alerts? # Check if any servers have gone down in the the last X minutes # If any have gone down, send report if email_controller.send...
up_down_flag = network.MonitorHTTP(url=self.sl_host, timeout=self.host_timeout).run_test()
Predict the next line for this snippet: <|code_start|> action="store", type=int, default=10, help="Wait x seconds for failure (10)") parser.add_argument("--debug", action="store_true", ...
db_monitor_list.get_print_server_list()
Predict the next line after this snippet: <|code_start|> level=logging.DEBUG) logging.debug(sys.path) logging.debug(args) logging.debug('Debug Mode Enabled') else: logging.basicConfig(filename=LOG_FILENAME, format="[%(asctime)s] ...
email_controller.send_gmail().configure()
Predict the next line after this snippet: <|code_start|> except KeyboardInterrupt: print("Bye Bye.") sys.exit(0) def multi_server(self): print("Multi Server mode") print("Press Ctrl-C to quit") while True: self.server_list = db_helpers.monitor_lis...
email_alerts.email_actions.generate_report()
Predict the next line after this snippet: <|code_start|> except urllib2.URLError: pass if http_response_code == 200: response_flag = True else: response_flag = False logging.error('Cannot reach gmail.com') logging.debug('Testing login') ...
db_helpers.email_log.log_email_sent(self.SEND_ALERT_TO)
Given snippet: <|code_start|> class SecurityCommand(unicode_str): """ A string suitable for passing as the 'command' parameter to the OS X 'security' command. """ def __new__(cls, cmd, store='generic'): cmd = '%(cmd)s-%(store)s-password' % vars() return super(SecurityCommand, cls)....
class Keyring(KeyringBackend):
Given snippet: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- # =========================================================================== # NEWS CHANNEL GENERATION SCRIPT # AUTHORS: LARSEN VALLECILLO # **************************************************************************** # Copyright (c) 2015-2022 Rii...
setup_log(config["sentry_url"], True)
Here is a snippet: <|code_start|> read = gmaps.geocode(name, language=languages[language_code]) loc_name = read[0]["address_components"][0]["long_name"] for loc in read[0]["address_components"]: if "locality" in loc["types"]: loc...
log(ex, "INFO")
Continue the code snippet: <|code_start|> for keys, values in list(data.items()): location = values[7] if location and location != "": if location not in locations: locations[location] = [None, None, []] locations[location][2].append(keys) for name in l...
country = u8(0)
Using the snippet: <|code_start|> location = values[7] if location and location != "": if location not in locations: locations[location] = [None, None, []] locations[location][2].append(keys) for name in list(locations.keys()): if name == "": ...
location = u16(0)
Given the following code snippet before the placeholder: <|code_start|> self.soup = soup self.session = requests.Session() if self.source != "AP" and self.source != "Reuters": init = self.newspaper_init() if init == []: return None { "...
u32(self.updated_time),
Here is a snippet: <|code_start|> if location and location != "": if location not in locations: locations[location] = [None, None, []] locations[location][2].append(keys) for name in list(locations.keys()): if name == "": continue print(...
zoom_factor = u32_littleendian(
Given snippet: <|code_start|> locations[location][2].append(keys) for name in list(locations.keys()): if name == "": continue print(name) coordinates = None if name not in cities: try: read = gmaps.geocode(name, language=language...
s16(int(read[0]["geometry"]["location"]["lat"] / (360 / 65536)))
Based on the snippet: <|code_start|> keyIndex = list(forecastlists.laundry).index(k) laundry[keyIndex] = v.encode("utf-16be") + pad(2) return laundry def make_pollen_text_table(): pollen = {} for k, v in forecastlists.pollen.items(): keyIndex = list(forecastlists.pollen).index(k) ...
setup_log(config["sentry_url"], False)
Given snippet: <|code_start|> def get_lat(forecast_list, key): return forecast_list[key][3][:4] def get_lng(forecast_list, key): return forecast_list[key][3][:8][4:] def isJapan(forecast_list, key): return forecast_list[key][2][1] == "Japan" def matches_country_code(forecast_list, key): v = foreca...
log("Coordinate Inaccuracy Detected: %s" % key, "WARNING")
Based on the snippet: <|code_start|> lon = coord_decode(get_lng(forecast_list, key)) if config["download_locations"]: location_key = request_data( "https://api.accuweather.com/locations/v1/cities/geoposition/search.json?q={},{}&apikey={}".format( lat, lon, api_key ...
header["country_code"] = u8(country_code) # Wii Country Code.
Predict the next line after this snippet: <|code_start|> for key in forecast_list.keys(): keyIndex = list(forecast_list).index(key) short_forecast_table["location_code_%s" % keyIndex] = binascii.unhexlify( get_locationkey(forecast_list, key) ) # Wii location code for city ...
short_forecast_table["unknown_2_%s" % keyIndex] = u16(0) # 00?
Predict the next line after this snippet: <|code_start|> except: blank_data(forecast_list, key) return j = 0 for i in range(hourly_start, 8): hourly[key][i] = get_icon( int(data_quarters[quarter_offset + j]["Icon"]), forecast_list, key ) j += 1...
file.write(u32(data))
Given snippet: <|code_start|> def make_long_forecast_table(forecast_list): long_forecast_table = {} for key in forecast_list.keys(): if ( matches_country_code(forecast_list, key) and get_region(forecast_list, key) != "" ): keyIndex = list(forecast_list).index(...
long_forecast_table["today_tempc_high_%s" % keyIndex] = s8(
Given snippet: <|code_start|> if file_type == "q" or file_type == "r": question_file = get_name() + "_" + file_type else: question_file = "voting" print("Writing to %s.bin ..." % question_file) with open(question_file, "wb") as f: for dictionary in dictionaries: ...
header["country_code"] = u8(country_code)
Given snippet: <|code_start|> f.write(values) f.write(pad(16)) f.write('RIICONNECT24'.encode("ASCII")) f.flush() if config["production"]: sign_file(question_file) print("Writing Completed") for dictionary in dictionaries: dictionary.clear() def make...
header["national_result_detailed_number"] = u16(national_results * region_number[country_code])
Based on the snippet: <|code_start|> "author_icon": "https://rc24.xyz/images/webhooks/votes/profile.png", "text": webhook_text, "title": "Update!", "fields": [{"title": "Script", "value": "Everybody Votes Channel", "short": "false"}], "thumb_url": "http...
def offset_count(): return u32(12 + sum(len(values) for dictionary in dictionaries for values in list(dictionary.values()) if values))
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- # =========================================================================== # NEWS CHANNEL GENERATION SCRIPT # AUTHORS: LARSEN VALLECILLO # ****************************************************************...
setup_log(config["sentry_url"], True) # error logging
Given the following code snippet before the placeholder: <|code_start|> ]: # brilliant way to keep the news flowing when it's close to or over the file size limit, surprisingly seems to work? path = "{}/v2/{}_{}".format(config["file_path"], language_code, region) try: size = round( ...
log("News files exceed the maximum file size amount.", "error")
Predict the next line after this snippet: <|code_start|> "title": "Script", "value": "News Channel (" + name + ")", "short": "false", } ], "thumb_url": "https://rc24.xyz/ima...
mkdir_p(path)
Based on the snippet: <|code_start|> for k, v in list(data.items()): if v[3] not in headlines: headlines.append(v[3]) elif v[3] in headlines: del data[k] return data # Make the news.bin # First part of the header def make_header(data): header = {} dictionarie...
header["language_select_%s" % numbers] = u8(language)
Here is a snippet: <|code_start|> numbers += 1 header["language_select_%s" % numbers] = u8(language) # Fills the rest of the languages as null while numbers < 16: numbers += 1 header["language_select_%s" % numbers] = u8(255) header["language_code"] = u8(language_code) # ...
header["count"] = u16(480) # Count value.
Predict the next line for this snippet: <|code_start|> # Run the functions to make the news def make_news_bin(mode, data, locations_data, region): global dictionaries, languages, country_code, language_code source = sources[mode] if source is None: print("Could not find %s in sources.") to...
newstime[data[keys][3]] = get_timestamp(1) + u32(numbers)
Given the code snippet: <|code_start|> + 1500 ) # Remove duplicate articles def remove_duplicates(data): headlines = [] for k, v in list(data.items()): if v[3] not in headlines: headlines.append(v[3]) elif v[3] in headlines: del data[k] return...
header["country_code"] = u32_littleendian(country_code) # Wii Country Code.
Continue the code snippet: <|code_start|> verify_hashes=True, retry_exceptions=(socket.error,)): """Download an archive to a file. :type filename: str :param filename: The name of the file where the archive contents will be saved. :type chunk_size: i...
raise TreeHashDoesNotMatchError(
Given the code snippet: <|code_start|> verify_hashes, retry_exceptions) def _download_to_fileob(self, fileobj, num_chunks, chunk_size, verify_hashes, retry_exceptions): for i in xrange(num_chunks): byte_range = ((i * chunk_size), (...
raise DownloadArchiveError("There was an error downloading"
Given snippet: <|code_start|> def download_to_file(self, filename, chunk_size=DefaultPartSize, verify_hashes=True, retry_exceptions=(socket.error,)): """Download an archive to a file. :type filename: str :param filename: The name of the file where the archive ...
actual_tree_hash = bytes_to_hex(tree_hash(chunk_hashes(data)))
Given the following code snippet before the placeholder: <|code_start|> def download_to_file(self, filename, chunk_size=DefaultPartSize, verify_hashes=True, retry_exceptions=(socket.error,)): """Download an archive to a file. :type filename: str :param filename: The...
actual_tree_hash = bytes_to_hex(tree_hash(chunk_hashes(data)))
Given the code snippet: <|code_start|> def download_to_file(self, filename, chunk_size=DefaultPartSize, verify_hashes=True, retry_exceptions=(socket.error,)): """Download an archive to a file. :type filename: str :param filename: The name of the file where the archi...
actual_tree_hash = bytes_to_hex(tree_hash(chunk_hashes(data)))
Continue the code snippet: <|code_start|> while self.should_continue: try: work = self._worker_queue.get(timeout=1) except Empty: continue if work is _END_SENTINEL: return result = self._process_chunk(work) ...
tree_hash_bytes = tree_hash(chunk_hashes(contents))
Predict the next line after this snippet: <|code_start|> :rtype: str :return: The archive id of the newly created archive. """ fileobj = open(filename, 'rb') total_size = os.fstat(fileobj.fileno()).st_size total_parts = int(math.ceil(total_size / float(self._part_size))) ...
self._vault_name, upload_id, bytes_to_hex(tree_hash(hash_chunks)),
Continue the code snippet: <|code_start|> :rtype: str :return: The archive id of the newly created archive. """ fileobj = open(filename, 'rb') total_size = os.fstat(fileobj.fileno()).st_size total_parts = int(math.ceil(total_size / float(self._part_size))) hash_ch...
self._vault_name, upload_id, bytes_to_hex(tree_hash(hash_chunks)),
Given the code snippet: <|code_start|> :type file: str :param file: The filename to upload :type description: str :param description: The description of the archive. :rtype: str :return: The archive id of the newly created archive. """ fileobj = open(fi...
except UploadArchiveError, e:
Given snippet: <|code_start|> break self.region = region self.account_id = account_id AWSAuthConnection.__init__(self, region.endpoint, aws_access_key_id, aws_secret_access_key, True, port, proxy, proxy_por...
raise UnexpectedHTTPResponseError(ok_responses, response)
Based on the snippet: <|code_start|> for reg in boto.glacier.regions(): if reg.name == region_name: region = reg break self.region = region self.account_id = account_id AWSAuthConnection.__init__(self, region.endpoint, ...
return GlacierResponse(response, response_headers)
Predict the next line after this snippet: <|code_start|> return Github(**credentials) #: Server-wide authenticated GitHub state github_setup = _github_setup() def get_repo_from_url(url, gh_setup=github_setup): """ Given an URL like (ssh://)git@github.com/user/repo.git or any other url that defines th...
raise InvalidRepositoryError('{0} is not a valid GitHub URL'.format(url))
Based on the snippet: <|code_start|> :raises: ``InvalidRepositoryError`` if there was no way to deterministically find the mapping file. """ candidates = filter_repo(repo, {'name': lambda val: val.endswith('.json')}) if not candidates: raise InvalidRepositoryError('No JSON mapping file f...
raise InvalidContentFileEncoding(
Next line prediction: <|code_start|>#-*- coding: utf-8 -*- class ImportForm(forms.Form): url = forms.CharField(max_length=255) def import_cookie(self): url = self.cleaned_data['url'] <|code_end|> . Use current file imports: (from django import forms from bakery.cookies.models import Cookie) and con...
cookie = Cookie.objects.import_from_url(url)
Given the following code snippet before the placeholder: <|code_start|>#-*- coding: utf-8 -*- repos = [ 'https://github.com/audreyr/cookiecutter-pypackage', 'https://github.com/sloria/cookiecutter-flask', 'https://github.com/lucuma/cookiecutter-flask-env', 'https://github.com/marcofucci/cookiecutter-s...
Cookie.objects.import_from_url(repo)
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- class Command(BaseCommand): username = '<username>' help = 'Change the user <username> to be a superuser.' def handle(self, username, **options): traceback = options.get('traceback', False) ...
user = BakeryUser.objects.get(username=username)
Here is a snippet: <|code_start|> def get_query_set(self): return CookieQuerySet(self.model) def update_or_create(self, *args, **kwargs): return self.get_query_set().update_or_create(**kwargs) def import_from_url(self, url): """Imports or updates from ``url``""" if 'git@gith...
owner, created = BakeryUser.objects.get_or_create(**filter_args)
Based on the snippet: <|code_start|> class CookieQuerySet(QuerySet): def update_or_create(self, *args, **kwargs): obj, created = self.get_or_create(*args, **kwargs) if not created: fields = dict(kwargs.pop("defaults", {})) fields.update(kwargs) for key, value ...
repo = gh.get_repo_from_url(url)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- class Command(BaseCommand): url = '<url>' args = 'url' help = 'Add the cookie defined by the VCS URL to the database.' def handle(self, url, *args, **options): verbosity = int(options.get('verbosity', 1)) traceback = options...
Cookie.objects.import_from_url(url)
Given the following code snippet before the placeholder: <|code_start|> class LoginErrorView(TemplateView): template_name = 'error.html' login_error = LoginErrorView.as_view() class LogoutView(RedirectView): permanent = False def get_redirect_url(self, **kwargs): auth.logout(self.request) ...
user = BakeryUser.objects.get(username=kwargs['username'])
Given the following code snippet before the placeholder: <|code_start|> class TestCommands(TestCase): def test_makesuperuser(self): BakeryUser.objects.create_user('SocialUser') user = BakeryUser.objects.get(username='SocialUser') self.assertFalse(user.is_staff) self.assertFalse(...
body=read(__file__, '..', '_replay_data', 'cookiecutter-pypacker-repository'),
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- class CookieDetailView(DetailView): model = Cookie def get_object(self): owner_name = self.kwargs['owner_name'] name = self.kwargs['name'] self.object = get_object_or_404(Cookie, owner_name=owner_name, ...
form_class = ImportForm
Using the snippet: <|code_start|># -*- coding: utf-8 -*- class CookieDetailView(DetailView): model = Cookie def get_object(self): owner_name = self.kwargs['owner_name'] name = self.kwargs['name'] self.object = get_object_or_404(Cookie, owner_name=owner_name, name=name) retu...
context['has_voted'] = Vote.objects.has_voted(self.request.user.id, self.object)
Next line prediction: <|code_start|> def test_get_repo_ssh_url(self): httpretty.register_uri(httpretty.GET, 'https://api.github.com/repos/muffins-on-dope/bakery', body=read(__file__, '..', '_replay_data', 'bakery-repository'), content_type='application/json; charset=utf-8'...
self.assertRaises(InvalidRepositoryError,
Continue the code snippet: <|code_start|>class TestGithub(TestCase): @override_settings(GITHUB_CREDENTIALS=None) def test_github_credentials_none(self): self.assertRaises(ImproperlyConfigured, _github_setup) @override_settings(GITHUB_CREDENTIALS={'something': 'value'}) def test_github_credenti...
body=read(__file__, '..', '_replay_data', 'bakery-repository'),
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- class TestGithub(TestCase): @override_settings(GITHUB_CREDENTIALS=None) def test_github_credentials_none(self): <|code_end|> . Write the next line using the current file imports: import httpretty from django.core.exceptions import ImproperlyConfigu...
self.assertRaises(ImproperlyConfigured, _github_setup)
Using the snippet: <|code_start|> def test_github_credentials_none(self): self.assertRaises(ImproperlyConfigured, _github_setup) @override_settings(GITHUB_CREDENTIALS={'something': 'value'}) def test_github_credentials_invalid_key(self): self.assertRaises(ImproperlyConfigured, _github_setup)...
repo = get_repo_from_url('git@github.com:muffins-on-dope/bakery')
Using the snippet: <|code_start|># -*- coding: utf-8 -*- DUMPS_KWARGS = { 'cls': DjangoJSONEncoder, 'indent': True if settings.DEBUG else None } class JSONResponse(HttpResponse): def __init__(self, data): super(JSONResponse, self).__init__( json.dumps(data, **DUMPS_KWARGS), ...
cookies = list(Cookie.objects.values('name', 'url', 'description', 'last_change').all()[start:end])
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- def do_vote(user, cookie): assert user and cookie if not Vote.objects.has_voted(user, cookie): with transaction.commit_on_success(): vote = Vote.objects.create(cookie=cookie, user=user) candy_type = random.choi...
objects = VoteManager()
Given snippet: <|code_start|># -*- coding: utf-8 -*- class BakeryUser(AbstractBaseUser): username = models.CharField(_('Username'), max_length=50, unique=True) email = models.EmailField(_('Email'), max_length=254, unique=True) name = models.CharField(_('Name'), max_length=100, blank=True, null=True) ...
objects = BakeryUserManager()