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 file stream to which the dumpfile is written :param progress: A file stream to which progress is written :param lower: Must be a numeric version number :param upper: Must be a numeric version number See ``svnadmin help dump`` for details on the other arguments. """ |
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)))
if incremental:
cmd.append('--incremental')
if deltas:
cmd.append('--deltas')
p = subprocess.Popen(cmd, cwd=self.path, stdout=stream, stderr=progress)
p.wait()
if p.returncode != 0:
raise subprocess.CalledProcessError(p.returncode, 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 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 dumpfile stream into the repository. :param stream: A file stream from which the dumpfile is read :param progress: A file stream to which progress is written See ``svnadmin help load`` for details on the other arguments. """ |
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_post_commit_hook:
cmd.append('--use-post-commit-hook')
if parent_dir:
cmd.extend(['--parent-dir', parent_dir])
p = subprocess.Popen(
cmd, cwd=self.path, stdin=stream, stdout=progress,
stderr=subprocess.PIPE
)
stderr = p.stderr.read()
p.stderr.close()
p.wait()
if p.returncode != 0:
raise subprocess.CalledProcessError(p.returncode, cmd, stderr) |
<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 when the context exits. The temporary file is created when entering the context manager and deleted when exiting it. The user may also supply some content for the file to be populated with: The temporary file can be placed in a custom directory: If, for some reason, the user wants to delete the temporary file before exiting the context, that's okay too: """ |
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 binary else content.encode())
finally:
os.close(fd)
yield path.resolve()
finally:
with temporary.util.allow_missing_file():
path.unlink() |
<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 content from the toc file
for n, c in cross(self.toc_file_soup.find_all('navLabel'), self.toc_file_soup.find_all('content')):
content_soup = bs(self.book_file.read(rel_path + c.get('src')))
self.content.append({'part_name': c.text,
'source_url': c.get('src'),
'content_source': content_soup,
'content_source_body': content_soup.body,
'content_source_text': content_soup.body.text}) |
<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 written for PostgreSQL, but should be very easy to adapt to other
databases.
""" |
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']
if RemoveOverrides:
ts.append('_overrides')
if RemoveFailsafes:
ts.append('_failsafes')
engine = create_engine(ENGINE_STR)
if RemoveDataTables:
results = engine.execute("SELECT name FROM _symbols;")
datatables = [row['name'] for row in results]
ts = ts + datatables
drops = "".join(['DROP TABLE IF EXISTS "{}" CASCADE;'.format(t) for t in ts])
engine.execute(drops) |
<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 and cleavage information derived from an in silico digestion of a polypeptide. :param proteinSequence: amino acid sequence of the poly peptide to be digested :param cleavageRule: cleavage rule expressed in a regular expression, see :attr:`maspy.constants.expasy_rules` :param missedCleavage: number of allowed missed cleavage sites :param removeNtermM: booo, True to consider also peptides with the N-terminal methionine of the protein removed :param minLength: int, only yield peptides with length >= minLength :param maxLength: int, only yield peptides with length <= maxLength :returns: a list of resulting peptide enries. Protein positions start with ``1`` and end with ``len(proteinSequence``. :: [(peptide amino acid sequence, {'startPos': int, 'endPos': int, 'missedCleavage': int} ] .. note:: This is a regex example for specifying N-terminal cleavage at lysine sites ``\\w(?=[K])`` """ |
passFilter = lambda startPos, endPos: (endPos - startPos >= minLength and
endPos - startPos <= maxLength
)
_regexCleave = re.finditer(cleavageRule, proteinSequence)
cleavagePosList = set(itertools.chain(map(lambda x: x.end(), _regexCleave)))
cleavagePosList.add(len(proteinSequence))
cleavagePosList = sorted(list(cleavagePosList))
#Add end of protein as cleavage site if protein doesn't end with specififed
#cleavage positions
numCleavageSites = len(cleavagePosList)
if missedCleavage >= numCleavageSites:
missedCleavage = numCleavageSites -1
digestionresults = list()
#Generate protein n-terminal peptides after methionine removal
if removeNtermM and proteinSequence[0] == 'M':
for cleavagePos in range(0, missedCleavage+1):
startPos = 1
endPos = cleavagePosList[cleavagePos]
if passFilter(startPos, endPos):
sequence = proteinSequence[startPos:endPos]
info = dict()
info['startPos'] = startPos+1
info['endPos'] = endPos
info['missedCleavage'] = cleavagePos
digestionresults.append((sequence, info))
#Generate protein n-terminal peptides
if cleavagePosList[0] != 0:
for cleavagePos in range(0, missedCleavage+1):
startPos = 0
endPos = cleavagePosList[cleavagePos]
if passFilter(startPos, endPos):
sequence = proteinSequence[startPos:endPos]
info = dict()
info['startPos'] = startPos+1
info['endPos'] = endPos
info['missedCleavage'] = cleavagePos
digestionresults.append((sequence, info))
#Generate all remaining peptides, including the c-terminal peptides
lastCleavagePos = 0
while lastCleavagePos < numCleavageSites:
for missedCleavage in range(0, missedCleavage+1):
nextCleavagePos = lastCleavagePos + missedCleavage + 1
if nextCleavagePos < numCleavageSites:
startPos = cleavagePosList[lastCleavagePos]
endPos = cleavagePosList[nextCleavagePos]
if passFilter(startPos, endPos):
sequence = proteinSequence[startPos:endPos]
info = dict()
info['startPos'] = startPos+1
info['endPos'] = endPos
info['missedCleavage'] = missedCleavage
digestionresults.append((sequence, info))
lastCleavagePos += 1
return digestionresults |
<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 default :attr:`maspy.constants.aaMass` :param aaModMass: A dictionary with the monoisotopic mass changes of modications, by default :attr:`maspy.constants.aaModMass` :param elementMass: A dictionary with the masses of chemical elements, by default ``pyteomics.mass.nist_mass`` :param peptide: peptide sequence, modifications have to be written in the format "[modificationId]" and "modificationId" has to be present in :attr:`maspy.constants.aaModMass` #TODO: change to a more efficient way of calculating the modified mass, by first extracting all present modifications and then looking up their masses. """ |
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 = '[' + modId + ']'
numMod = peptide.count(modSymbol)
if numMod > 0:
unmodPeptide = unmodPeptide.replace(modSymbol, '')
addModMass += modMass * numMod
if unmodPeptide.find('[') != -1:
print(unmodPeptide)
raise Exception('The peptide contains modification, ' +
'not present in maspy.constants.aaModMass'
)
unmodPeptideMass = sum(aaMass[i] for i in unmodPeptide)
unmodPeptideMass += elementMass['H'][0][0]*2 + elementMass['O'][0][0]
modPeptideMass = unmodPeptideMass + addModMass
return modPeptideMass |
<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, modifications have to be written in the format "[modificationName]" :param peptide: str :returns: amino acid sequence of ``peptide`` without any modifications """ |
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: peptide sequence, modifications have to be written in the format "[modificationName]" :param indexStart: returned amino acids positions of the peptide start with this number (first amino acid position = indexStart) :param removeModString: string to remove from the returned modification name #TODO: adapt removeModString to the new unimod ids in #maspy.constants.aaModComp ("UNIMOD:X" -> "u:X") -> also change unit tests. """ |
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 += indexStart
peptide = peptide.replace('['+currModification+']', '', 1)
if removeModString:
currModification = currModification.replace(removeModString, '')
unidmodPositionDict.setdefault(currModification,list())
unidmodPositionDict[currModification].append(currPosition)
return unidmodPositionDict |
<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 state :returns: mass to charge ratio of the mono protonated ion (charge = 1) """ |
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 :param charge: int, charge state :returns: mass to charge ratio of the specified charge state """ |
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: int, charge state :returns: mass to charge ratio of the specified charge state """ |
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: int, charge state :returns: non protonated mass (charge = 0) """ |
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 @param processProtocol: the ProcessProtocol instance to connect @param executable: the executable program to run @param args: the arguments to pass to the process @param env: environment variables to request the remote ssh server to set @param path: the remote path to start the remote process on @param uid: user id or username to connect to the ssh server with @param gid: this is not used for remote ssh processes @param usePTY: wither to request a pty for the process @param childFDs: file descriptors to use for stdin, stdout and stderr """ |
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
connectionDeferred.addCallback(connectProcess, processProtocol,
commandLine, env, usePTY, childFDs)
return connectionDeferred |
<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 connection: The connection service to start after authentication """ |
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 the key or errback if we decide to reject it. """ |
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 iterator :return: An method returning an iterator that yields every result only once at most. """ |
@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 TypeError:
return [var] |
<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 with only lists as parameters """ |
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 and other will be taken into account. Note that this decorator modifies the given class in place! :param members: A list of members to compare for equality. """ |
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)
cls.__eq__ = eq
cls.__ne__ = ne
return cls
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enforce_signature(function):
""" Enforces the signature of the function by throwing TypeError's if invalid arguments are provided. The return value is not checked. You can annotate any parameter of your function with the desired type or a tuple of allowed types. If you annotate the function with a value, this value only will be allowed (useful especially for None). Example: Any string value for any parameter e.g. would then trigger a TypeError. :param function: The function to check. """ |
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):
for i, annotation in unnamed_annotations.items():
if i < len(args):
assert_right_type(args[i], annotation[0], annotation[1])
for argname, argval in kwargs.items():
if argname in annotations:
assert_right_type(argval, annotations[argname], argname)
return function(*args, **kwargs)
return decorated |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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)
text = fp.getvalue()
return text |
<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,%s" % (
"%s%s" % (m.group("flags"), flag) if m.group("flags") \
else flag
)
)
newfilename = self.msgpathre.sub(replacer, self.filename)
self.filesystem.rename(self.filename, newfilename)
self.filename = newfilename |
<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 and then returned. If 'since' is passed in the modification time of the file is checked and the message is only returned if the mtime is since the specified time. If the 'since' check fails, None is returned. 'since' must be seconds since epoch. """ |
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 = MdMessage(
key,
filename = filename,
folder = folder,
filesystem = folder.filesystem
)
self.store[key] = stored
else:
if since and since > 0.0:
st = stat(stored.filename)
if st.st_mtime < since:
return None
return stored |
<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 self._foldername_cache[additionalpath] |
<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 update over time. The map contains MdFolder objects: maildir.folders()["Sent"] might retrieve the folder .Sent from the maildir. """ |
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):
dirs = list(just_dirs.keys())
dirs.sort()
dirs.reverse()
for dn in dirs:
yield MdFolder(
dn[1:],
base=folder,
subfolder=True,
filesystem=filesystem
)
return
def __list__(self):
return [dn[1:] for dn in just_dirs]
def __contains__(self, name):
return just_dirs.__contains__(".%s" % name)
def __getitem__(self, name):
return MdFolder(
just_dirs[".%s" % name][1:],
base=folder,
subfolder=True,
filesystem=filesystem
)
f = FolderList()
return f |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move(self, key, folder):
"""Move the specified key to folder. folder must be an MdFolder instance. MdFolders can be obtained through the 'folders' method call. """ |
# 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,
folder.get_name(),
"cur", # we should probably move it to new if it's in new
basename(path)
)
self.filesystem.rename(path, newpath)
# And update the caches in the new folder
folder._invalidate_cache() |
<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,
"%s:2,%s" % (filename, "")
)
self.filesystem.rename(curfilename, newfilename) |
<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)
return tuple(coords) |
<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 = self.rect.xy
self.press = [event.xdata], [event.ydata], event.button |
<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.append(event.ydata) |
<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.ax)
# plt.plot(x0, y0)
# button Mapping
btn = self.button_map[btn]
self.set_seeds(y0, x0, self.actual_slice, btn)
# self.fig.canvas.draw()
# pdb.set_trace();
self.press = None
self.update_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 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
# Format number value.
prefix = get_prefix(sign)
if type_ == 'd':
if prec is not None:
raise ValueError('precision not allowed in '
'integer format specifier')
string = format_number(value, 0, prefix, locale)
elif type_ in 'fF%':
format_ = format_percent if type_ == '%' else format_number
string = format_(value, int(prec or DEFAULT_PREC), prefix, locale)
else:
# Don't handle otherwise.
return None
if not comma:
# Formatted number always contains group symbols.
# Remove the symbols if not required.
string = remove_group_symbols(string, locale)
if not (fill or align or zero or width):
return string
# Fix a layout.
spec = ''.join([fill or u'', align or u'>',
zero or u'', width or u''])
return format(string, spec) |
<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[optname] = args[opt_position]
opt_position += 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 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
if isinstance(item, dict):
for key, val in self.payload(item):
data[key] = val
for k, v in self.params.items(): # update only absent parameters
if k not in data:
data[k] = v
data = dict(self.payload(data))
if self.hash_client_id:
data['cid'] = generate_uuid(data['cid'])
# Transmit the hit to Google...
await self.http.send(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* (`string`) -- maximum number of entities to retrieve
:return: Process log entries
'''
pid = self._get_pid(pid)
data = self._call_rest_api('get', '/processes/'+pid+'/log?start={}&limit={}'.format(start,limit), error='Failed to fetch process log')
return data['list'] |
<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
self.feature_counts[feature.type] += 1
fid = '{}{}'.format(feature.type,
self.feature_counts[feature.type])
feature.add_attribute('ID', fid)
else:
feature.drop_attribute('ID')
if isinstance(entry, Sequence) and not self._seq_written:
print('##FASTA', file=self.outfile)
self._seq_written = True
print(repr(entry), file=self.outfile) |
<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'
return doy, year |
<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 functions with closure data. """ |
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 for closure %s" % (fn,))
return {"__module__": get_module_name(fn), "__name__": fn.__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 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 key names such as __name__, __class__, __module__ as metadata about how to reconstruct an object. TODO: It would be cleaner to always wrap each object in a layer of type metadata and then have an inner dictionary which represents the flattened result of to_dict() for user-defined objects. """ |
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():
serialized_key_index = parse_serialized_keys_index(k)
if serialized_key_index is not None:
k = non_string_key_objects[serialized_key_index]
converted_dict[k] = from_serializable_repr(v)
if "__class__" in converted_dict:
class_object = converted_dict.pop("__class__")
if "__value__" in converted_dict:
return class_object(converted_dict["__value__"])
elif hasattr(class_object, "from_dict"):
return class_object.from_dict(converted_dict)
else:
return class_object(**converted_dict)
return converted_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 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_serializable_repr(x)
elif isinstance(x, (FunctionType, BuiltinFunctionType)):
return function_to_serializable_representation(x)
elif type(x) is type:
return class_to_serializable_representation(x)
else:
state_dictionary = to_serializable_repr(to_dict(x))
state_dictionary["__class__"] = class_to_serializable_representation(
x.__class__)
return state_dictionary |
<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 = 0
# if nextstate_id != state.id:
if nextstate_id in self.quickresponse:
examines = self.quickresponse[nextstate_id]
for examine in examines:
if examine.id == nextstate_id and examine.type == 1:
temp = PDAState()
temp.type = 1
temp.sym = examine.sym
temp.id = state.id
for nextnextstate_id in examine.trans:
# if nextnextstate_id != examine.id :
for x_char in state.trans[nextstate_id]:
for z_char in examine.trans[
nextnextstate_id]:
if nextnextstate_id not in temp.trans:
temp.trans[
nextnextstate_id] = []
if x_char != 0 and z_char != 0:
temp.trans[
nextnextstate_id].append(x_char + z_char)
# DEBUGprint 'transition is now
# '+x_char +' + '+ z_char
elif x_char != 0 and z_char == 0:
temp.trans[
nextnextstate_id].append(x_char)
# DEBUGprint 'transition is now
# '+x_char
elif x_char == 0 and z_char != 0:
temp.trans[
nextnextstate_id].append(z_char)
# DEBUGprint 'transition is now
# '+z_char
elif x_char == 0 and z_char == 0:
temp.trans[
nextnextstate_id].append(0)
# DEBUGprint 'transition is now
# empty'
else:
pass
found = 1
new.append(temp)
if found == 1:
# print 'Lets combine one with id '+`state.id`+'(rest)
# and one with id '+`nextstate_id`+'(push)'
change = 1
# del(state.trans[nextstate_id])
i = i + 1
if change == 0:
return []
else:
return new |
<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 self.quickresponse:
total = total + self.quickresponse[(1, 0)]
for key in total:
if (key.id == 1 or key.id == (1, 0)) and key.type == 3:
if accepted is None:
if 2 in key.trans:
# print 'Found'
return key.trans[2]
else:
for state in accepted:
if (2, state) in key.trans:
# print 'Found'
return key.trans[(2, state)]
return -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 _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
del new5
if len(new) == 0:
# self.printer()
# print 'PDA is empty'
# logging.debug('PDA is empty')
return None
self.statediag = self.statediag + new
del new
# print 'cleaning...'
# It is cheaper to create a new array than to use the old one and
# delete a key
newstates = []
for key in self.statediag:
if len(key.trans) == 0 or key.trans == {}:
# rint 'delete '+`key.id`
# self.statediag.remove(key)
pass
else:
newstates.append(key)
del self.statediag
self.statediag = newstates
self.quickresponse = {}
self.quickresponse_types = {}
self.quickresponse_types[0] = []
self.quickresponse_types[1] = []
self.quickresponse_types[2] = []
self.quickresponse_types[3] = []
self.quickresponse_types[4] = []
for state in self.statediag:
if state.id not in self.quickresponse:
self.quickresponse[state.id] = [state]
else:
self.quickresponse[state.id].append(state)
self.quickresponse_types[state.type].append(state)
# else:
# print `key.id`+' (type: '+`key.type`+' and sym:'+`key.sym`+')'
# print key.trans
# print 'checking...'
exists = self._check(accepted)
if exists == -1:
# DEBUGself.printer()
# raw_input('next step?')
return self._stage(accepted, count + 1)
else:
# DEBUGself.printer()
# print 'Found '
print exists
# return self._stage(accepted, count+1)
return exists |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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.quickresponse_types[3] = []
self.quickresponse_types[4] = []
for state in self.statediag:
if state.id not in self.quickresponse:
self.quickresponse[state.id] = [state]
else:
self.quickresponse[state.id].append(state)
self.quickresponse_types[state.type].append(state)
# self.printer()
# raw_input('next stepA?')
return self._stage(accepted, 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 execute(filelocation, outpath, executable, args=None, switchArgs=None):
"""Executes the dinosaur tool on Windows operating systems. :param filelocation: either a single mgf file path or a list of file paths. :param outpath: path of the output file, file must not exist :param executable: must specify the complete file path of the spectra-cluster-cli.jar file, supported version is 1.0.2 BETA. :param args: list of arguments containing a value, for details see the spectra-cluster-cli help. Arguments should be added as tuples or a list. For example: [('precursor_tolerance', '0.5'), ('rounds', '3')] :param switchArgs: list of arguments not containing a value, for details see the spectra-cluster-cli help. Arguments should be added as strings. For example: ['fast_mode', 'keep_binary_files'] """ |
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(filelocation))
## run it ##
proc = subprocess.Popen(procArgs, stderr=subprocess.PIPE)
## But do not wait till netstat finish, start displaying output immediately ##
while True:
out = proc.stderr.read(1)
if out == '' and proc.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush() |
<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 confpy and generate an example configuration file based on those options. """ |
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',
help='A python file which should be evaled.',
)
parser.add_argument(
'--format',
default='JSON',
choices=('JSON', 'INI'),
help='The output format of the configuration file.',
)
args = parser.parse_args(cmd_args)
for module in args.module or ():
__import__(module)
for source_file in args.file or ():
cfg = pyfile.PythonFile(path=source_file).config
cfg = config.Configuration()
print(example.generate_example(cfg, ext=args.format)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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. Returns: An integer of the number of bits in the array equal to val. """ |
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 being asked is wrong. An abstraction has failed somewhere. Fixing that will get rid of the need for this. """ |
_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],
)
group = _groups.get(key, None)
return group |
<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 to set. :param obj: Something JSON-dumpable to write into the response body. :return bytes: The response body to write out. eg, return this from a *render_* method. """ |
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 create the object. :param IObject obj: A description of the object to create. :return _KubernetesState: A new state based on the current state but also containing ``obj``. """ |
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 in which to replace an object. :param IObject old: A description of the object being replaced. :param IObject new: A description of the object to take the place of ``old``. :return _KubernetesState: A new state based on the current state but also containing ``obj``. """ |
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 key. The following example would add duration timing with the key ``my_function`` .. code: python @statsd.execution_timer def my_function(foo):
pass You can also have include a string argument value passed to your method as part of the key. Pass the index offset of the arguments to specify the argument number to use. In the following example, the key would be ``my_function.baz``: .. code:python @statsd.execution_timer(2) def my_function(foo, bar, 'baz'):
pass """ |
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('.'.join(key), value=duration)
return result
if type(value) is types.FunctionType:
def wrapper(*args, **kwargs):
return _invoke(value, None, *args, **kwargs)
return wrapper
else:
def duration_decorator(func):
def wrapper(*args, **kwargs):
return _invoke(func, value, *args, **kwargs)
return wrapper
return duration_decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _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),
headers=self.headers
)
else:
print('HipChat message: <{}>'.format(msg))
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 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 equivalent via exec. """ |
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):
lines[index] = ""
elif re.search(regex_inline, line):
lines[index] = re.sub(regex_inline, r'\1', line)
return '\n'.join(lines) |
<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 registered actions will be returned by such queries. """ |
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('(', '')\
.replace(')', '')
return self._alias |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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()
for key in proxy_parts:
proxy_parts[key] = matched.get(key)
else:
logger.error("Invalid proxy format `{proxy}`".format(proxy=proxy))
if proxy_parts['port'] is None:
proxy_parts['port'] = '80'
return proxy_parts |
<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 are reserved by IETF, and IANA for various reasons. https://en.wikipedia.org/wiki/Reserved_IP_addresses """ |
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_between(ip, "169.254.0.0", "169.254.255.255"):
return True
elif ip_between(ip, "172.16.0.0", "172.31.255.255"):
return True
elif ip_between(ip, "192.0.0.0", "192.0.0.255"):
return True
elif ip_between(ip, "192.0.2.0", "192.0.2.255"):
return True
elif ip_between(ip, "192.88.99.0", "192.88.99.255"):
return True
elif ip_between(ip, "192.168.0.0", "192.168.255.255"):
return True
elif ip_between(ip, "198.18.0.0", "198.19.255.255"):
return True
elif ip_between(ip, "198.51.100.0", "198.51.100.255"):
return True
elif ip_between(ip, "203.0.113.0", "203.0.113.255"):
return True
elif ip_between(ip, "224.0.0.0", "255.255.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_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_ssdeep, fhash):
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 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 record
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_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 in CFG:' + stage)
ctx.say_yellow('please check configuration in ' +
ctx.home + '/config/config.yaml')
raise click.Abort()
if 'TARGET' in STAGE:
TGT = STAGE.TARGET
if 'TRANSFORM' in STAGE:
transformed = True
else:
transformed = False
if not transformed:
ctx.say_yellow("""There is no transform defined in the configuration, will not transform,
using the results of step 'pulled' instead of 'push'
""")
if not TGT:
ctx.say_red('There is no TARGET in: ' + stage)
ctx.say_yellow('please check configuration in ' +
ctx.home + '/config/config.yaml')
raise click.Abort()
tgt_client = get_client(ctx.gbc, TGT.CLIENT, ctx.home)
try:
tclient = tgt_client.BubbleClient(cfg=TGT)
tclient.set_parent(ctx.gbc)
tclient.set_verbose(ctx.get_verbose())
except Exception as e:
ctx.say_red('cannot create bubble client:' + TGT.CLIENT)
ctx.say_red(str(e))
raise click.Abort('can not push')
step_to_load = 'push'
if not transformed:
step_to_load = 'pulled'
data_gen = bubble_lod_load(ctx, step_to_load, stage)
full_data = False
if amount == -1 and index == -1:
full_data = True
to_push = get_gen_slice(ctx.gbc, data_gen, amount, index)
error_count = Counter()
total_count = Counter()
pushres = do_yielding_push(ctx=ctx,
to_push=to_push,
tclient=tclient,
total_counter=total_count,
error_counter=error_count)
pfr = bubble_lod_dump(ctx=ctx,
step='pushed',
stage=stage,
full_data=full_data,
reset=True,
data_gen=pushres)
ctx.say('pushed [%d] objects' % pfr['total'])
stats = {}
stats['pushed_stat_error_count'] = error_count.get_total()
stats['pushed_stat_total_count'] = total_count.get_total()
update_stats(ctx, stage, stats)
return True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.