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 config_conf(obj):
"Extracts the configuration of the underlying ConfigParser from obj"
# If we ever want to add some default options this is where to do that
cfg = {}
for name in dir(obj):
if name in CONFIG_PARSER_CFG: # argument of ConfigParser
cfg[name] = getattr(obj, name)
return cfg |
<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_gnu_argument(self, *args, **kwargs):
"Prevent the addition of any single hyphen, multiple letter args"
gnu_args = []
for arg in args:
# Fix if we have at least 3 chars where the first is a hyphen
# and the second is not a hyphen (e.g. -op becomes --op)
if len(arg) > 3 and arg[0] == '-' and arg[1] != '-':
gnu_args.append('-' + arg)
else:
gnu_args.append(arg)
argparse.ArgumentParser.add_argument(self, *gnu_args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_valid_user_by_email(email):
""" Return user instance """ |
user = get_user(email)
if user:
if user.valid is False:
return Err("user not valid")
return Ok(user)
return Err("user not exists") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def truncatechars(value,arg=50):
'''
Takes a string and truncates it to the requested amount, by inserting an ellipses into the middle.
'''
arg = int(arg)
if arg < len(value):
half = (arg-3)/2
return "%s...%s" % (value[:half],value[-half:])
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 logpdf_diagonal_gaussian(self, x, mean, cov):
'''
Compute logpdf of a multivariate Gaussian distribution with diagonal covariance at a given point x.
A multivariate Gaussian distribution with a diagonal covariance is equivalent
to a collection of independent Gaussian random variables.
x should be a sparse matrix. The logpdf will be computed for each row of x.
mean and cov should be given as 1D numpy arrays
mean[i] : mean of i-th variable
cov[i] : variance of i-th variable'''
n = x.shape[0]
dim = x.shape[1]
assert(dim == len(mean) and dim == len(cov))
# multiply each i-th column of x by (1/(2*sigma_i)), where sigma_i is sqrt of variance of i-th variable.
scaled_x = x.dot(self.diag(1./(2*np.sqrt(cov))) )
# multiply each i-th entry of mean by (1/(2*sigma_i))
scaled_mean = mean/(2*np.sqrt(cov))
# sum of pairwise squared Eulidean distances gives SUM[(x_i - mean_i)^2/(2*sigma_i^2)]
return -np.sum(np.log(np.sqrt(2*np.pi*cov))) - pairwise_distances(scaled_x, [scaled_mean], 'euclidean').flatten()**2 |
<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_sum_exp(self,x, axis):
'''Compute the log of a sum of exponentials'''
x_max = np.max(x, axis=axis)
if axis == 1:
return x_max + np.log( np.sum(np.exp(x-x_max[:,np.newaxis]), axis=1) )
else:
return x_max + np.log( np.sum(np.exp(x-x_max), axis=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 lookup(ctx, number, comment, cache):
"""Get the carrier and country code for a phone number""" |
phone = PhoneNumber(number, comment=comment)
info('{0} | {1}'.format(phone.number, ctx.obj['config']['lookups'].keys()))
if phone.number in ctx.obj['config']['lookups']:
info('{0} is already cached:'.format(phone.number))
info(jsonify(ctx.obj['config']['lookups'][phone.number]))
return
data = phone.lookup()
info('carrier = {0}'.format(phone.carrier))
info('type = {0}'.format(phone.type))
info('cache = {0}'.format(cache))
if cache:
ctx.obj['config']['lookups'][phone.number] = phone.raw
with open(CONFIG_FILE, 'wb') as cfg:
cfg.write(json.dumps(ctx.obj['config'], indent=2)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def anonymous_required(function):
"""Redirect to user profile if user is already logged-in""" |
def wrapper(*args, **kwargs):
if args[0].user.is_authenticated():
url = settings.ANONYMOUS_REQUIRED_REDIRECT_URL
return HttpResponseRedirect(reverse(url))
return function(*args, **kwargs)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disqus_sso_script(context):
""" Provides a generic context variable which adds single-sign-on support to DISQUS if ``COMMENTS_DISQUS_API_PUBLIC_KEY`` and ``COMMENTS_DISQUS_API_SECRET_KEY`` are specified. """ |
settings = context["settings"]
public_key = getattr(settings, "COMMENTS_DISQUS_API_PUBLIC_KEY", "")
secret_key = getattr(settings, "COMMENTS_DISQUS_API_SECRET_KEY", "")
user = context["request"].user
if public_key and secret_key and user.is_authenticated():
context["public_key"] = public_key
context["sso_data"] = _get_disqus_sso(user, public_key, secret_key)
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 log_random_sleep(self, minimum=3.0, scale=1.0, hints=None):
"""wrap random sleep. - log it for debug purpose only """ |
hints = '{} slept'.format(hints) if hints else 'slept'
st = time.time()
helper.random_sleep(minimum, scale)
log.debug('{} {} {}s'.format(
self.symbols.get('sleep', ''), hints, self.color_log(time.time() - st))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def config_factory(ConfigClass=dict, prefix=None,
config_file=None
):
'''return a class, which implements the compiler_factory API
:param ConfigClass:
defaults to dict. A simple factory (without parameter) for a
dictionary-like object, which implements __setitem__() method.
Additionally you can implement following methods:
:``init_args``: A method to be called to initialize the config object
by passing :py:class:`~argparse.Namespace` object resulting from
:py:class:`~argparse.ArgumentParser.parseargs` method.
You could load data from a configuration file here.
:``compile_args``: A method, which can return the same like a
``compile`` function does. If there is no such method, a tuple
with a ConfigClass instance as single element is returned.
:param prefix:
Add this prefix to config_name. (e.g. if prefix="foo" and you
have config_name="x.y" final config_path results in "foo.x.y")
:param config_file:
An :py:class:`~argdeco.arguments.arg` to provide a config file.
If you provide this argument, you can implement one of the following
methods in your ``ConfigClass`` to load data from the configfile:
:``load``: If you pass ``config_file`` argument, this method can be
implemented to load configuration data from resulting stream.
If config_file is '-', stdin stream is passed.
:``load_from_file``: If you prefer to open the file yourself, you can
do this, by implementing ``load_from_file`` instead which has the
filename as its single argument.
:``update``: method like :py:meth:`dict.update`. If neither of
``load`` or ``load_from_file`` is present, but ``update`` is,
it is assumed, that config_file is of type YAML (or JSON) and
configuration is updated by calling ``update`` with the parsed data
as parameter.
If you implement neither of these, it is assumed, that configuration
file is of type YAML (or plain JSON, as YAML is a superset of it).
Data is loaded from file and will update configuration object using
dict-like :py:meth:`dict.update` method.
:type config_file: argdeco.arguments.arg
:returns:
ConfigFactory class, which implements compiler_factory API.
'''
config_factory = ConfigClass
class ConfigFactory:
def __init__(self, command):
self.command = command
if config_file:
from .arguments import arg
assert isinstance(config_file, arg), "config_file must be of type arg"
try:
self.command.add_argument(config_file)
except:
pass
def __call__(self, args, **opts):
cfg = ConfigClass()
if hasattr(cfg, 'init_args'):
cfg.init_args(args)
if config_file is not None:
if hasattr(args, config_file.dest):
fn = getattr(args, config_file.dest)
if fn is not None:
if hasattr(cfg, 'load'):
if config_file.dest == '-':
cfg.load(sys.stdin)
else:
with open(fn, 'r') as f:
cfg.load(f)
elif hasattr(cfg, 'load_from_file'):
cfg.load_from_file(fn)
elif hasattr(cfg, 'update'):
# assume yaml file
import yaml
with open(fn, 'r') as f:
data = yaml.load(f)
cfg.update(data)
for k,v in opts.items():
config_name = self.command.get_config_name(args.action, k)
if config_name is None: continue
if prefix is not None:
config_name = '.'.join([prefix, config_name])
cfg[config_name] = v
if hasattr(cfg, 'compile_args'):
return cfg.compile_args()
else:
return (cfg,)
return ConfigFactory |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def flatten(self, D):
'''flatten a nested dictionary D to a flat dictionary
nested keys are separated by '.'
'''
if not isinstance(D, dict):
return D
result = {}
for k,v in D.items():
if isinstance(v, dict):
for _k,_v in self.flatten(v).items():
result['.'.join([k,_k])] = _v
else:
result[k] = v
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 update(self, E=None, **F):
'''flatten nested dictionaries to update pathwise
>>> Config({'foo': {'bar': 'glork'}}).update({'foo': {'blub': 'bla'}})
{'foo': {'bar': 'glork', 'blub': 'bla'}
In contrast to:
>>> {'foo': {'bar': 'glork'}}.update({'foo': {'blub': 'bla'}})
{'foo: {'blub': 'bla'}'}
'''
def _update(D):
for k,v in D.items():
if super(ConfigDict, self).__contains__(k):
if isinstance(self[k], ConfigDict):
self[k].update(v)
else:
self[k] = self.assimilate(v)
else:
self[k] = self.assimilate(v)
if E is not None:
if not hasattr(E, 'keys'):
E = self.assimilate(dict(E))
_update(E)
_update(F)
return 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 import_legislators(src):
""" Read the legislators from the csv files into a single Dataframe. Intended for importing new data. """ |
logger.info("Importing Legislators From: {0}".format(src))
current = pd.read_csv("{0}/{1}/legislators-current.csv".format(
src, LEGISLATOR_DIR))
historic = pd.read_csv("{0}/{1}/legislators-historic.csv".format(
src, LEGISLATOR_DIR))
legislators = current.append(historic)
return legislators |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_legislators(legislators, destination):
""" Output legislators datafrom to csv. """ |
logger.info("Saving Legislators To: {0}".format(destination))
legislators.to_csv("{0}/legislators.csv".format(destination),
encoding='utf-8') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_committees(src):
""" Read the committees from the csv files into a single Dataframe. Intended for importing new data. """ |
committees = []
subcommittees = []
with open("{0}/{1}/committees-current.yaml".format(src, LEGISLATOR_DIR),
'r') as stream:
committees += yaml.load(stream)
with open("{0}/{1}/committees-historical.yaml".format(src, LEGISLATOR_DIR),
'r') as stream:
committees += yaml.load(stream)
# Sub Committees are not Committees
# And unfortunately the good folk at thomas thought modeling data with duplicate id's was a good idea.
# you can have two subcommittees with the ID 12. Makes a simple membership map impossible.
for com in committees:
com['committee_id'] = com['thomas_id']
if 'subcommittees' in com:
# process sub committees into separate DataFrame
for subcom in com.get('subcommittees'):
subcom['committee_id'] = com[
'thomas_id'
] # we use committee_id so we can easily merge dataframes
subcom['subcommittee_id'] = "{0}-{1}".format(
subcom['committee_id'], subcom['thomas_id'])
subcommittees.append(subcom)
del com['subcommittees']
committees_df = pd.DataFrame(committees)
subcommittees_df = pd.DataFrame(subcommittees)
return [committees_df, subcommittees_df] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_committees(src, dest):
""" Import stupid yaml files, convert to something useful. """ |
comm, sub_comm = import_committees(src)
save_committees(comm, dest)
save_subcommittees(comm, dest) |
<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_congress_dir(congress, dest):
""" If the directory for a given congress does not exist. Make it. """ |
congress_dir = "{0}/{1}".format(dest, congress)
path = os.path.dirname(congress_dir)
logger.debug("CSV DIR: {}".format(path))
if not os.path.exists(congress_dir):
logger.info("Created: {0}".format(congress_dir))
os.mkdir(congress_dir)
return congress_dir |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_congress(congress, dest):
""" Takes a congress object with legislation, sponser, cosponsor, commities and subjects attributes and saves each item to it's own csv file. """ |
try:
logger.debug(congress.name)
logger.debug(dest)
congress_dir = make_congress_dir(congress.name, dest)
congress.legislation.to_csv("{0}/legislation.csv".format(congress_dir),
encoding='utf-8')
logger.debug(congress_dir)
congress.sponsors.to_csv("{0}/sponsor_map.csv".format(congress_dir),
encoding='utf-8')
congress.cosponsors.to_csv(
"{0}/cosponsor_map.csv".format(congress_dir),
encoding='utf-8')
congress.events.to_csv("{0}/events.csv".format(congress_dir),
encoding='utf-8')
congress.committees.to_csv(
"{0}/committees_map.csv".format(congress_dir),
encoding='utf-8')
congress.subjects.to_csv("{0}/subjects_map.csv".format(congress_dir),
encoding='utf-8')
congress.votes.to_csv("{0}/votes.csv".format(congress_dir),
encoding='utf-8')
congress.votes_people.to_csv(
"{0}/votes_people.csv".format(congress_dir),
encoding='utf-8')
if hasattr(congress, 'amendments'):
congress.amendments.to_csv(
"{0}/amendments.csv".format(congress_dir),
encoding='utf-8')
except Exception:
logger.error("############################################shoot me")
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
logger.error(exc_type, fname, exc_tb.tb_lineno) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_sponsor(bill):
""" Return a list of the fields we need to map a sponser to a bill """ |
logger.debug("Extracting Sponsor")
sponsor_map = []
sponsor = bill.get('sponsor', None)
if sponsor:
sponsor_map.append(sponsor.get('type'))
sponsor_map.append(sponsor.get('thomas_id'))
sponsor_map.append(bill.get('bill_id'))
sponsor_map.append(sponsor.get('district'))
sponsor_map.append(sponsor.get('state'))
logger.debug("END Extracting Sponsor")
return sponsor_map if sponsor_map else 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 extract_cosponsors(bill):
""" Return a list of list relating cosponsors to legislation. """ |
logger.debug("Extracting Cosponsors")
cosponsor_map = []
cosponsors = bill.get('cosponsors', [])
bill_id = bill.get('bill_id', None)
for co in cosponsors:
co_list = []
co_list.append(co.get('thomas_id'))
co_list.append(bill_id)
co_list.append(co.get('district'))
co_list.append(co.get('state'))
cosponsor_map.append(co_list)
logger.debug("End Extractioning Cosponsors")
return cosponsor_map |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_subjects(bill):
""" Return a list subject for legislation. """ |
logger.debug("Extracting Subjects")
subject_map = []
subjects = bill.get('subjects', [])
bill_id = bill.get('bill_id', None)
bill_type = bill.get('bill_type', None)
for sub in subjects:
subject_map.append((bill_id, bill_type, sub))
logger.debug("End Extractioning Subjects")
return subject_map |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_committees(bill):
""" Returns committee associations from a bill. """ |
bill_id = bill.get('bill_id', None)
logger.debug("Extracting Committees for {0}".format(bill_id))
committees = bill.get('committees', None)
committee_map = []
for c in committees:
logger.debug("Processing committee {0}".format(c.get('committee_id')))
c_list = []
sub = c.get('subcommittee_id')
if sub:
logger.debug("is subcommittee")
c_list.append('subcommittee') # type
c_list.append(c.get('subcommittee'))
sub_id = "{0}-{1}".format(
c.get('committee_id'), c.get('subcommittee_id'))
logger.debug("Processing subcommittee {0}".format(sub_id))
c_list.append(sub_id)
else:
c_list.append('committee')
c_list.append(c.get('committee'))
c_list.append(c.get('committee_id'))
c_list.append(bill_id)
committee_map.append(c_list)
return committee_map |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_events(bill):
""" Returns all events from legislation. Thing of this as a log for congress. There are alot of events that occur around legislation. For now we are going to kepe it simple. Introduction, cosponsor, votes dates """ |
events = []
#logger.debug(events)
bill_id = bill.get('bill_id', None)
if bill_id:
for event in bill.get('actions', []):
e = []
e.append(bill_id)
e.append(event.get('acted_at', None))
e.append(event.get('how', None))
e.append(event.get('result', None))
e.append(event.get('roll', None))
e.append(event.get('status', None))
e.append(event.get('suspension', False))
e.append(event.get('text', None))
e.append(event.get('type', None))
e.append(event.get('vote_type', None))
e.append(event.get('where', None))
e.append(event.get('calander', None))
e.append(event.get('number', None))
e.append(event.get('under', None))
e.append(event.get('committee', None))
e.append(event.get('committees', []))
events.append(e)
#logger.debug(events)
return events |
<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_amendments(congress):
""" Traverse amendments for a project """ |
amend_dir = "{0}/{1}/amendments".format(congress['src'],
congress['congress'])
logger.info("Processing Amendments for {0}".format(congress['congress']))
amendments = []
for root, dirs, files in os.walk(amend_dir):
if "data.json" in files and "text-versions" not in root:
file_path = "{0}/data.json".format(root)
logger.debug("Processing {0}".format(file_path))
a = json.loads(open(file_path, 'r').read())
amendment = []
amendment.append(a['amendment_id'])
amendment.append(a['amendment_type'])
if a['amends_amendment']:
amendment.append(a['amends_amendment'].get('amendment_id',
None))
else:
amendment.append(None)
if a['amends_bill']:
amendment.append(a['amends_bill'].get('bill_id', None))
else:
amendment.append(None)
if a['amends_treaty']:
amendment.append(a['amends_treaty'].get('treaty_id', None))
else:
amendment.append(None)
amendment.append(a['chamber'])
amendment.append(a['congress'])
amendment.append(a['description'])
amendment.append(a['introduced_at'])
amendment.append(a['number'])
amendment.append(a.get('proposed_at', None))
amendment.append(a['purpose'])
amendment.append(a['sponsor'].get('thomas_id', None))
amendment.append(a['sponsor'].get('committee_id', None))
amendment.append(a['sponsor']['type'])
amendment.append(a['status'])
amendment.append(a['updated_at'])
amendments.append(amendment)
return amendments if amendments else [[None] * 17] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lis_to_bio_map(folder):
""" Senators have a lis_id that is used in some places. That's dumb. Build a dict from lis_id to bioguide_id which every member of congress has. """ |
logger.info("Opening legislator csv for lis_dct creation")
lis_dic = {}
leg_path = "{0}/legislators.csv".format(folder)
logger.info(leg_path)
with open(leg_path, 'r') as csvfile:
leg_reader = csv.reader(csvfile)
for row in leg_reader:
if row[22]:
lis_dic[row[22]] = row[19]
return lis_dic |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_level(self, record):
"""Converts a logging level into a logbook level.""" |
level = record.levelno
if level >= logging.CRITICAL:
return levels.CRITICAL
if level >= logging.ERROR:
return levels.ERROR
if level >= logging.WARNING:
return levels.WARNING
if level >= logging.INFO:
return levels.INFO
return levels.DEBUG |
<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_extra(self, record):
"""Tries to find custom data from the old logging record. The return value is a dictionary that is merged with the log record extra dictionaries. """ |
rv = vars(record).copy()
for key in ('name', 'msg', 'args', 'levelname', 'levelno',
'pathname', 'filename', 'module', 'exc_info',
'exc_text', 'lineno', 'funcName', 'created',
'msecs', 'relativeCreated', 'thread', 'threadName',
'processName', 'process'):
rv.pop(key, None)
return rv |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def view(db_name):
""" Register a map function as a view Currently, only a single map function can be created for each view NOTE: the map function source is saved in CouchDB, so it cannot depend on anything outside the function's scope. :param db_name: the database name """ |
def decorator(func):
v = View(db_name, func)
v.register()
return v
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_design_docs():
""" Load design docs for registered views """ |
url = ':'.join([options.url_registry_db, str(options.db_port)])
client = partial(couch.BlockingCouch, couch_url=url)
for name, docs in _views.items():
db = client(db_name=name)
views = []
for doc in docs:
try:
current_doc = db.get_doc(doc['_id'])
# use the current _rev if not provided
if '_rev' not in doc:
doc['_rev'] = current_doc['_rev']
except couch.NotFound:
pass
views.append(doc)
db.save_docs(views) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reference_links(doc):
"""Get reference links""" |
if doc.get('type') == 'organisation' and doc.get('state') != 'deactivated':
for asset_id_type, link in doc.get('reference_links', {}).get('links', {}).items():
value = {
'organisation_id': doc['_id'],
'link': link
}
yield asset_id_type, 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 active_services(doc):
"""View for getting active services""" |
if doc.get('state') != 'deactivated':
for service_id, service in doc.get('services', {}).items():
if service.get('state') != 'deactivated':
service_type = service.get('service_type')
org = doc['_id']
service['id'] = service_id
service['organisation_id'] = org
yield service_id, service
yield [service_type, org], service
yield [service_type, None], service
yield [None, org], service
yield [None, None], service |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def services(doc):
"""View for getting services""" |
for service_id, service in doc.get('services', {}).items():
service_type = service.get('service_type')
org = doc['_id']
service['id'] = service_id
service['organisation_id'] = org
yield service_id, service
yield [service_type, org], service
yield [service_type, None], service
yield [None, org], service
yield [None, None], service |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def active_service_location(doc):
"""View for getting active service by location""" |
if doc.get('state') != 'deactivated':
for service_id, service in doc.get('services', {}).items():
if service.get('state') != 'deactivated':
service['id'] = service_id
service['organisation_id'] = doc['_id']
location = service.get('location', None)
if location:
yield location, service |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def service_location(doc):
"""View for getting service by location""" |
for service_id, service in doc.get('services', {}).items():
service['id'] = service_id
service['organisation_id'] = doc['_id']
location = service.get('location', None)
if location:
yield location, service |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def service_name(doc):
"""View for getting service by name""" |
for service_id, service in doc.get('services', {}).items():
service['id'] = service_id
service['organisation_id'] = doc['_id']
name = service.get('name', None)
if name:
yield name, service |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def active_repositories(doc):
"""View for getting active repositories""" |
if doc.get('state') != 'deactivated':
for repository_id, repo in doc.get('repositories', {}).items():
if repo.get('state') != 'deactivated':
repo['id'] = repository_id
repo['organisation_id'] = doc['_id']
yield repository_id, repo |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def repositories(doc):
"""View for getting repositories""" |
for repository_id, repo in doc.get('repositories', {}).items():
repo['id'] = repository_id
repo['organisation_id'] = doc['_id']
yield repository_id, repo |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def repository_name(doc):
"""View for checking repository name is unique""" |
for repository_id, repo in doc.get('repositories', {}).items():
repo['id'] = repository_id
repo['organisation_id'] = doc['_id']
name = repo.get('name', None)
if name:
yield name, repository_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 service_and_repository(doc):
""" View for looking up services and repositories by their ID Used in the auth service """ |
if doc.get('type') == 'organisation' and doc.get('state') != 'deactivated':
for repository_id, repo in doc.get('repositories', {}).items():
if repo.get('state') != 'deactivated':
repo['id'] = repository_id
repo['organisation_id'] = doc['_id']
yield repository_id, repo
for service_id, service in doc.get('services', {}).items():
if service.get('state') != 'deactivated':
service['id'] = service_id
service['organisation_id'] = doc['_id']
yield service_id, service |
<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_design_doc(self):
"""Create a design document from a Python map function""" |
source = [x for x in inspect.getsourcelines(self.func)[0]
if not x.startswith('@')]
doc = {
'_id': '_design/{}'.format(self.name),
'language': 'python',
'views': {
self.name: {
'map': ''.join(source)
}
}
}
return doc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def values(self, **kwargs):
"""Get the view's values""" |
result = yield self.get(**kwargs)
if not result['rows']:
raise Return([])
raise Return([x['value'] for x in result['rows']]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def go(self, poller_configurations):
"""Create threaded pollers and start configured polling cycles """ |
try:
notify(
CachableSourcePollersAboutToStartEvent(poller_configurations))
logger.info("Starting pollers")
exit_ = threading.Event()
for config in poller_configurations: # config is a dict
kwargs = {'exit_': exit_}
kwargs.update(config)
threading.Thread(target=self.poll,
kwargs=(kwargs),
).start()
while threading.active_count() > 1:
time.sleep(.001)
except KeyboardInterrupt:
logger.info("KeyboardInterrupt signal caught, shutting down pollers...")
exit_.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 from_name(clz, name):
""" Instantiates the object from a known name """ |
if isinstance(name, list) and "green" in name:
name = "teal"
assert name in COLOR_NAMES, 'Unknown color name'
r, b, g = COLOR_NAMES[name]
return clz(r, b, g) |
<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_html(self):
""" Converts to Hex """ |
out = "#"
if self.r == 0:
out += "00"
else:
out += hex(self.r)[2:]
if self.b == 0:
out += "00"
else:
out += hex(self.b)[2:]
if self.g == 0:
out += "00"
else:
out += hex(self.g)[2:]
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(self, other):
""" Merges the values """ |
print "MERGING", self, other
other = self.coerce(other)
if self.is_contradictory(other):
raise Contradiction("Cannot merge %s and %s" % (self, other))
elif self.value is None and not other.value is None:
self.r, self.g, self.b = other.r, other.g, other.b
self.value = RGBColor(self.r, self.b, self.g, rgb_type='sRGB')
# last cases: other is none, or both are none
return 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 calculate_health(package_name, package_version=None, verbose=False, no_output=False):
""" Calculates the health of a package, based on several factors :param package_name: name of package on pypi.python.org :param package_version: version number of package to check, optional - defaults to latest version :param verbose: flag to print out reasons :param no_output: print no output :param lint: run pylint on the package :returns: (score: integer, reasons: list of reasons for score) :rtype: tuple """ |
total_score = 0
reasons = []
package_releases = CLIENT.package_releases(package_name)
if not package_releases:
if not no_output:
print(TERMINAL.red('{} is not listed on pypi'.format(package_name)))
return 0, []
if package_version is None:
package_version = package_releases[0]
package_info = CLIENT.release_data(package_name, package_version)
release_urls = CLIENT.release_urls(package_name, package_version)
if not package_info or not release_urls:
if not no_output:
print(TERMINAL.red('Version {} is not listed on pypi'.format(
package_version)))
return 0, []
if not no_output:
print(TERMINAL.bold('{} v{}'.format(package_name, package_version)))
print('-----')
checkers = [
checks.check_license,
checks.check_homepage,
checks.check_summary,
checks.check_description,
checks.check_python_classifiers,
checks.check_author_info,
checks.check_release_files,
checks.check_stale
]
for checker in checkers:
result, reason, score = checker(package_info, release_urls)
if result:
total_score += score
else:
reasons.append(reason)
if total_score < 0:
total_score = 0
if not no_output:
percentage = int(float(total_score) / float(checks.TOTAL_POSSIBLE) * 100)
score_string = 'score: {}/{} {}%'.format(total_score, checks.TOTAL_POSSIBLE, percentage)
print(get_health_color(percentage)(score_string))
if verbose and not no_output:
for reason in reasons:
print(reason)
if no_output:
return total_score, reasons |
<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(filter_creator):
""" Creates a decorator that can be used as a filter. .. warning:: This is currently not compatible with most other decorators, if you are using a decorator that isn't part of `hurler` you should take caution. """ |
filter_func = [None]
def function_getter(function):
if isinstance(function, Filter):
function.add_filter(filter)
return function
else:
return Filter(
filter=filter_func[0],
callback=function,
)
def filter_decorator(*args, **kwargs):
filter_function = filter_creator(*args, **kwargs)
filter_func[0] = filter_function
return function_getter
return filter_decorator |
<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_level(logger=None, log_level=None):
'''Set logging levels using logger names.
:param logger: Name of the logger
:type logger: String
:param log_level: A string or integer corresponding to a Python logging level
:type log_level: String
:rtype: None
'''
log_level = logging.getLevelName(os.getenv('VERBOSITY', 'WARNING'))
logging.getLogger(logger).setLevel(log_level) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def bin_priority(op,left,right):
"I don't know how to handle order of operations in the LR grammar, so here it is"
# note: recursion limits protect this from infinite looping. I'm serious. (i.e. it will crash rather than hanging)
if isinstance(left,BinX) and left.op < op: return bin_priority(left.op,left.left,bin_priority(op,left.right,right))
elif isinstance(left,UnX) and left.op < op: return un_priority(left.op,BinX(op,left.val,right)) # note: obviously, no need to do this when right is a UnX
elif isinstance(right,BinX) and right.op < op: return bin_priority(right.op,bin_priority(op,left,right.left),right.right)
else: return BinX(op,left,right) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def un_priority(op,val):
"unary expression order-of-operations helper"
if isinstance(val,BinX) and val.op < op: return bin_priority(val.op,UnX(op,val.left),val.right)
else: return UnX(op,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 lex(string):
"this is only used by tests"
safe_lexer = LEXER.clone() # reentrant? I can't tell, I hate implicit globals. do a threading test
safe_lexer.input(string)
a = []
while 1:
t = safe_lexer.token()
if t: a.append(t)
else: break
return a |
<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(string):
"return a BaseX tree for the string"
print string
if string.strip().lower().startswith('create index'): return IndexX(string)
return YACC.parse(string, lexer=LEXER.clone()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, model, index):
"""Register the model with the registry""" |
self.model_to_indexes[model].add(index)
if not self.connected:
connections.index_name = {}
from django.conf import settings
kwargs = {}
for name, params in settings.ELASTICSEARCH_CONNECTIONS.items():
params = copy.deepcopy(params)
kwargs[name] = params
connections.index_name[name] = params.pop("index_name")
connections.configure(**kwargs)
self.connected = 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 bucket(cls, bucket_name, connection=None):
"""Gives the bucket from couchbase server. :param bucket_name: Bucket name to fetch. :type bucket_name: str :returns: couchbase driver's Bucket object. :rtype: :class:`couchbase.client.Bucket` :raises: :exc:`RuntimeError` If the credentials wasn't set. """ |
connection = cls.connection if connection == None else connection
if bucket_name not in cls._buckets:
connection = "{connection}/{bucket_name}".format(connection=connection, bucket_name=bucket_name)
if cls.password:
cls._buckets[connection] = Bucket(connection, password=cls.password)
else:
cls._buckets[connection] = Bucket(connection)
return cls._buckets[connection] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def linreg_ols_qr(y, X):
"""Linear Regression, OLS, inverse by QR Factoring""" |
import numpy as np
try: # multiply with inverse to compute coefficients
q, r = np.linalg.qr(np.dot(X.T, X))
return np.dot(np.dot(np.linalg.inv(r), q.T), np.dot(X.T, y))
except np.linalg.LinAlgError:
print("LinAlgError: Factoring failed")
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 find_open_and_close_braces(line_index, start, brace, lines):
""" Take the line where we want to start and the index where we want to start and find the first instance of matched open and close braces of the same type as brace in file file. :param: line (int):
the index of the line we want to start searching at :param: start (int):
the index in the line we want to start searching at :param: brace (string):
one of the type of brace we are looking for ({, }, [, or ]) are looking in. :return: (start, start_line, end, end_line):
(int, int, int):
the index of the start and end of whatever braces we are looking for, and the line number that the end is on (since it may be different than the line we started on) """ |
if brace in ['[', ']']:
open_brace = '['
close_brace = ']'
elif brace in ['{', '}']:
open_brace = '{'
close_brace = '}'
elif brace in ['(', ')']:
open_brace = '('
close_brace = ')'
else:
# unacceptable brace type!
return (-1, -1, -1, -1)
open_braces = []
line = lines[line_index]
ret_open_index = line.find(open_brace, start)
line_index_cpy = line_index
# sometimes people don't put the braces on the same line
# as the tag
while ret_open_index == -1:
line_index = line_index + 1
if line_index >= len(lines):
# failed to find open braces...
return (0, line_index_cpy, 0, line_index_cpy)
line = lines[line_index]
ret_open_index = line.find(open_brace)
open_braces.append(open_brace)
ret_open_line = line_index
open_index = ret_open_index
close_index = ret_open_index
while len(open_braces) > 0:
if open_index == -1 and close_index == -1:
# we hit the end of the line! oh, noez!
line_index = line_index + 1
if line_index >= len(lines):
# hanging braces!
return (ret_open_index, ret_open_line,
ret_open_index, ret_open_line)
line = lines[line_index]
# to not skip things that are at the beginning of the line
close_index = line.find(close_brace)
open_index = line.find(open_brace)
else:
if close_index != -1:
close_index = line.find(close_brace, close_index + 1)
if open_index != -1:
open_index = line.find(open_brace, open_index + 1)
if close_index != -1:
open_braces.pop()
if len(open_braces) == 0 and \
(open_index > close_index or open_index == -1):
break
if open_index != -1:
open_braces.append(open_brace)
ret_close_index = close_index
return (ret_open_index, ret_open_line, ret_close_index, line_index) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assemble_caption(begin_line, begin_index, end_line, end_index, lines):
""" Take the caption of a picture and put it all together in a nice way. If it spans multiple lines, put it on one line. If it contains controlled characters, strip them out. If it has tags we don't want to worry about, get rid of them, etc. :param: begin_line (int):
the index of the line where the caption begins :param: begin_index (int):
the index within the line where the caption begins :param: end_line (int):
the index of the line where the caption ends :param: end_index (int):
the index within the line where the caption ends :return: caption (string):
the caption, formatted and pieced together """ |
# stuff we don't like
label_head = '\\label{'
# reassemble that sucker
if end_line > begin_line:
# our caption spanned multiple lines
caption = lines[begin_line][begin_index:]
for included_line_index in range(begin_line + 1, end_line):
caption = caption + ' ' + lines[included_line_index]
caption = caption + ' ' + lines[end_line][:end_index]
caption = caption.replace('\n', ' ')
caption = caption.replace(' ', ' ')
else:
# it fit on one line
caption = lines[begin_line][begin_index:end_index]
# clean out a label tag, if there is one
label_begin = caption.find(label_head)
if label_begin > -1:
# we know that our caption is only one line, so if there's a label
# tag in it, it will be all on one line. so we make up some args
dummy_start, dummy_start_line, label_end, dummy_end = \
find_open_and_close_braces(0, label_begin, '{', [caption])
caption = caption[:label_begin] + caption[label_end + 1:]
caption = caption.strip()
if len(caption) > 1 and caption[0] == '{' and caption[-1] == '}':
caption = caption[1:-1]
return caption |
<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_image_data(extracted_image_data, output_directory, image_mapping):
"""Prepare and clean image-data from duplicates and other garbage. :param: tex_file (string):
the location of the TeX (used for finding the associated images; the TeX is assumed to be in the same directory as the converted images) image file names """ |
img_list = {}
for image, caption, label in extracted_image_data:
if not image or image == 'ERROR':
continue
image_location = get_image_location(
image,
output_directory,
image_mapping.keys()
)
if not image_location or not os.path.exists(image_location) or \
len(image_location) < 3:
continue
image_location = os.path.normpath(image_location)
if image_location in img_list:
if caption not in img_list[image_location]['captions']:
img_list[image_location]['captions'].append(caption)
else:
img_list[image_location] = dict(
url=image_location,
original_url=image_mapping[image_location],
captions=[caption],
label=label,
name=get_name_from_path(image_location, output_directory)
)
return img_list.values() |
<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_converted_image_name(image):
"""Return the name of the image after it has been converted to png format. Strips off the old extension. :param: image (string):
The fullpath of the image before conversion :return: converted_image (string):
the fullpath of the image after convert """ |
png_extension = '.png'
if image[(0 - len(png_extension)):] == png_extension:
# it already ends in png! we're golden
return image
img_dir = os.path.split(image)[0]
image = os.path.split(image)[-1]
# cut off the old extension
if len(image.split('.')) > 1:
old_extension = '.' + image.split('.')[-1]
converted_image = image[:(0 - len(old_extension))] + png_extension
else:
# no extension... damn
converted_image = image + png_extension
return os.path.join(img_dir, converted_image) |
<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_tex_location(new_tex_name, current_tex_name, recurred=False):
""" Takes the name of a TeX file and attempts to match it to an actual file in the tarball. :param: new_tex_name (string):
the name of the TeX file to find :param: current_tex_name (string):
the location of the TeX file where we found the reference :return: tex_location (string):
the location of the other TeX file on disk or None if it is not found """ |
tex_location = None
current_dir = os.path.split(current_tex_name)[0]
some_kind_of_tag = '\\\\\\w+ '
new_tex_name = new_tex_name.strip()
if new_tex_name.startswith('input'):
new_tex_name = new_tex_name[len('input'):]
if re.match(some_kind_of_tag, new_tex_name):
new_tex_name = new_tex_name[len(new_tex_name.split(' ')[0]) + 1:]
if new_tex_name.startswith('./'):
new_tex_name = new_tex_name[2:]
if len(new_tex_name) == 0:
return None
new_tex_name = new_tex_name.strip()
new_tex_file = os.path.split(new_tex_name)[-1]
new_tex_folder = os.path.split(new_tex_name)[0]
if new_tex_folder == new_tex_file:
new_tex_folder = ''
# could be in the current directory
for any_file in os.listdir(current_dir):
if any_file == new_tex_file:
return os.path.join(current_dir, new_tex_file)
# could be in a subfolder of the current directory
if os.path.isdir(os.path.join(current_dir, new_tex_folder)):
for any_file in os.listdir(os.path.join(current_dir, new_tex_folder)):
if any_file == new_tex_file:
return os.path.join(os.path.join(current_dir, new_tex_folder),
new_tex_file)
# could be in a subfolder of a higher directory
one_dir_up = os.path.join(os.path.split(current_dir)[0], new_tex_folder)
if os.path.isdir(one_dir_up):
for any_file in os.listdir(one_dir_up):
if any_file == new_tex_file:
return os.path.join(one_dir_up, new_tex_file)
two_dirs_up = os.path.join(os.path.split(os.path.split(current_dir)[0])[0],
new_tex_folder)
if os.path.isdir(two_dirs_up):
for any_file in os.listdir(two_dirs_up):
if any_file == new_tex_file:
return os.path.join(two_dirs_up, new_tex_file)
if tex_location is None and not recurred:
return get_tex_location(new_tex_name + '.tex', current_tex_name,
recurred=True)
return tex_location |
<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_name_from_path(full_path, root_path):
"""Create a filename by merging path after root directory.""" |
relative_image_path = os.path.relpath(full_path, root_path)
return "_".join(relative_image_path.split('.')[:-1]).replace('/', '_')\
.replace(';', '').replace(':', '') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply(self, vpc):
""" returns a list of new security groups that will be added """ |
assert vpc is not None
# make sure we're up to date
self.reload_remote_groups()
vpc_groups = self.vpc_groups(vpc)
self._apply_groups(vpc)
# reloads groups from AWS, the authority
self.reload_remote_groups()
vpc_groups = self.vpc_groups(vpc)
groups = {k.name:k for k in vpc_groups}
for x,y in self.config.items():
# process 1 security group at a time
group = groups[x]
if y.get('rules'):
# apply all rule changes
rules = [Rule.parse(rule) for rule in y.get('rules')]
rules = list(itertools.chain(*rules))
rules = self.filter_existing_rules(rules, group)
# need to use chain because multiple rules can be created for a single stanza
for rule in rules:
group_name = groups.get(rule.group_name, None)
if group_name and rule.address:
raise Exception("Can't auth an address and a group")
logger.debug("Authorizing %s %s %s to address:%s name:%s", rule.protocol,
rule.from_port, rule.to_port, rule.address, rule.group_name)
group_to_authorize = groups.get(rule.group_name, None)
try:
group.authorize(rule.protocol,
rule.from_port,
rule.to_port,
rule.address,
group_to_authorize, None)
except Exception as e:
print "could not authorize group %s" % group_to_authorize
raise
# apply rules
return 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 anitya_unmapped_new_update(config, message):
""" New releases of upstream projects that have no mapping to Fedora Adding this rule will let through events when new upstream releases are detected, but only on upstream projects that have no mapping to Fedora Packages. This could be useful to you if you want to monitor release-monitoring.org itself and watch for projects that might need help adjusting their metadata. """ |
if not anitya_new_update(config, message):
return False
for package in message['msg']['message']['packages']:
if package['distro'].lower() == 'fedora':
return False
# If none of the packages were listed as Fedora, then this is unmapped.
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 anitya_specific_distro(config, message, distro=None, *args, **kw):
""" Distro-specific release-monitoring.org events This rule will match all anitya events *only for a particular distro*. """ |
if not distro:
return False
if not anitya_catchall(config, message):
return False
d = message['msg'].get('distro', {})
if d: # Have to be careful for None here
if d.get('name', '').lower() == distro.lower():
return True
d = None
p = message['msg'].get('project', {})
if p:
d = p.get('distro', {})
if d: # Have to be careful for None here
if d.get('name', '').lower() == distro.lower():
return True
for pkg in message['msg'].get('message', {}).get('packages', []):
if pkg['distro'].lower() == distro.lower():
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 anitya_by_upstream_project(config, message, projects=None, *args, **kw):
""" Anything regarding a particular "upstream project" Adding this rule will let through *any* anitya notification that pertains to a particular "upstream project". Note that the "project" name is often different from the distro "package" name. For instance, the package python-requests in Fedora will have the upstream project name "requests". You can specify a comma-separated list of upstream project names here. """ |
# We only deal in anitya messages, first off.
if not anitya_catchall(config, message):
return False
if not projects or not isinstance(projects, six.string_types):
return False
# Get the project for the message.
project = message.get('msg', {}).get('project', {}).get('name', None)
# Split the string into a list of targets
targets = [p.strip() for p in projects.split(',')]
# Filter out empty strings if someone is putting ',,,' garbage in
targets = [target for target in targets if target]
return project in 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 data(self, index, role):
"""use zipped icon.png as icon""" |
if index.column() == 0 and role == QtCore.Qt.DecorationRole:
if self.isPyz(index):
with ZipFile(str(self.filePath(index)), 'r') as myzip:
# print myzip.namelist()
try:
myzip.extract('icon', self._tmp_dir_work)
p = os.path.join(self._tmp_dir_work, 'icon')
return QtGui.QIcon(p)
except KeyError:
pass
return super(_FileSystemModel, self).data(index, role) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status_messages(self):
""" Returns status messages if any """ |
messages = IStatusMessage(self.request)
m = messages.show()
for item in m:
item.id = idnormalizer.normalize(item.message)
return m |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def users(self):
"""Get current users and add in any search results. :returns: a list of dicts with keys - id - title :rtype: list """ |
existing_users = self.existing_users()
existing_user_ids = [x['id'] for x in existing_users]
# Only add search results that are not already members
sharing = getMultiAdapter((self.my_workspace(), self.request),
name='sharing')
search_results = sharing.user_search_results()
users = existing_users + [x for x in search_results
if x['id'] not in existing_user_ids]
users.sort(key=lambda x: safe_unicode(x["title"]))
return users |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def children(self):
""" returns a list of dicts of items in the current context """ |
items = []
catalog = self.context.portal_catalog
current_path = '/'.join(self.context.getPhysicalPath())
sidebar_search = self.request.get('sidebar-search', None)
if sidebar_search:
st = '%s*' % sidebar_search # XXX plone only allows * as postfix.
# With solr we might want to do real substr
results = catalog.searchResults(SearchableText=st,
path=current_path)
else:
results = self.context.getFolderContents()
for item in results:
# Do some checks to set the right classes for icons and candy
desc = (
item['Description']
and 'has-description'
or 'has-no-description'
)
content_type = TYPE_MAP.get(item['portal_type'], 'none')
mime_type = '' # XXX: will be needed later for grouping by mimetyp
# typ can be user, folder, date and mime typish
typ = 'folder' # XXX: This needs to get dynamic later
url = item.getURL()
ptool = api.portal.get_tool('portal_properties')
view_action_types = \
ptool.site_properties.typesUseViewActionInListings
if content_type in FOLDERISH_TYPES:
dpi = (
"source: #workspace-documents; "
"target: #workspace-documents"
)
url = url + '/@@sidebar.default#workspace-documents'
content_type = 'group'
else:
if item['portal_type'] in view_action_types:
url = "%s/view" % url
dpi = (
"target: #document-body; "
"source: #document-body; "
"history: record"
)
content_type = 'document'
cls = 'item %s type-%s %s' % (content_type, typ, desc)
items.append({
'id': item['getId'],
'cls': cls,
'title': item['Title'],
'description': item['Description'],
'url': url,
'type': TYPE_MAP.get(item['portal_type'], 'none'),
'mime-type': mime_type,
'dpi': dpi})
return items |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def install(self):
'''
Use pip to install the requirements file.
'''
remote_path = os.path.join(self.venv, 'requirements.txt')
put(self.requirements, remote_path)
run('{pip} install -r {requirements}'.format(
pip=self.pip(), requirements=remote_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 freeze(self):
'''
Use pip to freeze the requirements and save them to the local
requirements.txt file.
'''
remote_path = os.path.join(self.venv, 'requirements.txt')
run('{} freeze > {}'.format(self.pip(), remote_path))
get(remote_path, self.requirements) |
<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):
'''
Remove the virtual environment completely
'''
print 'remove'
if self.exists():
print 'cleaning', self.venv
run('rm -rf {}'.format(self.venv)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def venv_pth(self, dirs):
'''
Add the directories in `dirs` to the `sys.path`. A venv.pth file
will be written in the site-packages dir of this virtualenv to add
dirs to sys.path.
dirs: a list of directories.
'''
# Create venv.pth to add dirs to sys.path when using the virtualenv.
text = StringIO.StringIO()
text.write("# Autogenerated file. Do not modify.\n")
for path in dirs:
text.write('{}\n'.format(path))
put(text, os.path.join(self.site_packages_dir(), 'venv.pth'), mode=0664) |
<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_to_team(self, **kw):
""" We override this method to add our additional participation policy groups, as detailed in available_groups above """ |
group = self.context.participant_policy.title()
data = kw.copy()
if "groups" in data:
data["groups"].add(group)
else:
data["groups"] = set([group])
super(PloneIntranetWorkspace, self).add_to_team(**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 group_for_policy(self, policy=None):
""" Lookup the collective.workspace usergroup corresponding to the given policy :param policy: The value of the policy to lookup, defaults to the current policy :type policy: str """ |
if policy is None:
policy = self.context.participant_policy
return "%s:%s" % (policy.title(), self.context.UID()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getRoles(self, principal_id):
""" give an Owner who is also a 'selfpublisher', the reviewer role """ |
context = self.context
current_roles = list(DefaultLocalRoleAdapter.getRoles(
self,
principal_id,
))
# check we are not on the workspace itself
if IHasWorkspace.providedBy(context):
return current_roles
# otherwise we should acquire the workspace and check out roles
workspace = getattr(context, 'acquire_workspace', lambda: None)()
if workspace is None:
return current_roles
workspace_roles = api.user.get_roles(obj=workspace)
if 'SelfPublisher' in workspace_roles and 'Owner' in current_roles:
current_roles.append('Reviewer')
return current_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 add(self, method, path_settings, target):
""" Simply creates Route and appends it to self.routes read Route class docs for parameters meaning """ |
self.routes.append(Route(method, path_settings, 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 clean_query_Dict(cls, query_Dict):
"""removes NoneTypes from the dict """ |
return {k: v for k, v in query_Dict.items() if v} |
<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(self, teamId=None, rType=None, maxResults=C.MAX_RESULT_DEFAULT, limit=C.ALL):
""" rType can be DIRECT or GROUP """ |
queryParams = {'teamId': teamId,
'type': rType,
'max': maxResults}
queryParams = self.clean_query_Dict(queryParams)
ret = self.send_request(C.GET, self.end, data=queryParams, limit=limit)
return [Room(self.token, roomData) for roomData in ret['items']] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_flag_args(**options):
"""Build a list of flags.""" |
flags = []
for key, value in options.items():
# Build short flags.
if len(key) == 1:
flag = f'-{key}'
# Built long flags.
else:
flag = f'--{key}'
flags = flags + [flag, value]
return flags |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kubectl(*args, input=None, **flags):
"""Simple wrapper to kubectl.""" |
# Build command line call.
line = ['kubectl'] + list(args)
line = line + get_flag_args(**flags)
if input is not None:
line = line + ['-f', '-']
# Run subprocess
output = subprocess.run(
line,
input=input,
capture_output=True,
text=True
)
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanString(someText):
""" remove special characters and spaces from string and convert to lowercase """ |
ret = ''
if someText is not None:
ret = filter(unicode.isalnum, someText.lower())
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 group_permissions(permissions):
""" Groups a permissions list Returns a dictionary, with permission types as keys and sets of entities with access to the resource as values, e.g.: { 'organisation_id': { 'org1': set(['rw', 'r', 'w']), 'org2': set(['-']), 'org3': set(['r', 'w']), }, 'all': set(['r']) } 'org1' has 'rw' access to the resource, 'org2' is denied access and 'org3' has 'r' & 'w' access (the same as 'rw'). Note that 'rw' will always result in 'rw', 'r' & 'w' in the set to make checks easier. If present in the resource's permissions, the 'all' permission type is an exception in that it's value is just a set instead of a dictionary. :param permissions: a list of permissions :returns: defaultdict """ |
groups = defaultdict(lambda: defaultdict(set))
for p in sorted(permissions, key=itemgetter('type')):
permission_set = groups[p['type']][p.get('value')]
permission_set.add(p['permission'])
if p['permission'] == 'rw':
permission_set.update({'r', 'w'})
# the 'all' permission type always has None as the value
groups['all'] = groups['all'][None]
return groups |
<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_secret(length=30):
""" Generate an ASCII secret using random.SysRandom Based on oauthlib's common.generate_token function """ |
rand = random.SystemRandom()
ascii_characters = string.ascii_letters + string.digits
return ''.join(rand.choice(ascii_characters) for _ in range(length)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(cls, state=None, include_deactivated=False):
""" Get all organisations :param state: State of organisation :param include_deactivated: Flag to include deactivated :returns: list of Organisation instances :raises: SocketError, CouchException """ |
if state and state not in validators.VALID_STATES:
raise exceptions.ValidationError('Invalid "state"')
elif state:
organisations = yield views.organisations.get(key=state,
include_docs=True)
elif include_deactivated:
organisations = yield views.organisations.get(include_docs=True)
else:
organisations = yield views.active_organisations.get(include_docs=True)
raise Return([cls(**org['doc']) for org in organisations['rows']]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def user_organisations(cls, user_id, state=None, include_deactivated=False):
""" Get organisations that the user has joined :param user_id: the user ID :param state: the user's "join" state :param include_deactivated: Include deactivated resources in response :returns: list of Organisation instances :raises: SocketError, CouchException """ |
if state and state not in validators.VALID_STATES:
raise exceptions.ValidationError('Invalid "state"')
if include_deactivated:
organisations = yield views.joined_organisations.get(
key=[user_id, state], include_docs=True)
else:
organisations = yield views.active_joined_organisations.get(
key=[user_id, state], include_docs=True)
raise Return([cls(**org['doc']) for org in organisations['rows']]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_update(self, user, **data):
""" Sys admins can always update an organisation. Organisation admins and creators can update, but may not update the following fields: - star_rating :param user: a User :param data: data that the user wants to update :returns: bool, set of fields that the user was not authorized to update """ |
if user.is_admin():
raise Return((True, set([])))
org_admin = user.is_org_admin(self.id)
creator = self.created_by == user.id
if org_admin or creator:
fields = {'star_rating'} & set(data.keys())
if fields:
raise Return((False, fields))
else:
raise Return((True, set([])))
raise Return((False, 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 check_unique(self):
"""Check the service's name and location are unique""" |
errors = []
service_id = getattr(self, 'id', None)
fields = [('location', views.service_location),
('name', views.service_name)]
for field, view in fields:
value = getattr(self, field, None)
if not value:
continue
result = yield view.values(key=value)
matched = {x['id'] for x in result if x['id'] != service_id}
if matched:
errors.append("Service with {} '{}' already exists"
.format(field, value))
if errors:
raise exceptions.ValidationError(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 get_by_location(cls, location, include_deactivated=False):
"""Get a service by it's location""" |
if include_deactivated:
view = views.service_location
else:
view = views.active_service_location
result = yield view.first(key=location, include_docs=True)
parent = cls.parent_resource(**result['doc'])
raise Return(cls(parent=parent, **result['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 all(cls, service_type=None, organisation_id=None, include_deactivated=False):
""" Get all resources :param service_type: Filter by service type :param organisation_id: Filter by organisation id :param include_deactivated: Flag to include deactivated Services :returns: list of Resource instances :raises: SocketError, CouchException """ |
if include_deactivated:
resources = yield views.services.get(key=[service_type, organisation_id])
else:
resources = yield views.active_services.get(key=[service_type, organisation_id])
# TODO: shouldn't this include the doc as the parent?
raise Return([cls(**resource['value']) for resource in resources['rows']]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_update(self, user, **kwargs):
"""Org admins may not update organisation_id or service_type""" |
if user.is_admin():
raise Return((True, set([])))
is_creator = self.created_by == user.id
if not (user.is_org_admin(self.organisation_id) or is_creator):
raise Return((False, set([])))
fields = ({'service_type', 'organisation_id'} & set(kwargs.keys()))
if fields:
raise Return((False, fields))
else:
raise Return((True, 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 authenticate(cls, client_id, secret):
""" Authenticate a client using it's secret :param client_id: the client / service ID :param secret: the client secret :returns: a Service instance """ |
result = yield views.oauth_client.get(key=[secret, client_id])
if not result['rows']:
raise Return()
service = yield Service.get(client_id)
raise Return(service) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authorized(self, requested_access, resource):
""" Check whether the service is authorized to access the resource :param requested_access: "r", "w", or "rw" :param resource: a Resource or SubResource with "permissions" attribute :returns: True if has access, False otherwise """ |
if {self.state, resource.state} != {State.approved}:
return False
permissions = group_permissions(getattr(resource, 'permissions', []))
org_permissions = permissions['organisation_id'][self.organisation_id]
type_permissions = permissions['service_type'][self.service_type]
all_permissions = permissions['all']
for permission_set in [org_permissions, type_permissions, all_permissions]:
if '-' in permission_set:
return False
elif set([x for x in requested_access]).issubset(permission_set):
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 validate(self):
"""Validate the resource""" |
if not self._resource.get('permissions'):
self.permissions = self.default_permissions
try:
# update _resource so have default values from the schema
self._resource = self.schema(self._resource)
except MultipleInvalid as e:
errors = [format_error(err, self.resource_type) for err in e.errors]
raise exceptions.ValidationError({'errors': errors})
yield self.check_service()
yield self.check_unique() |
<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_service(self):
"""Check the service exists and is a repository service""" |
try:
service = yield Service.get(self.service_id)
except couch.NotFound:
raise exceptions.ValidationError('Service {} not found'
.format(self.service_id))
if service.service_type != 'repository':
raise exceptions.ValidationError('{} is not a repository service'
.format(self.service_id))
if service.state != State.approved:
raise exceptions.ValidationError('{} is not an approved service'
.format(self.service_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 check_unique(self):
"""Check the repository's name is unique""" |
result = yield views.repository_name.values(key=self.name)
repo_id = getattr(self, 'id', None)
repos = {x for x in result if x != repo_id and x}
if repos:
raise exceptions.ValidationError(
"Repository with name '{}' already exists".format(self.name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_update(self, user, **kwargs):
""" Sys admin's can change anything If the user is an organisation administrator or created the repository, they may change any field other than "organisation_id" If the user is a service administrator the user may change the "state" but no other fields. """ |
if user.is_admin():
raise Return((True, set([])))
is_creator = self.created_by == user.id
if user.is_org_admin(self.organisation_id) or is_creator:
fields = set([])
if 'organisation_id' in kwargs:
fields.add('organisation_id')
if fields:
raise Return((False, fields))
else:
raise Return((True, set([])))
try:
service = yield Service.get(self.service_id)
if user.is_org_admin(service.organisation_id):
fields = set(kwargs) - {'state'}
if fields:
raise Return((False, fields))
else:
raise Return((True, fields))
except couch.NotFound:
# will be handled in Repository.validate
pass
raise Return((False, 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 with_relations(self, user=None):
""" Return a cleaned dictionary including relations :returns: a Repository instance """ |
repository = self.clean(user=user)
try:
parent = yield self.get_parent()
repository['organisation'] = parent.clean()
except couch.NotFound:
parent = None
repository['organisation'] = {'id': self.parent_id}
service_id = self.service_id
try:
# TODO: cache this lookup
service = yield Service.get(service_id)
repository['service'] = service.clean(user=user)
except couch.NotFound:
# just include the service ID if cannot find the service
repository['service'] = {'id': service_id}
del repository['service_id']
del repository['organisation_id']
raise Return(repository) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def client_secrets(cls, client_id):
""" Get the client's secrets using the client_id :param client_id: the client ID, e.g. a service ID :returns: list OAuthSecret instances """ |
secrets = yield cls.view.get(key=client_id, include_docs=True)
raise Return([cls(**secret['doc']) for secret in secrets['rows']]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.