import hmsclient<EOL>from thrift.transport import TSocket, TTransport<EOL>from thrift.protocol import TBinaryProtocol<EOL>ms = self.metastore_conn<EOL>auth_mechanism = ms.extra_dejson.get('<STR_LIT>', '<STR_LIT>')<EOL>if configuration.conf.get('<STR_LIT>', '<STR_LIT>') == '<STR_LIT>':<EOL><INDENT>auth_mechanism = ms.extra_dejson.get('<STR_LIT>', '<STR_LIT>')<EOL>kerberos_service_name = ms.extra_dejson.get('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>socket = TSocket.TSocket(ms.host, ms.port)<EOL>if configuration.conf.get('<STR_LIT>', '<STR_LIT>') == '<STR_LIT>'and auth_mechanism == '<STR_LIT>':<EOL><INDENT>try:<EOL><INDENT>import saslwrapper as sasl<EOL><DEDENT>except ImportError:<EOL><INDENT>import sasl<EOL><DEDENT>def sasl_factory():<EOL><INDENT>sasl_client = sasl.Client()<EOL>sasl_client.setAttr("<STR_LIT:host>", ms.host)<EOL>sasl_client.setAttr("<STR_LIT>", kerberos_service_name)<EOL>sasl_client.init()<EOL>return sasl_client<EOL><DEDENT>from thrift_sasl import TSaslClientTransport<EOL>transport = TSaslClientTransport(sasl_factory, "<STR_LIT>", socket)<EOL><DEDENT>else:<EOL><INDENT>transport = TTransport.TBufferedTransport(socket)<EOL><DEDENT>protocol = TBinaryProtocol.TBinaryProtocol(transport)<EOL>return hmsclient.HMSClient(iprot=protocol)<EOL>


def get_partitions(<EOL>self, schema, table_name, filter=None):

with self.metastore as client:<EOL><INDENT>table = client.get_table(dbname=schema, tbl_name=table_name)<EOL>if len(table.partitionKeys) == <NUM_LIT:0>:<EOL><INDENT>raise AirflowException("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>if filter:<EOL><INDENT>parts = client.get_partitions_by_filter(<EOL>db_name=schema, tbl_name=table_name,<EOL>filter=filter, max_parts=HiveMetastoreHook.MAX_PART_COUNT)<EOL><DEDENT>else:<EOL><INDENT>parts = client.get_partitions(<EOL>db_name=schema, tbl_name=table_name,<EOL>max_parts=HiveMetastoreHook.MAX_PART_COUNT)<EOL><DEDENT>pnames = [p.name for p in table.partitionKeys]<EOL>return [dict(zip(pnames, p.values)) for p in parts]<EOL><DEDENT><DEDENT>

Returns a list of all partitions in a table. Works only
for tables with less than 32767 (java short max val).
For subpartitioned table, the number might easily exceed this.

>>> hh = HiveMetastoreHook()
>>> t = 'static_babynames_partitioned'
>>> parts = hh.get_partitions(schema='airflow', table_name=t)
>>> len(parts)
1
>>> parts
[{'ds': '2015-01-01'}]


def get_results(self, hql, schema='<STR_LIT:default>', fetch_size=None, hive_conf=None):

results_iter = self._get_results(hql, schema,<EOL>fetch_size=fetch_size, hive_conf=hive_conf)<EOL>header = next(results_iter)<EOL>results = {<EOL>'<STR_LIT:data>': list(results_iter),<EOL>'<STR_LIT>': header<EOL>}<EOL>return results<EOL>

Get results of the provided hql in target schema.

:param hql: hql to be executed.
:type hql: str or list
:param schema: target schema, default to 'default'.
:type schema: str
:param fetch_size: max size of result to fetch.
:type fetch_size: int
:param hive_conf: hive_conf to execute alone with the hql.
:type hive_conf: dict
:return: results of hql execution, dict with data (list of results) and header
:rtype: dict


def table_exists(self, table_name, db='<STR_LIT:default>'):

try:<EOL><INDENT>self.get_table(table_name, db)<EOL>return True<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>

Check if table exists

>>> hh = HiveMetastoreHook()
>>> hh.table_exists(db='airflow', table_name='static_babynames')
True
>>> hh.table_exists(db='airflow', table_name='does_not_exist')
False


self.date_flag = date_flag<EOL>


dag = get_dag(args)<EOL>dr = DagRun.find(dag.dag_id, execution_date=args.execution_date)<EOL>print(dr[<NUM_LIT:0>].state if len(dr) > <NUM_LIT:0> else None)<EOL>

Returns the state of a DagRun at the command line.
>>> airflow dag_state tutorial 2015-01-01T00:00:00.000000
running


process = subprocess.Popen(<EOL>shlex.split(command),<EOL>stdout=subprocess.PIPE,<EOL>stderr=subprocess.PIPE,<EOL>close_fds=True)<EOL>output, stderr = [stream.decode(sys.getdefaultencoding(), '<STR_LIT:ignore>')<EOL>for stream in process.communicate()]<EOL>if process.returncode != <NUM_LIT:0>:<EOL><INDENT>raise AirflowConfigException(<EOL>"<STR_LIT>"<EOL>.format(command, process.returncode, output, stderr)<EOL>)<EOL><DEDENT>return output<EOL>


raise NotImplementedError()<EOL>


def create_pool(self, name, slots, description):

raise NotImplementedError()<EOL>

Create a pool.

        :param name: pool name
        :param slots: pool slots amount
        :param description: pool description


dagbag = DagBag()<EOL>if dag_id not in dagbag.dags:<EOL><INDENT>error_message = "<STR_LIT>".format(dag_id)<EOL>raise DagNotFound(error_message)<EOL><DEDENT>dag = dagbag.get_dag(dag_id)<EOL>dagrun = dag.get_dagrun(execution_date=execution_date)<EOL>if not dagrun:<EOL><INDENT>error_message = ('<STR_LIT>'<EOL>.format(execution_date, dag_id))<EOL>raise DagRunNotFound(error_message)<EOL><DEDENT>return {'<STR_LIT:state>': dagrun.get_state()}<EOL>

Return the task object identified by the given dag_id and task_id.


return value_2<EOL>

Pushes an XCom without a specific target, just by returning it


def ds_format(ds, input_format, output_format):

return datetime.strptime(ds, input_format).strftime(output_format)<EOL>

Takes an input string and outputs another string
as specified in the output format

:param ds: input string which contains a date
:type ds: str
:param input_format: input string format. E.g. %Y-%m-%d
:type input_format: str
:param output_format: output string format  E.g. %Y-%m-%d
:type output_format: str

>>> ds_format('2015-01-01', "%Y-%m-%d", "%m-%d-%y")
'01-01-15'
>>> ds_format('1/5/2015', "%m/%d/%Y",  "%Y-%m-%d")
'2015-01-05'


def closest_ds_partition(<EOL>table, ds, before=True, schema="<STR_LIT:default>",<EOL>metastore_conn_id='<STR_LIT>'):

from airflow.hooks.hive_hooks import HiveMetastoreHook<EOL>if '<STR_LIT:.>' in table:<EOL><INDENT>schema, table = table.split('<STR_LIT:.>')<EOL><DEDENT>hh = HiveMetastoreHook(metastore_conn_id=metastore_conn_id)<EOL>partitions = hh.get_partitions(schema=schema, table_name=table)<EOL>if not partitions:<EOL><INDENT>return None<EOL><DEDENT>part_vals = [list(p.values())[<NUM_LIT:0>] for p in partitions]<EOL>if ds in part_vals:<EOL><INDENT>return ds<EOL><DEDENT>else:<EOL><INDENT>parts = [datetime.datetime.strptime(pv, '<STR_LIT>')<EOL>for pv in part_vals]<EOL>target_dt = datetime.datetime.strptime(ds, '<STR_LIT>')<EOL>closest_ds = _closest_date(target_dt, parts, before_target=before)<EOL>return closest_ds.isoformat()<EOL><DEDENT>

This function finds the date in a list closest to the target date.
An optional parameter can be given to get the closest before or after.

:param table: A hive table name
:type table: str
:param ds: A datestamp ``%Y-%m-%d`` e.g. ``yyyy-mm-dd``
:type ds: list[datetime.date]
:param before: closest before (True), after (False) or either side of ds
:type before: bool or None
:returns: The closest date
:rtype: str or None

>>> tbl = 'airflow.static_babynames_partitioned'
>>> closest_ds_partition(tbl, '2015-01-02')
'2015-01-01'


if DAGS_FOLDER not in sys.path:<EOL><INDENT>sys.path.append(DAGS_FOLDER)<EOL><DEDENT>config_path = os.path.join(AIRFLOW_HOME, '<STR_LIT>')<EOL>if config_path not in sys.path:<EOL><INDENT>sys.path.append(config_path)<EOL><DEDENT>if PLUGINS_FOLDER not in sys.path:<EOL><INDENT>sys.path.append(PLUGINS_FOLDER)<EOL><DEDENT>

Ensures that certain subfolders of AIRFLOW_HOME are on the classpath


global DEFAULT_EXECUTOR<EOL>if DEFAULT_EXECUTOR is not None:<EOL><INDENT>return DEFAULT_EXECUTOR<EOL><DEDENT>executor_name = configuration.conf.get('<STR_LIT>', '<STR_LIT>')<EOL>DEFAULT_EXECUTOR = _get_executor(executor_name)<EOL>log = LoggingMixin().log<EOL>log.info("<STR_LIT>", executor_name)<EOL>return DEFAULT_EXECUTOR<EOL>

Creates a new instance of the configured executor if none exists and returns it


self.parallelism = parallelism<EOL>self.queued_tasks = OrderedDict()<EOL>self.running = {}<EOL>self.event_buffer = {}<EOL>

Class to derive in order to interface with executor-type systems
like Celery, Yarn and the likes.

:param parallelism: how many jobs should run at one time. Set to
    ``0`` for infinity
:type parallelism: int


if task_instance.key in self.queued_tasks or task_instance.key in self.running:<EOL><INDENT>return True<EOL><DEDENT>

Checks if a task is either queued or running in this executor

:param task_instance: TaskInstance
:return: True if the task is known to this executor


return max(<NUM_LIT:1>,<EOL>int(math.ceil(<NUM_LIT:1.0> * to_send_count / self._sync_parallelism)))<EOL>

How many Celery tasks should each worker process send.

:return: Number of tasks that should be sent per process
:rtype: int


raise AirflowException('<STR_LIT>')<EOL>

Function that the sensors defined while deriving this class should
override.


raise NotImplementedError()<EOL>

:return: maximum number of tasks that can run simultaneously from this DAG
:rtype: int


raise NotImplementedError()<EOL>

:return: A list of task IDs that are in this DAG
:rtype: List[unicode]


def construct_ingest_query(self, static_path, columns):

<EOL>num_shards = self.num_shards<EOL>target_partition_size = self.target_partition_size<EOL>if self.target_partition_size == -<NUM_LIT:1>:<EOL><INDENT>if self.num_shards == -<NUM_LIT:1>:<EOL><INDENT>target_partition_size = DEFAULT_TARGET_PARTITION_SIZE<EOL><DEDENT><DEDENT>else:<EOL><INDENT>num_shards = -<NUM_LIT:1><EOL><DEDENT>metric_names = [m['<STR_LIT>'] for m in self.metric_spec if m['<STR_LIT:type>'] != '<STR_LIT:count>']<EOL>dimensions = [c for c in columns if c not in metric_names and c != self.ts_dim]<EOL>ingest_query_dict = {<EOL>"<STR_LIT:type>": "<STR_LIT>",<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": self.metric_spec,<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": self.query_granularity,<EOL>"<STR_LIT>": self.intervals,<EOL>"<STR_LIT:type>": "<STR_LIT>",<EOL>"<STR_LIT>": self.segment_granularity,<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT:type>": "<STR_LIT:string>",<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": columns,<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": [],<EOL>"<STR_LIT>": dimensions,  <EOL>"<STR_LIT>": []<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": self.ts_dim,<EOL>"<STR_LIT>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT>": "<STR_LIT>"<EOL>}<EOL>},<EOL>"<STR_LIT>": self.druid_datasource<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT:type>": "<STR_LIT>",<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": "<STR_LIT:false>",<EOL>"<STR_LIT>": "<STR_LIT:false>",<EOL>"<STR_LIT>": "<STR_LIT:false>",<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT:type>": "<STR_LIT>",<EOL>"<STR_LIT>": target_partition_size,<EOL>"<STR_LIT>": num_shards,<EOL>},<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": static_path,<EOL>"<STR_LIT:type>": "<STR_LIT>"<EOL>},<EOL>"<STR_LIT:type>": "<STR_LIT>"<EOL>}<EOL>}<EOL>}<EOL>if self.job_properties:<EOL><INDENT>ingest_query_dict['<STR_LIT>']['<STR_LIT>']['<STR_LIT>'].update(self.job_properties)<EOL><DEDENT>if self.hadoop_dependency_coordinates:<EOL><INDENT>ingest_query_dict['<STR_LIT>']= self.hadoop_dependency_coordinates<EOL><DEDENT>return ingest_query_dict<EOL>

Builds an ingest query for an HDFS TSV load.

:param static_path: The path on hdfs where the data is
:type static_path: str
:param columns: List of all the columns that are available
:type columns: list


try:<EOL><INDENT>ret = float(s)<EOL><DEDENT>except (ValueError, TypeError):<EOL><INDENT>ret = s<EOL><DEDENT>return ret<EOL>

A small helper function to convert a string to a numeric value
if appropriate

:param s: the string to be converted
:type s: str


return DruidDbApiHook(druid_broker_conn_id=self.druid_broker_conn_id)<EOL>


def template_field_role(app, typ, rawtext, text, lineno, inliner, options={}, content=[]):

text = utils.unescape(text)<EOL>try:<EOL><INDENT>template_fields = get_template_field(app.env, text)<EOL><DEDENT>except RoleException as e:<EOL><INDENT>msg = inliner.reporter.error("<STR_LIT>" % (text, e, ), line=lineno)<EOL>prb = inliner.problematic(rawtext, rawtext, msg)<EOL>return [prb], [msg]<EOL><DEDENT>node = nodes.inline(rawtext=rawtext)<EOL>for i, field in enumerate(template_fields):<EOL><INDENT>if i != <NUM_LIT:0>:<EOL><INDENT>node += nodes.Text("<STR_LIT:U+002CU+0020>")<EOL><DEDENT>node += nodes.literal(field, "<STR_LIT>", nodes.Text(field))<EOL><DEDENT>return [node], []<EOL>

A role that allows you to include a list of template fields in the middle of the text. This is especially
useful when writing guides describing how to use the operator.
The result is a list of fields where each field is shorted in the literal block.

Sample usage::

:template-fields:`airflow.contrib.operators.gcp_natural_language_operator.CloudLanguageAnalyzeSentimentOperator`

For further information look at:

* [http://docutils.sourceforge.net/docs/howto/rst-roles.html](Creating reStructuredText Interpreted
  Text Roles)


def tube_hires(script, height=<NUM_LIT:1.0>, radius=None, radius1=None, radius2=None,<EOL>diameter=None, diameter1=None, diameter2=None, cir_segments=<NUM_LIT:32>,<EOL>rad_segments=<NUM_LIT:1>, height_segments=<NUM_LIT:1>, center=False,<EOL>simple_bottom=False, color=None):

<EOL>if radius is not None and diameter is None:<EOL><INDENT>if radius1 is None and diameter1 is None:<EOL><INDENT>radius1 = radius<EOL><DEDENT>if radius2 is None and diameter2 is None:<EOL><INDENT>radius2 = <NUM_LIT:0><EOL><DEDENT><DEDENT>if diameter is not None:<EOL><INDENT>if radius1 is None and diameter1 is None:<EOL><INDENT>radius1 = diameter / <NUM_LIT:2><EOL><DEDENT>if radius2 is None and diameter2 is None:<EOL><INDENT>radius2 = <NUM_LIT:0><EOL><DEDENT><DEDENT>if diameter1 is not None:<EOL><INDENT>radius1 = diameter1 / <NUM_LIT:2><EOL><DEDENT>if diameter2 is not None:<EOL><INDENT>radius2 = diameter2 / <NUM_LIT:2><EOL><DEDENT>if radius1 is None:<EOL><INDENT>radius1 = <NUM_LIT:1><EOL><DEDENT>if radius2 is None:<EOL><INDENT>radius2 = <NUM_LIT:0><EOL><DEDENT>annulus_hires(script,<EOL>radius1=radius1,<EOL>radius2=radius2,<EOL>cir_segments=cir_segments,<EOL>rad_segments=rad_segments)<EOL>transform.translate(script, [<NUM_LIT:0>, <NUM_LIT:0>, height])<EOL>if simple_bottom:<EOL><INDENT>annulus(script,<EOL>radius1=radius1,<EOL>radius2=radius2,<EOL>cir_segments=cir_segments)<EOL><DEDENT>else:<EOL><INDENT>layers.duplicate(script)<EOL>transform.translate(script, [<NUM_LIT:0>, <NUM_LIT:0>, -height])<EOL><DEDENT>transform.rotate(script, '<STR_LIT:x>', <NUM_LIT>)<EOL>cylinder_open_hires(script, height, radius1,<EOL>cir_segments=cir_segments,<EOL>height_segments=height_segments)<EOL>if radius2 != <NUM_LIT:0>:<EOL><INDENT>cylinder_open_hires(script, height, radius2,<EOL>cir_segments=cir_segments,<EOL>height_segments=height_segments,<EOL>invert_normals=True)<EOL><DEDENT>layers.join(script)<EOL>clean.merge_vert(script, threshold=<NUM_LIT>)<EOL>if center:<EOL><INDENT>transform.translate(script, [<NUM_LIT:0>, <NUM_LIT:0>, -height / <NUM_LIT:2>])<EOL><DEDENT>if color is not None:<EOL><INDENT>vert_color.function(script, color=color)<EOL><DEDENT>return None<EOL>

Create a cylinder with user defined number of segments


def torus(script, major_radius=<NUM_LIT>, minor_radius=<NUM_LIT:1.0>, inner_diameter=None,<EOL>outer_diameter=None, major_segments=<NUM_LIT>, minor_segments=<NUM_LIT:12>,<EOL>color=None):

if inner_diameter is not None and outer_diameter is not None:<EOL><INDENT>major_radius = (inner_diameter + outer_diameter) / <NUM_LIT:4><EOL>minor_radius = major_radius - inner_diameter / <NUM_LIT:2><EOL><DEDENT>filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % major_radius,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % minor_radius,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % major_segments,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % minor_segments,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>if isinstance(script, FilterScript):<EOL><INDENT>script.add_layer('<STR_LIT>', change_layer=True)<EOL><DEDENT>if color is not None:<EOL><INDENT>vert_color.function(script, color=color)<EOL><DEDENT>return None<EOL>

Create a torus mesh

    Args:
        major_radius (float, (optional)): radius from the origin to the
            center of the cross sections
        minor_radius (float, (optional)): radius of the torus cross
            section
        inner_diameter (float, (optional)): inner diameter of torus. If
            both inner_diameter and outer_diameter are provided then
            these will override major_radius and minor_radius.,
        outer_diameter (float, (optional)): outer diameter of torus. If
            both inner_diameter and outer_diameter are provided then
            these will override major_radius and minor_radius.
        major_segments (int (optional)): number of segments for the main
            ring of the torus
        minor_segments (int (optional)): number of segments for the minor
            ring of the torus
        color (str (optional)): color name to apply vertex colors to the
            newly created mesh

    Returns:
        None


def cube_open_hires_old(script, size=<NUM_LIT:1.0>, x_segments=<NUM_LIT:1>, y_segments=<NUM_LIT:1>, z_segments=<NUM_LIT:1>,<EOL>center=False, color=None):

"""<STR_LIT>"""<EOL>size = util.make_list(size, <NUM_LIT:3>)<EOL>grid(script, [size[<NUM_LIT:0>], size[<NUM_LIT:2>]],<EOL>x_segments=x_segments,<EOL>y_segments=z_segments)<EOL>transform.rotate(script, '<STR_LIT:x>', <NUM_LIT>)<EOL>layers.duplicate(script)<EOL>transform.rotate(script, '<STR_LIT:z>', <NUM_LIT>)<EOL>transform.translate(script, [size[<NUM_LIT:0>], size[<NUM_LIT:1>], <NUM_LIT:0>])<EOL>grid(script, [size[<NUM_LIT:2>], size[<NUM_LIT:1>]],<EOL>x_segments=z_segments,<EOL>y_segments=y_segments)<EOL>transform.rotate(script, '<STR_LIT:y>', -<NUM_LIT>)<EOL>layers.duplicate(script)<EOL>transform.rotate(script, '<STR_LIT:z>', <NUM_LIT>)<EOL>transform.translate(script, [size[<NUM_LIT:0>], size[<NUM_LIT:1>], <NUM_LIT:0>])<EOL>layers.join(script)<EOL>clean.merge_vert(script, threshold=<NUM_LIT>)<EOL>if center:<EOL><INDENT>transform.translate(script, [-size[<NUM_LIT:0>] / <NUM_LIT:2>, -size[<NUM_LIT:1>] / <NUM_LIT:2>, -size[<NUM_LIT:2>] / <NUM_LIT:2>])<EOL><DEDENT>if color is not None:<EOL><INDENT>vert_color.function(script, color=color)<EOL><DEDENT>return None<EOL>

Creates a square open tube, e.g. a box with no top or bottom.

    Useful if you want to wrap it around and join the open ends together, forming a torus.


def cube(script, size=<NUM_LIT:1.0>, center=False, color=None):

"""<STR_LIT>"""<EOL>size = util.make_list(size, <NUM_LIT:3>)<EOL>if script.ml_version == '<STR_LIT>':<EOL><INDENT>filter_name = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>filter_name = '<STR_LIT>'<EOL><DEDENT>filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>'.format(filter_name),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>if isinstance(script, FilterScript):<EOL><INDENT>script.add_layer('<STR_LIT>', change_layer=True)<EOL><DEDENT>transform.scale(script, value=size)<EOL>if not center:<EOL><INDENT>transform.translate(script, value=[size[<NUM_LIT:0>]/<NUM_LIT:2>, size[<NUM_LIT:1>]/<NUM_LIT:2>, size[<NUM_LIT:2>]/<NUM_LIT:2>])<EOL><DEDENT>if color is not None:<EOL><INDENT>vert_color.function(script, color=color)<EOL><DEDENT>return None<EOL>

Create a cube primitive

    Note that this is made of 6 quads, not triangles


pass<EOL>

Create  doublehelix function, takes spacing between helixes and
    rungs, rung diameter


def annulus(script, radius=None, radius1=None, radius2=None, diameter=None,<EOL>diameter1=None, diameter2=None, cir_segments=<NUM_LIT:32>, color=None):

if radius is not None and diameter is None:<EOL><INDENT>if radius1 is None and diameter1 is None:<EOL><INDENT>radius1 = radius<EOL><DEDENT>if radius2 is None and diameter2 is None:<EOL><INDENT>radius2 = <NUM_LIT:0><EOL><DEDENT><DEDENT>if diameter is not None:<EOL><INDENT>if radius1 is None and diameter1 is None:<EOL><INDENT>radius1 = diameter / <NUM_LIT:2><EOL><DEDENT>if radius2 is None and diameter2 is None:<EOL><INDENT>radius2 = <NUM_LIT:0><EOL><DEDENT><DEDENT>if diameter1 is not None:<EOL><INDENT>radius1 = diameter1 / <NUM_LIT:2><EOL><DEDENT>if diameter2 is not None:<EOL><INDENT>radius2 = diameter2 / <NUM_LIT:2><EOL><DEDENT>if radius1 is None:<EOL><INDENT>radius1 = <NUM_LIT:1><EOL><DEDENT>if radius2 is None:<EOL><INDENT>radius2 = <NUM_LIT:0><EOL><DEDENT>filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % radius1,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % radius2,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % cir_segments,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>if isinstance(script, FilterScript):<EOL><INDENT>script.add_layer('<STR_LIT>', change_layer=True)<EOL><DEDENT>if color is not None:<EOL><INDENT>vert_color.function(script, color=color)<EOL><DEDENT>return None<EOL>

Create a 2D (surface) circle or annulus
    radius1=1 # Outer radius of the circle
    radius2=0 # Inner radius of the circle (if non-zero it creates an annulus)
    color="" # specify a color name to apply vertex colors to the newly created mesh

    OpenSCAD: parameters: diameter overrides radius, radius1 & radius2 override radius


def grid(script, size=<NUM_LIT:1.0>, x_segments=<NUM_LIT:1>, y_segments=<NUM_LIT:1>, center=False,<EOL>color=None):

size = util.make_list(size, <NUM_LIT:2>)<EOL>filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(size[<NUM_LIT:0>]),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(size[<NUM_LIT:1>]),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(x_segments + <NUM_LIT:1>),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(y_segments + <NUM_LIT:1>),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>if isinstance(script, FilterScript):<EOL><INDENT>script.add_layer('<STR_LIT>', change_layer=True)<EOL><DEDENT>"""<STR_LIT>"""<EOL>transform.vert_function(script, z_func='<STR_LIT>')<EOL>"""<STR_LIT>"""<EOL>if center:<EOL><INDENT>transform.translate(script, value=[size[<NUM_LIT:0>]/<NUM_LIT:2>, -size[<NUM_LIT:1>]/<NUM_LIT:2>, <NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>transform.translate(script, value=[size[<NUM_LIT:0>], <NUM_LIT:0>, <NUM_LIT:0>])<EOL><DEDENT>if color is not None:<EOL><INDENT>vert_color.function(script, color=color)<EOL><DEDENT>return None<EOL>

2D square/plane/grid created on XY plane

    x_segments # Number of segments in the X direction.
    y_segments # Number of segments in the Y direction.
    center="false" # If true square will be centered on origin;
    otherwise it is place in the positive XY quadrant.


def flip(script, force_flip=False, selected=False):

Invert faces orientation, flipping the normals of the mesh.

    If requested, it tries to guess the right orientation; mainly it decides to
    flip all the faces if the minimum/maximum vertexes have not outward point
    normals for a few directions. Works well for single component watertight
    objects.

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        force_flip (bool): If selected, the normals will always be flipped;
            otherwise, the filter tries to set them outside.
        selected (bool): If selected, only selected faces will be affected.

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


reorient(script)<EOL>flip(script)<EOL>return<EOL>

Will reorient normals & ensure they are oriented outwards

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def function(script, red=<NUM_LIT:255>, green=<NUM_LIT:255>, blue=<NUM_LIT:255>, alpha=<NUM_LIT:255>, color=None):

<EOL>if color is not None:<EOL><INDENT>red, green, blue, _ = color_name[color.lower()]<EOL><DEDENT>filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(str(red).replace('<STR_LIT:&>', '<STR_LIT>').replace('<STR_LIT:<>', '<STR_LIT>')),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(str(green).replace('<STR_LIT:&>', '<STR_LIT>').replace('<STR_LIT:<>', '<STR_LIT>')),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(str(blue).replace('<STR_LIT:&>', '<STR_LIT>').replace('<STR_LIT:<>', '<STR_LIT>')),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(str(alpha).replace('<STR_LIT:&>', '<STR_LIT>').replace('<STR_LIT:<>', '<STR_LIT>')),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>return None<EOL>

Color function using muparser lib to generate new RGBA color for every
        vertex

    Red, Green, Blue and Alpha channels may be defined by specifying a function
    for each.

    See help(mlx.muparser_ref) for muparser reference documentation.

    It's possible to use the following per-vertex variables in the expression:

    Variables (per vertex):
        x, y, z (coordinates)
        nx, ny, nz (normal)
        r, g, b, a (color)
        q (quality)
        rad (radius)
        vi (vertex index)
        vtu, vtv (texture coordinates)
        ti (texture index)
        vsel (is the vertex selected? 1 yes, 0 no)
        and all custom vertex attributes already defined by user.

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        red (str [0, 255]): function to generate red component
        green (str [0, 255]): function to generate green component
        blue (str [0, 255]): function to generate blue component
        alpha (str [0, 255]): function to generate alpha component
        color (str): name of one of the 140 HTML Color Names defined
            in CSS & SVG.
            Ref: https://en.wikipedia.org/wiki/Web_colors#X11_color_names
            If not None this will override the per component variables.

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


Split non-manifold vertices until it becomes two-manifold.

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        vert_displacement_ratio (float): When a vertex is split it is moved
            along the average vector going from its position to the centroid
            of the FF connected faces sharing it.

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def close_holes(script, hole_max_edge=<NUM_LIT:30>, selected=False,<EOL>sel_new_face=True, self_intersection=True):

Close holes smaller than a given threshold

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        hole_max_edge (int): The size is expressed as number of edges composing
            the hole boundary.
        selected (bool): Only the holes with at least one of the boundary faces
            selected are closed.
        sel_new_face (bool): After closing a hole the faces that have been
            created are left selected. Any previous selection is lost. Useful
            for example for smoothing or subdividing the newly created holes.
        self_intersection (bool): When closing an holes it tries to prevent the
            creation of faces that intersect faces adjacent to the boundary of
            the hole. It is an heuristic, non intersecting hole filling can be
            NP-complete.

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def tex2vc_2_meshes(script, source_mesh=<NUM_LIT:0>, target_mesh=<NUM_LIT:1>, max_distance=<NUM_LIT:0.5>):

if script.ml_version == '<STR_LIT>':<EOL><INDENT>filter_name = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>filter_name = '<STR_LIT>'<EOL><DEDENT>filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>'.format(filter_name),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % source_mesh,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % target_mesh,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % max_distance,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>return None<EOL>

Transfer texture colors to vertex colors (between 2 meshes)

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        source_mesh (int): The mesh with associated texture that we want to sample from
        target_mesh (int): The mesh whose vertex color will be filled according to source mesh texture
        max_distance (float): Sample points for which we do not find anything within this distance are rejected and not considered for recovering color

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


filter_xml = '<STR_LIT>'<EOL>util.write_filter(script, filter_xml)<EOL>return None<EOL>

Transfer vertex colors to face colors

    Args:
        script: the FilterScript object or script filename to write
            the filter to.


Transfer face colors to vertex colors

    Args:
        script: the FilterScript object or script filename to write
            the filter to.


def vert_attr2tex_2_meshes(script, source_mesh=<NUM_LIT:0>, target_mesh=<NUM_LIT:1>, attribute=<NUM_LIT:0>,<EOL>max_distance=<NUM_LIT:0.5>, tex_name='<STR_LIT>',<EOL>tex_width=<NUM_LIT>, tex_height=<NUM_LIT>,<EOL>overwrite_tex=True, assign_tex=False,<EOL>fill_tex=True):

if script.ml_version == '<STR_LIT>':<EOL><INDENT>filter_name = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>filter_name = '<STR_LIT>'<EOL><DEDENT>filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>'.format(filter_name),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % source_mesh,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % target_mesh,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % attribute,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % max_distance,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % tex_name,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % tex_width,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % tex_height,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(overwrite_tex).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(assign_tex).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(fill_tex).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>return None<EOL>

Transfer Vertex Attributes to Texture (between 2 meshes)

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        source_mesh (int): The mesh that contains the source data that we want to transfer
        target_mesh (int): The mesh whose texture will be filled according to source mesh data
        attribute (int): Choose what attribute has to be transferred onto the target texture. You can choose between Per vertex attributes (color, normal, quality) or to transfer color information from source mesh texture
        max_distance (float): Sample points for which we do not find anything within this distance are rejected and not considered for recovering data
        tex_name (str): The texture file to be created
        tex_width (int): The texture width
        tex_height (int): The texture height
        overwrite_tex (bool): If target mesh has a texture will be overwritten (with provided texture dimension)
        assign_tex (bool): Assign the newly created texture to target mesh
        fill_tex (bool): If enabled the unmapped texture space is colored using a pull push filling algorithm, if false is set to black

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def measure_section(fbasename=None, log=None, axis='<STR_LIT:z>', offset=<NUM_LIT:0.0>,<EOL>rotate_x_angle=None, ml_version=ml_version):

ml_script1_file = '<STR_LIT>'<EOL>file_out = '<STR_LIT>'<EOL>ml_script1 = mlx.FilterScript(file_in=fbasename, file_out=file_out, ml_version=ml_version)<EOL>if rotate_x_angle is not None:<EOL><INDENT>transform.rotate(ml_script1, axis='<STR_LIT:x>', angle=rotate_x_angle)<EOL><DEDENT>compute.section(ml_script1, axis=axis, offset=offset)<EOL>layers.delete_lower(ml_script1)<EOL>ml_script1.save_to_file(ml_script1_file)<EOL>ml_script1.run_script(log=log, script_file=ml_script1_file)<EOL>aabb = measure_aabb(file_out, log)<EOL>return aabb<EOL>

Measure a cross section of a mesh

    Perform a plane cut in one of the major axes (X, Y, Z). If you want to cut on
    a different plane you will need to rotate the model in place, perform the cut,
    and rotate it back.

    Args:
        fbasename (str): filename of input model
        log (str): filename of log file
        axis (str): axis perpendicular to the cutting plane, e.g. specify "z" to cut
            parallel to the XY plane.
        offset (float): amount to offset the cutting plane from the origin
        rotate_x_angle (float): degrees to rotate about the X axis. Useful for correcting "Up" direction: 90 to rotate Y to Z, and -90 to rotate Z to Y.

    Returns:
        dict: dictionary with the following keys for the aabb of the section:
            min (list): list of the x, y & z minimum values
            max (list): list of the x, y & z maximum values
            center (list): the x, y & z coordinates of the center of the aabb
            size (list): list of the x, y & z sizes (max - min)
            diagonal (float): the diagonal of the aabb


fext = os.path.splitext(fbasename)[<NUM_LIT:1>][<NUM_LIT:1>:].strip().lower()<EOL>if fext != '<STR_LIT>':<EOL><INDENT>print('<STR_LIT>')<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>fread = open(fbasename, '<STR_LIT:r>')<EOL>first = True<EOL>polyline_vertices = []<EOL>line_segments = []<EOL>for line in fread:<EOL><INDENT>element, x_co, y_co, z_co = line.split()<EOL>if element == '<STR_LIT:v>':<EOL><INDENT>polyline_vertices.append(<EOL>[util.to_float(x_co), util.to_float(y_co), util.to_float(z_co)])<EOL><DEDENT>elif element == '<STR_LIT:l>':<EOL><INDENT>p1 = x_co<EOL>p2 = y_co<EOL>line_segments.append([int(p1), int(p2)])<EOL><DEDENT><DEDENT>fread.close()<EOL>if log is not None:<EOL><INDENT>log_file = open(log, '<STR_LIT:a>')<EOL>"""<STR_LIT>"""<EOL>log_file.close()<EOL><DEDENT>return None<EOL>

Sort separate line segments in obj format into a continuous polyline or polylines.
    NOT FINISHED; DO NOT USE

    Also measures the length of each polyline

    Return polyline and polylineMeta (lengths)


def measure_dimension(fbasename=None, log=None, axis1=None, offset1=<NUM_LIT:0.0>,<EOL>axis2=None, offset2=<NUM_LIT:0.0>, ml_version=ml_version):

axis1 = axis1.lower()<EOL>axis2 = axis2.lower()<EOL>ml_script1_file = '<STR_LIT>'<EOL>file_out = '<STR_LIT>'<EOL>ml_script1 = mlx.FilterScript(file_in=fbasename, file_out=file_out, ml_version=ml_version)<EOL>compute.section(ml_script1, axis1, offset1, surface=True)<EOL>compute.section(ml_script1, axis2, offset2, surface=False)<EOL>layers.delete_lower(ml_script1)<EOL>ml_script1.save_to_file(ml_script1_file)<EOL>ml_script1.run_script(log=log, script_file=ml_script1_file)<EOL>for val in ('<STR_LIT:x>', '<STR_LIT:y>', '<STR_LIT:z>'):<EOL><INDENT>if val not in (axis1, axis2):<EOL><INDENT>axis = val<EOL><DEDENT><DEDENT>axis_num = ord(axis) - ord('<STR_LIT:x>')<EOL>aabb = measure_aabb(file_out, log)<EOL>dimension = {'<STR_LIT>': aabb['<STR_LIT>'][axis_num], '<STR_LIT>': aabb['<STR_LIT>'][axis_num],<EOL>'<STR_LIT>': aabb['<STR_LIT:size>'][axis_num], '<STR_LIT>': axis}<EOL>if log is None:<EOL><INDENT>print('<STR_LIT>' % fbasename)<EOL>print('<STR_LIT>' % (axis, axis1, offset1,<EOL>axis2, offset2))<EOL>print('<STR_LIT>' % (dimension['<STR_LIT>'],<EOL>dimension['<STR_LIT>'], dimension['<STR_LIT>']))<EOL><DEDENT>else:<EOL><INDENT>log_file = open(log, '<STR_LIT:a>')<EOL>log_file.write('<STR_LIT>' % fbasename)<EOL>log_file.write('<STR_LIT>' % (axis, axis1, offset1,<EOL>axis2, offset2))<EOL>log_file.write('<STR_LIT>' % dimension['<STR_LIT>'])<EOL>log_file.write('<STR_LIT>' % dimension['<STR_LIT>'])<EOL>log_file.write('<STR_LIT>' % dimension['<STR_LIT>'])<EOL>log_file.close()<EOL><DEDENT>return dimension<EOL>


"""<STR_LIT>"""<EOL>value = util.make_list(value, <NUM_LIT:3>)<EOL>vert_function(script,<EOL>x_func='<STR_LIT>' % value[<NUM_LIT:0>],<EOL>y_func='<STR_LIT>' % value[<NUM_LIT:1>],<EOL>z_func='<STR_LIT>' % value[<NUM_LIT:2>])<EOL>return None<EOL>

An alternative scale implementation that uses a geometric function.
    This is more accurate than the built-in version.


def deform2curve(script, curve=mp_func.torus_knot('<STR_LIT:t>'), step=<NUM_LIT>):

curve_step = []<EOL>for idx, val in enumerate(curve):<EOL><INDENT>curve[idx] = val.replace('<STR_LIT:t>', '<STR_LIT:z>')<EOL>curve_step.append(val.replace('<STR_LIT:t>', '<STR_LIT>'.format(step)))<EOL><DEDENT>tangent = mp_func.v_subtract(curve_step, curve)<EOL>normal1 = mp_func.v_add(curve_step, curve)<EOL>bee = mp_func.v_cross(tangent, normal1)<EOL>normal = mp_func.v_cross(bee, tangent)<EOL>bee = mp_func.v_normalize(bee)<EOL>normal = mp_func.v_normalize(normal)<EOL>new_point = mp_func.v_add(mp_func.v_multiply('<STR_LIT:x>', normal), mp_func.v_multiply('<STR_LIT:y>', bee))<EOL>function = mp_func.v_add(curve, new_point)<EOL>vert_function(script, x_func=function[<NUM_LIT:0>], y_func=function[<NUM_LIT:1>], z_func=function[<NUM_LIT:2>])<EOL>return function<EOL>

Deform a mesh along a parametric curve function

    Provide a parametric curve function with z as the parameter. This will
    deform the xy cross section of the mesh along the curve as z increases.

    Source: http://blackpawn.com/texts/pqtorus/

    Methodology:
    T  = P' - P
    N1 = P' + P
    B  = T x N1
    N  = B x T

    newPoint = point.x*N + point.y*B


def vert_function(script, x_func='<STR_LIT:x>', y_func='<STR_LIT:y>', z_func='<STR_LIT:z>', selected=False):

Geometric function using muparser lib to generate new Coordinates

    You can change x, y, z for every vertex according to the function specified.

    See help(mlx.muparser_ref) for muparser reference documentation.
    It's possible to use the following per-vertex variables in the expression:

    Variables (per vertex):
        x, y, z (coordinates)
        nx, ny, nz (normal)
        r, g, b, a (color)
        q (quality)
        rad (radius)
        vi (vertex index)
        vtu, vtv (texture coordinates)
        ti (texture index)
        vsel (is the vertex selected? 1 yes, 0 no)
        and all custom vertex attributes already defined by user.

    Args:
        x_func (str): function to generate new coordinates for x
        y_func (str): function to generate new coordinates for y
        z_func (str): function to generate new coordinates for z
        selected (bool): if True, only affects selected vertices (ML ver 2016.12 & up)

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def radial_flare(script, flare_radius=None, start_radius=None, end_radius=None,<EOL>end_height=None):

<EOL>effective_radius = '<STR_LIT>'<EOL>r_func = '<STR_LIT>'<EOL>z_func = '<STR_LIT>'<EOL>r_func = r_func.replace('<STR_LIT>', str(effective_radius)).replace('<STR_LIT>', str(start_radius)).replace('<STR_LIT>', str(flare_radius))<EOL>z_func = z_func.replace('<STR_LIT>', str(effective_radius)).replace('<STR_LIT>', str(start_radius)).replace('<STR_LIT>', str(flare_radius))<EOL>function_cyl_co(script=script, r_func=r_func, z_func=z_func)<EOL>return None<EOL>


def butterfly(script, iterations=<NUM_LIT:1>, edge_threshold=<NUM_LIT:0>, selected=False):

Apply Butterfly Subdivision Surface algorithm.

    It is an interpolated method, defined on arbitrary triangular meshes.
    The scheme is known to be C1 but not C2 on regular meshes.

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        iterations (int): Number of times the model is subdivided.
        edge_threshold (float): All the edges longer than this threshold will
            be refined. Setting this value to zero will force a uniform
            refinement.
        selected (bool): If selected the filter is performed only on the
            selected faces.

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


Apply the Catmull-Clark Subdivision Surfaces.

    Note that position of the new vertices is simply linearly interpolated.
    If the mesh is triangle based (no faux edges) it generates a quad mesh,
    otherwise it honors the faux-edge bits.

    Args:
        script: the FilterScript object or script filename to write
            the filter to.

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def curvature_flipping(script, angle_threshold=<NUM_LIT:1.0>, curve_type=<NUM_LIT:0>,<EOL>selected=False):

Use the points and normals to build a surface using the Poisson
        Surface reconstruction approach.

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        angle_threshold (float): To avoid excessive flipping/swapping we
            consider only couple of faces with a significant diedral angle
            (e.g. greater than the indicated threshold).
        curve_type (int): Choose a metric to compute surface curvature on vertices
            H = mean curv, K = gaussian curv, A = area per vertex
            1: Mean curvature = H
            2: Norm squared mean curvature = (H * H) / A
            3: Absolute curvature:
                if(K >= 0) return 2 * H
                else return 2 * sqrt(H ^ 2 - A * K)

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def simplify(script, texture=True, faces=<NUM_LIT>, target_perc=<NUM_LIT:0.0>,<EOL>quality_thr=<NUM_LIT>, preserve_boundary=False, boundary_weight=<NUM_LIT:1.0>,<EOL>optimal_placement=True, preserve_normal=False,<EOL>planar_quadric=False, selected=False, extra_tex_coord_weight=<NUM_LIT:1.0>,<EOL>preserve_topology=True, quality_weight=False, autoclean=True):

Simplify a mesh using a Quadric based Edge Collapse Strategy, better
        than clustering but slower. Optionally tries to preserve UV
        parametrization for textured meshes.

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        texture (bool):
        faces (int): The desired final number of faces
        target_perc (float): If non zero, this parameter specifies the desired
            final size of the mesh as a percentage of the initial mesh size.
        quality_thr (float): Quality threshold for penalizing bad shaped faces.
            The value is in the range [0..1]0 accept any kind of face (no
            penalties), 0.5 penalize faces with quality less than 0.5,
            proportionally to their shape.
        preserve_boundary (bool): The simplification process tries not to
            affect mesh boundaries
        boundary_weight (float): The importance of the boundary during
            simplification. Default (1.0) means that the boundary has the same
            importance of the rest. Values greater than 1.0 raise boundary
            importance and has the effect of removing less vertices on the
            border. Admitted range of values (0,+inf).
        optimal_placement (bool): Each collapsed vertex is placed in the
            position minimizing the quadric error. It can fail (creating bad
            spikes) in case of very flat areas. If disabled edges are collapsed
            onto one of the two original vertices and the final mesh is
            composed by a subset of the original vertices.
        preserve_normal (bool): Try to avoid face flipping effects and try to
            preserve the original orientation of the surface.
        planar_quadric (bool): Add additional simplification constraints that
            improves the quality of the simplification of the planar portion of
            the mesh.
        selected (bool): The simplification is applied only to the selected set
            of faces. Take care of the target number of faces!
        extra_tex_coord_weight (float): Additional weight for each extra
            Texture Coordinates for every (selected) vertex. Ignored if texture
            is False.
        preserve_topology (bool): Avoid all the collapses that should cause a
            topology change in the mesh (like closing holes, squeezing handles,
            etc). If checked the genus of the mesh should stay unchanged.
        quality_weight (bool): Use the Per-Vertex quality as a weighting factor
            for the simplification. The weight is used as a error amplification
            value, so a vertex with a high quality value will not be simplified
            and a portion of the mesh with low quality values will be
            aggressively simplified.
        autoclean (bool): After the simplification an additional set of steps
            is performed to clean the mesh (unreferenced vertices, bad faces,
            etc).

    Layer stack:
        Unchanged; current mesh is simplified in place.

    MeshLab versions:
        2016.12 (different filter name)
        1.3.4BETA


def cylindrical_vert(script, radius=<NUM_LIT:1.0>, inside=True):

if inside:<EOL><INDENT>function = '<STR_LIT>'.format(radius)<EOL><DEDENT>else:<EOL><INDENT>function = '<STR_LIT>'.format(radius)<EOL><DEDENT>vert_function(script, function=function)<EOL>return None<EOL>

Select all vertices within a cylindrical radius

    Args:
        radius (float): radius of the sphere
        center_pt (3 coordinate tuple or list): center point of the sphere

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


filter_xml = '<STR_LIT>'<EOL>for _ in range(iterations):<EOL><INDENT>util.write_filter(script, filter_xml)<EOL><DEDENT>return None<EOL>

Grow (dilate, expand) the current set of selected faces

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        iterations (int): the number of times to grow the selection.

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


Clear the current set of selected faces

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        faces (bool): If True the filter will deselect all the faces.
        verts (bool): If True the filter will deselect all the vertices.

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def spherical_vert(script, radius=<NUM_LIT:1.0>, center_pt=(<NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>)):

function = '<STR_LIT>'.format(<EOL>center_pt[<NUM_LIT:0>], center_pt[<NUM_LIT:1>], center_pt[<NUM_LIT:2>], radius)<EOL>vert_function(script, function=function)<EOL>return None<EOL>

Select all vertices within a spherical radius

    Args:
        radius (float): radius of the sphere
        center_pt (3 coordinate tuple or list): center point of the sphere

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def vert_function(script, function='<STR_LIT>', strict_face_select=True):

if script.ml_version == '<STR_LIT>':<EOL><INDENT>strict_select = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(str(strict_face_select).lower()),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>])<EOL><DEDENT>else:<EOL><INDENT>strict_select = '<STR_LIT>'<EOL><DEDENT>filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(str(function).replace('<STR_LIT:&>', '<STR_LIT>').replace('<STR_LIT:<>', '<STR_LIT>')),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>strict_select,<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>return None<EOL>

Boolean function using muparser lib to perform vertex selection over current mesh.

    See help(mlx.muparser_ref) for muparser reference documentation.

    It's possible to use parenthesis, per-vertex variables and boolean operator:
        (, ), and, or, <, >, =
    It's possible to use the following per-vertex variables in the expression:

    Variables:
        x, y, z (coordinates)
        nx, ny, nz (normal)
        r, g, b, a (color)
        q (quality)
        rad
        vi (vertex index)
        vtu, vtv (texture coordinates)
        ti (texture index)
        vsel (is the vertex selected? 1 yes, 0 no)
        and all custom vertex attributes already defined by user.

    Args:
        script: the FilterScript object or script filename to write
            the filter] to.
        function (str): a boolean function that will be evaluated in order
            to select a subset of vertices. Example: (y > 0) and (ny > 0)
        strict_face_select (bool): if True a face is selected if ALL its
            vertices are selected. If False a face is selected if at least
            one of its vertices is selected. ML v1.3.4BETA only; this is
            ignored in 2016.12. In 2016.12 only vertices are selected.

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def invert(script, face=True, vert=True):

Invert the current set of selected faces

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        faces (bool): If True the filter will invert the selected faces.
        verts (bool): If True the filter will invert the selected vertices.

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def small_parts(script, ratio=<NUM_LIT>, non_closed_only=False):

Select the small disconnected parts (components) of a mesh.

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        ratio (float): This ratio (between 0 and 1) defines the meaning of
            'small' as the threshold ratio between the number of faces of the
            largest component and the other ones. A larger value will select
            more components.
        non_closed_only (bool): Select only non-closed components.

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def taubin(script, iterations=<NUM_LIT:10>, t_lambda=<NUM_LIT:0.5>, t_mu=-<NUM_LIT>, selected=False):

The lambda & mu Taubin smoothing, it make two steps of smoothing, forth
        and back, for each iteration.

    Based on:
    Gabriel Taubin
    "A signal processing approach to fair surface design"
    Siggraph 1995

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        iterations (int): The number of times that the taubin smoothing is
            iterated. Usually it requires a larger number of iteration than the
            classical laplacian.
        t_lambda (float): The lambda parameter of the Taubin Smoothing algorithm
        t_mu (float): The mu parameter of the Taubin Smoothing algorithm
        selected (bool): If selected the filter is performed only on the
            selected faces

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


HC Laplacian Smoothing, extended version of Laplacian Smoothing, based
        on the paper of Vollmer, Mencl, and Muller

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def laplacian(script, iterations=<NUM_LIT:1>, boundary=True, cotangent_weight=True,<EOL>selected=False):

Laplacian smooth of the mesh: for each vertex it calculates the average
        position with nearest vertex

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        iterations (int): The number of times that the whole algorithm (normal
            smoothing + vertex fitting) is iterated.
        boundary (bool): If true the boundary edges are smoothed only by
            themselves (e.g. the polyline forming the boundary of the mesh is
            independently smoothed). Can reduce the shrinking on the border but
            can have strange effects on very small boundaries.
        cotangent_weight (bool): If True the cotangent weighting scheme is
            computed for the averaging of the position. Otherwise (False) the
            simpler umbrella scheme (1 if the edge is present) is used.
        selected (bool): If selected the filter is performed only on the
            selected faces

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def join(script, merge_visible=True, merge_vert=False, delete_layer=True,<EOL>keep_unreferenced_vert=False):

Flatten all or only the visible layers into a single new mesh.

    Transformations are preserved. Existing layers can be optionally
    deleted.

    Args:
        script: the mlx.FilterScript object or script filename to write
            the filter to.
        merge_visible (bool): merge only visible layers
        merge_vert (bool): merge the vertices that are duplicated among
            different layers. Very useful when the layers are spliced portions
            of a single big mesh.
        delete_layer (bool): delete all the merged layers. If all layers are
            visible only a single layer will remain after the invocation of
            this filter.
        keep_unreferenced_vert (bool): Do not discard unreferenced vertices
            from source layers. Necessary for point-only layers.

    Layer stack:
        Creates a new layer "Merged Mesh"
        Changes current layer to the new layer
        Optionally deletes all other layers

    MeshLab versions:
        2016.12
        1.3.4BETA

    Bugs:
        UV textures: not currently preserved, however will be in a future
            release. https://github.com/cnr-isti-vclab/meshlab/issues/128
        merge_visible: it is not currently possible to change the layer
            visibility from meshlabserver, however this will be possible
            in the future https://github.com/cnr-isti-vclab/meshlab/issues/123


def rename(script, label='<STR_LIT:blank>', layer_num=None):

filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(label),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>if isinstance(script, mlx.FilterScript):<EOL><INDENT>if (layer_num is None) or (layer_num == script.current_layer()):<EOL><INDENT>util.write_filter(script, filter_xml)<EOL>script.layer_stack[script.current_layer()] = label<EOL><DEDENT>else:<EOL><INDENT>cur_layer = script.current_layer()<EOL>change(script, layer_num)<EOL>util.write_filter(script, filter_xml)<EOL>change(script, cur_layer)<EOL>script.layer_stack[layer_num] = label<EOL><DEDENT><DEDENT>else:<EOL><INDENT>util.write_filter(script, filter_xml)<EOL><DEDENT>return None<EOL>

Rename layer label

    Can be useful for outputting mlp files, as the output file names use
    the labels.

    Args:
        script: the mlx.FilterScript object or script filename to write
            the filter to.
        label (str): new label for the mesh layer
        layer_num (int): layer number to rename. Default is the
            current layer. Not supported on the file base API.

    Layer stack:
        Renames a layer

    MeshLab versions:
        2016.12
        1.3.4BETA


if layer_num is None:<EOL><INDENT>layer_num = script.current_layer()<EOL><DEDENT>if layer_num != <NUM_LIT:0>:<EOL><INDENT>change(script, <NUM_LIT:0>)<EOL><DEDENT>for i in range(layer_num):<EOL><INDENT>delete(script, <NUM_LIT:0>)<EOL><DEDENT>return None<EOL>

Delete all layers below the specified one.

    Useful for MeshLab ver 2016.12, whcih will only output layer 0.


def selected(script, face=True, vert=True):

if face and vert:<EOL><INDENT>filter_xml = '<STR_LIT>'<EOL><DEDENT>elif face and not vert:<EOL><INDENT>filter_xml = '<STR_LIT>'<EOL><DEDENT>elif not face and vert:<EOL><INDENT>filter_xml = '<STR_LIT>'<EOL><DEDENT>util.write_filter(script, filter_xml)<EOL>return None<EOL>

Delete selected vertices and/or faces

    Note: if the mesh has no faces (e.g. a point cloud) you must
    set face=False, or the vertices will not be deleted

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        face (bool): if True the selected faces will be deleted. If vert
            is also True, then all the vertices surrounded by those faces will
            also be deleted. Note that if no faces are selected (only vertices)
            then this filter will not do anything. For example, if you want to
            delete a point cloud selection, you must set this to False.
        vert (bool): if True the selected vertices will be deleted.

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


select.nonmanifold_edge(script)<EOL>selected(script, face=False)<EOL>return None<EOL>

Select & delete the faces and the vertices incident on
        non manifold edges (e.g. edges where more than two faces are incident).

    Note that this function selects the components that are related to
    non manifold edges. The case of non manifold vertices is specifically
    managed by nonmanifold_vert.

    Args:
        script: the FilterScript object or script filename to write
            the filter to.

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


select.nonmanifold_vert(script)<EOL>selected(script, face=False)<EOL>return None<EOL>

Select & delete the non manifold vertices that do not belong to
        non manifold edges.

    For example two cones connected by their apex. Vertices incident on
    non manifold edges are ignored.

    Args:
        script: the FilterScript object or script filename to write
            the filter to.

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def poisson_disk(script, sample_num=<NUM_LIT:1000>, radius=<NUM_LIT:0.0>,<EOL>montecarlo_rate=<NUM_LIT:20>, save_montecarlo=False,<EOL>approx_geodesic_dist=False, subsample=False, refine=False,<EOL>refine_layer=<NUM_LIT:0>, best_sample=True, best_sample_pool=<NUM_LIT:10>,<EOL>exact_num=False, radius_variance=<NUM_LIT:1.0>):

Create a new layer populated with a point sampling of the current mesh.

    Samples are generated according to a Poisson-disk distribution, using the
    algorithm described in:

    'Efficient and Flexible Sampling with Blue Noise Properties of Triangular Meshes'
    Massimiliano Corsini, Paolo Cignoni, Roberto Scopigno
    IEEE TVCG 2012

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        sample_num (int): The desired number of samples. The radius of the disk
            is calculated according to the sampling density.
        radius (float): If not zero this parameter overrides the previous
            parameter to allow exact radius specification.
        montecarlo_rate (int): The over-sampling rate that is used to generate
            the intial Monte Carlo samples (e.g. if this parameter is 'K' means
            that 'K * sample_num' points will be used). The generated
            Poisson-disk samples are a subset of these initial Monte Carlo
            samples. Larger numbers slow the process but make it a bit more
            accurate.
        save_montecarlo (bool): If True, it will generate an additional Layer
            with the Monte Carlo sampling that was pruned to build the Poisson
            distribution.
        approx_geodesic_dist (bool): If True Poisson-disk distances are
            computed using an approximate geodesic distance, e.g. an Euclidean
            distance weighted by a function of the difference between the
            normals of the two points.
        subsample (bool): If True the original vertices of the base mesh are
            used as base set of points. In this case the sample_num should be
            obviously much smaller than the original vertex number. Note that
            this option is very useful in the case you want to subsample a
            dense point cloud.
        refine (bool): If True the vertices of the refine_layer mesh layer are
            used as starting vertices, and they will be utterly refined by
            adding more and more points until possible.
        refine_layer (int): Used only if refine is True.
        best_sample (bool): If True it will use a simple heuristic for choosing
            the samples. At a small cost (it can slow the process a bit) it
            usually improves the maximality of the generated sampling.
        best_sample_pool (bool): Used only if best_sample is True. It controls
            the number of attempts that it makes to get the best sample. It is
            reasonable that it is smaller than the Monte Carlo oversampling
            factor.
        exact_num (bool): If True it will try to do a dicotomic search for the
            best Poisson-disk radius that will generate the requested number of
            samples with a tolerance of the 0.5%. Obviously it takes much
            longer.
        radius_variance (float): The radius of the disk is allowed to vary
            between r and r*var. If this parameter is 1 the sampling is the
            same as the Poisson-disk Sampling.

    Layer stack:
        Creates new layer 'Poisson-disk Samples'. Current layer is NOT changed
            to the new layer (see Bugs).
        If save_montecarlo is True, creates a new layer 'Montecarlo Samples'.
            Current layer is NOT changed to the new layer (see Bugs).

    MeshLab versions:
        2016.12
        1.3.4BETA

    Bugs:
        Current layer is NOT changed to the new layer, which is inconsistent
            with the majority of filters that create new layers.


def clustered_vert(script, cell_size=<NUM_LIT:1.0>, strategy='<STR_LIT>', selected=False):

if strategy.lower() == '<STR_LIT>':<EOL><INDENT>strategy_num = <NUM_LIT:0><EOL><DEDENT>elif strategy.lower() == '<STR_LIT>':<EOL><INDENT>strategy_num = <NUM_LIT:1><EOL><DEDENT>filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(cell_size),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(strategy_num),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(str(selected).lower()),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>if isinstance(script, FilterScript):<EOL><INDENT>script.add_layer('<STR_LIT>')<EOL><DEDENT>return None<EOL>

Create a new layer populated with a subsampling of the vertexes of the
        current mesh

    The subsampling is driven by a simple one-per-gridded cell strategy.

    Args:
        script: the FilterScript object or script filename to write
            the filter to.
        cell_size (float): The size of the cell of the clustering grid. Smaller the cell finer the resulting mesh. For obtaining a very coarse mesh use larger values.
        strategy (enum 'AVERAGE' or 'CENTER'): Average: for each cell we take the average of the sample falling into. The resulting point is a new point.
Closest to center: for each cell we take the sample that is closest to the center of the cell. Choosen vertices are a subset of the original ones.
        selected (bool): If true only for the filter is applied only on the selected subset of the mesh.

    Layer stack:
        Creates new layer 'Cluster Samples'. Current layer is changed to the new
            layer.

    MeshLab versions:
        2016.12
        1.3.4BETA


filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % texsize,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % textName,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(colorCorrection).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % colorCorrectionFilterSize,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(useDistanceWeight).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(useImgBorderWeight).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(useAlphaWeight).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(cleanIsolatedTriangles).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(stretchingAllowed).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % textureGutter,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>return None<EOL>


def project_rasters(script, tex_file_out="<STR_LIT>", tex_size=<NUM_LIT>,<EOL>fill_atlas_gaps=False, depth_threshold=<NUM_LIT:0.5>,<EOL>selected=False, use_angle=True, use_distance=True,<EOL>use_borders=True, use_silhouettes=True, use_alpha=False):

filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % tex_file_out,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % tex_size,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(fill_atlas_gaps).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % depth_threshold,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(selected).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(use_angle).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(use_distance).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(use_borders).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(use_silhouettes).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % str(use_alpha).lower(),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>return None<EOL>

Set texture

    Creates new texture file
    tex_file_out = must be png
    fill_atlas_gaps  = setting this to false will leave the unprojected area transparent. This can then be easily composed with the original texture with PIL


def set_texture(script, textName="<STR_LIT>", textDim=<NUM_LIT>):

filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % textName,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % textDim,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>return None<EOL>


def per_triangle(script, sidedim=<NUM_LIT:0>, textdim=<NUM_LIT>, border=<NUM_LIT:2>, method=<NUM_LIT:1>):

filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % sidedim,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % textdim,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % border,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % method,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>return None<EOL>


filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % AbsName,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>return None<EOL>

Isometric parameterization: Load Abstract Domain


filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % SamplingRate,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>return None<EOL>


def isometric_transfer(script, sourceMesh=<NUM_LIT:0>, targetMesh=<NUM_LIT:1>):

filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % sourceMesh,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % targetMesh,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>return None<EOL>

Isometric parameterization: transfer between meshes

    Provide the layer numbers of the source and target meshes.


def vert_attr(script, name='<STR_LIT>', function='<STR_LIT>'):

Add a new Per-Vertex scalar attribute to current mesh and fill it with
        the defined function.

    The specified name can be used in other filter functions.

    It's possible to use parenthesis, per-vertex variables and boolean operator:
        (, ), and, or, <, >, =
    It's possible to use the following per-vertex variables in the expression:

    Variables:
        x, y, z (coordinates)
        nx, ny, nz (normal)
        r, g, b, a (color)
        q (quality)
        rad
        vi (vertex index)
        ?vtu, vtv (texture coordinates)
        ?ti (texture index)
        ?vsel (is the vertex selected? 1 yes, 0 no)
        and all custom vertex attributes already defined by user.

    Args:
        script: the FilterScript object or script filename to write
            the filter] to.
        name (str): the name of new attribute. You can access attribute in
            other filters through this name.
        function (str): function to calculate custom attribute value for each
            vertex

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


return '<STR_LIT>'.replace(<EOL>'<STR_LIT>', str(math.pi)).replace('<STR_LIT:y>', y).replace('<STR_LIT:x>', x)<EOL>

muparser atan2 function

    Implements an atan2(y,x) function for older muparser versions (<2.1.0);
    atan2 was added as a built-in function in muparser 2.1.0

    Args:
        y (str): y argument of the atan2(y,x) function
        x (str): x argument of the atan2(y,x) function

    Returns:
        A muparser string that calculates atan2(y,x)


def face_attr(script, name='<STR_LIT>', function='<STR_LIT>'):

Add a new Per-Face attribute to current mesh and fill it with
        the defined function..

    The specified name can be used in other filter functions.

    It's possible to use parenthesis, per-face variables and boolean operator:
        (, ), and, or, <, >, =

    It's possible to use per-face variables like attributes associated to the
    three vertices of every face.

    It's possible to use the following per-face variables in the expression:

    Variables:
        x0,y0,z0 (first vertex); x1,y1,z1 (second vertex); x2,y2,z2 (third vertex)
        nx0,ny0,nz0; nx1,ny1,nz1; nx2,ny2,nz2 (normals)
        r0,g0,b0 (color)
        q0,q1,q2 (quality)
        wtu0, wtv0; wtu1, wtv1; wtu2, wtv2 (per wedge tex coord)
        fi (face index)
        ?fsel (is the vertex selected? 1 yes, 0 no)
        fi (face index)
        and all custom face attributes already defined by user.

    Args:
        script: the FilterScript object or script filename to write
            the filter] to.
        name (str): the name of new attribute. You can access attribute in
            other filters through this name.
        function (str): function to calculate custom attribute value for each
            face

    Layer stack:
        No impacts

    MeshLab versions:
        2016.12
        1.3.4BETA


def section(script, axis='<STR_LIT:z>', offset=<NUM_LIT:0.0>, surface=False, custom_axis=None,<EOL>planeref=<NUM_LIT:2>):

<EOL>if axis.lower() == '<STR_LIT:x>':<EOL><INDENT>axis_num = <NUM_LIT:0><EOL>axis_name = '<STR_LIT:X>'<EOL><DEDENT>elif axis.lower() == '<STR_LIT:y>':<EOL><INDENT>axis_num = <NUM_LIT:1><EOL>axis_name = '<STR_LIT:Y>'<EOL><DEDENT>elif axis.lower() == '<STR_LIT:z>':<EOL><INDENT>axis_num = <NUM_LIT:2><EOL>axis_name = '<STR_LIT>'<EOL><DEDENT>else:  <EOL><INDENT>axis_num = <NUM_LIT:3><EOL>axis_name = '<STR_LIT>'<EOL>if custom_axis is None:<EOL><INDENT>print('<STR_LIT>',<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>if custom_axis is None:<EOL><INDENT>custom_axis = (<NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:1.0>)<EOL><DEDENT>filter_xml = '<STR_LIT>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(axis_num),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(custom_axis[<NUM_LIT:0>], custom_axis[<NUM_LIT:1>],<EOL>custom_axis[<NUM_LIT:2>]),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(offset),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(planeref),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(str(surface).lower()),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>util.write_filter(script, filter_xml)<EOL>if isinstance(script, mlx.FilterScript):<EOL><INDENT>current_layer_label = script.layer_stack[script.current_layer()]<EOL>script.add_layer('<STR_LIT>'.format(current_layer_label, axis_name,<EOL>int(offset)))<EOL>if surface:<EOL><INDENT>script.add_layer('<STR_LIT>'.format(current_layer_label,<EOL>axis_name, int(offset)))<EOL><DEDENT><DEDENT>return None<EOL>

Compute the polyline representing a planar section (a slice) of a mesh.

    If the resulting polyline is closed the result can be filled with a
    triangular mesh representing the section.

    Args:
        script: the mlx.FilterScript object or script filename to write
            the filter to.
        axis (str): The slicing plane is perpendicular to this axis. Accepted
            values are 'x', 'y', or 'z'; any other input will be interpreted
            as a custom axis (although using 'custom' is recommended
            for clarity). Upper or lowercase values are accepted.
        offset (float): Specify an offset of the cross-plane. The offset
            corresponds to the distance along 'axis' from the point specified
            in 'planeref'.
        surface (bool): If True, in addition to a layer with the section
            polyline, also a layer with a triangulated version of the section
            polyline will be created. This only works if the section polyline
            is closed.
        custom_axis (3 component list or tuple): Specify a custom axis as
            a 3 component vector (x, y, z); this is ignored unless 'axis' is
            set  to 'custom'.
        planeref (int): Specify the reference from which the planes are
            shifted. Valid values are:
            0 - Bounding box center
            1 - Bounding box min
            2 - Origin (default)

    Layer stack:
        Creates a new layer '{label}_sect_{axis_name}_{offset}', where
            'axis_name' is one of [X, Y, Z, custom] and 'offest' is
            truncated 'offset'
        If surface is True, create a new layer '{label}_sect_{axis}_{offset}_mesh'
        Current layer is changed to the last (newly created) layer

    MeshLab versions:
        2016.12
        1.3.4BETA


def parse_hausdorff(ml_log, log=None, print_output=False):

hausdorff_distance = {"<STR_LIT>": <NUM_LIT:0.0>,<EOL>"<STR_LIT>": <NUM_LIT:0.0>,<EOL>"<STR_LIT>": <NUM_LIT:0.0>,<EOL>"<STR_LIT>": <NUM_LIT:0.0>,<EOL>"<STR_LIT>": <NUM_LIT:0>}<EOL>with open(ml_log) as fread:<EOL><INDENT>result = fread.readlines()<EOL>data = "<STR_LIT>"<EOL>for idx, line in enumerate(result):<EOL><INDENT>m = re.match(r"<STR_LIT>", line)<EOL>if m is not None:<EOL><INDENT>hausdorff_distance["<STR_LIT>"] = int(m.group(<NUM_LIT:1>))<EOL><DEDENT>if '<STR_LIT>' in line:<EOL><INDENT>data = result[idx + <NUM_LIT:2>]<EOL><DEDENT><DEDENT>m = re.match(r"<STR_LIT>", data)<EOL>hausdorff_distance["<STR_LIT>"] = float(m.group(<NUM_LIT:1>))<EOL>hausdorff_distance["<STR_LIT>"] = float(m.group(<NUM_LIT:2>))<EOL>hausdorff_distance["<STR_LIT>"] = float(m.group(<NUM_LIT:3>))<EOL>hausdorff_distance["<STR_LIT>"] = float(m.group(<NUM_LIT:4>))<EOL>for key, value in hausdorff_distance.items():<EOL><INDENT>if log is not None:<EOL><INDENT>log_file = open(log, '<STR_LIT:a>')<EOL>log_file.write('<STR_LIT>'.format(key, value))<EOL>log_file.close()<EOL><DEDENT>elif print_output:<EOL><INDENT>print('<STR_LIT>'.format(key, value))<EOL><DEDENT><DEDENT>return hausdorff_distance<EOL><DEDENT>

Parse the ml_log file generated by the hausdorff_distance function.

    Args:
        ml_log (str): MeshLab log file to parse
        log (str): filename to log output

    Returns:
        dict: dictionary with the following keys:
            number_points (int): number of points in mesh
            min_distance (float): minimum hausdorff distance
            max_distance (float): maximum hausdorff distance
            mean_distance (float): mean hausdorff distance
            rms_distance (float): root mean square distance


fext = os.path.splitext(fbasename)[<NUM_LIT:1>][<NUM_LIT:1>:].strip().lower()<EOL>material_file = None<EOL>texture_files = []<EOL>vert_colors = False<EOL>face_colors = False<EOL>if fext == '<STR_LIT>':<EOL><INDENT>with open(fbasename, '<STR_LIT:r>') as fread:<EOL><INDENT>for line in fread:<EOL><INDENT>if '<STR_LIT>' in line:<EOL><INDENT>material_file = os.path.basename(line.split()[<NUM_LIT:1>])<EOL>break<EOL><DEDENT><DEDENT><DEDENT>if material_file is not None:<EOL><INDENT>with open(material_file, '<STR_LIT:r>') as fread:<EOL><INDENT>for line in fread:<EOL><INDENT>if '<STR_LIT>' in line:<EOL><INDENT>texture_files.append(os.path.basename(line.split()[<NUM_LIT:1>]))<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>elif fext == '<STR_LIT>':<EOL><INDENT>face_element = False<EOL>with open(fbasename, '<STR_LIT:rb>') as fread:<EOL><INDENT>while True:<EOL><INDENT>line = fread.readline().strip().decode('<STR_LIT:ascii>')<EOL>if '<STR_LIT>' in line:<EOL><INDENT>face_element = True<EOL><DEDENT>if '<STR_LIT>' in line:<EOL><INDENT>if face_element:<EOL><INDENT>face_colors = True<EOL><DEDENT>else:<EOL><INDENT>vert_colors = True<EOL><DEDENT><DEDENT>if '<STR_LIT>' in line:<EOL><INDENT>texture_files.append(os.path.basename(line.split()[<NUM_LIT:2>]))<EOL><DEDENT>if '<STR_LIT>' in line:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif fext == '<STR_LIT>':  <EOL><INDENT>namespace = '<STR_LIT>'<EOL>tree = ET.parse(fbasename)<EOL>for elem in tree.findall(<EOL>'<STR_LIT>' % (namespace, namespace, namespace)):<EOL><INDENT>texture_files.append(elem.text)<EOL><DEDENT><DEDENT>elif fext == '<STR_LIT>':<EOL><INDENT>tree = ET.parse(fbasename)<EOL>for elem in tree.iter(tag='<STR_LIT>'):<EOL><INDENT>texture_files.append(elem.attrib['<STR_LIT:url>'])<EOL><DEDENT><DEDENT>elif fext == '<STR_LIT>':<EOL><INDENT>with open(fbasename, '<STR_LIT:r>') as fread:<EOL><INDENT>for line in fread:<EOL><INDENT>if '<STR_LIT>' in line:<EOL><INDENT>texture_files.append(os.path.basename(line.split('<STR_LIT:">')[<NUM_LIT:1>]))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif fext != '<STR_LIT>':  <EOL><INDENT>print('<STR_LIT>' % fext)<EOL><DEDENT>texture_files_unique = list(set(texture_files))<EOL>if log is not None:<EOL><INDENT>log_file = open(log, '<STR_LIT:a>')<EOL>log_file.write('<STR_LIT>')<EOL>log_file.write('<STR_LIT>' % fbasename)<EOL>log_file.write('<STR_LIT>' % texture_files)<EOL>log_file.write('<STR_LIT>' % texture_files_unique)<EOL>log_file.write('<STR_LIT>' % len(texture_files))<EOL>log_file.write(<EOL>'<STR_LIT>' %<EOL>len(texture_files_unique))<EOL>log_file.write('<STR_LIT>' % vert_colors)<EOL>log_file.write('<STR_LIT>' % face_colors)<EOL>log_file.close()<EOL><DEDENT>colors = {'<STR_LIT>':bool(texture_files), '<STR_LIT>':vert_colors, '<STR_LIT>':face_colors}<EOL>return texture_files, texture_files_unique, material_file, colors<EOL>

Finds the filenames of the referenced texture file(s) (and material
    file for obj) for the mesh.

    Args:
        fbasename (str): input filename. Supported file extensions:
            obj
            ply
            dae
            x3d
            wrl
        log (str): filename to log output

    Returns:
        list: list of all of the texture filenames referenced by the input file.
            May contain duplicates if the texture files are referenced more
            than once. List is empty if no texture files are found.
        list: list of all of the unique texture filenames, also empty if no
            texture files are found.
        str: for obj files only, returns the name of the referenced material file.
            Returns None if no material file is found.


def create_mlp(file_out, mlp_mesh=None, mlp_raster=None):

<EOL>mlp_file = open(file_out, '<STR_LIT:w>')<EOL>mlp_file.write('<STR_LIT:\n>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>']))<EOL>mlp_file.close()<EOL>if mlp_mesh is not None:<EOL><INDENT>mlp_file = open(file_out, '<STR_LIT:a>')<EOL>mlp_file.write('<STR_LIT>')<EOL>for i, val in enumerate(mlp_mesh):<EOL><INDENT>if '<STR_LIT:label>' not in mlp_mesh[i]:<EOL><INDENT>mlp_mesh[i]['<STR_LIT:label>'] = mlp_mesh[i]['<STR_LIT:filename>']<EOL><DEDENT>if '<STR_LIT>' not in mlp_mesh[i]:<EOL><INDENT>mlp_mesh[i]['<STR_LIT>'] = [[<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]]<EOL><DEDENT>mlp_file.write('<STR_LIT>'.format(mlp_mesh[i]['<STR_LIT:filename>'], mlp_mesh[i]['<STR_LIT:label>']))<EOL>mlp_file.write('<STR_LIT:\n>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(m=mlp_mesh[i]['<STR_LIT>'][<NUM_LIT:0>]),<EOL>'<STR_LIT>'.format(m=mlp_mesh[i]['<STR_LIT>'][<NUM_LIT:1>]),<EOL>'<STR_LIT>'.format(m=mlp_mesh[i]['<STR_LIT>'][<NUM_LIT:2>]),<EOL>'<STR_LIT>'.format(m=mlp_mesh[i]['<STR_LIT>'][<NUM_LIT:3>]),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>']))<EOL><DEDENT>mlp_file.write('<STR_LIT>')<EOL>mlp_file.close()<EOL><DEDENT>else:<EOL><INDENT>mlp_file = open(file_out, '<STR_LIT:a>')<EOL>mlp_file.write('<STR_LIT>')<EOL>mlp_file.close()<EOL><DEDENT>if mlp_raster is not None:<EOL><INDENT>mlp_file = open(file_out, '<STR_LIT:a>')<EOL>mlp_file.write('<STR_LIT>')<EOL>for i, val in enumerate(mlp_raster):<EOL><INDENT>if '<STR_LIT:label>' not in mlp_raster[i]:<EOL><INDENT>mlp_raster[i]['<STR_LIT:label>'] = mlp_raster[i]['<STR_LIT:filename>']<EOL><DEDENT>if '<STR_LIT>' not in mlp_raster[i]:<EOL><INDENT>mlp_raster[i]['<STR_LIT>'] = <NUM_LIT:1><EOL><DEDENT>if '<STR_LIT>' not in mlp_raster[i]['<STR_LIT>']:<EOL><INDENT>mlp_raster[i]['<STR_LIT>']['<STR_LIT>'] = [<NUM_LIT:0>, <NUM_LIT:0>]<EOL><DEDENT>if '<STR_LIT>' not in mlp_raster[i]['<STR_LIT>']:<EOL><INDENT>mlp_raster[i]['<STR_LIT>']['<STR_LIT>'] = [int(mlp_raster[i]['<STR_LIT>']['<STR_LIT>'][<NUM_LIT:0>]/<NUM_LIT:2>), int(mlp_raster[i]['<STR_LIT>']['<STR_LIT>'][<NUM_LIT:1>]/<NUM_LIT:2>)]<EOL><DEDENT>mlp_file.write('<STR_LIT>'.format(mlp_raster[i]['<STR_LIT:label>']))<EOL>mlp_file.write('<STR_LIT:U+0020>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(m=mlp_raster[i]['<STR_LIT>']['<STR_LIT>']),<EOL>'<STR_LIT>'.format(m=mlp_raster[i]['<STR_LIT>']['<STR_LIT>']),<EOL>'<STR_LIT>'.format(mlp_raster[i]['<STR_LIT>']['<STR_LIT>']),<EOL>'<STR_LIT>'.format(m=mlp_raster[i]['<STR_LIT>']['<STR_LIT>']),<EOL>'<STR_LIT>'.format(m=mlp_raster[i]['<STR_LIT>']['<STR_LIT>']),<EOL>'<STR_LIT>'.format(m=mlp_raster[i]['<STR_LIT>']['<STR_LIT>']),<EOL>'<STR_LIT>'.format(m=mlp_raster[i]['<STR_LIT>']['<STR_LIT>']),<EOL>'<STR_LIT>']))<EOL>mlp_file.write('<STR_LIT>'.format(mlp_raster[i]['<STR_LIT>'], mlp_raster[i]['<STR_LIT:filename>']))<EOL>mlp_file.write('<STR_LIT>')<EOL><DEDENT>mlp_file.write('<STR_LIT>')<EOL>mlp_file.close()<EOL><DEDENT>else:<EOL><INDENT>mlp_file = open(file_out, '<STR_LIT:a>')<EOL>mlp_file.write('<STR_LIT>')<EOL>mlp_file.close()<EOL><DEDENT>mlp_file = open(file_out, '<STR_LIT:a>')<EOL>mlp_file.write('<STR_LIT>')<EOL>mlp_file.close()<EOL>return<EOL>

Create mlp file
    mlp_mesh (list containing dictionary)
        filename*
        label
        matrix

    mlp_raster
        filename*
        label
        semantic
        camera
            trans_vector*
            rotation_matrix*
            focal_length*
            image_px*
            image_res_mm_per_px*
            lens_distortion
            center_px
    * Required

    http://vcg.isti.cnr.it/~cignoni/newvcglib/html/shot.html


def add_layer(self, label, change_layer=True):

self.layer_stack.insert(self.last_layer() + <NUM_LIT:1>, label)<EOL>if change_layer:<EOL><INDENT>self.set_current_layer(self.last_layer())<EOL><DEDENT>return None<EOL>

Add new mesh layer to the end of the stack

        Args:
            label (str): new label for the mesh layer
            change_layer (bool): change to the newly created layer


def default_output_mask(file_out, texture=True, vert_normals=True, vert_colors=False,<EOL>face_colors=False, ml_version=ML_VERSION):

vn = '<STR_LIT>'<EOL>wt = '<STR_LIT>'<EOL>vc = '<STR_LIT>'<EOL>fc = '<STR_LIT>'<EOL>if ml_version < '<STR_LIT>':<EOL><INDENT>om = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>om = '<STR_LIT>'<EOL><DEDENT>fext = os.path.splitext(file_out)[<NUM_LIT:1>][<NUM_LIT:1>:].strip().lower()<EOL>if fext in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>om = '<STR_LIT>'<EOL>texture = False<EOL>vert_normals = False<EOL>vert_colors = False<EOL>face_colors = False<EOL>

Set default output mask options based on file extension
Note: v1.34BETA changed -om switch to -m
Possible options (not all options are available for every format):
 vc -> vertex colors
 vf -> vertex flags
 vq -> vertex quality
 vn -> vertex normals
 vt -> vertex texture coords
 fc -> face colors
 ff -> face flags
 fq -> face quality
 fn -> face normals
 wc -> wedge colors
 wn -> wedge normals
 wt -> wedge texture coords


def install_npm(path=None, build_dir=None, source_dir=None, build_cmd='<STR_LIT>', force=False, npm=None):

class NPM(BaseCommand):<EOL><INDENT>description = '<STR_LIT>'<EOL>def run(self):<EOL><INDENT>if skip_npm:<EOL><INDENT>log.info('<STR_LIT>')<EOL>return<EOL><DEDENT>node_package = path or HERE<EOL>node_modules = pjoin(node_package, '<STR_LIT>')<EOL>is_yarn = os.path.exists(pjoin(node_package, '<STR_LIT>'))<EOL>npm_cmd = npm<EOL>if npm is None:<EOL><INDENT>if is_yarn:<EOL><INDENT>npm_cmd = ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>npm_cmd = ['<STR_LIT>']<EOL><DEDENT><DEDENT>if not which(npm_cmd[<NUM_LIT:0>]):<EOL><INDENT>log.error("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>.format(npm_cmd[<NUM_LIT:0>]))<EOL>return<EOL><DEDENT>if force or is_stale(node_modules, pjoin(node_package, '<STR_LIT>')):<EOL><INDENT>log.info('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>run(npm_cmd + ['<STR_LIT>'], cwd=node_package)<EOL><DEDENT>if build_dir and source_dir and not force:<EOL><INDENT>should_build = is_stale(build_dir, source_dir)<EOL><DEDENT>else:<EOL><INDENT>should_build = True<EOL><DEDENT>if should_build:<EOL><INDENT>run(npm_cmd + ['<STR_LIT>', build_cmd], cwd=node_package)<EOL><DEDENT><DEDENT><DEDENT>return NPM<EOL>

Return a Command for managing an npm installation.

    Note: The command is skipped if the `--skip-npm` flag is used.

    Parameters
    ----------
    path: str, optional
        The base path of the node package.  Defaults to the repo root.
    build_dir: str, optional
        The target build directory.  If this and source_dir are given,
        the JavaScript will only be build if necessary.
    source_dir: str, optional
        The source code directory.
    build_cmd: str, optional
        The npm command to build assets to the build_dir.
    npm: str or list, optional.
        The npm executable name, or a tuple of ['node', executable].


path = os.path.realpath(file)<EOL>version_ns = {}<EOL>with io.open(path, encoding="<STR_LIT:utf8>") as f:<EOL><INDENT>exec(f.read(), {}, version_ns)<EOL><DEDENT>return version_ns[name]<EOL>

Get the version of the package from the given file by
    executing it and extracting the given `name`.


class CombinedCommand(Command):<EOL><INDENT>user_options = []<EOL>def initialize_options(self):<EOL><INDENT>self.commands = []<EOL>for C in commands:<EOL><INDENT>self.commands.append(C(self.distribution))<EOL><DEDENT>for c in self.commands:<EOL><INDENT>c.initialize_options()<EOL><DEDENT><DEDENT>def finalize_options(self):<EOL><INDENT>for c in self.commands:<EOL><INDENT>c.finalize_options()<EOL><DEDENT><DEDENT>def run(self):<EOL><INDENT>for c in self.commands:<EOL><INDENT>c.run()<EOL><DEDENT><DEDENT><DEDENT>return CombinedCommand<EOL>

Return a Command that combines several commands.


wrapped = [prerelease_cmd] if prerelease_cmd else []<EOL>if package_data_spec or data_files_spec:<EOL><INDENT>wrapped.append('<STR_LIT>')<EOL><DEDENT>wrapper = functools.partial(_wrap_command, wrapped)<EOL>handle_files = _get_file_handler(package_data_spec, data_files_spec)<EOL>if '<STR_LIT>' in sys.argv:<EOL><INDENT>egg = wrapper(bdist_egg, strict=True)<EOL><DEDENT>else:<EOL><INDENT>egg = bdist_egg_disabled<EOL><DEDENT>cmdclass = dict(<EOL>build_py=wrapper(build_py, strict=is_repo),<EOL>bdist_egg=egg,<EOL>sdist=wrapper(sdist, strict=True),<EOL>handle_files=handle_files,<EOL>)<EOL>if bdist_wheel:<EOL><INDENT>cmdclass['<STR_LIT>'] = wrapper(bdist_wheel, strict=True)<EOL><DEDENT>cmdclass['<STR_LIT>'] = wrapper(develop, strict=True)<EOL>return cmdclass<EOL>

Create a command class with the given optional prerelease class.

    Parameters
    ----------
    prerelease_cmd: (name, Command) tuple, optional
        The command to run before releasing.
    package_data_spec: dict, optional
        A dictionary whose keys are the dotted package names and
        whose values are a list of glob patterns.
    data_files_spec: list, optional
        A list of (path, dname, pattern) tuples where the path is the
        `data_files` install path, dname is the source directory, and the
        pattern is a glob pattern.

    Notes
    -----
    We use specs so that we can find the files *after* the build
    command has run.

    The package data glob patterns should be relative paths from the package
    folder containing the __init__.py file, which is given as the package
    name.
    e.g. `dict(foo=['./bar/*', './baz/**'])`

    The data files directories should be absolute paths or relative paths
    from the root directory of the repository.  Data files are specified
    differently from `package_data` because we need a separate path entry
    for each nested folder in `data_files`, and this makes it easier to
    parse.
    e.g. `('share/foo/bar', 'pkgname/bizz, '*')`


packages = []<EOL>for d, dirs, _ in os.walk(top, followlinks=True):<EOL><INDENT>if os.path.exists(pjoin(d, '<STR_LIT>')):<EOL><INDENT>packages.append(os.path.relpath(d, top).replace(os.path.sep, '<STR_LIT:.>'))<EOL><DEDENT>elif d != top:<EOL><INDENT>dirs[:] = []<EOL><DEDENT><DEDENT>return packages<EOL>


res = '<STR_LIT>'<EOL>for part in translated_parts[:-<NUM_LIT:1>]:<EOL><INDENT>if part == '<STR_LIT>':<EOL><INDENT>res += part<EOL><DEDENT>else:<EOL><INDENT>res += part + os_sep_class<EOL><DEDENT><DEDENT>if translated_parts[-<NUM_LIT:1>] == '<STR_LIT>':<EOL><INDENT>res += '<STR_LIT>'<EOL>res += '<STR_LIT>'.format(os_sep_class=os_sep_class)<EOL><DEDENT>else:<EOL><INDENT>res += translated_parts[-<NUM_LIT:1>]<EOL><DEDENT>return res<EOL>

Join translated glob pattern parts.

    This is different from a simple join, as care need to be taken
    to allow ** to match ZERO or more directories.


class TargetsCheck(BaseCommand):<EOL><INDENT>def run(self):<EOL><INDENT>if skip_npm:<EOL><INDENT>log.info('<STR_LIT>')<EOL>return<EOL><DEDENT>missing = [t for t in targets if not os.path.exists(t)]<EOL>if missing:<EOL><INDENT>raise ValueError(('<STR_LIT>' % missing))<EOL><DEDENT><DEDENT><DEDENT>return TargetsCheck<EOL>

Return a Command that checks that certain files exist.

    Raises a ValueError if any of the files are missing.

    Note: The check is skipped if the `--skip-npm` flag is used.


(head, tail) = os.path.split(path)<EOL>if not head or (not tail and head == path):<EOL><INDENT>if head:<EOL><INDENT>yield head<EOL><DEDENT>if tail or not head:<EOL><INDENT>yield tail<EOL><DEDENT>return<EOL><DEDENT>for p in _iexplode_path(head):<EOL><INDENT>yield p<EOL><DEDENT>yield tail<EOL>

Iterate over all the parts of a path.

    Splits path recursively with os.path.split().


def compare_recursive_mtime(path, cutoff, newest=True):

if os.path.isfile(path):<EOL><INDENT>mt = mtime(path)<EOL>if newest:<EOL><INDENT>if mt > cutoff:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>elif mt < cutoff:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>for dirname, _, filenames in os.walk(path, topdown=False):<EOL><INDENT>for filename in filenames:<EOL><INDENT>mt = mtime(pjoin(dirname, filename))<EOL>if newest:  <EOL><INDENT>if mt > cutoff:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>elif mt < cutoff:<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>return False<EOL>

Compare the newest/oldest mtime for all files in a directory.

    Cutoff should be another mtime to be compared against. If an mtime that is
    newer/older than the cutoff is found it will return True.
    E.g. if newest=True, and a file in path is newer than the cutoff, it will
    return True.


if not isinstance(file_patterns, (list, tuple)):<EOL><INDENT>file_patterns = [file_patterns]<EOL><DEDENT>for i, p in enumerate(file_patterns):<EOL><INDENT>if os.path.isabs(p):<EOL><INDENT>file_patterns[i] = os.path.relpath(p, top)<EOL><DEDENT><DEDENT>matchers = [_compile_pattern(p) for p in file_patterns]<EOL>files = set()<EOL>for root, dirnames, filenames in os.walk(top):<EOL><INDENT>if '<STR_LIT>' in dirnames:<EOL><INDENT>dirnames.remove('<STR_LIT>')<EOL><DEDENT>for m in matchers:<EOL><INDENT>for filename in filenames:<EOL><INDENT>fn = os.path.relpath(pjoin(root, filename), top)<EOL>if m(fn):<EOL><INDENT>files.add(fn.replace(os.sep, '<STR_LIT:/>'))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return list(files)<EOL>

Expand file patterns to a list of paths.

    Parameters
    -----------
    file_patterns: list or str
        A list of glob patterns for the data file locations.
        The globs can be recursive if they include a `**`.
        They should be relative paths from the top directory or
        absolute paths.
    top: str
        the directory to consider for data files

    Note:
    Files in `node_modules` are ignored.


def which(cmd, mode=os.F_OK | os.X_OK, path=None):

<EOL>def _access_check(fn, mode):<EOL><INDENT>return (os.path.exists(fn) and os.access(fn, mode) and<EOL>not os.path.isdir(fn))<EOL><DEDENT>if _access_check(cmd, mode):<EOL><INDENT>return cmd<EOL><DEDENT>path = (path or os.environ.get("<STR_LIT>", os.defpath)).split(os.pathsep)<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>if os.curdir not in path:<EOL><INDENT>path.insert(<NUM_LIT:0>, os.curdir)<EOL><DEDENT>pathext = os.environ.get("<STR_LIT>", "<STR_LIT>").split(os.pathsep)<EOL>matches = [cmd for ext in pathext if cmd.lower().endswith(ext.lower())]<EOL>files = [cmd] if matches else [cmd + ext.lower() for ext in pathext]<EOL><DEDENT>else:<EOL><INDENT>files = [cmd]<EOL><DEDENT>seen = set()<EOL>for dir in path:<EOL><INDENT>dir = os.path.normcase(dir)<EOL>if dir not in seen:<EOL><INDENT>seen.add(dir)<EOL>for thefile in files:<EOL><INDENT>name = os.path.join(dir, thefile)<EOL>if _access_check(name, mode):<EOL><INDENT>return name<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return None<EOL>

Given a command, mode, and a PATH string, return the path which
    conforms to the given mode on the PATH, or None if there is no such
    file.
    `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
    of os.environ.get("PATH"), or can be overridden with a custom search
    path.


if file_patterns is None:<EOL><INDENT>file_patterns = ['<STR_LIT:*>']<EOL><DEDENT>return _get_files(file_patterns, pjoin(HERE, root))<EOL>

Expand file patterns to a list of `package_data` paths.

    Parameters
    -----------
    root: str
        The relative path to the package root from `HERE`.
    file_patterns: list or str, optional
        A list of glob patterns for the data file locations.
        The globs can be recursive if they include a `**`.
        They should be relative paths from the root or
        absolute paths.  If not given, all files will be used.

    Note:
    Files in `node_modules` are ignored.


translated_parts = []<EOL>for part in _iexplode_path(pat):<EOL><INDENT>translated_parts.append(_translate_glob_part(part))<EOL><DEDENT>os_sep_class = '<STR_LIT>' % re.escape(SEPARATORS)<EOL>res = _join_translated(translated_parts, os_sep_class)<EOL>return '<STR_LIT>'.format(res=res)<EOL>

Translate a glob PATTERN to a regular expression.


x = x.transpose((<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:0>))<EOL>x[:, :, <NUM_LIT:0>] += <NUM_LIT><EOL>x[:, :, <NUM_LIT:1>] += <NUM_LIT><EOL>x[:, :, <NUM_LIT:2>] += <NUM_LIT><EOL>x = x[:,:,::-<NUM_LIT:1>]  <EOL>return x<EOL>

Decondition an image from the VGG16 model.


if not isinstance(value, Token):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if not hasattr(value, '<STR_LIT>'):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if not value.identifier:<EOL><INDENT>value = value.__class__(**value.__dict__)<EOL>value.identifier = '<STR_LIT:v>'<EOL><DEDENT>ident = Identifier(value.identifier)<EOL>return Query([<EOL>Match(value),<EOL>Return(ident)<EOL>])<EOL>


self.data['<STR_LIT>'].append('<STR_LIT>'%(index,<EOL>'<STR_LIT:U+002C>'.join(map(smart_str, args))))<EOL>return self.parent<EOL>

Set the range of each axis, one at a time
args are of the form <start of range>,<end of range>,<interval>
APIPARAM: chxr