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)
... |
<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 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 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... |
<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]))
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 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 ``C... |
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_ke... |
<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.
Ad... |
<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.fla... |
<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'}})
... |
<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 leg... |
<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:
committee... |
<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'... |
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... |
<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'))
... |
<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'))
... |
<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")
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 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.ge... |
<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. F... |
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... |
<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-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 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 co... |
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[... |
<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
retu... |
<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... |
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',
... |
<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 save... |
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'])
... |
<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, va... |
<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
serv... |
<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_ty... |
<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... |
<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']
yie... |
<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)
... |
<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_}
... |
<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:]
re... |
<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
... |
<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... |
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 = pack... |
<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 yo... |
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_dec... |
<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.getL... |
<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... |
<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)
... |
<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 :retur... |
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... |
<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... |
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)
... |
<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 m... |
# 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 + ' ' + li... |
<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_fil... |
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.... |
<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 (stri... |
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... |
<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.... |
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 =... |
<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)
gr... |
<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 wh... |
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 *... |
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('p... |
<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 thr... |
# 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)
... |
<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)
... |
<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 = ... |
<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.
# Wit... |
<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 us... |
<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 t... |
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 t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 ou... |
<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 res... |
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' permis... |
<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 de... |
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_deactivat... |
<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 st... |
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 ... |
<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 followi... |
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)... |
<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
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 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 organi... |
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(**res... |
<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()))
... |
<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 ... |
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" :... |
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]
... |
<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(... |
<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.... |
<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... |
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... |
<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
... |
<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 OAuthSecre... |
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.