def extractZip(zip, dest): "extract zip archive to dest directory" logger.info("Begin extracting:" + zip + " --> " + dest) mkdir_p(dest) zipfile = ZipFile(zip) entries = zipfile.entries() while entries.hasMoreElements(): entry = entries.nextElement() if entry.isDirectory(): mkdir_p(os.path.join(dest, entry.name)) else: newFile = File(dest, entry.name) mkdir_p(newFile.parent) zis = zipfile.getInputStream(entry) fos = FileOutputStream(newFile) nread = 0 buffer = ByteBuffer.allocate(1024) while True: nread = zis.read(buffer.array(), 0, 1024) if nread <= 0: break fos.write(buffer.array(), 0, nread) fos.close() zis.close() logger.info("End extracting:" + str(zip) + " --> " + str(dest))
def extractZip(zip, dest): "extract zip archive to dest directory" logger.info("Begin extracting:" + zip + " --> " +dest) mkdir_p(dest) zipfile = ZipFile(zip) entries = zipfile.entries() while entries.hasMoreElements(): entry = entries.nextElement() if entry.isDirectory(): mkdir_p(os.path.join(dest, entry.name)) else: newFile = File(dest, entry.name) mkdir_p(newFile.parent) zis = zipfile.getInputStream(entry) fos = FileOutputStream(newFile) nread = 0 buffer = ByteBuffer.allocate(1024) while True: nread = zis.read(buffer.array(), 0, 1024) if nread <= 0: break fos.write(buffer.array(), 0, nread) fos.close() zis.close() logger.info("End extracting:" + str(zip) + " --> " + str(dest))
def asBytes(ID, entry): b = ByteBuffer.allocate(12) # (2 + 2 + 4 + 4) b.putShort(ID) # TagId b.putShort(entry[0]) # DataType b.putInt(1) # DataCount # DataOffset can contain the data when it fits in 4 bytes, but left-justified: must shift leftwards b.putInt(entry[2] << ((4 - entry[1]) * 8)) return b.array()
def send_light_status(self): buffer = ByteBuffer.allocate(12) buffer.put(START) buffer.put(SET_LIGHT_STATUS) buffer.putLong(self.arduino.light_time) buffer.put(1 if self.arduino.light_status else 0) buffer.put(END) buf = buffer.array(); self.output_stream.write(buf)
def test_buffer_no_array(self): """ Directly tests StreamIO with and without a backing array and an InputStream that returns early. """ size = 10000 without_array = ByteBuffer.allocateDirect(size) self.assertFalse(without_array.hasArray()) with_array = ByteBuffer.allocate(size) self.assertTrue(with_array.hasArray()) bbs = [with_array, without_array] for bb in bbs: iis = InfiniteInputStream() io = StreamIO(iis, True) self.assertEqual(io.readinto(bb), size)
def encode(self, input, errors='strict'): error_function = codecs.lookup_error(errors) # workaround non-BMP issues - need to get the exact count of chars, not codepoints input_buffer = CharBuffer.allocate(StringBuilder(input).length()) input_buffer.put(input) input_buffer.rewind() encoder = Charset.forName(self.encoding).newEncoder() output_buffer = ByteBuffer.allocate(min(max(len(input) * 2, 256), 1024)) builder = StringIO() while True: result = encoder.encode(input_buffer, output_buffer, True) pos = output_buffer.position() output_buffer.rewind() builder.write(output_buffer.array()[0:pos].tostring()) if result.isUnderflow(): break _process_encode_errors(self.encoding, input, result, error_function, input_buffer, builder) return builder.getvalue(), len(input)
def str2num(self, size, f): i = 0 n = 0 buf = ByteBuffer.allocate(4) buf.order(ByteOrder.LITTLE_ENDIAN) read = 0 while read < size: r = f.read(buf.array(), read, size - read) if r == -1: raise IOException() read += r while read < 4: buf.put(read, byte(0)) read += 1 return buf.getInt()
def process_command(self, command): if command == START and self.count <= 0: self.buffer = [] self.first = True elif command == END and self.count <= 0: print self.buffer buffer = ByteBuffer.allocate(len(self.buffer)) for b in self.buffer: buffer.put(b) buffer.flip() cmd = buffer.get() if cmd == REQUEST_LIGHT_STATUS: self.send_light_status() pass elif cmd == SET_LIGHT_STATUS: time = buffer.getLong() status = buffer.get() print status self.arduino.switch_arduino_lights(status, time) elif cmd == SET_ROUGH: time = buffer.getLong() self.arduino.send_rough_data(time) elif cmd == SET_REALLY_ROUGH: time = buffer.getLong() self.arduino.send_really_rough_data(time) else: self.buffer.append(command) if self.first: if command == SET_LIGHT_STATUS: self.count = 10 elif command == REQUEST_LIGHT_STATUS: self.count = 1 elif command == SET_ROUGH: self.count = 9 elif command == SET_REALLY_ROUGH: self.count = 9 self.first = False self.count -= 1
def iconv(file): print 'Converting', file f = File(file) if not f.exists(): print file, 'does not exist' sys.exit(1) buffer = ByteBuffer.allocate(f.length() * 2) input = FileInputStream(f) input.getChannel().read(buffer) buffer.limit(buffer.position()) buffer.position(0) if buffer.limit() != f.length(): print file, 'could not be read completely' sys.exit(1) input.close() buffer = encoder.encode(decoder.decode(buffer)) buffer.position(0) output = FileOutputStream(file + '.cnv') if output.getChannel().write(buffer) != buffer.limit(): print file, 'could not be reencoded' sys.exit(1) output.close() f.delete() File(file + '.cnv').renameTo(f)
# Write as TIFF file filepath = os.path.join( tempfile.gettempdir(), "bit-img-" + datetime.now().strftime("%Y-%m-%d-%H:%M:%S") + ".tif") ra = RandomAccessFile(filepath, 'rw') try: # Header: big endian (4D, 4D) or (M, M), magic number (42, 42), and offset of 9 bytes to first IFD # Note: # bin(int("4D", 16))[2:].zfill(8) == '01001101' # int("4D", 16) == 77 ra.write(array([77, 77, 0, 42, 0, 0, 0, 8], 'b')) # A tmp plane img to copy into it each 2D slice for saving later as the pixel data of each IFD plane_img = ArrayImgs.bits([img.dimension(0), img.dimension(1)]) plane_array = plane_img.update(None).getCurrentStorageArray() # a long[] bb = ByteBuffer.allocate(len(plane_array) * 8) # each long primitive has 8 bytes # Each IFD and image data # Use either short (3) or int (4) for the DataType, so that ImageJ's ij.io.TiffDecoder can read it tags = { 256: (4, 4, img.dimension(0)), # signed int (32-bit), 4 bytes, width 257: (4, 4, img.dimension(1)), # signed int (32-bit), 4 bytes, height 258: (4, 4, bitDepth), # signed byte, 1 byte, bitDepth (BitsPerSample) 259: ( 4, 4, 1 ), # signed byte, 1 byte, compression: 1 means uncompressed: it's true, in a way 277: (4, 4, 1), # signed byte, 1 byte, SamplesPerPixel: 1 channel 278: (4, 4, 1), # signed byte, 1 byte, RowsPerStrip 279: (4, 4, bb.capacity()) } # signed int (32-bit), StripByteCounts # Pending to append: variable tag ID 273: ?, # StripOffsets, taking 12 bytes like each of the other tags,
def datetime(val): milliseconds = long(float(val) * 1e3) return ByteBuffer.allocate(8).putLong(0, milliseconds)
def __init__(self, errors='strict', encoding=None): assert encoding self.encoding = encoding self.errors = errors self.encoder = Charset.forName(self.encoding).newEncoder() self.output_buffer = ByteBuffer.allocate(1024)
from android.hardware.usb import UsbDevice, UsbDeviceConnection, UsbEndpoint, UsbInterface, UsbManager, UsbRequest from java.nio import ByteBuffer from . import TransportException from .protocol import ProtocolBasedTransport, ProtocolV1, Handle LOG = logging.getLogger(__name__) INTERFACE = 0 ENDPOINT = 1 DEBUG_INTERFACE = 1 DEBUG_ENDPOINT = 2 Timeout = 100 forceClaim = True USB_Manager = None USB_DEVICE = None RESPONSE = ByteBuffer.allocate(64) class AndroidUsbHandle(Handle): def __init__(self) -> None: self.device = USB_DEVICE # type: UsbDevice self.manger = USB_Manager # type: UsbManager self.interface = None # type: UsbInterface self.endpoint_in = None # type: UsbEndpoint self.endpoint_out = None # type: UsbEndpoint self.handle = None # type: UsbDeviceConnection def open(self) -> None: assert self.device is not None, "Android USB is not available" self.interface = self.device.getInterface(0)