code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
conn, addr = client
if self.handle_incoming(conn, addr):
logging.info('Accepted connection from client: {}'.format(addr))
conn.setblocking(False)
self.clients[conn] = addr
self.register(conn)
else:
logging.info('Refused connec... | def _subthread_handle_accepted(self, client) | Gets accepted clients from the queue object and sets up the client socket.
The client can then be found in the clients dictionary with the socket object
as the key. | 3.637061 | 3.429993 | 1.06037 |
if self.handle_readable(conn):
self.register(conn)
else:
self.disconnect(conn) | def _subthread_handle_readable(self, conn) | Handles readable client sockets. Calls the user modified handle_readable with
the client socket as the only variable. If the handle_readable function returns
true the client is again registered to the selector object otherwise the client
is disconnected. | 6.50317 | 3.751183 | 1.733632 |
logger.info('Subtracting mean visibility in time...')
data_read = numpyview(data_read_mem, 'complex64', datashape(d))
tsubpart = partial(rtlib.meantsub, data_read)
blranges = [(d['nbl'] * t/d['nthread'], d['nbl']*(t+1)/d['nthread']) for t in range(d['nthread'])]
with closing(mp.Pool(1, initia... | def meantsubpool(d, data_read) | Wrapper for mean visibility subtraction in time.
Doesn't work when called from pipeline using multiprocessing pool. | 8.511294 | 7.165844 | 1.187759 |
for flag in d['flaglist']:
mode, sig, conv = flag
# resultlist = []
# with closing(mp.Pool(4, initializer=initreadonly, initargs=(data_read_mem,))) as flagpool:
for ss in d['spw']:
chans = n.arange(d['spw_chanr_select'][ss][0], d['spw_chanr_select'][ss][1])
... | def dataflag(d, data_read) | Flagging data in single process | 4.136725 | 4.141136 | 0.998935 |
data = numpyview(data_mem, 'complex64', datashape(d))
# data = n.ma.masked_array(data, data==0j) # this causes massive overflagging on 14sep03 data
return rtlib.dataflag(data, chans, pol, d, sig, mode, conv) | def dataflagatom(chans, pol, d, sig, mode, conv) | Wrapper function to get shared memory as numpy array into pool
Assumes data_mem is global mps.Array | 12.258048 | 11.528421 | 1.063289 |
data_resamp = numpyview(data_resamp_mem, 'complex64', datashape(d))
with closing(mp.Pool(1, initializer=initresamp, initargs=(data_mem, data_resamp_mem))) as repropool:
# dedisperse
logger.info('Dedispersing with DM=%.1f, dt=%d...' % (d['dmarr'][dmind], d['dtarr'][dtind]))
repropo... | def runreproduce(d, data_mem, data_resamp_mem, u, v, w, dmind, dtind, candint=-1, lm=None, twindow=30) | Reproduce function, much like search.
Returns image and rephased data for given candint.
If no candint is given, it returns resampled data by default. Optionally rephases to lm=(l, m) coordinates. | 3.868641 | 3.78226 | 1.022838 |
ang = lambda ch: l1 * u * d['freq'][ch]/d['freq_orig'][0] + m1 * v * d['freq'][ch]/d['freq_orig'][0]
delay = lambda ch: n.round(4.1488e-3 * dm * (d['freq'][ch]**(-2) - d['freq'][-1]**(-2))/d['inttime'], 0).astype(int)
#snr_ideal = s/(data[i].real.std()/n.sqrt(d['npol']*d['nbl']*d['nchan']))
#logg... | def add_transient(d, data, u, v, w, l1, m1, i, s, dm=0, dt=1) | Add a transient to data.
l1, m1 are relative direction cosines (location) of transient
added at integration i (at highest freq) with brightness s (per int/chan/bl/pol in data units)
dm/dt are dispersion (in pc/cm3) and pulse width (in s). | 6.456856 | 5.885705 | 1.097041 |
rad_arcmin = math.pi/(180*60)
phimin = 0.0
phimax = 2*math.pi
# Amplitude of transient, done in units of the std
# std is calculated assuming that noise level in the middle of the data,
# at index d['readints']/2, is characteristic of that throughout the data
A = random.uniform(... | def make_transient(std, DMmax, Amin=6., Amax=20., rmax=20., rmin=0., DMmin=0.) | Produce a mock transient pulse source for the purposes of characterizing the
detection success of the current pipeline.
Assumes
- Code to inject the transients does so by inserting at an array index
- Noise level at the center of the data array is characteristic of the
noise level throughout... | 5.826029 | 4.112968 | 1.416502 |
if scan == -1: scan = d['scan']
if segments == []: segments = range(d['nsegments'])
d = set_pipeline(d['filename'], scan, fileroot=d['fileroot'], dmarr=[0], dtarr=[1], savenoise=False, timesub='', logfile=False, nsegments=d['nsegments'])
# define memory and numpy arrays
data_mem = mps.Array(... | def pipeline_lightcurve(d, l1=0, m1=0, segments=[], scan=-1) | Makes lightcurve at given (l1, m1)
l1, m1 define phase center. if not set, then image max is used. | 3.50341 | 3.456868 | 1.013463 |
if domock:
prefix = 'candsmock_'
else:
prefix= 'cands_'
if d.has_key('segment'):
return os.path.join(d['workdir'], prefix + d['fileroot'] + '_sc' + str(d['scan']) + 'seg' + str(d['segment']) + '.pkl')
elif segment >= 0:
return os.path.join(d['workdir'], prefix + d['... | def getcandsfile(d, segment=-1, domock=False) | Return name of candsfile for a given dictionary. Must have d['segment'] defined.
domock is option to save simulated cands. | 2.725261 | 2.488352 | 1.095207 |
if d.has_key('segment'):
return os.path.join(d['workdir'], 'noise_' + d['fileroot'] + '_sc' + str(d['scan']) + 'seg' + str(d['segment']) + '.pkl')
elif segment >= 0:
return os.path.join(d['workdir'], 'noise_' + d['fileroot'] + '_sc' + str(d['scan']) + 'seg' + str(segment) + '.pkl')
else... | def getnoisefile(d, segment=-1) | Return name of noisefile for a given dictionary. Must have d['segment'] defined. | 2.383722 | 2.14289 | 1.112387 |
dtfactor = n.sum([1./i for i in d['dtarr']]) # assumes dedisperse-all algorithm
ntrials = d['readints'] * dtfactor * len(d['dmarr']) * d['npixx'] * d['npixy']
qfrac = 1 - (erf(d['sigma_image1']/n.sqrt(2)) + 1)/2.
nfalse = int(qfrac*ntrials)
return nfalse | def calc_nfalse(d) | Calculate the number of thermal-noise false positives per segment. | 11.628778 | 11.146863 | 1.043233 |
# this casts to int (flooring) to avoid 0.5 int rounding issue.
stopdts = n.linspace(d['nskip']+d['t_overlap']/d['inttime'], d['nints'], d['nsegments']+1)[1:] # nseg+1 assures that at least one seg made
startdts = n.concatenate( ([d['nskip']], stopdts[:-1]-d['t_overlap']/d['inttime']) )
... | def calc_segment_times(d) | Helper function for set_pipeline to define segmenttimes list, given nsegments definition | 4.069871 | 3.974352 | 1.024034 |
toGB = 8/1024.**3 # number of complex64s to GB
d0 = d.copy()
# limit defined for dm sweep time and max nchunk/nthread ratio
if limit:
d0['readints'] = d['t_overlap']/d['inttime']
d0['nchunk'] = max(d['dtarr'])/min(d['dtarr']) * d['nthread']
vismem = headroom * datasize(d0) ... | def calc_memory_footprint(d, headroom=4., visonly=False, limit=False) | Given pipeline state dict, this function calculates the memory required
to store visibilities and make images.
headroom scales visibility memory size from single data object to all copies (and potential file read needs)
limit=True returns a the minimum memory configuration
Returns tuple of (vismem, imme... | 7.932269 | 7.302537 | 1.086235 |
maxbl = d['uvres']*d['npix']/2 # fringe time for imaged data only
fringetime = 0.5*(24*3600)/(2*n.pi*maxbl/25.) # max fringe window in seconds
return fringetime | def calc_fringetime(d) | Estimate largest time span of a "segment".
A segment is the maximal time span that can be have a single bg fringe subtracted and uv grid definition.
Max fringe window estimated for 5% amp loss at first null averaged over all baselines. Assumes dec=+90, which is conservative.
Returns time in seconds that def... | 12.438943 | 10.080447 | 1.233967 |
data = numpyview(data_mem, 'complex64', datashape(d))
data_resamp = numpyview(data_resamp_mem, 'complex64', datashape(d))
bl0,bl1 = blrange
data_resamp[:, bl0:bl1] = data[:, bl0:bl1]
rtlib.dedisperse_resample(data_resamp, d['freq'], d['inttime'], d['dmarr'][dmind], d['dtarr'][dtind], blrange, ... | def correct_dmdt(d, dmind, dtind, blrange) | Dedisperses and resamples data *in place*.
Drops edges, since it assumes that data is read with overlapping chunks in time. | 5.061259 | 4.772439 | 1.060518 |
data = numpyview(data_mem, 'complex64', datashape(d))
data_resamp = numpyview(data_resamp_mem, 'complex64', datashape(d))
bl0,bl1 = blrange
data_resamp[:, bl0:bl1] = data[:, bl0:bl1]
rtlib.dedisperse_par(data_resamp, d['freq'], d['inttime'], dm, blrange, verbose=0) | def correct_dm(d, dm, blrange) | Dedisperses data into data_resamp
Drops edges, since it assumes that data is read with overlapping chunks in time. | 5.58589 | 4.694475 | 1.189886 |
data = numpyview(data_mem, 'complex64', datashape(d))
data_resamp = numpyview(data_resamp_mem, 'complex64', datashape(d))
bl0,bl1 = blrange
rtlib.resample_par(data_resamp, d['freq'], d['inttime'], dt, blrange, verbose=0) | def correct_dt(d, dt, blrange) | Resamples data_resamp
Drops edges, since it assumes that data is read with overlapping chunks in time. | 7.744878 | 6.747905 | 1.147746 |
if len(pix) == 0: # default is to get pixel from image
if minmax == 'max':
peakl, peakm = n.where(im == im.max())
elif minmax == 'min':
peakl, peakm = n.where(im == im.min())
peakl = peakl[0]; peakm = peakm[0]
elif len(pix) == 2: # can also specify
... | def calc_lm(d, im=[], pix=(), minmax='max') | Helper function to calculate location of image pixel in (l,m) coords.
Assumes peak pixel, but input can be provided in pixel units.
minmax defines whether to look for image maximum or minimum. | 2.720627 | 2.467694 | 1.102498 |
logger.info('Rephasing data to (l, m)=(%.4f, %.4f).' % (l1, m1))
data_resamp = numpyview(data_resamp_mem, 'complex64', datashape(d))
rtlib.phaseshift_threaded(data_resamp, d, l1, m1, u, v) | def move_phasecenter(d, l1, m1, u, v) | Handler function for phaseshift_threaded | 8.057575 | 6.829351 | 1.179845 |
# parameters
tsamp = d['inttime']*1e6 # in microsec
k = 8.3
freq = d['freq'].mean() # central (mean) frequency in GHz
bw = 1e3*(d['freq'][-1] - d['freq'][0])
ch = 1e3*(d['freq'][1] - d['freq'][0]) # channel width in MHz
# width functions and loss factor
dt0 = lambda dm: n.sqrt(... | def calc_dmgrid(d, maxloss=0.05, dt=3000., mindm=0., maxdm=0.) | Function to calculate the DM values for a given maximum sensitivity loss.
maxloss is sensitivity loss tolerated by dm bin width. dt is assumed pulse width in microsec. | 4.562429 | 4.434367 | 1.028879 |
data_resamp = numpyview(data_resamp_mem, 'complex64', datashape(d))
ims,snr,candints = rtlib.imgallfullfilterxy(n.outer(u, d['freq']/d['freq_orig'][0]), n.outer(v, d['freq']/d['freq_orig'][0]), data_resamp[i0:i1], d['npixx'], d['npixy'], d['uvres'], d['sigma_image1'])
feat = {}
for i in xrange(le... | def image2(d, i0, i1, u, v, w, dmind, dtind, beamnum) | Parallelizable function for imaging a chunk of data for a single dm.
Assumes data is dedispersed and resampled, so this just images each integration.
Two-stage imaging uses ideal uv coverage in second image.
returns dictionary with keys of cand location and values as tuple of features | 2.869556 | 2.779895 | 1.032254 |
data_resamp = numpyview(data_resamp_mem, 'complex64', datashape(d))
image = rtlib.imgonefullxy(n.outer(u, d['freq']/d['freq_orig'][0]), n.outer(v, d['freq']/d['freq_orig'][0]), data_resamp[candint], npixx, npixy, d['uvres'], verbose=1)
return image | def image1wrap(d, u, v, w, npixx, npixy, candint) | Parallelizable function for imaging a chunk of data for a single dm.
Assumes data is dedispersed and resampled, so this just images each integration.
Simple one-stage imaging that returns dict of params.
returns dictionary with keys of cand location and values as tuple of features | 9.54401 | 9.302059 | 1.02601 |
import sdmpy
sdm = sdmpy.SDM(sdmfile)
ants = {ant.stationId:ant.name for ant in sdm['Antenna']}
stations = {st.stationId: st.name for st in sdm['Station'] if 'X' not in str(st.name)}
west = [int(str(ants[st]).lstrip('ea')) for st in stations if 'W' in str(stations[st])]
east = [int(str(ant... | def imagearm(sdmfile, scan, segment, npix=512, res=50, **kwargs) | Function to do end-to-end 1d, arm-based imaging | 2.631164 | 2.638386 | 0.997263 |
if i == -1:
i = len(data)/2
if imager == 'xy':
image = rtlib.imgonefullxy(n.outer(u, d['freq']/d['freq_orig'][0]), n.outer(v, d['freq']/d['freq_orig'][0]), data[i], d['npixx'], d['npixy'], d['uvres'], verbose=verbose)
elif imager == 'w':
npix = max(d['npixx'], d['npixy'])
... | def sample_image(d, data, u, v, w, i=-1, verbose=0, imager='xy', wres=100) | Samples one integration and returns image
i is integration to image. Default is mid int. | 2.746492 | 2.722982 | 1.008634 |
# define noise per baseline for data seen by detect_bispectra or image
datamean = data.mean(axis=2).imag # use imaginary part to estimate noise without calibrated, on-axis signal
(datameanmin, datameanmax) = rtlib.sigma_clip(datamean.flatten())
good = n.where( (datamean>da... | def estimate_noiseperbl(data) | Takes large data array and sigma clips it to find noise per bl for input to detect_bispectra.
Takes mean across pols and channels for now, as in detect_bispectra. | 6.168091 | 5.507536 | 1.119937 |
if d['savenoise']:
noisefile = getnoisefile(d)
if os.path.exists(noisefile):
logger.warn('noisefile %s already exists' % noisefile)
else:
nints = len(data)
chunk = min(chunk, nints) # ensure at least one measurement
results = []
... | def noisepickle(d, data, u, v, w, chunk=200) | Calculates noise properties and saves values to pickle.
chunk defines window for measurement. at least one measurement always made. | 3.898277 | 3.738573 | 1.042718 |
with open(getcandsfile(d, domock=domock), 'w') as pkl:
pickle.dump(d, pkl)
pickle.dump(cands, pkl) | def savecands(d, cands, domock=False) | Save all candidates in pkl file for later aggregation and filtering.
domock is option to save simulated cands file | 3.961157 | 4.091128 | 0.968231 |
if raw:
return n.frombuffer(arr, dtype=n.dtype(datatype)).view(n.dtype(datatype)).reshape(shape) # for shared mps.RawArray
else:
return n.frombuffer(arr.get_obj(), dtype=n.dtype(datatype)).view(n.dtype(datatype)).reshape(shape) | def numpyview(arr, datatype, shape, raw=False) | Takes mp shared array and returns numpy array with given shape. | 3.668144 | 3.326369 | 1.102747 |
parent, child = os.path.split(self)
return self.__class__(parent), child | def splitpath(self) | p.splitpath() -> Return (p.parent, p.name). | 5.818298 | 3.350867 | 1.736356 |
drive, rel = os.path.splitdrive(self)
return self.__class__(drive), rel | def splitdrive(self) | p.splitdrive() -> Return (p.drive, <the rest of p>).
Split the drive specifier from this path. If there is
no drive specifier, p.drive is empty, so the return value
is simply (path(''), p). This is always the case on Unix. | 6.132835 | 6.156727 | 0.996119 |
filename, ext = os.path.splitext(self)
return self.__class__(filename), ext | def splitext(self) | p.splitext() -> Return (p.stripext(), p.ext).
Split the filename extension from this path and return
the two parts. Either part may be empty.
The extension is everything from '.' to the end of the
last path segment. This has the property that if
(a, b) == p.splitext(), then a... | 5.034375 | 8.273111 | 0.608523 |
return self.__class__(os.path.join(self, *args)) | def joinpath(self, *args) | Join two or more path components, adding a separator
character (os.sep) if needed. Returns a new path
object. | 4.182408 | 4.496073 | 0.930236 |
cwd = self.__class__(os.getcwd())
return cwd.relpathto(self) | def relpath(self) | Return this path as a relative path,
based from the current working directory. | 6.871452 | 6.536568 | 1.051232 |
origin = self.abspath()
dest = self.__class__(dest).abspath()
orig_list = origin.normcase().splitall()
# Don't normcase dest! We want to preserve the case.
dest_list = dest.splitall()
if orig_list[0] != os.path.normcase(dest_list[0]):
# Can't get h... | def relpathto(self, dest) | Return a relative path from self to dest.
If there is no relative path from self to dest, for example if
they reside on different drives in Windows, then this returns
dest.abspath(). | 3.820266 | 3.663659 | 1.042746 |
names = os.listdir(self)
if pattern is not None:
names = fnmatch.filter(names, pattern)
return [self / child for child in names] | def listdir(self, pattern=None) | D.listdir() -> List of items in this directory.
Use D.files() or D.dirs() instead if you want a listing
of just files or just subdirectories.
The elements of the list are path objects.
With the optional 'pattern' argument, this only lists
items whose names match the given patt... | 3.220393 | 4.388578 | 0.733812 |
if errors not in ('strict', 'warn', 'ignore'):
raise ValueError("invalid errors parameter")
try:
childList = self.listdir()
except Exception:
if errors == 'ignore':
return
elif errors == 'warn':
warnings.wa... | def walk(self, pattern=None, errors='strict') | D.walk() -> iterator over files and subdirs, recursively.
The iterator yields path objects naming each child item of
this directory and its descendants. This requires that
D.isdir().
This performs a depth-first traversal of the directory tree.
Each directory is returned just b... | 2.190369 | 2.208791 | 0.991659 |
cls = self.__class__
return [cls(s) for s in glob.glob(_base(self / pattern))] | def glob(self, pattern) | Return a list of path objects that match the pattern.
pattern - a path relative to this directory, with wildcards.
For example, ``path('/users').glob('*/bin/*')`` returns a list
of all the files users have in their bin directories. | 10.2303 | 11.706975 | 0.873864 |
def _write_bytes(bytes, append):
if append:
mode = 'ab'
else:
mode = 'wb'
f = self.open(mode)
try:
f.write(bytes)
finally:
f.close()
dry("write_bytes %s '%r...' append=%r... | def write_bytes(self, bytes, append=False) | Open this file and write the given bytes to it.
Default behavior is to overwrite any existing file.
Call p.write_bytes(bytes, append=True) to append instead. | 3.778511 | 3.661456 | 1.03197 |
r
if encoding is None:
# 8-bit
f = self.open(_textmode)
try:
return f.read()
finally:
f.close()
else:
# Unicode
f = codecs.open(self, 'r', encoding, errors)
# (Note - Can't use 'U'... | def text(self, encoding=None, errors='strict') | r""" Open this file, read it in, return the content as a string.
This uses 'U' mode in Python 2.3 and later, so '\r\n' and '\r'
are automatically translated to '\n'.
Optional arguments:
encoding - The Unicode encoding (or character set) of
the file. If present, the conten... | 3.133482 | 2.903203 | 1.079319 |
r
if isinstance(text, unicode):
if linesep is not None:
# Convert all standard end-of-line sequences to
# ordinary newline characters.
text = (text.replace(u'\r\n', u'\n')
.replace(u'\r\x85', u'\n')
... | def write_text(self, text, encoding=None, errors='strict', linesep=os.linesep, append=False) | r""" Write the given text to this file.
The default behavior is to overwrite any existing file;
to append instead, use the 'append=True' keyword argument.
There are two differences between path.write_text() and
path.write_bytes(): newline handling and Unicode handling.
See belo... | 2.786707 | 2.440608 | 1.141808 |
r
if append:
mode = 'ab'
else:
mode = 'wb'
f = self.open(mode)
try:
for line in lines:
isUnicode = isinstance(line, unicode)
if linesep is not None:
# Strip off any existing line-end and add t... | def write_lines(self, lines, encoding=None, errors='strict',
linesep=os.linesep, append=False) | r""" Write the given lines of text to this file.
By default this overwrites any existing file at this path.
This puts a platform-specific newline sequence on every line.
See 'linesep' below.
lines - A list of strings.
encoding - A Unicode encoding to use. This applies only i... | 2.472886 | 2.339602 | 1.056969 |
f = self.open('rb')
try:
m = hashlib.md5()
while True:
d = f.read(8192)
if not d:
break
m.update(d)
finally:
f.close()
if hex:
return m.hexdigest()
else:
... | def read_md5(self, hex=False) | Calculate the md5 hash for this file.
hex - Return the digest as hex string.
This reads through the entire file. | 1.772794 | 1.796717 | 0.986685 |
r
if os.name == 'nt':
if win32security is None:
raise Exception("path.owner requires win32all to be installed")
desc = win32security.GetFileSecurity(
self, win32security.OWNER_SECURITY_INFORMATION)
sid = desc.GetSecurityDescriptorOwner(... | def owner(self) | r""" Return the name of the owner of this file or directory.
This follows symbolic links.
On Windows, this returns a name of the form ur'DOMAIN\User Name'.
On Windows, a group can own a file or directory. | 3.584121 | 3.508872 | 1.021445 |
if not self.exists() or not self.isdir():
os.makedirs(self, mode) | def ensure_dir(self, mode=0777) | Make sure the directory exists, create if necessary. | 4.280164 | 4.075312 | 1.050267 |
self.copy(to)
path(to).chmod(chmod) | def install(self, to, chmod=0644) | Copy data and set mode to 'chmod'. | 12.161812 | 8.360568 | 1.454663 |
with open(paramfile, 'r') as f:
for line in f.readlines():
line_clean = line.rstrip('\n').split('#')[0] # trim out comments and trailing cr
if line_clean and '=' in line: # use valid lines only
attribute, value = line_clean.split('=')... | def parse(self, paramfile) | Read parameter file and set parameter values.
File should have python-like syntax. Full file name needed. | 3.660879 | 3.560904 | 1.028076 |
try:
data = Persistence.read(self.path, create_file=True)
except ValueError:
data = {}
return self.load_data(data, indexables) | def load(self, indexables) | Load the index file and reorder the banks based in order listed in index
:param list[Indexable] indexables: Banks that will be reordered based in index file
:return list[Bank]: Banks reordered | 6.620895 | 8.540593 | 0.775227 |
uow, is_duplicate = self.insert_and_publish_uow(job_record, 0, 0)
try:
target_state = self._compute_next_job_state(job_record)
self.update_job(job_record, uow, target_state)
except ValueError:
# do no processing for the future timeperiods
... | def _process_state_embryo(self, job_record) | method that takes care of processing job records in STATE_EMBRYO state | 7.830223 | 7.346295 | 1.065874 |
def _process_state(target_state, uow):
if uow.is_active:
# Large Job processing takes more than 1 tick of the Scheduler
# Let the Job processing complete - do no updates to Scheduler records
pass
elif uow.is_finished:
... | def _process_state_in_progress(self, job_record) | method that takes care of processing job records in STATE_IN_PROGRESS state | 7.676937 | 7.412287 | 1.035704 |
self.observer_manager.append(observer)
observer.manager = self | def register(self, observer) | Register an observer for it be notified when occurs changes.
For more details, see :class:`.UpdatesObserver`
:param UpdatesObserver observer: Observer that will be notified then occurs changes | 11.428253 | 17.80279 | 0.641936 |
self.observer_manager.observers.remove(observer)
observer.manager = None | def unregister(self, observer) | Remove the observers of the observers list.
It will not receive any more notifications when occurs changes.
:param UpdatesObserver observer: Observer you will not receive any more notifications then
occurs changes. | 9.0533 | 12.330392 | 0.734226 |
if uow.is_active:
# Large Job processing takes more than 1 tick of Scheduler
# Let the Large Job processing complete - do no updates to Scheduler records
pass
elif uow.is_finished:
# create new uow to cover new inserts
uow, is_duplicat... | def __process_non_finalizable_job(self, job_record, uow) | method handles given job_record based on the unit_of_work status
Assumption: job_record is in STATE_IN_PROGRESS and is not yet finalizable | 12.698119 | 11.198674 | 1.133895 |
uow, is_duplicate = self.insert_and_publish_uow(job_record, 0, 0)
self.update_job(job_record, uow, job.STATE_IN_PROGRESS) | def _process_state_embryo(self, job_record) | method that takes care of processing job records in STATE_EMBRYO state | 8.453515 | 7.599679 | 1.112352 |
time_qualifier = context.process_context[job_record.process_name].time_qualifier
actual_timeperiod = time_helper.actual_timeperiod(time_qualifier)
is_job_finalizable = self.timetable.is_job_record_finalizable(job_record)
uow = self.uow_dao.get_one(job_record.related_unit_of_work... | def _process_state_in_progress(self, job_record) | method that takes care of processing job records in STATE_IN_PROGRESS state | 3.618662 | 3.504616 | 1.032542 |
if append_to_console is None:
append_to_console = settings.settings['under_test']
if redirect_stdstream is None:
redirect_stdstream=not settings.settings['under_test']
if process_name not in logger_pool:
file_name = get_log_filename(process_name)
log_tag = get_log_tag(p... | def get_logger(process_name, append_to_console=None, redirect_stdstream=None) | method returns initiated logger | 2.265971 | 2.244182 | 1.009709 |
process_obj = context.process_context[process_name]
if isinstance(process_obj, FreerunProcessEntry):
return str(process_obj.token)
elif isinstance(process_obj, ManagedProcessEntry):
return str(process_obj.token) + str(process_obj.time_qualifier)
elif isinstance(process_obj, DaemonPr... | def get_log_tag(process_name) | method returns tag that all messages will be preceded with | 3.257512 | 3.266898 | 0.997127 |
if msg is not None and len(msg.strip()) > 0:
self.logger.log(level, msg) | def write(self, msg, level=logging.INFO) | method implements stream write interface, allowing to redirect stdout to logger | 2.950303 | 2.836832 | 1.039999 |
'''Counts all k-mers in sequence.'''
for kmer in iter_kmers(seq, self.k, canonical=self.canonical):
self._incr(kmer) | def consume(self, seq) | Counts all k-mers in sequence. | 7.674078 | 5.660128 | 1.355814 |
with screed.open(filename) as sequences:
for seq in sequences:
self.consume(seq['sequence']) | def consume_file(self, filename) | Counts all kmers in all sequences in a FASTA/FASTQ file. | 6.313719 | 4.586135 | 1.376697 |
'''Subtracts all k-mers in sequence.'''
for kmer in iter_kmers(seq, self.k, canonical=self.canonical):
self._decr(kmer) | def unconsume(self, seq) | Subtracts all k-mers in sequence. | 8.996123 | 5.462464 | 1.646898 |
supported_plugins = self._supported_plugins
for plugin in metadata:
if not ignore_unsupported_plugins \
or plugin['uri'] in supported_plugins:
self._plugins[plugin['uri']] = Lv2Plugin(plugin) | def reload(self, metadata, ignore_unsupported_plugins=True) | Loads the metadata. They will be used so that it is possible to generate lv2 audio plugins.
:param list metadata: lv2 audio plugins metadata
:param bool ignore_unsupported_plugins: Not allows instantiation of uninstalled or unrecognized audio plugins? | 5.424615 | 4.634498 | 1.170486 |
try:
plugin = self._plugins[lv2_uri]
except KeyError:
raise Lv2EffectBuilderError(
"Lv2EffectBuilder not contains metadata information about the plugin '{}'. \n"
"Try re-scan the installed plugins using the reload method::\n"
... | def build(self, lv2_uri) | Returns a new :class:`.Lv2Effect` by the valid lv2_uri
:param string lv2_uri:
:return Lv2Effect: Effect created | 7.304833 | 6.651089 | 1.098291 |
try:
self.logger.info('JobStatusListener {')
mq_request = MqTransmission.from_json(message.body)
job_record = self.job_dao.get_by_id(mq_request.process_name, mq_request.record_db_id)
# step 1: identify dependant tree nodes
tree_obj = self.ti... | def _mq_callback(self, message) | method receives a message from Synergy Scheduler notifying of Job completion,
builds up a list of dependant TreeNodes/Jobs and triggers their ManagedThreadHandlers, if applicable
:param message: <MqTransmission> mq message | 3.890518 | 3.334866 | 1.166619 |
if hostname is None:
hostname = settings.settings['mx_host']
if port is None:
port = settings.settings['mx_port']
reloader = False # use_reloader: the default setting for the reloader.
debugger = False #
evalex = True # sh... | def start(self, hostname=None, port=None) | Spawns a new HTTP server, residing on defined hostname and port
:param hostname: the default hostname the server should listen on.
:param port: the default port of the server. | 3.35161 | 3.241167 | 1.034075 |
self.check_insertion(item)
self.real_list.append(item)
self._items |= {item} | def append(self, item) | See :meth:`~pluginsmanager.observer.observable_list.ObservableList.append()` method | 10.258669 | 9.162725 | 1.119609 |
self.real_list.remove(item)
self._items.remove(item) | def remove(self, item) | See :meth:`~pluginsmanager.observer.observable_list.ObservableList.remove()` method | 7.374556 | 5.649518 | 1.305343 |
self.check_insertion(x)
self.real_list.insert(index, x)
self._items |= {x} | def insert(self, index, x) | See :meth:`~pluginsmanager.observer.observable_list.ObservableList.insert()` method | 9.222614 | 7.652339 | 1.205202 |
if index is None:
index = len(self.real_list) - 1
effect = self[index]
returned = self.real_list.pop(index)
self._items.remove(effect)
return returned | def pop(self, index=None) | See :meth:`~pluginsmanager.observer.observable_list.ObservableList.pop()` method | 5.198594 | 4.666078 | 1.114125 |
if ((self.season == "") and (self.episode == "")):
regexp = '^%s.*' % self.title.lower()
elif (self.episode == ""):
regexp = '^%s.*(s[0]*%s|season[\s\_\-\.]*%s).*' % (self.title.lower(), self.season, self.season)
else:
regexp = '^%s.*((s[0]*%s.*e[0]*%... | def search_regexp(self) | Define the regexp used for the search | 3.222172 | 3.067649 | 1.050372 |
try:
s = self.source.search(self.title.lower(), limit)
except Exception as e:
logging.error("Can not send search request to the t411 server")
logging.error(e.message)
sys.exit(1)
try:
for t in s.items():
... | def buildlist(self, category=tpb.CATEGORIES.VIDEO.TV_SHOWS, limit=1000) | Build the torrent list
Return list of list sorted by seeders count
Id can be used to retrieve torrent associate with this id
[[<title>, <Seeders>, <id>] ...] | 4.261502 | 3.950954 | 1.078601 |
if ((self.season == "") and (self.episode == "")):
# Find serie
try:
print("%s has %s seasons (the serie is %s)" % (self.tvdb.data['seriesname'], self.tvdb.get_season_number(), self.tvdb.data['status'].lower()))
# print self.tvdb.data
... | def search_regexp(self) | Define the regexp used for the search | 2.792902 | 2.74607 | 1.017054 |
try:
s = self.source.search(self.title.lower(), category=category)
except:
logging.error("Can not send search request to the Piracy Bay")
self.__tpb_error_()
sys.exit(1)
logging.info("Search %s in the category %s..." % (self.title.lower(... | def buildlist(self, category=tpb.CATEGORIES.VIDEO.TV_SHOWS) | Build the torrent list
Return list of list sorted by Seeders
[[<title>, <Seeders>, <MagnetURL>, <TorrentURL] ...] | 3.760784 | 3.387903 | 1.110062 |
'''
Helper function for ``GenomeIntervalTree.from_bed and ``.from_table``.
Data tables may contain intervals with begin >= end. Such intervals lead to infinite recursions and
other unpleasant behaviour, so something has to be done about them. We 'fix' them by simply setting end = begin+1.
'''
i... | def _fix(interval) | Helper function for ``GenomeIntervalTree.from_bed and ``.from_table``.
Data tables may contain intervals with begin >= end. Such intervals lead to infinite recursions and
other unpleasant behaviour, so something has to be done about them. We 'fix' them by simply setting end = begin+1. | 11.8923 | 2.807557 | 4.235818 |
_ROUTING_PREFIX = 'routing_'
_QUEUE_PREFIX = 'queue_'
if arguments is not None:
assert isinstance(arguments, dict)
process_entry = ManagedProcessEntry(
process_name=process_name,
trigger_frequency=trigger_frequency,
state_machine_name=state_machine_name,
is... | def managed_context_entry(process_name,
classname,
token,
time_qualifier,
trigger_frequency='every 60',
state_machine_name=STATE_MACHINE_DISCRETE,
is_on=True,
... | forms process context entry | 1.823401 | 1.822747 | 1.000359 |
@wraps(func)
def wrapper(self, key, *args, **kwargs):
if posixpath.sep in key:
raise ValueError('Keys cannot contains slashes')
return func(self, key, *args, **kwargs)
return wrapper | def validate_key(func) | Decorator to validate a key for zookeeper. | 3.307849 | 2.895215 | 1.142523 |
encoded = self.encoding.encode(value)
self.__set_or_create(key, encoded)
self.__increment_last_updated() | def persist(self, key, value) | Encode and save ``value`` at ``key``.
:param key: Key to store ``value`` at in Zookeeper.
:type key: string
:param value: Value to store. Encoded before being stored.
:type value: value | 7.324325 | 9.61554 | 0.761718 |
self.connection.retry(self.connection.delete, self.__path_of(key))
self.__increment_last_updated() | def depersist(self, key) | Remove ``key`` from dictionary.
:param key: Key to remove from Zookeeper.
:type key: string | 13.61147 | 13.196486 | 1.031447 |
results = dict()
for child in self.connection.retry(self.connection.get_children, self.keyspace):
value, _ = self.connection.retry(
self.connection.get,
self.__path_of(child),
watch=self.__increment_last_updated
)
... | def durables(self) | Dictionary of all keys and their values in Zookeeper. | 6.924853 | 4.770813 | 1.451504 |
path = self.__path_of(key)
value = None
try:
# We need to both delete and return the value that was in ZK here.
raw_value, _ = self.connection.retry(self.connection.get, path)
value = self.encoding.decode(raw_value)
except self.no_node_error:... | def _pop(self, key, default=None) | If ``key`` is present in Zookeeper, removes it from Zookeeper and
returns the value. If key is not in Zookeper and ``default`` argument
is provided, ``default`` is returned. If ``default`` argument is not
provided, ``KeyError`` is raised.
:param key: Key to remove from Zookeeper
... | 5.580544 | 5.435929 | 1.026604 |
return self.connection.retry(self.__inner_set_default, key, default) | def _setdefault(self, key, default=None) | If ``key`` is not present, set it as ``default`` and return it. If
``key`` is present, return its value.
:param key: Key to add to Zookeeper
:type key: string
:param default: Default object to return if ``key`` is present.
:type default: object
Will retry trying to get... | 16.258421 | 14.339684 | 1.133806 |
path = self.__path_of(key)
try:
# Try to get and return the existing node with its data
value, _ = self.connection.retry(self.connection.get, path)
return self.encoding.decode(value)
except self.no_node_error:
# Node does not exist, we ha... | def __inner_set_default(self, key, value) | Tries to return the value at key. If the key does not exist, attempts
to create it with the value. If the node is created in the mean time,
a ``NodeExistsError`` will be raised. | 4.659507 | 4.294444 | 1.085008 |
'''
Prints a table of k-mer counts
Parameters
----------
sparse: bool
Print only observed kmers
file: IO object
Print to `file`
sep: str
Separate k-mers and their counts with `sep`
'''
for kmer, count in sorted... | def print_table(self, sparse=False, file=None, sep='\t') | Prints a table of k-mer counts
Parameters
----------
sparse: bool
Print only observed kmers
file: IO object
Print to `file`
sep: str
Separate k-mers and their counts with `sep` | 4.230737 | 1.82382 | 2.319711 |
if tree in self.dependent_on:
self.dependent_on.remove(tree) | def unregister_dependent_on(self, tree) | unregistering tree that we are dependent on | 2.948209 | 2.36305 | 1.247629 |
grandparent = parent.parent
if grandparent is None:
# here, we work at yearly/linear level
return None
parent_siblings = list(grandparent.children)
sorted_keys = sorted(parent_siblings)
index = sorted_keys.index(parent.timeperiod)
if inde... | def _get_next_parent_node(self, parent) | Used by _get_next_child_node, this method is called to find next possible parent.
For example if timeperiod 2011010200 has all children processed, but is not yet processed itself
then it makes sense to look in 2011010300 for hourly nodes | 4.872521 | 4.515471 | 1.079073 |
children_keys = list(parent.children)
sorted_keys = sorted(children_keys)
for key in sorted_keys:
node = parent.children[key]
if node.job_record is None:
self.timetable.assign_job_record(node)
return node
elif self.shou... | def _get_next_child_node(self, parent) | Iterates among children of the given parent and looks for a suitable node to process
In case given parent has no suitable nodes, a younger parent will be found
and the logic will be repeated for him | 4.540152 | 4.207541 | 1.079051 |
hierarchy_entry = self.process_hierarchy.get_by_qualifier(time_qualifier)
if hierarchy_entry.parent:
parent_time_qualifier = hierarchy_entry.parent.process_entry.time_qualifier
parent_timeperiod = hierarchy_entry.parent.cast_timeperiod(timeperiod)
parent = se... | def _get_node(self, time_qualifier, timeperiod) | Method retrieves a tree node identified by time_qualifier and timeperiod
In case intermittent or target nodes does not exist - method will request their creation
:param time_qualifier: identifies the tree level
:param timeperiod: identifies the target node timeperiod
:return: requested n... | 2.57044 | 2.683743 | 0.957782 |
hierarchy_entry = self.process_hierarchy.get_by_qualifier(time_qualifier)
if hierarchy_entry.parent:
parent_time_qualifier = hierarchy_entry.parent.process_entry.time_qualifier
parent = self._get_next_node(parent_time_qualifier)
else:
parent = self.ro... | def _get_next_node(self, time_qualifier) | Method goes to the top of the tree and traverses from
there in search of the next suitable node for processing
to the level defined by the given time_qualifier
:param time_qualifier: defines target level of the tree
:return: located node; type <TreeNode> | 3.068906 | 3.300454 | 0.929844 |
# case 1: node processing is complete
if node.job_record.is_finished:
return True
# case 2: this is a bottom-level leaf node. retry this node for MAX_NUMBER_OF_FAILURES
if node.process_name == self.process_hierarchy.bottom_process.process_name:
if len(no... | def should_skip_tree_node(self, node) | :return True: in case the node should be _skipped_ and not included into processing | 5.979671 | 5.831207 | 1.02546 |
time_qualifier = self.process_hierarchy.bottom_process.time_qualifier
process_name = self.process_hierarchy.bottom_process.process_name
if rebuild or self.build_timeperiod is None:
timeperiod = settings.settings['synergy_start_timeperiod']
else:
timeperi... | def build_tree(self, rebuild=False) | method builds tree by iterating from the synergy_start_timeperiod to the current time
and inserting corresponding nodes | 3.957779 | 3.333914 | 1.187127 |
if process_name not in self.process_hierarchy:
raise ValueError('unable to compute the next_node due to unknown process: {0}'.format(process_name))
time_qualifier = self.process_hierarchy[process_name].process_entry.time_qualifier
return self._get_next_node(time_qualifier) | def get_next_node(self, process_name) | :return: <AbstractTreeNode> next node to process by a process with process_name | 4.629138 | 4.270133 | 1.084073 |
if job_record.process_name not in self.process_hierarchy:
raise ValueError('unable to update the node due to unknown process: {0}'.format(job_record.process_name))
time_qualifier = self.process_hierarchy[job_record.process_name].process_entry.time_qualifier
node = self._get... | def update_node(self, job_record) | Updates job record property for a tree node associated with the given Job | 4.008272 | 3.851669 | 1.040658 |
if process_name not in self.process_hierarchy:
raise ValueError('unable to retrieve the node due to unknown process: {0}'.format(process_name))
time_qualifier = self.process_hierarchy[process_name].process_entry.time_qualifier
return self._get_node(time_qualifier, timeperio... | def get_node(self, process_name, timeperiod) | Method retrieves a tree node identified by the time_qualifier and the timeperiod | 4.206474 | 3.337382 | 1.260411 |
for timeperiod, child in self.root.children.items():
child.validate()
self.validation_timestamp = datetime.utcnow() | def validate(self) | method starts validation of the tree.
@see TreeNode.validate | 10.119952 | 11.025895 | 0.917835 |
klass = error_classes.get(response.status)
if klass is None:
if 400 <= response.status < 500:
klass = ClientError
if 500 <= response.status < 600:
klass = ServerError # pragma: no cover
return klass(response) | def error_for(response) | Return the appropriate initialized exception class for a response. | 2.446957 | 2.160615 | 1.132528 |
"Worker thread for data reading"
try:
while True:
written = in_sock.recv(32768)
if not written:
try:
out_sock.shutdown(socket.SHUT_WR)
except socket.error:
self.threads[onk... | def piper(self, in_sock, out_sock, out_addr, onkill) | Worker thread for data reading | 4.14943 | 3.646876 | 1.137804 |
_ROUTING_PREFIX = 'routing_'
_QUEUE_PREFIX = 'queue_'
_SUFFIX = '_daemon'
if arguments is not None:
assert isinstance(arguments, dict)
process_entry = DaemonProcessEntry(
process_name=process_name,
classname=classname,
token=token,
mq_queue=queue if que... | def daemon_context_entry(process_name,
classname,
token,
exchange=EXCHANGE_UTILS,
present_on_boxes=None,
arguments=None,
queue=None,
routing=None... | forms process context entry | 2.003308 | 2.004671 | 0.99932 |
assert enclosed_processes is not None and not isinstance(enclosed_processes, string_types)
assert dependent_on is not None and not isinstance(dependent_on, string_types)
timetable_entry = TimetableTreeEntry(tree_name=tree_name,
enclosed_processes=enclosed_proce... | def timetable_tree_entry(tree_name,
enclosed_processes,
dependent_on=None,
mx_name=None,
mx_page=None) | creates timetable context entry | 1.788539 | 1.798246 | 0.994602 |
device_configs = self.device_configurations(use_included=use_included)
for device_config in device_configs:
if device_config.is_loaded() is not pending:
return device_config
return None | def device_configuration(self, pending=False, use_included=False) | Get a specific device configuration.
A device can have at most one loaded and one pending device
configuration. This returns that device_configuration based on
a given flag.
Keyword Args:
pending(bool): Fetch the pending configuration or return
the loaded o... | 3.182191 | 3.671707 | 0.866679 |
if sys.platform == 'win32':
python = path.join(VE_ROOT, 'Scripts', 'python.exe')
else:
python = path.join(VE_ROOT, 'bin', 'python')
return python | def get_python() | Determine the path to the virtualenv python | 2.608548 | 2.227479 | 1.171076 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.