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 check_version():
"""Sanity check version information for corrupt virtualenv symlinks """ |
if sys.version_info[0:3] == PYTHON_VERSION_INFO[0:3]:
return
sys.exit(
ansi.error() + ' your virtual env points to the wrong python version. '
'This is likely because you used a python installer that clobbered '
'the system installation, which breaks virtualenv creation. '
'To fix, check this symlink, and delete the installation of python '
'that it is brokenly pointing to, then delete the virtual env itself '
'and rerun lore install: ' + os.linesep + os.linesep + BIN_PYTHON +
os.linesep
) |
<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_requirements():
"""Make sure all listed packages from requirements.txt have been installed into the virtualenv at boot. """ |
if not os.path.exists(REQUIREMENTS):
sys.exit(
ansi.error() + ' %s is missing. Please check it in.' % ansi.underline(REQUIREMENTS)
)
with open(REQUIREMENTS, 'r', encoding='utf-8') as f:
dependencies = f.readlines()
vcs = [d for d in dependencies if re.match(r'^(-e )?(git|svn|hg|bzr).*', d)]
dependencies = list(set(dependencies) - set(vcs))
missing = []
try:
pkg_resources.require(dependencies)
except (
pkg_resources.ContextualVersionConflict,
pkg_resources.DistributionNotFound,
pkg_resources.VersionConflict
) as error:
missing.append(str(error))
except pkg_resources.RequirementParseError:
pass
if missing:
missing = ' missing requirement:\n ' + os.linesep.join(missing)
if '--env-checked' in sys.argv:
sys.exit(ansi.error() + missing + '\nRequirement installation failure, please check for errors in:\n $ lore install\n')
else:
print(ansi.warning() + missing)
import lore.__main__
lore.__main__.install_requirements(None)
reboot('--env-checked') |
<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_config(path):
"""Load a config from disk :param path: target config :type path: unicode :return: :rtype: configparser.Config """ |
if configparser is None:
return None
# Check for env specific configs first
if os.path.exists(os.path.join(ROOT, 'config', NAME, path)):
path = os.path.join(ROOT, 'config', NAME, path)
else:
path = os.path.join(ROOT, 'config', path)
if not os.path.isfile(path):
return None
conf = open(path, 'rt').read()
conf = os.path.expandvars(conf)
config = configparser.SafeConfigParser()
if sys.version_info[0] == 2:
from io import StringIO
config.readfp(StringIO(unicode(conf)))
else:
config.read_string(conf)
return config |
<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_version(path):
"""Attempts to read a python version string from a runtime.txt file :param path: to source of the string :return: python version :rtype: unicode or None """ |
version = None
if os.path.exists(path):
version = open(path, 'r', encoding='utf-8').read().strip()
if version:
return re.sub(r'^python-', '', version)
return version |
<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_installed_packages():
"""Idempotently caches the list of packages installed in the virtualenv. Can be run safely before the virtualenv is created, and will be rerun afterwards. """ |
global INSTALLED_PACKAGES, REQUIRED_VERSION
if INSTALLED_PACKAGES:
return
if os.path.exists(BIN_PYTHON):
pip = subprocess.Popen(
(BIN_PYTHON, '-m', 'pip', 'freeze'),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
(stdout, stderr) = pip.communicate()
pip.wait()
INSTALLED_PACKAGES = [r.decode().split('==')[0].lower() for r in stdout.split()]
REQUIRED_VERSION = next((package for package in INSTALLED_PACKAGES if re.match(r'^lore[!<>=]', package)), None)
if REQUIRED_VERSION:
REQUIRED_VERSION = re.split(r'[!<>=]', REQUIRED_VERSION)[-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 _force_https(self):
"""Redirect any non-https requests to https. Based largely on flask-sslify. """ |
if self.session_cookie_secure:
if not self.app.debug:
self.app.config['SESSION_COOKIE_SECURE'] = True
criteria = [
self.app.debug,
flask.request.is_secure,
flask.request.headers.get('X-Forwarded-Proto', 'http') == 'https',
]
local_options = self._get_local_options()
if local_options['force_https'] and not any(criteria):
if flask.request.url.startswith('http://'):
url = flask.request.url.replace('http://', 'https://', 1)
code = 302
if self.force_https_permanent:
code = 301
r = flask.redirect(url, code=code)
return r |
<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_response_headers(self, response):
"""Applies all configured headers to the given response.""" |
options = self._get_local_options()
self._set_feature_headers(response.headers, options)
self._set_frame_options_headers(response.headers, options)
self._set_content_security_policy_headers(response.headers, options)
self._set_hsts_headers(response.headers)
self._set_referrer_policy_headers(response.headers)
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 init_weapon_list():
"""Initialize the possible weapon combinations.""" |
twohand = []
for item in TWOHANDED_WEAPONS:
twohand.append([item])
onehand = []
for item in ONEHANDED_WEAPONS:
onehand.append([item])
shield = SHIELDS
dualwield_variations = []
weapon_shield_variations = []
for item in ONEHANDED_WEAPONS:
for i in ONEHANDED_WEAPONS:
dualwield_variations.append([item, i])
for j in shield:
weapon_shield_variations.append([j, item])
return twohand + onehand + dualwield_variations + weapon_shield_variations |
<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_sequence(seq, n):
"""Generates tokens of length n from a sequence. The last token may be of smaller length.""" |
tokens = []
while seq:
tokens.append(seq[:n])
seq = seq[n:]
return tokens |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grind_hash_for_weapon(hashcode):
""" Grinds the given hashcode for a weapon to draw on the pixelmap. Utilizes the second six characters from the hashcode.""" |
weaponlist = init_weapon_list()
# The second six characters of the hash
# control the weapon decision.
weapon_control = hashcode[ASPECT_CONTROL_LEN:(ASPECT_CONTROL_LEN * 2)]
# Decimal value of the hash chunk to map.
hash_dec_value = int(weapon_control, HEX_BASE)
decision = map_decision(MAX_DECISION_VALUE, len(weaponlist), hash_dec_value)
return choose_weapon(decision, weaponlist) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def choose_weapon(decision, weapons):
"""Chooses a weapon from a given list based on the decision.""" |
choice = []
for i in range(len(weapons)):
if (i < decision):
choice = weapons[i]
return choice |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def choose_aspect(decision):
"""Chooses a style from ASPECTSTYLES based on the decision.""" |
choice = []
for i in range(len(ASPECTSTYLES)):
if (i < decision):
choice = ASPECTSTYLES[i]
return choice |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hex2rgb(hexvalue):
"""Converts a given hex color to its respective rgb color.""" |
# Make sure a possible '#' char is eliminated
# before processing the color.
if ('#' in hexvalue):
hexcolor = hexvalue.replace('#', '')
else:
hexcolor = hexvalue
# Hex colors have a fixed length of 6 characters excluding the '#'
# TODO: Include custom exception here, even if it should never happen.
if (len(hexcolor) != 6):
print ("Unexpected length of hex color value.\nSix characters excluding \'#\' expected.")
return 0
# Convert each two characters of
# the hex to an RGB color value.
r = int(hexcolor[0:2], HEX_BASE)
g = int(hexcolor[2:4], HEX_BASE)
b = int(hexcolor[4:6], HEX_BASE)
return r, g, b |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index():
"""main functionality of webserver""" |
default = ["pagan", "python", "avatar", "github"]
slogan = request.forms.get("slogan")
if not slogan:
if request.get_cookie("hist1"):
slogan = request.get_cookie("hist1")
else:
slogan = "pagan"
if not request.get_cookie("hist1"):
hist1, hist2, hist3, hist4 = default[:]
else:
hist1 = request.get_cookie("hist1")
hist2 = request.get_cookie("hist2")
hist3 = request.get_cookie("hist3")
hist4 = request.get_cookie("hist4")
if slogan in (hist1, hist2, hist3, hist4):
history = [hist1, hist2, hist3, hist4]
history.remove(slogan)
hist1, hist2, hist3 = history[0], history[1], history[2]
response.set_cookie("hist1", slogan, max_age=60*60*24*30, httponly=True)
response.set_cookie("hist2", hist1, max_age=60*60*24*30, httponly=True)
response.set_cookie("hist3", hist2, max_age=60*60*24*30, httponly=True)
response.set_cookie("hist4", hist3, max_age=60*60*24*30, httponly=True)
# slogan, hist1, hist2, hist3 = escape(slogan), escape(hist1),\
# escape(hist2), escape(hist3)
md5 = hashlib.md5()
md5.update(slogan)
slogan_hash = md5.hexdigest()
md5.update(hist1)
hist1_hash = md5.hexdigest()
md5.update(hist2)
hist2_hash = md5.hexdigest()
md5.update(hist3)
hist3_hash = md5.hexdigest()
return template(TEMPLATEINDEX, slogan=slogan,
hist1=hist1, hist2=hist2, hist3=hist3,
sloganHash=slogan_hash, hist1Hash=hist1_hash,
hist2Hash=hist2_hash, hist3Hash=hist3_hash) |
<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_image(self, inpt, hashfun):
"""Creates the avatar based on the input and the chosen hash function.""" |
if hashfun not in generator.HASHES.keys():
print ("Unknown or unsupported hash function. Using default: %s"
% self.DEFAULT_HASHFUN)
algo = self.DEFAULT_HASHFUN
else:
algo = hashfun
return generator.generate(inpt, algo) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def change(self, inpt, hashfun=DEFAULT_HASHFUN):
"""Change the avatar by providing a new input. Uses the standard hash function if no one is given.""" |
self.img = self.__create_image(inpt, hashfun) |
<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_shield_deco_layer(weapons, ip):
'''Reads the SHIELD_DECO.pgn file and creates
the shield decal layer.'''
layer = []
if weapons[0] in hashgrinder.SHIELDS:
layer = pgnreader.parse_pagan_file(FILE_SHIELD_DECO, ip, invert=False, sym=False)
return layer |
<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_hair_layer(aspect, ip):
'''Reads the HAIR.pgn file and creates
the hair layer.'''
layer = []
if 'HAIR' in aspect:
layer = pgnreader.parse_pagan_file(FILE_HAIR, ip, invert=False, sym=True)
return layer |
<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_torso_layer(aspect, ip):
'''Reads the TORSO.pgn file and creates
the torso layer.'''
layer = []
if 'TOP' in aspect:
layer = pgnreader.parse_pagan_file(FILE_TORSO, ip, invert=False, sym=True)
return layer |
<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_subfield_layer(aspect, ip):
'''Reads the SUBFIELD.pgn file and creates
the subfield layer.'''
layer = []
if 'PANTS' in aspect:
layer = pgnreader.parse_pagan_file(FILE_SUBFIELD, ip, invert=False, sym=True)
else:
layer = pgnreader.parse_pagan_file(FILE_MIN_SUBFIELD, ip, invert=False, sym=True)
return layer |
<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_boots_layer(aspect, ip):
'''Reads the BOOTS.pgn file and creates
the boots layer.'''
layer = []
if 'BOOTS' in aspect:
layer = pgnreader.parse_pagan_file(FILE_BOOTS, ip, invert=False, sym=True)
return layer |
<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_shield_layer(shield, hashcode):
"""Creates the layer for shields.""" |
return pgnreader.parse_pagan_file(('%s%spgn%s' % (PACKAGE_DIR, os.sep, os.sep)) + shield + '.pgn', hashcode, sym=False, invert=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 create_weapon_layer(weapon, hashcode, isSecond=False):
"""Creates the layer for weapons.""" |
return pgnreader.parse_pagan_file(('%s%spgn%s' % (PACKAGE_DIR, os.sep, os.sep)) + weapon + '.pgn', hashcode, sym=False, invert=isSecond) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scale_pixels(color, layer):
"""Scales the pixel to the virtual pixelmap.""" |
pixelmap = []
# Scaling the pixel offsets.
for pix_x in range(MAX_X + 1):
for pix_y in range(MAX_Y + 1):
# Horizontal pixels
y1 = pix_y * dotsize[0]
x1 = pix_x * dotsize[1]
# Vertical pixels
y2 = pix_y * dotsize[0] + (dotsize[0] - 1)
x2 = pix_x * dotsize[1] + (dotsize[1] - 1)
if (y1 <= MAX_Y) and (y2 <= MAX_Y):
if (x1 <= MAX_X) and (x2 <= MAX_X):
if (pix_x, pix_y) in layer:
pixelmap.append([(y1, x1), (y2, x2), color])
return pixelmap |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def draw_image(pixelmap, img):
'''Draws the image based on the given pixelmap.'''
for item in pixelmap:
color = item[2]
# Access the rectangle edges.
pixelbox = (item[0][0], item[0][1], item[1][0], item[1][1])
draw = ImageDraw.Draw(img)
draw.rectangle(pixelbox, fill=color) |
<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_pixelmap(hashcode):
"""Creates and combines all required layers to build a pixelmap for creating the virtual pixels.""" |
# Color distribution.
# colors = hashgrinder.grindIpForColors(ip)
colors = hashgrinder.grind_hash_for_colors(hashcode)
color_body = colors[0]
color_subfield = colors[1]
color_weapon_a = colors[2]
color_weapon_b = colors[3]
color_shield_deco = colors[4]
color_boots = colors[5]
color_hair = colors[6]
color_top = colors[7]
# Grinds for the aspect.
aspect = hashgrinder.grind_hash_for_aspect(hashcode)
#Determine weapons of the avatar.
weapons = hashgrinder.grind_hash_for_weapon(hashcode)
if DEBUG:
print ("Current aspect: %r" % aspect)
print ("Current weapons: %r" % weapons)
# There is just one body template. The optional pixels need to be mirrored so
# the body layout will be symmetric to avoid uncanny looks.
layer_body = pgnreader.parse_pagan_file(FILE_BODY, hashcode, invert=False, sym=True)
layer_hair = create_hair_layer(aspect, hashcode)
layer_boots = create_boots_layer(aspect, hashcode)
layer_torso = create_torso_layer(aspect, hashcode)
has_shield = (weapons[0] in hashgrinder.SHIELDS)
if has_shield:
layer_weapon_a = create_shield_layer(weapons[0], hashcode)
layer_weapon_b = create_weapon_layer(weapons[1], hashcode)
else:
layer_weapon_a = create_weapon_layer(weapons[0], hashcode)
if (len(weapons) == 2):
layer_weapon_b = create_weapon_layer(weapons[1], hashcode, True)
layer_subfield = create_subfield_layer(aspect, hashcode)
layer_deco = create_shield_deco_layer(weapons, hashcode)
pixelmap = scale_pixels(color_body, layer_body)
pixelmap += scale_pixels(color_top, layer_torso)
pixelmap += scale_pixels(color_hair, layer_hair)
pixelmap += scale_pixels(color_subfield, layer_subfield)
pixelmap += scale_pixels(color_boots, layer_boots)
pixelmap += scale_pixels(color_weapon_a, layer_weapon_a)
if (len(weapons) == 2):
pixelmap += scale_pixels(color_weapon_b, layer_weapon_b)
pixelmap += scale_pixels(color_shield_deco, layer_deco)
return pixelmap |
<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(str, alg):
"""Generates an PIL image avatar based on the given input String. Acts as the main accessor to pagan.""" |
img = Image.new(IMAGE_MODE, IMAGE_SIZE, BACKGROUND_COLOR)
hashcode = hash_input(str, alg)
pixelmap = setup_pixelmap(hashcode)
draw_image(pixelmap, img)
return img |
<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_by_hash(hashcode):
"""Generates an PIL image avatar based on the given hash String. Acts as the main accessor to pagan.""" |
img = Image.new(IMAGE_MODE, IMAGE_SIZE, BACKGROUND_COLOR)
if len(hashcode) < 32:
print ("hashcode must have lenght >= 32, %s" % hashcode)
raise FalseHashError
allowed = "0123456789abcdef"
hashcheck = [c in allowed for c in hashcode]
if False in hashcheck:
print ("hashcode has not allowed structure %s" % hashcode)
raise FalseHashError
pixelmap = setup_pixelmap(hashcode)
draw_image(pixelmap, img)
return img |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def enforce_vertical_symmetry(pixmap):
'''Enforces vertical symmetry of the pixelmap.
Returns a pixelmap with all pixels mirrored in the middle.
The initial ones still remain.'''
mirror = []
for item in pixmap:
y = item[0]
x = item[1]
if x <= IMAGE_APEX:
diff_x = diff(x, IMAGE_APEX)
mirror.append((y, x + (2 * diff_x) - 1))
if x > IMAGE_APEX:
diff_x = diff(x, IMAGE_APEX)
mirror.append((y, x - (2 * diff_x) - 1))
return mirror + pixmap |
<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_types(text):
"""Chomp down company types to a more convention form.""" |
if not hasattr(replace_types, '_replacer'):
replace_types._replacer = build_replacer()
return replace_types._replacer(text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_strict(text, boundary=WS):
"""Super-hardcore string scrubbing.""" |
# transliterate to ascii
text = ascii_text(text)
# replace punctuation and symbols
text = CHARACTERS_REMOVE_RE.sub('', text)
text = category_replace(text)
# pad out for company type replacements
text = ''.join((boundary, collapse_spaces(text), boundary))
return text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def selfcheck(tools):
"""Audit the system for issues. :param tools: Tools description. Use elevation.TOOLS to test elevation. """ |
msg = []
for tool_name, check_cli in collections.OrderedDict(tools).items():
try:
subprocess.check_output(check_cli, shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
msg.append('%r not found or not usable.' % tool_name)
return '\n'.join(msg) if msg else 'Your system is ready.' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def seed(cache_dir=CACHE_DIR, product=DEFAULT_PRODUCT, bounds=None, max_download_tiles=9, **kwargs):
"""Seed the DEM to given bounds. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice. :param bounds: Output bounds in 'left bottom right top' order. :param max_download_tiles: Maximum number of tiles to process. :param kwargs: Pass additional kwargs to ensure_tiles. """ |
datasource_root, spec = ensure_setup(cache_dir, product)
ensure_tiles_names = list(spec['tile_names'](*bounds))
# FIXME: emergency hack to enforce the no-bulk-download policy
if len(ensure_tiles_names) > max_download_tiles:
raise RuntimeError("Too many tiles: %d. Please consult the providers' websites "
"for how to bulk download tiles." % len(ensure_tiles_names))
with util.lock_tiles(datasource_root, ensure_tiles_names):
ensure_tiles(datasource_root, ensure_tiles_names, **kwargs)
with util.lock_vrt(datasource_root, product):
util.check_call_make(datasource_root, targets=['all'])
return datasource_root |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clip(bounds, output=DEFAULT_OUTPUT, margin=MARGIN, **kwargs):
"""Clip the DEM to given bounds. :param bounds: Output bounds in 'left bottom right top' order. :param output: Path to output file. Existing files will be overwritten. :param margin: Decimal degree margin added to the bounds. Use '%' for percent margin. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice. """ |
bounds = build_bounds(bounds, margin=margin)
datasource_root = seed(bounds=bounds, **kwargs)
do_clip(datasource_root, bounds, output, **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 info(cache_dir=CACHE_DIR, product=DEFAULT_PRODUCT):
"""Show info about the product cache. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice. """ |
datasource_root, _ = ensure_setup(cache_dir, product)
util.check_call_make(datasource_root, targets=['info']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def new_oauth(yaml_path):
'''
Return the consumer and oauth tokens with three-legged OAuth process and
save in a yaml file in the user's home directory.
'''
print('Retrieve consumer key and consumer secret from http://www.tumblr.com/oauth/apps')
consumer_key = input('Paste the consumer key here: ').strip()
consumer_secret = input('Paste the consumer secret here: ').strip()
request_token_url = 'http://www.tumblr.com/oauth/request_token'
authorize_url = 'http://www.tumblr.com/oauth/authorize'
access_token_url = 'http://www.tumblr.com/oauth/access_token'
# STEP 1: Obtain request token
oauth_session = OAuth1Session(consumer_key, client_secret=consumer_secret)
fetch_response = oauth_session.fetch_request_token(request_token_url)
resource_owner_key = fetch_response.get('oauth_token')
resource_owner_secret = fetch_response.get('oauth_token_secret')
# STEP 2: Authorize URL + Rresponse
full_authorize_url = oauth_session.authorization_url(authorize_url)
# Redirect to authentication page
print('\nPlease go here and authorize:\n{}'.format(full_authorize_url))
redirect_response = input('Allow then paste the full redirect URL here:\n').strip()
# Retrieve oauth verifier
oauth_response = oauth_session.parse_authorization_response(redirect_response)
verifier = oauth_response.get('oauth_verifier')
# STEP 3: Request final access token
oauth_session = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
resource_owner_key=resource_owner_key,
resource_owner_secret=resource_owner_secret,
verifier=verifier
)
oauth_tokens = oauth_session.fetch_access_token(access_token_url)
tokens = {
'consumer_key': consumer_key,
'consumer_secret': consumer_secret,
'oauth_token': oauth_tokens.get('oauth_token'),
'oauth_token_secret': oauth_tokens.get('oauth_token_secret')
}
yaml_file = open(yaml_path, 'w+')
yaml.dump(tokens, yaml_file, indent=2)
yaml_file.close()
return tokens |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_params(valid_options, params):
""" Helps us validate the parameters for the request :param valid_options: a list of strings of valid options for the api request :param params: a dict, the key-value store which we really only care about the key which has tells us what the user is using for the API request :returns: None or throws an exception if the validation fails """ |
#crazy little if statement hanging by himself :(
if not params:
return
#We only allow one version of the data parameter to be passed
data_filter = ['data', 'source', 'external_url', 'embed']
multiple_data = [key for key in params.keys() if key in data_filter]
if len(multiple_data) > 1:
raise Exception("You can't mix and match data parameters")
#No bad fields which are not in valid options can pass
disallowed_fields = [key for key in params.keys() if key not in valid_options]
if disallowed_fields:
field_strings = ",".join(disallowed_fields)
raise Exception("{} are not allowed fields".format(field_strings)) |
<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(self, url, params):
""" Issues a GET request against the API, properly formatting the params :param url: a string, the url you are requesting :param params: a dict, the key-value of all the paramaters needed in the request :returns: a dict parsed of the JSON response """ |
url = self.host + url
if params:
url = url + "?" + urllib.parse.urlencode(params)
try:
resp = requests.get(url, allow_redirects=False, headers=self.headers, auth=self.oauth)
except TooManyRedirects as e:
resp = e.response
return self.json_parse(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post(self, url, params={}, files=[]):
""" Issues a POST request against the API, allows for multipart data uploads :param url: a string, the url you are requesting :param params: a dict, the key-value of all the parameters needed in the request :param files: a list, the list of tuples of files :returns: a dict parsed of the JSON response """ |
url = self.host + url
try:
if files:
return self.post_multipart(url, params, files)
else:
data = urllib.parse.urlencode(params)
if not PY3:
data = str(data)
resp = requests.post(url, data=data, headers=self.headers, auth=self.oauth)
return self.json_parse(resp)
except HTTPError as e:
return self.json_parse(e.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 json_parse(self, response):
""" Wraps and abstracts response validation and JSON parsing to make sure the user gets the correct response. :param response: The response returned to us from the request :returns: a dict of the json response """ |
try:
data = response.json()
except ValueError:
data = {'meta': { 'status': 500, 'msg': 'Server Error'}, 'response': {"error": "Malformed JSON or HTML was returned."}}
# We only really care about the response if we succeed
# and the error if we fail
if 200 <= data['meta']['status'] <= 399:
return data['response']
else:
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_multipart(self, url, params, files):
""" Generates and issues a multipart request for data files :param url: a string, the url you are requesting :param params: a dict, a key-value of all the parameters :param files: a dict, matching the form '{name: file descriptor}' :returns: a dict parsed from the JSON response """ |
resp = requests.post(
url,
data=params,
params=params,
files=files,
headers=self.headers,
allow_redirects=False,
auth=self.oauth
)
return self.json_parse(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def avatar(self, blogname, size=64):
""" Retrieves the url of the blog's avatar :param blogname: a string, the blog you want the avatar for :returns: A dict created from the JSON response """ |
url = "/v2/blog/{}/avatar/{}".format(blogname, size)
return self.send_api_request("get", 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 tagged(self, tag, **kwargs):
""" Gets a list of posts tagged with the given tag :param tag: a string, the tag you want to look for :param before: a unix timestamp, the timestamp you want to start at to look at posts. :param limit: the number of results you want :param filter: the post format that you want returned: html, text, raw client.tagged("gif", limit=10) :returns: a dict created from the JSON response """ |
kwargs.update({'tag': tag})
return self.send_api_request("get", '/v2/tagged', kwargs, ['before', 'limit', 'filter', 'tag', 'api_key'], 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 posts(self, blogname, type=None, **kwargs):
""" Gets a list of posts from a particular blog :param blogname: a string, the blogname you want to look up posts for. eg: codingjester.tumblr.com :param id: an int, the id of the post you are looking for on the blog :param tag: a string, the tag you are looking for on posts :param limit: an int, the number of results you want :param offset: an int, the offset of the posts you want to start at. :param before: an int, the timestamp for posts you want before. :param filter: the post format you want returned: HTML, text or raw. :param type: the type of posts you want returned, e.g. video. If omitted returns all post types. :returns: a dict created from the JSON response """ |
if type is None:
url = '/v2/blog/{}/posts'.format(blogname)
else:
url = '/v2/blog/{}/posts/{}'.format(blogname, type)
return self.send_api_request("get", url, kwargs, ['id', 'tag', 'limit', 'offset', 'before', 'reblog_info', 'notes_info', 'filter', 'api_key'], 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 blog_info(self, blogname):
""" Gets the information of the given blog :param blogname: the name of the blog you want to information on. eg: codingjester.tumblr.com :returns: a dict created from the JSON response of information """ |
url = "/v2/blog/{}/info".format(blogname)
return self.send_api_request("get", url, {}, ['api_key'], 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 blog_following(self, blogname, **kwargs):
""" Gets the publicly exposed list of blogs that a blog follows :param blogname: the name of the blog you want to get information on. eg: codingjester.tumblr.com :param limit: an int, the number of blogs you want returned :param offset: an int, the blog to start at, for pagination. # Start at the 20th blog and get 20 more blogs. client.blog_following('pytblr', offset=20, limit=20}) :returns: a dict created from the JSON response """ |
url = "/v2/blog/{}/following".format(blogname)
return self.send_api_request("get", url, kwargs, ['limit', 'offset']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def like(self, id, reblog_key):
""" Like the post of the given blog :param id: an int, the id of the post you want to like :param reblog_key: a string, the reblog key of the post :returns: a dict created from the JSON response """ |
url = "/v2/user/like"
params = {'id': id, 'reblog_key': reblog_key}
return self.send_api_request("post", url, params, ['id', 'reblog_key']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unlike(self, id, reblog_key):
""" Unlike the post of the given blog :param id: an int, the id of the post you want to like :param reblog_key: a string, the reblog key of the post :returns: a dict created from the JSON response """ |
url = "/v2/user/unlike"
params = {'id': id, 'reblog_key': reblog_key}
return self.send_api_request("post", url, params, ['id', 'reblog_key']) |
<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_photo(self, blogname, **kwargs):
""" Create a photo post or photoset on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param caption: a string, the caption that you want applied to the photo :param link: a string, the 'click-through' url you want on the photo :param source: a string, the photo source url :param data: a string or a list of the path of photo(s) :returns: a dict created from the JSON response """ |
kwargs.update({"type": "photo"})
return self._send_post(blogname, 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 create_text(self, blogname, **kwargs):
""" Create a text post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param title: a string, the optional title of a post :param body: a string, the body of the text post :returns: a dict created from the JSON response """ |
kwargs.update({"type": "text"})
return self._send_post(blogname, 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 create_quote(self, blogname, **kwargs):
""" Create a quote post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param quote: a string, the full text of the quote :param source: a string, the cited source of the quote :returns: a dict created from the JSON response """ |
kwargs.update({"type": "quote"})
return self._send_post(blogname, 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 create_link(self, blogname, **kwargs):
""" Create a link post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param title: a string, the title of the link :param url: a string, the url of the link you are posting :param description: a string, the description of the link you are posting :returns: a dict created from the JSON response """ |
kwargs.update({"type": "link"})
return self._send_post(blogname, 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 create_chat(self, blogname, **kwargs):
""" Create a chat post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a string, the GMT date and time of the post :param format: a string, sets the format type of the post. html or markdown :param slug: a string, a short text summary to the end of the post url :param title: a string, the title of the conversation :param conversation: a string, the conversation you are posting :returns: a dict created from the JSON response """ |
kwargs.update({"type": "chat"})
return self._send_post(blogname, 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 reblog(self, blogname, **kwargs):
""" Creates a reblog on the given blogname :param blogname: a string, the url of the blog you want to reblog to :param id: an int, the post id that you are reblogging :param reblog_key: a string, the reblog key of the post :param comment: a string, a comment added to the reblogged post :returns: a dict created from the JSON response """ |
url = "/v2/blog/{}/post/reblog".format(blogname)
valid_options = ['id', 'reblog_key', 'comment'] + self._post_valid_options(kwargs.get('type', None))
if 'tags' in kwargs and kwargs['tags']:
# Take a list of tags and make them acceptable for upload
kwargs['tags'] = ",".join(kwargs['tags'])
return self.send_api_request('post', url, kwargs, valid_options) |
<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_post(self, blogname, id):
""" Deletes a post with the given id :param blogname: a string, the url of the blog you want to delete from :param id: an int, the post id that you want to delete :returns: a dict created from the JSON response """ |
url = "/v2/blog/{}/post/delete".format(blogname)
return self.send_api_request('post', url, {'id': id}, ['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 _send_post(self, blogname, params):
""" Formats parameters and sends the API request off. Validates common and per-post-type parameters and formats your tags for you. :param blogname: a string, the blogname of the blog you are posting to :param params: a dict, the key-value of the parameters for the api request :param valid_options: a list of valid options that the request allows :returns: a dict parsed from the JSON response """ |
url = "/v2/blog/{}/post".format(blogname)
valid_options = self._post_valid_options(params.get('type', None))
if len(params.get("tags", [])) > 0:
# Take a list of tags and make them acceptable for upload
params['tags'] = ",".join(params['tags'])
return self.send_api_request("post", url, params, valid_options) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_api_request(self, method, url, params={}, valid_parameters=[], needs_api_key=False):
""" Sends the url with parameters to the requested url, validating them to make sure that they are what we expect to have passed to us :param method: a string, the request method you want to make :param params: a dict, the parameters used for the API request :param valid_parameters: a list, the list of valid parameters :param needs_api_key: a boolean, whether or not your request needs an api key injected :returns: a dict parsed from the JSON response """ |
if needs_api_key:
params.update({'api_key': self.request.consumer_key})
valid_parameters.append('api_key')
files = {}
if 'data' in params:
if isinstance(params['data'], list):
for idx, data in enumerate(params['data']):
files['data['+str(idx)+']'] = open(params['data'][idx], 'rb')
else:
files = {'data': open(params['data'], 'rb')}
del params['data']
validate_params(valid_parameters, params)
if method == "get":
return self.request.get(url, params)
else:
return self.request.post(url, params, files) |
<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(path, code=None, params=None, **meta):
"""MCCabe code checking. :return list: List of errors. """ |
tree = compile(code, path, "exec", ast.PyCF_ONLY_AST)
McCabeChecker.max_complexity = int(params.get('complexity', 10))
return [
{'lnum': lineno, 'offset': offset, 'text': text, 'type': McCabeChecker._code}
for lineno, offset, text, _ in McCabeChecker(tree, path).run()
] |
<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_csp_str(val):
""" Split comma separated string into unique values, keeping their order. :returns: list of splitted values """ |
seen = set()
values = val if isinstance(val, (list, tuple)) else val.strip().split(',')
return [x for x in values if x and not (x in seen or seen.add(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 parse_linters(linters):
""" Initialize choosen linters. :returns: list of inited linters """ |
result = list()
for name in split_csp_str(linters):
linter = LINTERS.get(name)
if linter:
result.append((name, linter))
else:
logging.warning("Linter `%s` not found.", name)
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 get_default_config_file(rootdir=None):
"""Search for configuration file.""" |
if rootdir is None:
return DEFAULT_CONFIG_FILE
for path in CONFIG_FILES:
path = os.path.join(rootdir, path)
if os.path.isfile(path) and os.access(path, os.R_OK):
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 parse_options(args=None, config=True, rootdir=CURDIR, **overrides):
# noqa """ Parse options from command line and configuration files. :return argparse.Namespace: """ |
args = args or []
# Parse args from command string
options = PARSER.parse_args(args)
options.file_params = dict()
options.linters_params = dict()
# Compile options from ini
if config:
cfg = get_config(str(options.options), rootdir=rootdir)
for opt, val in cfg.default.items():
LOGGER.info('Find option %s (%s)', opt, val)
passed_value = getattr(options, opt, _Default())
if isinstance(passed_value, _Default):
if opt == 'paths':
val = val.split()
if opt == 'skip':
val = fix_pathname_sep(val)
setattr(options, opt, _Default(val))
# Parse file related options
for name, opts in cfg.sections.items():
if name == cfg.default_section:
continue
if name.startswith('pylama'):
name = name[7:]
if name in LINTERS:
options.linters_params[name] = dict(opts)
continue
mask = re.compile(fnmatch.translate(fix_pathname_sep(name)))
options.file_params[mask] = dict(opts)
# Override options
_override_options(options, **overrides)
# Postprocess options
for name in options.__dict__:
value = getattr(options, name)
if isinstance(value, _Default):
setattr(options, name, process_value(name, value.value))
if options.concurrent and 'pylint' in options.linters:
LOGGER.warning('Can\'t parse code asynchronously with pylint enabled.')
options.concurrent = False
return options |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _override_options(options, **overrides):
"""Override options.""" |
for opt, val in overrides.items():
passed_value = getattr(options, opt, _Default())
if opt in ('ignore', 'select') and passed_value:
value = process_value(opt, passed_value.value)
value += process_value(opt, val)
setattr(options, opt, value)
elif isinstance(passed_value, _Default):
setattr(options, opt, process_value(opt, 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 process_value(name, value):
""" Compile option value. """ |
action = ACTIONS.get(name)
if not action:
return value
if callable(action.type):
return action.type(value)
if action.const:
return bool(int(value))
return 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_config(ini_path=None, rootdir=None):
""" Load configuration from INI. :return Namespace: """ |
config = Namespace()
config.default_section = 'pylama'
if not ini_path:
path = get_default_config_file(rootdir)
if path:
config.read(path)
else:
config.read(ini_path)
return config |
<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_logger(options):
"""Do the logger setup with options.""" |
LOGGER.setLevel(logging.INFO if options.verbose else logging.WARN)
if options.report:
LOGGER.removeHandler(STREAM)
LOGGER.addHandler(logging.FileHandler(options.report, mode='w'))
if options.options:
LOGGER.info('Try to read configuration from: %r', options.options) |
<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(path, code=None, params=None, **meta):
"""Check code with pyflakes. :return list: List of errors. """ |
import _ast
builtins = params.get("builtins", "")
if builtins:
builtins = builtins.split(",")
tree = compile(code, path, "exec", _ast.PyCF_ONLY_AST)
w = checker.Checker(tree, path, builtins=builtins)
w.messages = sorted(w.messages, key=lambda m: m.lineno)
return [{
'lnum': m.lineno,
'text': m.message % m.message_args,
'type': m.message[0]
} for m in w.messages] |
<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_path(options, rootdir=None, candidates=None, code=None):
"""Check path. :param rootdir: Root directory (for making relative file paths) :param options: Parsed pylama options (from pylama.config.parse_options) :returns: (list) Errors list """ |
if not candidates:
candidates = []
for path_ in options.paths:
path = op.abspath(path_)
if op.isdir(path):
for root, _, files in walk(path):
candidates += [op.relpath(op.join(root, f), CURDIR)
for f in files]
else:
candidates.append(path)
if rootdir is None:
rootdir = path if op.isdir(path) else op.dirname(path)
paths = []
for path in candidates:
if not options.force and not any(l.allow(path)
for _, l in options.linters):
continue
if not op.exists(path):
continue
paths.append(path)
if options.concurrent:
return check_async(paths, options, rootdir)
errors = []
for path in paths:
errors += run(path=path, code=code, rootdir=rootdir, options=options)
return errors |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shell(args=None, error=True):
"""Endpoint for console. Parse a command arguments, configuration files and run a checkers. :return list: list of errors :raise SystemExit: """ |
if args is None:
args = sys.argv[1:]
options = parse_options(args)
setup_logger(options)
LOGGER.info(options)
# Install VSC hook
if options.hook:
from .hook import install_hook
for path in options.paths:
return install_hook(path)
return process_paths(options, error=error) |
<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_paths(options, candidates=None, error=True):
"""Process files and log errors.""" |
errors = check_path(options, rootdir=CURDIR, candidates=candidates)
if options.format in ['pycodestyle', 'pep8']:
pattern = "%(filename)s:%(lnum)s:%(col)s: %(text)s"
elif options.format == 'pylint':
pattern = "%(filename)s:%(lnum)s: [%(type)s] %(text)s"
else: # 'parsable'
pattern = "%(filename)s:%(lnum)s:%(col)s: [%(type)s] %(text)s"
for er in errors:
if options.abspath:
er._info['filename'] = op.abspath(er.filename)
LOGGER.warning(pattern, er._info)
if error:
sys.exit(int(bool(errors)))
return errors |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset(self, source):
""" Reset scanner's state. :param source: Source for parsing """ |
self.tokens = []
self.source = source
self.pos = 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 scan(self):
""" Scan source and grab tokens. """ |
self.pre_scan()
token = None
end = len(self.source)
while self.pos < end:
best_pat = None
best_pat_len = 0
# Check patterns
for p, regexp in self.patterns:
m = regexp.match(self.source, self.pos)
if m:
best_pat = p
best_pat_len = len(m.group(0))
break
if best_pat is None:
raise SyntaxError(
"SyntaxError[@char {0}: {1}]".format(
self.pos, "Bad token."))
# Ignore patterns
if best_pat in self.ignore:
self.pos += best_pat_len
continue
# Create token
token = (
best_pat,
self.source[self.pos:self.pos + best_pat_len],
self.pos,
self.pos + best_pat_len,
)
self.pos = token[-1]
self.tokens.append(token) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pre_scan(self):
""" Prepare string for scanning. """ |
escape_re = re.compile(r'\\\n[\t ]+')
self.source = escape_re.sub('', self.source) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iteritems(self, raw=False):
""" Iterate self items. """ |
for key in self:
yield key, self.__getitem__(key, raw=raw) |
<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(self, *files, **params):
""" Read and parse INI files. :param *files: Files for reading :param **params: Params for parsing Set `update=False` for prevent values redefinition. """ |
for f in files:
try:
with io.open(f, encoding='utf-8') as ff:
NS_LOGGER.info('Read from `{0}`'.format(ff.name))
self.parse(ff.read(), **params)
except (IOError, TypeError, SyntaxError, io.UnsupportedOperation):
if not self.silent_read:
NS_LOGGER.error('Reading error `{0}`'.format(ff.name))
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 write(self, f):
""" Write namespace as INI file. :param f: File object or path to file. """ |
if isinstance(f, str):
f = io.open(f, 'w', encoding='utf-8')
if not hasattr(f, 'read'):
raise AttributeError("Wrong type of file: {0}".format(type(f)))
NS_LOGGER.info('Write to `{0}`'.format(f.name))
for section in self.sections.keys():
f.write('[{0}]\n'.format(section))
for k, v in self[section].items():
f.write('{0:15}= {1}\n'.format(k, v))
f.write('\n')
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 parse(self, source, update=True, **params):
""" Parse INI source as string. :param source: Source of INI :param update: Replace already defined items """ |
scanner = INIScanner(source)
scanner.scan()
section = self.default_section
name = None
for token in scanner.tokens:
if token[0] == 'KEY_VALUE':
name, value = re.split('[=:]', token[1], 1)
name, value = name.strip(), value.strip()
if not update and name in self[section]:
continue
self[section][name] = value
elif token[0] == 'SECTION':
section = token[1].strip('[]')
elif token[0] == 'CONTINUATION':
if not name:
raise SyntaxError(
"SyntaxError[@char {0}: {1}]".format(
token[2], "Bad continuation."))
self[section][name] += '\n' + token[1].strip() |
<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_modeline(code):
"""Parse params from file's modeline. :return dict: Linter params. """ |
seek = MODELINE_RE.search(code)
if seek:
return dict(v.split('=') for v in seek.group(1).split(':'))
return dict() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_params(modeline, fileconfig, options):
"""Prepare and merge a params from modelines and configs. :return dict: """ |
params = dict(skip=False, ignore=[], select=[], linters=[])
if options:
params['ignore'] = list(options.ignore)
params['select'] = list(options.select)
for config in filter(None, [modeline, fileconfig]):
for key in ('ignore', 'select', 'linters'):
params[key] += process_value(key, config.get(key, []))
params['skip'] = bool(int(config.get('skip', False)))
# TODO: skip what? This is causing erratic behavior for linters.
params['skip'] = False
params['ignore'] = set(params['ignore'])
params['select'] = set(params['select'])
return params |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_errors(errors, select=None, ignore=None, **params):
"""Filter errors by select and ignore options. :return bool: """ |
select = select or []
ignore = ignore or []
for e in errors:
for s in select:
if e.number.startswith(s):
yield e
break
else:
for s in ignore:
if e.number.startswith(s):
break
else:
yield e |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_skiplines(code, errors):
"""Filter lines by `noqa`. :return list: A filtered errors """ |
if not errors:
return errors
enums = set(er.lnum for er in errors)
removed = set([
num for num, l in enumerate(code.split('\n'), 1)
if num in enums and SKIP_PATTERN(l)
])
if removed:
errors = [er for er in errors if er.lnum not in removed]
return errors |
<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_async(paths, options, rootdir=None):
"""Check given paths asynchronously. :return list: list of errors """ |
LOGGER.info('Async code checking is enabled.')
path_queue = Queue.Queue()
result_queue = Queue.Queue()
for num in range(CPU_COUNT):
worker = Worker(path_queue, result_queue)
worker.setDaemon(True)
LOGGER.info('Start worker #%s', (num + 1))
worker.start()
for path in paths:
path_queue.put((path, dict(options=options, rootdir=rootdir)))
path_queue.join()
errors = []
while True:
try:
errors += result_queue.get(False)
except Queue.Empty:
break
return errors |
<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):
""" Run tasks from queue. """ |
while True:
path, params = self.path_queue.get()
errors = run(path, **params)
self.result_queue.put(errors)
self.path_queue.task_done() |
<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(self, line):
"""Parse the output line""" |
try:
result = line.split(':', maxsplit=4)
filename, line_num_txt, column_txt, message_type, text = result
except ValueError:
return
try:
self.line_num = int(line_num_txt.strip())
self.column = int(column_txt.strip())
except ValueError:
return
self.filename = filename
self.message_type = message_type.strip()
self.text = text.strip()
self.valid = 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 to_result(self):
"""Convert to the Linter.run return value""" |
text = [self.text]
if self.note:
text.append(self.note)
return {
'lnum': self.line_num,
'col': self.column,
'text': ' - '.join(text),
'type': self.types.get(self.message_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 run(path, code=None, params=None, **meta):
"""Check code with mypy. :return list: List of errors. """ |
args = [path, '--follow-imports=skip', '--show-column-numbers']
stdout, stderr, status = api.run(args)
messages = []
for line in stdout.split('\n'):
line.strip()
if not line:
continue
message = _MyPyMessage(line)
if message.valid:
if message.message_type == 'note':
if messages[-1].line_num == message.line_num:
messages[-1].add_note(message.text)
else:
messages.append(message)
return [m.to_result() for m in messages] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_value(value):
"""Prepare value to pylint.""" |
if isinstance(value, (list, tuple, set)):
return ",".join(value)
if isinstance(value, bool):
return "y" if value else "n"
return str(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(path, code=None, params=None, **meta):
"""Check code with pycodestyle. :return list: List of errors. """ |
parser = get_parser()
for option in parser.option_list:
if option.dest and option.dest in params:
value = params[option.dest]
if isinstance(value, str):
params[option.dest] = option.convert_value(option, value)
for key in ["filename", "exclude", "select", "ignore"]:
if key in params and isinstance(params[key], str):
params[key] = _parse_multi_options(params[key])
P8Style = StyleGuide(reporter=_PycodestyleReport, **params)
buf = StringIO(code)
return P8Style.input_file(path, lines=buf.readlines()) |
<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_file(self, filename, lines, expected, line_offset):
"""Prepare storage for errors.""" |
super(_PycodestyleReport, self).init_file(
filename, lines, expected, line_offset)
self.errors = [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error(self, line_number, offset, text, check):
"""Save errors.""" |
code = super(_PycodestyleReport, self).error(
line_number, offset, text, check)
if code:
self.errors.append(dict(
text=text,
type=code.replace('E', 'C'),
col=offset + 1,
lnum=line_number,
)) |
<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(path, code=None, params=None, **meta):
"""pydocstyle code checking. :return list: List of errors. """ |
if 'ignore_decorators' in params:
ignore_decorators = params['ignore_decorators']
else:
ignore_decorators = None
check_source_args = (code, path, ignore_decorators) if THIRD_ARG else (code, path)
return [{
'lnum': e.line,
# Remove colon after error code ("D403: ..." => "D403 ...").
'text': (e.message[0:4] + e.message[5:]
if e.message[4] == ':' else e.message),
'type': 'D',
'number': e.code
} for e in PyDocChecker().check_source(*check_source_args)] |
<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(path, code=None, params=None, ignore=None, select=None, **meta):
"""Check code with Radon. :return list: List of errors. """ |
complexity = params.get('complexity', 10)
no_assert = params.get('no_assert', False)
show_closures = params.get('show_closures', False)
visitor = ComplexityVisitor.from_code(code, no_assert=no_assert)
blocks = visitor.blocks
if show_closures:
blocks = add_inner_blocks(blocks)
return [
{'lnum': block.lineno, 'col': block.col_offset, 'type': 'R', 'number': 'R709',
'text': 'R701: %s is too complex %d' % (block.name, block.complexity)}
for block in visitor.blocks if block.complexity > complexity
] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def git_hook(error=True):
"""Run pylama after git commit.""" |
_, files_modified, _ = run("git diff-index --cached --name-only HEAD")
options = parse_options()
setup_logger(options)
if sys.version_info >= (3,):
candidates = [f.decode('utf-8') for f in files_modified]
else:
candidates = [str(f) for f in files_modified]
if candidates:
process_paths(options, candidates=candidates, error=error) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hg_hook(ui, repo, node=None, **kwargs):
"""Run pylama after mercurial commit.""" |
seen = set()
paths = []
if len(repo):
for rev in range(repo[node], len(repo)):
for file_ in repo[rev].files():
file_ = op.join(repo.root, file_)
if file_ in seen or not op.exists(file_):
continue
seen.add(file_)
paths.append(file_)
options = parse_options()
setup_logger(options)
if paths:
process_paths(options, candidates=paths) |
<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_git(path):
"""Install hook in Git repository.""" |
hook = op.join(path, 'pre-commit')
with open(hook, 'w') as fd:
fd.write("""#!/usr/bin/env python
import sys
from pylama.hook import git_hook
if __name__ == '__main__':
sys.exit(git_hook())
""")
chmod(hook, 484) |
<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_hg(path):
""" Install hook in Mercurial repository. """ |
hook = op.join(path, 'hgrc')
if not op.isfile(hook):
open(hook, 'w+').close()
c = ConfigParser()
c.readfp(open(hook, 'r'))
if not c.has_section('hooks'):
c.add_section('hooks')
if not c.has_option('hooks', 'commit'):
c.set('hooks', 'commit', 'python:pylama.hooks.hg_hook')
if not c.has_option('hooks', 'qrefresh'):
c.set('hooks', 'qrefresh', 'python:pylama.hooks.hg_hook')
c.write(open(hook, 'w+')) |
<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_hook(path):
""" Auto definition of SCM and hook installation. """ |
git = op.join(path, '.git', 'hooks')
hg = op.join(path, '.hg')
if op.exists(git):
install_git(git)
LOGGER.warn('Git hook has been installed.')
elif op.exists(hg):
install_hg(hg)
LOGGER.warn('Mercurial hook has been installed.')
else:
LOGGER.error('VCS has not found. Check your path.')
sys.exit(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 run(path, code=None, params=None, **meta):
"""Eradicate code checking. :return list: List of errors. """ |
code = converter(code)
line_numbers = commented_out_code_line_numbers(code)
lines = code.split('\n')
result = []
for line_number in line_numbers:
line = lines[line_number - 1]
result.append(dict(
lnum=line_number,
offset=len(line) - len(line.rstrip()),
# https://github.com/sobolevn/flake8-eradicate#output-example
text=converter('E800 Found commented out code: ') + line,
# https://github.com/sobolevn/flake8-eradicate#error-codes
type='E800',
))
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 remove_duplicates(errors):
""" Filter duplicates from given error's list. """ |
passed = defaultdict(list)
for error in errors:
key = error.linter, error.number
if key in DUPLICATES:
if key in passed[error.lnum]:
continue
passed[error.lnum] = DUPLICATES[key]
yield error |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fork(self, strictindex, new_value):
""" Return a chunk referring to the same location in a duplicated document. Used when modifying a YAML chunk so that the modification can be validated before changing it. """ |
forked_chunk = YAMLChunk(
deepcopy(self._ruamelparsed),
pointer=self.pointer,
label=self.label,
key_association=copy(self._key_association),
)
forked_chunk.contents[self.ruamelindex(strictindex)] = new_value.as_marked_up()
forked_chunk.strictparsed()[strictindex] = deepcopy(new_value.as_marked_up())
return forked_chunk |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.