rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
st += self.getWaveform(network_id=network_id, station_id=station_id, location_id=location_id, channel_id=cha, start_datetime=start_datetime, end_datetime=end_datetime)
if 'channel_id' in kwargs: kwargs.pop('channel_id') st += self.getWaveform(channel_id=cha, **kwargs)
def getWaveform(self, network_id, station_id, location_id, channel_id, start_datetime, end_datetime): """ Get Waveform in an ObsPy stream object from Fissures / DHI.
def getPAZ(self, network_id="GR", station_id="GRA1"):
def getPAZ(self, network_id="GR", station_id="GRA1", datetime="2010-08-01"):
def getPAZ(self, network_id="GR", station_id="GRA1"): """ EXPERIMENTAL! Units and scalings not yet correct! see: http://www.seis.sc.edu/software/simple/ http://www.seis.sc.edu/downloads/simple/simple-1.0.tar.gz http://www.seis.sc.edu/viewvc/seis/branches/IDL2.0/fissuresUtil/src/edu/sc/seis/fissuresUtil2/sac/SacPoleZer...
def _getSuites(verbosity=1, tests=[]):
def _getSuites(verbosity=1, names=[]):
def _getSuites(verbosity=1, tests=[]): """ The obspy test suite. """ if tests == []: names = DEFAULT_MODULES else: names = [] # Search for short cuts in tests, if there are no short cuts, # names variables is equal to tests variable for test in tests: if test in ALL_MODULES: names.append(test) # Construct the test suit...
if tests == []:
if names == []:
def _getSuites(verbosity=1, tests=[]): """ The obspy test suite. """ if tests == []: names = DEFAULT_MODULES else: names = [] # Search for short cuts in tests, if there are no short cuts, # names variables is equal to tests variable for test in tests: if test in ALL_MODULES: names.append(test) # Construct the test suit...
else: names = [] for test in tests: if test in ALL_MODULES: names.append(test)
def _getSuites(verbosity=1, tests=[]): """ The obspy test suite. """ if tests == []: names = DEFAULT_MODULES else: names = [] # Search for short cuts in tests, if there are no short cuts, # names variables is equal to tests variable for test in tests: if test in ALL_MODULES: names.append(test) # Construct the test suit...
module = 'obspy.%s.tests.suite' % name
def _getSuites(verbosity=1, tests=[]): """ The obspy test suite. """ if tests == []: names = DEFAULT_MODULES else: names = [] # Search for short cuts in tests, if there are no short cuts, # names variables is equal to tests variable for test in tests: if test in ALL_MODULES: names.append(test) # Construct the test suit...
try: suite.append(ut.loadTestsFromName(module, None))
if name in ALL_MODULES: test = 'obspy.%s.tests.suite' % name else: test = name try: suite.append(ut.loadTestsFromName(test, None))
def _getSuites(verbosity=1, tests=[]): """ The obspy test suite. """ if tests == []: names = DEFAULT_MODULES else: names = [] # Search for short cuts in tests, if there are no short cuts, # names variables is equal to tests variable for test in tests: if test in ALL_MODULES: names.append(test) # Construct the test suit...
QtGui.QMainWindow.__init__(self)
QtGui.QWidget.__init__(self)
def __init__(self, options): # make all commandline options available for later use # e.g. in update() methods self.options = options # for convenience set some instance wide attributes self.low = options.low self.high = options.high self.zerophase = options.zerophase
main = QtGui.QWidget(self) main.setGeometry(100, 100, 300, 300) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(main.sizePolicy().hasHeightForWidth()) main.setSizePolicy(sizePolicy)
self.setGeometry(300, 300, 500, 500)
def __setup_GUI(self): """ Add matplotlib canvas, some buttons and stuff... """ self.setWindowTitle("Title of main window...")
hlayout = QtGui.QVBoxLayout(main)
hlayout = QtGui.QVBoxLayout() hlayout.addStretch(1) self.setLayout(hlayout)
def __setup_GUI(self): """ Add matplotlib canvas, some buttons and stuff... """ self.setWindowTitle("Title of main window...")
myMainWindow = MyMainWindow(options)
myWidget = MyWidget(options)
def main(): """ Gets executed when the program starts. """ usage = "Usage information goes here..." parser = optparse.OptionParser(usage) parser.add_option("-l", "--low", type=float, dest="low", default=1.0, help="Lowpass frequency") parser.add_option("--high", type=float, dest="high", default=20.0, help="Highpass freq...
return
pass return
def iterate(self): """ Handles exactly one directory. """ # skip if service is not running # be aware that the processor pool is still active waiting for work if not self.running: return # skip if input queue is full if len(self.input_queue) > self.options.number_of_cpus: return # try to finalize a single processed str...
geometry[:,0] -= geometry[:,0].mean() geometry[:,1] -= geometry[:,1].mean() geometry[:,2] -= geometry[:,2].mean()
geometry[:,0] -= geometry[:-1,0].mean() geometry[:,1] -= geometry[:-1,1].mean() geometry[:,2] -= geometry[:-1,2].mean()
def get_geometry(stream, coordsys='lonlat', verbose=False): """ Method to calculate the array geometry and the center coordinates in km :param stream: Stream object, the trace.stats dict like class must contain a obspy.core.util.attribdict with 'latitude', 'longitude' (in degrees) and 'elevation' (in km), or 'x', 'y',...
temp[0].data = np.require(temp[0].data, 'float32')
def loadGaps(self, frames, network, station, location, channel): """ Returns a stream object that will contain all time spans from the provided list. """ streams = [] for frame in frames: temp = self.env.seishub.getPreview(network, station, location, channel, UTCDateTime(frame[0]), UTCDateTime(frame[1])) # XXX: Not nec...
"removed in the future. Please specify all options as kwargs."
"removed in the future. Please specify all options as " + \ "kwargs."
def new_func(*args, **kwargs): # function itself is first arg so len(args) == 3 means we got 2 args... if len(args) == 3 and isinstance(args[2], dict): msg = "Using a dictionary to pass on filter options will be " + \ "removed in the future. Please specify all options as kwargs." warnings.warn(msg, DeprecationWarning) ...
out = Trace(header=deepcopy(lt.stats))
out = self.__class__(header=deepcopy(lt.stats))
def __add__(self, trace, method=0, interpolation_samples=0, fill_value=None, sanity_checks=True): """ Adds another Trace object to current trace.
print seisSim.__doc__
print signal.seisSim.__doc__
def simulate(self, paz_remove=None, paz_simulate=None, remove_sensitivity=True, simulate_sensitivity=True, **kwargs): """ Correct for instrument response / Simulate new instrument response.
if timestap == 'julsec':
if timestamp == 'julsec':
def sonic(stream, win_len, win_frac, sll_x, slm_x, sll_y, slm_y, sl_s, semb_thres, vel_thres, frqlow, frqhigh, stime, etime, prewhiten, verbose=False, coordsys='lonlat', timestamp='julsec'): """ Method for Seismic-Array-Beamforming/FK-Analysis :param stream: Stream object, the trace.stats dict like class must contain ...
(length - abs(min_dt) - abs(max_dt)) / df - 1
(length - int(abs(min_dt)) - int(abs(max_dt))) / df - 1
def suite(): return unittest.makeSuite(SonicTestCase, 'test')
temp = "L001:%d~ R000:%f~ R026:%f~ " % (trace.stats.npts, trace.stats.delta, trace.stats.calib)
temp = "L000:%d~ " % cur_npts cur_npts += trace.stats.npts temp += "L001:%d~ R000:%f~ R026:%f~ " % (trace.stats.npts, trace.stats.delta, trace.stats.calib)
def writeQ(stream, filename, data_directory=None, byteorder='='): """ Writes a Q file from given ObsPy Stream object. This function should NOT be called directly, it registers via the obspy :meth:`~obspy.core.stream.Stream.write` method of an ObsPy Stream object, call this instead. Parameters ---------- stream : :cla...
msg = 'Only supporting Laplace transform response type' raise SEEDParserException(msg)
msg = 'Only supporting Laplace transform response ' + \ 'type. Skipping other response information.' warnings.warn(msg) del resp del label continue
def getPAZ(self, channel_id, datetime=None): """ Return PAZ, currently only the Laplace transform is supported, that is blockettes 43 and 53. No multiple stations or locations codes in the same XSEED volume are allowed.
channels[id]['poles'] = \ [complex(x, y) for x, y in zip(resp.real_pole, resp.imaginary_pole)]
try: channels[id]['poles'] = \ [complex(x, y) for x, y in \ zip(resp.real_pole, resp.imaginary_pole)] except AttributeError, e: if resp.number_of_complex_poles == 0: channels[id]['poles'] = [] else: raise e
def getPAZ(self, channel_id, datetime=None): """ Return PAZ, currently only the Laplace transform is supported, that is blockettes 43 and 53. No multiple stations or locations codes in the same XSEED volume are allowed.
channels[id]['zeros'] = \ [complex(x, y) for x, y in zip(resp.real_zero, resp.imaginary_zero)]
try: channels[id]['zeros'] = \ [complex(x, y) for x, y in \ zip(resp.real_zero, resp.imaginary_zero)] except AttributeError, e: if resp.number_of_complex_zeros == 0: channels[id]['zeros'] = [] else: raise e
def getPAZ(self, channel_id, datetime=None): """ Return PAZ, currently only the Laplace transform is supported, that is blockettes 43 and 53. No multiple stations or locations codes in the same XSEED volume are allowed.
src + 'selection.c', src + 'logging.c'],
src + 'selection.c', src + 'logging.c', src + 'fileutils_addon.c'],
def __init__(self, *args, **kwargs): Extension.__init__(self, *args, **kwargs) self.export_symbols = finallist(self.export_symbols)
debug=False):
debug=False, command_delay=0):
def __init__(self, host="webdc.eu", port=18001, timeout=20, user="Anonymous", password="", institution="Anonymous", debug=False): """ """ self.user = user self.password = password self.institution = institution # timeout exists only for Python >= 2.6 if sys.hexversion < 0x02060000: Telnet.__init__(self, host, port) els...
for route in xml_doc.route:
for route in xml_doc.getchildren(): if 'route' not in route.tag: continue
def getRouting(self, network_id, station_id, start_datetime, end_datetime): """ Get responsible host addresses for given network/stations from ArcLink.
for node in route.arclink:
for node in route.getchildren(): if 'arclink' not in node.tag: continue
def getRouting(self, network_id, station_id, start_datetime, end_datetime): """ Get responsible host addresses for given network/stations from ArcLink.
@deprecated
def __getattr__(self, hname): """ convenience function to access header values
y_values = np.ma.empty(2 * self.width) y_values.mask = True
y_values = np.ma.masked_all(2 * self.width)
def __plotMinMax(self, trace, *args, **kwargs): """ Plots the data using a min/max approach that calculated the minimum and maximum values of each "pixel" and than plots only these values. Works much faster with large data sets. """ # Some variables to help calculate the values. starttime = self.starttime.timestamp end...
libraries.append(':'+fftpack)
if platform.system() == 'Darwin': extra_link_args=['-dylib_file libfftpack_lite.dylib:%s/%s' % \ (numpy_lib_dir, fftpack)] else: libraries.append(':'+fftpack)
def __init__(self, *args, **kwargs): Extension.__init__(self, *args, **kwargs) self.export_symbols = finallist(self.export_symbols)
extra_link_args=[])
extra_link_args=extra_link_args)
def __init__(self, *args, **kwargs): Extension.__init__(self, *args, **kwargs) self.export_symbols = finallist(self.export_symbols)
raise e
raise SacError(e)
def _get_dist_(self): """ calculate distance from station and event coordinates
>>> from obspy.core import read
>>> from obspy.core import Stream
def __iter__(self): """ Return a robust iterator for stream.traces.
... tr = Trace(header={'channel': channel})
... tr = Trace(header={'station': 'TEST', 'channel': channel})
def __iter__(self): """ Return a robust iterator for stream.traces.
...EH1 | 1970-01-01T00:00:00.000000Z - 1970-01-01T00:00:00.000000Z | 1.0 Hz, 0 samples ...EHZ | 1970-01-01T00:00:00.000000Z - 1970-01-01T00:00:00.000000Z | 1.0 Hz, 0 samples ...EH2 | 1970-01-01T00:00:00.000000Z - 1970-01-01T00:00:00.000000Z | 1.0 Hz, 0 samples ...EH3 | 1970-01-01T00:00:00.000000Z - 1970-01-01T00:00:00....
TEST...EH1 | 1970-01-01T00:00:00.000000Z - 1970-01-01T00:00:00.000000Z | 1.0 Hz, 0 samples TEST...EHZ | 1970-01-01T00:00:00.000000Z - 1970-01-01T00:00:00.000000Z | 1.0 Hz, 0 samples TEST...EH2 | 1970-01-01T00:00:00.000000Z - 1970-01-01T00:00:00.000000Z | 1.0 Hz, 0 samples TEST...EH3 | 1970-01-01T00:00:00.000000Z - 1970...
def __iter__(self): """ Return a robust iterator for stream.traces.
...EHZ | 1970-01-01T00:00:00.000000Z - 1970-01-01T00:00:00.000000Z | 1.0 Hz, 0 samples ...EHZ | 1970-01-01T00:00:00.000000Z - 1970-01-01T00:00:00.000000Z | 1.0 Hz, 0 samples ...EHN | 1970-01-01T00:00:00.000000Z - 1970-01-01T00:00:00.000000Z | 1.0 Hz, 0 samples ...EHE | 1970-01-01T00:00:00.000000Z - 1970-01-01T00:00:00....
TEST...EHZ | 1970-01-01T00:00:00.000000Z - 1970-01-01T00:00:00.000000Z | 1.0 Hz, 0 samples TEST...EHZ | 1970-01-01T00:00:00.000000Z - 1970-01-01T00:00:00.000000Z | 1.0 Hz, 0 samples TEST...EHN | 1970-01-01T00:00:00.000000Z - 1970-01-01T00:00:00.000000Z | 1.0 Hz, 0 samples TEST...EHE | 1970-01-01T00:00:00.000000Z - 1970...
def __iter__(self): """ Return a robust iterator for stream.traces.
chksum_data = abs(lib.check_sum(data, head.n_samps, C.c_longlong()))
chksum_data = abs(lib.check_sum(data, head.n_samps, C.c_int32()))
def read(f, verify_chksum=True): """ Read GSE2 file and return header and data. Currently supports only CM6 compressed GSE2 files, this should be sufficient for most cases. Data are in circular frequency counts, for correction of calper multiply by 2PI and calper: data * 2 * pi * header['calper']. :type f: File Point...
chksum = C.c_longlong()
chksum = C.c_int32()
def write(headdict, data, f, inplace=False): """ Write GSE2 file, given the header and data. Currently supports only CM6 compressed GSE2 files, this should be sufficient for most cases. Data are in circular frequency counts, for correction of calper multiply by 2PI and calper: data * 2 * pi * header['calper']. Warnin...
raise_flag=True)
raise_flag=False)
def readMSTracesViaRecords(self, filename, reclen= -1, dataflag=1, skipnotdata=1, verbose=0, starttime=None, endtime=None): """ Read MiniSEED file. Returns a list with header informations and data for each trace in the file. The list returned contains a list for each trace in the file with the lists first element bein...
def suite(tests=[]):
def suite(verbosity=1, tests=[]):
def suite(tests=[]): """ The obspy test suite. """ if tests == []: names = ['obspy.%s.tests.suite' % d for d in DEFAULT_MODULES] else: names = [] # Search for short cuts in tests, if there are no short cuts # names is equal to tests for test in tests: if test in DEFAULT_MODULES: test = 'obspy.%s.tests.suite' % test nam...
suite = unittest.TestLoader().loadTestsFromNames(names) return suite
suites = [] ut = unittest.TestLoader() for name in names: try: suites.append(ut.loadTestsFromName(name, None)) except: if verbosity: print "Cannot import test suite for module %s" % name return ut.suiteClass(suites)
def suite(tests=[]): """ The obspy test suite. """ if tests == []: names = ['obspy.%s.tests.suite' % d for d in DEFAULT_MODULES] else: names = [] # Search for short cuts in tests, if there are no short cuts # names is equal to tests for test in tests: if test in DEFAULT_MODULES: test = 'obspy.%s.tests.suite' % test nam...
unittest.TextTestRunner(verbosity=verbosity).run(suite(tests))
unittest.TextTestRunner(verbosity=verbosity).run(suite(verbosity, tests))
def runTests(verbosity=1, tests=[]): """ This function runs all available tests in obspy, from Python :param verbosity: Run tests in verbose mode. 0 quiet, 1 normal, 2 verbose :param tests: List of tests to run. Defaults to runs all. Example ['obspy.core.tests.suite'] """ unittest.TextTestRunner(verbosity=verbosity).r...
query = session.query(WaveformFile, WaveformChannel)
query = session.query(WaveformFile, WaveformChannel, WaveformPath) query = query.filter(WaveformPath.id == WaveformFile.path_id)
def _update_or_insert(self, dataset): """ Add a new file into or modifies existing file in database. """ if len(dataset) < 1: return session = self.session() data = dataset[0] # check for duplicates if self.options.check_duplicates: query = session.query(WaveformFile, WaveformChannel) query = query.filter(WaveformFile....
extra_link_args=extra_link_args)
extra_link_args=extra_link_args, extra_compile_args=extra_compile_args)
def __init__(self, *args, **kwargs): Extension.__init__(self, *args, **kwargs) self.export_symbols = finallist(self.export_symbols)
if abs(last_endtime - header['starttime']) <= 1.01 * delta and \ last_msrid == msrid:
record_delta = abs(last_endtime - header['starttime']) if record_delta <= 1.01 * delta and\ record_delta >= 0.99 * delta and\ last_msrid == msrid:
def readMSTracesViaRecords(self, filename, reclen= -1, dataflag=1, skipnotdata=1, verbose=0, starttime=None, endtime=None): """ Read MiniSEED file. Returns a list with header informations and data for each trace in the file. The list returned contains a list for each trace in the file with the lists first element bein...
self.SetHvalue('e', begin + len(trace) * delta)
self.SetHvalue('e', begin + (len(trace) - 1) * delta)
def fromarray(self, trace, begin=0.0, delta=1.0, distkm=0, starttime=UTCDateTime("1970-01-01T00:00:00.000000")): """ Create a SAC file from an numpy.ndarray instance
def saveKML(self, filename, overwrite=False, nolabels=False, **kwargs):
def saveKML(self, filename, overwrite=False, **kwargs):
def saveKML(self, filename, overwrite=False, nolabels=False, **kwargs): """ Posts an event.getList() and writes the results as a KML file. For optional arguments, see docstring of :meth:`~obspy.seishub.client._EventMapperClient.getList()` :type filename: String :param filename: Filename (complete path) to save KML to....
optional arguments, see docstring of :meth:`~obspy.seishub.client._EventMapperClient.getList()`
optional arguments, see help for :meth:`~obspy.seishub.client._EventMapperClient.getList()` and :meth:`~obspy.seishub.client._EventMapperClient.getKML()`
def saveKML(self, filename, overwrite=False, nolabels=False, **kwargs): """ Posts an event.getList() and writes the results as a KML file. For optional arguments, see docstring of :meth:`~obspy.seishub.client._EventMapperClient.getList()` :type filename: String :param filename: Filename (complete path) to save KML to....
kml_string = self.getKML(nolabels=False, **kwargs)
kml_string = self.getKML(**kwargs)
def saveKML(self, filename, overwrite=False, nolabels=False, **kwargs): """ Posts an event.getList() and writes the results as a KML file. For optional arguments, see docstring of :meth:`~obspy.seishub.client._EventMapperClient.getList()` :type filename: String :param filename: Filename (complete path) to save KML to....
f = open(fname, 'r')
f = open(fname, 'rb')
def ReadSacHeader(self, fname): """ Reads only the header portion of a binary SAC-file.
f = open(fname, 'r+')
f = open(fname, 'rb+')
def WriteSacHeader(self, fname): """ Writes an updated header to an existing binary SAC-file.
s = open(filename).read(blocksize)
s = open(filename, 'rb').read(blocksize)
def _istext_(self, filename, blocksize=512): ### Find out if it is a text or a binary file. This should ### always be true if a file is a text-file and only true for a ### binary file in rare occasions (Recipe 173220 found on ### http://code.activestate.com/ text_characters = "".join(map(chr, range(32, 127)) + list("\n...
result.printErrors() self.stream.writeln(result.separator2)
def run(self, suites): "Run the given test case or test suite." startTime = time.time() results = {} for id, test in suites.iteritems(): result = self._makeResult() test(result) results[id] = result stopTime = time.time() timeTaken = stopTime - startTime runs = 0 faileds = 0 erroreds = 0 wasSuccessful = True for result...
patterns = ["%Y%j"]
pattern = "%Y%j"
def __new__(cls, *args, **kwargs): """ Creates a new UTCDateTime object. """ if len(args) == 0 and len(kwargs) == 0: dt = datetime.datetime.utcnow() return UTCDateTime._new(cls, dt) elif len(args) == 1: value = args[0] # check types if type(value) in [int, long, float]: # got a timestamp dt = datetime.datetime.utcfromt...
patterns = ["%Y%j%H%M%S", "%Y%j"]
value = ''.join(parts) if len(parts) > 2: pattern = "%Y%j%H%M%S" else: pattern = "%Y%j"
def __new__(cls, *args, **kwargs): """ Creates a new UTCDateTime object. """ if len(args) == 0 and len(kwargs) == 0: dt = datetime.datetime.utcnow() return UTCDateTime._new(cls, dt) elif len(args) == 1: value = args[0] # check types if type(value) in [int, long, float]: # got a timestamp dt = datetime.datetime.utcfromt...
patterns = ["%Y%m%d%H%M%S", "%Y%m%d"] value = ''.join(parts)
value = ''.join(parts) if len(value) > 8: pattern = "%Y%m%d%H%M%S" else: pattern = "%Y%m%d"
def __new__(cls, *args, **kwargs): """ Creates a new UTCDateTime object. """ if len(args) == 0 and len(kwargs) == 0: dt = datetime.datetime.utcnow() return UTCDateTime._new(cls, dt) elif len(args) == 1: value = args[0] # check types if type(value) in [int, long, float]: # got a timestamp dt = datetime.datetime.utcfromt...
if not value.isdigit():
if not ''.join(parts).isdigit():
def __new__(cls, *args, **kwargs): """ Creates a new UTCDateTime object. """ if len(args) == 0 and len(kwargs) == 0: dt = datetime.datetime.utcnow() return UTCDateTime._new(cls, dt) elif len(args) == 1: value = args[0] # check types if type(value) in [int, long, float]: # got a timestamp dt = datetime.datetime.utcfromt...
dt = None for pattern in patterns: try: dt = datetime.datetime.strptime(value, pattern) except: continue else: break if dt: dt = UTCDateTime(dt) + ms return UTCDateTime._new(cls, dt)
dt = datetime.datetime.strptime(value, pattern) dt = UTCDateTime(dt) + ms return UTCDateTime._new(cls, dt)
def __new__(cls, *args, **kwargs): """ Creates a new UTCDateTime object. """ if len(args) == 0 and len(kwargs) == 0: dt = datetime.datetime.utcnow() return UTCDateTime._new(cls, dt) elif len(args) == 1: value = args[0] # check types if type(value) in [int, long, float]: # got a timestamp dt = datetime.datetime.utcfromt...
self.assertEqual('Agg', matplotlib.get_backend())
self.assertEqual('AGG', matplotlib.get_backend().upper())
def test_Backend(self): """ Test to see if tests are running without any X11 or any other display variable set. Therefor, the Agg backend is chosen in obspy.imaging.tests.__init__, and nothing must be imported before, e.g. by obspy.imaging.__init__. The agg backend does not require and display setting. It is therefor t...
xx = sparse.csr_matrix((v, help)).todense()
xx = sparse.coo_matrix((v, help)).transpose().todense()
def logbankm(p, n, fs, w): """ Matrix for a log-spaced filterbank. Computes a matrix containing the filterbank amplitudes for a log-spaced filterbank. :param p: Number of filters in filterbank. :param n: Length of fft. :param fs: Sampling frequency in Hz. :param w: Window function. :return xx: Matrix containing the f...
self.bounds = (min(longs), max(longs), min(lats), max(lats))
try: self.bounds = (min(longs), max(longs), min(lats), max(lats)) except ValueError: self.bounds = (47.0, 49.0, 11.0, 12.0)
def getBoundaries(self): lats = [] longs = [] for station in self.stations: info = station[2] lats.append(info['latitude']) longs.append(info['longitude']) self.bounds = (min(longs), max(longs), min(lats), max(lats))
stream.write("test", "Q")
def test_read101Traces(self): """ Testing reading Q file with more than 100 traces. """ testfile = os.path.join(self.path, 'data', '101.QHD') # read stream = readQ(testfile) stream.verify() self.assertEqual(len(stream), 101) stream.write("test", "Q")
length = int(self._readln())
fd = self.get_socket().makefile('rb+') length = int(fd.readline(100).strip())
def _fetch(self, request_type, request_data): self._hello() self._writeln(request_type) for line in request_data: self._writeln(line) self._writeln('END') self._readln('OK') self._writeln('STATUS') req_id = int(self._readln()) while 1: self._writeln('STATUS %d' % req_id) xml_doc = self._readln() if 'ready="true"' in xm...
i = 0 while 1: data += self.rawq_getchar() i += 1 if i > length and 'END' in data: break data = data[:-3] if len(data) != length:
while len(data) < length: buf = fd.read(min(4096, length - len(data))) data += buf buf = fd.readline(100).strip() if buf != "END" or len(data) != length:
def _fetch(self, request_type, request_data): self._hello() self._writeln(request_type) for line in request_data: self._writeln(line) self._writeln('END') self._readln('OK') self._writeln('STATUS') req_id = int(self._readln()) while 1: self._writeln('STATUS %d' % req_id) xml_doc = self._readln() if 'ready="true"' in xm...
print data
print "%d bytes of data read" % len(data)
def _fetch(self, request_type, request_data): self._hello() self._writeln(request_type) for line in request_data: self._writeln(line) self._writeln('END') self._readln('OK') self._writeln('STATUS') req_id = int(self._readln()) while 1: self._writeln('STATUS %d' % req_id) xml_doc = self._readln() if 'ready="true"' in xm...
def openfile(): """ Opens the file, reads it and calculates a minmax list. """ filename = tkFileDialog.askopenfilename() if not filename: return NV.st = read(filename) st = NV.st NV.minmax = minmaxlist(st, 799, st[0].stats.starttime.timestamp, st[0].stats.endtime.timestamp)[2] del NV.minmax[-1] create_graph()
def openfile(): """ Opens the file, reads it and calculates a minmax list. """ filename = tkFileDialog.askopenfilename() if not filename: return # Read the file. NV.st = read(filename) st = NV.st # Get minmaxlist. NV.minmax = minmaxlist(st, 799, st[0].stats.starttime.timestamp, st[0].stats.endtime.timestamp)[2] del NV....
trace.stats.endtime = UTCDateTime(NV.endtime.get())
def getWaveform(*args, **kwargs): """ Retrieves the waveforms and normalizes the graphs """ # Check the two dates. try: st = UTCDateTime(NV.starttime.get()) except: status_bar.configure(text='Please enter a valid start time.', foreground='red') status_bar.update_idletasks() return try: ed = UTCDateTime(NV.endtime.get()...
self.assertEqual(['AD', 'AF', 'AF', 'AK', 'AL'], ids[0:5])
self.assertTrue('GE' in ids)
def test_getNetworkIds(self): """ Retrieve networks_ids from DHI """ #client = Client(network_dc=("/edu/caltech/gps/k2","SCEDC_NetworkDC")) client = Client() print "This will take a very long time" ids = client.getNetworkIds() self.assertEqual(['AD', 'AF', 'AF', 'AK', 'AL'], ids[0:5]) self.assertTrue(len(ids) > 300)
if failed: self.stream.write(", ")
if faileds: self.stream.write(", ")
def run(self, suites): "Run the given test case or test suite." startTime = time.time() results = {} for id, test in suites.iteritems(): result = self._makeResult() test(result) results[id] = result stopTime = time.time() timeTaken = stopTime - startTime runs = 0 faileds = 0 erroreds = 0 wasSuccessful = True self.strea...
service.options = options
service.skip_dots = options.skip_dots service.cleanup = options.cleanup service.log = logging
def _runIndexer(options): logging.info("Starting Indexer ...") # paths if ';' in options.data: items = options.data.split(';') else: items = [options.data] paths = {} for item in items: if '=' in item: path, wc = item.split('=', 1) wcs = wc.split(',') else: path = item wcs = ['*.*'] # check path if not os.path.isdir(pa...
[b, a] = iirfilter(corners, [freqmin / fe, freqmax / fe], btype='band',
low = freqmin / fe high = freqmax / fe if high > 1: high = 1.0 msg = "Selected high corner frequency is above Nyquist. " + \ "Setting Nyquist as high corner." warnings.warn(msg) if low > 1: msg = "Selected low corner frequency is above Nyquist." raise ValueError(msg) [b, a] = iirfilter(corners, [low, high], btype='ban...
def bandpass(data, freqmin, freqmax, df, corners=4, zerophase=False): """ Butterworth-Bandpass Filter. Filter data from freqmin to freqmax using corners corners. :param data: Data to filter, type numpy.ndarray. :param freqmin: Pass band low corner frequency. :param freqmax: Pass band high corner frequency. :param df:...
[b, a] = iirfilter(corners, [freqmin / fe, freqmax / fe],
low = freqmin / fe high = freqmax / fe if high > 1: high = 1.0 msg = "Selected high corner frequency is above Nyquist. " + \ "Setting Nyquist as high corner." warnings.warn(msg) if low > 1: msg = "Selected low corner frequency is above Nyquist." raise ValueError(msg) [b, a] = iirfilter(corners, [low, high],
def bandstop(data, freqmin, freqmax, df, corners=4, zerophase=False): """ Butterworth-Bandstop Filter. Filter data removing data between frequencies freqmin and freqmax using corners corners. :param data: Data to filter, type numpy.ndarray. :param freqmin: Stop band low corner frequency. :param freqmax: Stop band hig...
[b, a] = iirfilter(corners, freq / fe, btype='lowpass', ftype='butter',
f = freq / fe if f > 1: f = 1.0 msg = "Selected corner frequency is above Nyquist. " + \ "Setting Nyquist as high corner." warnings.warn(msg) [b, a] = iirfilter(corners, f, btype='lowpass', ftype='butter',
def lowpass(data, freq, df, corners=4, zerophase=False): """ Butterworth-Lowpass Filter. Filter data removing data over certain frequency freq using corners corners. :param data: Data to filter, type numpy.ndarray. :param freq: Filter corner frequency. :param df: Sampling rate in Hz. :param corners: Filter corners. N...
[b, a] = iirfilter(corners, freq / fe, btype='highpass', ftype='butter',
f = freq / fe if f > 1: msg = "Selected corner frequency is above Nyquist." raise ValueError(msg) [b, a] = iirfilter(corners, f, btype='highpass', ftype='butter',
def highpass(data, freq, df, corners=4, zerophase=False): """ Butterworth-Highpass Filter. Filter data removing data below certain frequency freq using corners. :param data: Data to filter, type numpy.ndarray. :param freq: Filter corner frequency. :param df: Sampling rate in Hz. :param corners: Filter corners. Note: ...
counter = parse_func(data, samp_int, path, 1, options.format,
counter = parse_func(data, samp_int, path, counter, options.format,
def main(): parser = OptionParser(__doc__.strip()) parser.add_option("-f", "--format", default=None, type="string", dest="format", help="Optional, the file format.\n" + \ " ".join(__doc__.split('\n')[-4:])) parser.add_option("-v", "--verbose", default=False, action="store_true", dest="verbose", help="Optional. Verbose ...
Test case for xcorr. (1) Tests example in ObsPy paper submitted to the Electronic Seismologist section of SRL is still working. The test shouldn't be changed because the reference gets wrong. If xcorr is imported before hand e.g. via a doctest, this test will fail with a segmentation fault. (2) Test case of real way ho...
def test_xcorr(self): """ Test case for xcorr. (1) Tests example in ObsPy paper submitted to the Electronic Seismologist section of SRL is still working. The test shouldn't be changed because the reference gets wrong. If xcorr is imported before hand e.g. via a doctest, this test will fail with a segmentation fault. (2...
np.random.seed(815) data1 = np.random.randn(1000).astype('float32') data2 = data1.copy() window_len = 100 path = os.path.dirname(inspect.getsourcefile(self.__class__)) name = os.path.join(path, os.pardir, 'lib', lib_name) lib = C.CDLL(name) shift = C.c_int() coe_p = C.c_double() lib.X_corr(data1.ctypes.data, data2.ct...
def test_xcorr(self): """ Test case for xcorr. (1) Tests example in ObsPy paper submitted to the Electronic Seismologist section of SRL is still working. The test shouldn't be changed because the reference gets wrong. If xcorr is imported before hand e.g. via a doctest, this test will fail with a segmentation fault. (2...
caseNumber = aTags[i].contents[0] if 'n' in caseNumber:
caseNumber = aTags[i].next.next.next.next.next.contents[0].strip()\ .strip('&nbsp;') fileName = aTags[i].contents[0] if 'n' in fileName:
def scrapeCourt(courtID, result): if (courtID == 1): """ PDFs are available from the first circuit if you go to their RSS feed. So go to their RSS feed we shall. """ url = "http://www.ca1.uscourts.gov/opinions/opinionrss.php" ct = Court.objects.get(courtUUID='ca1') req = urllib2.urlopen(url) tree = etree.parse(req) c...
documentType = "U" elif 'p' in caseNumber: documentType = "P" doc.documentType = documentType
doc.documentType = "U" elif 'p' in fileName: doc.documentType = "P"
def scrapeCourt(courtID, result): if (courtID == 1): """ PDFs are available from the first circuit if you go to their RSS feed. So go to their RSS feed we shall. """ url = "http://www.ca1.uscourts.gov/opinions/opinionrss.php" ct = Court.objects.get(courtUUID='ca1') req = urllib2.urlopen(url) tree = etree.parse(req) c...
return str(self.barMembershipUUID)
return self.get_barMembership_display()
def __unicode__(self): return str(self.barMembershipUUID)
userProfile = request.user.get_profile() employer = userProfile.employer bar_memberships = userProfile.barmembership.all() print bar_memberships location = userProfile.location plaintextPreferred = userProfile.plaintextPreferred wantsNewsletter = userProfile.wantsNewsletter profileForm = ProfileForm( initial = {'employ...
try: userProfile = request.user.get_profile() employer = userProfile.employer bar_memberships = userProfile.barmembership.all() location = userProfile.location plaintextPreferred = userProfile.plaintextPreferred wantsNewsletter = userProfile.wantsNewsletter profileForm = ProfileForm( initial = {'employer': employer, 'b...
def viewSettings(request): if request.method == 'POST': userForm = UserForm(request.POST) profileForm = ProfileForm(request.POST) if profileForm.is_valid() and userForm.is_valid(): # Save things to the profile (this should be done with cleaned_data, # but I can't get past an error with the barmemberships field...it's #...
else: return render_to_response('display_cases.html', {'title': case, 'court': ct}, RequestContext(request))
def viewCases(request, court, case): """Take a court and a caseNameShort, and display what we know about that case. """ # get the court information from the URL ct = Court.objects.get(courtUUID = court) # try looking it up by casename. Failing that, try the caseNumber. # replace spaces with hyphens to undo the URLizi...
def queryset_iterator(queryset, chunksize=1000): '''''
def queryset_iterator(queryset, chunksize=100): '''
def queryset_iterator(queryset, chunksize=1000): ''''' from: http://djangosnippets.org/snippets/1949/ Iterate over a Django Queryset ordered by the primary key This method loads a maximum of chunksize (default: 1000) rows in its memory at the same time while django normally would load all rows in its memory. Using the...
os.link(old, new)
try: os.link(old, new) except OSError as exc: if exc.errno == 17: print "Duplicate file found, appending -2" filename = filename[0:string.rfind(filename, ".")] + "-2" \ + filename[string.rfind(filename, "."):] new = os.path.join(root, "pdf", year, month, day, filename) os.link(old, new)
def update_date(doc, simulate): time.sleep(1) # take the doc, check its dateFiled field, make a hardlink to the PDF # location, and update the database if doc.dateFiled != None: dateFiled = doc.dateFiled else: # break from this function. print "\n***No dateFiled value for doc: " + str(doc.documentUUID) + ". Punting.***...
def emailer(rate, verbose):
def emailer(rate, verbose, simulate):
def emailer(rate, verbose): """This will load all the users each day/week/month, and send them emails.""" # remap the FREQUENCY variable from the model so the human keys relate back # to the indices rates = {} for r in FREQUENCY: rates[r[1].lower()] = r[0] RATE = rates[rate] # sphinx likes time in UnixTime format, whi...
if verbose: print "email_text: " + str(email_text)
if verbose and simulate: print "email_text: " + str(email_text)
def emailer(rate, verbose): """This will load all the users each day/week/month, and send them emails.""" # remap the FREQUENCY variable from the model so the human keys relate back # to the indices rates = {} for r in FREQUENCY: rates[r[1].lower()] = r[0] RATE = rates[rate] # sphinx likes time in UnixTime format, whi...
send_mail( EMAIL_SUBJECT, email_text, EMAIL_SENDER, [userProfile.user.email], fail_silently=False)
if not simulate: send_mail( EMAIL_SUBJECT, email_text, EMAIL_SENDER, [userProfile.user.email], fail_silently=False)
def emailer(rate, verbose): """This will load all the users each day/week/month, and send them emails.""" # remap the FREQUENCY variable from the model so the human keys relate back # to the indices rates = {} for r in FREQUENCY: rates[r[1].lower()] = r[0] RATE = rates[rate] # sphinx likes time in UnixTime format, whi...
if verbose:
if verbose and simulate:
def emailer(rate, verbose): """This will load all the users each day/week/month, and send them emails.""" # remap the FREQUENCY variable from the model so the human keys relate back # to the indices rates = {} for r in FREQUENCY: rates[r[1].lower()] = r[0] RATE = rates[rate] # sphinx likes time in UnixTime format, whi...
msg = EmailMultiAlternatives(EMAIL_SUBJECT, email_text, EMAIL_SENDER, [userProfile.user.email]) msg.attach_alternative(html_text, "text/html") msg.send(fail_silently=False)
if not simulate: msg = EmailMultiAlternatives(EMAIL_SUBJECT, email_text, EMAIL_SENDER, [userProfile.user.email]) msg.attach_alternative(html_text, "text/html") msg.send(fail_silently=False)
def emailer(rate, verbose): """This will load all the users each day/week/month, and send them emails.""" # remap the FREQUENCY variable from the model so the human keys relate back # to the indices rates = {} for r in FREQUENCY: rates[r[1].lower()] = r[0] RATE = rates[rate] # sphinx likes time in UnixTime format, whi...
return emailer(rate, verbose)
if simulate: print "******************" print "* NO EMAILS SENT *" print "******************" return emailer(rate, verbose, simulate)
def main(): usage = "usage: %prog -r RATE | --rate=RATE" parser = OptionParser(usage) parser.add_option('-r', '--rate', dest='rate', metavar='RATE', help="The rate to send emails") parser.add_option('-v', '--verbose', action="store_true", dest='verbose', default=False, help="Display variable values during execution") (...
if (count(xml, "<url>") == 2):
if (count(xml, "<url>") == 250):
def cachedSitemap(request, sitemaps, section=None): '''Copied from django.contrib.sitemaps.view, and modified to add a file-based cache.''' # creates two new lists maps, urls = [], [] if section is not None: # if we are using an index page with section names if section not in sitemaps: # is the section name valid? rai...
key_expires__lte = two_months_ago.isoformat())
user__date_joined__lte = two_months_ago.isoformat())
def delete_old_accounts(verbose, simulate): """This script will find accounts older than roughly two months that have not been confirmed, and delete them. It can be run once a month, or so. """ two_months_ago = (datetime.date.today() - datetime.timedelta(60)) # get the accounts unconfirmed_ups = UserProfile.objects.f...
attributes = re.findall('@\w*', query) validRegex = re.compile(r'^@court$|^@casename$|^@docstatus$|^@doctext$')
attributes = re.findall('(?:@)([^\( ]*)', query) regex0 = re.compile(''' @ (?: \w+ \b | ( \( [^@(),]+ (?: , * [^@(),]+ )* \) ) ) ''', re.VERBOSE) groupedAttributes = re.findall(regex0, query) for item in groupedAttributes: attributes.extend(item.strip("(").strip(")").split(", ")) validRegex = re.compile(r'^court$...
def showResults(request): """Show the results for a query as either an alert or a search""" try: query = request.GET['q'] except: # if somebody is URL hacking at /search/results/ query = "" # this handles the alert creation form. if request.method == 'POST': from alert.userHandling.models import Alert # an alert has ...
badAttrs.append(attribute)
if attribute not in badAttrs: badAttrs.append(attribute)
def showResults(request): """Show the results for a query as either an alert or a search""" try: query = request.GET['q'] except: # if somebody is URL hacking at /search/results/ query = "" # this handles the alert creation form. if request.method == 'POST': from alert.userHandling.models import Alert # an alert has ...
numResults = paginator.count
try: numResults = paginator.count except: numResults = 0
def showResults(request): """Show the results for a query as either an alert or a search""" try: query = request.GET['q'] except: # if somebody is URL hacking at /search/results/ query = "" # this handles the alert creation form. if request.method == 'POST': from alert.userHandling.models import Alert # an alert has ...
courtID = options.parseID
courtID = int(options.parseID)
def main(): usage = "usage: %prog (-s SCRAPEID | -p PARSEID) [-v | -V]" parser = OptionParser(usage) parser.add_option('-s', '--scrape', dest='scrapeID', metavar='SCRAPEID', help="The court to scrape and parse") parser.add_option('-p', '--parse', dest='parseID', metavar='PARSEID', help="The court to only parse") parser...
courtID = options.scrapeID
courtID = int(options.scrapeID)
def main(): usage = "usage: %prog (-s SCRAPEID | -p PARSEID) [-v | -V]" parser = OptionParser(usage) parser.add_option('-s', '--scrape', dest='scrapeID', metavar='SCRAPEID', help="The court to scrape and parse") parser.add_option('-p', '--parse', dest='parseID', metavar='PARSEID', help="The court to only parse") parser...
SSN_AND_ITIN = re.compile('(\s|^)(\d{3}-\d{2}-\d{4})(\s|$)') EIN = re.compile('(\s|^)(\d{2}-\d{7})(\s|$)')
def cleanString(s): # replace evil characters with better ones, get rid of white space on the # ends, and get rid of semicolons on the ends. s = s.replace('&rsquo;', '\'').replace('&rdquo;', "\"")\ .replace('&ldquo;',"\"").replace('&nbsp;', ' ').replace('&amp;', '&')\ .replace('%20', ' ').strip().strip(';') # get rid ...
email_addy = request.user.email full_name = request.user.get_full_name() form = ContactForm( initial = {'name': full_name, 'email': email_addy})
try: email_addy = request.user.email full_name = request.user.get_full_name() form = ContactForm( initial = {'name': full_name, 'email': email_addy}) except: form = ContactForm()
def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data # pull the email addresses out of the MANAGERS tuple i = 0 emailAddys = [] while i < len(settings.MANAGERS): emailAddys.append(settings.MANAGERS[i][1]) i += 1 # send the email to the MANAGERS...
try: query = request.GET['q'] except: query = ''
query = request.GET['q']
def get_object(self, request, query): try: query = request.GET['q'] except: query = '' return query