Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the code snippet: <|code_start|> @property def decimal_separator(self): return self._decimal_separator @decimal_separator.setter def decimal_separator(self, new_decimal_separator): assert self.format in (FORMAT_DELIMITED, FORMAT_FIXED) assert new_decimal_separator in _VALID...
For example ``set_property(KEY_LINE_DELIMITER, 'lf')`` results in \
Continue the code snippet: <|code_start|> @property def decimal_separator(self): return self._decimal_separator @decimal_separator.setter def decimal_separator(self, new_decimal_separator): assert self.format in (FORMAT_DELIMITED, FORMAT_FIXED) assert new_decimal_separator in _VA...
For example ``set_property(KEY_LINE_DELIMITER, 'lf')`` results in \
Here is a snippet: <|code_start|> return self._decimal_separator @decimal_separator.setter def decimal_separator(self, new_decimal_separator): assert self.format in (FORMAT_DELIMITED, FORMAT_FIXED) assert new_decimal_separator in _VALID_DECIMAL_SEPARATORS self._decimal_separator...
:type location: str or None
Given snippet: <|code_start|> @property def decimal_separator(self): return self._decimal_separator @decimal_separator.setter def decimal_separator(self, new_decimal_separator): assert self.format in (FORMAT_DELIMITED, FORMAT_FIXED) assert new_decimal_separator in _VALID_DECIMAL_...
For example ``set_property(KEY_LINE_DELIMITER, 'lf')`` results in \
Given the following code snippet before the placeholder: <|code_start|>#: Format name for Open Document spreadsheets (ODS). FORMAT_ODS = "ods" KEY_ALLOWED_CHARACTERS = "allowed_characters" KEY_ENCODING = "encoding" KEY_ESCAPE_CHARACTER = "escape_character" KEY_FORMAT = "format" KEY_HEADER = "header" KEY_ITEM_DELIMITER...
Create a new data format.
Predict the next line after this snippet: <|code_start|> def standard_groupingForInj(abf,target=200): for i in range(abf.sweeps): abf.setSweep(i) if abf.protoSeqY[1]==target: #first step is target pA injection swhlab.ap.check_AP_group(abf,i) swhlab.plot.save(abf,tag='05-group...
swhlab.plot.save(abf,tag="check")
Given the code snippet: <|code_start|> pylab.title("average (n=%d)"%abf.sweeps) swhlab.plot.save(abf,tag='overlay') def standard_groupingForInj(abf,target=200): for i in range(abf.sweeps): abf.setSweep(i) if abf.protoSeqY[1]==target: #first step is target pA injection swhlab.ap.c...
swhlab.ap.detect(abf)
Given the code snippet: <|code_start|> # Uncomment the next two lines to enable the admin: admin.autodiscover() urlpatterns = patterns('', url(r'^$', HomeView.as_view(), name="home"), <|code_end|> , generate the next line using the imports in this file: from django.conf.urls import patterns, include, url from dja...
url(r'^openid/?', include('django_openid_auth.urls')),
Given snippet: <|code_start|> # Uncomment the next two lines to enable the admin: admin.autodiscover() urlpatterns = patterns('', url(r'^$', HomeView.as_view(), name="home"), url(r'^openid/?', include('django_openid_auth.urls')), <|code_end|> , continue by predicting the next line. Consider current file import...
url(r'^admin/?', include(admin.site.urls)),
Based on the snippet: <|code_start|> class FeedForm(ModelForm): class Meta: model = Feed fields = ['link'] widgets = { 'link': TextInput(attrs={'placeholder': 'Paste RSS address here!', 'id': 'feed-url-input'}) } def clean(self...
cleaned_data = super(FeedForm, self).clean()
Next line prediction: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
self.assertTrue(1 + 1 == 2)
Predict the next line for this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
def test_queue_create(self, client):
Next line prediction: <|code_start|># Copyright 2015 Cisco Systems. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
if not data:
Predict the next line after this snippet: <|code_start|> response = {} attempt = 0 while response == {}: url = "https://api.steampowered.com/idota2match_570/getmatchhistory/v001/?key=" + SteamAPIKey + "&account_id=" \ + str(playerID) + "&matches_requested=" + st...
time.sleep(1)
Using the snippet: <|code_start|>#message = True def requestGetMatchHistory(playerID, amount=100, heroID=None, gameModeID=None, tournamentGamesOnly=False): if message: print('[getmatchhistory] Getting matchhistory of player id: %s' %playerID) start_at_match_id = 0 results_remaining = True matches = []...
if tournamentGamesOnly:
Using the snippet: <|code_start|> if message: print('[loginreddit] updating heroDictionary success') if message: print('[loginreddit] updating proPlayerDictionary') getproplayerlist.requestGetProPlayerList() if message: print('[loginreddit] updating proPlayerDictionary success') ...
self.r = r
Predict the next line for this snippet: <|code_start|>#message = True class LoginReddit: def __init__(self): if message: print('[loginreddit] logging in') r = praw.Reddit(client_id=obot.client_id, client_secret=obot.client_secret, user_agent=obot.us...
username=obot.username,
Based on the snippet: <|code_start|>#message = True class LoginReddit: def __init__(self): if message: print('[loginreddit] logging in') <|code_end|> , predict the immediate next line with the help of imports: import praw import obot import threading from steamapi import getheroes, getproplayerlist, get...
r = praw.Reddit(client_id=obot.client_id,
Predict the next line for this snippet: <|code_start|> if message: print('[loginreddit] logging successful') if message: print('[loginreddit] updating heroDictionary') getheroes.requestGetHeroes() if message: print('[loginreddit] updating heroDictionary success') if message: p...
t.start()
Based on the snippet: <|code_start|>#message = True class LoginReddit: def __init__(self): if message: print('[loginreddit] logging in') r = praw.Reddit(client_id=obot.client_id, client_secret=obot.client_secret, user_agent=obot.user_agent, ...
password=obot.password)
Given snippet: <|code_start|>#message = True class LoginReddit: def __init__(self): if message: print('[loginreddit] logging in') r = praw.Reddit(client_id=obot.client_id, <|code_end|> , continue by predicting the next line. Consider current file imports: import praw import obot import threading...
client_secret=obot.client_secret,
Here is a snippet: <|code_start|> while response == {}: if message: print('[getmatchdetails] get match details') URL = "https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?key=" + SteamAPIKey + "&match_id=" + str(matchID) response = requests.get(URL) ...
q.put(response)
Given the code snippet: <|code_start|>message2 = False def findComments(r): subreddit = r.subreddit(SUBREDDIT) cycles = 0 if message: print('[workerfindcomments] Opening SQL Database') sql = sqlite3.connect('sql.db') <|code_end|> , generate the next line using the imports in this file: import time ...
cur = sql.cursor()
Predict the next line for this snippet: <|code_start|> if pauthor.lower() == r.user.me(): # Don't reply to yourself, robot! if message2: print('[workerfindcomments] will not reply to myself') continue if IGNOREAUTHORS != [] and...
except:
Predict the next line for this snippet: <|code_start|>message2 = False def findComments(r): subreddit = r.subreddit(SUBREDDIT) cycles = 0 if message: print('[workerfindcomments] Opening SQL Database') sql = sqlite3.connect('sql.db') cur = sql.cursor() cur.execute('CREATE TABLE IF NOT EXISTS ...
except AttributeError:
Given the following code snippet before the placeholder: <|code_start|> for post in posts: pid = post.id try: pauthor = post.author.name except AttributeError: if message2: print('[workerfindcomments] author is delete...
cur.execute('INSERT INTO oldposts VALUES(?)', [pid])
Given snippet: <|code_start|>message2 = False def findComments(r): subreddit = r.subreddit(SUBREDDIT) cycles = 0 if message: print('[workerfindcomments] Opening SQL Database') sql = sqlite3.connect('sql.db') cur = sql.cursor() cur.execute('CREATE TABLE IF NOT EXISTS oldposts(id TEXT)') ...
if message2: print('[workerfindcomments] author is deleted, don\' care about this post')
Here is a snippet: <|code_start|> if IGNOREAUTHORS != [] and any(auth2.lower() == pauthor.lower() for auth2 in IGNOREAUTHORS): # This post was made by a ignoreauthor if message2: print('[workerfindcomments] Post made by ignore author: ' + pauthor.lower()) ...
except:
Based on the snippet: <|code_start|>message2 = False def findComments(r): subreddit = r.subreddit(SUBREDDIT) cycles = 0 if message: print('[workerfindcomments] Opening SQL Database') sql = sqlite3.connect('sql.db') cur = sql.cursor() cur.execute('CREATE TABLE IF NOT EXISTS oldposts(id TEXT)'...
pauthor = post.author.name
Predict the next line for this snippet: <|code_start|> response = response.json() print(response) global dota2schema URL = response['result']['items_game_url'] with open ("items_game_url.txt", "r") as text_file: data=text_file.read() print(data) print(URL) if (data != URL): ...
data=text_file.read()
Given snippet: <|code_start|>#message = True def deleteRequestedComments(r): while True: try: print('[workerdeleterequestedcomments] checking mail with DELETION subject') unread = r.inbox.unread() <|code_end|> , continue by predicting the next line. Consider current file imports: ...
for msg in unread:
Given snippet: <|code_start|> countryFlag = '[](/%s)' %proPlayerDictionary[playerID]['country_code'] else: countryFlag = '' playerName = '%.12s' %proPlayerDictionary[playerID]['name'] #trimming name length because of some people result += '[DB](http://dotabuff.com/players/%s "Dotabu...
break
Predict the next line for this snippet: <|code_start|> keyValues = ['name', 'description', 'tournament_url', 'itemdef'] response = {} attempt = 0 while response == {}: URL = "https://api.steampowered.com/IDOTA2Match_570/GetLeagueListing/v1?key=" + SteamAPIKey response = requests.ge...
for league in response['result']['leagues']:
Here is a snippet: <|code_start|> 'hero_id': player.get('hero_id', None)} introTemplate = '####&#009;\n#####&#009; Hover to view [chat log](https://www.opendota.com/matches/{matchid}/chat)\n######&#009;\n\n' \ 'This chat log was provided by [**OpenDota**...
return (intro + chatResult + '\n---\n\n')
Based on the snippet: <|code_start|> def displayResult(matchJson, playerSummariesJson): introTemplate = '####&#009;\n#####&#009; ' \ 'Hover to view match ID: {matchid} [DB](http://www.dotabuff.com/matches/{matchid})/' \ '[OD](https://www.opendota.com/matches/{matchid})/' \ ...
if matchJson['result']['radiant_win']:
Using the snippet: <|code_start|> def displayResult(matchJson, playerSummariesJson): introTemplate = '####&#009;\n#####&#009; ' \ 'Hover to view match ID: {matchid} [DB](http://www.dotabuff.com/matches/{matchid})/' \ '[OD](https://www.opendota.com/matches/{matchid})/' \ <|co...
'[STRATZ](https://stratz.com/match/{matchid})' \
Based on the snippet: <|code_start|>#message = True heroDictionary = {} heroDictionaryDotabuff = {} def requestGetHeroes(): if message: print('[getheroes] request get heroes...') URL = "https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=" + SteamAPIKey + "&language=en_us" response = request...
heroID['localized_name'] = heroID['localized_name'].lower().replace(" ", "-").replace("'", "").replace("_", "")
Given the following code snippet before the placeholder: <|code_start|>#message = True proPlayerDictionary = {} playerOnLeaderboard = {} def requestGetProPlayerList(): keyValues = ['locked_until', 'team_id', 'sponsor', 'is_locked', 'fantasy_role', 'team_tag', 'name', 'country_code', 'is_pro', 't...
proPlayerDictionary[player['account_id']] = {}
Given snippet: <|code_start|>#message = True itemDictionary = {} def requestGetGameItems(): if message: print('[getgameitems] request get items...') URL = "https://api.steampowered.com/IEconDOTA2_570/GetGameItems/v1/?key=" + SteamAPIKey + "&language=en_us" response = requests.get(URL) response.connec...
itemID['localized_name'] = itemID['localized_name'].lower().replace(" ", "").replace("-", "").replace("_", "").replace("'", "")
Given snippet: <|code_start|>#message = True itemDictionary = {} def requestGetGameItems(): if message: print('[getgameitems] request get items...') URL = "https://api.steampowered.com/IEconDOTA2_570/GetGameItems/v1/?key=" + SteamAPIKey + "&language=en_us" <|code_end|> , continue by predicting the next line....
response = requests.get(URL)
Predict the next line after this snippet: <|code_start|> queryParameters = m.group('queryParameters') website = m.group('website') heroID = None gameModeID = None if queryParameters != None and (website == 'opendota.com' ...
else:
Given snippet: <|code_start|> heroID = n.group('heroID') reverseDBHeroDictionary = {v:k for k,v in getheroes.heroDictionaryDotabuff.items()} heroID = reverseDBHeroDictionary[heroID] except: ...
analyzedMatches.append(matchID)
Given snippet: <|code_start|> partialReply += str(match.match(matchID)) commandCounter += 1 analyzedMatches.append(matchID) else: break except: print('[workeranalyzecontent] failed to get match') replyIntro = ...
j += 1
Given the code snippet: <|code_start|> partialReply += str(odotachat.odotaChat(matchID)) else: partialReply += str(match.match(matchID)) commandCounter += 1 analyzedMatches.append(matchID) else: ...
j = 0
Given the code snippet: <|code_start|> if isPost: text = post.body.lower() else: print('this is a thread') partialReply = '' analyzedMatches = [] analyzedPlayers = [] commandCounter = 0 try: pattern = '(?P<website>yasp\.co|dotabuff\.com|opendota\.com)\/players\/(?P...
heroID = n.group('heroID')
Continue the code snippet: <|code_start|> pattern = '(?P<website>yasp\.co|dotabuff\.com|opendota\.com)\/players\/(?P<playerID>\d{1,9})((\/(?P<tab>\w+))?((?P<queryParameters>\S+))?)?' patternHero = '[?&](hero|hero_id)=(?P<heroID>[\w\-]+)' #TODO: check if gameMode filtering is working, as of 2016-1...
except:
Based on the snippet: <|code_start|> def match(matchID): t = threading.Thread(target=requestparsematch.requestParseMatch, args = (matchID,)) t.start() matchJson = getmatchdetails.getMatchDetails(matchID) <|code_end|> , predict the immediate next line with the help of imports: from steamapi import getma...
accountIDs = []
Predict the next line after this snippet: <|code_start|> def match(matchID): t = threading.Thread(target=requestparsematch.requestParseMatch, args = (matchID,)) t.start() matchJson = getmatchdetails.getMatchDetails(matchID) accountIDs = [] for player in matchJson['result']['players']: <|code_end...
accountIDs.append(player['account_id'])
Given the code snippet: <|code_start|> def match(matchID): t = threading.Thread(target=requestparsematch.requestParseMatch, args = (matchID,)) t.start() matchJson = getmatchdetails.getMatchDetails(matchID) <|code_end|> , generate the next line using the imports in this file: from steamapi import getmat...
accountIDs = []
Given snippet: <|code_start|> def match(matchID): t = threading.Thread(target=requestparsematch.requestParseMatch, args = (matchID,)) t.start() matchJson = getmatchdetails.getMatchDetails(matchID) accountIDs = [] for player in matchJson['result']['players']: accountIDs.append(player['acc...
return reply
Based on the snippet: <|code_start|> attempt = 0 while response == {}: URL = 'https://api.steampowered.com/IDOTA2MatchStats_570/GetRealtimeStats/v1?key=' + SteamAPIKey + '&server_steam_id=' + str(serverSteamID) print(URL) response = requests.get(URL) resp...
return response
Given snippet: <|code_start|> def odotaChat(matchID): requestparsematch.requestParseMatch(matchID, holdUntilParsed=True) matchJson = getodmatchdetails.getODMatchDetails(matchID) if matchJson['chat'] is not None: reply = drodotachat.displayResult(matchJson) <|code_end|> , continue by predicting the ...
return reply
Given the code snippet: <|code_start|> def odotaChat(matchID): requestparsematch.requestParseMatch(matchID, holdUntilParsed=True) matchJson = getodmatchdetails.getODMatchDetails(matchID) if matchJson['chat'] is not None: reply = drodotachat.displayResult(matchJson) <|code_end|> , generate the next ...
return reply
Based on the snippet: <|code_start|> #from steamapi.getheroes import heroDictionary, requestGetHeroes def printTableLine(name, source, divider): keyValues = ['kills', 'deaths', 'assists', 'last_hits', 'denies', 'gold_per_min', 'xp_per_min', 'hero_damage', 'tower_damage', 'hero_healing'] #'level', 'gold', 'gold...
break
Using the snippet: <|code_start|> playedModes[gameMode(i)] = len(analysis['general'][gameMode(i)]) sortedModes = sorted(playedModes.keys(), key=lambda x:playedModes[x], reverse=1) modeString = '' for mode in sortedModes: modeString = modeString + ', %s %s' %(playedModes[mode], mode) ...
resultTable = resultTable + '-------|-----|------|-------|---------|------|---|---|-----------|------------|------------|--------------------\n'
Next line prediction: <|code_start|> #from steamapi.getheroes import heroDictionary, requestGetHeroes def printTableLine(name, source, divider): keyValues = ['kills', 'deaths', 'assists', 'last_hits', 'denies', 'gold_per_min', 'xp_per_min', 'hero_damage', 'tower_damage', 'hero_healing'] #'level', 'gold', 'gold...
def printHeroLine(name, playedHeroes):
Predict the next line for this snippet: <|code_start|> def getPlayerSummaries(accountIDs): accountIDString = '' for accountID in accountIDs: accountIDString += str(76561197960265728 + accountID) + ',' <|code_end|> with the help of current file imports: import requests import time from steamapi.steamap...
accountIDString = accountIDString[:-1]
Continue the code snippet: <|code_start|> """Insert multiple blocks. If a block already exists, the data is appended. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data)""" start = 0 bulk_insert = self.bulk_insert blocks_len = len(bl...
return cursor.fetchone()
Predict the next line for this snippet: <|code_start|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <cohara87@gmail.com> """ class TimeSeries(object): """A representation of a time series with a fixed interval""" def __init__(self, points): """Initialise ...
@property
Predict the next line after this snippet: <|code_start|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <cohara87@gmail.com> """ class TimeSeries(object): """A representation of a time series with a fixed interval""" def __init__(self, points): """Initialis...
def timestamps(self):
Here is a snippet: <|code_start|> 'flags = VALUES(flags)' execute = self.cursor.execute to_buffer = self.to_buffer while start < blocks_len: rows = blocks[start:start+bulk_insert] params = [] for namespace, offset, key, data, flags in rows: ...
def get_metadata(self, key):
Here is a snippet: <|code_start|> """Clear all gauged data""" execute = self.cursor.execute execute("""TRUNCATE gauged_data; TRUNCATE gauged_keys RESTART IDENTITY; TRUNCATE gauged_writer_history; TRUNCATE gauged_cache; TRUNCATE gauged_statistics""")...
return migrations
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- class Limit_test(TestCase): def test_less(self): less = limit.__dict__['__limit_less'] assert less(42, 42) assert not less(42, 41) assert less(1e99, resource.RLIM_INFINITY) asser...
assert not less(resource.RLIM_INFINITY, 1e99)
Given the following code snippet before the placeholder: <|code_start|> languages.Language('id', vals) vals['compile'] = 'echo {nonexistent}' with pytest.raises(languages.LanguageConfigError): languages.Language('id', vals) def test_missing_run(self): vals = self.__l...
vals['compile'] = 'echo {mainfile}'
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- def config_paths_mock(): return [os.path.join(os.path.dirname(__file__), 'config1'), os.path.join(os.path.dirname(__file__), 'config2')] def test_load_basic_config(monkeypatch): monkeypatch.setattr(config, '__config_fi...
def test_load_updated_config(monkeypatch):
Next line prediction: <|code_start|> from_email='no-reply@indabom.com', subject_template_name='indabom/password-reset-subject.txt', ...
handler404 = 'indabom.views.handler404'
Given snippet: <|code_start|># the GNU Affero General Public License (AGPL) as published by the Free # Software Foundation (FSF), either version 3 of the License, or (at your # option) any later version of the AGPL published by the FSF. # # This program is distributed in the hope that it will be useful, but # WITHOUT A...
rows = table.find_elements_by_css_selector('td')
Using the snippet: <|code_start|># Software Foundation (FSF), either version 3 of the License, or (at your # option) any later version of the AGPL published by the FSF. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY ...
for identifier, title, xml in scenarios_list:
Next line prediction: <|code_start|> } # for handling duplicate entries dataUniqe = dict() # find all entries: # suche <div class="houses"> parking_houses = soup.find_all('div', class_='houses') for parking_group in parking_houses : parking_lots = parking_group.find_all('li') ...
"id": lot.id,
Given the code snippet: <|code_start|> # for handling duplicate entries dataUniqe = dict() # find all entries: # suche <div class="houses"> parking_houses = soup.find_all('div', class_='houses') for parking_group in parking_houses : parking_lots = parking_group.find_all('li') fo...
"forecast": False
Predict the next line for this snippet: <|code_start|>state_map = { "frei": "open", "geschlossen": "closed", "besetzt": "open" } geodata = GeoData(__file__) def parse_html(html): soup = BeautifulSoup(html, "html.parser") lot_table_trs = soup.select("div#parkingList table")[0].find_all("tr") ...
"coords": lot.coords,
Continue the code snippet: <|code_start|> "geschlossen": "closed", "besetzt": "open" } geodata = GeoData(__file__) def parse_html(html): soup = BeautifulSoup(html, "html.parser") lot_table_trs = soup.select("div#parkingList table")[0].find_all("tr") date_field = soup.find(id="lastRefresh").text.s...
"forecast": False
Predict the next line for this snippet: <|code_start|> self.city[1], self.city[2], self.city[3], self.city[4], json["source"], json["public"], ...
url,
Continue the code snippet: <|code_start|> private_path = os.path.join(env.APP_ROOT, "park_api", "cities", private_file) try: with open(private_path) as p: self.private_data = json.load(p) self._process_private(self.private_data) except FileNotFoundError...
json["source"],
Predict the next line after this snippet: <|code_start|> def main(): log_path = os.path.join(env.APP_ROOT, "log", env.ENV + ".log") log_handler = RotatingFileHandler(log_path, maxBytes=1000000, backupCount=1) <|code_end|> using the cu...
formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s ")
Predict the next line for this snippet: <|code_start|> def main(): log_path = os.path.join(env.APP_ROOT, "log", env.ENV + ".log") log_handler = RotatingFileHandler(log_path, maxBytes=1000000, backupCount=1) <|code_end|> with the help ...
formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s ")
Here is a snippet: <|code_start|>def parse_html(html): # BeautifulSoup is a great and easy way to parse the html and find the bits and pieces we're looking for. soup = BeautifulSoup(html, "html.parser") data = { "last_updated": '', # URL for the page where the scraper can gather the data ...
except :
Using the snippet: <|code_start|> parking_data = soup.find( 'div', class_='container-fluid') # Letzte Aktualisierung: 04.07.2019 11:03:00 last_updated = convert_date( parking_data.find('h5').text, 'Letzte Aktualisierung: %d.%m.%Y %H:%M:%S') data["last_updated"] = last_updated except :...
})
Predict the next line for this snippet: <|code_start|> # BeautifulSoup is a great and easy way to parse the html and find the bits and pieces we're looking for. soup = BeautifulSoup(html, "html.parser") data = { "last_updated": '', # URL for the page where the scraper can gather the data ...
parking_status = 'nodata'
Next line prediction: <|code_start|># from park_api.util import utc_now # This loads the geodata for this city if <city>.geojson exists in the same directory as this file. # No need to remove this if there's no geodata (yet), everything will still work. geodata = GeoData(__file__) # This function is called by the scr...
for one_entry in entries_rows[1:] :
Given snippet: <|code_start|># from park_api.util import utc_now # This loads the geodata for this city if <city>.geojson exists in the same directory as this file. # No need to remove this if there's no geodata (yet), everything will still work. geodata = GeoData(__file__) # This function is called by the scraper an...
entries_rows = entries.find_all( 'tr' )
Predict the next line after this snippet: <|code_start|> class ScraperTestCase(unittest.TestCase): def setUp(self): db.setup() @requests_mock.Mocker() <|code_end|> using the current file's imports: import os import unittest import helpers import requests import requests_mock from park_api import env, ...
def test_insert(self, mock):
Next line prediction: <|code_start|> class ScraperTestCase(unittest.TestCase): def setUp(self): db.setup() @requests_mock.Mocker() <|code_end|> . Use current file imports: (import os import unittest import helpers import requests import requests_mock from park_api import env, scraper, db) and context ...
def test_insert(self, mock):
Predict the next line for this snippet: <|code_start|> # Falls das hier jemals einer von den Menschen # hinter OpenDataZürich lesen sollte: Ihr seid so toll <3 geodata = GeoData(__file__) def parse_html(xml_data): feed = feedparser.parse(xml_data) try: last_updated = feed["entries"][0]["updated"] <|...
except KeyError:
Next line prediction: <|code_start|> def parse_html(xml_data): feed = feedparser.parse(xml_data) try: last_updated = feed["entries"][0]["updated"] except KeyError: last_updated = utc_now() data = { "lots": [], # remove trailing timezone for consensistency "last_...
"forecast": False,
Predict the next line after this snippet: <|code_start|> LOT_COUNTS_PER_CITY = {} def get_most_lots_from_known_data(city, lot_name): """ Get the total value from the highest known value in the last saved JSON. This is useful for cities that don't publish total number of spaces for a parking lot. ...
ORDER BY timestamp_downloaded DESC LIMIT 600;
Given the code snippet: <|code_start|> # This loads the geodata for this city if <city>.geojson exists in the same directory as this file. # No need to remove this if there's no geodata (yet), everything will still work. geodata = GeoData(__file__) # This function is called by the scraper and given the data of the pag...
lot_free = int(feature['properties']['obs_free'])
Predict the next line after this snippet: <|code_start|>geodata = GeoData(__file__) # This function is called by the scraper and given the data of the page specified as source in geojson above. # It's supposed to return a dictionary containing everything the current spec expects. Tests will fail if it doesn't ;) def p...
if feature['properties']['obs_state'] == "1":
Next line prediction: <|code_start|>#!/usr/bin/env python HEADERS = { "User-Agent": "ParkAPI v%s - Info: %s" % (env.SERVER_VERSION, env.SOURCE_REPOSITORY), <|code_end|> . Use current file imports: (import json import traceback import requests from bs4 import BeautifulSoup from park_api import util, env, db) ...
}
Here is a snippet: <|code_start|> soup = BeautifulSoup(r.text, "html.parser") meta_content = soup.find("meta", {"http-equiv": "content-type"}) if meta_content is not None: encoding = meta_content["content"].split("=")[-1] r.encoding = encoding return r.text def parse_html(city, html): ...
data)
Using the snippet: <|code_start|> meta_content = soup.find("meta", {"http-equiv": "content-type"}) if meta_content is not None: encoding = meta_content["content"].split("=")[-1] r.encoding = encoding return r.text def parse_html(city, html): """Use a city module to parse its html""" ...
VALUES (%(updated)s, %(downloaded)s, %(city)s, %(data)s)
Based on the snippet: <|code_start|> break with open(path, 'rb') as f: city = importlib.import_module("park_api.cities." + city) return city.parse_html(f.read().decode('utf-8', 'replace')) def get_tests(): modpath = os.path.join(env.APP_ROOT, "park_api", "cities") strip_py = lamb...
self.assertIn("state", lot)
Next line prediction: <|code_start|> def scrape_city(city): allowed_extensions = [".html", ".json", ".xml"] for extension in allowed_extensions: path = os.path.join(helpers.TEST_ROOT, "fixtures", city.lower() + extension) if os.path.isfile...
city = importlib.import_module("park_api.cities." + city)
Given the code snippet: <|code_start|> def scrape_city(city): allowed_extensions = [".html", ".json", ".xml"] for extension in allowed_extensions: path = os.path.join(helpers.TEST_ROOT, "fixtures", city.lower() + extension) if os.path.isfi...
class CityTestCase(unittest.TestCase):
Based on the snippet: <|code_start|> API_VERSION = '1.0' SERVER_VERSION = '0.3.0' SOURCE_REPOSITORY = 'https://github.com/offenesdresden/ParkAPI' APP_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..")) SERVER_CONF = None ENV = None SUPPORTED_CITIES = None DATABASE = {} DEFAULT_CONFIGURATION = { ...
return ENV == "testing"
Next line prediction: <|code_start|> API_VERSION = '1.0' SERVER_VERSION = '0.3.0' SOURCE_REPOSITORY = 'https://github.com/offenesdresden/ParkAPI' APP_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..")) <|code_end|> . Use current file imports: (import os import importlib import configparser import...
SERVER_CONF = None
Here is a snippet: <|code_start|>def parse_html(xml_data): feed = feedparser.parse(xml_data) try: last_updated = feed["entries"][0]["updated"] last_updated = datetime.strptime(last_updated[5:25], "%d %b %Y %H:%M:%S").isoformat() except KeyError: last_updated = utc_now() data ...
"coords": lot.coords,
Predict the next line after this snippet: <|code_start|> geodata = GeoData(__file__) def parse_html(xml_data): feed = feedparser.parse(xml_data) try: last_updated = feed["entries"][0]["updated"] last_updated = datetime.strptime(last_updated[5:25], "%d %b %Y %H:%M:%S").isoformat() except K...
"id": html.unescape(lot.id),
Predict the next line for this snippet: <|code_start|> def main(): backend = get_backend(env.DATABASE_URI) migrations = read_migrations(os.path.join(env.APP_ROOT, "schema/db")) <|code_end|> with the help of current file imports: import os from yoyo import read_migrations, get_backend from park_api import en...
backend.apply_migrations(migrations)
Next line prediction: <|code_start|> count = int(member.find('app:stellplaetze_gesamt').string) except AttributeError: pass free = 0 state = "nodata" situation = member.find('app:situation') if situation and situation.string != "keine Auslastungsdaten": ...
coord_member = member.find('gml:pos')