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_assets(cls, lat, lon, begin=None, end=None):
""" Returns date and ids of flyovers Args: lat: latitude float lon: longitude float begin: date instance end: date instance Returns: json """ |
instance = cls('planetary/earth/assets')
filters = {
'lat': lat,
'lon': lon,
'begin': begin,
'end': end,
}
return instance.get_resource(**filters) |
<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_imagery(cls, lat, lon, date=None, dim=None, cloud_score=False):
""" Returns satellite image Args: lat: latitude float lon: longitude float date: date instance of available date from `get_assets` dim: width and height of image in degrees as float cloud_score: boolean to calculate the percentage of the image covered by clouds Returns: json """ |
instance = cls('planetary/earth/imagery')
filters = {
'lat': lat,
'lon': lon,
'date': date,
'dim': dim,
'cloud_score': cloud_score
}
return instance.get_resource(**filters) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def valid_station(station: str):
""" Checks the validity of a station ident This function doesn't return anything. It merely raises a BadStation error if needed """ |
station = station.strip()
if len(station) != 4:
raise BadStation('ICAO station idents must be four characters long')
uses_na_format(station) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uses_na_format(station: str) -> bool: """ Returns True if the station uses the North American format, False if the International format """ |
if station[0] in NA_REGIONS:
return True
if station[0] in IN_REGIONS:
return False
if station[:2] in M_NA_REGIONS:
return True
if station[:2] in M_IN_REGIONS:
return False
raise BadStation("Station doesn't start with a recognized character set") |
<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_leading_zeros(num: str) -> str: """ Strips zeros while handling -, M, and empty strings """ |
if not num:
return num
if num.startswith('M'):
ret = 'M' + num[1:].lstrip('0')
elif num.startswith('-'):
ret = '-' + num[1:].lstrip('0')
else:
ret = num.lstrip('0')
return '0' if ret in ('', 'M', '-') else ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spoken_number(num: str) -> str: """ Returns the spoken version of a number Ex: 1.2 -> one point two 1 1/2 -> one and one half """ |
ret = []
for part in num.split(' '):
if part in FRACTIONS:
ret.append(FRACTIONS[part])
else:
ret.append(' '.join([NUMBER_REPL[char] for char in part if char in NUMBER_REPL]))
return ' and '.join(ret) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_number(num: str, repr_: str = None, speak: str = None):
""" Returns a Number or Fraction dataclass for a number string """ |
if not num or is_unknown(num):
return
# Check CAVOK
if num == 'CAVOK':
return Number('CAVOK', 9999, 'ceiling and visibility ok') # type: ignore
# Check special
if num in SPECIAL_NUMBERS:
return Number(repr_ or num, None, SPECIAL_NUMBERS[num]) # type: ignore
# Create Fraction
if '/' in num:
nmr, dnm = [int(i) for i in num.split('/')]
unpacked = unpack_fraction(num)
spoken = spoken_number(unpacked)
return Fraction(repr_ or num, nmr / dnm, spoken, nmr, dnm, unpacked) # type: ignore
# Create Number
val = num.replace('M', '-')
val = float(val) if '.' in num else int(val) # type: ignore
return Number(repr_ or num, val, spoken_number(speak or str(val))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_first_in_list(txt: str, str_list: [str]) -> int: # type: ignore """ Returns the index of the earliest occurence of an item from a list in a string Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3 """ |
start = len(txt) + 1
for item in str_list:
if start > txt.find(item) > -1:
start = txt.find(item)
return start if len(txt) + 1 > start > -1 else -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 get_remarks(txt: str) -> ([str], str):
# type: ignore """ Returns the report split into components and the remarks string Remarks can include items like RMK and on, NOSIG and on, and BECMG and on """ |
txt = txt.replace('?', '').strip()
# First look for Altimeter in txt
alt_index = len(txt) + 1
for item in [' A2', ' A3', ' Q1', ' Q0', ' Q9']:
index = txt.find(item)
if len(txt) - 6 > index > -1 and txt[index + 2:index + 6].isdigit():
alt_index = index
# Then look for earliest remarks 'signifier'
sig_index = find_first_in_list(txt, METAR_RMK)
if sig_index == -1:
sig_index = len(txt) + 1
if sig_index > alt_index > -1:
return txt[:alt_index + 6].strip().split(' '), txt[alt_index + 7:]
if alt_index > sig_index > -1:
return txt[:sig_index].strip().split(' '), txt[sig_index + 1:]
return txt.strip().split(' '), '' |
<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_taf_remarks(txt: str) -> (str, str):
# type: ignore """ Returns report and remarks separated if found """ |
remarks_start = find_first_in_list(txt, TAF_RMK)
if remarks_start == -1:
return txt, ''
remarks = txt[remarks_start:]
txt = txt[:remarks_start].strip()
return txt, remarks |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sanitize_report_string(txt: str) -> str: """ Provides sanitization for operations that work better when the report is a string Returns the first pass sanitized report string """ |
if len(txt) < 4:
return txt
# Standardize whitespace
txt = ' '.join(txt.split())
# Prevent changes to station ID
stid, txt = txt[:4], txt[4:]
# Replace invalid key-value pairs
for key, rep in STR_REPL.items():
txt = txt.replace(key, rep)
# Check for missing spaces in front of cloud layers
# Ex: TSFEW004SCT012FEW///CBBKN080
for cloud in CLOUD_LIST:
if cloud in txt and ' ' + cloud not in txt:
start, counter = 0, 0
while txt.count(cloud) != txt.count(' ' + cloud):
cloud_index = start + txt[start:].find(cloud)
if len(txt[cloud_index:]) >= 3:
target = txt[cloud_index + len(cloud):cloud_index + len(cloud) + 3]
if target.isdigit() or not target.strip('/'):
txt = txt[:cloud_index] + ' ' + txt[cloud_index:]
start = cloud_index + len(cloud) + 1
# Prevent infinite loops
if counter > txt.count(cloud):
break
counter += 1
return stid + txt |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sanitize_line(txt: str) -> str: """ Fixes common mistakes with 'new line' signifiers so that they can be recognized """ |
for key in LINE_FIXES:
index = txt.find(key)
if index > -1:
txt = txt[:index] + LINE_FIXES[key] + txt[index + len(key):]
# Fix when space is missing following new line signifiers
for item in ['BECMG', 'TEMPO']:
if item in txt and item + ' ' not in txt:
index = txt.find(item) + len(item)
txt = txt[:index] + ' ' + txt[index:]
return txt |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extra_space_exists(str1: str, str2: str) -> bool: # noqa """ Return True if a space shouldn't exist between two items """ |
ls1, ls2 = len(str1), len(str2)
if str1.isdigit():
# 10 SM
if str2 in ['SM', '0SM']:
return True
# 12 /10
if ls2 > 2 and str2[0] == '/' and str2[1:].isdigit():
return True
if str2.isdigit():
# OVC 040
if str1 in CLOUD_LIST:
return True
# 12/ 10
if ls1 > 2 and str1.endswith('/') and str1[:-1].isdigit():
return True
# 12/1 0
if ls2 == 1 and ls1 > 3 and str1[:2].isdigit() and '/' in str1 and str1[3:].isdigit():
return True
# Q 1001
if str1 in ['Q', 'A']:
return True
# 36010G20 KT
if str2 == 'KT' and str1[-1].isdigit() \
and (str1[:5].isdigit() or (str1.startswith('VRB') and str1[3:5].isdigit())):
return True
# 36010K T
if str2 == 'T' and ls1 >= 6 \
and (str1[:5].isdigit() or (str1.startswith('VRB') and str1[3:5].isdigit())) and str1[-1] == 'K':
return True
# OVC022 CB
if str2 in CLOUD_TRANSLATIONS and str2 not in CLOUD_LIST and ls1 >= 3 and str1[:3] in CLOUD_LIST:
return True
# FM 122400
if str1 in ['FM', 'TL'] and (str2.isdigit() or (str2.endswith('Z') and str2[:-1].isdigit())):
return True
# TX 20/10
if str1 in ['TX', 'TN'] and str2.find('/') != -1:
return True
return False |
<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_altimeter(wxdata: [str], units: Units, version: str = 'NA') -> ([str], Number):
# type: ignore # noqa """ Returns the report list and the removed altimeter item Version is 'NA' (North American / default) or 'IN' (International) """ |
if not wxdata:
return wxdata, None
altimeter = ''
target = wxdata[-1]
if version == 'NA':
# Version target
if target[0] == 'A':
altimeter = wxdata.pop()[1:]
# Other version but prefer normal if available
elif target[0] == 'Q':
if wxdata[-2][0] == 'A':
wxdata.pop()
altimeter = wxdata.pop()[1:]
else:
units.altimeter = 'hPa'
altimeter = wxdata.pop()[1:].lstrip('.')
# Else grab the digits
elif len(target) == 4 and target.isdigit():
altimeter = wxdata.pop()
elif version == 'IN':
# Version target
if target[0] == 'Q':
altimeter = wxdata.pop()[1:].lstrip('.')
if '/' in altimeter:
altimeter = altimeter[:altimeter.find('/')]
# Other version but prefer normal if available
elif target[0] == 'A':
if wxdata[-2][0] == 'Q':
wxdata.pop()
altimeter = wxdata.pop()[1:]
else:
units.altimeter = 'inHg'
altimeter = wxdata.pop()[1:]
# Some stations report both, but we only need one
if wxdata and (wxdata[-1][0] == 'A' or wxdata[-1][0] == 'Q'):
wxdata.pop()
# convert to Number
if not altimeter:
return wxdata, None
if units.altimeter == 'inHg':
value = altimeter[:2] + '.' + altimeter[2:]
else:
value = altimeter
return wxdata, make_number(value, altimeter) |
<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_station_and_time(wxdata: [str]) -> ([str], str, str):
# type: ignore """ Returns the report list and removed station ident and time strings """ |
station = wxdata.pop(0)
qtime = wxdata[0]
if wxdata and qtime.endswith('Z') and qtime[:-1].isdigit():
rtime = wxdata.pop(0)
elif wxdata and len(qtime) == 6 and qtime.isdigit():
rtime = wxdata.pop(0) + 'Z'
else:
rtime = ''
return wxdata, station, rtime |
<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_visibility(wxdata: [str], units: Units) -> ([str], Number):
# type: ignore """ Returns the report list and removed visibility string """ |
visibility = '' # type: ignore
if wxdata:
item = copy(wxdata[0])
# Vis reported in statue miles
if item.endswith('SM'): # 10SM
if item in ('P6SM', 'M1/4SM'):
visibility = item[:-2]
elif '/' not in item:
visibility = str(int(item[:item.find('SM')]))
else:
visibility = item[:item.find('SM')] # 1/2SM
wxdata.pop(0)
units.visibility = 'sm'
# Vis reported in meters
elif len(item) == 4 and item.isdigit():
visibility = wxdata.pop(0)
units.visibility = 'm'
elif 7 >= len(item) >= 5 and item[:4].isdigit() \
and (item[4] in ['M', 'N', 'S', 'E', 'W'] or item[4:] == 'NDV'):
visibility = wxdata.pop(0)[:4]
units.visibility = 'm'
elif len(item) == 5 and item[1:].isdigit() and item[0] in ['M', 'P', 'B']:
visibility = wxdata.pop(0)[1:]
units.visibility = 'm'
elif item.endswith('KM') and item[:item.find('KM')].isdigit():
visibility = item[:item.find('KM')] + '000'
wxdata.pop(0)
units.visibility = 'm'
# Vis statute miles but split Ex: 2 1/2SM
elif len(wxdata) > 1 and wxdata[1].endswith('SM') and '/' in wxdata[1] and item.isdigit():
vis1 = wxdata.pop(0) # 2
vis2 = wxdata.pop(0).replace('SM', '') # 1/2
visibility = str(int(vis1) * int(vis2[2]) + int(vis2[0])) + vis2[1:] # 5/2
units.visibility = 'sm'
return wxdata, make_number(visibility) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def starts_new_line(item: str) -> bool: """ Returns True if the given element should start a new report line """ |
if item in TAF_NEWLINE:
return True
for start in TAF_NEWLINE_STARTSWITH:
if item.startswith(start):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_taf(txt: str) -> [str]: # type: ignore """ Splits a TAF report into each distinct time period """ |
lines = []
split = txt.split()
last_index = 0
for i, item in enumerate(split):
if starts_new_line(item) and i != 0 and not split[i - 1].startswith('PROB'):
lines.append(' '.join(split[last_index:i]))
last_index = i
lines.append(' '.join(split[last_index:]))
return lines |
<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_next_time(lines: [dict], target: str) -> str: # type: ignore """ Returns the next FROM target value or empty """ |
for line in lines:
if line[target] and not _is_tempo_or_prob(line['type']):
return line[target]
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 get_temp_min_and_max(wxlist: [str]) -> ([str], str, str):
# type: ignore """ Pull out Max temp at time and Min temp at time items from wx list """ |
temp_max, temp_min = '', ''
for i, item in reversed(list(enumerate(wxlist))):
if len(item) > 6 and item[0] == 'T' and '/' in item:
# TX12/1316Z
if item[1] == 'X':
temp_max = wxlist.pop(i)
# TNM03/1404Z
elif item[1] == 'N':
temp_min = wxlist.pop(i)
# TM03/1404Z T12/1316Z -> Will fix TN/TX
elif item[1] == 'M' or item[1].isdigit():
if temp_min:
if int(temp_min[2:temp_min.find('/')].replace('M', '-')) \
> int(item[1:item.find('/')].replace('M', '-')):
temp_max = 'TX' + temp_min[2:]
temp_min = 'TN' + item[1:]
else:
temp_max = 'TX' + item[1:]
else:
temp_min = 'TN' + item[1:]
wxlist.pop(i)
return wxlist, temp_max, temp_min |
<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_digit_list(alist: [str], from_index: int) -> ([str], [str]):
# type: ignore """ Returns a list of items removed from a given list of strings that are all digits from 'from_index' until hitting a non-digit item """ |
ret = []
alist.pop(from_index)
while len(alist) > from_index and alist[from_index].isdigit():
ret.append(alist.pop(from_index))
return alist, ret |
<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_oceania_temp_and_alt(wxlist: [str]) -> ([str], [str], [str]):
# type: ignore """ Get Temperature and Altimeter lists for Oceania TAFs """ |
tlist, qlist = [], [] # type: ignore
if 'T' in wxlist:
wxlist, tlist = _get_digit_list(wxlist, wxlist.index('T'))
if 'Q' in wxlist:
wxlist, qlist = _get_digit_list(wxlist, wxlist.index('Q'))
return wxlist, tlist, qlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sanitize_cloud(cloud: str) -> str: """ Fix rare cloud layer issues """ |
if len(cloud) < 4:
return cloud
if not cloud[3].isdigit() and cloud[3] != '/':
if cloud[3] == 'O':
cloud = cloud[:3] + '0' + cloud[4:] # Bad "O": FEWO03 -> FEW003
else: # Move modifiers to end: BKNC015 -> BKN015C
cloud = cloud[:3] + cloud[4:] + cloud[3]
return cloud |
<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_clouds(wxdata: [str]) -> ([str], list):
# type: ignore """ Returns the report list and removed list of split cloud layers """ |
clouds = []
for i, item in reversed(list(enumerate(wxdata))):
if item[:3] in CLOUD_LIST or item[:2] == 'VV':
cloud = wxdata.pop(i)
clouds.append(make_cloud(cloud))
return wxdata, sorted(clouds, key=lambda cloud: (cloud.altitude, cloud.type)) |
<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_flight_rules(vis: Number, ceiling: Cloud) -> int: """ Returns int based on current flight rules from parsed METAR data 0=VFR, 1=MVFR, 2=IFR, 3=LIFR Note: Common practice is to report IFR if visibility unavailable """ |
# Parse visibility
if not vis:
return 2
if vis.repr == 'CAVOK' or vis.repr.startswith('P6'):
vis = 10 # type: ignore
elif vis.repr.startswith('M'):
vis = 0 # type: ignore
# Convert meters to miles
elif len(vis.repr) == 4:
vis = vis.value * 0.000621371 # type: ignore
else:
vis = vis.value # type: ignore
# Parse ceiling
cld = ceiling.altitude if ceiling else 99
# Determine flight rules
if (vis <= 5) or (cld <= 30): # type: ignore
if (vis < 3) or (cld < 10): # type: ignore
if (vis < 1) or (cld < 5): # type: ignore
return 3 # LIFR
return 2 # IFR
return 1 # MVFR
return 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 get_taf_flight_rules(lines: [dict]) -> [dict]: # type: ignore """ Get flight rules by looking for missing data in prior reports """ |
for i, line in enumerate(lines):
temp_vis, temp_cloud = line['visibility'], line['clouds']
for report in reversed(lines[:i]):
if not _is_tempo_or_prob(report['type']):
if temp_vis == '':
temp_vis = report['visibility']
if 'SKC' in report['other'] or 'CLR' in report['other']:
temp_cloud = 'temp-clear'
elif temp_cloud == []:
temp_cloud = report['clouds']
if temp_vis != '' and temp_cloud != []:
break
if temp_cloud == 'temp-clear':
temp_cloud = []
line['flight_rules'] = FLIGHT_RULES[get_flight_rules(temp_vis, get_ceiling(temp_cloud))]
return lines |
<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_ceiling(clouds: [Cloud]) -> Cloud: # type: ignore """ Returns ceiling layer from Cloud-List or None if none found Assumes that the clouds are already sorted lowest to highest Only 'Broken', 'Overcast', and 'Vertical Visibility' are considdered ceilings Prevents errors due to lack of cloud information (eg. '' or 'FEW///') """ |
for cloud in clouds:
if cloud.altitude and cloud.type in ('OVC', 'BKN', 'VV'):
return cloud
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 parse_date(date: str, hour_threshold: int = 200):
""" Parses a report timestamp in ddhhZ or ddhhmmZ format This function assumes the given timestamp is within the hour threshold from current date """ |
# Format date string
date = date.strip('Z')
if len(date) == 4:
date += '00'
if not (len(date) == 6 and date.isdigit()):
return
# Create initial guess
now = datetime.utcnow()
guess = now.replace(day=int(date[0:2]),
hour=int(date[2:4]) % 24,
minute=int(date[4:6]) % 60,
second=0, microsecond=0)
hourdiff = (guess - now) / timedelta(minutes=1) / 60
# Handle changing months
if hourdiff > hour_threshold:
guess += relativedelta(months=-1)
elif hourdiff < -hour_threshold:
guess += relativedelta(months=+1)
return guess |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync_one(self, aws_syncr, amazon, bucket):
"""Make sure this bucket exists and has only attributes we want it to have""" |
if bucket.permission.statements:
permission_document = bucket.permission.document
else:
permission_document = ""
bucket_info = amazon.s3.bucket_info(bucket.name)
if not bucket_info.creation_date:
amazon.s3.create_bucket(bucket.name, permission_document, bucket)
else:
amazon.s3.modify_bucket(bucket_info, bucket.name, permission_document, bucket) |
<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_python_inside(self, file_path):
# type: (str) -> bool """ If .py, yes. If extensionless, open file and check shebang TODO: support variations on this: #!/usr/bin/env python :param file_path: :return: """ |
if file_path.endswith(".py"):
return True # duh.
# not supporting surprising extensions, ege. .py2, .python, .corn_chowder
# extensionless
if "." not in file_path:
try:
firstline = self.open_this(file_path, "r").readline()
if firstline.startswith("#") and "python" in firstline:
return True
except:
pass
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def toXMLname(string):
"""Convert string to a XML name.""" |
if string.find(':') != -1 :
(prefix, localname) = string.split(':',1)
else:
prefix = None
localname = string
T = unicode(localname)
N = len(localname)
X = [];
for i in range(N) :
if i< N-1 and T[i]==u'_' and T[i+1]==u'x':
X.append(u'_x005F_')
elif i==0 and N >= 3 and \
( T[0]==u'x' or T[0]==u'X' ) and \
( T[1]==u'm' or T[1]==u'M' ) and \
( T[2]==u'l' or T[2]==u'L' ):
X.append(u'_xFFFF_' + T[0])
elif (not _NCNameChar(T[i])) or (i==0 and not _NCNameStartChar(T[i])):
X.append(_toUnicodeHex(T[i]))
else:
X.append(T[i])
if prefix:
return "%s:%s" % (prefix, u''.join(X))
return u''.join(X) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fromXMLname(string):
"""Convert XML name to unicode string.""" |
retval = sub(r'_xFFFF_','', string )
def fun( matchobj ):
return _fromUnicodeHex( matchobj.group(0) )
retval = sub(r'_x[0-9A-Za-z]+_', fun, retval )
return retval |
<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_sip_to_fc(fc, tfidf, limit=40):
'''add "bowNP_sip" to `fc` using `tfidf` data
'''
if 'bowNP' not in fc:
return
if tfidf is None:
return
sips = features.sip_noun_phrases(tfidf, fc['bowNP'].keys(), limit=limit)
fc[u'bowNP_sip'] = StringCounter(sips) |
<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_password(self):
'''
a method to retrieve the password for the group mosquitto server
:return: string with group mosquitto server password
NOTE: result is added to self.password property
'''
import requests
url = '%s/mqtt' % self.endpoint
params = {
'group': self.group_name
}
response = requests.put(url, params=params)
response_details = response.json()
self.password = response_details['password']
return self.password |
<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_position(self, user_id, track=False, confidence=False):
'''
a method to retrieve the latest position of a user
:param user_id: string with id of user
:param track: [optional] boolean to add user to self.positions
:param confidence: [optional] boolean to include the data model confidence scores
:return: dictionaries with position details
NOTE: if user does not exist, then location and time are null values
{
'time': 0.0,
'location': 'location.id',
'id': 'user_id',
bayes: {}, # if confidence = True
svm: None, # if confidence = True
rf: {} # if confidence = True
}
'''
title = '%s.get_position' % self.__class__.__name__
# validate inputs
input_fields = {
'user_id': user_id
}
for key, value in input_fields.items():
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
# construct empty response
position_details = {
'location': '',
'time': 0.0,
'id': user_id
}
# construct empty position history
position_history = []
# compose request
import requests
url = self.endpoint + '/location'
params = {
'group': self.group_name,
'user': user_id,
'n': 1
}
response = requests.get(url, params=params)
# ingest response
response_details = response.json()
from labpack.records.time import labDT
for key in response_details['users'].keys():
if key == user_id:
for entry in response_details['users'][key]:
if 'time' in entry.keys() and 'location' in entry.keys():
time_string = entry['time']
time_string = time_string.replace(' +0000 UTC', 'Z')
time_string = time_string.replace(' ', 'T')
time_dt = labDT.fromISO(time_string).epoch()
if confidence:
for key, value in entry.items():
position_details[key] = value
position_details['time'] = time_dt
position_details['location'] = entry['location']
break
if track:
stored_position = {
'location': position_details['location'],
'time': position_details['time']
}
self.positions[user_id] = stored_position
return position_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 log_begin_message(message):
""" Create and print a new log message waiting for an end log message """ |
global MESSAGE
MESSAGE = message
sys.stdout.write("[....] ")
sys.stdout.write(message)
sys.stdout.flush() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_end_message(log):
""" End a log message with a status defined by log """ |
if not log in MESSAGE_LOG.keys():
log = -1
res = colors.color_text(*MESSAGE_LOG[log][1])
sys.stdout.write("\r[" + res + "] " + MESSAGE + "\n") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _fetchFilesFromFolder(self, target, recursive):
'''
Fetches files from the target directory, and - if recursive
mode is on, all subdirectories.
Returns a list of all found files
'''
directory_items = os.walk(target)
# If recursive is false, fetch only the first tuple
if not recursive:
directory_items = [next(directory_items)]
targets = []
for dir_name, folders, files in directory_items:
for f in files:
targets.append(os.path.join(dir_name, f))
return targets |
<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(self, iid):
'''
Deletes file from vault and removes database information
'''
for index in iid:
target = Target.getTarget(index)
target.delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def deploy(self, iid):
'''
Links an item from the vault to the original path
'''
for index in iid:
target = Target.getTarget(index)
if target:
verbose('Deploying id {} from {} to {} with the name {}'
.format(index, target.vault_path, target.path, target.name))
target.deploy()
verbose('Deploy complete') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def deployAll(self):
'''
Deploys all the items from the vault. Useful after a format
'''
targets = [Target.getTarget(iid) for iid, n, p in self.db.listTargets()]
for target in targets:
target.deploy()
verbose('Deploy all complete') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_delete(resc, req, resp, rid):
# pylint: disable=unused-argument """ Delete the single item Upon a successful deletion an empty bodied 204 is returned. """ |
signals.pre_req.send(resc.model)
signals.pre_req_delete.send(resc.model)
model = find(resc.model, rid)
goldman.sess.store.delete(model)
resp.status = falcon.HTTP_204
signals.post_req.send(resc.model)
signals.post_req_delete.send(resc.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 on_get(resc, req, resp, rid):
""" Find the model by id & serialize it back """ |
signals.pre_req.send(resc.model)
signals.pre_req_find.send(resc.model)
model = find(resc.model, rid)
props = to_rest_model(model, includes=req.includes)
resp.last_modified = model.updated
resp.serialize(props)
signals.post_req.send(resc.model)
signals.post_req_find.send(resc.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 on_patch(resc, req, resp, rid):
""" Deserialize the payload & update the single item """ |
signals.pre_req.send(resc.model)
signals.pre_req_update.send(resc.model)
props = req.deserialize()
model = find(resc.model, rid)
from_rest(model, props)
goldman.sess.store.update(model)
props = to_rest_model(model, includes=req.includes)
resp.last_modified = model.updated
resp.serialize(props)
signals.post_req.send(resc.model)
signals.post_req_update.send(resc.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 decode(data):
""" Handles decoding of the XML `data`. Args: data (str):
Data which will be decoded. Returns: dict: Dictionary with decoded data. """ |
dom = None
try:
dom = dhtmlparser.parseString(data)
except Exception, e:
raise MetaParsingException("Can't parse your XML data: %s" % e.message)
root = dom.find("root")
# check whether there is <root>s
if not root:
raise MetaParsingException("All elements have to be inside <root>.")
# and make sure, that there is not too many <root>s
if len(root) > 1:
raise MetaParsingException("Too many <root> elements in your XML!")
items = root[0].find("item")
# check for items
if not items:
raise MetaParsingException("There are no <items> in your XML <root>!")
decoded = []
for item in items:
if "key" not in item.params:
raise MetaParsingException(
"There is no 'key' parameter in %s." % str(item)
)
decoded.append([
item.params["key"],
item.getContent().strip()
])
decoded = validator.check_structure(decoded)
return decoded |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def activate(self, ideSettings, ideGlobalData):
"""Activates the plugin. The plugin may override the method to do specific plugin activation handling. ideSettings - reference to the IDE Settings singleton see codimension/src/utils/settings.py ideGlobalData - reference to the IDE global settings see codimension/src/utils/globals.py Note: if overriden do not forget to call the base class activate() """ |
WizardInterface.activate(self, ideSettings, ideGlobalData)
self.__where = self.__getConfiguredWhere()
self.ide.editorsManager.sigTabClosed.connect(self.__collectGarbage)
self.ide.project.sigProjectChanged.connect(self.__collectGarbage) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deactivate(self):
"""Deactivates the plugin. The plugin may override the method to do specific plugin deactivation handling. Note: if overriden do not forget to call the base class deactivate() """ |
self.ide.project.sigProjectChanged.disconnect(self.__collectGarbage)
self.ide.editorsManager.sigTabClosed.disconnect(self.__collectGarbage)
WizardInterface.deactivate(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def populateMainMenu(self, parentMenu):
"""Populates the main menu. The main menu looks as follows: Plugins - Plugin manager (fixed item) - Separator (fixed item) - <Plugin #1 name> (this is the parentMenu passed) If no items were populated by the plugin then there will be no <Plugin #N name> menu item shown. It is suggested to insert plugin configuration item here if so. """ |
parentMenu.addAction("Configure", self.configure)
parentMenu.addAction("Collect garbage", self.__collectGarbage) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def populateBufferContextMenu(self, parentMenu):
"""Populates the editing buffer context menu. The buffer context menu shown for the current edited/viewed file will have an item with a plugin name and subitems which are populated here. If no items were populated then the plugin menu item will not be shown. Note: when a buffer context menu is selected by the user it always refers to the current widget. To get access to the current editing widget the plugin can use: self.ide.currentEditorWidget The widget could be of different types and some circumstances should be considered, e.g.: - it could be a new file which has not been saved yet - it could be modified - it could be that the disk file has already been deleted - etc. Having the current widget reference the plugin is able to retrieve the infirmation it needs. """ |
parentMenu.addAction("Configure", self.configure)
parentMenu.addAction("Collect garbage", self.__collectGarbage) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure(self):
"""Configures the garbage collector plugin""" |
dlg = GCPluginConfigDialog(self.__where)
if dlg.exec_() == QDialog.Accepted:
newWhere = dlg.getCheckedOption()
if newWhere != self.__where:
self.__where = newWhere
self.__saveConfiguredWhere() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __getConfiguredWhere(self):
"""Provides the saved configured value""" |
defaultSettings = {'where': GCPluginConfigDialog.SILENT}
configFile = self.__getConfigFile()
if not os.path.exists(configFile):
values = defaultSettings
else:
values = loadJSON(configFile,
'garbage collector plugin settings',
defaultSettings)
try:
value = values['where']
if value < GCPluginConfigDialog.SILENT or \
value > GCPluginConfigDialog.LOG:
return GCPluginConfigDialog.SILENT
return value
except:
return GCPluginConfigDialog.SILENT |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self, data, accepted_media_type=None, renderer_context=None):
""" Render `data` into JSON, returning a bytestring. """ |
if data is None:
return bytes()
renderer_context = renderer_context or {}
indent = self.get_indent(accepted_media_type, renderer_context)
if indent is None:
separators = SHORT_SEPARATORS if self.compact else LONG_SEPARATORS
else:
separators = INDENT_SEPARATORS
ret = json.dumps(
data, cls=self.encoder_class,
indent=indent, ensure_ascii=self.ensure_ascii,
separators=separators
)
# On python 2.x json.dumps() returns bytestrings if ensure_ascii=True,
# but if ensure_ascii=False, the return type is underspecified,
# and may (or may not) be unicode.
# On python 3.x json.dumps() returns unicode strings.
if isinstance(ret, six.text_type):
# We always fully escape \u2028 and \u2029 to ensure we output JSON
# that is a strict javascript subset. If bytes were returned
# by json.dumps() then we don't have these characters in any case.
# See: http://timelessrepo.com/json-isnt-a-javascript-subset
ret = ret.replace('\u2028', '\\u2028').replace('\u2029', '\\u2029')
return bytes(ret.encode('utf-8'))
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self, data, accepted_media_type=None, renderer_context=None):
""" Render serializer data and return an HTML form, as a string. """ |
form = data.serializer
style = renderer_context.get('style', {})
if 'template_pack' not in style:
style['template_pack'] = self.template_pack
style['renderer'] = self
template_pack = style['template_pack'].strip('/')
template_name = template_pack + '/' + self.base_template
template = loader.get_template(template_name)
context = {
'form': form,
'style': style
}
return template_render(template, context) |
<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_content(self, renderer, data, accepted_media_type, renderer_context):
""" Get the content as if it had been rendered by the default non-documenting renderer. """ |
if not renderer:
return '[No renderers were found]'
renderer_context['indent'] = 4
content = renderer.render(data, accepted_media_type, renderer_context)
render_style = getattr(renderer, 'render_style', 'text')
assert render_style in ['text', 'binary'], 'Expected .render_style ' \
'"text" or "binary", but got "%s"' % render_style
if render_style == 'binary':
return '[%d bytes of binary content]' % len(content)
return content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_form_for_method(self, view, method, request, obj):
""" Returns True if a form should be shown for this method. """ |
if method not in view.allowed_methods:
return # Not a valid method
try:
view.check_permissions(request)
if obj is not None:
view.check_object_permissions(request, obj)
except exceptions.APIException:
return False # Doesn't have permissions
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 get_rendered_html_form(self, data, view, method, request):
""" Return a string representing a rendered HTML form, possibly bound to either the input or output data. In the absence of the View having an associated form then return None. """ |
# See issue #2089 for refactoring this.
serializer = getattr(data, 'serializer', None)
if serializer and not getattr(serializer, 'many', False):
instance = getattr(serializer, 'instance', None)
if isinstance(instance, Page):
instance = None
else:
instance = None
# If this is valid serializer data, and the form is for the same
# HTTP method as was used in the request then use the existing
# serializer instance, rather than dynamically creating a new one.
if request.method == method and serializer is not None:
try:
kwargs = {'data': request.data}
except ParseError:
kwargs = {}
existing_serializer = serializer
else:
kwargs = {}
existing_serializer = None
with override_method(view, request, method) as request:
if not self.show_form_for_method(view, method, request, instance):
return
if method in ('DELETE', 'OPTIONS'):
return True # Don't actually need to return a form
has_serializer = getattr(view, 'get_serializer', None)
has_serializer_class = getattr(view, 'serializer_class', None)
if (
(not has_serializer and not has_serializer_class) or
not any(is_form_media_type(parser.media_type) for parser in view.parser_classes)
):
return
if existing_serializer is not None:
serializer = existing_serializer
else:
if has_serializer:
if method in ('PUT', 'PATCH'):
serializer = view.get_serializer(instance=instance, **kwargs)
else:
serializer = view.get_serializer(**kwargs)
else:
# at this point we must have a serializer_class
if method in ('PUT', 'PATCH'):
serializer = self._get_serializer(view.serializer_class, view,
request, instance=instance, **kwargs)
else:
serializer = self._get_serializer(view.serializer_class, view,
request, **kwargs)
if hasattr(serializer, 'initial_data'):
serializer.is_valid()
form_renderer = self.form_renderer_class()
return form_renderer.render(
serializer.data,
self.accepted_media_type,
{'style': {'template_pack': 'rest_framework/horizontal'}}
) |
<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_context(self, data, accepted_media_type, renderer_context):
""" Returns the context used to render. """ |
view = renderer_context['view']
request = renderer_context['request']
response = renderer_context['response']
renderer = self.get_default_renderer(view)
raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request)
raw_data_put_form = self.get_raw_data_form(data, view, 'PUT', request)
raw_data_patch_form = self.get_raw_data_form(data, view, 'PATCH', request)
raw_data_put_or_patch_form = raw_data_put_form or raw_data_patch_form
response_headers = OrderedDict(sorted(response.items()))
renderer_content_type = ''
if renderer:
renderer_content_type = '%s' % renderer.media_type
if renderer.charset:
renderer_content_type += ' ;%s' % renderer.charset
response_headers['Content-Type'] = renderer_content_type
if getattr(view, 'paginator', None) and view.paginator.display_page_controls:
paginator = view.paginator
else:
paginator = None
context = {
'content': self.get_content(renderer, data, accepted_media_type, renderer_context),
'view': view,
'request': request,
'response': response,
'description': self.get_description(view, response.status_code),
'name': self.get_name(view),
'version': VERSION,
'paginator': paginator,
'breadcrumblist': self.get_breadcrumbs(request),
'allowed_methods': view.allowed_methods,
'available_formats': [renderer_cls.format for renderer_cls in view.renderer_classes],
'response_headers': response_headers,
'put_form': self.get_rendered_html_form(data, view, 'PUT', request),
'post_form': self.get_rendered_html_form(data, view, 'POST', request),
'delete_form': self.get_rendered_html_form(data, view, 'DELETE', request),
'options_form': self.get_rendered_html_form(data, view, 'OPTIONS', request),
'filter_form': self.get_filter_form(data, view, request),
'raw_data_put_form': raw_data_put_form,
'raw_data_post_form': raw_data_post_form,
'raw_data_patch_form': raw_data_patch_form,
'raw_data_put_or_patch_form': raw_data_put_or_patch_form,
'display_edit_forms': bool(response.status_code != 403),
'api_settings': api_settings
}
return context |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(package, **kwargs):
"""a template for the python setup.py installer routine * take setup information from the packages __init__.py file - __email__ - __version__ - __depencies__ are still available after installation * exclude /tests* * create scripts from all files in /bin * create the long description from - /README.rst - /CHANGES.rst - /AUTHORS.rst * remove /build at the end """ |
def read(*paths):
"""Build a file path from *paths* and return the contents."""
p = os.path.join(*paths)
if os.path.exists(p):
with open(p, 'r') as f:
return f.read()
return ''
setuptoolsSetup(
name=package.__name__,
version=package.__version__,
author=package.__author__,
author_email=package.__email__,
url=package.__url__,
license=package.__license__,
install_requires=package.__depencies__,
classifiers=package.__classifiers__,
description=package.__description__,
packages=find_packages(exclude=['tests*']),
include_package_data=True,
scripts=[] if not os.path.exists('bin') else [
os.path.join('bin', x) for x in os.listdir('bin')],
long_description=(
read('README.rst') + '\n\n' +
read('CHANGES.rst') + '\n\n' +
read('AUTHORS.rst')),
**kwargs
)
# remove the build
# else old and notexistent files could come again in the installed pkg
mainPath = os.path.abspath(os.path.dirname(__file__))
bPath = os.path.join(mainPath, 'build')
if os.path.exists(bPath):
shutil.rmtree(bPath) |
<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_object(self, correlation_id, parameters):
""" Reads configuration file, parameterizes its content and converts it into JSON object. :param correlation_id: (optional) transaction id to trace execution through call chain. :param parameters: values to parameters the configuration. :return: a JSON object with configuration. """ |
path = self.get_path()
if path == None:
raise ConfigException(correlation_id, "NO_PATH", "Missing config file path")
if not os.path.isfile(path):
raise FileException(correlation_id, 'FILE_NOT_FOUND', 'Config file was not found at ' + path)
try:
with open(path, 'r') as file:
config = file.read()
config = self._parameterize(config, parameters)
return yaml.load(config)
except Exception as ex:
raise FileException(
correlation_id,
"READ_FAILED",
"Failed reading configuration " + path + ": " + str(ex)
).with_details("path", path).with_cause(ex) |
<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_config(self, correlation_id, parameters):
""" Reads configuration and parameterize it with given values. :param correlation_id: (optional) transaction id to trace execution through call chain. :param parameters: values to parameters the configuration or null to skip parameterization. :return: ConfigParams configuration. """ |
value = self._read_object(correlation_id, parameters)
return ConfigParams.from_value(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 _read_config(correlation_id, path, parameters):
""" Reads configuration from a file, parameterize it with given values and returns a new ConfigParams object. :param correlation_id: (optional) transaction id to trace execution through call chain. :param path: a path to configuration file. :param parameters: values to parameters the configuration. :return: ConfigParams configuration. """ |
value = YamlConfigReader(path)._read_object(correlation_id, parameters)
return ConfigParams.from_value(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 run(self):
""" Perform the specified action """ |
if self.args['add']:
self.action_add()
elif self.args['rm']:
self.action_rm()
elif self.args['show']:
self.action_show()
elif self.args['rename']:
self.action_rename()
else:
self.action_run_command() |
<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_db(self):
""" Init database and prepare tables """ |
# database file
db_path = self.get_data_file("data.sqlite")
# comect and create cursor
self.db = sqlite3.connect(db_path)
self.cursor = self.db.cursor()
# prep tables
self.db_exec('''
CREATE TABLE IF NOT EXISTS shortcuts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
path TEXT NOT NULL,
command TEXT NOT NULL
)
''') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shortcut_str(self, path, cmd):
""" Get a string with colors describing a shortcut """ |
s = colored('| path = ', 'cyan') + colored(path, 'yellow') + '\n' \
+ colored('| cmd = ', 'cyan') + \
colored(cmd, 'green', attrs=['bold'])
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_bucket():
""" Delete S3 Bucket """ |
args = parser.parse_args
s3_bucket(args.aws_access_key_id, args.aws_secret_access_key, args.bucket_name)().delete() |
<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_instance_status(self, instance_id, wait=True):
'''
a method to wait until AWS instance reports an OK status
:param instance_id: string of instance id on AWS
:param wait: [optional] boolean to wait for instance while initializing
:return: True
'''
title = '%s.check_instance_status' % self.__class__.__name__
# validate inputs
input_fields = {
'instance_id': instance_id
}
for key, value in input_fields.items():
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
# notify status check
self.iam.printer('Querying AWS region %s for status of instance %s.' % (self.iam.region_name, instance_id))
# check state of instance
self.iam.printer_on = False
self.check_instance_state(instance_id)
self.iam.printer_on = True
# check instance status
response = self.connection.describe_instance_status(
InstanceIds=[ instance_id ]
)
if not response['InstanceStatuses']:
from time import sleep
from timeit import timeit as timer
sleep(1)
response = self.connection.describe_instance_status(
InstanceIds=[ instance_id ]
)
self.iam.printer(response)
instance_status = response['InstanceStatuses'][0]['InstanceStatus']['Status']
# wait for instance status to be ok
if instance_status != 'ok' and wait:
from time import sleep
from timeit import timeit as timer
self.iam.printer('Waiting for initialization of instance %s to stop' % instance_id, flush=True)
delay = 3
status_timeout = 0
while instance_status != 'ok':
self.iam.printer('.', flush=True)
sleep(delay)
t3 = timer()
response = self.connection.describe_instance_status(
InstanceIds=[ instance_id ]
)
t4 = timer()
response_time = t4 - t3
if 3 - response_time > 0:
delay = 3 - response_time
else:
delay = 0
status_timeout += 1
if status_timeout > 300:
raise Exception('\nTimeout. Failure initializing instance %s on AWS in less than 15min' % instance_id)
instance_status = response['InstanceStatuses'][0]['InstanceStatus']['Status']
print(' done.')
# report outcome
self.iam.printer('Instance %s is %s.' % (instance_id, instance_status))
return instance_status |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list_instances(self, tag_values=None):
'''
a method to retrieve the list of instances on AWS EC2
:param tag_values: [optional] list of tag values
:return: list of strings with instance AWS ids
'''
title = '%s.list_instances' % self.__class__.__name__
# validate inputs
input_fields = {
'tag_values': tag_values
}
for key, value in input_fields.items():
if value:
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
# add tags to method arguments
kw_args = {}
tag_text = ''
if tag_values:
kw_args = {
'Filters': [ { 'Name': 'tag-value', 'Values': tag_values } ]
}
from labpack.parsing.grammar import join_words
plural_value = ''
if len(tag_values) > 1:
plural_value = 's'
tag_text = ' with tag value%s %s' % (plural_value, join_words(tag_values))
# request instance details from AWS
self.iam.printer('Querying AWS region %s for instances%s.' % (self.iam.region_name, tag_text))
instance_list = []
try:
if tag_values:
response = self.connection.describe_instances(**kw_args)
else:
response = self.connection.describe_instances()
except:
raise AWSConnectionError(title)
# repeat request if any instances are currently pending
response_list = response['Reservations']
for instance in response_list:
instance_info = instance['Instances'][0]
if instance_info['State']['Name'] == 'pending':
self.check_instance_state(instance_info['InstanceId'])
try:
if tag_values:
response = self.connection.describe_instances(**kw_args)
else:
response = self.connection.describe_instances()
except:
raise AWSConnectionError(title)
response_list = response['Reservations']
# populate list of instances with instance details
for instance in response_list:
instance_info = instance['Instances'][0]
state_name = instance_info['State']['Name']
if state_name not in ('shutting-down', 'terminated'):
instance_list.append(instance_info['InstanceId'])
# report results and return details
if instance_list:
print_out = 'Found instance'
if len(instance_list) > 1:
print_out += 's'
from labpack.parsing.grammar import join_words
print_out += ' %s.' % join_words(instance_list)
self.iam.printer(print_out)
else:
self.iam.printer('No instances found.')
return instance_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 read_instance(self, instance_id):
'''
a method to retrieving the details of a single instances on AWS EC2
:param instance_id: string of instance id on AWS
:return: dictionary with instance attributes
relevant fields:
'instance_id': '',
'image_id': '',
'instance_type': '',
'region': '',
'state': { 'name': '' },
'key_name': '',
'public_dns_name': '',
'public_ip_address': '',
'tags': [{'key': '', 'value': ''}]
'''
title = '%s.read_instance' % self.__class__.__name__
# validate inputs
input_fields = {
'instance_id': instance_id
}
for key, value in input_fields.items():
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
# report query
self.iam.printer('Querying AWS region %s for properties of instance %s.' % (self.iam.region_name, instance_id))
# check instance state
self.iam.printer_on = False
self.check_instance_state(instance_id)
self.iam.printer_on = True
# discover details associated with instance id
try:
response = self.connection.describe_instances(InstanceIds=[ instance_id ])
except:
raise AWSConnectionError(title)
instance_info = response['Reservations'][0]['Instances'][0]
# repeat request if any instances are currently pending
if instance_info['State']['Name'] == 'pending':
self.check_instance_state(instance_info['InstanceId'])
try:
response = self.connection.describe_instances(
InstanceIds=[ instance_id ]
)
except:
raise AWSConnectionError(title)
instance_info = response['Reservations'][0]['Instances'][0]
# create dictionary of instance details
instance_details = {
'instance_id': '',
'image_id': '',
'key_name': '',
'instance_type': '',
'region': self.iam.region_name,
'tags': [],
'public_ip_address': '',
'public_dns_name': '',
'security_groups': [],
'subnet_id': '',
'vpc_id': ''
}
instance_details = self.iam.ingest(instance_info, instance_details)
return instance_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 delete_instance(self, instance_id):
'''
method for removing an instance from AWS EC2
:param instance_id: string of instance id on AWS
:return: string reporting state of instance
'''
title = '%s.delete_instance' % self.__class__.__name__
# validate inputs
input_fields = {
'instance_id': instance_id
}
for key, value in input_fields.items():
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
# report query
self.iam.printer('Removing instance %s from AWS region %s.' % (instance_id, self.iam.region_name))
# retrieve state
old_state = self.check_instance_state(instance_id)
# discover tags associated with instance id
tag_list = []
try:
response = self.connection.describe_tags(
Filters=[ { 'Name': 'resource-id', 'Values': [ instance_id ] } ]
)
import re
aws_tag_pattern = re.compile('aws:')
for i in range(0, len(response['Tags'])):
if not aws_tag_pattern.findall(response['Tags'][i]['Key']):
tag = {}
tag['Key'] = response['Tags'][i]['Key']
tag['Value'] = response['Tags'][i]['Value']
tag_list.append(tag)
except:
raise AWSConnectionError(title)
# remove tags from instance
try:
self.connection.delete_tags(
Resources=[ instance_id ],
Tags=tag_list
)
self.iam.printer('Tags have been deleted from %s.' % instance_id)
except:
raise AWSConnectionError(title)
# stop instance
try:
self.connection.stop_instances(
InstanceIds=[ instance_id ]
)
except:
raise AWSConnectionError(title)
# terminate instance
try:
response = self.connection.terminate_instances(
InstanceIds=[ instance_id ]
)
new_state = response['TerminatingInstances'][0]['CurrentState']['Name']
except:
raise AWSConnectionError(title)
# report outcome and return true
self.iam.printer('Instance %s was %s.' % (instance_id, old_state))
self.iam.printer('Instance %s is %s.' % (instance_id, new_state))
return new_state |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list_images(self, tag_values=None):
'''
a method to retrieve the list of images of account on AWS EC2
:param tag_values: [optional] list of tag values
:return: list of image AWS ids
'''
title = '%s.list_images' % self.__class__.__name__
# validate inputs
input_fields = {
'tag_values': tag_values
}
for key, value in input_fields.items():
if value:
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
# add tags to method arguments
kw_args = { 'Owners': [ self.iam.owner_id ] }
tag_text = ''
if tag_values:
kw_args = {
'Filters': [ { 'Name': 'tag-value', 'Values': tag_values } ]
}
from labpack.parsing.grammar import join_words
plural_value = ''
if len(tag_values) > 1:
plural_value = 's'
tag_text = ' with tag value%s %s' % (plural_value, join_words(tag_values))
# request image details from AWS
self.iam.printer('Querying AWS region %s for images%s.' % (self.iam.region_name, tag_text))
image_list = []
try:
response = self.connection.describe_images(**kw_args)
except:
raise AWSConnectionError(title)
response_list = response['Images']
# repeat request
if not response_list:
from time import sleep
from timeit import default_timer as timer
self.iam.printer('No images found initially. Checking again', flush=True)
state_timeout = 0
delay = 3
while not response_list and state_timeout < 12:
self.iam.printer('.', flush=True)
sleep(delay)
t3 = timer()
try:
response = self.connection.describe_images(**kw_args)
except:
raise AWSConnectionError(title)
response_list = response['Images']
t4 = timer()
state_timeout += 1
response_time = t4 - t3
if 3 - response_time > 0:
delay = 3 - response_time
else:
delay = 0
self.iam.printer(' done.')
# wait until all images are no longer pending
for image in response_list:
image_list.append(image['ImageId'])
# report outcome and return results
if image_list:
print_out = 'Found image'
if len(image_list) > 1:
print_out += 's'
from labpack.parsing.grammar import join_words
print_out += ' %s.' % join_words(image_list)
self.iam.printer(print_out)
else:
self.iam.printer('No images found.')
return image_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 read_image(self, image_id):
'''
a method to retrieve the details of a single image on AWS EC2
:param image_id: string with AWS id of image
:return: dictionary of image attributes
relevant fields:
'image_id': '',
'snapshot_id': '',
'region': '',
'state': '',
'tags': []
'''
title = '%s.read_image' % self.__class__.__name__
# validate inputs
input_fields = {
'image_id': image_id
}
for key, value in input_fields.items():
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
# report query
self.iam.printer('Querying AWS region %s for properties of image %s.' % (self.iam.region_name, image_id))
# check image state
self.iam.printer_on = False
self.check_image_state(image_id)
self.iam.printer_on = True
# discover tags and snapshot id associated with image id
try:
response = self.connection.describe_images(ImageIds=[ image_id ])
except:
raise AWSConnectionError(title)
image_info = response['Images'][0]
# construct image details from response
image_details = {
'image_id': '',
'state': '',
'name': '',
'region': self.iam.region_name,
'tags': []
}
image_details = self.iam.ingest(image_info, image_details)
image_details['snapshot_id'] = image_details['block_device_mappings'][0]['ebs']['snapshot_id']
return image_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 delete_image(self, image_id):
'''
method for removing an image from AWS EC2
:param image_id: string with AWS id of instance
:return: string with AWS response from snapshot delete
'''
title = '%s.delete_image' % self.__class__.__name__
# validate inputs
input_fields = {
'image_id': image_id
}
for key, value in input_fields.items():
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
# report query
self.iam.printer('Removing image %s from AWS region %s.' % (image_id, self.iam.region_name))
# retrieve state
old_state = self.check_image_state(image_id)
# discover snapshot id and tags associated with instance id
image_details = self.read_image(image_id)
tag_list = image_details['tags']
snapshot_id = image_details['snapshot_id']
# remove tags from instance
try:
delete_kwargs = {
'Resources': [ image_id ],
'Tags': self.iam.prepare(tag_list)
}
self.connection.delete_tags(**delete_kwargs)
self.iam.printer('Tags have been deleted from %s.' % image_id)
except:
raise AWSConnectionError(title)
# deregister image
try:
self.connection.deregister_image(
ImageId=image_id
)
except:
raise AWSConnectionError(title)
self.iam.printer('Image %s has been deregistered.' % image_id)
# delete snapshot
try:
response = self.connection.delete_snapshot(
SnapshotId=snapshot_id
)
except:
raise AWSConnectionError(title)
self.iam.printer('Snapshot %s associated with image %s has been deleted.' % (snapshot_id, image_id))
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list_keypairs(self):
'''
a method to discover the list of key pairs on AWS
:return: list of key pairs
'''
title = '%s.list_keypairs' % self.__class__.__name__
# request subnet list from AWS
self.iam.printer('Querying AWS region %s for key pairs.' % self.iam.region_name)
keypair_list = []
try:
response = self.connection.describe_key_pairs()
except:
raise AWSConnectionError(title)
response_list = []
if 'KeyPairs' in response:
response_list = response['KeyPairs']
# construct list of keypairs from response
for sub_dict in response_list:
keypair_list.append(sub_dict['KeyName'])
# report results and return list
if keypair_list:
print_out = 'Found key pair'
if len(keypair_list) > 1:
print_out += 's'
from labpack.parsing.grammar import join_words
print_out += ' %s.' % join_words(keypair_list)
self.iam.printer(print_out)
else:
self.iam.printer('No key pairs found.')
return keypair_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 list_subnets(self, tag_values=None):
'''
a method to discover the list of subnets on AWS EC2
:param tag_values: [optional] list of tag values
:return: list of strings with subnet ids
'''
title = '%s.list_subnets' % self.__class__.__name__
# validate inputs
input_fields = {
'tag_values': tag_values
}
for key, value in input_fields.items():
if value:
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
# add tags to method arguments
kw_args = {}
tag_text = ''
if tag_values:
kw_args = {
'Filters': [ { 'Name': 'tag-value', 'Values': tag_values } ]
}
from labpack.parsing.grammar import join_words
plural_value = ''
if len(tag_values) > 1:
plural_value = 's'
tag_text = ' with tag value%s %s' % (plural_value, join_words(tag_values))
# request instance details from AWS
self.iam.printer('Querying AWS region %s for subnets%s.' % (self.iam.region_name, tag_text))
subnet_list = []
try:
if kw_args:
response = self.connection.describe_subnets(**kw_args)
else:
response = self.connection.describe_subnets()
except:
raise AWSConnectionError(title)
response_list = []
if 'Subnets' in response:
response_list = response['Subnets']
# construct list of subnets from response
for sub_dict in response_list:
subnet_list.append(sub_dict['SubnetId'])
# report results and return list
if subnet_list:
print_out = 'Found subnet'
if len(subnet_list) > 1:
print_out += 's'
from labpack.parsing.grammar import join_words
print_out += ' %s.' % join_words(subnet_list)
self.iam.printer(print_out)
else:
self.iam.printer('No subnets found.')
return subnet_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 read_subnet(self, subnet_id):
'''
a method to retrieve the details about a subnet
:param subnet_id: string with AWS id of subnet
:return: dictionary with subnet details
relevant fields:
'subnet_id': '',
'vpc_id': '',
'availability_zone': '',
'state': '',
'tags': [{'key': '', 'value': ''}]
'''
title = '%s.read_subnet' % self.__class__.__name__
# validate inputs
input_fields = {
'subnet_id': subnet_id
}
for key, value in input_fields.items():
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
# report query
self.iam.printer('Querying AWS region %s for properties of subnet %s.' % (self.iam.region_name, subnet_id))
# construct keyword definitions
kw_args = { 'SubnetIds': [ subnet_id ] }
# send request for details about subnet
try:
response = self.connection.describe_subnets(**kw_args)
except:
raise AWSConnectionError(title)
# construct subnet details from response
subnet_dict = response['Subnets'][0]
subnet_details = {
'subnet_id': '',
'vpc_id': '',
'availability_zone': '',
'state': '',
'tags': []
}
subnet_details = self.iam.ingest(subnet_dict, subnet_details)
return subnet_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 read_security_group(self, group_id):
'''
a method to retrieve the details about a security group
:param group_id: string with AWS id of security group
:return: dictionary with security group details
relevant fields:
'group_id: '',
'vpc_id': '',
'group_name': '',
'tags': [{'key': '', 'value': ''}]
'ip_permissions': [{
'from_port': 0,
'ip_ranges':[{'cidr_ip':'0.0.0.0/0'}]
}]
'''
title = '%s.read_security_group' % self.__class__.__name__
# validate inputs
input_fields = {
'group_id': group_id
}
for key, value in input_fields.items():
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
# report query
self.iam.printer('Querying AWS region %s for properties of security group %s.' % (self.iam.region_name, group_id))
# construct keyword definitions
kw_args = { 'GroupIds': [ group_id ] }
# send request for details about security group
try:
response = self.connection.describe_security_groups(**kw_args)
except:
raise AWSConnectionError(title)
# construct security group details from response
group_info = response['SecurityGroups'][0]
group_details = {
'group_id': '',
'vpc_id': '',
'group_name': '',
'tags': [],
'ip_permissions': []
}
group_details = self.iam.ingest(group_info, group_details)
return group_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 print_help(self, file=None):
""" recursively call all command parsers' helps """ |
output = file or self.stderr
CustomStderrOptionParser.print_help(self, output)
output.write("\nCommands:\n")
for command_def in self.command_definitions.values():
command_def.opt_parser.print_help(output)
output.write("\n") |
<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_groups(user):
"""Return the set of associated TenantGroups for the given user.""" |
if user.is_active and user.is_authenticated():
if user.is_superuser:
return TenantGroup.objects.all()
else:
return TenantGroup.objects.filter(tenantrole__user=user).distinct()
else:
return TenantGroup.objects.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_user_tenants(user, group):
"""Return the set of associated Tenants for the given user and group.""" |
if user.is_active and user.is_authenticated():
if user.is_superuser or is_group_manager(user, group.pk):
return Tenant.objects.filter(group=group)
else:
return Tenant.objects.filter(group=group, tenantrole__user=user).distinct()
else:
return Tenant.objects.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_user_roles(user):
"""Return a list of all of the user's roles.""" |
if not hasattr(user, '_role_cache'):
user._role_cache = list(TenantRole.objects.filter(user=user).values_list(
'group', 'role', 'tenant'))
return user._role_cache |
<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_group_manager(user, group=None):
"""Returns True if user is a group manager either for the group or any group.""" |
roles = get_user_roles(user)
return any(x[1] == TenantRole.ROLE_GROUP_MANAGER and (not group or x[0] == group) for x in roles) |
<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_instance(page_to_consume):
"""Return an instance of ConsumePage.""" |
global _instances
if isinstance(page_to_consume, basestring):
uri = page_to_consume
page_to_consume = page.get_instance(uri)
elif isinstance(page_to_consume, page.Page):
uri = page_to_consume.uri
else:
raise TypeError(
"get_instance() expects a parker.Page or basestring derivative."
)
page_to_consume.fetch()
parsed_page = parser.parse(page_to_consume)
try:
instance = _instances[uri]
except KeyError:
instance = ConsumePage(
parsed_page
)
_instances[uri] = instance
return instance |
<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_key_value_dict_by_selectors( self, key_selector, value_selector, value_sub_selector=None ):
"""Return a dictionary of key value data.""" |
key_nodes = self.parsedpage.get_nodes_by_selector(key_selector)
keys = [
self.parsedpage.get_text_from_node(node)
for node in key_nodes
]
value_nodes = self.parsedpage.get_nodes_by_selector(value_selector)
if value_sub_selector is not None:
vals = [
[
self.parsedpage.get_text_from_node(subnode)
for subnode in node.find(value_sub_selector)
]
for node in value_nodes.items()
]
else:
vals = [
self.parsedpage.get_text_from_node(node)
for node in value_nodes
]
return dict(zip(keys, vals)) |
<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_crumb_list_by_selector(self, crumb_selector):
"""Return a list of crumbs.""" |
return [
self.parsedpage.get_text_from_node(crumb)
for crumb in self.parsedpage.get_nodes_by_selector(crumb_selector)
] |
<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_media_list_by_selector( self, media_selector, media_attribute="src" ):
"""Return a list of media.""" |
page_url = urlparse.urlparse(self.uri)
return [
mediafile.get_instance(
urlparse.urljoin(
"%s://%s" % (
page_url.scheme,
page_url.netloc
),
urlparse.urlparse(
media.attrib[media_attribute],
scheme="http"
).geturl()
)
)
for media in self.parsedpage.get_nodes_by_selector(media_selector)
] |
<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_data_dict_from_config(self, config_dict):
"""Return a dictionary of data inferred from config_dict.""" |
return {
key: self.parsedpage.get_filtered_values_by_selector(
item_dict['selector'],
item_dict.get('regex_filter', None),
item_dict.get('regex_group', 1)
)
for key, item_dict in config_dict.iteritems()
if item_dict.get('selector', None) is not 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 generate_jobs(args, job_list, argument_string):
"""Generate actual scripts to be submitted to the cluster :param args: argparse argument collection :param job_list: dictionary containing each each job to be submitted :param argument_string: string containing general arguments to be used by mvtest.py during execution :return: None """ |
mvtest_path = args.mvpath
template = "".join(args.template.readlines())
logpath = os.path.abspath(args.logpath)
respath = os.path.abspath(args.res_path)
scriptpath = os.path.abspath(args.script_path)
pwd = os.path.abspath(os.getcwd())
for jobname in job_list.keys():
filename = "%s/%s.sh" % (scriptpath, jobname)
job_body = mvtest_path + " " + argument_string + " " + job_list[jobname]
contents = Template(template).safe_substitute(
logpath=logpath,
respath=respath,
body=job_body,
jobname=jobname,
memory=args.mem,
walltime=args.walltime,
pwd=pwd)
file = open(filename, "w")
print >> file,contents |
<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_template_file(args):
"""Returns valid template file, generating the default template file if it doesn't exist and one wasn't specified on command line. :param args: Argument collection as generated by parseargs :return file""" |
if args.template is None:
template_filename = os.getenv("HOME") + "/.mvmany.template"
try:
template_filename = open(template_filename, "r")
except:
with open(template_filename, "w") as file:
print >> file, """#SBATCH --job-name=$jobname
#SBATCH --nodes=1
#SBATCH --tasks-per-node=1
#SBATCH --cpus-per-task=1
#SBATCH --mem=$memory
#SBATCH --time=$walltime
#SBATCH --error $logpath/$jobname.e
#SBATCH --output $respath/$jobname.txt
cd $pwd
$body
"""
print >> sys.stderr, """PLEASE NOTE: \n
A default template file, %s, has been created. You are encouraged to configure it according to work with your cluster
management software or personalize it with email notifications, etc.\n"""
template_filename = open(template_filename, "r")
return template_filename |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_mach_jobs(args, filename):
"""Parse the MACH file and generate the list of jobs. :param args: Arguments from parseargs :param filename: name of file containing list of mach dosage files :return jobs to be run """ |
max_snp_count = args.snps_per_job
job_list = {}
cur = None
last_pos = None
job_string = ""
job_name = ""
mach_count = 1
if args.mach_count:
mach_count = args.mach_count
ExitIf("mvmany doesn't support splitting mach jobs into pieces at this time", max_snp_count > 1)
dosage_files = []
for line in open(filename):
dosage_files.append(line.strip().split("/")[-1].split(".")[0])
dosage_files.append(".".join(line.strip().split()[-1].split("/")[-1].split(".")[0:-1]))
file_count = len(dosage_files)
job_count = int(math.ceil(float(file_count) / mach_count))
for job_num in range(job_count):
job_idx = job_num * mach_count + 1
job_string = "--mach-count %d --mach-offset %d" % (mach_count, job_idx)
job_name = "job%04d-%s" % (job_num+1, dosage_files[job_idx - 1])
job_list[job_name] = job_string
return job_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 split_impute_jobs(args, filename):
"""Parse the IMPUTE file and generate the list of jobs. :param args: parsearg object containing command line arguments :filename args: file containing the IMPUTE gen files and chromosome numbers """ |
max_snp_count = args.snps_per_job
if args.impute_count:
impute_count = args.impute_count
else:
impute_count = 1
ExitIf("mvmany doesn't support splitting IMPUTE jobs into pieces at this time", max_snp_count > 1)
job_list = {}
gen_files = []
for line in open(filename):
gen_files.append(".".join(line.strip().split()[-1].split("/")[-1].split(".")[0:-1]))
file_count = len(gen_files)
job_count = int(math.ceil(float(file_count) / impute_count))
for job_num in range(job_count):
job_idx = job_num * impute_count + 1
job_string = "--impute-offset %d --impute-count %d" % (job_idx, impute_count)
job_name = "job%04d-%s" % (job_num+1, gen_files[job_idx -1])
job_list[job_name] = job_string
print job_string
return job_list
# For now, let's not deal with the complexity of splitting chromosomes in IMPUTE
poscol = 2
cur = None
last_pos = None
job_string = ""
job_name = ""
file_index = 0
for line in open(filename):
chr, genfile = line.strip().split()
if max_snp_count > 0:
locus_index = 0
last_pos = 1
for locus in open(genfile):
if locus_index >= max_snp_count - 1:
rsid, pos = locus.split()[1:2]
job_name = "chr%d_%d" % (chr, last_pos)
job_string = "--chr %s --from-bp %d --to-bp %d" % (chr, last_pos, pos)
last_pos = pos + 1
job_list[job_name] = job_string
locus_index = 0
if cur is None:
cur = pos
for line in sys_call("cut -f 1,%d %s" % (poscol, chrom_file)):
chrom, pos = [int(x) for x in line.split()]
if cur is None: # First line observed
cur = chrom
job_string = "--chr %d --from-bp %d" % (chrom, pos)
job_name = "Chr%d_%d-" % (chrom, pos)
snp_count = 0
elif cur != cur: # Changed chromosome
job_string += " --to-bp %d" % (last_pos)
job_name += str(last_pos)
job_list[job_name] = job_string
cur = chrom
job_string = "--chr %d --from-bp %d" % (chrom, pos)
job_name = "Chr%d_%d-" % (chrom, pos)
snp_count = 0
# create new job based on snp count
elif snp_count < max_snp_count:
snp_count += 1
else:
job_string += " --to-bp %d" % (last_pos)
job_name += str(last_pos)
job_list[job_name] = job_string
job_string = "--chr %d --from-bp" % (chrom, pos)
job_name = "Chr%d_%d-" % (chrom, pos)
snp_count = 0
last_pos = pos
if job_string != "":
job_string += " --to-bp %d" % (last_pos)
job_name += str(last_pos)
job_list[job_name] = job_string
return job_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 split_chrom_jobs(args, chrom_file):
"""Split up GWAS jobs based on portions of a chromosome :param args: arguments from parseargs :param chrom_file: marker info file :return dictionary name=>job_details """ |
max_snp_count = args.snps_per_job
poscol = 3
if args.map3:
poscol = 2
job_list = {}
cur = None
last_pos = None
job_string = ""
job_name = ""
for line in sys_call("cut -f 1,%d %s" % (poscol, chrom_file)):
pos = -1
values = line.split()
if len(values) > 0:
chrom, pos = [int(x) for x in values]
if cur is None: # First line observed
cur = chrom
job_string = "--chr %d --from-bp %d" % (chrom, pos)
job_name = "Chr%d_%d-" % (chrom, pos)
snp_count = 0
elif cur != cur: # Changed chromosome
job_string += " --to-bp %d" % (last_pos)
job_name += str(last_pos)
job_list[job_name] = job_string
cur = chrom
job_string = "--chr %d --from-bp %d" % (chrom, pos)
job_name = "Chr%d_%d-" % (chrom, pos)
snp_count = 0
# create new job based on snp count
elif snp_count < max_snp_count:
snp_count += 1
else:
job_string += " --to-bp %d" % (last_pos)
job_name += str(last_pos)
job_list[job_name] = job_string
job_string = "--chr %d --from-bp" % (chrom, pos)
job_name = "Chr%d_%d-" % (chrom, pos)
snp_count = 0
last_pos = pos
if job_string != "":
job_string += " --to-bp %d" % (last_pos)
job_name += str(last_pos)
job_list[job_name] = job_string
return job_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 diff(self, *args):
"""Call forward_mode; discard value, only keep the derivative.""" |
arg_dicts = self._parse_args_forward_mode(*args)
val, diff = self._forward_mode(*arg_dicts)
return diff |
<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_forward_mode_input_dict(self, var_tbl: dict) -> int: """ Check whether one forward mode input dict has elements of valid shape Returns inferred value of T """ |
T: int = 1
for var_name in var_tbl:
# The bound value to this variable name
val = var_tbl[var_name]
# case 1: this is a scalar; T=1
if isinstance(val, scalar_instance_types):
t = 1
# case 2: this is an array; calulate T
elif isinstance(val, np.ndarray):
t = self._calc_T_var(val)
#case 3: throw an error
else:
raise ValueError(f'val={val} in var_tbl; {type(val)} not a recognized value type.')
#update T
if t > 1 and T == 1:
T = t
elif t not in (1,T):
raise ValueError(f'Bound variable {var_name} has inconsistent shape')
return T |
<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_forward_mode_input_array(self, X: np.ndarray) -> int: """ Check whether one forward mode input array is of valid shape Returns inferred value of T """ |
# Find the length of each variable to infer T
if not isinstance(X, np.ndarray):
raise ValueError('X must be a numpy array, dict, or scalar')
# Get the shape and tensor rank
shape = X.shape
tensor_rank = len(shape)
T = 0
# Only 1D and 2D arrays are supported
if tensor_rank not in (0, 1, 2):
raise ValueError(f'Shape of X = {X.shape}. Numpy array must be a 1D vector or 2D matrix')
if tensor_rank == 0:
T = 1
# If the input was a 1D vector, its length must EITHER (1) be T, or (2) m, with T == 1
if tensor_rank == 1 and (shape[0] != self.m) and self.m != 1:
raise ValueError(f'Error: X has shape {X.shape}, incompatible with m = {self.m} on fluxion.')
# Return the value of T in this situation
if tensor_rank == 1 and shape[0] == self.m:
T = 1
if tensor_rank == 1 and self.m == 1:
T = shape[0]
# If the input was a 2D vector, it must be of shape Txn
if tensor_rank == 2 and (shape[1] != self.m):
raise ValueError(f'Error: X has shape {X.shape}, incompatible with m = {self.m} on fluxion.')
if tensor_rank == 2:
T = shape[0]
return T |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _calc_T_var(self,X) -> int: """Calculate the number of samples, T, from the shape of X""" |
shape = X.shape
tensor_rank: int = len(shape)
if tensor_rank == 0:
return 1
if tensor_rank == 1:
return shape[0]
if tensor_rank == 2:
if shape[1] > 1:
raise ValueError('Initial value of a variable must have dimension T*1.')
return shape[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 _forward_mode(self, *args):
"""Forward mode differentiation for a sum""" |
# (f+g)(x) = f(x) + g(x)
f_val, f_diff = self.f._forward_mode(*args)
g_val, g_diff = self.g._forward_mode(*args)
# The function value and derivative is the sum of f and g
val = f_val + g_val
diff = f_diff + g_diff
return val, diff |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _forward_mode(self, *args):
"""Forward mode differentiation for variables""" |
# Parse arguments into two numpy arrays
X: np.ndarray
dX: np.ndarray
X, dX = self._parse_dicts(*args)
# The value is X
if X is not None:
val = X
else:
val = self.X
# The derivative is the seed dX
if dX is not None:
diff = dX
else:
diff = np.ones_like(val)
# Return both arrays
return (val, diff) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run():
"""Command for applying upgrades.""" |
logfilename = os.path.join(current_app.config['CFG_LOGDIR'],
'invenio_upgrader.log')
upgrader = InvenioUpgrader()
logger = upgrader.get_logger(logfilename=logfilename)
try:
upgrades = upgrader.get_upgrades()
if not upgrades:
logger.info("All upgrades have been applied.")
return
logger.info("Following upgrade(s) will be applied:")
for u in upgrades:
logger.info(" * %s (%s)" % (u.name, u.info))
logger.info("Running pre-upgrade checks...")
upgrader.pre_upgrade_checks(upgrades)
logger.info("Calculating estimated upgrade time...")
estimate = upgrader.human_estimate(upgrades)
click.confirm(
"You are going to upgrade your installation "
"(estimated time: {0})!".format(estimate), abort=True)
for u in upgrades:
logger.info("Applying %s (%s)" % (u.name, u.info))
upgrader.apply_upgrade(u)
logger.info("Running post-upgrade checks...")
upgrader.post_upgrade_checks(upgrades)
if upgrader.has_warnings():
logger.warning("Upgrade completed with %s warnings - please check "
"log-file for further information:\nless %s"
% (upgrader.get_warnings_count(), logfilename))
else:
logger.info("Upgrade completed successfully.")
except RuntimeError as e:
for msg in e.args:
logger.error(unicode(msg))
logger.info("Please check log file for further information:\n"
"less %s" % logfilename)
click.Abort() |
<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():
"""Command for checking upgrades.""" |
upgrader = InvenioUpgrader()
logger = upgrader.get_logger()
try:
# Run upgrade pre-checks
upgrades = upgrader.get_upgrades()
# Check if there's anything to upgrade
if not upgrades:
logger.info("All upgrades have been applied.")
return
logger.info("Following upgrade(s) have not been applied yet:")
for u in upgrades:
logger.info(
" * {0} {1}".format(u.name, u.info))
logger.info("Running pre-upgrade checks...")
upgrader.pre_upgrade_checks(upgrades)
logger.info("Upgrade check successful - estimated time for upgrading"
" Invenio is %s..." % upgrader.human_estimate(upgrades))
except RuntimeError as e:
for msg in e.args:
logger.error(unicode(msg))
logger.error("Upgrade check failed. Aborting.")
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 pending():
"""Command for showing upgrades ready to be applied.""" |
upgrader = InvenioUpgrader()
logger = upgrader.get_logger()
try:
upgrades = upgrader.get_upgrades()
if not upgrades:
logger.info("All upgrades have been applied.")
return
logger.info("Following upgrade(s) are ready to be applied:")
for u in upgrades:
logger.info(
" * {0} {1}".format(u.name, u.info))
except RuntimeError as e:
for msg in e.args:
logger.error(unicode(msg))
raise |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.