code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
obj = obj or self
obj.__dict__['_dirty_attributes'].clear()
obj._dirty = False
for key, val in vars(obj).items():
if isinstance(val, BaseObject):
self._clean_dirty(val)
else:
func = getattr(val, '_clean_dirty', None)
... | def _clean_dirty(self, obj=None) | Recursively clean self and all child objects. | 3.235666 | 2.852591 | 1.13429 |
obj = obj or self
for key, value in vars(obj).items():
if key not in ('api', '_dirty_attributes', '_always_dirty', '_dirty_callback', '_dirty'):
setattr(obj, key, value)
if isinstance(value, BaseObject):
self._set_dirty(value) | def _set_dirty(self, obj=None) | Recursively set self and all child objects _dirty flag. | 4.23683 | 3.561976 | 1.189461 |
return json.dumps(self, default=json_encode_for_printing, indent=indent) | def to_json(self, indent=2) | Return self formatted as JSON. | 6.8261 | 5.485654 | 1.244355 |
if serialize:
encode_method = json_encode_for_zendesk
else:
encode_method = json_encode_for_printing
return json.loads(json.dumps(self._to_dict(serialize=serialize), default=encode_method)) | def to_dict(self, serialize=False) | This method returns the object as a Python dict. If serialize is passed, only those attributes
that have been modified will be included in the result.
:param serialize:
:return: | 4.492181 | 4.558968 | 0.98535 |
copy_dict = self.__dict__.copy()
for key, value in vars(self).items():
# We want to send all ids to Zendesk always
if serialize and key == 'id':
continue
# If this is a Zenpy object, convert it to a dict.
if not serialize and isin... | def _to_dict(self, serialize=False) | This method works by copying self.__dict__, and removing everything that should not be serialized. | 4.492428 | 4.341056 | 1.03487 |
if self.api and self.group_id:
return self.api._get_group(self.group_id) | def group(self) | | Comment: The id of a group | 5.918661 | 5.209541 | 1.136119 |
if self.api and self.organization_id:
return self.api._get_organization(self.organization_id) | def organization(self) | | Comment: The ID of the organization associated with this user, in this membership | 5.349533 | 4.844688 | 1.104206 |
if self.api and self.assignee_id:
return self.api._get_user(self.assignee_id) | def assignee(self) | | Comment: The id of the assignee if the field is visible to end users | 4.80148 | 4.851346 | 0.989721 |
if self.api and self.collaborator_ids:
return self.api._get_users(self.collaborator_ids) | def collaborators(self) | | Comment: Who are currently CC'ed on the ticket | 6.003365 | 6.579094 | 0.912491 |
if self.api and self.requester_id:
return self.api._get_user(self.requester_id) | def requester(self) | | Comment: The id of the requester | 7.031323 | 6.056565 | 1.160942 |
if self.api and self.forum_topic_id:
return self.api._get_topic(self.forum_topic_id) | def forum_topic(self) | | Comment: The topic this ticket originated from, if any | 4.847863 | 4.913283 | 0.986685 |
if self.api and self.problem_id:
return self.api._get_problem(self.problem_id) | def problem(self) | | Comment: For tickets of type "incident", the ID of the problem the incident is linked to | 5.462592 | 5.767289 | 0.947168 |
if self.api and self.sharing_agreement_ids:
return self.api._get_sharing_agreements(self.sharing_agreement_ids) | def sharing_agreements(self) | | Comment: The ids of the sharing agreements used for this ticket | 4.543554 | 4.197066 | 1.082555 |
if self.api and self.submitter_id:
return self.api._get_user(self.submitter_id) | def submitter(self) | | Comment: The user who submitted the ticket. The submitter always becomes the author of the first comment on the ticket | 5.435031 | 5.086709 | 1.068477 |
if self.api and self.restricted_brand_ids:
return self.api._get_restricted_brands(self.restricted_brand_ids) | def restricted_brands(self) | | Comment: ids of all brands that this ticket form is restricted to | 5.33586 | 5.12624 | 1.040891 |
if self.api and self.ticket_field_ids:
return self.api._get_ticket_fields(self.ticket_field_ids) | def ticket_fields(self) | | Comment: ids of all ticket fields which are in this ticket form | 4.987999 | 3.97845 | 1.253755 |
if self.api and self.custom_role_id:
return self.api._get_custom_role(self.custom_role_id) | def custom_role(self) | | Comment: A custom role if the user is an agent on the Enterprise plan | 4.447737 | 4.10756 | 1.082817 |
response_objects = dict()
if all((t in response_json for t in ('ticket', 'audit'))):
response_objects["ticket_audit"] = self.object_mapping.object_from_json(
"ticket_audit",
response_json
)
# Locate and store the single objects.
... | def deserialize(self, response_json) | Locate and deserialize all objects in the returned JSON.
Return a dict keyed by object_type. If the key is plural, the value will be a list,
if it is singular, the value will be an object of that type.
:param response_json: | 2.35862 | 2.438613 | 0.967198 |
response_json = response.json()
# Special case for ticket audits.
if get_endpoint_path(self.api, response).startswith('/ticket_audits.json'):
return TicketAuditGenerator(self, response_json)
zenpy_objects = self.deserialize(response_json)
# Collection of o... | def build(self, response) | Deserialize the returned objects and return either a single Zenpy object, or a ResultGenerator in
the case of multiple results.
:param response: the requests Response object. | 3.582865 | 3.349623 | 1.069632 |
new_cache = self._get_cache_impl(cache_impl, maxsize, **kwargs)
self._populate_new_cache(new_cache)
self.cache = new_cache | def set_cache_impl(self, cache_impl, maxsize, **kwargs) | Change cache implementation. The contents of the old cache will
be transferred to the new one.
:param cache_impl: Name of cache implementation, must exist in AVAILABLE_CACHES | 3.097982 | 3.90659 | 0.793015 |
new_cache = self._get_cache_impl(self.impl_name, maxsize, **kwargs)
self._populate_new_cache(new_cache)
self.cache = new_cache | def set_maxsize(self, maxsize, **kwargs) | Set maxsize. This involves creating a new cache and transferring the items. | 5.768833 | 4.386309 | 1.315191 |
object_type = get_object_type(zenpy_object)
if object_type not in self.mapping or self.disabled:
return
attr_name = self._cache_key_attribute(object_type)
cache_key = getattr(zenpy_object, attr_name)
log.debug("Caching: [{}({}={})]".format(zenpy_object.__clas... | def add(self, zenpy_object) | Add a Zenpy object to the relevant cache. If no cache exists for this object nothing is done. | 3.117653 | 2.776798 | 1.122751 |
if not isinstance(to_delete, list):
to_delete = [to_delete]
for zenpy_object in to_delete:
object_type = get_object_type(zenpy_object)
object_cache = self.mapping.get(object_type, None)
if object_cache:
removed_object = object_cach... | def delete(self, to_delete) | Purge one or more items from the relevant caches | 2.866106 | 2.804978 | 1.021793 |
if object_type not in self.mapping or self.disabled:
return None
cache = self.mapping[object_type]
if cache_key in cache:
log.debug("Cache HIT: [%s %s]" % (object_type.capitalize(), cache_key))
return cache[cache_key]
else:
log.deb... | def get(self, object_type, cache_key) | Query the cache for a Zenpy object | 2.523584 | 2.533469 | 0.996098 |
object_type = get_object_type(zenpy_object)
cache_key = self._cache_key_attribute(object_type)
return self.get(object_type, getattr(zenpy_object, cache_key)) | def query_cache_by_object(self, zenpy_object) | Convenience method for testing. Given an object, return the cached version | 3.649831 | 3.433689 | 1.062947 |
if object_type in self.mapping:
cache = self.mapping[object_type]
log.debug("Purging [{}] cache of {} values.".format(object_type, len(cache)))
cache.purge() | def purge_cache(self, object_type) | Purge the named cache of all values. If no cache exists for object_type, nothing is done | 4.201155 | 3.525866 | 1.191524 |
object_type = get_object_type(zenpy_object)
cache_key_attr = self._cache_key_attribute(object_type)
return self.get(object_type, getattr(zenpy_object, cache_key_attr)) is not None | def in_cache(self, zenpy_object) | Determine whether or not this object is in the cache | 3.389227 | 3.302943 | 1.026123 |
return dict(
# Transparently retry requests that are safe to retry, with the exception of 429. This is handled
# in the Api._call_api() method.
max_retries=Retry(
total=3,
status_forcelist=[r for r in Retry.RETRY_AFTER_STATUS_CODES if... | def http_adapter_kwargs() | Provides Zenpy's default HTTPAdapter args for those users providing their own adapter. | 7.216501 | 6.735522 | 1.071409 |
cache = self._get_cache(cache_name)
cache.set_maxsize(maxsize, **kwargs) | def set_cache_max(self, cache_name, maxsize, **kwargs) | Sets the maxsize attribute of the named cache | 2.689373 | 2.826397 | 0.95152 |
self._get_cache(cache_name).set_cache_impl(impl_name, maxsize, **kwargs) | def set_cache_implementation(self, cache_name, impl_name, maxsize, **kwargs) | Changes the cache implementation for the named cache | 2.87306 | 3.134438 | 0.916611 |
if object_type not in ZendeskObjectMapping.class_mapping:
raise ZenpyException("No such object type: %s" % object_type)
self.cache.mapping[object_type] = ZenpyCache(cache_impl_name, maxsize, **kwargs) | def add_cache(self, object_type, cache_impl_name, maxsize, **kwargs) | Add a new cache for the named object type and cache implementation | 4.779977 | 4.597838 | 1.039614 |
if not isinstance(object_json, dict):
return object_json
obj = self.instantiate_object(object_type, parent)
for key, value in object_json.items():
if key not in self.skip_attrs:
key, value = self._deserialize(key, obj, value)
if isinst... | def object_from_json(self, object_type, object_json, parent=None) | Given a blob of JSON representing a Zenpy object, recursively deserialize it and
any nested objects it contains. This method also adds the deserialized object
to the relevant cache if applicable. | 2.814497 | 2.704837 | 1.040542 |
ZenpyClass = self.class_for_type(object_type)
obj = ZenpyClass(api=self.api)
if parent:
def dirty_callback():
parent._dirty = True
obj._dirty = True
obj._dirty_callback = dirty_callback
obj._always_dirty.update(self.always... | def instantiate_object(self, object_type, parent) | Instantiate a Zenpy object. If this object has a parent, add a callback to call the parent if it is modified.
This is so the parent object is correctly marked as dirty when a child is modified, eg:
view.conditions.all.append(<something>)
Also, some attributes need to be sent together to Ze... | 4.899216 | 3.924737 | 1.248291 |
if object_type not in self.class_mapping:
raise ZenpyException("Unknown object_type: " + str(object_type))
else:
return self.class_mapping[object_type] | def class_for_type(self, object_type) | Given an object_type return the class associated with it. | 3.539617 | 3.139248 | 1.127537 |
values = self[field].unique()
results = {}
for value in values:
results[value] = self.model_class(**self[self[field] == value].iloc[0])
return results | def index_by(self, field) | Returns a dict with a key for each value of `field` and the first record with that value as value.
:param field: Name of the field to index by.
:type field: string. | 3.275207 | 3.561188 | 0.919695 |
if self.persisted:
if self.soft_delete and not force:
self.__class__.update(
values={
self.__class__.deleted_at_column(): datetime.utcnow()
},
where=self.where_self
)
... | def destroy(self, force=False) | Deletes the record. If the model has ``soft_delete`` activated, the record will not actually be deleted.
:param force: forces the record to be actually deleted if ``soft_delete`` is activated.
:type force: boolean | 5.083315 | 4.6931 | 1.083146 |
#select='*', where=None, inner_joins=None, left_joins=None,
#group=None, order=None, limit=None, db=None, role='replica'):
db_adapter = self.db_adapter(
db_name=kwargs.get('db'),
role=kwargs.get('role', 'replica')
)
kwargs['stack'] = self.st... | def select(self, **kwargs) | Perform a SELECT statement on the model's table in the replica database.
:param select: Columns to return in the SELECT statement.
:type select: string, array, dict
:param where: WHERE clause of the SELECT statement. This can be a plain string, a dict or an array.
:type where: string, d... | 7.042826 | 5.29486 | 1.330125 |
results = query(
sql=sql,
filename=filename,
db=self.db_names[kwargs.get('role', 'replica')],
**kwargs
)
if results is None:
return None
else:
return self.collection_instance(results) | def query(self, sql=None, filename=None, **kwargs) | run raw sql from sql or file against.
:param sql: Raw SQL query to pass directly to the connection.
:type sql: string
:param filename: Path to a file containing a SQL query. The path should be relative to CWD.
:type filename: string
:param db: `optional` Database name from your ... | 5.916087 | 5.069862 | 1.166913 |
if 'select' in kwargs:
kwargs['select'] = {'cnt': 'COUNT(%s)' % kwargs['select']}
else:
kwargs['select'] = {'cnt': 'COUNT(*)'}
res = self.db_adapter(
db_name=kwargs.get('db'),
role=kwargs.get('role', 'replica')
).select(**kwar... | def count(self, **kwargs) | Performs a COUNT statement on the model's table in the replica database.
:param select: Column to be counted.
:type select: string
:param where: WHERE clause of the SELECT statement. This can be a plain string, a dict or an array.
:type where: string, dict, array
:param db: Data... | 4.604928 | 4.114873 | 1.119094 |
if len(kwargs['values']) == 0:
config.logger.warning('No values to insert.')
return
values = kwargs['values']
if isinstance(values, self):
values = values.attributes.copy()
if isinstance(values, dict):
for (k, v) in values.items():... | def insert(self, **kwargs) | Performs an INSERT statement on the model's table in the master database.
:param values: A dictionary containing the values to be inserted. ``datetime``, ``dict`` and ``bool`` objects can be passed as is and will be correctly serialized by psycopg2.
:type values: dict | 4.262135 | 4.167593 | 1.022685 |
kwargs['stack'] = self.stack_mark(inspect.stack())
kwargs['primary_key'] = self.primary_key
column_names = self.table_schema().keys()
now = datetime.utcnow()
if 'updated_at' in column_names:
kwargs['values']['updated_at'] = now
results = self.db_adapt... | def update(self, **kwargs) | Performs an UPDATE statement on the model's table in the master database.
:param values: A dictionary of values to update. ``datetime``, ``dict`` and ``bool`` objects can be passed as is and will be correctly serialized by psycopg2.
:type values: dict
:param where: The WHERE clause. This can be... | 6.427923 | 6.006484 | 1.070164 |
kwargs['stack'] = self.stack_mark(inspect.stack())
return self.db_adapter(role='master').delete(**kwargs) | def delete(self, **kwargs) | Performs a DELETE statement on the model's table in the master database.
:param where: The WHERE clause. This can be a plain string, a dict or an array.
:type where: string, dict, array | 19.900879 | 23.546507 | 0.845173 |
return self.collection_instance(
self.db_adapter(
db_name=kwargs.get('db'),
role=kwargs.get('role', 'replica')
).select(
where='created_at IS NOT NULL',
order='created_at DESC',
limit... | def last(self, limit=1, **kwargs) | Returns the last `limit` records inserted in the model's table in the replica database. Rows are sorted by ``created_at``. | 6.087996 | 4.779697 | 1.27372 |
try:
return self(
**self.select(
where=values,
limit=1,
**kwargs
).to_dict(orient='records')[0]
)
except IndexError:
return None | def find_by(self, values={}, **kwargs) | Returns a single record matching the criteria in ``values`` found in the model's table in the replica database.
:param values: Criteria to find the record.
:type values: dict
:returns: an instance of the model. | 4.963503 | 5.160986 | 0.961735 |
return self.find_by(values={self.primary_key: id}, **kwargs) | def find(self, id, **kwargs) | Finds a record by its id in the model's table in the replica database.
:returns: an instance of the model. | 7.411361 | 8.423286 | 0.879866 |
if not self._use_replica():
return 0
try:
kwargs['stack'] = self.stack_mark(inspect.stack())
sql = "select EXTRACT(EPOCH FROM NOW() - pg_last_xact_replay_timestamp()) AS replication_lag"
return self.collection_instance(
self.db_ada... | def replica_lag(self, **kwargs) | Returns the current replication lag in seconds between the master and replica databases.
:returns: float | 7.993745 | 8.336972 | 0.958831 |
if self.__dict__.get('_table_schema') is None:
self._table_schema = None
table_schema = {}
for row in self.query_schema():
name, default, dtype = self.db().lexicon.column_info(row)
if isinstance(default, str):
json_... | def table_schema(self) | Returns the table schema.
:returns: dict | 3.314502 | 3.40282 | 0.974046 |
def deco_retry(f):
@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 1:
try:
return f(*args, **kwargs)
except ExceptionToCheck as e:
msg = "%s, Retrying in %d seco... | def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None) | Retry calling the decorated function using an exponential backoff.
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:param ExceptionToCheck: the exception to check. may be a tuple of
exceptions to check
:type ExceptionToCheck: Exception or tuple
:param tries: number of ti... | 1.294848 | 1.339662 | 0.966548 |
material.vertices = struct.unpack('{}f'.format(length // 4), fd.read(length)) | def load_vertex_buffer(self, fd, material, length) | Load vertex data from file. Can be overriden to reduce data copy
:param fd: file object
:param material: The material these vertices belong to
:param length: Byte length of the vertex data | 5.784036 | 6.489653 | 0.89127 |
fd = gzip.open(cache_name(self.file_name), 'rb')
for buff in self.meta.vertex_buffers:
mat = self.wavefront.materials.get(buff['material'])
if not mat:
mat = Material(name=buff['material'], is_default=True)
self.wavefront.materials[mat.n... | def _load_vertex_buffers(self) | Load each vertex buffer into each material | 4.352796 | 3.955646 | 1.100401 |
for mtllib in self.meta.mtllibs:
try:
materials = self.material_parser_cls(
os.path.join(self.path, mtllib),
encoding=self.encoding,
strict=self.strict).materials
except IOError:
raise IO... | def _parse_mtllibs(self) | Load mtl files | 3.998066 | 3.667497 | 1.090135 |
self._vertex_buffers.append({
"material": material,
"vertex_format": vertex_format,
"byte_offset": byte_offset,
"byte_length": byte_length,
}) | def add_vertex_buffer(self, material, vertex_format, byte_offset, byte_length) | Add a vertex buffer | 1.848055 | 1.943837 | 0.950725 |
with open(path, 'w') as fd:
fd.write(json.dumps(
{
"created_at": self._created_at,
"version": self._version,
"mtllibs": self._mtllibs,
"vertex_buffers": self._vertex_buffers,
},
... | def write(self, path) | Save the metadata as json | 3.508909 | 3.433675 | 1.021911 |
for material in self.materials:
if material.name == new_material.name:
return True
return False | def has_material(self, new_material) | Determine whether we already have a material of this name. | 3.066274 | 2.409365 | 1.272648 |
if self.has_material(material):
return
self.materials.append(material) | def add_material(self, material) | Add a material to the mesh, IF it's not already present. | 4.485361 | 3.15874 | 1.419984 |
def inner(*args, **kwargs):
func(*args, **kwargs)
args[0].consume_line()
return inner | def auto_consume(func) | Decorator for auto consuming lines when leaving the function | 4.008595 | 3.434455 | 1.167171 |
if self.file_name.endswith(".gz"):
if sys.version_info.major == 3:
gz = gzip.open(self.file_name, mode='rt', encoding=self.encoding)
else:
gz = gzip.open(self.file_name, mode='rt')
for line in gz.readlines():
yield li... | def create_line_generator(self) | Creates a generator function yielding lines in the file
Should only yield non-empty lines | 2.258763 | 2.127666 | 1.061615 |
self.line = next(self.lines) # Will raise StopIteration when there are no more lines
self.values = self.line.split() | def next_line(self) | Read the next line from the line generator and split it | 6.213875 | 4.559755 | 1.362765 |
try:
# Continues until `next_line()` raises StopIteration
# This can trigger here or in parse functions in the subclass
while True:
# Only advance the parser if the previous line was consumed.
# Parse functions reading multiple lines c... | def parse(self) | Parse all the lines in the obj file
Determines what type of line we are and dispatch appropriately. | 8.1264 | 7.874411 | 1.032001 |
if self.strict:
raise PywavefrontException("Unimplemented OBJ format statement '%s' on line '%s'"
% (self.values[0], self.line.rstrip()))
else:
logger.warning("Unimplemented OBJ format statement '%s' on line '%s'"
... | def parse_fallback(self) | Fallback method when parser doesn't know the statement | 5.987186 | 5.077822 | 1.179086 |
return {"_".join(a.split("_")[1:]): getattr(self, a)
for a in dir(self)
if a.startswith("parse_")} | def _build_dispatch_map(self) | Build a dispatch map: {func name": func} dict
This is to easily dispatch to each parse method.
Parse methods must start with `parse_` to be registered.
The suffix should be the name of the obj statement
such as `parse_v` for vertex statements. | 4.888003 | 3.831814 | 1.275637 |
# Draw Wavefront instance
if isinstance(instance, Wavefront):
draw_materials(instance.materials)
# Draw single material
elif isinstance(instance, Material):
draw_material(instance)
# Draw dict of materials
elif isinstance(instance, dict):
draw_materials(instance)
... | def draw(instance) | Generic draw function | 3.608685 | 3.758993 | 0.960014 |
if material.gl_floats is None:
material.gl_floats = (GLfloat * len(material.vertices))(*material.vertices)
material.triangle_count = len(material.vertices) / material.vertex_size
vertex_format = VERTEX_FORMATS.get(material.vertex_format)
if not vertex_format:
raise ValueError("... | def draw_material(material, face=GL_FRONT_AND_BACK) | Draw a single material | 2.107623 | 2.113639 | 0.997153 |
if not getattr(texture, 'image', None):
texture.image = load_image(texture.path)
glEnable(texture.image.target)
glBindTexture(texture.image.target, texture.image.id)
gl.glTexParameterf(texture.image.target,
gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE)
gl.glTexParam... | def bind_texture(texture) | Draw a single texture | 1.878908 | 1.886285 | 0.996089 |
image = pyglet.image.load(name).texture
verify_dimensions(image)
return image | def load_image(name) | Load an image | 8.025877 | 7.843263 | 1.023283 |
while len(values) < 4:
values.append(0.)
return list(map(float, values)) | def pad_light(self, values) | Accept an array of up to 4 values, and return an array of 4 values.
If the input array is less than length 4, pad it with zeroes until it
is length 4. Also ensure each value is a float | 5.091803 | 4.396445 | 1.158164 |
self.transparency = alpha
self.diffuse[3] = alpha
self.ambient[3] = alpha
self.specular[3] = alpha
self.emissive[3] = alpha | def set_alpha(self, alpha) | Set alpha/last value on all four lighting attributes. | 2.889182 | 2.318607 | 1.246085 |
Kd = os.path.join(self.dir, " ".join(self.values[1:]))
self.this_material.set_texture(Kd) | def parse_map_Kd(self) | Diffuse map | 10.688532 | 9.753407 | 1.095877 |
Kd = os.path.join(self.dir, " ".join(self.values[1:]))
self.this_material.set_texture_ambient(Kd) | def parse_map_Ka(self) | Ambient map | 13.364265 | 10.179883 | 1.312811 |
Kd = os.path.join(self.dir, " ".join(self.values[1:]))
self.this_material.set_texture_specular_color(Kd) | def parse_map_Ks(self) | Specular color map | 14.893834 | 9.983087 | 1.491907 |
Kd = os.path.join(self.dir, " ".join(self.values[1:]))
self.this_material.set_texture_specular_highlight(Kd) | def parse_map_Ns(self) | Specular color map | 17.844597 | 12.084456 | 1.476657 |
Kd = os.path.join(self.dir, " ".join(self.values[1:]))
self.this_material.set_texture_alpha(Kd) | def parse_map_d(self) | Alpha map | 16.056313 | 11.920673 | 1.34693 |
Kd = os.path.join(self.dir, " ".join(self.values[1:]))
self.this_material.set_texture_bump(Kd) | def parse_map_bump(self) | Bump map | 13.053658 | 12.281753 | 1.06285 |
start = time.time()
if self.cache:
self.load_cache()
if not self.cache_loaded:
super(ObjParser, self).parse()
logger.info("%s: Load time: %s", self.file_name, time.time() - start) | def parse(self) | Trigger cache load or call superclass parse() | 4.71834 | 4.090791 | 1.153405 |
self.cache_loaded = self.cache_loader_cls(
self.file_name,
self.wavefront,
strict=self.strict,
create_materials=self.create_materials,
encoding=self.encoding,
parse=self.parse,
).parse() | def load_cache(self) | Loads the file using cached data | 7.253194 | 7.142998 | 1.015427 |
if self.cache and not self.cache_loaded:
self.cache_writer_cls(self.file_name, self.wavefront).write() | def post_parse(self) | Called after parsing is done | 11.731625 | 10.466801 | 1.120842 |
while True:
# Vertex color
if len(self.values) == 7:
yield (
float(self.values[1]),
float(self.values[2]),
float(self.values[3]),
float(self.values[4]),
float(self... | def consume_vertices(self) | Consumes all consecutive vertices.
NOTE: There is no guarantee this will consume all vertices since other
statements can also occur in the vertex list | 2.41826 | 2.510113 | 0.963407 |
# The first iteration processes the current/first vn statement.
# The loop continues until there are no more vn-statements or StopIteration is raised by generator
while True:
yield (
float(self.values[1]),
float(self.values[2]),
... | def consume_normals(self) | Consumes all consecutive texture coordinate lines | 5.819793 | 5.112133 | 1.138428 |
# The first iteration processes the current/first vt statement.
# The loop continues until there are no more vt-statements or StopIteration is raised by generator
while True:
yield (
float(self.values[1]),
float(self.values[2]),
)
... | def consume_texture_coordinates(self) | Consume all consecutive texture coordinates | 6.327986 | 6.009617 | 1.052977 |
if code:
error = error_text(code, context)
logger.error(error)
raise Snap7Exception(error) | def check_error(code, context="client") | check if the error code is set. If so, a Python log message is generated
and an error is raised. | 6.097776 | 5.306863 | 1.149036 |
assert context in ("client", "server", "partner")
logger.debug("error text for %s" % hex(error))
len_ = 1024
text_type = c_char * len_
text = text_type()
library = load_library()
if context == "client":
library.Cli_ErrorText(error, text, len_)
elif context == "server":
... | def error_text(error, context="client") | Returns a textual explanation of a given error number
:param error: an error integer
:param context: server, client or partner
:returns: the error string | 3.537241 | 3.485558 | 1.014828 |
logger.debug("error text for %s" % hex(event.EvtCode))
len_ = 1024
text_type = ctypes.c_char * len_
text = text_type()
error = self.library.Srv_EventText(ctypes.byref(event),
ctypes.byref(text), len_)
check_error(error)
... | def event_text(self, event) | Returns a textual explanation of a given event object
:param event: an PSrvEvent struct object
:returns: the error string | 4.72189 | 4.171724 | 1.13188 |
logger.info("creating server")
self.library.Srv_Create.restype = snap7.snap7types.S7Object
self.pointer = snap7.snap7types.S7Object(self.library.Srv_Create()) | def create(self) | create the server. | 8.188143 | 6.702748 | 1.22161 |
size = ctypes.sizeof(userdata)
logger.info("registering area %s, index %s, size %s" % (area_code,
index, size))
size = ctypes.sizeof(userdata)
return self.library.Srv_RegisterArea(self.pointer, area_code, index,
... | def register_area(self, area_code, index, userdata) | Shares a memory area with the server. That memory block will be
visible by the clients. | 3.777125 | 3.90694 | 0.966773 |
logger.info("setting event callback")
callback_wrap = ctypes.CFUNCTYPE(None, ctypes.c_void_p,
ctypes.POINTER(snap7.snap7types.SrvEvent),
ctypes.c_int)
def wrapper(usrptr, pevent, size):
... | def set_events_callback(self, call_back) | Sets the user callback that the Server object has to call when an
event is created. | 4.41649 | 4.313925 | 1.023775 |
logger.info("setting read event callback")
callback_wrapper = ctypes.CFUNCTYPE(None, ctypes.c_void_p,
ctypes.POINTER(snap7.snap7types.SrvEvent),
ctypes.c_int)
def wrapper(usrptr, pevent, size):
... | def set_read_events_callback(self, call_back) | Sets the user callback that the Server object has to call when a Read
event is created.
:param call_back: a callback function that accepts a pevent argument. | 4.33139 | 4.574125 | 0.946933 |
logger.debug("setting up event logger")
def log_callback(event):
logger.info("callback event: " + self.event_text(event))
self.set_events_callback(log_callback) | def _set_log_callback(self) | Sets a callback that logs the events | 6.033264 | 5.417719 | 1.113617 |
if tcpport != 102:
logger.info("setting server TCP port to %s" % tcpport)
self.set_param(snap7.snap7types.LocalPort, tcpport)
logger.info("starting server on 0.0.0.0:%s" % tcpport)
return self.library.Srv_Start(self.pointer) | def start(self, tcpport=102) | start the server. | 4.890854 | 4.661252 | 1.049258 |
logger.info("destroying server")
if self.library:
self.library.Srv_Destroy(ctypes.byref(self.pointer)) | def destroy(self) | destroy the server. | 11.627976 | 8.763325 | 1.326891 |
logger.debug("get server status")
server_status = ctypes.c_int()
cpu_status = ctypes.c_int()
clients_count = ctypes.c_int()
error = self.library.Srv_GetStatus(self.pointer, ctypes.byref(server_status),
ctypes.byref(cpu_status),
... | def get_status(self) | Reads the server status, the Virtual CPU status and the number of
the clients connected.
:returns: server status, cpu status, client count | 2.754575 | 2.350477 | 1.171921 |
return self.library.Srv_UnregisterArea(self.pointer, area_code, index) | def unregister_area(self, area_code, index) | Unshares' a memory area previously shared with Srv_RegisterArea().
That memory block will be no longer visible by the clients. | 13.642149 | 4.894798 | 2.787071 |
logger.debug("unlocking area code %s index %s" % (code, index))
return self.library.Srv_UnlockArea(self.pointer, code, index) | def unlock_area(self, code, index) | Unlocks a previously locked shared memory area. | 6.447113 | 6.199929 | 1.039869 |
logger.debug("locking area code %s index %s" % (code, index))
return self.library.Srv_LockArea(self.pointer, code, index) | def lock_area(self, code, index) | Locks a shared memory area. | 6.595912 | 6.031533 | 1.093571 |
if tcpport != 102:
logger.info("setting server TCP port to %s" % tcpport)
self.set_param(snap7.snap7types.LocalPort, tcpport)
assert re.match(ipv4, ip), '%s is invalid ipv4' % ip
logger.info("starting server to %s:102" % ip)
return self.library.Srv_Start(... | def start_to(self, ip, tcpport=102) | start server on a specific interface. | 5.996651 | 5.794919 | 1.034812 |
logger.debug("setting param number %s to %s" % (number, value))
return self.library.Srv_SetParam(self.pointer, number,
ctypes.byref(ctypes.c_int(value))) | def set_param(self, number, value) | Sets an internal Server object parameter. | 5.398362 | 5.111003 | 1.056223 |
logger.debug("setting mask kind %s to %s" % (kind, mask))
return self.library.Srv_SetMask(self.pointer, kind, mask) | def set_mask(self, kind, mask) | Writes the specified filter mask. | 7.276116 | 6.800053 | 1.070009 |
assert status in snap7.snap7types.cpu_statuses, 'unknown cpu state %s' % status
logger.debug("setting cpu status to %s" % status)
return self.library.Srv_SetCpuStatus(self.pointer, status) | def set_cpu_status(self, status) | Sets the Virtual CPU status. | 7.534173 | 7.254407 | 1.038565 |
logger.debug("checking event queue")
event = snap7.snap7types.SrvEvent()
ready = ctypes.c_int32()
code = self.library.Srv_PickEvent(self.pointer, ctypes.byref(event),
ctypes.byref(ready))
check_error(code)
if ready:
... | def pick_event(self) | Extracts an event (if available) from the Events queue. | 5.213026 | 4.804888 | 1.084942 |
logger.debug("retreiving param number %s" % number)
value = ctypes.c_int()
code = self.library.Srv_GetParam(self.pointer, number,
ctypes.byref(value))
check_error(code)
return value.value | def get_param(self, number) | Reads an internal Server object parameter. | 5.467738 | 4.761081 | 1.148424 |
logger.debug("retrieving mask kind %s" % kind)
mask = snap7.snap7types.longword()
code = self.library.Srv_GetMask(self.pointer, kind, ctypes.byref(mask))
check_error(code)
return mask | def get_mask(self, kind) | Reads the specified filter mask. | 6.843409 | 6.333337 | 1.080538 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.