text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user_group_list(self, steamID, format=None):
"""Request a list of groups a user is subscribed to. steamID: User ID format: Return format. None defaults to json. (json, xml, vdf) """ |
parameters = {'steamid' : steamID}
if format is not None:
parameters['format'] = format
url = self.create_request_url(self.interface, 'GetUserGroupList', 1,
parameters)
data = self.retrieve_request(url)
return self.return_data(data, format=format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_vanity_url(self, vanityURL, url_type=1, format=None):
"""Request the steam id associated with a vanity url. vanityURL: The users vanity URL url_type: The type of vanity URL. 1 (default):
Individual profile, 2: Group, 3: Official game group format: Return format. None defaults to json. (json, xml, vdf) """ |
parameters = {'vanityurl' : vanityURL, "url_type" : url_type}
if format is not None:
parameters['format'] = format
url = self.create_request_url(self.interface, 'ResolveVanityUrl', 1,
parameters)
data = self.retrieve_request(url)
return self.return_data(data, format=format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_global_achievement_percentages_for_app(self, gameID, format=None):
"""Request statistics showing global achievements that have been unlocked. gameID: The id of the game. format: Return format. None defaults to json. (json, xml, vdf) """ |
parameters = {'gameid' : gameID}
if format is not None:
parameters['format'] = format
url = self.create_request_url(self.interface,
'GetGlobalAchievementPercentagesForApp', 2, parameters)
data = self.retrieve_request(url)
return self.return_data(data, format=format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_global_stats_for_game(self, appID, count, names, startdate, enddate, format=None):
"""Request global stats for a give game. appID: The app ID count: Number of stats to get. names: A list of names of stats to get. startdate: The start time to gather stats. Unix timestamp enddate: The end time to gather stats. Unix timestamp format: Return format. None defaults to json. (json, xml, vdf) """ |
parameters = {
'appid' : appID,
'count' : count,
'startdate' : startdate,
'enddate' : enddate
}
count = 0
for name in names:
param = "name[" + str(count) + "]"
parameters[param] = name
count += 1
if format is not None:
parameters['format'] = format
url = self.create_request_url(self.interface, 'GetGlobalStatsForGame', 1,
parameters)
data = self.retrieve_request(url)
return self.return_data(data, format=format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_number_of_current_players(self, appID, format=None):
"""Request the current number of players for a given app. appID: The app ID format: Return format. None defaults to json. (json, xml, vdf) """ |
parameters = {'appid' : appID}
if format is not None:
parameters['format'] = format
url = self.create_request_url(self.interface,
'GetNumberOfCurrentPlayers', 1, parameters)
data = self.retrieve_request(url)
return self.return_data(data, format=format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_player_achievements(self, steamID, appID, language=None, format=None):
"""Request the achievements for a given app and steam id. steamID: Users steam ID appID: The app id language: The language to return the results in. None uses default. format: Return format. None defaults to json. (json, xml, vdf) """ |
parameters = {'steamid' : steamID, 'appid' : appID}
if format is not None:
parameters['format'] = format
if language is not None:
parameters['l'] = language
else:
parameters['l'] = self.language
url = self.create_request_url(self.interface, 'GetPlayerAchievements', 1,
parameters)
data = self.retrieve_request(url)
return self.return_data(data, format=format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_schema_for_game(self, appID, language=None, format=None):
"""Request the available achievements and stats for a game. appID: The app id language: The language to return the results in. None uses default. format: Return format. None defaults to json. (json, xml, vdf) """ |
parameters = {'appid' : appID}
if format is not None:
parameters['format'] = format
if language is not None:
parameters['l'] = language
else:
parameters['l'] = self.language
url = self.create_request_url(self.interface, 'GetSchemaForGame', 2,
parameters)
data = self.retrieve_request(url)
return self.return_data(data, format=format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user_stats_for_game(self, steamID, appID, format=None):
"""Request the user stats for a given game. steamID: The users ID appID: The app id format: Return format. None defaults to json. (json, xml, vdf) """ |
parameters = {'steamid' : steamID, 'appid' : appID}
if format is not None:
parameters['format'] = format
url = self.create_request_url(self.interface, 'GetUserStatsForGame', 2,
parameters)
data = self.retrieve_request(url)
return self.return_data(data, format=format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_recently_played_games(self, steamID, count=0, format=None):
"""Request a list of recently played games by a given steam id. steamID: The users ID count: Number of games to return. (0 is all recent games.) format: Return format. None defaults to json. (json, xml, vdf) """ |
parameters = {'steamid' : steamID, 'count' : count}
if format is not None:
parameters['format'] = format
url = self.create_request_url(self.interface, 'GetRecentlyPlayedGames', 1,
parameters)
data = self.retrieve_request(url)
return self.return_data(data, format=format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_owned_games(self, steamID, include_appinfo=1, include_played_free_games=0, appids_filter=None, format=None):
"""Request a list of games owned by a given steam id. steamID: The users id include_appinfo: boolean. include_played_free_games: boolean. appids_filter: a json encoded list of app ids. format: Return format. None defaults to json. (json, xml, vdf) """ |
parameters = {
'steamid' : steamID,
'include_appinfo' : include_appinfo,
'include_played_free_games' : include_played_free_games
}
if format is not None:
parameters['format'] = format
if appids_filter is not None:
parameters['appids_filter'] = appids_filter
url = self.create_request_url(self.interface, 'GetOwnedGames', 1,
parameters)
data = self.retrieve_request(url)
return self.return_data(data, format=format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_community_badge_progress(self, steamID, badgeID, format=None):
"""Gets all the quests needed to get the specified badge, and which are completed. steamID: The users ID badgeID: The badge we're asking about format: Return format. None defaults to json. (json, xml, vdf) """ |
parameters = {'steamid' : steamID, 'badgeid' : badgeID}
if format is not None:
parameters['format'] = format
url = self.create_request_url(self.interface, 'GetCommunityBadgeProgress', 1,
parameters)
data = self.retrieve_request(url)
return self.return_data(data, format=format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_playing_shared_game(self, steamID, appid_playing, format=None):
"""Returns valid lender SteamID if game currently played is borrowed. steamID: The users ID appid_playing: The game player is currently playing format: Return format. None defaults to json. (json, xml, vdf) """ |
parameters = {'steamid' : steamID, 'appid_playing' : appid_playing}
if format is not None:
parameters['format'] = format
url = self.create_request_url(self.interface, 'IsPlayingSharedGame', 1,
parameters)
data = self.retrieve_request(url)
return self.return_data(data, format=format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_server_info(self, format=None):
"""Request the Steam Web API status and time. format: Return format. None defaults to json. (json, xml, vdf) """ |
parameters = {}
if format is not None:
parameters['format'] = format
url = self.create_request_url(self.interface, 'GetServerInfo', 1,
parameters)
data = self.retrieve_request(url)
return self.return_data(data, format=format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_request_url(self, profile_type, steamID):
"""Create the url to submit to the Steam Community XML feed.""" |
regex = re.compile('^\d{17,}$')
if regex.match(steamID):
if profile_type == self.USER:
url = "http://steamcommunity.com/profiles/%s/?xml=1" % (steamID)
if profile_type == self.GROUP:
url = "http://steamcommunity.com/gid/%s/memberslistxml/?xml=1" % (steamID)
else:
if profile_type == self.USER:
url = "http://steamcommunity.com/id/%s/?xml=1" % (steamID)
if profile_type == self.GROUP:
url = "http://steamcommunity.com/groups/%s/memberslistxml/?xml=1" % (steamID)
return url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user_info(self, steamID):
"""Request the Steam Community XML feed for a specific user.""" |
url = self.create_request_url(self.USER, steamID)
data = self.retrieve_request(url)
return self.return_data(data, format='xml') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_group_info(self, steamID):
"""Request the Steam Community XML feed for a specific group.""" |
url = self.create_request_url(self.GROUP, steamID)
data = self.retrieve_request(url)
return self.return_data(data, format='xml') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export(cls, folder, particles, datetimes):
""" Export trackline data to GeoJSON file """ |
normalized_locations = [particle.normalized_locations(datetimes) for particle in particles]
track_coords = []
for x in xrange(0, len(datetimes)):
points = MultiPoint([loc[x].point.coords[0] for loc in normalized_locations])
track_coords.append(points.centroid.coords[0])
ls = LineString(track_coords)
if not os.path.exists(folder):
os.makedirs(folder)
filepath = os.path.join(folder, "trackline.geojson")
f = open(filepath, "wb")
f.write(json.dumps(mapping(ls)))
f.close()
return filepath |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export(cls, folder, particles, datetimes):
""" Export particle and datetime data to Pickled objects. This can be used to debug or to generate different output in the future. """ |
if not os.path.exists(folder):
os.makedirs(folder)
particle_path = os.path.join(folder, 'particles.pickle')
f = open(particle_path, "wb")
pickle.dump(particles, f)
f.close()
datetimes_path = os.path.join(folder, 'datetimes.pickle')
f = open(datetimes_path, "wb")
pickle.dump(datetimes, f)
f.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_settings_class(setting_name):
""" Return the class pointed to be an app setting variable. """ |
config_value = getattr(settings, setting_name)
if config_value is None:
raise ImproperlyConfigured("Required setting not found: {0}".format(setting_name))
return import_class(config_value, setting_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_class(import_path, setting_name=None):
""" Import a class by name. """ |
mod_name, class_name = import_path.rsplit('.', 1)
# import module
mod = import_module_or_none(mod_name)
if mod is not None:
# Loaded module, get attribute
try:
return getattr(mod, class_name)
except AttributeError:
pass
# For ImportError and AttributeError, raise the same exception.
if setting_name:
raise ImproperlyConfigured("{0} does not point to an existing class: {1}".format(setting_name, import_path))
else:
raise ImproperlyConfigured("Class not found: {0}".format(import_path)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_module_or_none(module_label):
""" Imports the module with the given name. Returns None if the module doesn't exist, but it does propagates import errors in deeper modules. """ |
try:
# On Python 3, importlib has much more functionality compared to Python 2.
return importlib.import_module(module_label)
except ImportError:
# Based on code from django-oscar:
# There are 2 reasons why there could be an ImportError:
#
# 1. Module does not exist. In that case, we ignore the import and return None
# 2. Module exists but another ImportError occurred when trying to import the module.
# In that case, it is important to propagate the error.
#
# ImportError does not provide easy way to distinguish those two cases.
# Fortunately, the traceback of the ImportError starts at __import__
# statement. If the traceback has more than one frame, it means that
# application was found and ImportError originates within the local app
__, __, exc_traceback = sys.exc_info()
frames = traceback.extract_tb(exc_traceback)
frames = [f for f in frames
if f[0] != "<frozen importlib._bootstrap>" and # Python 3.6
f[0] != IMPORT_PATH_IMPORTLIB and
not f[0].endswith(IMPORT_PATH_GEVENT) and
not IMPORT_PATH_PYDEV in f[0]]
if len(frames) > 1:
raise
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_logger(name):
"""Gets a logger Arguments: name - the name you wish to log as Returns: A logger! """ |
logger = logging.getLogger(name)
logger.addHandler(logging.NullHandler())
return logger |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_suspension(user_twitter_id_list):
""" Looks up a list of user ids and checks whether they are currently suspended. Input: - user_twitter_id_list: A python list of Twitter user ids in integer format to be looked-up. Outputs: - suspended_user_twitter_id_list: A python list of suspended Twitter user ids in integer format. - non_suspended_user_twitter_id_list: A python list of non suspended Twitter user ids in integer format. - unknown_status_user_twitter_id_list: A python list of unknown status Twitter user ids in integer format. """ |
####################################################################################################################
# Log into my application.
####################################################################################################################
twitter = login()
####################################################################################################################
# Lookup users
####################################################################################################################
# Initialize look-up lists
suspended_user_twitter_id_list = list()
non_suspended_user_twitter_id_list = list()
unknown_status_user_twitter_id_list = list()
append_suspended_twitter_user = suspended_user_twitter_id_list.append
append_non_suspended_twitter_user = non_suspended_user_twitter_id_list.append
extend_unknown_status_twitter_user = unknown_status_user_twitter_id_list.extend
# Split twitter user id list into sub-lists of length 100 (This is the Twitter API function limit).
user_lookup_counter = 0
user_lookup_time_window_start = time.perf_counter()
for hundred_length_sub_list in chunks(list(user_twitter_id_list), 100):
# Make safe twitter request.
try:
api_result, user_lookup_counter, user_lookup_time_window_start\
= safe_twitter_request_handler(twitter_api_func=twitter.lookup_user,
call_rate_limit=60,
call_counter=user_lookup_counter,
time_window_start=user_lookup_time_window_start,
max_retries=10,
wait_period=2,
parameters=hundred_length_sub_list)
# If the call is succesful, turn hundred sub-list to a set for faster search.
hundred_length_sub_list = set(hundred_length_sub_list)
# Check who is suspended and who is not.
for hydrated_user_object in api_result:
hydrated_twitter_user_id = hydrated_user_object["id"]
if hydrated_twitter_user_id in hundred_length_sub_list:
append_non_suspended_twitter_user(hydrated_twitter_user_id)
else:
append_suspended_twitter_user(hydrated_twitter_user_id)
except twython.TwythonError:
# If the call is unsuccesful, we do not know about the status of the users.
extend_unknown_status_twitter_user(hundred_length_sub_list)
except URLError:
# If the call is unsuccesful, we do not know about the status of the users.
extend_unknown_status_twitter_user(hundred_length_sub_list)
except BadStatusLine:
# If the call is unsuccesful, we do not know about the status of the users.
extend_unknown_status_twitter_user(hundred_length_sub_list)
return suspended_user_twitter_id_list, non_suspended_user_twitter_id_list, unknown_status_user_twitter_id_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def handler(self):
'''Handle loop, get and process messages'''
self.ws = await websockets.connect(self.url, ssl=self.ssl)
while self.ws:
message = await self.ws.recv()
for handle in self.on_message:
if asyncio.iscoroutinefunction(handle):
await handle(self, message)
else:
handle(self, message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_url(self, path='/', websocket=False, remote=True,
attach_api_key=True, userId=None, pass_uid=False, **query):
'''construct a url for an emby request
Parameters
----------
path : str
uri path(excluding domain and port) of get request for emby
websocket : bool, optional
if true, then `ws(s)` are used instead of `http(s)`
remote : bool, optional
if true, remote-address is used (default True)
attach_api_key : bool, optional
if true, apikey is added to the query (default True)
userId : str, optional
uid to use, if none, default is used
pass_uid : bool, optional
if true, uid is added to the query (default False)
query : karg dict
additional parameters to set (part of url after the `?`)
Also See
--------
get :
getJson :
post :
delete :
Returns
-------
full url
'''
userId = userId or self.userid
if attach_api_key and self.api_key:
query.update({'api_key':self.api_key, 'deviceId': self.device_id})
if pass_uid:
query['userId'] = userId
if remote:
url = self.urlremote or self.url
else:
url = self.url
if websocket:
scheme = {'http':'ws', 'https':'wss'}[url.scheme]
else:
scheme = url.scheme
netloc = url.netloc + '/emby'
url = urlunparse((scheme, netloc, path, '', '{params}', '')).format(
UserId = userId,
ApiKey = self.api_key,
DeviceId = self.device_id,
params = urlencode(query)
)
return url[:-1] if url[-1] == '?' else url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def get(self, path, **query):
'''return a get request
Parameters
----------
path : str
same as get_url
query : kargs dict
additional info to pass to get_url
See Also
--------
get_url :
getJson :
Returns
-------
requests.models.Response
the response that was given
'''
url = self.get_url(path, **query)
for i in range(self.tries+1):
try:
resp = await self.session.get(url, timeout=self.timeout)
if await self._process_resp(resp):
return resp
else:
continue
except aiohttp.ClientConnectionError:
if i >= self.tries:
raise aiohttp.ClientConnectionError(
'Emby server is probably down'
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def post(self, path, data={}, send_raw=False, **params):
'''sends post request
Parameters
----------
path : str
same as get_url
query : kargs dict
additional info to pass to get_url
See Also
--------
get_url :
Returns
-------
requests.models.Response
the response that was given
'''
url = self.get_url(path, **params)
jstr = json.dumps(data)
for i in range(self.tries+1):
try:
if send_raw:
resp = await self.session.post(url, data=data, timeout=self.timeout)
else:
resp = await self.session.post(url, data=jstr, timeout=self.timeout)
if await self._process_resp(resp):
return resp
else:
continue
except aiohttp.ClientConnectionError:
if i >= self.tries:
raise aiohttp.ClientConnectionError(
'Emby server is probably down'
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def getJson(self, path, **query):
'''wrapper for get, parses response as json
Parameters
----------
path : str
same as get_url
query : kargs dict
additional info to pass to get_url
See Also
--------
get_url :
get :
Returns
-------
dict
the response content as a dict
'''
for i in range(self.tries+1):
try:
return await (await self.get(path, **query)).json()
except:
if i >= self.tries:
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def standardize():
"""
return variant standarize function
""" |
def f(G, bim):
G_out = standardize_snps(G)
return G_out, bim
return f |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def impute(imputer):
"""
return impute function
""" |
def f(G, bim):
return imputer.fit_transform(G), bim
return f |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compose(func_list):
"""
composion of preprocessing functions
""" |
def f(G, bim):
for func in func_list:
G, bim = func(G, bim)
return G, bim
return f |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def asdict(self):
""" Copy the data back out of here and into a dict. Then return it. Some libraries may check specifically for dict objects, such as the json library; so, this makes it convenient to get the data back out. True True """ |
items = {}
for name in self._items:
value = self._items[name]
if isinstance(value, DictionaryObject):
items[name] = value.asdict()
else:
items[name] = value
return items |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_joke():
"""Return a jokes from one of the random services.""" |
joke = None
while joke is None:
service_num = randint(1, NUM_SERVICES)
joke = load_joke(service_num)
return joke |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_joke(service_num=1):
"""Pulls the joke from the service based on the argument. It is expected that all services used will return a string when successful or None otherwise. """ |
result = {
1 : ronswanson.get_joke(),
2 : chucknorris.get_joke(),
3 : catfacts.get_joke(),
4 : dadjokes.get_joke(),
}.get(service_num)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_14c(fl):
"""Create CalibCurve instance from Bacon curve file """ |
indata = pd.read_csv(fl, index_col=None, skiprows=11, header=None,
names=['calbp', 'c14age', 'error', 'delta14c', 'sigma'])
outcurve = CalibCurve(calbp=indata['calbp'],
c14age=indata['c14age'],
error=indata['error'],
delta14c=indata['delta14c'],
sigma=indata['sigma'])
return outcurve |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_chron(fl):
"""Create ChronRecord instance from Bacon file """ |
indata = pd.read_csv(fl, sep=r'\s*\,\s*', index_col=None, engine='python')
outcore = ChronRecord(age=indata['age'],
error=indata['error'],
depth=indata['depth'],
labid=indata['labID'])
return outcore |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_proxy(fl):
"""Read a file to create a proxy record instance """ |
outcore = ProxyRecord(data=pd.read_csv(fl, sep=r'\s*\,\s*', index_col=None, engine='python'))
return outcore |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_pandas(self):
"""Convert record to pandas.DataFrame""" |
agedepthdf = pd.DataFrame(self.age, index=self.data.depth)
agedepthdf.columns = list(range(self.n_members()))
out = (agedepthdf.join(self.data.set_index('depth'))
.reset_index()
.melt(id_vars=self.data.columns.values, var_name='mciter', value_name='age'))
out['mciter'] = pd.to_numeric(out.loc[:, 'mciter'])
if self.n_members() == 1:
out = out.drop('mciter', axis=1)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def negotiate_header(url):
""" Return the "Authorization" HTTP header value to use for this URL. """ |
hostname = urlparse(url).hostname
_, krb_context = kerberos.authGSSClientInit('HTTP@%s' % hostname)
# authGSSClientStep goes over the network to the KDC (ie blocking).
yield threads.deferToThread(kerberos.authGSSClientStep,
krb_context, '')
negotiate_details = kerberos.authGSSClientResponse(krb_context)
defer.returnValue('Negotiate ' + negotiate_details) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_specification(self, specification):
""" Read the specification provided. It can either be a url or a file location. """ |
result = six.moves.urllib.parse.urlparse(specification)
# If the specification has an http or an https scheme we can
# retrieve it via an HTTP get request, else we try to open it
# as a file.
if result.scheme in ['http', 'https']:
response = requests.get(specification)
spec_json = response.json()
else:
with open(specification, 'r') as spec_file:
spec_json = json.load(spec_file)
return spec_json |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_headers(self, resource):
""" Get CSV file headers from the provided resource. """ |
# If the resource is a file we just open it up with the csv
# reader (after being sure we're reading from the beginning
# of the file
if type(resource) == file:
resource.seek(0)
reader = csv.reader(resource)
# If the resource is a basestring it is either a url or a file
# location, so similarly to the specification mechanism we either
# access it with an HTTP get request or by opening the file.
elif isinstance(resource, basestring):
result = six.moves.urllib.parse.urlparse(resource)
if result.scheme in ['http', 'https']:
with closing(requests.get(resource, stream=True)) as response:
# Headers are alway the first row of a CSV file
# so it's enought to just get the first line and
# hopefully save bandwidth
header_row = response.iter_lines().next()
else:
# It may seem weird to open up a csv file, read its header row
# and then StringIO that into a new csv reader but this file
# we want to close and we want the same interface for all
with open(resource) as resource_file:
reader = csv.reader(resource_file)
header_row = reader.next()
reader = csv.reader(cStringIO.StringIO(header_row))
else:
raise IOError('Resource type not supported')
return reader.next() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schema(self):
""" The generated budget data package schema for this resource. If the resource has any fields that do not conform to the provided specification this will raise a NotABudgetDataPackageException. """ |
if self.headers is None:
raise exceptions.NoResourceLoadedException(
'Resource must be loaded to find schema')
try:
fields = self.specification.get('fields', {})
parsed = {
'primaryKey': 'id',
'fields': [{
'name': header,
'type': fields[header]['type'],
'description': fields[header]['description']
} for header in self.headers]
}
except KeyError:
raise exceptions.NotABudgetDataPackageException(
'Includes other fields than the Budget Data Package fields')
return parsed |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_time(self, idx=0):
"""Return the time of the tif data since the epoch The time is stored in the "61238" tag. """ |
timestr = SingleTifPhasics._get_meta_data(path=self.path,
section="acquisition info",
name="date & heure")
if timestr is not None:
timestr = timestr.split(".")
# '2016-04-29_17h31m35s.00827'
structtime = time.strptime(timestr[0],
"%Y-%m-%d_%Hh%Mm%Ss")
fracsec = float(timestr[1]) * 1e-5
# use calendar, because we need UTC
thetime = calendar.timegm(structtime) + fracsec
else:
thetime = np.nan
return thetime |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate_and_store_mold_id_map(self, template_map, molds):
""" Not a pure generator expression as this has the side effect of storing the resulting id and map it into a local dict. Produces a list of all valid mold_ids from the input template_keys. Internal function; NOT meant to be used outside of this class. """ |
name = self.req_tmpl_name
for key in sorted(template_map.keys(), reverse=True):
if len(key.split('/')) == 3 and key.endswith(name):
mold_id = key[len(self.text_prefix):-len(name) - 1]
molds[mold_id] = template_map[key][:-len(name) - 1]
yield mold_id |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mold_id_to_path(self, mold_id, default=_marker):
""" Lookup the filesystem path of a mold identifier. """ |
def handle_default(debug_msg=None):
if debug_msg:
logger.debug('mold_id_to_path:' + debug_msg, mold_id)
if default is _marker:
raise KeyError(
'Failed to lookup mold_id %s to a path' % mold_id)
return default
result = self.molds.get(mold_id)
if result:
return result
if not self.tracked_entry_points:
return handle_default()
try:
prefix, mold_basename = mold_id.split('/')
except ValueError:
return handle_default(
'mold_id %s not found and not in standard format')
entry_point = self.tracked_entry_points.get(prefix)
if entry_point is None:
return handle_default()
return join(self._entry_point_to_path(entry_point), mold_basename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lookup_path(self, mold_id_path, default=_marker):
""" For the given mold_id_path, look up the mold_id and translate that path to its filesystem equivalent. """ |
fragments = mold_id_path.split('/')
mold_id = '/'.join(fragments[:2])
try:
subpath = []
for piece in fragments[2:]:
if (sep in piece or (altsep and altsep in piece) or
piece == pardir):
raise KeyError
elif piece and piece != '.':
subpath.append(piece)
path = self.mold_id_to_path(mold_id)
except KeyError:
if default is _marker:
raise
return default
return join(path, *subpath) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify_path(self, mold_id_path):
""" Lookup and verify path. """ |
try:
path = self.lookup_path(mold_id_path)
if not exists(path):
raise KeyError
except KeyError:
raise_os_error(ENOENT)
return path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_skippers(configure, file_name=None):
""" Returns the skippers of configuration. :param configure: The configuration of HaTeMiLe. :type configure: hatemile.util.configure.Configure :param file_name: The file path of skippers configuration. :type file_name: str :return: The skippers of configuration. :rtype: list(dict(str, str)) """ |
skippers = []
if file_name is None:
file_name = os.path.join(os.path.dirname(os.path.dirname(
os.path.dirname(os.path.realpath(__file__))
)), 'skippers.xml')
xmldoc = minidom.parse(file_name)
skippers_xml = xmldoc.getElementsByTagName(
'skippers'
)[0].getElementsByTagName('skipper')
for skipper_xml in skippers_xml:
skippers.append({
'selector': skipper_xml.attributes['selector'].value,
'description': configure.get_parameter(
skipper_xml.attributes['description'].value
),
'shortcut': skipper_xml.attributes['shortcut'].value
})
return skippers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate_list_skippers(self):
""" Generate the list of skippers of page. :return: The list of skippers of page. :rtype: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
container = self.parser.find(
'#'
+ AccessibleNavigationImplementation.ID_CONTAINER_SKIPPERS
).first_result()
html_list = None
if container is None:
local = self.parser.find('body').first_result()
if local is not None:
container = self.parser.create_element('div')
container.set_attribute(
'id',
AccessibleNavigationImplementation.ID_CONTAINER_SKIPPERS
)
local.prepend_element(container)
if container is not None:
html_list = self.parser.find(container).find_children(
'ul'
).first_result()
if html_list is None:
html_list = self.parser.create_element('ul')
container.append_element(html_list)
self.list_skippers_added = True
return html_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate_list_heading(self):
""" Generate the list of heading links of page. """ |
local = self.parser.find('body').first_result()
id_container_heading_before = (
AccessibleNavigationImplementation.ID_CONTAINER_HEADING_BEFORE
)
id_container_heading_after = (
AccessibleNavigationImplementation.ID_CONTAINER_HEADING_AFTER
)
if local is not None:
container_before = self.parser.find(
'#'
+ id_container_heading_before
).first_result()
if (container_before is None) and (self.elements_heading_before):
container_before = self.parser.create_element('div')
container_before.set_attribute(
'id',
id_container_heading_before
)
text_container_before = self.parser.create_element('span')
text_container_before.set_attribute(
'class',
AccessibleNavigationImplementation.CLASS_TEXT_HEADING
)
text_container_before.append_text(self.elements_heading_before)
container_before.append_element(text_container_before)
local.prepend_element(container_before)
if container_before is not None:
self.list_heading_before = self.parser.find(
container_before
).find_children('ol').first_result()
if self.list_heading_before is None:
self.list_heading_before = self.parser.create_element('ol')
container_before.append_element(self.list_heading_before)
container_after = self.parser.find(
'#'
+ id_container_heading_after
).first_result()
if (container_after is None) and (self.elements_heading_after):
container_after = self.parser.create_element('div')
container_after.set_attribute('id', id_container_heading_after)
text_container_after = self.parser.create_element('span')
text_container_after.set_attribute(
'class',
AccessibleNavigationImplementation.CLASS_TEXT_HEADING
)
text_container_after.append_text(self.elements_heading_after)
container_after.append_element(text_container_after)
local.append_element(container_after)
if container_after is not None:
self.list_heading_after = self.parser.find(
container_after
).find_children('ol').first_result()
if self.list_heading_after is None:
self.list_heading_after = self.parser.create_element('ol')
container_after.append_element(self.list_heading_after)
self.list_heading_added = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_heading_level(self, element):
""" Returns the level of heading. :param element: The heading. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :return: The level of heading. :rtype: int """ |
# pylint: disable=no-self-use
tag = element.get_tag_name()
if tag == 'H1':
return 1
elif tag == 'H2':
return 2
elif tag == 'H3':
return 3
elif tag == 'H4':
return 4
elif tag == 'H5':
return 5
elif tag == 'H6':
return 6
return -1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_valid_heading(self):
""" Check that the headings of page are sintatic correct. :return: True if the headings of page are sintatic correct or False if not. :rtype: bool """ |
elements = self.parser.find('h1,h2,h3,h4,h5,h6').list_results()
last_level = 0
count_main_heading = 0
self.validate_heading = True
for element in elements:
level = self._get_heading_level(element)
if level == 1:
if count_main_heading == 1:
return False
else:
count_main_heading = 1
if (level - last_level) > 1:
return False
last_level = level
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate_anchor_for(self, element, data_attribute, anchor_class):
""" Generate an anchor for the element. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :param data_attribute: The name of attribute that links the element with the anchor. :type data_attribute: str :param anchor_class: The HTML class of anchor. :type anchor_class: str :return: The anchor. :rtype: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
self.id_generator.generate_id(element)
if self.parser.find(
'[' + data_attribute + '="' + element.get_attribute('id') + '"]'
).first_result() is None:
if element.get_tag_name() == 'A':
anchor = element
else:
anchor = self.parser.create_element('a')
self.id_generator.generate_id(anchor)
anchor.set_attribute('class', anchor_class)
element.insert_before(anchor)
if not anchor.has_attribute('name'):
anchor.set_attribute('name', anchor.get_attribute('id'))
anchor.set_attribute(data_attribute, element.get_attribute('id'))
return anchor
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _free_shortcut(self, shortcut):
""" Replace the shortcut of elements, that has the shortcut passed. :param shortcut: The shortcut. :type shortcut: str """ |
alpha_numbers = '1234567890abcdefghijklmnopqrstuvwxyz'
elements = self.parser.find('[accesskey]').list_results()
found = False
for element in elements:
shortcuts = element.get_attribute('accesskey').lower()
if CommonFunctions.in_list(shortcuts, shortcut):
for key in alpha_numbers:
found = True
for element_with_shortcuts in elements:
shortcuts = element_with_shortcuts.get_attribute(
'accesskey'
).lower()
if CommonFunctions.in_list(shortcuts, key):
found = False
break
if found:
element.set_attribute('accesskey', key)
break
if found:
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _add(self, name, *args, **kwargs):
'''Appends a command to the scrims list of commands. You should not
need to use this.'''
self.commands.append(Command(name, args, kwargs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def write(self):
'''Write this Scrims commands to its path'''
if self.path is None:
raise Exception('Scrim.path is None')
dirname = os.path.dirname(os.path.abspath(self.path))
if not os.path.exists(dirname):
try:
os.makedirs(dirname)
except:
raise OSError('Failed to create root for scrim output.')
with open(self.path, 'w') as f:
f.write(self.to_string()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_orphans(self, instance, **kwargs):
""" When an item is deleted, first delete any Activity object that has been created on its behalf. """ |
from activity_monitor.models import Activity
try:
instance_content_type = ContentType.objects.get_for_model(instance)
timeline_item = Activity.objects.get(content_type=instance_content_type, object_id=instance.pk)
timeline_item.delete()
except Activity.DoesNotExist:
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def follow_model(self, model):
""" Follow a particular model class, updating associated Activity objects automatically. """ |
if model:
self.models_by_name[model.__name__.lower()] = model
signals.post_save.connect(create_or_update, sender=model)
signals.post_delete.connect(self.remove_orphans, sender=model) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_for_model(self, model):
""" Return a QuerySet of only items of a certain type. """ |
return self.filter(content_type=ContentType.objects.get_for_model(model)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_last_update_of_model(self, model, **kwargs):
""" Return the last time a given model's items were updated. Returns the epoch if the items were never updated. """ |
qs = self.get_for_model(model)
if kwargs:
qs = qs.filter(**kwargs)
try:
return qs.order_by('-timestamp')[0].timestamp
except IndexError:
return datetime.datetime.fromtimestamp(0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def for_each(self, operation, limit=0, verbose=False):
""" Applies the given Operation to each item in the stream. The Operation executes on the items in the stream in the order that they appear in the stream. If the limit is supplied, then processing of the stream will stop after that many items have been processed. """ |
if limit != 0:
count = 0
while self.has_next():
operation.perform(self.next())
count += 1
if verbose:
print count
if count >= limit:
break
else:
while self.has_next():
operation.perform(self.next()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iregex(value, iregex):
"""Returns true if the value case insentively matches agains the regex. """ |
return re.match(iregex, value, flags=re.I) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_subdirectories(directory):
""" Get subdirectories without pycache """ |
return [name for name in os.listdir(directory)
if name != '__pycache__'
if os.path.isdir(os.path.join(directory, name))] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_python_path() -> str:
""" Accurately get python executable """ |
python_bin = None
if os.name == 'nt':
python_root = os.path.abspath(
os.path.join(os.__file__, os.pardir, os.pardir))
python_bin = os.path.join(python_root, 'python.exe')
else:
python_root = os.path.abspath(
os.path.join(os.__file__, os.pardir, os.pardir, os.pardir))
python = os.__file__.rsplit('/')[-2]
python_bin = os.path.join(python_root, 'bin', python)
return python_bin |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __collect_fields(self):
""" Use field values from config.json and collect from request """ |
form = FormData()
form.add_field(self.__username_field, required=True,
error=self.__username_error)
form.add_field(self.__password_field, required=True,
error=self.__password_error)
form.parse()
self.username = form.values[self.__username_field]
self.password = form.values[self.__password_field]
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_board(board_id, board_options, hwpack='arduino', replace_existing=False):
"""install board in boards.txt. :param board_id: string identifier :param board_options: dict like :param replace_existing: bool :rtype: None """ |
doaction = 0
if board_id in boards(hwpack).keys():
log.debug('board already exists: %s', board_id)
if replace_existing:
log.debug('remove board: %s' , board_id)
remove_board(board_id)
doaction = 1
else:
doaction = 1
if doaction:
lines = bunch2properties(board_id, board_options)
boards_txt().write_lines([''] + lines, append=1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cycles(cls, **kwargs):
""" Classmethod for convienence in returning both the sunrise and sunset based on a location and date. Always calculates the sunrise and sunset on the given date, no matter the time passed into the function in the datetime object. Parameters: loc = Location4D (object) OR point = Shapely point (object) time = datetime in UTC (object) OR lat = latitude (float) lon = longitude (float) time = datetime in UTC (object) Returns: { 'sunrise': datetime in UTC, 'sunset': datetime in UTC } Sources: http://williams.best.vwh.net/sunrise_sunset_example.htm """ |
if "loc" not in kwargs:
if "point" not in kwargs:
if "lat" not in kwargs or "lon" not in kwargs:
raise ValueError("You must supply some form of lat/lon coordinates")
else:
lat = kwargs.get("lat")
lon = kwargs.get("lon")
else:
lat = kwargs.get("point").y
lon = kwargs.get("point").x
if "time" not in kwargs:
raise ValueError("You must supply a datetime object")
else:
time = kwargs.get("time")
else:
lat = kwargs.get("loc").latitude
lon = kwargs.get("loc").longitude
time = kwargs.get("loc").time
# Convert time to UTC. Save passed in timezone to return later.
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.utc)
original_zone = pytz.utc
else:
original_zone = time.tzinfo
local_jd = time.timetuple().tm_yday
utc_jd = time.astimezone(pytz.utc).timetuple().tm_yday
# We ALWAYS want to return the sunrise/sunset for the day that was passed
# in (with timezone accounted for), regardless of what the UTC day is. Modify
# the UTC julian day here if need be.
comp = cmp(utc_jd, local_jd)
if comp == 1:
utc_jd -= 1
elif comp == -1:
utc_jd += 1
time = time.replace(hour=0, minute=0, second=0, microsecond=0)
rising_h, rising_m = cls._calc(jd=utc_jd, lat=lat, lon=lon, stage=cls.RISING)
setting_h, setting_m = cls._calc(jd=utc_jd, lat=lat, lon=lon, stage=cls.SETTING)
# _calc returns UTC hours and minutes, so assume time is in UTC for a few lines...
rising = time.replace(tzinfo=pytz.utc) + timedelta(hours=rising_h, minutes=rising_m)
setting = time.replace(tzinfo=pytz.utc) + timedelta(hours=setting_h, minutes=setting_m)
# LOOK: We may be adding 24 hours to the setting time. Why?
if setting < rising:
setting = setting + timedelta(hours=24)
rising = rising.astimezone(original_zone)
setting = setting.astimezone(original_zone)
return { cls.RISING : rising, cls.SETTING : setting} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _operation_speak_as_spell_out(self, content, index, children):
""" The operation method of _speak_as method for spell-out. :param content: The text content of element. :type content: str :param index: The index of pattern in text content of element. :type index: int :param children: The children of element. :type children: list(hatemile.util.html.htmldomelement.HTMLDOMElement) """ |
children.append(self._create_content_element(
content[0:(index + 1)],
'spell-out'
))
children.append(self._create_aural_content_element(' ', 'spell-out'))
return children |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _operation_speak_as_literal_punctuation( self, content, index, children ):
""" The operation method of _speak_as method for literal-punctuation. :param content: The text content of element. :type content: str :param index: The index of pattern in text content of element. :type index: int :param children: The children of element. :type children: list(hatemile.util.html.htmldomelement.HTMLDOMElement) """ |
data_property_value = 'literal-punctuation'
if index != 0:
children.append(self._create_content_element(
content[0:index],
data_property_value
))
children.append(self._create_aural_content_element(
(
' '
+ self._get_description_of_symbol(content[index:(index + 1)])
+ ' '
),
data_property_value)
)
children.append(self._create_visual_content_element(
content[index:(index + 1)],
data_property_value
))
return children |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _operation_speak_as_no_punctuation(self, content, index, children):
""" The operation method of _speak_as method for no-punctuation. :param content: The text content of element. :type content: str :param index: The index of pattern in text content of element. :type index: int :param children: The children of element. :type children: list(hatemile.util.html.htmldomelement.HTMLDOMElement) """ |
if index != 0:
children.append(self._create_content_element(
content[0:index],
'no-punctuation'
))
children.append(self._create_visual_content_element(
content[index:(index + 1)],
'no-punctuation'
))
return children |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _operation_speak_as_digits(self, content, index, children):
""" The operation method of _speak_as method for digits. :param content: The text content of element. :type content: str :param index: The index of pattern in text content of element. :type index: int :param children: The children of element. :type children: list(hatemile.util.html.htmldomelement.HTMLDOMElement) """ |
data_property_value = 'digits'
if index != 0:
children.append(self._create_content_element(
content[0:index],
data_property_value
))
children.append(self._create_aural_content_element(
' ',
data_property_value
))
children.append(self._create_content_element(
content[index:(index + 1)],
data_property_value
))
return children |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_symbols(self, file_name, configure):
""" Load the symbols with configuration. :param file_name: The file path of symbol configuration. :type file_name: str :param configure: The configuration of HaTeMiLe. :type configure: hatemile.util.configure.Configure """ |
self.symbols = []
if file_name is None:
file_name = os.path.join(os.path.dirname(os.path.dirname(
os.path.dirname(os.path.realpath(__file__))
)), 'symbols.xml')
xmldoc = minidom.parse(file_name)
symbols_xml = xmldoc.getElementsByTagName(
'symbols'
)[0].getElementsByTagName('symbol')
for symbol_xml in symbols_xml:
self.symbols.append({
'symbol': symbol_xml.attributes['symbol'].value,
'description': configure.get_parameter(
symbol_xml.attributes['description'].value
)
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_formated_symbol(self, symbol):
""" Returns the symbol formated to be searched by regular expression. :param symbol: The symbol. :type symbol: str :return: The symbol formated. :rtype: str """ |
# pylint: disable=no-self-use
old_symbols = [
'\\',
'.',
'+',
'*',
'?',
'^',
'$',
'[',
']',
'{',
'}',
'(',
')',
'|',
'/',
',',
'!',
'=',
':',
'-'
]
replace_dict = {
'\\': '\\\\',
'.': r'\.',
'+': r'\+',
'*': r'\*',
'?': r'\?',
'^': r'\^',
'$': r'\$',
'[': r'\[',
']': r'\]',
'{': r'\{',
'}': r'\}',
'(': r'\(',
')': r'\)',
'|': r'\|',
'/': r'\/',
',': r'\,',
'!': r'\!',
'=': r'\=',
':': r'\:',
'-': r'\-'
}
for old in old_symbols:
symbol = symbol.replace(old, replace_dict[old])
return symbol |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_regular_expression_of_symbols(self):
""" Returns the regular expression to search all symbols. :return: The regular expression to search all symbols. :rtype: str """ |
regular_expression = None
for symbol in self.symbols:
formated_symbol = self._get_formated_symbol(symbol['symbol'])
if regular_expression is None:
regular_expression = '(' + formated_symbol + ')'
else:
regular_expression = (
regular_expression +
'|(' +
formated_symbol +
')'
)
return regular_expression |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_valid_inherit_element(self, element):
""" Check that the children of element can be manipulated to apply the CSS properties. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :return: True if the children of element can be manipulated to apply the CSS properties or False if the children of element cannot be manipulated to apply the CSS properties. :rtype: bool """ |
# pylint: disable=no-self-use
tag_name = element.get_tag_name()
return (
(tag_name in AccessibleCSSImplementation.VALID_INHERIT_TAGS)
and (not element.has_attribute(CommonFunctions.DATA_IGNORE))
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _isolate_text_node(self, element):
""" Isolate text nodes of element nodes. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
if (
(element.has_children_elements())
and (self._is_valid_element(element))
):
if self._is_valid_element(element):
child_nodes = element.get_children()
for child_node in child_nodes:
if isinstance(child_node, HTMLDOMTextNode):
span = self.html_parser.create_element('span')
span.set_attribute(
AccessibleCSSImplementation.DATA_ISOLATOR_ELEMENT,
'true'
)
span.append_text(child_node.get_text_content())
child_node.replace_node(span)
children = element.get_children_elements()
for child in children:
self._isolate_text_node(child) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _replace_element_by_own_content(self, element):
""" Replace the element by own text content. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
# pylint: disable=no-self-use
if element.has_children_elements():
children = element.get_children_elements()
for child in children:
element.insert_before(child)
element.remove_node()
elif element.has_children():
element.replace_node(element.get_first_node_child()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _visit(self, element, operation):
""" Visit and execute a operation in element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :param operation: The operation to be executed. :type operation: function """ |
if self._is_valid_inherit_element(element):
if element.has_children_elements():
children = element.get_children_elements()
for child in children:
self._visit(child, operation)
elif self._is_valid_element(element):
operation(element) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_content_element(self, content, data_property_value):
""" Create a element to show the content. :param content: The text content of element. :type content: str :param data_property_value: The value of custom attribute used to identify the fix. :type data_property_value: str :return: The element to show the content. :rtype: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
content_element = self.html_parser.create_element('span')
content_element.set_attribute(
AccessibleCSSImplementation.DATA_ISOLATOR_ELEMENT,
'true'
)
content_element.set_attribute(
AccessibleCSSImplementation.DATA_SPEAK_AS,
data_property_value
)
content_element.append_text(content)
return content_element |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_aural_content_element(self, content, data_property_value):
""" Create a element to show the content, only to aural displays. :param content: The text content of element. :type content: str :param data_property_value: The value of custom attribute used to identify the fix. :type data_property_value: str :return: The element to show the content. :rtype: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
content_element = self._create_content_element(
content,
data_property_value
)
content_element.set_attribute('unselectable', 'on')
content_element.set_attribute('class', 'screen-reader-only')
return content_element |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_visual_content_element(self, content, data_property_value):
""" Create a element to show the content, only to visual displays. :param content: The text content of element. :type content: str :param data_property_value: The value of custom attribute used to identify the fix. :type data_property_value: str :return: The element to show the content. :rtype: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
content_element = self._create_content_element(
content,
data_property_value
)
content_element.set_attribute('aria-hidden', 'true')
content_element.set_attribute('role', 'presentation')
return content_element |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _speak_normal(self, element):
""" Speak the content of element only. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
if element.has_attribute(AccessibleCSSImplementation.DATA_SPEAK):
if (
(element.get_attribute(
AccessibleCSSImplementation.DATA_SPEAK
) == 'none')
and (not element.has_attribute(
AccessibleCSSImplementation.DATA_ISOLATOR_ELEMENT
))
):
element.remove_attribute('role')
element.remove_attribute('aria-hidden')
element.remove_attribute(
AccessibleCSSImplementation.DATA_SPEAK
)
else:
self._replace_element_by_own_content(element) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _speak_normal_inherit(self, element):
""" Speak the content of element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
self._visit(element, self._speak_normal)
element.normalize() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _speak_none(self, element):
""" No speak any content of element only. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
# pylint: disable=no-self-use
element.set_attribute('role', 'presentation')
element.set_attribute('aria-hidden', 'true')
element.set_attribute(AccessibleCSSImplementation.DATA_SPEAK, 'none') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _speak_none_inherit(self, element):
""" No speak any content of element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
self._isolate_text_node(element)
self._visit(element, self._speak_none) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _speak_as( self, element, regular_expression, data_property_value, operation ):
""" Execute a operation by regular expression for element only. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :param regular_expression: The regular expression. :type regular_expression: str :param data_property_value: The value of custom attribute used to identify the fix. :type data_property_value: str :param operation: The operation to be executed. :type operation: function """ |
children = []
pattern = re.compile(regular_expression)
content = element.get_text_content()
while content:
matches = pattern.search(content)
if matches is not None:
index = matches.start()
children = operation(content, index, children)
new_index = index + 1
content = content[new_index:]
else:
break
if children:
if content:
children.append(self._create_content_element(
content,
data_property_value
))
while element.has_children():
element.get_first_node_child().remove_node()
for child in children:
element.append_element(child) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reverse_speak_as(self, element, data_property_value):
""" Revert changes of a speak_as method for element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :param data_property_value: The value of custom attribute used to identify the fix. :type data_property_value: str """ |
data_property = (
'['
+ AccessibleCSSImplementation.DATA_SPEAK_AS
+ '="'
+ data_property_value
+ '"]'
)
auxiliar_elements = self.html_parser.find(element).find_descendants(
data_property
).list_results()
for auxiliar_element in auxiliar_elements:
auxiliar_element.remove_node()
content_elements = self.html_parser.find(element).find_descendants(
data_property
).list_results()
for content_element in content_elements:
if (
(element.has_attribute(
AccessibleCSSImplementation.DATA_ISOLATOR_ELEMENT
))
and (element.has_attribute(
AccessibleCSSImplementation.DATA_ISOLATOR_ELEMENT
) == 'true')
):
self._replace_element_by_own_content(content_element)
element.normalize() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _speak_as_normal(self, element):
""" Use the default speak configuration of user agent for element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
self._reverse_speak_as(element, 'spell-out')
self._reverse_speak_as(element, 'literal-punctuation')
self._reverse_speak_as(element, 'no-punctuation')
self._reverse_speak_as(element, 'digits') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _speak_as_spell_out_inherit(self, element):
""" Speak one letter at a time for each word for elements and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
self._reverse_speak_as(element, 'spell-out')
self._isolate_text_node(element)
self._visit(element, self._speak_as_spell_out) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _speak_as_literal_punctuation(self, element):
""" Speak the punctuation for elements only. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
self._speak_as(
element,
self._get_regular_expression_of_symbols(),
'literal-punctuation',
self._operation_speak_as_literal_punctuation
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _speak_as_literal_punctuation_inherit(self, element):
""" Speak the punctuation for elements and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
self._reverse_speak_as(element, 'literal-punctuation')
self._reverse_speak_as(element, 'no-punctuation')
self._isolate_text_node(element)
self._visit(element, self._speak_as_literal_punctuation) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _speak_as_no_punctuation_inherit(self, element):
""" No speak the punctuation for element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
self._reverse_speak_as(element, 'literal-punctuation')
self._reverse_speak_as(element, 'no-punctuation')
self._isolate_text_node(element)
self._visit(element, self._speak_as_no_punctuation) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _speak_as_digits_inherit(self, element):
""" Speak the digit at a time for each number for element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
self._reverse_speak_as(element, 'digits')
self._isolate_text_node(element)
self._visit(element, self._speak_as_digits) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _speak_header_always_inherit(self, element):
""" The cells headers will be spoken for every data cell for element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
self._speak_header_once_inherit(element)
cell_elements = self.html_parser.find(element).find_descendants(
'td[headers],th[headers]'
).list_results()
accessible_display = AccessibleDisplayImplementation(
self.html_parser,
self.configure
)
for cell_element in cell_elements:
accessible_display.display_cell_header(cell_element) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _speak_header_once_inherit(self, element):
""" The cells headers will be spoken one time for element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ |
header_elements = self.html_parser.find(element).find_descendants(
'['
+ AccessibleDisplayImplementation.DATA_ATTRIBUTE_HEADERS_OF
+ ']'
).list_results()
for header_element in header_elements:
header_element.remove_node() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _provide_speak_properties_with_rule(self, element, rule):
""" Provide the CSS features of speaking and speech properties in element. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement :param rule: The stylesheet rule. :type rule: hatemile.util.css.stylesheetrule.StyleSheetRule """ |
if rule.has_property('speak'):
declarations = rule.get_declarations('speak')
for declaration in declarations:
property_value = declaration.get_value()
if property_value == 'none':
self._speak_none_inherit(element)
elif property_value == 'normal':
self._speak_normal_inherit(element)
elif property_value == 'spell-out':
self._speak_as_spell_out_inherit(element)
if rule.has_property('speak-as'):
declarations = rule.get_declarations('speak-as')
for declaration in declarations:
speak_as_values = declaration.get_values()
self._speak_as_normal(element)
for speak_as_value in speak_as_values:
if speak_as_value == 'spell-out':
self._speak_as_spell_out_inherit(element)
elif speak_as_value == 'literal-punctuation':
self._speak_as_literal_punctuation_inherit(element)
elif speak_as_value == 'no-punctuation':
self._speak_as_no_punctuation_inherit(element)
elif speak_as_value == 'digits':
self._speak_as_digits_inherit(element)
if rule.has_property('speak-punctuation'):
declarations = rule.get_declarations('speak-punctuation')
for declaration in declarations:
property_value = declaration.get_value()
if property_value == 'code':
self._speak_as_literal_punctuation_inherit(element)
elif property_value == 'none':
self._speak_as_no_punctuation_inherit(element)
if rule.has_property('speak-numeral'):
declarations = rule.get_declarations('speak-numeral')
for declaration in declarations:
property_value = declaration.get_value()
if property_value == 'digits':
self._speak_as_digits_inherit(element)
elif property_value == 'continuous':
self._speak_as_continuous_inherit(element)
if rule.has_property('speak-header'):
declarations = rule.get_declarations('speak-header')
for declaration in declarations:
property_value = declaration.get_value()
if property_value == 'always':
self._speak_header_always_inherit(element)
elif property_value == 'once':
self._speak_header_once_inherit(element) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def commonprefix(m):
u"Given a list of pathnames, returns the longest common leading component"
if not m:
return ''
prefix = m[0]
for item in m:
for i in range(len(prefix)):
if prefix[:i + 1].lower() != item[:i + 1].lower():
prefix = prefix[:i]
if i == 0:
return u''
break
return prefix |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_incremental_search(self, searchfun, init_event):
u"""Initialize search prompt
""" |
log("init_incremental_search")
self.subsearch_query = u''
self.subsearch_fun = searchfun
self.subsearch_old_line = self.l_buffer.get_line_text()
queue = self.process_keyevent_queue
queue.append(self._process_incremental_search_keyevent)
self.subsearch_oldprompt = self.prompt
if (self.previous_func != self.reverse_search_history and
self.previous_func != self.forward_search_history):
self.subsearch_query = self.l_buffer[0:Point].get_line_text()
if self.subsearch_fun == self.reverse_search_history:
self.subsearch_prompt = u"reverse-i-search%d`%s': "
else:
self.subsearch_prompt = u"forward-i-search%d`%s': "
self.prompt = self.subsearch_prompt%(self._history.history_cursor, "")
if self.subsearch_query:
self.line = self._process_incremental_search_keyevent(init_event)
else:
self.line = u"" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_digit_argument(self, keyinfo):
"""Initialize search prompt
""" |
c = self.console
line = self.l_buffer.get_line_text()
self._digit_argument_oldprompt = self.prompt
queue = self.process_keyevent_queue
queue = self.process_keyevent_queue
queue.append(self._process_digit_argument_keyevent)
if keyinfo.char == "-":
self.argument = -1
elif keyinfo.char in u"0123456789":
self.argument = int(keyinfo.char)
log(u"<%s> %s"%(self.argument, type(self.argument)))
self.prompt = u"(arg: %s) "%self.argument
log(u"arg-init %s %s"%(self.argument, keyinfo.char)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_keyevent(self, keyinfo):
u"""return True when line is final
""" |
#Process exit keys. Only exit on empty line
log(u"_process_keyevent <%s>"%keyinfo)
def nop(e):
pass
if self.next_meta:
self.next_meta = False
keyinfo.meta = True
keytuple = keyinfo.tuple()
if self._insert_verbatim:
self.insert_text(keyinfo)
self._insert_verbatim = False
self.argument = 0
return False
if keytuple in self.exit_dispatch:
pars = (self.l_buffer, lineobj.EndOfLine(self.l_buffer))
log(u"exit_dispatch:<%s, %s>"%pars)
if lineobj.EndOfLine(self.l_buffer) == 0:
raise EOFError
if keyinfo.keyname or keyinfo.control or keyinfo.meta:
default = nop
else:
default = self.self_insert
dispatch_func = self.key_dispatch.get(keytuple, default)
log(u"readline from keyboard:<%s,%s>"%(keytuple, dispatch_func))
r = None
if dispatch_func:
r = dispatch_func(keyinfo)
self._keylog(dispatch_func, self.l_buffer)
self.l_buffer.push_undo()
self.previous_func = dispatch_func
return r |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.