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 updateFile(cls, file_, url):
"""Check and update file compares with remote_url Args: file_: str. Local filename. Normally it's __file__ Returns: bool: file u... |
def compare(s1, s2):
return s1 == s2, len(s2) - len(s1)
if not url or not file_:
return False
try:
req = urllib.request.urlopen(url)
raw_codes = req.read()
with open(file_, 'rb') as f:
current_codes = f.read().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 ajax(cls, url, param={}, method='get'):
"""Get info by ajax Args: url: string Returns: dict: json decoded into a dict """ |
param = urllib.parse.urlencode(param)
if method.lower() == 'get':
req = urllib.request.Request(url + '?' + param)
elif method.lower() == 'post':
param = param.encode('utf-8')
req = urllib.request.Request(url, data=param)
else:
raise Except... |
<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_dir_meta(fp, atts):
"""Pop path information and map to supplied atts """ |
# Attibutes are popped from deepest directory first
atts.reverse()
dirname = os.path.split(fp)[0]
meta = dirname.split('/')
res = {}
try:
for key in atts:
res[key] = meta.pop()
except IndexError:
raise PathError(dirname)
return 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 trionyx(request):
"""Add trionyx context data""" |
return {
'TX_APP_NAME': settings.TX_APP_NAME,
'TX_LOGO_NAME_START': settings.TX_LOGO_NAME_START,
'TX_LOGO_NAME_END': settings.TX_LOGO_NAME_END,
'TX_LOGO_NAME_SMALL_START': settings.TX_LOGO_NAME_SMALL_START,
'TX_LOGO_NAME_SMALL_END': settings.TX_LOGO_NAME_SMALL_END,
... |
<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, pattern, view=None):
'''Allow decorator-style construction of URL pattern lists.'''
if view is None:
return partial(self.register, pattern)
self.patterns.append(self._make_url((pattern, view)))
return view |
<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_fields(cls, inlcude_base=False, include_id=False):
"""Get model fields""" |
for field in cls._meta.fields:
if field.name == 'deleted':
continue
if not include_id and field.name == 'id':
continue
if not inlcude_base and field.name in ['created_at', 'updated_at']:
continue
yield field |
<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_absolute_url(self):
"""Get model url""" |
return reverse('trionyx:model-view', kwargs={
'app': self._meta.app_label,
'model': self._meta.model_name,
'pk': self.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 parse(self):
"""Parse an asset from Earth Engine to STAC item Raises: ValueError -- If asset is not of type Image or ImageCollection Returns: Item -- STAC fe... |
if self.type == TOKEN_TYPE[0][1]:
try:
return Item(
item_id=self._link(None, None)[1],
links=self._link(None, None)[0],
assets=self._asset(None),
properties=self._properties(None)[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 Genra(request):
""" Generate dict of Dept and its grade. """ |
school = request.GET['school']
c = Course(school=school)
return JsonResponse(c.getGenra(), safe=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 Remove(self,directory,filename):
"""Deletes post from wordpress""" |
db = self._loadDB(directory)
logger.debug("wp: Attempting to remove %s from wp"%(filename))
# See if this already exists in our DB
if db.has_key(filename):
pid=db[filename]
logger.debug('wp: Found %s in DB with post id %s'%(filename,pid))
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eq(self, event_property, value):
"""An equals filter chain. request(elapsed_ms).eq(path, "/") """ |
c = self.copy()
c.filters.append(filters.EQ(event_property, value))
return c |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ne(self, event_property, value):
"""A not-equal filter chain. request(elapsed_ms).ne(path, "/") """ |
c = self.copy()
c.filters.append(filters.NE(event_property, value))
return c |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lt(self, event_property, value):
"""A less-than filter chain. request(elapsed_ms).lt(elapsed_ms, 500) """ |
c = self.copy()
c.filters.append(filters.LT(event_property, value))
return c |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def le(self, event_property, value):
"""A less-than-or-equal-to filter chain. request(elapsed_ms).le(elapsed_ms, 500) """ |
c = self.copy()
c.filters.append(filters.LE(event_property, value))
return c |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gt(self, event_property, value):
"""A greater-than filter chain. request(elapsed_ms).gt(elapsed_ms, 500) """ |
c = self.copy()
c.filters.append(filters.GT(event_property, value))
return c |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ge(self, event_property, value):
"""A greater-than-or-equal-to filter chain. request(elapsed_ms).ge(elapsed_ms, 500) """ |
c = self.copy()
c.filters.append(filters.GE(event_property, value))
return c |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def re(self, event_property, value):
"""A regular expression filter chain. request(elapsed_ms).re(path, "[^A-Za-z0-9+]") """ |
c = self.copy()
c.filters.append(filters.RE(event_property, value))
return c |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def startswith(self, event_property, value):
"""A starts-with filter chain. request(elapsed_ms).re(path, "^/cube") """ |
c = self.copy()
c.filters.append(filters.RE(event_property, "^{value}".format(
value=value)))
return c |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def in_array(self, event_property, value):
"""An in-array filter chain. request(elapsed_ms).in(path, ["/", "e", "v", "e", "n", "t"]) request(elapsed_ms).in(path,... |
c = self.copy()
c.filters.append(filters.IN(event_property, value))
return c |
<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_multiple_data():
"""Get data from all the platforms listed in makerlabs.""" |
# Get data from all the mapped platforms
all_labs = {}
all_labs["diybio_org"] = diybio_org.get_labs(format="dict")
all_labs["fablabs_io"] = fablabs_io.get_labs(format="dict")
all_labs["makeinitaly_foundation"] = makeinitaly_foundation.get_labs(
format="dict")
all_labs["hackaday_io"] = ... |
<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_timeline(source):
"""Rebuild a timeline of the history of makerlabs.""" |
# Set up the pandas timeseries dataframe
timeline_format = ["name", "type", "source", "country", "city", "latitude",
"longitude", "website_url", "twitter_url",
"facebook_page_url", "facebook_group_url",
"whois_start", "whois_end", "wayback_s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_genotypes(self):
"""This really just intializes the file by opening it up. """ |
if DataParser.compressed_pedigree:
self.genotype_file = gzip.open("%s.gz" % self.tped_file, 'rb')
else:
self.genotype_file = open(self.tped_file)
self.filter_missing() |
<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_genotypes(self, data):
"""Parse pedigree line and remove excluded individuals from geno Translates alleles into numerical genotypes (0, 1, 2) countin... |
# Get a list of uniq entries in the data, except for missing
alleles = list(set(data[4:]) - set(DataParser.missing_representation))
if len(alleles) > 2:
raise TooManyAlleles(chr=self.chr, rsid=self.rsid, alleles=alleles)
# We don't have a way to know this in advance, so we ... |
<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_missing(self):
"""Filter out individuals and SNPs that have too many missing to be considered""" |
missing = None
locus_count = 0
# Filter out individuals according to missingness
self.genotype_file.seek(0)
for genotypes in self.genotype_file:
genotypes = genotypes.split()
chr, rsid, junk, pos = genotypes[0:4]
if DataP... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def populate_iteration(self, iteration):
"""Pour the current data into the iteration object""" |
cur_idx = iteration.cur_idx
genotypes = self.genotype_file.next().split()
iteration.chr, iteration.rsid, junk, iteration.pos = genotypes[0:4]
iteration.chr = int(iteration.chr)
iteration.pos = int(iteration.pos)
if DataParser.boundary.TestBoundary(iteration.chr, iterat... |
<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_labs(format):
"""Gets current UK Makerspaces data as listed by NESTA.""" |
ukmakerspaces_data = data_from_nesta()
ukmakerspaces = {}
# Iterate over csv rows
for index, row in ukmakerspaces_data.iterrows():
current_lab = UKMakerspace()
current_lab.address_1 = row["Address"].replace("\r", " ")
current_lab.address_2 = row["Region"].replace("\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 init_self(self, cls, name):
"""Initialize this descriptor instance Parameters cls : class The class which owns this descriptor name : str The attribute name ... |
# the class the descriptor is defined on
self.this_class = cls
# the attribute name of this descriptor
self.this_name = 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_fields(self, **fields):
"""Add new data fields to this struct instance""" |
self.__class__ = type(self.__class__.__name__,
(self.__class__,), fields)
for k, v in fields.items():
v.init_inst(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 del_fields(self, *names):
"""Delete data fields from this struct instance""" |
cls = type(self)
self.__class__ = cls
for n in names:
# don't raise error if a field is absent
if isinstance(getattr(cls, n, None), DataField):
if n in self._field_values:
del self._field_values[n]
delattr(cls, n) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_field(self, name, value):
"""Forcibly sets field values without parsing""" |
f = getattr(self, name, None)
if isinstance(f, DataField):
f.set(self, value)
else:
raise FieldError("No field named '%s'" % 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_success_url(self):
"""Ensure the user-originating redirection URL is safe.""" |
redirect_to = self.request.POST.get(
self.redirect_field_name,
self.request.GET.get(self.redirect_field_name, '')
)
url_is_safe = is_safe_url(
url=redirect_to,
# allowed_hosts=self.get_success_url_allowed_hosts(),
# require_https=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 form_valid(self, form):
"""Security check complete. Log the user in.""" |
auth_login(self.request, form.get_user())
return HttpResponseRedirect(self.get_success_url()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _request(self, method, url, **kwargs):
''' Wrap `utils.requests.request` adding user and password. '''
self._ask_for_password()
return request(method, url, user=self._user, password=self._password,
**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, weeks):
"""Create the user and ip profiles for the given weeks.""" |
user_pageviews = self.create_profiles('Pageviews', weeks)
user_downloads = self.create_profiles('Downloads', weeks)
self._export_profiles('Profiles', user_pageviews, user_downloads)
user_pageviews = self.create_profiles('Pageviews_IP', weeks, True)
user_downloads = self.create... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _export_profiles(self, profile_name, user_pageviews, user_downloads, ip_user=False):
"""Filter and export the user profiles.""" |
views_min = self.config.get('user_views_min')
views_max = self.config.get('user_views_max')
ip_user_id = 500000000000
add_user_id = 100000000000
stat_records = 0
with self.storage.get_user_profiles(profile_name) as store:
store.clear()
for user in... |
<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_profiles(self, prefix, weeks, ip_user=False):
"""Create the user profiles for the given weeks.""" |
# Future: Add a time range in weeks for how long a user is considered
# as the same user.
# Count accessed records
record_counter = {}
for year, week in weeks:
file = self.storage.get(prefix, year, week)
self.count_records(record_counter, file)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_records(self, record_counter, file):
"""Count the number of viewed records.""" |
counter = record_counter
events_counter = 0
for record in file.get_records():
recid = record[2]
counter[recid] = counter.get(recid, 0) + 1
events_counter += 1
self.stat['user_record_events'] = events_counter
return counter |
<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_counter(self, counter, min=2, max=100000000):
""" Filter the counted records. Returns: List with record numbers. """ |
records_filterd = {}
counter_all_records = 0
for item in counter:
counter_all_records += 1
if max > counter[item] >= min:
records_filterd[item] = counter[item]
self.stat['user_record_events'] = counter_all_records
self.stat['records_filte... |
<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_user_profiles(self, profiles, file, valid_records, ip_user=False, year=None, week=None):
""" Create user profiles with all the records visited or dow... |
for record in file.get_records():
recid = record[2]
if not valid_records.get(recid, None):
# Record not valid
continue
if ip_user:
ip = record[4]
user_agent = record[5]
# Generate unique user 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 handle_dims(opts):
'''
Script option handling.
'''
use,res = [],[];
if opts['--X']:
use.append('x');
res.append(int(opts['--xres']));
if opts['--Y']:
use.append('y');
res.append(int(opts['--yres']));
if opts['--Z']:
use.append('z');
res.app... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _temporary_filenames(total):
"""Context manager to create temporary files and remove them after use.""" |
temp_files = [_get_temporary_filename('optimage-') for i in range(total)]
yield temp_files
for temp_file in temp_files:
try:
os.remove(temp_file)
except OSError:
# Continue in case we could not remove the file. One reason is that
# the fail was never crea... |
<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(compressor, input_filename, output_filename):
"""Helper function to compress an image. Returns: _CompressorResult named tuple, with the resulting si... |
compressor(input_filename, output_filename)
result_size = os.path.getsize(output_filename)
return _CompressorResult(result_size, output_filename, compressor.__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 _compress_with(input_filename, output_filename, compressors):
"""Helper function to compress an image with several compressors. In case the compressors do no... |
with _temporary_filenames(len(compressors)) as temp_filenames:
results = []
for compressor, temp_filename in zip(compressors, temp_filenames):
results.append(_process(compressor, input_filename, temp_filename))
best_result = min(results)
os.rename(best_result.filename, o... |
<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_map(map_obj, lat, lon, date_time, key, cluster_obj):
"""Add individual elements to a foilum map in a cluster object""" |
text = "Event {0} at {1}".format(key, date_time.split()[1])
folium.Marker([lat, lon], popup=text).add_to(cluster_obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sign(hash,priv,k=0):
'''
Returns a DER-encoded signature from a input of a hash and private
key, and optionally a K value.
Hash and private key inputs must be 64-char hex strings,
k input is an int/long.
>>> h = 'f7011e94125b5bba7f62eb25efe23339eb1637539206c87df3ee61b5ec6b023e'
>>> 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 verify(hash,sig,pub,exceptonhighS=False):
'''
Verify a DER-encoded signature against a given hash and public key
No checking of format is done in this function, so the signature
format (and other inputs) should be verified as being the correct
format prior to using this method.
Hash is jus... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def checksigformat(a,invalidatehighS=False):
'''
Checks input to see if it's a correctly formatted DER Bitcoin
signature in hex string format.
Returns True/False. If it excepts, there's a different problem
unrelated to the signature...
This does NOT valid the signature in any way, it ONLY che... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def param_converter(*decorator_args, **decorator_kwargs):
""" Call with the url parameter names as keyword argument keys, their values being the model to convert... |
def wrapped(fn):
@wraps(fn)
def decorated(*view_args, **view_kwargs):
view_kwargs = _convert_models(view_kwargs, decorator_kwargs)
view_kwargs = _convert_query_params(view_kwargs, decorator_kwargs)
return fn(*view_args, **view_kwargs)
return decorated
... |
<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(name, filepath, separator="---"):
"""Load given file into knowledge base. Simply load data into an existing knowledge base: .. code-block:: console $ in... |
current_app.logger.info(
">>> Going to load knowledge base {0} into '{1}'...".format(
filepath, name
)
)
if not os.path.isfile(filepath):
current_app.logger.error(
"Path to non-existing file\n",
file=sys.stderr
)
sys.exit(1)
tr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Run manager.""" |
from invenio_base.factory import create_app
app = create_app()
manager.app = app
manager.run() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def command(func):
"""Decorator for CLI exposed functions""" |
func.parser = SUB_PARSER.add_parser(func.__name__, help=func.__doc__)
func.parser.set_defaults(func=func)
return func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serv(args):
"""Serve a rueckenwind application""" |
if not args.no_debug:
tornado.autoreload.start()
extra = []
if sys.stdout.isatty():
# set terminal title
sys.stdout.write('\x1b]2;rw: {}\x07'.format(' '.join(sys.argv[2:])))
if args.cfg:
extra.append(os.path.abspath(args.cfg))
listen = (int(args.port), args.addre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Entry point of rw cli""" |
# check logging
log_level = os.environ.get('LOG_LEVEL', 'INFO')
logging.basicConfig(level=getattr(logging, log_level),
format='%(asctime)s %(name)s[%(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
current_path = os.path.abspath('.')
if curre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _checker(keywords):
"""Generate a checker which tests a given value not starts with keywords.""" |
def _(v):
"""Check a given value matches to keywords."""
for k in keywords:
if k in v:
return False
return True
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 _parse_doc(doc):
"""Parse a docstring. Parse a docstring and extract three components; headline, description, and map of arguments to help texts. Args: doc: ... |
lines = doc.split("\n")
descriptions = list(itertools.takewhile(_checker(_KEYWORDS), lines))
if len(descriptions) < 3:
description = lines[0]
else:
description = "{0}\n\n{1}".format(
lines[0], textwrap.dedent("\n".join(descriptions[2:])))
args = list(itertools.takewhil... |
<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_parser(self, func=None, name=None, **kwargs):
"""Add parser. This method makes a new sub command parser. It takes same arguments as add_parser() of the a... |
if func:
if not func.__doc__:
raise ValueError(
"No docstrings given in {0}".format(func.__name__))
info = _parse_doc(func.__doc__)
if _HELP not in kwargs or not kwargs[_HELP]:
kwargs[_HELP] = info["headline"]
... |
<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_argument(self, *args, **kwargs):
"""Add an argument. This method adds a new argument to the current parser. The function is same as ``argparse.ArgumentPa... |
if _HELP not in kwargs:
for name in args:
name = name.replace("-", "")
if name in self.__argmap:
kwargs[_HELP] = self.__argmap[name]
break
return super(ArgumentParser, self).add_argument(*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 __user_location(__pkg: str, type_) -> str: """Utility function to look up XDG basedir locations Args: __pkg: Package name __type: Location type """ |
if ALLOW_DARWIN and sys.platform == 'darwin':
user_dir = '~/Library/{}'.format(__LOCATIONS[type_][0])
else:
user_dir = getenv('XDG_{}_HOME'.format(type_.upper()),
path.sep.join([getenv('HOME', ''),
__LOCATIONS[type_][1]]))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_configs(__pkg: str, __name: str = 'config') -> List[str]: """Return all configs for given package. Args: __pkg: Package name __name: Configuration file na... |
dirs = [user_config(__pkg), ]
dirs.extend(path.expanduser(path.sep.join([d, __pkg]))
for d in getenv('XDG_CONFIG_DIRS', '/etc/xdg').split(':'))
configs = []
for dname in reversed(dirs):
test_path = path.join(dname, __name)
if path.exists(test_path):
configs.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_data(__pkg: str, __name: str) -> str: """Return top-most data file for given package. Args: __pkg: Package name __name: Data file name """ |
for dname in get_data_dirs(__pkg):
test_path = path.join(dname, __name)
if path.exists(test_path):
return test_path
raise FileNotFoundError('No data file {!r} for {!r}'.format(__name, __pkg)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_data_dirs(__pkg: str) -> List[str]: """Return all data directories for given package. Args: __pkg: Package name """ |
dirs = [user_data(__pkg), ]
dirs.extend(path.expanduser(path.sep.join([d, __pkg]))
for d in getenv('XDG_DATA_DIRS',
'/usr/local/share/:/usr/share/').split(':'))
return [d for d in dirs if path.isdir(d)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def replay_messages(filepath, process_message, *args, **kwargs):
''' Take pulse messages from a file and process each with process_message.
:param filepath: File containing dumped pulse messages
:type filepath: str
:param process_message: Function to process each pulse message with
:type process_me... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize_path(path, filetype=None, has_filetype=True):
""" Convert dot-separated paths to directory paths Allows non-python files to be placed in the PYTHON... |
if not isinstance(path, str):
return path
if '.' in path and os.path.sep not in path: # path is dot separated
parts = path.split('.')
extension = ''
if len(parts) > 1:
if filetype and has_filetype:
has_filetype = False # filetype is more specific
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
""" Executes a list of functions and returns the first non none result. All kwargs will be passed as kwargs to each individual function. If all functions return N... |
Validator.is_real_iterable(raise_ex=True, eval_list=eval_list)
for eval_fun in eval_list:
res = eval_fun(**kwargs)
if res is not None:
return res
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 on_person_new(self, people):
""" New people joined the audience :param people: People that just joined the audience :type people: list[paps.person.Person] :r... |
self.debug("()")
changed = []
with self._people_lock:
for p in people:
person = Person.from_person(p)
if person.id in self._people:
self.warning(
u"{} already in audience".format(person.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 normalize_col_name(self, col_name, used_column_names, is_relation):
""" Modify the column name to make it Python-compatible as a field name """ |
field_params = {}
field_notes = []
new_name = col_name.lower()
if new_name != col_name:
field_notes.append('Field name made lowercase.')
if is_relation:
if new_name.endswith('_id'):
new_name = new_name[:-3]
else:
... |
<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_field_type(self, connection, table_name, row):
""" Given the database connection, the table name, and the cursor row description, this routine will retur... |
field_params = {}
field_notes = []
try:
field_type = connection.introspection.get_field_type(row[1], row)
except KeyError:
field_type = 'TextField'
field_notes.append('This field type is a guess.')
# This is a hook for DATA_TYPES_REVERSE to ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def MonSQL(host=None, port=None, username=None, password=None, dbname=None, dbpath=None, dbtype=None):
""" Initialize and return a Database instance """ |
if dbtype is None:
raise MonSQLException('Database type must be specified')
if dbtype == DB_TYPES.MYSQL:
return MySQLDatabase(host, port, username, password, dbname)
elif dbtype == DB_TYPES.SQLITE3:
return SQLite3Database(dbpath)
elif dbtype == DB_TYPES.POSTGRESQL:
return PostgreSQLDatabase(host, port, 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 check_password(self, raw_password):
""" Returns a boolean of whether the raw_password was correct. Handles hashing formats behind the scenes. """ |
def setter(raw_password):
self.set_password(raw_password)
self.save(update_fields=[self.PASSWORD_FIELD])
return check_password(raw_password, getattr(self, self.PASSWORD_FIELD), setter) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_context_data(self, **kwargs):
""" Insert the form into the context dict. """ |
for key in self.get_form_class_keys():
kwargs['{}_form'.format(key)] = self.get_form(key)
return super(FormMixin, self).get_context_data(**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 form_valid(self, forms):
""" If the form is valid, save the associated model. """ |
for key, form in forms.items():
setattr(self, '{}_object'.format(key), form.save())
return super(MultipleModelFormMixin, self).form_valid(forms) |
<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_on_site(self, request, content_type_id, object_id):
""" Redirect to an object's page based on a content-type ID and an object ID. """ |
# Look up the object, making sure it's got a get_absolute_url() function.
try:
content_type = ContentType.objects.get(pk=content_type_id)
if not content_type.model_class():
raise Http404(_("Content type %(ct_id)s object has no associated model") % {
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_graderoster(section, instructor, requestor):
""" Returns a restclients.GradeRoster for the passed Section model and instructor Person. """ |
label = GradeRoster(section=section,
instructor=instructor).graderoster_label()
url = "{}/{}".format(graderoster_url, encode_section_label(label))
headers = {"Accept": "text/xhtml",
"Connection": "keep-alive",
"X-UW-Act-as": requestor.uwnetid}
resp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_graderoster(graderoster, requestor):
""" Updates the graderoster resource for the passed restclients.GradeRoster model. A new restclients.GradeRoster ... |
label = graderoster.graderoster_label()
url = "{}/{}".format(graderoster_url, encode_section_label(label))
headers = {"Content-Type": "application/xhtml+xml",
"Connection": "keep-alive",
"X-UW-Act-as": requestor.uwnetid}
body = graderoster.xhtml()
response = SWS_Grade... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def netdevs():
''' RX and TX bytes for each of the network devices '''
with open('/proc/net/dev') as f:
net_dump = f.readlines()
device_data={}
data = namedtuple('data',['rx','tx'])
for line in net_dump[2:]:
line = line.split(':')
if line[0].strip() != 'lo':
... |
<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_model(self, model, model_id):
"""Get a single model from the server. Args: model (string):
The class as a string. model_id (string):
The integer ID as ... |
return self._store.find_record(self._get_model_class(model), int(model_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 get_models(self, model, page=None):
"""Get all the models from the server. Args: model (string):
The class as a string. page (string, optional):
The page n... |
if page is not None:
return self._store.find_all(self._get_model_class(model), params={'page': int(page)})
else:
return self._store.find_all(self._get_model_class(model)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makeFigFromFile(filename,*args,**kwargs):
""" Renders an image in a matplotlib figure, so it can be added to reports args and kwargs are passed to plt.subplo... |
import matplotlib.pyplot as plt
img = plt.imread(filename)
fig,ax = plt.subplots(*args,**kwargs)
ax.axis('off')
ax.imshow(img)
return fig |
<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_exes(self):
"""List the installed executables by this project.""" |
return [path.join(self.env_bin, f)
for f
in os.listdir(self.env_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 create_env(self):
"""Create a virtual environment.""" |
virtualenv(self.env, _err=sys.stderr)
os.mkdir(self.env_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 install_program(self, extra_args):
"""Install the app to the virtualenv""" |
pip = Command(path.join(self.env, 'bin', 'pip'))
args = ['install', self.raw_name,
'--install-option', '--install-scripts={}'
.format(self.env_bin)] + list(extra_args)
print_pretty("<BOLD>pip {}<END>\n".format(' '.join(args)))
pip(args, _out=sys.stdout, _... |
<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_links(self):
"""Create links to installed scripts in the virtualenv's bin directory to our bin directory. """ |
for link in self.list_exes():
print_pretty("<FG_BLUE>Creating link for {}...<END>".format(link))
os.symlink(link, path.join(ENV_BIN, path.basename(link))) |
<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_links(self):
"""Remove links from our bin.""" |
for link in self.list_exes():
link = path.join(ENV_BIN, path.basename(link))
print_pretty("<FG_BLUE>Removing link {}...<END>".format(link))
os.remove(link) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uninstall(self):
"""Uninstall the environment and links.""" |
if path.isdir(self.env_bin):
self.remove_links()
if path.isdir(self.env):
print_pretty("<FG_BLUE>Removing env {}...<END>".format(self.env))
shutil.rmtree(self.env) |
<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, pip_args=None):
"""Install the program and put links in place.""" |
if path.isdir(self.env):
print_pretty("<FG_RED>This seems to already be installed.<END>")
else:
print_pretty("<FG_BLUE>Creating environment {}...<END>\n".format(self.env))
self.create_env()
self.install_program(pip_args)
self.create_links() |
<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_git(config_info):
"""This function initializes and Git SCM tool object.""" |
git_args = {}
def _add_value(value, key):
args_key, args_value = _GIT_ARG_FNS[key](value)
git_args[args_key] = args_value
devpipeline_core.toolsupport.args_builder("git", config_info, _GIT_ARGS, _add_value)
if git_args.get("uri"):
return devpipeline_scm.make_simple_scm(Git(git... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checkout(self, repo_dir, shared_dir, **kwargs):
"""This function checks out code from a Git SCM server.""" |
del kwargs
args = []
for checkout_fn in _CHECKOUT_ARG_BUILDERS:
args.extend(checkout_fn(shared_dir, repo_dir, self._args))
return args |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, repo_dir, **kwargs):
"""This function updates an existing checkout of source code.""" |
del kwargs
rev = self._args.get("revision")
if rev:
return [{"args": ["git", "checkout", rev], "cwd": repo_dir}] + _ff_command(
rev, repo_dir
)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_absorption(line, lines):
"""Parse Energy, Re sigma xx, Re sigma zz, absorp xx, absorp zz""" |
split_line = line.split()
energy = float(split_line[0])
re_sigma_xx = float(split_line[1])
re_sigma_zz = float(split_line[2])
absorp_xx = float(split_line[3])
absorp_zz = float(split_line[4])
return {"energy": energy, "re_sigma_xx": re_sigma_xx, "re_sigma_zz": re_sigma_zz,
"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 args(parsed_args, name=None):
"""Interpret parsed args to streams""" |
strings = parsed_args.arg_strings(name)
files = [s for s in strings if os.path.isfile(s)]
if files:
streams = [open(f) for f in files]
else:
streams = []
if getattr(parsed_args, 'paste', not files):
streams.append(clipboard_stream())
if getattr(parsed_args, 'stdin', Fals... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(argv=None):
"""Execute each module in the same interpreter. Args: argv: Each item of argv will be treated as a separate module with potential arguments ... |
if argv is None:
argv = sys.argv[1:]
args = _get_parser().parse_args(argv)
mand(args.module_seq) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_multiple_modules(module_gen):
"""Call each module module_gen should be a iterator """ |
for args_seq in module_gen:
module_name_or_path = args_seq[0]
with replace_sys_args(args_seq):
if re.match(VALID_PACKAGE_RE, module_name_or_path):
runpy.run_module(module_name_or_path,
run_name='__main__')
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace_sys_args(new_args):
"""Temporarily replace sys.argv with current arguments Restores sys.argv upon exit of the context manager. """ |
# Replace sys.argv arguments
# for module import
old_args = sys.argv
sys.argv = new_args
try:
yield
finally:
sys.argv = old_args |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_bim(self, map3=False):
"""Basic marker details loading. (chr, rsid, gen. dist, pos, allelel 1, allele2) :param map3: When true, ignore the genetic dista... |
cols = [0, 1, 3, 4, 5]
if map3:
cols = [0, 1, 2, 3, 4]
logging.info("Loading file: %s" % self.bim_file)
val = sys_call('wc -l %s' % (self.bim_file))[0][0].split()[0]
marker_count = int(val)
self.markers = numpy.zeros((marker_count, 2), dtype=int)
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 init_genotype_file(self):
"""Resets the bed file and preps it for starting at the start of the \ genotype data Returns to beginning of file and reads the ver... |
self.genotype_file.seek(0)
buff = self.genotype_file.read(3)
version = 0
magic, data_format = buff.unpack("HB", version)
return magic, data_format |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_genotypes(self, bytes):
"""Extracts encoded genotype data from binary formatted file. :param bytes: array of bytes pulled from the .bed file :return:... |
genotypes = []
for b in bytes:
for i in range(0, 4):
v = ((b>>(i*2)) & 3)
genotypes.append(self.geno_conversions[v])
return genotypes[0:self.ind_count] |
<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_missing(self):
"""Filter out individuals and SNPs that have too many missing to be \ considered :return: None This must be run prior to actually parsi... |
missing = None
locus_count = 0
logging.info("Sorting out missing data from genotype data")
# Filter out individuals according to missingness
self.genotype_file.seek(0)
magic, data_format = struct.unpack("<HB", self.genotype_file.read(3))
if d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def full_path(path):
"""Get the real path, expanding links and bashisms""" |
return os.path.realpath(os.path.expanduser(os.path.expandvars(path))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, generator):
"""Parse an iterable source of strings into a generator""" |
gen = iter(generator)
for line in gen:
block = {}
for rule in self.rules:
if rule[0](line):
block = rule[1](line, gen)
break
yield block |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ReportConfiguration(self, file):
"""Report the configuration details for logging purposes. :param file: Destination for report details :return: None """ |
global encodingpar
print >> file, libgwas.BuildReportLine("MACH_ARCHIVES", "")
if self.chrpos_encoding:
print >> file, libgwas.BuildReportLine("MACH_CHRPOS",
("IDS expected to be in format chr:pos" +
" SNP bound... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.