本文整理汇总了Python中future.utils.native方法的典型用法代码示例。如果您正苦于以下问题:Python utils.native方法的具体用法?Python utils.native怎么用?Python utils.native使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类future.utils
的用法示例。
在下文中一共展示了utils.native方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native [as 别名]
def __init__(self, segy_file, like=None):
"""
Parameters
----------
segy_file : str
segy file path
like : str, optional
created segy file has the same dimesions as like.
"""
self.segy_file = segy_file
self.inDepth = False # True if dataset Z is in Depth
self.property_type = None
if like is not None:
if Path(native(like)).exists() and not Path(native(self.segy_file)).exists():
copyfile(src=like, dst=self.segy_file)
if Path(native(self.segy_file)).exists():
self._parse_segy()
else:
raise Exception("File does not exist!")
示例2: from_json
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native [as 别名]
def from_json(cls, json_file, segy_file=None):
"""
Initialize SeiSEGY from an json file containing information
Parameters
----------
json_file : str
json file path
segy_file : str
segy file path for overriding information in json file.
"""
with open(json_file, 'r') as fl:
json_object = json.load(fl)
segy = json_object["path"]
inDepth = json_object["inDepth"]
property_type = json_object["Property_Type"]
if segy_file:
segy = segy_file
instance = cls(native(segy))
instance.inDepth = inDepth
instance.property_type = property_type
return instance
示例3: __init__
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native [as 别名]
def __init__(self, survey_dir):
"""
Parameters
----------
survey_dir : str
survey directory.
"""
self.survey_dir = Path(native(survey_dir))
self.setting_json = None
self._check_dir()
super(Survey, self).__init__(ThreePoints(self.setting_json))
self.wells = dict()
self.seismics = dict()
self.inl_crl = dict()
self.horizons = dict()
self._add_seis_wells()
self._add_seismic()
self._add_horizon()
示例4: store_images
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native [as 别名]
def store_images(self, callback_data, batch_ind, imgs_to_store, img_batch_data, C, H, W):
"""
Store images
"""
n_imgs = len(imgs_to_store)
if n_imgs:
img_data = img_batch_data[:, imgs_to_store].get()
img_store = callback_data.create_group('deconv/img/batch_' + str(batch_ind))
# Store uint8 HWC formatted data for plotting
img_hwc8 = img_store.create_dataset("HWC_uint8", (H, W, C, n_imgs),
dtype='uint8', compression=True)
img_hwc_f32 = np.transpose(img_data.reshape((C, H, W, n_imgs)), (1, 2, 0, 3))
img_hwc8[:] = self.scale_to_rgb(img_hwc_f32)
# keep image in native format to use for fprop in visualization
# don't need this beyond runtime so avoid writing to file
self.raw_img_cache[batch_ind] = img_data
# Keep a lookup from img_ind -> file position
# In order to store only needed imgs from batch in flat prealloc array
self.raw_img_key[batch_ind] = dict()
for i, img_idx in enumerate(imgs_to_store):
img_store.attrs[str(img_idx)] = i
self.raw_img_key[batch_ind][img_idx] = i
示例5: infer_shape
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native [as 别名]
def infer_shape(self, node, input_shapes):
"""Return a list of output shapes based on ``input_shapes``.
This method is optional. It allows to compute the shape of the
output without having to evaluate.
Parameters
----------
node : `theano.gof.graph.Apply`
The node of this Op in the computation graph.
input_shapes : 1-element list of `theano.compile.ops.Shape`
Symbolic shape of the input.
Returns
-------
output_shapes : 1-element list of tuples
Fixed shape of the output determined by `odl_op`.
"""
if isinstance(self.operator, Functional):
return [()]
else:
# Need to convert to native to avoid error in Theano from
# future.int
return [tuple(native(si) for si in self.operator.range.shape)]
示例6: from_bytes
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native [as 别名]
def from_bytes(cls, mybytes, byteorder='big', signed=False):
"""
Return the integer represented by the given array of bytes.
The mybytes argument must either support the buffer protocol or be an
iterable object producing bytes. Bytes and bytearray are examples of
built-in objects that support the buffer protocol.
The byteorder argument determines the byte order used to represent the
integer. If byteorder is 'big', the most significant byte is at the
beginning of the byte array. If byteorder is 'little', the most
significant byte is at the end of the byte array. To request the native
byte order of the host system, use `sys.byteorder' as the byte order value.
The signed keyword-only argument indicates whether two's complement is
used to represent the integer.
"""
if byteorder not in ('little', 'big'):
raise ValueError("byteorder must be either 'little' or 'big'")
if isinstance(mybytes, unicode):
raise TypeError("cannot convert unicode objects to bytes")
# mybytes can also be passed as a sequence of integers on Py3.
# Test for this:
elif isinstance(mybytes, collections.Iterable):
mybytes = newbytes(mybytes)
b = mybytes if byteorder == 'big' else mybytes[::-1]
if len(b) == 0:
b = b'\x00'
# The encode() method has been disabled by newbytes, but Py2's
# str has it:
num = int(native(b).encode('hex'), 16)
if signed and (b[0] & 0x80):
num = num - (2 ** (len(b)*8))
return cls(num)
# def _twos_comp(val, bits):
# """compute the 2's compliment of int value val"""
# if( (val&(1<<(bits-1))) != 0 ):
# val = val - (1<<bits)
# return val
示例7: from_bytes
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native [as 别名]
def from_bytes(cls, mybytes, byteorder='big', signed=False):
"""
Return the integer represented by the given array of bytes.
The mybytes argument must either support the buffer protocol or be an
iterable object producing bytes. Bytes and bytearray are examples of
built-in objects that support the buffer protocol.
The byteorder argument determines the byte order used to represent the
integer. If byteorder is 'big', the most significant byte is at the
beginning of the byte array. If byteorder is 'little', the most
significant byte is at the end of the byte array. To request the native
byte order of the host system, use `sys.byteorder' as the byte order value.
The signed keyword-only argument indicates whether two's complement is
used to represent the integer.
"""
if byteorder not in ('little', 'big'):
raise ValueError("byteorder must be either 'little' or 'big'")
if isinstance(mybytes, unicode):
raise TypeError("cannot convert unicode objects to bytes")
# mybytes can also be passed as a sequence of integers on Py3.
# Test for this:
elif isinstance(mybytes, Iterable):
mybytes = newbytes(mybytes)
b = mybytes if byteorder == 'big' else mybytes[::-1]
if len(b) == 0:
b = b'\x00'
# The encode() method has been disabled by newbytes, but Py2's
# str has it:
num = int(native(b).encode('hex'), 16)
if signed and (b[0] & 0x80):
num = num - (2 ** (len(b)*8))
return cls(num)
# def _twos_comp(val, bits):
# """compute the 2's compliment of int value val"""
# if( (val&(1<<(bits-1))) != 0 ):
# val = val - (1<<bits)
# return val
示例8: _check_dir
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native [as 别名]
def _check_dir(self):
survey_file = self.survey_dir / '.survey'
if survey_file.exists():
self.setting_json = native(str(survey_file))
else:
raise Exception("No survey setting file in folder!")
示例9: _add_seismic
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native [as 别名]
def _add_seismic(self):
seis_dir = self.survey_dir / "Seismics"
for seis_name in get_data_files(seis_dir):
info_file = str(self.survey_dir.absolute() / \
"Seismics" / "{}.seis".format(seis_name))
data_path = None
with open(info_file, "r") as fl:
data_path = Path(native(json.load(fl)["path"]))
if not data_path.is_absolute() and \
data_path.name == str(data_path):
data_path = self.survey_dir.absolute() / "Seismics" / data_path
self.seismics[seis_name] = SeiSEGY.from_json(info_file,
str(data_path))
示例10: read_las
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native [as 别名]
def read_las(self):
if Path(native(self.las_file)).exists():
las = LASReader(native(str(Path(self.las_file))), null_subs=np.nan)
# well_name = las.well.items['WELL'].data
df = pd.DataFrame(
las.data2d,
columns=["{}({})".format(
las.curves.items[name].descr.replace(' ', '_'),
las.curves.items[name].units) \
for name in las.curves.names])
if 'Depth(M)' in df.columns.values.tolist():
df.rename(columns={'Depth(M)': 'Depth(m)'}, inplace=True)
self._data_frame = df
示例11: _encrypt
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native [as 别名]
def _encrypt(self, data, iv):
encrypter = pyaes.Encrypter(
pyaes.AESModeOfOperationCBC(self._hash.hash, iv=native(iv)))
enc_data = encrypter.feed(self.MAGIC_DETECT_ENC + data)
enc_data += encrypter.feed()
return enc_data
示例12: _decrypt
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native [as 别名]
def _decrypt(self, data, iv):
decrypter = pyaes.Decrypter(
pyaes.AESModeOfOperationCBC(self._hash.hash, iv=native(iv)))
try:
dec_data = decrypter.feed(data)
dec_data += decrypter.feed()
except ValueError:
# in most "wrong password" cases the pkcs7 padding will be wrong
raise StoragePasswordError("Wrong password.")
if not dec_data.startswith(self.MAGIC_DETECT_ENC):
raise StoragePasswordError("Wrong password.")
return dec_data[len(self.MAGIC_DETECT_ENC):]
示例13: load_callbacks
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native [as 别名]
def load_callbacks(cls, cdict, model, data=[]):
"""
Load callbacks.
"""
if type(native(cdict)) is str:
cdict = load_obj(cdict)
callbacks = cls(model, output_file=cdict['output_file'])
callbacks.epoch_marker = cdict['epoch_marker']
callbacks.callbacks = []
for cb in cdict['callbacks']:
module = load_class(cb['type'])
callbacks.callbacks.append(module(**cb['config']))
return callbacks
示例14: _norm_default
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native [as 别名]
def _norm_default(x):
"""Default Euclidean norm implementation."""
# Lazy import to improve `import odl` time
import scipy.linalg
if _blas_is_applicable(x.data):
nrm2 = scipy.linalg.blas.get_blas_funcs('nrm2', dtype=x.dtype)
norm = partial(nrm2, n=native(x.size))
else:
norm = np.linalg.norm
return norm(x.data.ravel())
示例15: to_bytes
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native [as 别名]
def to_bytes(self, length, byteorder='big', signed=False):
"""
Return an array of bytes representing an integer.
The integer is represented using length bytes. An OverflowError is
raised if the integer is not representable with the given number of
bytes.
The byteorder argument determines the byte order used to represent the
integer. If byteorder is 'big', the most significant byte is at the
beginning of the byte array. If byteorder is 'little', the most
significant byte is at the end of the byte array. To request the native
byte order of the host system, use `sys.byteorder' as the byte order value.
The signed keyword-only argument determines whether two's complement is
used to represent the integer. If signed is False and a negative integer
is given, an OverflowError is raised.
"""
if length < 0:
raise ValueError("length argument must be non-negative")
if length == 0 and self == 0:
return newbytes()
if signed and self < 0:
bits = length * 8
num = (2**bits) + self
if num <= 0:
raise OverflowError("int too smal to convert")
else:
if self < 0:
raise OverflowError("can't convert negative int to unsigned")
num = self
if byteorder not in ('little', 'big'):
raise ValueError("byteorder must be either 'little' or 'big'")
h = b'%x' % num
s = newbytes((b'0'*(len(h) % 2) + h).zfill(length*2).decode('hex'))
if signed:
high_set = s[0] & 0x80
if self > 0 and high_set:
raise OverflowError("int too big to convert")
if self < 0 and not high_set:
raise OverflowError("int too small to convert")
if len(s) > length:
raise OverflowError("int too big to convert")
return s if byteorder == 'big' else s[::-1]