text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_tabs(self, model_alias, object):
""" Get all active tabs for given model :param model_alias: :param object: Object used to filter tabs :return: """ |
model_alias = self.get_model_alias(model_alias)
for item in self.tabs[model_alias]:
if item.display_filter(object):
yield item |
<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_tab(self, model_alias, object, tab_code):
""" Get tab for given object and tab code :param model_alias: :param object: Object used to render tab :param t... |
model_alias = self.get_model_alias(model_alias)
for item in self.tabs[model_alias]:
if item.code == tab_code and item.display_filter(object):
return item
raise Exception('Given tab does not exits or is filtered') |
<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_alias, code='general', name=None, order=None, display_filter=None):
""" Register new tab :param model_alias: :param code: :param name: :... |
model_alias = self.get_model_alias(model_alias)
def wrapper(create_layout):
item = TabItem(
code=code,
create_layout=create_layout,
name=name,
order=order,
display_filter=display_filter
)
... |
<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, model_alias, code='general', name=None, order=None, display_filter=None):
""" Update given tab :param model_alias: :param code: :param name: :pa... |
model_alias = self.get_model_alias(model_alias)
for item in self.tabs[model_alias]:
if item.code != code:
continue
if name:
item.name = name
if order:
item.order = order
if display_filter:
it... |
<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_alias(self, model_alias):
"""Get model alias if class then convert to alias string""" |
from trionyx.models import BaseModel
if inspect.isclass(model_alias) and issubclass(model_alias, BaseModel):
config = models_config.get_config(model_alias)
return '{}.{}'.format(config.app_label, config.model_name)
return model_alias |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auto_generate_missing_tabs(self):
"""Auto generate tabs for models with no tabs""" |
for config in models_config.get_all_configs():
model_alias = '{}.{}'.format(config.app_label, config.model_name)
if model_alias not in self.tabs:
@self.register(model_alias)
def general_layout(obj):
return Layout(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def name(self):
"""Give back tab name if is set else generate name by code""" |
if self._name:
return self._name
return self.code.replace('_', ' ').capitalize() |
<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_layout(self, object):
"""Get complete layout for given object""" |
layout = self.create_layout(object)
if isinstance(layout, Component):
layout = Layout(layout)
if isinstance(layout, list):
layout = Layout(*layout)
for update_layout in self.layout_updates:
update_layout(layout, object)
layout.set_object(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 main():
""" Main entry point for the script. Create a parser, process the command line, and run it """ |
parser = cli.Cli()
parser.parse(sys.argv[1:])
return parser.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 run_backup(filename, root_dir, ignore=[], ignore_ext=[], ignore_pattern=[]):
"""The backup utility method. :param root_dir: the directory you want to backup ... |
tab = " "
# Step 1, calculate files to backup
print("Perform backup '%s'..." % root_dir)
print(tab + "1. Calculate files...")
total_size_in_bytes = 0
init_mode = WinFile.init_mode
WinFile.use_regular_init()
fc = FileCollection.from_path_except(
root_dir, ignore, ignore_ext, i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prompt_file(prompt, default=None):
"""Prompt a file name with autocompletion""" |
def complete(text: str, state):
text = text.replace('~', HOME)
sugg = (glob.glob(text + '*') + [None])[state]
if sugg is None:
return
sugg = sugg.replace(HOME, '~')
sugg = sugg.replace('\\', '/')
if os.path.isdir(sugg) and not sugg.endswith('/'):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isprime(n):
"""Check the number is prime value. if prime value returns True, not False.""" |
n = abs(int(n))
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
# 在一般领域, 对正整数n, 如果用2 到 sqrt(n) 之间所有整数去除, 均无法整除, 则n为质数.
for x in range(3, int(n ** 0.5)+1, 2):
if n % x == 0:
return False
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 create(self):
"""Create an application context on the server""" |
self.before_create()
puts(green('Creating app context'))
tdir = os.path.dirname(__file__)
# Ensure the app context user exists
user_ensure(self.user, home='/home/' + self.user)
dir_ensure('/home/%s/.ssh' % self.user)
t = '/home/%s/.ssh/authorized_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 upload_release(self):
"""Upload an application bundle to the server for a given context""" |
self.before_upload_release()
with settings(user=self.user):
with app_bundle():
local_bundle = env.local_bundle
env.bundle = '/tmp/' + os.path.basename(local_bundle)
file_upload(env.bundle, local_bundle)
# Extract the bundle into ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _print_breakdown(cls, savedir, fname, data):
"""Function to print model fixtures into generated file""" |
if not os.path.exists(savedir):
os.makedirs(savedir)
with open(os.path.join(savedir, fname), 'w') as fout:
fout.write(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 read_json_breakdown(cls, fname):
"""Read json file to get fixture data""" |
if not os.path.exists(fname):
raise RuntimeError
with open(fname, 'r') as data_file:
return cls.fixup_from_json(data_file.read()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, fetchcommand, sql, params=None):
""" where 'fetchcommand' is either 'fetchone' or 'fetchall' """ |
cur = self.conn.cursor()
if params:
if not type(params).__name__ == 'tuple':
raise ValueError('the params argument needs to be a tuple')
return None
cur.execute(sql, params)
else:
cur.execute(sql)
self.conn.commit()
if not fetchcommand or fetchcommand == 'none':
return
if fetchcomma... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cp_parents(files, target_dir: Union[str, Path]):
""" This function requires Python >= 3.6. This acts like bash cp --parents in Python inspiration from http:/... |
# %% make list if it's a string
if isinstance(files, (str, Path)):
files = [files]
# %% cleanup user
# relative path or absolute path is fine
files = (Path(f).expanduser() for f in files)
target_dir = Path(target_dir).expanduser()
# %% work
for f in files:
# to make it work like cp ... |
<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_plot_params(theme=None):
""" set plot parameters for session, as an alternative to manipulating RC file """ |
# set solarized color progression no matter what
mpl.rcParams['axes.color_cycle'] = ('268bd2, dc322f, 859900, ' +
'b58900, d33682, 2aa198, ' +
'cb4b16, 002b36')
# non-color options are independent as well
mpl.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 handle(self, *args, **options):
"""Load a default admin user""" |
try:
admin = User.objects.get(username='admin')
except User.DoesNotExist:
admin = User(
username='admin',
first_name='admin',
last_name='admin',
email='admin@localhost.localdomain',
is_staff=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 left_zero_pad(s, blocksize):
""" Left padding with zero bytes to a given block size :param s: :param blocksize: :return: """ |
if blocksize > 0 and len(s) % blocksize:
s = (blocksize - len(s) % blocksize) * b('\000') + s
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_bot(user_agent):
"""Check if user_agent is a known bot.""" |
bot_list = [
'http://www.baidu.com/search/spider.html',
'python-requests',
'http://ltx71.com/',
'http://drupal.org/',
'www.sogou.com',
'http://search.msn.com/msnbot.htm',
'semantic-visions.com crawler',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_download(ending):
"""Check if file ending is considered as download.""" |
list = [
'PDF',
'DOC',
'TXT',
'PPT',
'XLSX',
'MP3',
'SVG',
'7Z',
'HTML',
'TEX',
'MPP',
'ODT',
'RAR',
'ZIP',
'TAR',
'EPUB',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self, year, week, overwrite=False):
"""Fetch PageViews and Downloads from Elasticsearch.""" |
self.config['overwrite_files'] = overwrite
time_start = time.time()
self._fetch_pageviews(self.storage, year, week, ip_users=False)
self._fetch_downloads(self.storage, year, week, ip_users=False)
# CDS has no user_agent before this date 1433400000:
self._fetch_pageviews(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fetch_pageviews(self, storage, year, week, ip_users=False):
""" Fetch PageViews from Elasticsearch. :param time_from: Staring at timestamp. :param time_to: ... |
prefix = 'Pageviews'
if ip_users:
query_add = "AND !(bot:True) AND (id_user:0)"
prefix += '_IP'
else:
query_add = "AND !(bot:True) AND !(id_user:0)"
store = self.storage.get(prefix, year, week)
if not self.config['overwrite_files'] and store.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 _fetch_elasticsearch(self, es_query):
""" Load data from Elasticsearch. :param query: TODO :param time_from: TODO :param time_to: TODO :returns: TODO """ |
# TODO: Show error if index is not found.
scanResp = self._esd.search(index=self.config['es_index'],
body=es_query, size=2000,
search_type="scan", scroll="10000",
timeout=900, request_timeout=900... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump_queue(self, *names):
"""Debug-log some of the queues. ``names`` may include any of "worker", "available", "priorities", "expiration", "workers", or "res... |
conn = redis.StrictRedis(connection_pool=self.pool)
for name in names:
if name == 'worker':
logger.debug('last worker: ' + conn.get(self._key_worker()))
elif name == 'available':
logger.debug('available: ' +
str(conn.z... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def worker_id(self):
"""A unique identifier for this queue instance and the items it owns.""" |
if self._worker_id is not None: return self._worker_id
return self._get_worker_id(self._conn()) |
<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_worker_id(self, conn):
"""Get the worker ID, using a preestablished connection.""" |
if self._worker_id is None:
self._worker_id = conn.incr(self._key_worker())
return self._worker_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 add_item(self, item, priority):
"""Add ``item`` to this queue. It will have the specified ``priority`` (highest priority runs first). If it is already in the... |
conn = self._conn()
self._run_expiration(conn)
script = conn.register_script("""
if (redis.call("hexists", KEYS[2], ARGV[1]) ~= 0) and
not(redis.call("zscore", KEYS[1], ARGV[1]))
then
return -1
end
redis.call("zadd", KEYS[1], ARGV[2], ARGV[... |
<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_out_item(self, expiration):
"""Get the highest-priority item out of this queue. Returns the item, or None if no items are available. The item must be e... |
conn = redis.StrictRedis(connection_pool=self.pool)
self._run_expiration(conn)
expiration += time.time()
script = conn.register_script("""
local item = redis.call("zrevrange", KEYS[1], 0, 0)
if #item == 0 then return nil end
item = item[1]
redis.call("zre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def renew_item(self, item, expiration):
"""Update the expiration time for ``item``. The item will remain checked out for ``expiration`` seconds beyond the curren... |
conn = self._conn()
self._run_expiration(conn)
expiration += time.time()
script = conn.register_script("""
-- already expired?
if redis.call("hget", KEYS[2], "i" .. ARGV[1]) ~= "w" .. ARGV[3]
then return -1 end
-- otherwise just update the expiration
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reserve_items(self, parent_item, *items):
"""Reserve a set of items until a parent item is returned. Prevent ``check_out_item()`` from returning any of ``ite... |
conn = redis.StrictRedis(connection_pool=self.pool)
self._run_expiration(conn)
script = conn.register_script("""
-- expired?
if redis.call("hget", KEYS[2], "i" .. ARGV[1]) ~= "w" .. ARGV[2]
then return -1 end
-- loop through each item
local result = {}
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _run_expiration(self, conn):
"""Return any items that have expired.""" |
# The logic here is sufficiently complicated, and we need
# enough random keys (Redis documentation strongly encourages
# not constructing key names in scripts) that we'll need to
# do this in multiple steps. This means that, when we do
# go in and actually expire things, we ne... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def cleanup_sweep_threads():
'''
Not used. Keeping this function in case we decide not to use
daemonized threads and it becomes necessary to clean up the
running threads upon exit.
'''
for dict_name, obj in globals().items():
if isinstance(obj, (TimedDict,)):
logging.info(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def set_expiration(self, key, ignore_missing=False,
additional_seconds=None, seconds=None):
'''
Alters the expiration time for a key. If the key is not
present, then raise an Exception unless `ignore_missing`
is set to `True`.
Args:
key: The key whose exp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def expire_key(self, key):
'''
Expire the key, delete the value, and call the callback function
if one is specified.
Args:
key: The ``TimedDict`` key
'''
value = self.base_dict[key]
del self[key]
if self.callback is not None:
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 _open(self, file_path=None):
""" Opens the file specified by the given path. Raises ValueError if there is a problem with opening or reading the file. ... |
if file_path is None:
file_path = self.file_path
if not os.path.exists(file_path):
raise ValueError('Could not find file: {}'.format(file_path))
try:
f = open(file_path, encoding='utf-8', newline='')
except OSError as err:
self.log.error(str(err))
raise ValueError('Could not open file: {}'.for... |
<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_dialect(self):
""" Returns a Dialect named tuple or None if the dataset file comprises a single column of data. If the dialect is not already known... |
if self.is_single_col:
return None
if self.delimiter and self.quotechar:
return Dialect(self.delimiter, self.quotechar,
True if self.escapechar is None else False,
self.escapechar)
ext = os.path.basename(self.file_path).rsplit('.', maxsplit=1)
ext = ext[1].lower() if len(ext) > 1 else None
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_csv_reader(self, f, dialect):
""" Returns a csv.reader for the given file handler and csv Dialect named tuple. If the file has a header, it alread... |
reader = csv.reader(f,
delimiter = dialect.delimiter,
quotechar = dialect.quotechar,
doublequote = dialect.doublequote,
escapechar = dialect.escapechar)
if self.has_header:
header = next(reader)
if not isinstance(self.ipa_col, int):
self.ipa_col = self._infer_ipa_col(header)
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 gen_ipa_data(self):
""" Generator for iterating over the IPA strings found in the dataset file. Yields the IPA data string paired with the respective l... |
dialect = self.get_dialect()
f = self._open()
try:
if dialect:
for res in self._gen_csv_data(f, dialect):
yield res
else:
for res in self._gen_txt_data(f):
yield res
finally:
f.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _findAll(self, name, attrs, text, limit, generator, **kwargs):
"Iterates over a generator looking for things that match."
if isinstance(name, SoupStrainer):
strainer = name
# (Possibly) special case some findAll*(...) searches
elif text is None and not limit and not attr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decompose(self):
"""Recursively destroys the contents of this tree.""" |
self.extract()
if len(self.contents) == 0:
return
current = self.contents[0]
while current is not None:
next = current.next
if isinstance(current, Tag):
del current.contents[:]
current.parent = None
current.prev... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _smartPop(self, name):
"""We need to pop up to the previous tag of this type, unless one of this tag's nesting reset triggers comes between this tag and the ... |
nestingResetTriggers = self.NESTABLE_TAGS.get(name)
isNestable = nestingResetTriggers != None
isResetNesting = self.RESET_NESTING_TAGS.has_key(name)
popTo = None
inclusive = True
for i in range(len(self.tagStack)-1, 0, -1):
p = self.tagStack[i]
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _subMSChar(self, orig):
"""Changes a MS smart quote character to an XML or HTML entity.""" |
sub = self.MS_CHARS.get(orig)
if isinstance(sub, tuple):
if self.smartQuotesTo == 'xml':
sub = '&#x%s;' % sub[1]
else:
sub = '&%s;' % sub[0]
return sub |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_file_values(env_file, fail_silently=True):
""" Borrowed from Honcho. """ |
env_data = {}
try:
with open(env_file) as f:
content = f.read()
except IOError:
if fail_silently:
logging.error("Could not read file '{0}'".format(env_file))
return env_data
raise
for line in content.splitlines():
m1 = re.match(r'\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_suffix(path):
""" Return suffix from `path`. ``/home/xex/somefile.txt`` --> ``txt``. Args: path (str):
Full file path. Returns: str: Suffix. Raises: Us... |
suffix = os.path.basename(path).split(".")[-1]
if "/" in suffix:
raise UserWarning("Filename can't contain '/' in suffix (%s)!" % path)
return suffix |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SRU_Compute_CPU(activation_type, d, bidirectional=False, scale_x=1):
"""CPU version of the core SRU computation. Has the same interface as SRU_Compute_GPU() ... |
def sru_compute_cpu(u, x, bias, init=None, mask_h=None):
bidir = 2 if bidirectional else 1
length = x.size(0) if x.dim() == 3 else 1
batch = x.size(-2)
k = u.size(-1) // d // bidir
if mask_h is None:
mask_h = 1
u = u.view(length, batch, bidir, d, k)
... |
<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_encoding(binary):
"""Return the encoding type.""" |
try:
from chardet import detect
except ImportError:
LOGGER.error("Please install the 'chardet' module")
sys.exit(1)
encoding = detect(binary).get('encoding')
return 'iso-8859-1' if encoding == 'CP949' else encoding |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getch():
"""Request a single character input from the user.""" |
if sys.platform in ['darwin', 'linux']:
import termios
import tty
file_descriptor = sys.stdin.fileno()
settings = termios.tcgetattr(file_descriptor)
try:
tty.setraw(file_descriptor)
return sys.stdin.read(1)
finally:
termios.tcseta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ismatch(text, pattern):
"""Test whether text contains string or matches regex.""" |
if hasattr(pattern, 'search'):
return pattern.search(text) is not None
else:
return pattern in text if Config.options.case_sensitive \
else pattern.lower() in text.lower() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logger():
"""Configure program logger.""" |
scriptlogger = logging.getLogger(__program__)
# ensure logger is not reconfigured
if not scriptlogger.hasHandlers():
# set log level
scriptlogger.setLevel(logging.INFO)
fmt = '%(name)s:%(levelname)s: %(message)s'
# configure terminal log
streamhandler = logging.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pattern_logic_aeidon():
"""Return patterns to be used for searching subtitles via aeidon.""" |
if Config.options.pattern_files:
return prep_patterns(Config.options.pattern_files)
elif Config.options.regex:
return Config.REGEX
else:
return Config.TERMS |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pattern_logic_srt():
"""Return patterns to be used for searching srt subtitles.""" |
if Config.options.pattern_files and Config.options.regex:
return prep_regex(prep_patterns(Config.options.pattern_files))
elif Config.options.pattern_files:
return prep_patterns(Config.options.pattern_files)
elif Config.options.regex:
return prep_regex(Config.REGEX)
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 prep_patterns(filenames):
"""Load pattern files passed via options and return list of patterns.""" |
patterns = []
for filename in filenames:
try:
with open(filename) as file:
patterns += [l.rstrip('\n') for l in file]
except: # pylint: disable=W0702
LOGGER.error("Unable to load pattern file '%s'" % filename)
sys.exit(1)
if patterns:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prep_regex(patterns):
"""Compile regex patterns.""" |
flags = 0 if Config.options.case_sensitive else re.I
return [re.compile(pattern, flags) for pattern in patterns] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prerequisites():
"""Display information about obtaining the aeidon module.""" |
url = "http://home.gna.org/gaupol/download.html"
debian = "sudo apt-get install python3-aeidon"
other = "python3 setup.py --user --without-gaupol clean install"
LOGGER.error(
"The aeidon module is missing!\n\n"
"Try '{0}' or the appropriate command for your package manager.\n\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 remove_elements(target, indices):
"""Remove multiple elements from a list and return result. This implementation is faster than the alternative below. Also n... |
copied = list(target)
for index in reversed(indices):
del copied[index]
return copied |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_aeidon():
"""Prepare filenames and patterns then process subtitles with aeidon.""" |
extensions = ['ass', 'srt', 'ssa', 'sub']
Config.filenames = prep_files(Config.args, extensions)
Config.patterns = pattern_logic_aeidon()
for filename in Config.filenames:
AeidonProject(filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_srt():
"""Prepare filenames and patterns then process srt subtitles.""" |
extensions = ['srt']
Config.filenames = prep_files(Config.args, extensions)
Config.patterns = pattern_logic_srt()
for filename in Config.filenames:
SrtProject(filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fixchars(self):
"""Replace characters or strings within subtitle file.""" |
for key in Config.CHARFIXES:
self.project.set_search_string(key)
self.project.set_search_replacement(Config.CHARFIXES[key])
self.project.replace_all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open(self):
"""Open the subtitle file into an Aeidon project.""" |
try:
self.project.open_main(self.filename)
except UnicodeDecodeError:
with open(self.filename, 'rb') as openfile:
encoding = get_encoding(openfile.read())
try:
self.project.open_main(self.filename, encoding)
except Unicode... |
<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(self):
"""Save subtitle file.""" |
try:
# ensure file is encoded properly while saving
self.project.main_file.encoding = 'utf_8'
self.project.save_main()
if self.fix:
LOGGER.info("Saved changes to '%s'", self.filename)
except: # pylint: disable=W0702
LOGGER.err... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self):
"""Search srt in project for cells matching list of terms.""" |
matches = []
for pattern in Config.patterns:
matches += self.termfinder(pattern)
return sorted(set(matches), key=int) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def termfinder(self, pattern):
"""Search srt in project for cells matching term.""" |
if Config.options.regex:
flags = re.M | re.S | \
(0 if Config.options.case_sensitive else re.I)
self.project.set_search_regex(
pattern, flags=flags)
else:
self.project.set_search_string(
pattern, ignore_case=not Config... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fixchars(self, text):
"""Find and replace problematic characters.""" |
keys = ''.join(Config.CHARFIXES.keys())
values = ''.join(Config.CHARFIXES.values())
fixed = text.translate(str.maketrans(keys, values))
if fixed != text:
self.modified = True
return fixed |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prompt(self, matches):
"""Prompt user to remove cells from subtitle file.""" |
if Config.options.autoyes:
return matches
deletions = []
for match in matches:
os.system('clear')
print(self.cells[match])
print('----------------------------------------')
print("Delete cell %s of '%s'?" % (str(match + 1), self.fil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def renumber(self):
"""Re-number cells.""" |
num = 0
for cell in self.cells:
cell_split = cell.splitlines()
if len(cell_split) >= 2:
num += 1
cell_split[0] = str(num)
yield '\n'.join(cell_split) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self):
"""Format and save cells.""" |
# re-number cells
self.cells = list(self.renumber())
# add a newline to the last line if necessary
if not self.cells[-1].endswith('\n'):
self.cells[-1] += '\n'
# save the rejoined the list of cells
with open(self.filename, 'w') as file_open:
fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self):
"""Return list of cells to be removed.""" |
matches = []
for index, cell in enumerate(self.cells):
for pattern in Config.patterns:
if ismatch(cell, pattern):
matches.append(index)
break
return matches |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split(self, text):
"""Split text into a list of cells.""" |
import re
if re.search('\n\n', text):
return text.split('\n\n')
elif re.search('\r\n\r\n', text):
return text.split('\r\n\r\n')
else:
LOGGER.error("'%s' does not appear to be a 'srt' subtitle file",
self.filename)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def keys(request):
"""Lists API keys. Compatible with jQuery DataTables.""" |
iDisplayStart = parse_int_param(request, 'iDisplayStart')
iDisplayLength = parse_int_param(request, 'iDisplayLength')
sEcho = parse_int_param(request, 'sEcho')
iSortCol_0 = parse_int_param(request, 'iSortCol_0')
sSortDir_0 = request.GET.get('sSortDir_0', 'asc')
sSearch = request.GET.get('sSearc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grouper_dict(d, n):
"""Evenly divide dictionary into fixed-length piece, no filled value if chunk size smaller than fixed-length. Usage:: 6: 'F', 7: 'G', 8: ... |
chunk = dict()
counter = 0
for k, v in d.items():
counter += 1
chunk[k] = v
print(counter ,chunk)
if counter == n:
yield chunk
chunk = dict()
counter = 0
if len(chunk) > 0:
yield chunk |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def running_windows(iterable, size):
"""Generate n-size running windows. Usage:: [1, 2, 3] [2, 3, 4] [3, 4, 5] """ |
fifo = collections.deque(maxlen=size)
for i in iterable:
fifo.append(i)
if len(fifo) == size:
yield list(fifo) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shift_to_the_left(array, dist, pad=True, trim=True):
"""Shift array to the left. :param array: An iterable object. :type array: iterable object :param dist: ... |
if dist < 0:
raise ValueError("Shift distance has to greater or equal than 0.")
if pad:
if trim:
new_array = array[dist:] + [array[-1]] * dist
else:
new_array = array + [array[-1]] * dist
else:
if trim:
new_array = array[dist:]
el... |
<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_generator(generator, memory_efficient=True):
"""Count number of item in generator. memory_efficient=True, 3 times slower, but memory_efficient. memory_... |
if memory_efficient:
counter = 0
for _ in generator:
counter += 1
return counter
else:
return len(list(generator)) |
<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_key(self, key, using_name=True):
"""Given a field key or name, return it's field key. """ |
try:
if using_name:
return self.f_name[key].key
else:
return self.f[key].key
except KeyError:
raise ValueError("'%s' are not found!" % key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_object_key(self, key, using_name=True):
"""Given a object key or name, return it's object key. """ |
try:
if using_name:
return self.o_name[key].key
else:
return self.o[key].key
except KeyError:
raise ValueError("'%s' are not found!" % key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zip_a_folder(src, dst):
"""Add a folder and everything inside to zip archive. Example:: |---paper |--- algorithm.pdf |--- images |--- 1.jpg zip_a_folder("pap... |
src, dst = os.path.abspath(src), os.path.abspath(dst)
cwd = os.getcwd()
todo = list()
dirname, basename = os.path.split(src)
os.chdir(dirname)
for dirname, _, fnamelist in os.walk(basename):
for fname in fnamelist:
newname = os.path.join(dirname, fname)
todo.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 zip_many_files(list_of_abspath, dst):
"""Add many files to a zip archive. **中文文档** 将一系列的文件压缩到一个压缩包中, 若有重复的文件名, 在zip中保留所有的副本。 """ |
base_dir = os.getcwd()
with ZipFile(dst, "w") as f:
for abspath in list_of_abspath:
dirname, basename = os.path.split(abspath)
os.chdir(dirname)
f.write(basename)
os.chdir(base_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 write_gzip(content, abspath):
"""Write binary content to gzip file. **中文文档** 将二进制内容压缩后编码写入gzip压缩文件。 """ |
with gzip.open(abspath, "wb") as f:
f.write(content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iter_bases(bases):
""" Performs MRO linearization of a set of base classes. Yields each base class in turn. """ |
sequences = ([list(inspect.getmro(base)) for base in bases] +
[list(bases)])
# Loop over sequences
while True:
sequences = [seq for seq in sequences if seq]
if not sequences:
return
# Select a good head
for ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inherit_dict(base, namespace, attr_name, inherit=lambda k, v: True):
""" Perform inheritance of dictionaries. Returns a list of key and value pairs for value... |
items = []
# Get the dicts to compare
base_dict = getattr(base, attr_name, {})
new_dict = namespace.setdefault(attr_name, {})
for key, value in base_dict.items():
# Skip keys that have been overridden or that we shouldn't
# inherit
if key 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 inherit_set(base, namespace, attr_name, inherit=lambda i: True):
""" Perform inheritance of sets. Returns a list of items that were inherited, for post-proce... |
items = []
# Get the sets to compare
base_set = getattr(base, attr_name, set())
new_set = namespace.setdefault(attr_name, set())
for item in base_set:
# Skip items that have been overridden or that we
# shouldn't inherit
if item in new_set 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 decrypt_result(self, *args, **kwargs):
""" Decrypts ProcessData result with comm keys :param args: :param kwargs: :return: """ |
if self.response is None:
raise ValueError('Empty response')
if self.response.response is None \
or 'result' not in self.response.response \
or self.response.response['result'] is None:
raise ValueError('No result data')
res_hex = self.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 get(self, cls, rid):
"""Return record of given type with key `rid` 'Toto' Traceback (most recent call last):
ValueError: Unsupported record type "badcls" Tr... |
self.validate_record_type(cls)
rows = self.db.select(cls, where={ID: rid}, limit=1)
if not rows:
raise KeyError('No {} record with id {}'.format(cls, rid))
return rows[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 create(self, cls, record, user='undefined'):
"""Persist new record 'jane' Traceback (most recent call last):
ValueError: Unsupported record type "badcls" Tr... |
self.validate_record(cls, record)
record[CREATION_DATE] = record[UPDATE_DATE] = self.nowstr()
record[CREATOR] = record[UPDATER] = user
try:
return self.db.insert(cls, record)
except (psycopg2.IntegrityError, psycopg2.ProgrammingError,
psycopg2.DataErr... |
<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, cls, rid, partialrecord, user='undefined'):
"""Update existing record 25 'jane' Traceback (most recent call last):
KeyError: 'No such record' T... |
self.validate_partial_record(cls, partialrecord)
partialrecord[UPDATE_DATE] = self.nowstr()
partialrecord[UPDATER] = user
try:
updatecount = self.db.update(cls, partialrecord, where={ID: rid})
if updatecount < 1:
raise KeyError('No such record')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, cls, rid, user='undefined'):
""" Delete a record by id. `user` currently unused. Would be used with soft deletes. 1 0 Traceback (most recent cal... |
self.validate_record_type(cls)
deletedcount = self.db.delete(cls, {ID: rid})
if deletedcount < 1:
raise KeyError('No record {}/{}'.format(cls, rid)) |
<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_record_type(self, cls):
""" Validate given record is acceptable. Traceback (most recent call last):
ValueError: Unsupported record type "bad" """ |
if self.record_types and cls not in self.record_types:
raise ValueError('Unsupported record type "' + cls + '"') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_record(self, cls, content_type, strdata):
""" Returns a record from serialized string representation. {u'id': u'1', u'name': u'Toto'} """ |
self.validate_record_type(cls)
parsedrecord = self.deserialize(content_type, strdata)
return self.post_process_record(cls, parsedrecord) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(self, cls, record):
""" Serialize the record to JSON. cls unused in this implementation. '{"id": "1", "name": "Toto"}' """ |
return json.dumps(record, cls=self.encoder) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deserialize(self, content_type, strdata):
"""Deserialize string of given content type. `self` unused in this implementation. {u'id': u'1', u'name': u'Toto'} ... |
if content_type != 'application/json':
raise ValueError('Unsupported content type "' + content_type + '"')
return json.loads(strdata) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def frameify(self, state, data):
"""Yield the data as a single frame.""" |
try:
yield state.recv_buf + data
except FrameSwitch:
pass
finally:
state.recv_buf = '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def frameify(self, state, data):
"""Yield chunk data as a single frame, and buffer the rest.""" |
# If we've pulled in all the chunk data, buffer the data
if state.chunk_remaining <= 0:
state.recv_buf += data
return
# Pull in any partially-processed data
data = state.recv_buf + data
# Determine how much belongs to the chunk
if len(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 frameify(self, state, data):
"""Split data into a sequence of lines.""" |
# Pull in any partially-processed data
data = state.recv_buf + data
# Loop over the data
while data:
line, sep, rest = data.partition('\n')
# Did we have a whole line?
if sep != '\n':
break
# OK, update the 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 streamify(self, state, frame):
"""Prepare frame for output as a byte-stuffed stream.""" |
# Split the frame apart for stuffing...
pieces = frame.split(self.prefix)
return '%s%s%s%s%s' % (self.prefix, self.begin,
(self.prefix + self.nop).join(pieces),
self.prefix, self.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 _get_tab(cls):
"""Generate and return the COBS table.""" |
if not cls._tabs['dec_cobs']:
# Compute the COBS table for decoding
cls._tabs['dec_cobs']['\xff'] = (255, '')
cls._tabs['dec_cobs'].update(dict((chr(l), (l, '\0'))
for l in range(1, 255)))
# Compute the COBS table f... |
<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_tab_zpe(cls):
"""Generate and return the COBS ZPE table.""" |
if not cls._tabs['dec_cobs_zpe']:
# Compute the COBS ZPE table for decoding
cls._tabs['dec_cobs_zpe']['\xe0'] = (224, '')
cls._tabs['dec_cobs_zpe'].update(dict((chr(l), (l, '\0'))
for l in range(1, 224)))
cls._ta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _decode(frame, tab):
"""Decode a frame with the help of the table.""" |
blocks = []
# Decode each block
while frame:
length, endseq = tab[frame[0]]
blocks.extend([frame[1:length], endseq])
frame = frame[length:]
# Remove one (and only one) trailing '\0' as necessary
if blocks and len(blocks[-1]) > 0:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.