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 dump( self, stream, progress=None, lower=None, upper=None, incremental=False, deltas=False ):
"""Dump the repository to a dumpfile stream. :param stream: A f... |
cmd = [SVNADMIN, 'dump', '.']
if progress is None:
cmd.append('-q')
if lower is not None:
cmd.append('-r')
if upper is None:
cmd.append(str(int(lower)))
else:
cmd.append('%d:%d' % (int(lower), int(upper)))
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 load( self, stream, progress=None, ignore_uuid=False, force_uuid=False, use_pre_commit_hook=False, use_post_commit_hook=False, parent_dir=None ):
"""Load a d... |
cmd = [SVNADMIN, 'load', '.']
if progress is None:
cmd.append('-q')
if ignore_uuid:
cmd.append('--ignore-uuid')
if force_uuid:
cmd.append('--force-uuid')
if use_pre_commit_hook:
cmd.append('--use-pre-commit-hook')
if use_po... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def temp_file( content=None, suffix='', prefix='tmp', parent_dir=None):
""" Create a temporary file and optionally populate it with content. The file is deleted ... |
binary = isinstance(content, (bytes, bytearray))
parent_dir = parent_dir if parent_dir is None else str(parent_dir)
fd, abs_path = tempfile.mkstemp(suffix, prefix, parent_dir, text=False)
path = pathlib.Path(abs_path)
try:
try:
if content:
os.write(fd, content 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 load_content(self):
""" Load the book content """ |
# get the toc file from the root file
rel_path = self.root_file_url.replace(os.path.basename(self.root_file_url), '')
self.toc_file_url = rel_path + self.root_file.find(id="ncx")['href']
self.toc_file_soup = bs(self.book_file.read(self.toc_file_url), 'xml')
# get the book cont... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def UninstallTrump(RemoveDataTables=True, RemoveOverrides=True, RemoveFailsafes=True):
"""
This script removes all tables associated with Trump.
It's writte... |
ts = ['_symbols', '_symbol_validity', '_symbol_tags', '_symbol_aliases',
'_feeds', '_feed_munging', '_feed_munging_args', '_feed_sourcing',
'_feed_validity', '_feed_meta', '_feed_tags', '_feed_handle',
'_index_kwargs', '_indicies', '_symbol_handle', '_symboldatadef']
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def digestInSilico(proteinSequence, cleavageRule='[KR]', missedCleavage=0, removeNtermM=True, minLength=5, maxLength=55):
"""Returns a list of peptide sequences ... |
passFilter = lambda startPos, endPos: (endPos - startPos >= minLength and
endPos - startPos <= maxLength
)
_regexCleave = re.finditer(cleavageRule, proteinSequence)
cleavagePosList = set(itertools.chain(map(lambda x: x.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 calcPeptideMass(peptide, **kwargs):
"""Calculate the mass of a peptide. :param aaMass: A dictionary with the monoisotopic masses of amino acid residues, by d... |
aaMass = kwargs.get('aaMass', maspy.constants.aaMass)
aaModMass = kwargs.get('aaModMass', maspy.constants.aaModMass)
elementMass = kwargs.get('elementMass', pyteomics.mass.nist_mass)
addModMass = float()
unmodPeptide = peptide
for modId, modMass in viewitems(aaModMass):
modSymbol = '['... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def removeModifications(peptide):
"""Removes all modifications from a peptide string and return the plain amino acid sequence. :param peptide: peptide sequence, ... |
while peptide.find('[') != -1:
peptide = peptide.split('[', 1)[0] + peptide.split(']', 1)[1]
return peptide |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def returnModPositions(peptide, indexStart=1, removeModString='UNIMOD:'):
"""Determines the amino acid positions of all present modifications. :param peptide: pe... |
unidmodPositionDict = dict()
while peptide.find('[') != -1:
currModification = peptide.split('[')[1].split(']')[0]
currPosition = peptide.find('[') - 1
if currPosition == -1: # move n-terminal modifications to first position
currPosition = 0
currPosition += indexStar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calcMhFromMz(mz, charge):
"""Calculate the MH+ value from mz and charge. :param mz: float, mass to charge ratio (Dalton / charge) :param charge: int, charge ... |
mh = (mz * charge) - (maspy.constants.atomicMassProton * (charge-1) )
return mh |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calcMzFromMh(mh, charge):
"""Calculate the mz value from MH+ and charge. :param mh: float, mass to charge ratio (Dalton / charge) of the mono protonated ion ... |
mz = (mh + (maspy.constants.atomicMassProton * (charge-1))) / charge
return mz |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calcMzFromMass(mass, charge):
"""Calculate the mz value of a peptide from its mass and charge. :param mass: float, exact non protonated mass :param charge: i... |
mz = (mass + (maspy.constants.atomicMassProton * charge)) / charge
return mz |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calcMassFromMz(mz, charge):
"""Calculate the mass of a peptide from its mz and charge. :param mz: float, mass to charge ratio (Dalton / charge) :param charge... |
mass = (mz - maspy.constants.atomicMassProton) * charge
return mass |
<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, processProtocol, command, env={}, path=None, uid=None, gid=None, usePTY=0, childFDs=None):
"""Execute a process on the remote machine using SSH... |
sshCommand = (command if isinstance(command, SSHCommand)
else SSHCommand(command, self.precursor, path))
commandLine = sshCommand.getCommandLine()
# Get connection to ssh server
connectionDeferred = self.getConnection(uid)
# spawn the remote process
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getUserAuthObject(self, user, connection):
"""Get a SSHUserAuthClient object to use for authentication @param user: The username to authenticate for @param ... |
credentials = self._getCredentials(user)
userAuthObject = AutomaticUserAuthClient(user, connection, **credentials)
return userAuthObject |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _verifyHostKey(self, hostKey, fingerprint):
"""Called when ssh transport requests us to verify a given host key. Return a deferred that callback if we accept... |
if fingerprint in self.knownHosts:
return defer.succeed(True)
return defer.fail(UnknownHostKey(hostKey, fingerprint)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def yield_once(iterator):
""" Decorator to make an iterator returned by a method yield each result only once. [1, 2] :param iterator: Any method that returns an ... |
@wraps(iterator)
def yield_once_generator(*args, **kwargs):
yielded = set()
for item in iterator(*args, **kwargs):
if item not in yielded:
yielded.add(item)
yield item
return yield_once_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 _to_list(var):
""" Make variable to list. [] ['whee'] [None] [1, 2, 3] :param var: variable of any type :return: list """ |
if isinstance(var, list):
return var
elif var is None:
return []
elif isinstance(var, str) or isinstance(var, dict):
# We dont want to make a list out of those via the default constructor
return [var]
else:
try:
return list(var)
except TypeErr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def arguments_to_lists(function):
""" Decorator for a function that converts all arguments to lists. :param function: target function :return: target function wi... |
def l_function(*args, **kwargs):
l_args = [_to_list(arg) for arg in args]
l_kwargs = {}
for key, value in kwargs.items():
l_kwargs[key] = _to_list(value)
return function(*l_args, **l_kwargs)
return l_function |
<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_eq(*members):
""" Decorator that generates equality and inequality operators for the decorated class. The given members as well as the type of self ... |
def decorator(cls):
def eq(self, other):
if not isinstance(other, cls):
return False
return all(getattr(self, member) == getattr(other, member)
for member in members)
def ne(self, other):
return not eq(self, other)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enforce_signature(function):
""" Enforces the signature of the function by throwing TypeError's if invalid arguments are provided. The return value is not ch... |
argspec = inspect.getfullargspec(function)
annotations = argspec.annotations
argnames = argspec.args
unnamed_annotations = {}
for i, arg in enumerate(argnames):
if arg in annotations:
unnamed_annotations[i] = (annotations[arg], arg)
def decorated(*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 as_string(self):
"""Get the underlying message object as a string""" |
if self.headers_only:
self.msgobj = self._get_content()
# We could just use msgobj.as_string() but this is more flexible... we might need it.
from email.generator import Generator
fp = StringIO()
g = Generator(fp, maxheaderlen=60)
g.flatten(self.msgobj)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iteritems(self):
"""Present the email headers""" |
for n,v in self.msgobj.__dict__["_headers"]:
yield n.lower(), v
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_flag(self, flag):
"""Turns the specified flag on""" |
self.folder._invalidate_cache()
# TODO::: turn the flag off when it's already on
def replacer(m):
return "%s/%s.%s%s" % (
joinpath(self.folder.base, self.folder.folder, "cur"),
m.group("key"),
m.group("hostname"),
":2,%... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_message(self, key, since=None):
"""Return the MdMessage object for the key. The object is either returned from the cache in the store or made, cached an... |
stored = self.store[key]
if isinstance(stored, dict):
filename = stored["path"]
folder = stored["folder"]
if since and since > 0.0:
st = stat(filename)
if st.st_mtime < since:
return None
stored = MdMess... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _foldername(self, additionalpath=""):
"""Dot decorate a folder name.""" |
if not self._foldername_cache.get(additionalpath):
fn = joinpath(self.base, self.folder, additionalpath) \
if not self.is_subfolder \
else joinpath(self.base, ".%s" % self.folder, additionalpath)
self._foldername_cache[additionalpath] = fn
return ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def folders(self):
"""Return a map of the subfolder objects for this folder. This is a snapshot of the folder list at the time the call was made. It does not upd... |
entrys = self.filesystem.listdir(abspath(self._foldername()))
regex = re.compile("\\..*")
just_dirs = dict([(d,d) for d in entrys if regex.match(d)])
folder = self._foldername()
filesystem = self.filesystem
class FolderList(object):
def __iter__(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 move(self, key, folder):
"""Move the specified key to folder. folder must be an MdFolder instance. MdFolders can be obtained through the 'folders' method cal... |
# Basically this is a sophisticated __delitem__
# We need the path so we can make it in the new folder
path, host, flags = self._exists(key)
self._invalidate_cache()
# Now, move the message file to the new folder
newpath = joinpath(
folder.base,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _muaprocessnew(self):
"""Moves all 'new' files into cur, correctly flagging""" |
foldername = self._foldername("new")
files = self.filesystem.listdir(foldername)
for filename in files:
if filename == "":
continue
curfilename = self._foldername(joinpath("new", filename))
newfilename = joinpath(
self._cur,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _exists(self, key):
"""Find a key in a particular section Searches through all the files and looks for matches with a regex. """ |
filecache, keycache = self._fileslist()
msg = keycache.get(key, None)
if msg:
path = msg.filename
meta = filecache[path]
return path, meta["hostname"], meta.get("flags", "")
raise KeyError("not found %s" % 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 __put_slice_in_slim(slim, dataim, sh, i):
"""
put one small slice as a tile in a big image
""" |
a, b = np.unravel_index(int(i), sh)
st0 = int(dataim.shape[0] * a)
st1 = int(dataim.shape[1] * b)
sp0 = int(st0 + dataim.shape[0])
sp1 = int(st1 + dataim.shape[1])
slim[
st0:sp0,
st1:sp1
] = dataim
return slim |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
""" |
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data)
except:
pass
data = __select_slices(data, axis, slice_step, first_slice_offset=first_slice_offset)
return 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 index_to_coords(index, shape):
'''convert index to coordinates given the shape'''
coords = []
for i in xrange(1, len(shape)):
divisor = int(np.product(shape[i:]))
value = index // divisor
coords.append(value)
index -= value * divisor
coords.append(index)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.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 on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(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 get_seed_sub(self, label):
""" Return list of all seeds with specific label
""" |
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def push(self, item):
'''Push the value item onto the heap, maintaining the heap invariant.
If the item is not hashable, a TypeError is raised.
'''
hash(item)
heapq.heappush(self._items, 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 format_field_by_match(self, value, match):
"""Formats a field by a Regex match of the format spec pattern.""" |
groups = match.groups()
fill, align, sign, sharp, zero, width, comma, prec, type_ = groups
if not comma and not prec and type_ not in list('fF%'):
return None
if math.isnan(value) or math.isinf(value):
return None
locale = self.numeric_locale
# Fo... |
<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(self):
""" Resets the time intervals """ |
self._start = 0
self._first_start = 0
self._stop = time.perf_counter()
self._array = None
self._array_len = 0
self.intervals = []
self._intervals_len = 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 read(filename):
""" Read a file relative to setup.py location. """ |
import os
here = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(here, filename)) as fd:
return fd.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 find_version(filename):
""" Find package version in file. """ |
import re
content = read(filename)
version_match = re.search(
r"^__version__ = ['\"]([^'\"]*)['\"]", content, re.M
)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to find version string.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_requirements(filename):
""" Find requirements in file. """ |
import string
content = read(filename)
requirements = []
for line in content.splitlines():
line = line.strip()
if line and line[:1] in string.ascii_letters:
requirements.append(line)
return requirements |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_uuid(basedata=None):
""" Provides a _random_ UUID with no input, or a UUID4-format MD5 checksum of any input data provided """ |
if basedata is None:
return str(uuid.uuid4())
elif isinstance(basedata, str):
checksum = hashlib.md5(basedata).hexdigest()
return '%8s-%4s-%4s-%4s-%12s' % (
checksum[0:8], checksum[8:12], checksum[12:16], checksum[16:20], checksum[20:32]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_unix(cls, seconds, milliseconds=0):
""" Produce a full |datetime.datetime| object from a Unix timestamp """ |
base = list(time.gmtime(seconds))[0:6]
base.append(milliseconds * 1000) # microseconds
return cls(*base) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_unix(cls, timestamp):
""" Wrapper over time module to produce Unix epoch time as a float """ |
if not isinstance(timestamp, datetime.datetime):
raise TypeError('Time.milliseconds expects a datetime object')
base = time.mktime(timestamp.timetuple())
return base |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
""" Convert all strings to UTF-8 """ |
for key in data:
if isinstance(data[key], str):
data[key] = data[key].encode('utf-8')
return 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 consume_options(cls, data, hittype, args):
""" Interpret sequential arguments related to known hittypes based on declared structures """ |
opt_position = 0
data['t'] = hittype # integrate hit type parameter
if hittype in cls.option_sequence:
for expected_type, optname in cls.option_sequence[hittype]:
if opt_position < len(args) and isinstance(args[opt_position], expected_type):
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 set_timestamp(self, data):
""" Interpret time-related options, apply queue-time parameter as needed """ |
if 'hittime' in data: # an absolute timestamp
data['qt'] = self.hittime(timestamp=data.pop('hittime', None))
if 'hitage' in data: # a relative age (in seconds)
data['qt'] = self.hittime(age=data.pop('hitage', None)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def send(self, hittype, *args, **data):
""" Transmit HTTP requests to Google Analytics using the measurement protocol """ |
if hittype not in self.valid_hittypes:
raise KeyError('Unsupported Universal Analytics Hit Type: {0}'.format(repr(hittype)))
self.set_timestamp(data)
self.consume_options(data, hittype, args)
for item in args: # process dictionary-object arguments of transcient 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 get_process_log(self, pid=None, start=0, limit=1000):
'''
get_process_log(self, pid=None, start=0, limit=1000
Get process logs
:Parameters:
* *pid* (`string`) -- Identifier of an existing process
* *pid* (`string`) -- start index to retrieve logs from
* *pid... |
<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(self):
"""Pull features from the instream and write them to the output.""" |
for entry in self._instream:
if isinstance(entry, Feature):
for feature in entry:
if feature.num_children > 0 or feature.is_multi:
if feature.is_multi and feature != feature.multi_rep:
continue
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def date2doy(time: Union[str, datetime.datetime]) -> Tuple[int, int]: """ < 366 for leap year too. normal year 0..364. Leap 0..365. """ |
T = np.atleast_1d(time)
year = np.empty(T.size, dtype=int)
doy = np.empty_like(year)
for i, t in enumerate(T):
yd = str(datetime2yeardoy(t)[0])
year[i] = int(yd[:4])
doy[i] = int(yd[4:])
assert ((0 < doy) & (doy < 366)).all(), 'day of year must be 0 < doy < 366'
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 randomdate(year: int) -> datetime.date: """ gives random date in year""" |
if calendar.isleap(year):
doy = random.randrange(366)
else:
doy = random.randrange(365)
return datetime.date(year, 1, 1) + datetime.timedelta(days=doy) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def function_to_serializable_representation(fn):
""" Converts a Python function into a serializable representation. Does not currently work for methods or functi... |
if type(fn) not in (FunctionType, BuiltinFunctionType):
raise ValueError(
"Can't serialize %s : %s, must be globally defined function" % (
fn, type(fn),))
if hasattr(fn, "__closure__") and fn.__closure__ is not None:
raise ValueError("No serializable representation ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_serializable_dict(x):
""" Reconstruct a dictionary by recursively reconstructing all its keys and values. This is the most hackish part since we rely on... |
if "__name__" in x:
return _lookup_value(x.pop("__module__"), x.pop("__name__"))
non_string_key_objects = [
from_json(serialized_key)
for serialized_key
in x.pop(SERIALIZED_DICTIONARY_KEYS_FIELD, [])
]
converted_dict = type(x)()
for k, v in x.items():
serial... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_serializable_repr(x):
""" Convert an instance of Serializable or a primitive collection containing such instances into serializable types. """ |
t = type(x)
if isinstance(x, list):
return list_to_serializable_repr(x)
elif t in (set, tuple):
return {
"__class__": class_to_serializable_representation(t),
"__value__": list_to_serializable_repr(x)
}
elif isinstance(x, dict):
return dict_to_ser... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _combine_rest_push(self):
"""Combining Rest and Push States""" |
new = []
change = 0
# DEBUG
# logging.debug('Combining Rest and Push')
i = 0
examinetypes = self.quickresponse_types[3]
for state in examinetypes:
if state.type == 3:
for nextstate_id in state.trans.keys():
found = ... |
<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(self, accepted):
"""_check for string existence""" |
# logging.debug('A check is now happening...')
# for key in self.statediag[1].trans:
# logging.debug('transition to '+`key`+" with "+self.statediag[1].trans[key][0])
total = []
if 1 in self.quickresponse:
total = total + self.quickresponse[1]
if (1, 0) 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 _stage(self, accepted, count=0):
"""This is a repeated state in the state removal algorithm""" |
new5 = self._combine_rest_push()
new1 = self._combine_push_pop()
new2 = self._combine_push_rest()
new3 = self._combine_pop_rest()
new4 = self._combine_rest_rest()
new = new1 + new2 + new3 + new4 + new5
del new1
del new2
del new3
del new4
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def printer(self):
"""Visualizes the current state""" |
for key in self.statediag:
if key.trans is not None and len(key.trans) > 0:
print '****** ' + repr(key.id) + '(' + repr(key.type)\
+ ' on sym ' + repr(key.sym) + ') ******'
print key.trans |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init(self, states, accepted):
"""Initialization of the indexing dictionaries""" |
self.statediag = []
for key in states:
self.statediag.append(states[key])
self.quickresponse = {}
self.quickresponse_types = {}
self.quickresponse_types[0] = []
self.quickresponse_types[1] = []
self.quickresponse_types[2] = []
self.quickrespon... |
<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(filelocation, outpath, executable, args=None, switchArgs=None):
"""Executes the dinosaur tool on Windows operating systems. :param filelocation: eith... |
procArgs = ['java', '-jar', executable]
procArgs.extend(['-output_path', outpath])
if args is not None:
for arg in args:
procArgs.extend(['-'+arg[0], arg[1]])
if switchArgs is not None:
procArgs.extend(['-'+arg for arg in switchArgs])
procArgs.extend(aux.toList(fileloca... |
<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_example():
"""Generate a configuration file example. This utility will load some number of Python modules which are assumed to register options with... |
cmd_args = sys.argv[1:]
parser = argparse.ArgumentParser(description='Confpy example generator.')
parser.add_argument(
'--module',
action='append',
help='A python module which should be imported.',
)
parser.add_argument(
'--file',
action='append',
hel... |
<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(self, val=True):
"""Get the number of bits in the array with the specified value. Args: val: A boolean value to check against the array's value. Return... |
return sum((elem.count(val) for elem in self._iter_components())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _api_group_for_type(cls):
""" Determine which Kubernetes API group a particular PClass is likely to belong with. This is basically nonsense. The question bei... |
_groups = {
(u"v1beta1", u"Deployment"): u"extensions",
(u"v1beta1", u"DeploymentList"): u"extensions",
(u"v1beta1", u"ReplicaSet"): u"extensions",
(u"v1beta1", u"ReplicaSetList"): u"extensions",
}
key = (
cls.apiVersion,
cls.__name__.rsplit(u".")[-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 response(request, status, obj):
""" Generate a response. :param IRequest request: The request being responsed to. :param int status: The response status code... |
request.setResponseCode(status)
request.responseHeaders.setRawHeaders(
u"content-type", [u"application/json"],
)
body = dumps_bytes(obj)
return body |
<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, collection_name, obj):
""" Create a new object in the named collection. :param unicode collection_name: The name of the collection in which to c... |
obj = self.agency.before_create(self, obj)
new = self.agency.after_create(self, obj)
updated = self.transform(
[collection_name],
lambda c: c.add(new),
)
return updated |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace(self, collection_name, old, new):
""" Replace an existing object with a new version of it. :param unicode collection_name: The name of the collection... |
self.agency.before_replace(self, old, new)
updated = self.transform(
[collection_name],
lambda c: c.replace(old, new),
)
return updated |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execution_timer(value):
"""The ``execution_timer`` decorator allows for easy instrumentation of the duration of function calls, using the method name in the ... |
def _invoke(method, key_arg_position, *args, **kwargs):
start_time = time.time()
result = method(*args, **kwargs)
duration = time.time() - start_time
key = [method.func_name]
if key_arg_position is not None:
key.append(args[key_arg_position])
add_timing(... |
<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_lang(self, *args, **kwargs):
""" Let users select language """ |
if "lang" in kwargs:
if kwargs["lang"] in self._available_languages:
self.lang = kwargs["lang"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def notify(self, msg, color='green', notify='true', message_format='text'):
"""Send notification to specified HipChat room""" |
self.message_dict = {
'message': msg,
'color': color,
'notify': notify,
'message_format': message_format,
}
if not self.debug:
return requests.post(
self.notification_url,
json.dumps(self.message_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 trial(path=TESTS_PATH, coverage=False):
"""Run tests using trial """ |
args = ['trial']
if coverage:
args.append('--coverage')
args.append(path)
print args
local(' '.join(args)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_result_value(self, value, dialect):
""" When SQLAlchemy gets the string representation from a ReprObjType column, it converts it to the python equiva... |
if value is not None:
cmd = "value = {}".format(value)
exec(cmd)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_regex(separator):
"""Utility function to create regexp for matching escaped separators in strings. """ |
return re.compile(r'(?:' + re.escape(separator) + r')?((?:[^' +
re.escape(separator) + 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 strip_comments(text):
"""Comment stripper for JSON. """ |
regex = r'\s*(#|\/{2}).*$'
regex_inline = r'(:?(?:\s)*([A-Za-z\d\.{}]*)|((?<=\").*\"),?)(?:\s)*(((#|(\/{2})).*)|)$' # noqa
lines = text.split('\n')
for index, line in enumerate(lines):
if re.search(regex, line):
if re.search(r'^' + regex, line, re.IGNORECASE):
line... |
<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(action):
"""Action registration is used to support generating lists of permitted actions from a permission set and an object pattern. Only registere... |
if isinstance(action, str):
Action.register(Action(action))
elif isinstance(action, Action):
Action.registered.add(action)
else:
for a in action:
Action.register(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 allow(self, act, obj=None):
"""Determine where a given action on a given object is allowed. """ |
objc = obj.components if obj is not None else []
try:
return self.tree[act.components + objc] == 'allow'
except KeyError:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def permitted_actions(self, obj=None):
"""Determine permitted actions for a given object pattern. """ |
return [a for a in Action.registered
if self.allow(a, obj(str(a)) if obj is not None 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 subscribe(ws):
"""WebSocket endpoint, used for liveupdates""" |
while ws is not None:
gevent.sleep(0.1)
try:
message = ws.receive() # expect function name to subscribe to
if message:
stream.register(ws, message)
except WebSocketError:
ws = 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 could_scope_out(self):
""" could bubble up from current scope :return: """ |
return not self.waiting_for or \
isinstance(self.waiting_for, callable.EndOfStory) or \
self.is_breaking_a_loop() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def alias(self):
""" If the _alias cache is None, just build the alias from the item name. """ |
if self._alias is None:
if self.name in self.aliases_fix:
self._alias = self.aliases_fix[self.name]
else:
self._alias = self.name.lower()\
.replace(' ', '-')\
.replace('(', '')\
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_configs(self, conf_file):
""" Assumes that the config file does not have any sections, so throw it all in global """ |
with open(conf_file) as stream:
lines = itertools.chain(("[global]",), stream)
self._config.read_file(lines)
return self._config['global'] |
<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_quotes(self, configs):
""" Because some values are wraped in single quotes """ |
for key in configs:
value = configs[key]
if value[0] == "'" and value[-1] == "'":
configs[key] = value[1:-1]
return configs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chunks_of(max_chunk_size, list_to_chunk):
""" Yields the list with a max size of max_chunk_size """ |
for i in range(0, len(list_to_chunk), max_chunk_size):
yield list_to_chunk[i:i + max_chunk_size] |
<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_into(max_num_chunks, list_to_chunk):
""" Yields the list with a max total size of max_num_chunks """ |
max_chunk_size = math.ceil(len(list_to_chunk) / max_num_chunks)
return chunks_of(max_chunk_size, list_to_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 get_proxy_parts(proxy):
""" Take a proxy url and break it up to its parts """ |
proxy_parts = {'schema': None,
'user': None,
'password': None,
'host': None,
'port': None,
}
# Find parts
results = re.match(proxy_parts_pattern, proxy)
if results:
matched = results.groupdict()
... |
<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_html_tag(input_str='', tag=None):
""" Returns a string with the html tag and all its contents from a string """ |
result = input_str
if tag is not None:
pattern = re.compile('<{tag}[\s\S]+?/{tag}>'.format(tag=tag))
result = re.sub(pattern, '', str(input_str))
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ip_between(ip, start, finish):
"""Checks to see if IP is between start and finish""" |
if is_IPv4Address(ip) and is_IPv4Address(start) and is_IPv4Address(finish):
return IPAddress(ip) in IPRange(start, finish)
else:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_rfc1918(ip):
"""Checks to see if an IP address is used for local communications within a private network as specified by RFC 1918 """ |
if ip_between(ip, "10.0.0.0", "10.255.255.255"):
return True
elif ip_between(ip, "172.16.0.0", "172.31.255.255"):
return True
elif ip_between(ip, "192.168.0.0", "192.168.255.255"):
return True
else:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_reserved(ip):
"""Checks to see if an IP address is reserved for special purposes. This includes all of the RFC 1918 addresses as well as other blocks that... |
if ip_between(ip, "0.0.0.0", "0.255.255.255"):
return True
elif ip_between(ip, "10.0.0.0", "10.255.255.255"):
return True
elif ip_between(ip, "100.64.0.0", "100.127.255.255"):
return True
elif ip_between(ip, "127.0.0.0", "127.255.255.255"):
return True
elif ip_betwee... |
<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_hash(fhash):
"""Returns true for valid hashes, false for invalid.""" |
# Intentionally doing if/else statement for ease of testing and reading
if re.match(re_md5, fhash):
return True
elif re.match(re_sha1, fhash):
return True
elif re.match(re_sha256, fhash):
return True
elif re.match(re_sha512, fhash):
return True
elif re.match(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 reverse_dns_sna(ipaddress):
"""Returns a list of the dns names that point to a given ipaddress using StatDNS API""" |
r = requests.get("http://api.statdns.com/x/%s" % ipaddress)
if r.status_code == 200:
names = []
for item in r.json()['answer']:
name = str(item['rdata']).strip(".")
names.append(name)
return names
elif r.json()['code'] == 503:
# NXDOMAIN - no PTR ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vt_ip_check(ip, vt_api):
"""Checks VirusTotal for occurrences of an IP address""" |
if not is_IPv4Address(ip):
return None
url = 'https://www.virustotal.com/vtapi/v2/ip-address/report'
parameters = {'ip': ip, 'apikey': vt_api}
response = requests.get(url, params=parameters)
try:
return response.json()
except ValueError:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vt_name_check(domain, vt_api):
"""Checks VirusTotal for occurrences of a domain name""" |
if not is_fqdn(domain):
return None
url = 'https://www.virustotal.com/vtapi/v2/domain/report'
parameters = {'domain': domain, 'apikey': vt_api}
response = requests.get(url, params=parameters)
try:
return response.json()
except ValueError:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vt_hash_check(fhash, vt_api):
"""Checks VirusTotal for occurrences of a file hash""" |
if not is_hash(fhash):
return None
url = 'https://www.virustotal.com/vtapi/v2/file/report'
parameters = {'resource': fhash, 'apikey': vt_api}
response = requests.get(url, params=parameters)
try:
return response.json()
except ValueError:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ipinfo_ip_check(ip):
"""Checks ipinfo.io for basic WHOIS-type data on an IP address""" |
if not is_IPv4Address(ip):
return None
response = requests.get('http://ipinfo.io/%s/json' % ip)
return response.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dshield_ip_check(ip):
"""Checks dshield for info on an IP address""" |
if not is_IPv4Address(ip):
return None
headers = {'User-Agent': useragent}
url = 'https://isc.sans.edu/api/ip/'
response = requests.get('{0}{1}?json'.format(url, ip), headers=headers)
return response.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx, amount, index, stage):
"""Push data to Target Service Client""" |
if not ctx.bubble:
ctx.say_yellow('There is no bubble present, will not push')
raise click.Abort()
TGT = None
transformed = True
STAGE = None
if stage in STAGES and stage in ctx.cfg.CFG:
STAGE = ctx.cfg.CFG[stage]
if not STAGE:
ctx.say_red('There is no STAGE ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.