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 cancel( self, identifier: typing.Any, exc_type: typing.Optional[type]=None, ) -> bool: """Cancel an active coroutine and remove it from the schedule. Args: id... |
raise NotImplementedError() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fill_text(self, text, width=None, indent=None):
""" Reflow text width while maintaining certain formatting characteristics like double newlines and indented... |
assert isinstance(text, str)
if indent is None:
indent = NBSP * self._current_indent
assert isinstance(indent, str)
paragraphs = []
line_buf = []
pre = ''
for fragment in text.splitlines():
pre_indent = self.leadingws.match(fragment)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bind_env(self, action, env):
""" Bind an environment variable to an argument action. The env value will traditionally be something uppercase like `MYAPP_FOO_... |
if env in self._env_actions:
raise ValueError('Duplicate ENV variable: %s' % env)
self._env_actions[env] = action
action.env = 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 print_help(self, *args, **kwargs):
""" Add pager support to help output. """ |
if self._command is not None and self._command.session.allow_pager:
desc = 'Help\: %s' % '-'.join(self.prog.split())
pager_kwargs = self._command.get_pager_spec()
with paging.pager_redirect(desc, **pager_kwargs):
return super().print_help(*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 add_subparsers(self, prog=None, **kwargs):
""" Supplement a proper `prog` keyword argument for the subprocessor. The superclass technique for getting the `pr... |
if prog is None:
# Use a non-shellish help formatter to avoid vt100 codes.
f = argparse.HelpFormatter(prog=self.prog)
f.add_usage(self.usage, self._get_positional_actions(),
self._mutually_exclusive_groups, '')
prog = f.format_help().strip... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _analyze(self):
""" Apply the filter to the log file """ |
for parsed_line in self.parsed_lines:
if 'ip' in parsed_line:
if parsed_line['ip'] in self.filter['ips']:
self.noisy_logs.append(parsed_line)
else:
self.quiet_logs.append(parsed_line)
else:
self.quie... |
<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_features(self):
""" Get the feature data from the log file necessary for a reduction """ |
for parsed_line in self.parsed_lines:
result = {'raw': parsed_line}
if 'ip' in parsed_line:
result['ip'] = parsed_line['ip']
if result['ip'] not in self.features['ips']:
self.features['ips'].append(result['ip']) |
<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_local_ip():
""" Get the local ip of this device :return: Ip of this computer :rtype: str """ |
return set([x[4][0] for x in socket.getaddrinfo(
socket.gethostname(),
80,
socket.AF_INET
)]).pop() |
<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_listen_socket(self):
""" Init listen socket :rtype: None """ |
self.debug("()")
self._listen_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._listen_socket.setsockopt(
socket.SOL_SOCKET,
socket.SO_REUSEADDR,
1
)
self._listen_socket.bind((self._listen_ip, self._listen_port))
self._li... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _shutdown_listen_socket(self):
""" Shutdown listening socket :rtype: None """ |
self.debug("()")
if self._listen_socket in self._listening:
self._listening.remove(self._listen_socket)
if self._listen_socket:
self._listen_socket.close()
self._listen_socket = 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 _send(self, ip, port, data):
""" Send an UDP message :param ip: Ip to send to :type ip: str :param port: Port to send to :type port: int :return: Number of b... |
return self._listen_socket.sendto(data, (ip, port)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _send_ack(self, ip, port, packet, update_timestamp=True):
""" Send an ack packet :param ip: Ip to send to :type ip: str :param port: Port to send to :type po... |
# TODO: maybe wait a bit, so the ack could get attached to another
# packet
ack = APPMessage(message_type=MsgType.ACK)
ack.header.ack_sequence_number = packet.header.sequence_number
self._send_packet(
ip, port, ack,
update_timestamp=update_timestamp, ackn... |
<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_packet(self, socket):
""" Read packet and put it into inbox :param socket: Socket to read from :type socket: socket.socket :return: Read packet :rtype: ... |
data, (ip, port) = socket.recvfrom(self._buffer_size)
packet, remainder = self._unpack(data)
self.inbox.put((ip, port, packet))
self.new_packet.set()
self.debug(u"RX: {}".format(packet))
if packet.header.sequence_number is not None:
# Packet needs to be ackn... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _acking(self, params=None):
""" Packet acknowledge and retry loop :param params: Ignore :type params: None :rtype: None """ |
while self._is_running:
try:
t, num_try, (ip, port), packet = self._to_ack.get(
timeout=self._select_timeout
)
except queue.Empty:
# Timed out
continue
diff = t - time.time()
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_request_args(method, **kwargs):
"""Use `method` and other settings to produce a flickr API arguments. Here also use json as the return type. :param meth... |
args = [
('api_key', api_key),
('format', 'json'),
('method', method),
('nojsoncallback', '1'),
]
if kwargs:
for key, value in kwargs.iteritems():
args.append((key, value))
args.sort(key=lambda tup: tup[0])
api_sig = _get_api_sig(args)
args.ap... |
<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_api_sig(args):
"""Flickr API need a hash string which made using post arguments :param args: Arguments of the flickr request :type args: list of sets :r... |
tmp_sig = api_secret
for i in args:
tmp_sig = tmp_sig + i[0] + i[1]
api_sig = hashlib.md5(tmp_sig.encode('utf-8')).hexdigest()
return 'api_sig', api_sig |
<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_dir(path):
"""Create dir with the path :param path: The path to be created :type path: str """ |
if os.path.exists(path):
if not os.path.isdir(path):
logger.error('%s is not a directory', path)
sys.exit(1)
else: # ignore
pass
else:
os.makedirs(path)
logger.info('Create dir: %s', path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_photos_info(photoset_id):
"""Request the photos information with the photoset id :param photoset_id: The photoset id of flickr :type photoset_id: str :re... |
args = _get_request_args(
'flickr.photosets.getPhotos',
photoset_id=photoset_id
)
resp = requests.post(API_URL, data=args)
resp_json = json.loads(resp.text.encode('utf-8'))
logger.debug(resp_json)
photos = resp_json['photoset']['photo']
return photos |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def single_download_photos(photos):
"""Use single process to download photos :param photos: The photos to be downloaded :type photos: list of dicts """ |
global counter
counter = len(photos)
for photo in photos:
download_photo(photo) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multithread_download_photos(photos):
"""Use multiple threads to download photos :param photos: The photos to be downloaded :type photos: list of dicts """ |
from concurrent import futures
global counter
counter = len(photos)
cpu_num = multiprocessing.cpu_count()
with futures.ThreadPoolExecutor(max_workers=cpu_num) as executor:
for photo in photos:
executor.submit(download_photo, photo) |
<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_logger():
"""Initialize the logger and set its format """ |
formatter = logging.Formatter('%(levelname)s: %(message)s')
console = logging.StreamHandler(stream=sys.stdout)
console.setLevel(logging.INFO)
console.setFormatter(formatter)
logger.addHandler(console) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _gevent_patch():
"""Patch the modules with gevent :return: Default is GEVENT. If it not supports gevent then return MULTITHREAD :rtype: int """ |
try:
assert gevent
assert grequests
except NameError:
logger.warn('gevent not exist, fallback to multiprocess...')
return MULTITHREAD
else:
monkey.patch_all() # Must patch before get_photos_info
return GEVENT |
<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():
"""The main procedure """ |
init_logger()
args = _parse_cli_args()
if args.u:
enter_api_key()
return
if args.O == GEVENT:
args.O = _gevent_patch()
set_image_size_mode(args.s)
photoset_id = args.g
global directory
directory = args.d if args.d else photoset_id
read_config()
photo... |
<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_cjk_punctuation(char):
"""Returns true if char is a punctuation mark in a CJK language.""" |
lower = int('0x3000', 16)
higher = int('0x300F', 16)
return ord(char) >= lower and ord(char) <= higher |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def force_populate(self):
""" Populates the parser with the entire contents of the word reference file. """ |
if not os.path.exists(self.ref):
raise FileNotFoundError("The reference file path '{}' does not exists.".format(self.ref))
with open(self.ref, 'r') as f:
for word in f:
word = word.strip('\n')
self.db.add(word)
self.populated = 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 leveled(self):
"""Return all countries with a level set""" |
# Compatibility support for Django<1.6
safe_get_queryset = (self.get_query_set if hasattr(self, 'get_query_set') else self.get_queryset)
return safe_get_queryset.exclude(level=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 popd(pop_all=False, throw_if_dir_invalid=True):
"""Restore current working directory to previous directory. The previous directory is whatever it was when la... |
global _pushdstack
from os import chdir
if len(_pushdstack) == 0:
raise ValueError("popd() called on an empty stack.")
if pop_all:
while( len(_pushdstack) > 1):
_pushdstack.pop()
try:
chdir(_pushdstack.pop())
err = 0
except OSError:
if thro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pyVersionStr(self):
"""Version of Python running my script Returns ------- str A descriptive string containing the version of Python running this script. """ |
from sys import version_info
return "Python Interpreter Version: {}.{}.{}".format(version_info.major,
version_info.minor,
version_info.micro) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self):
"""Returns a tuple containing all elements of the object This method returns all elements of the path in the form of a tuple. e.g.: `(abs_path, dr... |
return (self._full, self._driv, self._path, self._name, self._ext, self._size, self._time) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format(self, fmt):
"""Returns string representing the items specified in the format string The format string can contain: .. code:: d - drive letter p - path... |
val = ''
for x in fmt:
if x == 'd':
val += self._driv
elif x == 'p':
val += self._path
elif x == 'n':
val += self._name
elif x == 'x':
val += self._ext
elif x == '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 cached(attr):
""" In-memory caching for a nullary callable. """ |
def decorator(f):
@functools.wraps(f)
def decorated(self):
try:
return getattr(self, attr)
except AttributeError:
value = f(self)
setattr(self, attr, value)
return value
return decorated
return deco... |
<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_cell_type(cell, cell_type):
'''
Checks the cell type to see if it represents the cell_type passed in.
Args:
cell_type: The type id for a cell match or None for empty match.
'''
if cell_type == None or cell_type == type(None):
return cell == None or (isinstance(cell, basest... |
<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_convert_cell_no_flags(cell, units=None, parens_as_neg=True):
'''
Performs a first step conversion of the cell to check
it's type or try to convert if a valid conversion exists.
This version of conversion doesn't flag changes nor store
cell units.
Args:
units: The dictionary hol... |
<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_convert_cell(flagable, cell, position, worksheet, flags, units, parens_as_neg=True):
'''
Performs a first step conversion of the cell to check
it's type or try to convert if a valid conversion exists.
Args:
parens_as_neg: Converts numerics surrounded by parens to negative values
''... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def auto_convert_string_cell(flagable, cell_str, position, worksheet, flags,
units, parens_as_neg=True):
'''
Handles the string case of cell and attempts auto-conversion
for auto_convert_cell.
Args:
parens_as_neg: Converts numerics surrounded by parens to negative v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, field, value):
""" Sets the value of an app field. :param str field: The name of the app field. Trying to set immutable fields ``uuid`` or ``key`` ... |
if field == 'uuid':
raise ValueError('uuid cannot be set')
elif field == 'key':
raise ValueError(
'key cannot be set. Use \'reset_key\' method')
else:
self.data[field] = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset_key(self):
""" Resets the app's key on the `unicore.hub` server. :returns: str -- the new key """ |
new_key = self.client.reset_app_key(self.get('uuid'))
self.data['key'] = new_key
return new_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 raise_exception(self, original_exception=None):
"""Raise a retry exception if under the max retries. After, raise the original_exception provided to this met... |
if self._executed_retries < self._max_retries:
curr_backoff = self._ms_backoff
self._executed_retries += 1
self._ms_backoff = self._ms_backoff * 2
raise ActionRetryException(curr_backoff)
else:
raise original_exception or Exception() |
<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():
# pragma: nocover """Print checksum and file name for all files in the directory. """ |
p = argparse.ArgumentParser(add_help="Recursively list interesting files.")
p.add_argument(
'directory', nargs="?", default="",
help="The directory to process (current dir if omitted)."
)
p.add_argument(
'--verbose', '-v', action='store_true',
help="Increase verbosity."
... |
<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_exists(pid=None):
""" Evaluates a Pid Value defaults to the currently foucsed window against the current open programs, if there is a match returns t... |
if not pid:
pid = current_pid()
elif callable(pid):
pid = pid()
if pid and psutil.pid_exists(pid):
pname = psutil.Process(pid).name()
if os.name == 'nt':
return os.path.splitext(pname)[0], pid
return pname, pid
return None, 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_active_window_pos():
'''screen coordinates massaged so that movewindow command works to
restore the window to the same position
returns x, y
'''
# http://stackoverflow.com/questions/26050788/in-bash-on-ubuntu-14-04-unity-how-can-i-get-the-total-size-of-an-open-window-i/26060527#26060527
... |
<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_active_title():
'''returns the window title of the active window'''
if os.name == 'posix':
cmd = ['xdotool','getactivewindow','getwindowname']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
title = proc.communicate()[0].decode('utf-8')
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_processes():
'''returns process names owned by the user'''
user = getpass.getuser()
for proc in psutil.process_iter():
if proc.username() != user:
continue
pname = psutil.Process(proc.pid).name()
if os.name == 'nt':
pname = pname[:-4] # remov... |
<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_titles():
'''returns titles of all open windows'''
if os.name == 'posix':
for proc in get_processes():
cmd = ['xdotool','search','--name', proc]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
window_ids = proc.communicate()[0].dec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_gcd(a, b):
"Return greatest common divisor for a and b."
while a:
a, b = b % a, a
return b |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auto_tweet(sender, instance, *args, **kwargs):
""" Allows auto-tweeting newly created object to twitter on accounts configured in settings. You MUST create a... |
if not twitter or getattr(settings, 'TWITTER_SETTINGS') is False:
#print 'WARNING: Twitter account not configured.'
return False
if not kwargs.get('created'):
return False
twitter_key = settings.TWITTER_SETTINGS
try:
api = twitter.Api(
consumer_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 postalCodeLookup(self, countryCode, postalCode):
""" Looks up locations for this country and postal code. """ |
params = {"country": countryCode, "postalcode": postalCode}
d = self._call("postalCodeLookupJSON", params)
d.addCallback(operator.itemgetter("postalcodes"))
return 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 _print(*args):
""" Print txt by coding GBK. *args list, list of printing contents """ |
if not CFG.debug:
return
if not args:
return
encoding = 'gbk'
args = [_cs(a, encoding) for a in args]
f_back = None
try:
raise Exception
except:
f_back = sys.exc_traceback.tb_frame.f_back
f_name = f_back.f_code.co_name
filename = os.path.basename(f_ba... |
<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_err(*args):
""" Print errors. *args list, list of printing contents """ |
if not CFG.debug:
return
if not args:
return
encoding = 'utf8' if os.name == 'posix' else 'gbk'
args = [_cs(a, encoding) for a in args]
f_back = None
try:
raise Exception
except:
f_back = sys.exc_traceback.tb_frame.f_back
f_name = f_back.f_code.co_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 fileprint(filename, category, level=logging.DEBUG, maxBytes=1024*10124*100, backupCount=0):
""" Print files by file size. filename string, file name category... |
path = os.path.join(CFG.filedir, category, filename)
# Initialize filer
filer = logging.getLogger(filename)
frt = logging.Formatter('%(message)s')
hdr = RotatingFileHandler(path, 'a', maxBytes, backupCount, 'utf-8')
hdr.setFormatter(frt)
hdr._name = '##_rfh_##'
already_in = 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 pt_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return point at t on bezier curve defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def pts_on_bezier_curve(P=[(0.0, 0.0)], n_seg=0):
'''Return list N+1 points representing N line segments on bezier curve
defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 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 bezier_curve_approx_len(P=[(0.0, 0.0)]):
'''Return approximate length of a bezier curve defined by control points P.
Segment curve into N lines where N is the order of the curve, and accumulate
the length of the segments.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
ass... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def engage(args, password):
""" Construct payloads and POST to Red October """ |
if args['create']:
payload = {'Name': args['--user'], 'Password': password}
goodquit_json(api_call('create', args, payload))
elif args['delegate']:
payload = {
'Name': args['--user'], 'Password': password,
'Time': args['--time'], 'Uses': args['--uses']
}... |
<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, data, filename='', debuglevel=0):
""" Parse given data. data: A string containing the filter definition filename: Name of the file being parsed (... |
self.lexer.filename = filename
self.lexer.reset_lineno()
if not data or data.isspace():
return []
return self.parser.parse(data, lexer=self.lexer, debug=debuglevel) |
<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_factor_rule(tok):
""" Simple helper method for creating factor node objects based on node name. """ |
if tok[0] == 'IPV4':
return IPV4Rule(tok[1])
if tok[0] == 'IPV6':
return IPV6Rule(tok[1])
if tok[0] == 'DATETIME':
return DatetimeRule(tok[1])
if tok[0] == 'TIMEDELTA':
return TimedeltaRule(tok[1])
if tok[0] == 'INTEGER':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unshorten_url(short_url):
"""Unshortens the short_url or returns None if not possible.""" |
short_url = short_url.strip()
if not short_url.startswith('http'):
short_url = 'http://{0}'.format(short_url)
try:
cached_url = UnshortenURL.objects.get(short_url=short_url)
except UnshortenURL.DoesNotExist:
cached_url = UnshortenURL(short_url=short_url)
else:
retur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self, spider_name=None):
"""Stop the named running spider, or the first spider found, if spider_name is None""" |
if spider_name is None:
spider_name = self.spider_name
else:
self.spider_name = spider_name
if self.spider_name is None:
self.spider_name = self.list_running()[0].split(':')[-1]
self.jsonrpc_call('crawler/engine', 'close_spider', self.spider_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 copy(self):
'''
makes a clone copy of the mapper. It won't clone the serializers or deserializers and it won't copy the events
'''
try:
tmp = self.__class__()
except Exception:
tmp = self.__class__(self._pdict)
tmp._serializers = ... |
<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_required_fn(fn, root_path):
""" Definition of the MD5 file requires, that all paths will be absolute for the package directory, not for the filesystem. ... |
if not fn.startswith(root_path):
raise ValueError("Both paths have to be absolute or local!")
replacer = "/" if root_path.endswith("/") else ""
return fn.replace(root_path, replacer, 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 partition(f, xs):
"""
Works similar to filter, except it returns a two-item tuple where the
first item is the sequence of items that passed the filter and... |
t = type(xs)
true = filter(f, xs)
false = [x for x in xs if x not in true]
return t(true), t(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 lazy_binmap(f, xs):
"""
Maps a binary function over a sequence. The function is applied to each item
and the item after it until the last item is reached.... |
return (f(x, y) for x, y in zip(xs, xs[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 lazy_reverse_binmap(f, xs):
"""
Same as lazy_binmap, except the parameters are flipped for the binary function
""" |
return (f(y, x) for x, y in zip(xs, xs[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 analog_linear2_ramp(ramp_data, start_time, end_time, value_final, time_subarray):
"""Use this when you want a discontinuous jump at the end of the linear ram... |
value_initial = ramp_data["value"]
value_final2 = ramp_data["value_final"]
interp = (time_subarray - start_time)/(end_time - start_time)
return value_initial*(1.0 - interp) + value_final2*interp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bake(self):
"""Find absolute times for all keys. Absolute time is stored in the KeyFrame dictionary as the variable __abs_time__. """ |
self.unbake()
for key in self.dct:
self.get_absolute_time(key)
self.is_baked = 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 unbake(self):
"""Remove absolute times for all keys.""" |
for key in self.dct:
# pop __abs_time__ if it exists
self.dct[key].pop('__abs_time__', None)
self.is_baked = 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 get_absolute_time(self, key):
"""Returns the absolute time position of the key. If absolute time positions are not calculated, then this function calculates ... |
keyframe = self.dct[key]
try:
# if absolute time is already calculated, return that
return keyframe['__abs_time__']
except KeyError:
# if not, calculate by adding relative time to parent's time
if keyframe['parent'] is None:
keyfra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sorted_key_list(self):
"""Returns list of keys sorted according to their absolute time.""" |
if not self.is_baked:
self.bake()
key_value_tuple = sorted(self.dct.items(),
key=lambda x: x[1]['__abs_time__'])
skl = [k[0] for k in key_value_tuple]
return skl |
<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_time(self, key_name, new_time):
"""Sets the time of key.""" |
self.unbake()
kf = self.dct[key_name]
kf['time'] = new_time
self.bake() |
<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_comment(self, key_name, new_comment):
"""Sets the comment of key.""" |
kf = self.dct[key_name]
kf['comment'] = new_comment |
<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_parent(self, key_name, new_parent):
"""Sets the parent of the key.""" |
self.unbake()
kf = self.dct[key_name]
kf['parent'] = new_parent
self.bake() |
<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_ancestor(self, child_key_name, ancestor_key_name):
"""Returns True if ancestor lies in the ancestry tree of child.""" |
# all keys are descendents of None
if ancestor_key_name is None:
return True
one_up_parent = self.dct[child_key_name]['parent']
if child_key_name == ancestor_key_name:
# debatable semantics, but a person lies in his/her own
# ancestry tree
... |
<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_hook(self, key_name, hook_name, hook_dict):
"""Add hook to the keyframe key_name.""" |
kf = self.dct[key_name]
if 'hooks' not in kf:
kf['hooks'] = {}
kf['hooks'][str(hook_name)] = hook_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_hook(self, key_name, hook_name):
"""Remove hook from the keyframe key_name.""" |
kf = self.dct[key_name]
if 'hooks' in kf:
if hook_name in kf['hooks']:
return kf['hooks'].pop(hook_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 list_hooks(self, key_name):
"""Return list of all hooks attached to key_name.""" |
kf = self.dct[key_name]
if 'hooks' not in kf:
return []
else:
return kf['hooks'].iterkeys() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_keyframes_overlap(self):
"""Checks for keyframs timing overlap. Returns the name of the first keyframs that overlapped.""" |
skl = self.sorted_key_list()
for i in range(len(skl)-1):
this_time = self.dct[skl[i]]['__abs_time__']
next_time = self.dct[skl[i+1]]['__abs_time__']
if abs(next_time-this_time) < 1e-6:
# key frame times overlap
return skl[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 del_unused_keyframes(self):
"""Scans through list of keyframes in the channel and removes those which are not in self.key_frame_list.""" |
skl = self.key_frame_list.sorted_key_list()
unused_keys = [k for k in self.dct['keys']
if k not in skl]
for k in unused_keys:
del self.dct['keys'][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_used_key_frames(self):
"""Returns a list of the keyframes used by this channel, sorted with time. Each element in the list is a tuple. The first element ... |
skl = self.key_frame_list.sorted_key_list()
# each element in used_key_frames is a tuple (key_name, key_dict)
used_key_frames = []
for kf in skl:
if kf in self.dct['keys']:
used_key_frames.append((kf, self.dct['keys'][kf]))
return used_key_frames |
<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_ramp_regions(self):
"""Returns a numpy array where each element corresponds to whether to ramp in that region or jump.""" |
skl = self.key_frame_list.sorted_key_list()
ramp_or_jump = np.zeros(len(skl) - 1)
used_key_frames = self.get_used_key_frame_list()
for region_number, start_key in enumerate(skl[:-1]):
if start_key in used_key_frames:
key_data = self.dct['keys'][start_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 generate_ramp(self, time_div=4e-3):
"""Returns the generated ramp and a time array. This function assumes a uniform time division throughout. time_div - time... |
if self.dct['type'] == 'analog':
is_analog = True
else:
is_analog = False
skl = self.key_frame_list.sorted_key_list()
# each element in used_key_frames is a tuple (key_name, key_dict)
used_key_frames = self.get_used_key_frames()
max_time = self.ke... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def possible_forms(self):
""" Generate a list of possible forms for the current lemma :returns: List of possible forms for the current lemma :rtype: [str] """ |
forms = []
for morph in self.modele().morphos():
for desinence in self.modele().desinences(morph):
radicaux = self.radical(desinence.numRad())
if isinstance(radicaux, Radical):
forms.append(radicaux.gr() + desinence.gr())
e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_moves():
"""Visit Bulbapedia and pull names and descriptions from the table, 'list of moves.' Save as JSON.""" |
page = requests.get('http://bulbapedia.bulbagarden.net/wiki/List_of_moves')
soup = bs4.BeautifulSoup(page.text)
table = soup.table.table
tablerows = [tr for tr in table.children if tr != '\n'][1:]
moves = {}
for tr in tablerows:
cells = tr.find_all('td')
move_name = cells[1].g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_from_path(path, filetype=None, has_filetype=True):
""" load file content from a file specified as dot-separated The file is located according to logic i... |
if not isinstance(path, str):
try:
return path.read()
except AttributeError:
return path
path = normalize_path(path, filetype, has_filetype)
with open(path) as data:
return data.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 load_lines_from_path(path, filetype=None, has_filetype=True):
""" load lines from a file specified as dot-separated The file is located according to logic in... |
if not isinstance(path, str):
try:
return path.readlines()
except AttributeError:
return path
path = normalize_path(path, filetype)
with open(path) as data:
return data.readlines() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self):
"""Pickle the addressbook and a timestamp """ |
if self.contacts: # never write a empty addressbook
cache = {'contacts': self.contacts,
'aadbook_cache': CACHE_FORMAT_VERSION}
pickle.dump(cache, open(self._config.cache_filename, 'wb')) |
<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_intercom_data(self):
"""Specify the user data sent to Intercom API""" |
return {
"user_id": self.intercom_id,
"email": self.email,
"name": self.get_full_name(),
"last_request_at": self.last_login.strftime("%s") if self.last_login else "",
"created_at": self.date_joined.strftime("%s"),
"custom_attributes": {
... |
<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_list(file,fmt):
'''makes a list out of the fmt from the LspOutput f using the format
i for int
f for float
d for double
s for string'''
out=[]
for i in fmt:
if i == 'i':
out.append(get_int(file));
elif i == 'f' or i == 'd':
out.appe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def flds_firstsort(d):
'''
Perform a lexsort and return the sort indices and shape as a tuple.
'''
shape = [ len( np.unique(d[l]) )
for l in ['xs', 'ys', 'zs'] ];
si = np.lexsort((d['z'],d['y'],d['x']));
return si,shape; |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def flds_sort(d,s):
'''
Sort based on position. Sort with s as a tuple of the sort
indices and shape from first sort.
Parameters:
-----------
d -- the flds/sclr data
s -- (si, shape) sorting and shaping data from firstsort.
'''
labels = [ key for key in d.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 read(fname,**kw):
'''
Reads an lsp output file and returns a raw dump of data,
sectioned into quantities either as an dictionary or a typed numpy array.
Parameters:
-----------
fname -- filename of thing to read
Keyword Arguments:
------------------
vprint -- Verbose 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 sigterm_handler(signum, stack_frame):
""" Just tell the server to exit. WARNING: There are race conditions, for example with TimeoutSocket.accept. We don't c... |
# pylint: disable-msg=W0613
global _KILLED
for name, cmd in _COMMANDS.iteritems():
if cmd.at_stop:
LOG.info("at_stop: %r", name)
cmd.at_stop()
_KILLED = True
if _HTTP_SERVER:
_HTTP_SERVER.kill()
_HTTP_SERVER.server_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 run(options, http_req_handler = HttpReqHandler):
""" Start and execute the server """ |
# pylint: disable-msg=W0613
global _HTTP_SERVER
for x in ('server_version', 'sys_version'):
if _OPTIONS.get(x) is not None:
setattr(http_req_handler, x, _OPTIONS[x])
_HTTP_SERVER = threading_tcp_server.KillableThreadingHTTPServer(
_OPTIONS,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init(options, use_sigterm_handler=True):
""" Must be called just after registration, before anything else """ |
# pylint: disable-msg=W0613
global _AUTH, _OPTIONS
if isinstance(options, dict):
_OPTIONS = DEFAULT_OPTIONS.copy()
_OPTIONS.update(options)
else:
for optname, optvalue in DEFAULT_OPTIONS.iteritems():
if hasattr(options, optname):
_OPTIONS[optname] = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def report(self, req_handler):
"Send a response corresponding to this error to the client"
if self.exc:
req_handler.send_exception(self.code, self.exc, self.headers)
return
text = (self.text
or BaseHTTPRequestHandler.responses[self.code][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 send_error_explain(self, code, message=None, headers=None, content_type=None):
"do not use directly"
if headers is None:
headers = {}
if code in self.responses:
if message is None:
message = self.responses[code][0]
explain = self.response... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def send_exception(self, code, exc_info=None, headers=None):
"send an error response including a backtrace to the client"
if headers is None:
headers = {}
if not exc_info:
exc_info = sys.exc_info()
self.send_error_msg(code,
traceback.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def send_error_json(self, code, message, headers=None):
"send an error to the client. text message is formatted in a json stream"
if headers is None:
headers = {}
self.end_response(HttpResponseJson(code,
{'code': code,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def common_req(self, execute, send_body=True):
"Common code for GET and POST requests"
self._SERVER = {'CLIENT_ADDR_HOST': self.client_address[0],
'CLIENT_ADDR_PORT': self.client_address[1]}
self._to_log = True
self._cmd ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def base_parser():
""" Create arguments parser with basic options and no help message. * -c, --config: load configuration file. * -v, --verbose: increase logging... |
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("-c", "--config", dest="config",
type=argparse.FileType('r'),
metavar="FILE",
help="configuration file")
parser.add_argument("-o", "--output", dest="output",
type=argparse.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cliconfig(fp, env=None):
""" Load configuration data. Given pointer is closed internally. If ``None`` is given, force to exit. More detailed information is a... |
if fp is None:
raise SystemExit('No configuration file is given.')
from clitool.config import ConfigLoader
loader = ConfigLoader(fp)
cfg = loader.load(env)
if not fp.closed:
fp.close()
if not cfg:
logging.warn('Configuration may be empty.')
return cfg |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.