本文整理汇总了Python中copy.copy方法的典型用法代码示例。如果您正苦于以下问题:Python copy.copy方法的具体用法?Python copy.copy怎么用?Python copy.copy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类copy
的用法示例。
在下文中一共展示了copy.copy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __add__
# 需要导入模块: import copy [as 别名]
# 或者: from copy import copy [as 别名]
def __add__(self, other):
"""
This implements set union and returns
a new Composite that is self union other.
If other is an atomic agent, just add it to
this group.
"""
if other is None:
return self
new_dict = copy(self.members)
if is_composite(other):
new_dict.update(other.members)
else:
new_dict[other.name] = other
new_grp = grp_from_nm_dict(self.name + "+" + other.name, new_dict)
self.add_group(new_grp)
other.add_group(new_grp)
return new_grp
示例2: add_border
# 需要导入模块: import copy [as 别名]
# 或者: from copy import copy [as 别名]
def add_border(self, val, img_shape=None):
if val == 0:
return self.copy()
else:
if isinstance(val, int):
rect = Rectangle(x1=self.x1-val, x2=self.x2+val, y1=self.y1-val, y2=self.y2+val)
elif isinstance(val, float):
rect = Rectangle(x1=int(self.x1 - self.width*val), x2=int(self.x2 + self.width*val), y1=int(self.y1 - self.height*val), y2=int(self.y2 + self.height*val))
elif isinstance(val, tuple):
assert len(val) == 4, str(len(val))
if all([isinstance(subval, int) for subval in val]):
rect = Rectangle(x1=self.x1-val[3], x2=self.x2+val[1], y1=self.y1-val[0], y2=self.y2+val[2])
elif all([isinstance(subval, float) or subval == 0 for subval in val]): # "or subval==0" da sonst zB (0.1, 0, 0.1, 0) einen fehler erzeugt (0 ist int)
rect = Rectangle(x1=int(self.x1 - self.width*val[3]), x2=int(self.x2 + self.width*val[1]), y1=int(self.y1 - self.height*val[0]), y2=int(self.y2 + self.height*val[2]))
else:
raise Exception("Tuple of all ints or tuple of all floats expected, got %s" % (str([type(v) for v in val]),))
else:
raise Exception("int or float or tuple of ints/floats expected, got %s" % (type(val),))
if img_shape is not None:
rect.fix_by_image_dimensions(height=img_shape[0], width=img_shape[1])
return rect
示例3: draw_on_image
# 需要导入模块: import copy [as 别名]
# 或者: from copy import copy [as 别名]
def draw_on_image(self, img, color=[0, 255, 0], alpha=1.0, copy=True, from_img=None):
if copy:
img = np.copy(img)
orig_dtype = img.dtype
if alpha != 1.0 and img.dtype != np.float32:
img = img.astype(np.float32, copy=False)
for rect in self:
if from_img is not None:
rect.resize(from_img, img).draw_on_image(img, color=color, alpha=alpha, copy=False)
else:
rect.draw_on_image(img, color=color, alpha=alpha, copy=False)
if orig_dtype != img.dtype:
img = img.astype(orig_dtype, copy=False)
return img
示例4: turn
# 需要导入模块: import copy [as 别名]
# 或者: from copy import copy [as 别名]
def turn(self):
"""Turn"""
nt = copy.deepcopy(self.table)
for y in range(0, self.height):
for x in range(0, self.width):
neighbours = self.liveNeighbours(y, x)
if self.table[y][x] == 0:
if neighbours == 3:
nt[y][x] = 1
else:
if (neighbours < 2) or (neighbours > 3):
nt[y][x] = 0
self._oldStates.append(self.table)
if len(self._oldStates) > 3:
self._oldStates.popleft()
self.table = nt
示例5: create_time_table
# 需要导入模块: import copy [as 别名]
# 或者: from copy import copy [as 别名]
def create_time_table(self, t):
t = time.localtime(t)
hr = t.tm_hour
if not self.mil_time:
hr = hr % 12
hrs = str(hr).zfill(2)
mins = str(t.tm_min).zfill(2)
val = hrs + ":" + mins
w, h = font.str_dim(val, font=self.font_name,
font_scale=self.scale, final_sep=False)
x = (self.width - w) // 2
y = (self.height - h) // 2
old_buf = copy.copy(self.layout.colors)
self.layout.all_off()
self.layout.drawText(val, x, y, color=COLORS.Red,
font=self.font_name, font_scale=self.scale)
table = []
for y in range(self.height):
table.append([0] * self.width)
for x in range(self.width):
table[y][x] = int(any(self.layout.get(x, y)))
self.layout.setBuffer(old_buf)
return table
示例6: generate_our_response
# 需要导入模块: import copy [as 别名]
# 或者: from copy import copy [as 别名]
def generate_our_response():
"""
生成我们的响应
:rtype: Response
"""
# copy and parse remote response
resp = copy_response(is_streamed=parse.streamed_our_response)
if parse.time["req_time_header"] >= 0.00001:
parse.set_extra_resp_header('X-Header-Req-Time', "%.4f" % parse.time["req_time_header"])
if parse.time.get("start_time") is not None and not parse.streamed_our_response:
# remote request time should be excluded when calculating total time
parse.set_extra_resp_header('X-Body-Req-Time', "%.4f" % parse.time["req_time_body"])
parse.set_extra_resp_header('X-Compute-Time',
"%.4f" % (process_time() - parse.time["start_time"]))
parse.set_extra_resp_header('X-Powered-By', 'zmirror/%s' % CONSTS.__VERSION__)
if developer_dump_all_traffics and not parse.streamed_our_response:
dump_zmirror_snapshot("traffic")
return resp
示例7: test_copy
# 需要导入模块: import copy [as 别名]
# 或者: from copy import copy [as 别名]
def test_copy(self):
entity1 = fake_cloud_client.make_entity(('abc', '1'))
entity1['k1'] = ['v1']
self.assertEqual(entity1.key,
fake_cloud_client.FakeDatastoreKey('abc', '1'))
self.assertEqual(dict(entity1),
{'k1': ['v1']})
entity2 = copy.copy(entity1)
entity2['k1'].append('v2')
entity2['k3'] = 'v3'
self.assertIsInstance(entity2, fake_cloud_client.FakeDatastoreEntity)
self.assertEqual(entity1.key,
fake_cloud_client.FakeDatastoreKey('abc', '1'))
self.assertEqual(dict(entity1),
{'k1': ['v1', 'v2']})
self.assertEqual(entity2.key,
fake_cloud_client.FakeDatastoreKey('abc', '1'))
self.assertEqual(dict(entity2),
{'k1': ['v1', 'v2'], 'k3': 'v3'})
示例8: test_deep_copy
# 需要导入模块: import copy [as 别名]
# 或者: from copy import copy [as 别名]
def test_deep_copy(self):
entity1 = fake_cloud_client.make_entity(('abc', '1'))
entity1['k1'] = ['v1']
self.assertEqual(entity1.key,
fake_cloud_client.FakeDatastoreKey('abc', '1'))
self.assertEqual(dict(entity1),
{'k1': ['v1']})
entity2 = copy.deepcopy(entity1)
entity2['k1'].append('v2')
entity2['k3'] = 'v3'
self.assertIsInstance(entity2, fake_cloud_client.FakeDatastoreEntity)
self.assertEqual(entity1.key,
fake_cloud_client.FakeDatastoreKey('abc', '1'))
self.assertEqual(dict(entity1),
{'k1': ['v1']})
self.assertEqual(entity2.key,
fake_cloud_client.FakeDatastoreKey('abc', '1'))
self.assertEqual(dict(entity2),
{'k1': ['v1', 'v2'], 'k3': 'v3'})
示例9: _check_tarball
# 需要导入模块: import copy [as 别名]
# 或者: from copy import copy [as 别名]
def _check_tarball(self, *path_parts):
rpath = self.join(*path_parts)
# start by checking our base path:
if self.base_path is not None and self.base_path != '':
(tbloc, tbinternal) = split_tarball_path(self.base_path)
if tbloc is not None:
if tbinternal == '':
# we're fine; we just need to cache the current file...
return (self._cache_tarball(''), rpath)
else:
# We copy ourselves to handle this base-path
tmp = copy.copy(self)
object.__setattr__(tmp, 'base_path', tbloc)
rpath = self.join(tbinternal, rpath)
# we defer to this path object with the new relative path:
return (tmp._cache_tarball(''), rpath)
# okay, next check the relative path
fpath = self.join('' if self.base_path is None else self.base_path, rpath)
(tbloc, tbinternal) = split_tarball_path(fpath)
if tbloc is not None:
tbp = self._cache_tarball(tbloc)
return (tbp, tbinternal)
# otherwise, we have no tarball on the path and just need to return ourselves as we are:
return (self, rpath)
示例10: _check_without_ordering
# 需要导入模块: import copy [as 别名]
# 或者: from copy import copy [as 别名]
def _check_without_ordering(cells):
errors = []
for cell in copy(cells):
if cell.get('field') is not None:
header = cell.get('header')
if header != cell['field'].name and header is not None:
# Add error
message_substitutions = {
'field_name': '"{}"'.format(cell['field'].name),
'header': '"{}"'.format(cell.get('header')),
}
error = Error(
'non-matching-header',
cell,
message_substitutions=message_substitutions
)
errors.append(error)
if _slugify(header) != _slugify(cell['field'].name):
# Remove cell
cells.remove(cell)
return errors
示例11: missing_value
# 需要导入模块: import copy [as 别名]
# 或者: from copy import copy [as 别名]
def missing_value(cells):
"""
missing-value: A row has less columns than the header.
"""
errors = []
for cell in copy(cells):
# Skip if cell has value
# There is a difference between:
# - not having value at all - there is no `value` key
# - having a value which is falsy (None, False, '', etc)
# (so we don't use something like `if cell.get('value')`)
if 'value' in cell or cell.get('is-virtual'):
continue
# Add error
error = Error('missing-value', cell)
errors.append(error)
# Remove cell
cells.remove(cell)
return errors
示例12: copy
# 需要导入模块: import copy [as 别名]
# 或者: from copy import copy [as 别名]
def copy(self):
# TODO Test the copy function
replay_memory = copy.copy(self)
replay_memory.states = numpy.zeros(self.states.shape, dtype=self.states.dtype)
replay_memory.actions = numpy.zeros(self.actions.shape, dtype=self.actions.dtype)
replay_memory.rewards = numpy.zeros(self.rewards.shape, dtype='float32')
replay_memory.terminate_flags = numpy.zeros(self.terminate_flags.shape, dtype='bool')
replay_memory.states[numpy.arange(self.top-self.size, self.top), ::] = \
self.states[numpy.arange(self.top-self.size, self.top)]
replay_memory.actions[numpy.arange(self.top-self.size, self.top)] = \
self.actions[numpy.arange(self.top-self.size, self.top)]
replay_memory.rewards[numpy.arange(self.top-self.size, self.top)] = \
self.rewards[numpy.arange(self.top-self.size, self.top)]
replay_memory.terminate_flags[numpy.arange(self.top-self.size, self.top)] = \
self.terminate_flags[numpy.arange(self.top-self.size, self.top)]
return replay_memory
示例13: initialize
# 需要导入模块: import copy [as 别名]
# 或者: from copy import copy [as 别名]
def initialize(self, init=initializer.Uniform(), ctx=None, verbose=False,
force_reinit=False):
"""Initializes :py:class:`Parameter` s of this :py:class:`Block` and its children.
Equivalent to ``block.collect_params().initialize(...)``
Parameters
----------
init : Initializer
Global default Initializer to be used when :py:meth:`Parameter.init` is ``None``.
Otherwise, :py:meth:`Parameter.init` takes precedence.
ctx : Context or list of Context
Keeps a copy of Parameters on one or many context(s).
verbose : bool, default False
Whether to verbosely print out details on initialization.
force_reinit : bool, default False
Whether to force re-initialization if parameter is already initialized.
"""
self.collect_params().initialize(init, ctx, verbose, force_reinit)
示例14: builder
# 需要导入模块: import copy [as 别名]
# 或者: from copy import copy [as 别名]
def builder(func: Callable) -> Callable:
"""
Decorator for wrapper "builder" functions. These are functions on the Query class or other classes used for
building queries which mutate the query and return self. To make the build functions immutable, this decorator is
used which will deepcopy the current instance. This decorator will return the return value of the inner function
or the new copy of the instance. The inner function does not need to return self.
"""
import copy
def _copy(self, *args, **kwargs):
self_copy = copy.copy(self) if getattr(self, "immutable", True) else self
result = func(self_copy, *args, **kwargs)
# Return self if the inner function returns None. This way the inner function can return something
# different (for example when creating joins, a different builder is returned).
if result is None:
return self_copy
return result
return _copy
示例15: replace_table
# 需要导入模块: import copy [as 别名]
# 或者: from copy import copy [as 别名]
def replace_table(self, current_table: Optional[Table], new_table: Optional[Table]) -> "JoinUsing":
"""
Replaces all occurrences of the specified table with the new table. Useful when reusing
fields across queries.
:param current_table:
The table to be replaced.
:param new_table:
The table to replace with.
:return:
A copy of the join with the tables replaced.
"""
self.item = new_table if self.item == current_table else self.item
self.fields = [
field.replace_table(current_table, new_table) for field in self.fields
]