body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
82ed62f97ea458c106de525433104f48d9588b1c7ece5d6caa0f8606a75f1bca
@classmethod def from_dict(cls, data): 'Create a new PulseLibraryItem object from a dictionary.\n\n Args:\n data (dict): A dictionary for the experiment config\n\n Returns:\n PulseLibraryItem: The object from the input dictionary.\n ' return cls(**data)
Create a new PulseLibraryItem object from a dictionary. Args: data (dict): A dictionary for the experiment config Returns: PulseLibraryItem: The object from the input dictionary.
qiskit/qobj/pulse_qobj.py
from_dict
areeq-hasan/qiskit-terra
11
python
@classmethod def from_dict(cls, data): 'Create a new PulseLibraryItem object from a dictionary.\n\n Args:\n data (dict): A dictionary for the experiment config\n\n Returns:\n PulseLibraryItem: The object from the input dictionary.\n ' return cls(**data)
@classmethod def from_dict(cls, data): 'Create a new PulseLibraryItem object from a dictionary.\n\n Args:\n data (dict): A dictionary for the experiment config\n\n Returns:\n PulseLibraryItem: The object from the input dictionary.\n ' return cls(**data)<|docstring|>Create a new PulseLibraryItem object from a dictionary. Args: data (dict): A dictionary for the experiment config Returns: PulseLibraryItem: The object from the input dictionary.<|endoftext|>
74d724c9d04256eda45f0a0ba21eb469c0e2abb3a0221d1d95a1eba470ed5936
def __init__(self, qobj_id, config, experiments, header=None): 'Instatiate a new Pulse Qobj Object.\n\n Each Pulse Qobj object is used to represent a single payload that will\n be passed to a Qiskit provider. It mirrors the Qobj the published\n `Qobj specification <https://arxiv.org/abs/1809.03452>`_ for Pulse\n experiments.\n\n Args:\n qobj_id (str): An identifier for the qobj\n config (PulseQobjConfig): A config for the entire run\n header (QobjHeader): A header for the entire run\n experiments (list): A list of lists of :class:`PulseQobjExperiment`\n objects representing an experiment\n ' self.qobj_id = qobj_id self.config = config self.header = (header or QobjHeader()) self.experiments = experiments self.type = 'PULSE' self.schema_version = '1.2.0'
Instatiate a new Pulse Qobj Object. Each Pulse Qobj object is used to represent a single payload that will be passed to a Qiskit provider. It mirrors the Qobj the published `Qobj specification <https://arxiv.org/abs/1809.03452>`_ for Pulse experiments. Args: qobj_id (str): An identifier for the qobj config (PulseQobjConfig): A config for the entire run header (QobjHeader): A header for the entire run experiments (list): A list of lists of :class:`PulseQobjExperiment` objects representing an experiment
qiskit/qobj/pulse_qobj.py
__init__
areeq-hasan/qiskit-terra
11
python
def __init__(self, qobj_id, config, experiments, header=None): 'Instatiate a new Pulse Qobj Object.\n\n Each Pulse Qobj object is used to represent a single payload that will\n be passed to a Qiskit provider. It mirrors the Qobj the published\n `Qobj specification <https://arxiv.org/abs/1809.03452>`_ for Pulse\n experiments.\n\n Args:\n qobj_id (str): An identifier for the qobj\n config (PulseQobjConfig): A config for the entire run\n header (QobjHeader): A header for the entire run\n experiments (list): A list of lists of :class:`PulseQobjExperiment`\n objects representing an experiment\n ' self.qobj_id = qobj_id self.config = config self.header = (header or QobjHeader()) self.experiments = experiments self.type = 'PULSE' self.schema_version = '1.2.0'
def __init__(self, qobj_id, config, experiments, header=None): 'Instatiate a new Pulse Qobj Object.\n\n Each Pulse Qobj object is used to represent a single payload that will\n be passed to a Qiskit provider. It mirrors the Qobj the published\n `Qobj specification <https://arxiv.org/abs/1809.03452>`_ for Pulse\n experiments.\n\n Args:\n qobj_id (str): An identifier for the qobj\n config (PulseQobjConfig): A config for the entire run\n header (QobjHeader): A header for the entire run\n experiments (list): A list of lists of :class:`PulseQobjExperiment`\n objects representing an experiment\n ' self.qobj_id = qobj_id self.config = config self.header = (header or QobjHeader()) self.experiments = experiments self.type = 'PULSE' self.schema_version = '1.2.0'<|docstring|>Instatiate a new Pulse Qobj Object. Each Pulse Qobj object is used to represent a single payload that will be passed to a Qiskit provider. It mirrors the Qobj the published `Qobj specification <https://arxiv.org/abs/1809.03452>`_ for Pulse experiments. Args: qobj_id (str): An identifier for the qobj config (PulseQobjConfig): A config for the entire run header (QobjHeader): A header for the entire run experiments (list): A list of lists of :class:`PulseQobjExperiment` objects representing an experiment<|endoftext|>
4231885a3bc7d75c57f774b013f21bf3afb22597a1ea6f144513e12d473b422e
def to_dict(self, validate=False): 'Return a dictionary format representation of the Pulse Qobj.\n\n Note this dict is not in the json wire format expected by IBMQ and qobj\n specification because complex numbers are still of type complex. Also\n this may contain native numpy arrays. When serializing this output\n for use with IBMQ you can leverage a json encoder that converts these\n as expected. For example:\n\n .. code-block::\n\n import json\n import numpy\n\n class QobjEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, numpy.ndarray):\n return obj.tolist()\n if isinstance(obj, complex):\n return (obj.real, obj.imag)\n return json.JSONEncoder.default(self, obj)\n\n json.dumps(qobj.to_dict(), cls=QobjEncoder)\n\n Args:\n validate (bool): When set to true validate the output dictionary\n against the jsonschema for qobj spec.\n\n Returns:\n dict: A dictionary representation of the PulseQobj object\n ' out_dict = {'qobj_id': self.qobj_id, 'header': self.header.to_dict(), 'config': self.config.to_dict(), 'schema_version': self.schema_version, 'type': self.type, 'experiments': [x.to_dict() for x in self.experiments]} if validate: warnings.warn("The jsonschema validation included in qiskit-terra is deprecated and will be removed in a future release. If you're relying on this schema validation you should pull the schemas from the Qiskit/ibmq-schemas and directly validate your payloads with that", DeprecationWarning, stacklevel=2) self._validate_json_schema(out_dict) return out_dict
Return a dictionary format representation of the Pulse Qobj. Note this dict is not in the json wire format expected by IBMQ and qobj specification because complex numbers are still of type complex. Also this may contain native numpy arrays. When serializing this output for use with IBMQ you can leverage a json encoder that converts these as expected. For example: .. code-block:: import json import numpy class QobjEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, numpy.ndarray): return obj.tolist() if isinstance(obj, complex): return (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) json.dumps(qobj.to_dict(), cls=QobjEncoder) Args: validate (bool): When set to true validate the output dictionary against the jsonschema for qobj spec. Returns: dict: A dictionary representation of the PulseQobj object
qiskit/qobj/pulse_qobj.py
to_dict
areeq-hasan/qiskit-terra
11
python
def to_dict(self, validate=False): 'Return a dictionary format representation of the Pulse Qobj.\n\n Note this dict is not in the json wire format expected by IBMQ and qobj\n specification because complex numbers are still of type complex. Also\n this may contain native numpy arrays. When serializing this output\n for use with IBMQ you can leverage a json encoder that converts these\n as expected. For example:\n\n .. code-block::\n\n import json\n import numpy\n\n class QobjEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, numpy.ndarray):\n return obj.tolist()\n if isinstance(obj, complex):\n return (obj.real, obj.imag)\n return json.JSONEncoder.default(self, obj)\n\n json.dumps(qobj.to_dict(), cls=QobjEncoder)\n\n Args:\n validate (bool): When set to true validate the output dictionary\n against the jsonschema for qobj spec.\n\n Returns:\n dict: A dictionary representation of the PulseQobj object\n ' out_dict = {'qobj_id': self.qobj_id, 'header': self.header.to_dict(), 'config': self.config.to_dict(), 'schema_version': self.schema_version, 'type': self.type, 'experiments': [x.to_dict() for x in self.experiments]} if validate: warnings.warn("The jsonschema validation included in qiskit-terra is deprecated and will be removed in a future release. If you're relying on this schema validation you should pull the schemas from the Qiskit/ibmq-schemas and directly validate your payloads with that", DeprecationWarning, stacklevel=2) self._validate_json_schema(out_dict) return out_dict
def to_dict(self, validate=False): 'Return a dictionary format representation of the Pulse Qobj.\n\n Note this dict is not in the json wire format expected by IBMQ and qobj\n specification because complex numbers are still of type complex. Also\n this may contain native numpy arrays. When serializing this output\n for use with IBMQ you can leverage a json encoder that converts these\n as expected. For example:\n\n .. code-block::\n\n import json\n import numpy\n\n class QobjEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, numpy.ndarray):\n return obj.tolist()\n if isinstance(obj, complex):\n return (obj.real, obj.imag)\n return json.JSONEncoder.default(self, obj)\n\n json.dumps(qobj.to_dict(), cls=QobjEncoder)\n\n Args:\n validate (bool): When set to true validate the output dictionary\n against the jsonschema for qobj spec.\n\n Returns:\n dict: A dictionary representation of the PulseQobj object\n ' out_dict = {'qobj_id': self.qobj_id, 'header': self.header.to_dict(), 'config': self.config.to_dict(), 'schema_version': self.schema_version, 'type': self.type, 'experiments': [x.to_dict() for x in self.experiments]} if validate: warnings.warn("The jsonschema validation included in qiskit-terra is deprecated and will be removed in a future release. If you're relying on this schema validation you should pull the schemas from the Qiskit/ibmq-schemas and directly validate your payloads with that", DeprecationWarning, stacklevel=2) self._validate_json_schema(out_dict) return out_dict<|docstring|>Return a dictionary format representation of the Pulse Qobj. Note this dict is not in the json wire format expected by IBMQ and qobj specification because complex numbers are still of type complex. Also this may contain native numpy arrays. When serializing this output for use with IBMQ you can leverage a json encoder that converts these as expected. For example: .. code-block:: import json import numpy class QobjEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, numpy.ndarray): return obj.tolist() if isinstance(obj, complex): return (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) json.dumps(qobj.to_dict(), cls=QobjEncoder) Args: validate (bool): When set to true validate the output dictionary against the jsonschema for qobj spec. Returns: dict: A dictionary representation of the PulseQobj object<|endoftext|>
a497a164e3be334c1b0aeea00d98477bcc275f47be58a5cf83f6bd41819c1538
@classmethod def from_dict(cls, data): 'Create a new PulseQobj object from a dictionary.\n\n Args:\n data (dict): A dictionary representing the PulseQobj to create. It\n will be in the same format as output by :func:`to_dict`.\n\n Returns:\n PulseQobj: The PulseQobj from the input dictionary.\n ' config = None if ('config' in data): config = PulseQobjConfig.from_dict(data['config']) experiments = None if ('experiments' in data): experiments = [PulseQobjExperiment.from_dict(exp) for exp in data['experiments']] header = None if ('header' in data): header = QobjHeader.from_dict(data['header']) return cls(qobj_id=data.get('qobj_id'), config=config, experiments=experiments, header=header)
Create a new PulseQobj object from a dictionary. Args: data (dict): A dictionary representing the PulseQobj to create. It will be in the same format as output by :func:`to_dict`. Returns: PulseQobj: The PulseQobj from the input dictionary.
qiskit/qobj/pulse_qobj.py
from_dict
areeq-hasan/qiskit-terra
11
python
@classmethod def from_dict(cls, data): 'Create a new PulseQobj object from a dictionary.\n\n Args:\n data (dict): A dictionary representing the PulseQobj to create. It\n will be in the same format as output by :func:`to_dict`.\n\n Returns:\n PulseQobj: The PulseQobj from the input dictionary.\n ' config = None if ('config' in data): config = PulseQobjConfig.from_dict(data['config']) experiments = None if ('experiments' in data): experiments = [PulseQobjExperiment.from_dict(exp) for exp in data['experiments']] header = None if ('header' in data): header = QobjHeader.from_dict(data['header']) return cls(qobj_id=data.get('qobj_id'), config=config, experiments=experiments, header=header)
@classmethod def from_dict(cls, data): 'Create a new PulseQobj object from a dictionary.\n\n Args:\n data (dict): A dictionary representing the PulseQobj to create. It\n will be in the same format as output by :func:`to_dict`.\n\n Returns:\n PulseQobj: The PulseQobj from the input dictionary.\n ' config = None if ('config' in data): config = PulseQobjConfig.from_dict(data['config']) experiments = None if ('experiments' in data): experiments = [PulseQobjExperiment.from_dict(exp) for exp in data['experiments']] header = None if ('header' in data): header = QobjHeader.from_dict(data['header']) return cls(qobj_id=data.get('qobj_id'), config=config, experiments=experiments, header=header)<|docstring|>Create a new PulseQobj object from a dictionary. Args: data (dict): A dictionary representing the PulseQobj to create. It will be in the same format as output by :func:`to_dict`. Returns: PulseQobj: The PulseQobj from the input dictionary.<|endoftext|>
648454fde75dfaae7477d66a7ab548ca8730e7a97d737df0f9a44e5c611a2cfb
def __init__(self, model, view): '\n\n Args:\n model (Model):\n view (View):\n ' self.guides_grp = None self.guides = [] self.guide_names = [] self.created_spine_jnts = [] self.created_pelvis_jnt = None self.ik_spline = None self.created_locs = [] self.created_fk_ctrls = [] self.created_inv_fk_ctrls = [] self.created_pelvis_ctrl = None self.created_ik_ctrls = [] self.jnts_to_skin = [] self.bend_ctrls = [] RigController.__init__(self, model, view)
Args: model (Model): view (View):
animal/quadruped_spine.py
__init__
Sookhaal/auri_rigging_scripts
5
python
def __init__(self, model, view): '\n\n Args:\n model (Model):\n view (View):\n ' self.guides_grp = None self.guides = [] self.guide_names = [] self.created_spine_jnts = [] self.created_pelvis_jnt = None self.ik_spline = None self.created_locs = [] self.created_fk_ctrls = [] self.created_inv_fk_ctrls = [] self.created_pelvis_ctrl = None self.created_ik_ctrls = [] self.jnts_to_skin = [] self.bend_ctrls = [] RigController.__init__(self, model, view)
def __init__(self, model, view): '\n\n Args:\n model (Model):\n view (View):\n ' self.guides_grp = None self.guides = [] self.guide_names = [] self.created_spine_jnts = [] self.created_pelvis_jnt = None self.ik_spline = None self.created_locs = [] self.created_fk_ctrls = [] self.created_inv_fk_ctrls = [] self.created_pelvis_ctrl = None self.created_ik_ctrls = [] self.jnts_to_skin = [] self.bend_ctrls = [] RigController.__init__(self, model, view)<|docstring|>Args: model (Model): view (View):<|endoftext|>
687c9139b983a56976e48bf822249a4479f5e69c66e3c8df8b711b610e2ddc98
@pytest.mark.parametrize('model_config', [dict(fields={'category': models.TextField()}, partitioning_options=dict(method=PostgresPartitioningMethod.LIST, key='category')), dict(fields={'timestamp': models.DateTimeField()}, partitioning_options=dict(method=PostgresPartitioningMethod.RANGE, key='timestamp'))]) @postgres_patched_migrations() def test_make_migration_create_partitioned_model(fake_app, model_config): 'Tests whether the right operations are generated when creating a new\n partitioned model.' model = define_fake_partitioned_model(**model_config, meta_options=dict(app_label=fake_app.name)) migration = make_migration(model._meta.app_label) ops = migration.operations assert (len(ops) == 2) assert isinstance(ops[0], operations.PostgresCreatePartitionedModel) assert isinstance(ops[1], operations.PostgresAddDefaultPartition) assert (len(ops[0].bases) == 1) assert issubclass(ops[0].bases[0], PostgresPartitionedModel) assert (ops[0].partitioning_options == model_config['partitioning_options']) assert (ops[1].model_name == model.__name__) assert (ops[1].name == 'default')
Tests whether the right operations are generated when creating a new partitioned model.
tests/test_make_migrations.py
test_make_migration_create_partitioned_model
ivanp/django-postgres-extra
529
python
@pytest.mark.parametrize('model_config', [dict(fields={'category': models.TextField()}, partitioning_options=dict(method=PostgresPartitioningMethod.LIST, key='category')), dict(fields={'timestamp': models.DateTimeField()}, partitioning_options=dict(method=PostgresPartitioningMethod.RANGE, key='timestamp'))]) @postgres_patched_migrations() def test_make_migration_create_partitioned_model(fake_app, model_config): 'Tests whether the right operations are generated when creating a new\n partitioned model.' model = define_fake_partitioned_model(**model_config, meta_options=dict(app_label=fake_app.name)) migration = make_migration(model._meta.app_label) ops = migration.operations assert (len(ops) == 2) assert isinstance(ops[0], operations.PostgresCreatePartitionedModel) assert isinstance(ops[1], operations.PostgresAddDefaultPartition) assert (len(ops[0].bases) == 1) assert issubclass(ops[0].bases[0], PostgresPartitionedModel) assert (ops[0].partitioning_options == model_config['partitioning_options']) assert (ops[1].model_name == model.__name__) assert (ops[1].name == 'default')
@pytest.mark.parametrize('model_config', [dict(fields={'category': models.TextField()}, partitioning_options=dict(method=PostgresPartitioningMethod.LIST, key='category')), dict(fields={'timestamp': models.DateTimeField()}, partitioning_options=dict(method=PostgresPartitioningMethod.RANGE, key='timestamp'))]) @postgres_patched_migrations() def test_make_migration_create_partitioned_model(fake_app, model_config): 'Tests whether the right operations are generated when creating a new\n partitioned model.' model = define_fake_partitioned_model(**model_config, meta_options=dict(app_label=fake_app.name)) migration = make_migration(model._meta.app_label) ops = migration.operations assert (len(ops) == 2) assert isinstance(ops[0], operations.PostgresCreatePartitionedModel) assert isinstance(ops[1], operations.PostgresAddDefaultPartition) assert (len(ops[0].bases) == 1) assert issubclass(ops[0].bases[0], PostgresPartitionedModel) assert (ops[0].partitioning_options == model_config['partitioning_options']) assert (ops[1].model_name == model.__name__) assert (ops[1].name == 'default')<|docstring|>Tests whether the right operations are generated when creating a new partitioned model.<|endoftext|>
8044288a73be29c6fa6e12204cdb71ac1cb368d44157bb9521c1644e59f4f14c
@postgres_patched_migrations() def test_make_migration_create_view_model(fake_app): 'Tests whether the right operations are generated when creating a new\n view model.' underlying_model = get_fake_model({'name': models.TextField()}) model = define_fake_view_model(fields={'name': models.TextField()}, view_options=dict(query=underlying_model.objects.all()), meta_options=dict(app_label=fake_app.name)) migration = make_migration(model._meta.app_label) ops = migration.operations assert (len(ops) == 1) assert isinstance(ops[0], operations.PostgresCreateViewModel) assert (len(ops[0].bases) == 1) assert issubclass(ops[0].bases[0], PostgresViewModel) assert (ops[0].view_options == model._view_meta.original_attrs)
Tests whether the right operations are generated when creating a new view model.
tests/test_make_migrations.py
test_make_migration_create_view_model
ivanp/django-postgres-extra
529
python
@postgres_patched_migrations() def test_make_migration_create_view_model(fake_app): 'Tests whether the right operations are generated when creating a new\n view model.' underlying_model = get_fake_model({'name': models.TextField()}) model = define_fake_view_model(fields={'name': models.TextField()}, view_options=dict(query=underlying_model.objects.all()), meta_options=dict(app_label=fake_app.name)) migration = make_migration(model._meta.app_label) ops = migration.operations assert (len(ops) == 1) assert isinstance(ops[0], operations.PostgresCreateViewModel) assert (len(ops[0].bases) == 1) assert issubclass(ops[0].bases[0], PostgresViewModel) assert (ops[0].view_options == model._view_meta.original_attrs)
@postgres_patched_migrations() def test_make_migration_create_view_model(fake_app): 'Tests whether the right operations are generated when creating a new\n view model.' underlying_model = get_fake_model({'name': models.TextField()}) model = define_fake_view_model(fields={'name': models.TextField()}, view_options=dict(query=underlying_model.objects.all()), meta_options=dict(app_label=fake_app.name)) migration = make_migration(model._meta.app_label) ops = migration.operations assert (len(ops) == 1) assert isinstance(ops[0], operations.PostgresCreateViewModel) assert (len(ops[0].bases) == 1) assert issubclass(ops[0].bases[0], PostgresViewModel) assert (ops[0].view_options == model._view_meta.original_attrs)<|docstring|>Tests whether the right operations are generated when creating a new view model.<|endoftext|>
0a6d78ae81b905e65da5d69ee2d9c3e0e563f59579eac385fda205448bc66dd3
@postgres_patched_migrations() def test_make_migration_create_materialized_view_model(fake_app): 'Tests whether the right operations are generated when creating a new\n materialized view model.' underlying_model = get_fake_model({'name': models.TextField()}) model = define_fake_materialized_view_model(fields={'name': models.TextField()}, view_options=dict(query=underlying_model.objects.all()), meta_options=dict(app_label=fake_app.name)) migration = make_migration(model._meta.app_label) ops = migration.operations assert (len(ops) == 1) assert isinstance(ops[0], operations.PostgresCreateMaterializedViewModel) assert (len(ops[0].bases) == 1) assert issubclass(ops[0].bases[0], PostgresMaterializedViewModel) assert (ops[0].view_options == model._view_meta.original_attrs)
Tests whether the right operations are generated when creating a new materialized view model.
tests/test_make_migrations.py
test_make_migration_create_materialized_view_model
ivanp/django-postgres-extra
529
python
@postgres_patched_migrations() def test_make_migration_create_materialized_view_model(fake_app): 'Tests whether the right operations are generated when creating a new\n materialized view model.' underlying_model = get_fake_model({'name': models.TextField()}) model = define_fake_materialized_view_model(fields={'name': models.TextField()}, view_options=dict(query=underlying_model.objects.all()), meta_options=dict(app_label=fake_app.name)) migration = make_migration(model._meta.app_label) ops = migration.operations assert (len(ops) == 1) assert isinstance(ops[0], operations.PostgresCreateMaterializedViewModel) assert (len(ops[0].bases) == 1) assert issubclass(ops[0].bases[0], PostgresMaterializedViewModel) assert (ops[0].view_options == model._view_meta.original_attrs)
@postgres_patched_migrations() def test_make_migration_create_materialized_view_model(fake_app): 'Tests whether the right operations are generated when creating a new\n materialized view model.' underlying_model = get_fake_model({'name': models.TextField()}) model = define_fake_materialized_view_model(fields={'name': models.TextField()}, view_options=dict(query=underlying_model.objects.all()), meta_options=dict(app_label=fake_app.name)) migration = make_migration(model._meta.app_label) ops = migration.operations assert (len(ops) == 1) assert isinstance(ops[0], operations.PostgresCreateMaterializedViewModel) assert (len(ops[0].bases) == 1) assert issubclass(ops[0].bases[0], PostgresMaterializedViewModel) assert (ops[0].view_options == model._view_meta.original_attrs)<|docstring|>Tests whether the right operations are generated when creating a new materialized view model.<|endoftext|>
179bdf20fc2deadf41b32832ff80393397c0e3f984da79ef807c9fdb492745dc
@pytest.mark.parametrize('define_view_model', [define_fake_materialized_view_model, define_fake_view_model]) @postgres_patched_migrations() def test_make_migration_field_operations_view_models(fake_app, define_view_model): "Tests whether field operations against a (materialized) view are always\n wrapped in the :see:ApplyState operation so that they don't actually get\n applied to the database, yet Django applies to them to the project state.\n\n This is important because you can't actually alter/add or delete\n fields from a (materialized) view.\n " underlying_model = get_fake_model({'first_name': models.TextField(), 'last_name': models.TextField()}, meta_options=dict(app_label=fake_app.name)) model = define_view_model(fields={'first_name': models.TextField()}, view_options=dict(query=underlying_model.objects.all()), meta_options=dict(app_label=fake_app.name)) state_1 = ProjectState.from_apps(apps) migration = make_migration(model._meta.app_label) apply_migration(migration.operations, state_1) last_name_field = models.TextField(null=True) last_name_field.contribute_to_class(model, 'last_name') migration = make_migration(model._meta.app_label, from_state=state_1) assert (len(migration.operations) == 1) assert isinstance(migration.operations[0], operations.ApplyState) assert isinstance(migration.operations[0].state_operation, AddField) state_2 = ProjectState.from_apps(apps) last_name_field = models.TextField(null=True, blank=True) last_name_field.contribute_to_class(model, 'last_name') migration = make_migration(model._meta.app_label, from_state=state_2) assert (len(migration.operations) == 1) assert isinstance(migration.operations[0], operations.ApplyState) assert isinstance(migration.operations[0].state_operation, AlterField) migration = make_migration(model._meta.app_label, from_state=ProjectState.from_apps(apps), to_state=state_1) assert isinstance(migration.operations[0], operations.ApplyState) assert isinstance(migration.operations[0].state_operation, RemoveField)
Tests whether field operations against a (materialized) view are always wrapped in the :see:ApplyState operation so that they don't actually get applied to the database, yet Django applies to them to the project state. This is important because you can't actually alter/add or delete fields from a (materialized) view.
tests/test_make_migrations.py
test_make_migration_field_operations_view_models
ivanp/django-postgres-extra
529
python
@pytest.mark.parametrize('define_view_model', [define_fake_materialized_view_model, define_fake_view_model]) @postgres_patched_migrations() def test_make_migration_field_operations_view_models(fake_app, define_view_model): "Tests whether field operations against a (materialized) view are always\n wrapped in the :see:ApplyState operation so that they don't actually get\n applied to the database, yet Django applies to them to the project state.\n\n This is important because you can't actually alter/add or delete\n fields from a (materialized) view.\n " underlying_model = get_fake_model({'first_name': models.TextField(), 'last_name': models.TextField()}, meta_options=dict(app_label=fake_app.name)) model = define_view_model(fields={'first_name': models.TextField()}, view_options=dict(query=underlying_model.objects.all()), meta_options=dict(app_label=fake_app.name)) state_1 = ProjectState.from_apps(apps) migration = make_migration(model._meta.app_label) apply_migration(migration.operations, state_1) last_name_field = models.TextField(null=True) last_name_field.contribute_to_class(model, 'last_name') migration = make_migration(model._meta.app_label, from_state=state_1) assert (len(migration.operations) == 1) assert isinstance(migration.operations[0], operations.ApplyState) assert isinstance(migration.operations[0].state_operation, AddField) state_2 = ProjectState.from_apps(apps) last_name_field = models.TextField(null=True, blank=True) last_name_field.contribute_to_class(model, 'last_name') migration = make_migration(model._meta.app_label, from_state=state_2) assert (len(migration.operations) == 1) assert isinstance(migration.operations[0], operations.ApplyState) assert isinstance(migration.operations[0].state_operation, AlterField) migration = make_migration(model._meta.app_label, from_state=ProjectState.from_apps(apps), to_state=state_1) assert isinstance(migration.operations[0], operations.ApplyState) assert isinstance(migration.operations[0].state_operation, RemoveField)
@pytest.mark.parametrize('define_view_model', [define_fake_materialized_view_model, define_fake_view_model]) @postgres_patched_migrations() def test_make_migration_field_operations_view_models(fake_app, define_view_model): "Tests whether field operations against a (materialized) view are always\n wrapped in the :see:ApplyState operation so that they don't actually get\n applied to the database, yet Django applies to them to the project state.\n\n This is important because you can't actually alter/add or delete\n fields from a (materialized) view.\n " underlying_model = get_fake_model({'first_name': models.TextField(), 'last_name': models.TextField()}, meta_options=dict(app_label=fake_app.name)) model = define_view_model(fields={'first_name': models.TextField()}, view_options=dict(query=underlying_model.objects.all()), meta_options=dict(app_label=fake_app.name)) state_1 = ProjectState.from_apps(apps) migration = make_migration(model._meta.app_label) apply_migration(migration.operations, state_1) last_name_field = models.TextField(null=True) last_name_field.contribute_to_class(model, 'last_name') migration = make_migration(model._meta.app_label, from_state=state_1) assert (len(migration.operations) == 1) assert isinstance(migration.operations[0], operations.ApplyState) assert isinstance(migration.operations[0].state_operation, AddField) state_2 = ProjectState.from_apps(apps) last_name_field = models.TextField(null=True, blank=True) last_name_field.contribute_to_class(model, 'last_name') migration = make_migration(model._meta.app_label, from_state=state_2) assert (len(migration.operations) == 1) assert isinstance(migration.operations[0], operations.ApplyState) assert isinstance(migration.operations[0].state_operation, AlterField) migration = make_migration(model._meta.app_label, from_state=ProjectState.from_apps(apps), to_state=state_1) assert isinstance(migration.operations[0], operations.ApplyState) assert isinstance(migration.operations[0].state_operation, RemoveField)<|docstring|>Tests whether field operations against a (materialized) view are always wrapped in the :see:ApplyState operation so that they don't actually get applied to the database, yet Django applies to them to the project state. This is important because you can't actually alter/add or delete fields from a (materialized) view.<|endoftext|>
0d6013801cc1b5f2f1d39107288a521794efe9bf324233cf10fde1402f91d953
def removeDuplicates(self, nums) -> int: '\n 读题:\n 1、感觉不难,有两个要求,一个是记录长度,一个是要移动合适的位置\n 2、双指针,第一个指针向下读取,后面指针负责确定当前位置,以及最终长度\n \n 测试:\n 1、一次通过,性能不错\n \n 答案:\n 可以更快,但感觉意义不大了\n \n ' i = 1 newi = 1 doubleFlag = 1 while (i < len(nums)): if (nums[(i - 1)] == nums[i]): doubleFlag += 1 else: doubleFlag = 1 nums[newi] = nums[i] if (doubleFlag < 3): newi += 1 i += 1 return newi
读题: 1、感觉不难,有两个要求,一个是记录长度,一个是要移动合适的位置 2、双指针,第一个指针向下读取,后面指针负责确定当前位置,以及最终长度 测试: 1、一次通过,性能不错 答案: 可以更快,但感觉意义不大了
code/Solution_0080_removeDuplicates.py
removeDuplicates
qizhenkang/myLeetCode
0
python
def removeDuplicates(self, nums) -> int: '\n 读题:\n 1、感觉不难,有两个要求,一个是记录长度,一个是要移动合适的位置\n 2、双指针,第一个指针向下读取,后面指针负责确定当前位置,以及最终长度\n \n 测试:\n 1、一次通过,性能不错\n \n 答案:\n 可以更快,但感觉意义不大了\n \n ' i = 1 newi = 1 doubleFlag = 1 while (i < len(nums)): if (nums[(i - 1)] == nums[i]): doubleFlag += 1 else: doubleFlag = 1 nums[newi] = nums[i] if (doubleFlag < 3): newi += 1 i += 1 return newi
def removeDuplicates(self, nums) -> int: '\n 读题:\n 1、感觉不难,有两个要求,一个是记录长度,一个是要移动合适的位置\n 2、双指针,第一个指针向下读取,后面指针负责确定当前位置,以及最终长度\n \n 测试:\n 1、一次通过,性能不错\n \n 答案:\n 可以更快,但感觉意义不大了\n \n ' i = 1 newi = 1 doubleFlag = 1 while (i < len(nums)): if (nums[(i - 1)] == nums[i]): doubleFlag += 1 else: doubleFlag = 1 nums[newi] = nums[i] if (doubleFlag < 3): newi += 1 i += 1 return newi<|docstring|>读题: 1、感觉不难,有两个要求,一个是记录长度,一个是要移动合适的位置 2、双指针,第一个指针向下读取,后面指针负责确定当前位置,以及最终长度 测试: 1、一次通过,性能不错 答案: 可以更快,但感觉意义不大了<|endoftext|>
b21e1ad3ec8cafb64f1dccd5f2d6d5fecdff6cba87bff1f149d224d26043aff0
def json_serial(obj): 'JSON serializer for objects not serializable by default json code' if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError(('Type %s not serializable' % type(obj)))
JSON serializer for objects not serializable by default json code
crtsh.py
json_serial
malvidin/crt.sh
2
python
def json_serial(obj): if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError(('Type %s not serializable' % type(obj)))
def json_serial(obj): if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError(('Type %s not serializable' % type(obj)))<|docstring|>JSON serializer for objects not serializable by default json code<|endoftext|>
198dcabe037b0f9a87661833a787eacc02a994ef26def4977a6e1da1a5ba3ea1
def get_input(self, idx): '\n Returns x for a given idx.\n ' idx = self.full_idxs[idx] img = Image.open(((self.root / 'images') / f'rgb_img_{idx}.png')).convert('RGB') return img
Returns x for a given idx.
wilds/datasets/fmow_dataset.py
get_input
sequoia-n9/wilds
355
python
def get_input(self, idx): '\n \n ' idx = self.full_idxs[idx] img = Image.open(((self.root / 'images') / f'rgb_img_{idx}.png')).convert('RGB') return img
def get_input(self, idx): '\n \n ' idx = self.full_idxs[idx] img = Image.open(((self.root / 'images') / f'rgb_img_{idx}.png')).convert('RGB') return img<|docstring|>Returns x for a given idx.<|endoftext|>
c7a68bde705f296a54bab076461bd6dd2a5adca1b14908f4e2bb1cd89f53a9a8
def eval(self, y_pred, y_true, metadata, prediction_fn=None): '\n Computes all evaluation metrics.\n Args:\n - y_pred (Tensor): Predictions from a model. By default, they are predicted labels (LongTensor).\n But they can also be other model outputs such that prediction_fn(y_pred)\n are predicted labels.\n - y_true (LongTensor): Ground-truth labels\n - metadata (Tensor): Metadata\n - prediction_fn (function): A function that turns y_pred into predicted labels\n Output:\n - results (dictionary): Dictionary of evaluation metrics\n - results_str (str): String summarizing the evaluation metrics\n ' metric = Accuracy(prediction_fn=prediction_fn) (all_results, all_results_str) = self.standard_group_eval(metric, self._eval_groupers['year'], y_pred, y_true, metadata) region_grouper = self._eval_groupers['region'] region_results = metric.compute_group_wise(y_pred, y_true, region_grouper.metadata_to_group(metadata), region_grouper.n_groups) all_results[f'{metric.name}_worst_year'] = all_results.pop(metric.worst_group_metric_field) region_metric_list = [] for group_idx in range(region_grouper.n_groups): group_str = region_grouper.group_field_str(group_idx) group_metric = region_results[metric.group_metric_field(group_idx)] group_counts = region_results[metric.group_count_field(group_idx)] all_results[f'{metric.name}_{group_str}'] = group_metric all_results[f'count_{group_str}'] = group_counts if ((region_results[metric.group_count_field(group_idx)] == 0) or ('Other' in group_str)): continue all_results_str += f''' {region_grouper.group_str(group_idx)} [n = {region_results[metric.group_count_field(group_idx)]:6.0f}]: {metric.name} = {region_results[metric.group_metric_field(group_idx)]:5.3f} ''' region_metric_list.append(region_results[metric.group_metric_field(group_idx)]) all_results[f'{metric.name}_worst_region'] = metric.worst(region_metric_list) all_results_str += f'''Worst-group {metric.name}: {all_results[f'{metric.name}_worst_region']:.3f} ''' return (all_results, all_results_str)
Computes all evaluation metrics. Args: - y_pred (Tensor): Predictions from a model. By default, they are predicted labels (LongTensor). But they can also be other model outputs such that prediction_fn(y_pred) are predicted labels. - y_true (LongTensor): Ground-truth labels - metadata (Tensor): Metadata - prediction_fn (function): A function that turns y_pred into predicted labels Output: - results (dictionary): Dictionary of evaluation metrics - results_str (str): String summarizing the evaluation metrics
wilds/datasets/fmow_dataset.py
eval
sequoia-n9/wilds
355
python
def eval(self, y_pred, y_true, metadata, prediction_fn=None): '\n Computes all evaluation metrics.\n Args:\n - y_pred (Tensor): Predictions from a model. By default, they are predicted labels (LongTensor).\n But they can also be other model outputs such that prediction_fn(y_pred)\n are predicted labels.\n - y_true (LongTensor): Ground-truth labels\n - metadata (Tensor): Metadata\n - prediction_fn (function): A function that turns y_pred into predicted labels\n Output:\n - results (dictionary): Dictionary of evaluation metrics\n - results_str (str): String summarizing the evaluation metrics\n ' metric = Accuracy(prediction_fn=prediction_fn) (all_results, all_results_str) = self.standard_group_eval(metric, self._eval_groupers['year'], y_pred, y_true, metadata) region_grouper = self._eval_groupers['region'] region_results = metric.compute_group_wise(y_pred, y_true, region_grouper.metadata_to_group(metadata), region_grouper.n_groups) all_results[f'{metric.name}_worst_year'] = all_results.pop(metric.worst_group_metric_field) region_metric_list = [] for group_idx in range(region_grouper.n_groups): group_str = region_grouper.group_field_str(group_idx) group_metric = region_results[metric.group_metric_field(group_idx)] group_counts = region_results[metric.group_count_field(group_idx)] all_results[f'{metric.name}_{group_str}'] = group_metric all_results[f'count_{group_str}'] = group_counts if ((region_results[metric.group_count_field(group_idx)] == 0) or ('Other' in group_str)): continue all_results_str += f' {region_grouper.group_str(group_idx)} [n = {region_results[metric.group_count_field(group_idx)]:6.0f}]: {metric.name} = {region_results[metric.group_metric_field(group_idx)]:5.3f} ' region_metric_list.append(region_results[metric.group_metric_field(group_idx)]) all_results[f'{metric.name}_worst_region'] = metric.worst(region_metric_list) all_results_str += f'Worst-group {metric.name}: {all_results[f'{metric.name}_worst_region']:.3f} ' return (all_results, all_results_str)
def eval(self, y_pred, y_true, metadata, prediction_fn=None): '\n Computes all evaluation metrics.\n Args:\n - y_pred (Tensor): Predictions from a model. By default, they are predicted labels (LongTensor).\n But they can also be other model outputs such that prediction_fn(y_pred)\n are predicted labels.\n - y_true (LongTensor): Ground-truth labels\n - metadata (Tensor): Metadata\n - prediction_fn (function): A function that turns y_pred into predicted labels\n Output:\n - results (dictionary): Dictionary of evaluation metrics\n - results_str (str): String summarizing the evaluation metrics\n ' metric = Accuracy(prediction_fn=prediction_fn) (all_results, all_results_str) = self.standard_group_eval(metric, self._eval_groupers['year'], y_pred, y_true, metadata) region_grouper = self._eval_groupers['region'] region_results = metric.compute_group_wise(y_pred, y_true, region_grouper.metadata_to_group(metadata), region_grouper.n_groups) all_results[f'{metric.name}_worst_year'] = all_results.pop(metric.worst_group_metric_field) region_metric_list = [] for group_idx in range(region_grouper.n_groups): group_str = region_grouper.group_field_str(group_idx) group_metric = region_results[metric.group_metric_field(group_idx)] group_counts = region_results[metric.group_count_field(group_idx)] all_results[f'{metric.name}_{group_str}'] = group_metric all_results[f'count_{group_str}'] = group_counts if ((region_results[metric.group_count_field(group_idx)] == 0) or ('Other' in group_str)): continue all_results_str += f' {region_grouper.group_str(group_idx)} [n = {region_results[metric.group_count_field(group_idx)]:6.0f}]: {metric.name} = {region_results[metric.group_metric_field(group_idx)]:5.3f} ' region_metric_list.append(region_results[metric.group_metric_field(group_idx)]) all_results[f'{metric.name}_worst_region'] = metric.worst(region_metric_list) all_results_str += f'Worst-group {metric.name}: {all_results[f'{metric.name}_worst_region']:.3f} ' return (all_results, all_results_str)<|docstring|>Computes all evaluation metrics. Args: - y_pred (Tensor): Predictions from a model. By default, they are predicted labels (LongTensor). But they can also be other model outputs such that prediction_fn(y_pred) are predicted labels. - y_true (LongTensor): Ground-truth labels - metadata (Tensor): Metadata - prediction_fn (function): A function that turns y_pred into predicted labels Output: - results (dictionary): Dictionary of evaluation metrics - results_str (str): String summarizing the evaluation metrics<|endoftext|>
9abbb4dc8ec71d56bf54a4899beda08da4768cf9367728bcd7beeeb22f810a95
def fd_jenkinson(in_file, rmax=80.0, out_file=None): "\n @ Krsna\n May 2013\n compute\n 1) Jenkinson FD from 3dvolreg's *.affmat12.1D file from -1Dmatrix_save\n option input: subject ID, rest_number, name of 6 parameter motion\n correction file (an output of 3dvolreg) output: FD_J.1D file\n Assumptions: 1) subject is available in BASE_DIR\n 2) 3dvolreg is already performed and the 1D motion parameter and 1D_matrix\n file file is present in sub?/rest_? called as --->'lfo_mc_affmat.1D'\n\n Method to calculate Framewise Displacement (FD) calculations\n (Jenkinson et al., 2002)\n Parameters; in_file : string\n rmax : float\n The default radius (as in FSL) of a sphere represents the brain\n Returns; out_file : string\n NOTE: infile should have one 3dvolreg affine matrix in one row -\n NOT the motion parameters\n " import numpy as np import os import os.path as op from shutil import copyfile import sys import math if (out_file is None): (fname, ext) = op.splitext(op.basename(in_file)) out_file = op.abspath(('%s_fdfile%s' % (fname, ext))) if ('rel.rms' in in_file): copyfile(in_file, out_file) return out_file pm_ = np.genfromtxt(in_file) original_shape = pm_.shape pm = np.zeros((pm_.shape[0], (pm_.shape[1] + 4))) pm[(:, :original_shape[1])] = pm_ pm[(:, original_shape[1]:)] = [0.0, 0.0, 0.0, 1.0] T_rb_prev = np.matrix(np.eye(4)) flag = 0 X = [0] for i in range(0, pm.shape[0]): T_rb = np.matrix(pm[i].reshape(4, 4)) if (flag == 0): flag = 1 else: M = (np.dot(T_rb, T_rb_prev.I) - np.eye(4)) A = M[(0:3, 0:3)] b = M[(0:3, 3)] FD_J = math.sqrt(((((rmax * rmax) / 5) * np.trace(np.dot(A.T, A))) + np.dot(b.T, b))) X.append(FD_J) T_rb_prev = T_rb np.savetxt(out_file, np.array(X)) return out_file
@ Krsna May 2013 compute 1) Jenkinson FD from 3dvolreg's *.affmat12.1D file from -1Dmatrix_save option input: subject ID, rest_number, name of 6 parameter motion correction file (an output of 3dvolreg) output: FD_J.1D file Assumptions: 1) subject is available in BASE_DIR 2) 3dvolreg is already performed and the 1D motion parameter and 1D_matrix file file is present in sub?/rest_? called as --->'lfo_mc_affmat.1D' Method to calculate Framewise Displacement (FD) calculations (Jenkinson et al., 2002) Parameters; in_file : string rmax : float The default radius (as in FSL) of a sphere represents the brain Returns; out_file : string NOTE: infile should have one 3dvolreg affine matrix in one row - NOT the motion parameters
qap/temporal_qc.py
fd_jenkinson
ycq90/my_qap
0
python
def fd_jenkinson(in_file, rmax=80.0, out_file=None): "\n @ Krsna\n May 2013\n compute\n 1) Jenkinson FD from 3dvolreg's *.affmat12.1D file from -1Dmatrix_save\n option input: subject ID, rest_number, name of 6 parameter motion\n correction file (an output of 3dvolreg) output: FD_J.1D file\n Assumptions: 1) subject is available in BASE_DIR\n 2) 3dvolreg is already performed and the 1D motion parameter and 1D_matrix\n file file is present in sub?/rest_? called as --->'lfo_mc_affmat.1D'\n\n Method to calculate Framewise Displacement (FD) calculations\n (Jenkinson et al., 2002)\n Parameters; in_file : string\n rmax : float\n The default radius (as in FSL) of a sphere represents the brain\n Returns; out_file : string\n NOTE: infile should have one 3dvolreg affine matrix in one row -\n NOT the motion parameters\n " import numpy as np import os import os.path as op from shutil import copyfile import sys import math if (out_file is None): (fname, ext) = op.splitext(op.basename(in_file)) out_file = op.abspath(('%s_fdfile%s' % (fname, ext))) if ('rel.rms' in in_file): copyfile(in_file, out_file) return out_file pm_ = np.genfromtxt(in_file) original_shape = pm_.shape pm = np.zeros((pm_.shape[0], (pm_.shape[1] + 4))) pm[(:, :original_shape[1])] = pm_ pm[(:, original_shape[1]:)] = [0.0, 0.0, 0.0, 1.0] T_rb_prev = np.matrix(np.eye(4)) flag = 0 X = [0] for i in range(0, pm.shape[0]): T_rb = np.matrix(pm[i].reshape(4, 4)) if (flag == 0): flag = 1 else: M = (np.dot(T_rb, T_rb_prev.I) - np.eye(4)) A = M[(0:3, 0:3)] b = M[(0:3, 3)] FD_J = math.sqrt(((((rmax * rmax) / 5) * np.trace(np.dot(A.T, A))) + np.dot(b.T, b))) X.append(FD_J) T_rb_prev = T_rb np.savetxt(out_file, np.array(X)) return out_file
def fd_jenkinson(in_file, rmax=80.0, out_file=None): "\n @ Krsna\n May 2013\n compute\n 1) Jenkinson FD from 3dvolreg's *.affmat12.1D file from -1Dmatrix_save\n option input: subject ID, rest_number, name of 6 parameter motion\n correction file (an output of 3dvolreg) output: FD_J.1D file\n Assumptions: 1) subject is available in BASE_DIR\n 2) 3dvolreg is already performed and the 1D motion parameter and 1D_matrix\n file file is present in sub?/rest_? called as --->'lfo_mc_affmat.1D'\n\n Method to calculate Framewise Displacement (FD) calculations\n (Jenkinson et al., 2002)\n Parameters; in_file : string\n rmax : float\n The default radius (as in FSL) of a sphere represents the brain\n Returns; out_file : string\n NOTE: infile should have one 3dvolreg affine matrix in one row -\n NOT the motion parameters\n " import numpy as np import os import os.path as op from shutil import copyfile import sys import math if (out_file is None): (fname, ext) = op.splitext(op.basename(in_file)) out_file = op.abspath(('%s_fdfile%s' % (fname, ext))) if ('rel.rms' in in_file): copyfile(in_file, out_file) return out_file pm_ = np.genfromtxt(in_file) original_shape = pm_.shape pm = np.zeros((pm_.shape[0], (pm_.shape[1] + 4))) pm[(:, :original_shape[1])] = pm_ pm[(:, original_shape[1]:)] = [0.0, 0.0, 0.0, 1.0] T_rb_prev = np.matrix(np.eye(4)) flag = 0 X = [0] for i in range(0, pm.shape[0]): T_rb = np.matrix(pm[i].reshape(4, 4)) if (flag == 0): flag = 1 else: M = (np.dot(T_rb, T_rb_prev.I) - np.eye(4)) A = M[(0:3, 0:3)] b = M[(0:3, 3)] FD_J = math.sqrt(((((rmax * rmax) / 5) * np.trace(np.dot(A.T, A))) + np.dot(b.T, b))) X.append(FD_J) T_rb_prev = T_rb np.savetxt(out_file, np.array(X)) return out_file<|docstring|>@ Krsna May 2013 compute 1) Jenkinson FD from 3dvolreg's *.affmat12.1D file from -1Dmatrix_save option input: subject ID, rest_number, name of 6 parameter motion correction file (an output of 3dvolreg) output: FD_J.1D file Assumptions: 1) subject is available in BASE_DIR 2) 3dvolreg is already performed and the 1D motion parameter and 1D_matrix file file is present in sub?/rest_? called as --->'lfo_mc_affmat.1D' Method to calculate Framewise Displacement (FD) calculations (Jenkinson et al., 2002) Parameters; in_file : string rmax : float The default radius (as in FSL) of a sphere represents the brain Returns; out_file : string NOTE: infile should have one 3dvolreg affine matrix in one row - NOT the motion parameters<|endoftext|>
2cf7055e54bbf05e6dc057827fe06e3fd883b58778dff5becb0ee7bf54285183
def outlier_timepoints(func_file, mask_file, out_fraction=True): "\n Calculates the number of 'outliers' in a 4D functional dataset,\n at each time-point.\n\n Will call on AFNI's 3dToutcount.\n\n Parameters\n ----------\n func_file: str\n Path to 4D functional file (could be motion corrected or not??)\n mask_file: str\n Path to functional brain mask\n out_fraction: bool (default: True)\n Whether the output should be a count (False) or fraction (True)\n of the number of masked voxels which are outliers at each time point.\n\n Returns\n -------\n outliers: list\n " import commands import re opts = [] if out_fraction: opts.append('-fraction') opts.append(('-mask %s' % mask_file)) opts.append(func_file) str_opts = ' '.join(opts) cmd = ('3dToutcount %s' % str_opts) out = commands.getoutput(cmd) lines = out.splitlines() outliers = [float(l) for l in lines if re.match('[0-9]+$', l.strip())] return outliers
Calculates the number of 'outliers' in a 4D functional dataset, at each time-point. Will call on AFNI's 3dToutcount. Parameters ---------- func_file: str Path to 4D functional file (could be motion corrected or not??) mask_file: str Path to functional brain mask out_fraction: bool (default: True) Whether the output should be a count (False) or fraction (True) of the number of masked voxels which are outliers at each time point. Returns ------- outliers: list
qap/temporal_qc.py
outlier_timepoints
ycq90/my_qap
0
python
def outlier_timepoints(func_file, mask_file, out_fraction=True): "\n Calculates the number of 'outliers' in a 4D functional dataset,\n at each time-point.\n\n Will call on AFNI's 3dToutcount.\n\n Parameters\n ----------\n func_file: str\n Path to 4D functional file (could be motion corrected or not??)\n mask_file: str\n Path to functional brain mask\n out_fraction: bool (default: True)\n Whether the output should be a count (False) or fraction (True)\n of the number of masked voxels which are outliers at each time point.\n\n Returns\n -------\n outliers: list\n " import commands import re opts = [] if out_fraction: opts.append('-fraction') opts.append(('-mask %s' % mask_file)) opts.append(func_file) str_opts = ' '.join(opts) cmd = ('3dToutcount %s' % str_opts) out = commands.getoutput(cmd) lines = out.splitlines() outliers = [float(l) for l in lines if re.match('[0-9]+$', l.strip())] return outliers
def outlier_timepoints(func_file, mask_file, out_fraction=True): "\n Calculates the number of 'outliers' in a 4D functional dataset,\n at each time-point.\n\n Will call on AFNI's 3dToutcount.\n\n Parameters\n ----------\n func_file: str\n Path to 4D functional file (could be motion corrected or not??)\n mask_file: str\n Path to functional brain mask\n out_fraction: bool (default: True)\n Whether the output should be a count (False) or fraction (True)\n of the number of masked voxels which are outliers at each time point.\n\n Returns\n -------\n outliers: list\n " import commands import re opts = [] if out_fraction: opts.append('-fraction') opts.append(('-mask %s' % mask_file)) opts.append(func_file) str_opts = ' '.join(opts) cmd = ('3dToutcount %s' % str_opts) out = commands.getoutput(cmd) lines = out.splitlines() outliers = [float(l) for l in lines if re.match('[0-9]+$', l.strip())] return outliers<|docstring|>Calculates the number of 'outliers' in a 4D functional dataset, at each time-point. Will call on AFNI's 3dToutcount. Parameters ---------- func_file: str Path to 4D functional file (could be motion corrected or not??) mask_file: str Path to functional brain mask out_fraction: bool (default: True) Whether the output should be a count (False) or fraction (True) of the number of masked voxels which are outliers at each time point. Returns ------- outliers: list<|endoftext|>
5773ad4eb19a92155ec0815e2bcbb16019e62b8008dc06989425714c00cd6139
def quality_timepoints(func_file, automask=True): "\n Calculates a 'quality index' for each timepoint in the 4D functional\n dataset. Low values are good and indicate that the timepoint is not very\n different from the norm.\n " import subprocess opts = [] if automask: opts.append('-automask') opts.append(func_file) str_opts = ' '.join(opts) cmd = ('3dTqual %s' % str_opts) p = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = p.communicate() lines = out.splitlines() lines = [l for l in lines if (l[:2] != '++')] outliers = [float(l.strip()) for l in lines] return outliers
Calculates a 'quality index' for each timepoint in the 4D functional dataset. Low values are good and indicate that the timepoint is not very different from the norm.
qap/temporal_qc.py
quality_timepoints
ycq90/my_qap
0
python
def quality_timepoints(func_file, automask=True): "\n Calculates a 'quality index' for each timepoint in the 4D functional\n dataset. Low values are good and indicate that the timepoint is not very\n different from the norm.\n " import subprocess opts = [] if automask: opts.append('-automask') opts.append(func_file) str_opts = ' '.join(opts) cmd = ('3dTqual %s' % str_opts) p = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = p.communicate() lines = out.splitlines() lines = [l for l in lines if (l[:2] != '++')] outliers = [float(l.strip()) for l in lines] return outliers
def quality_timepoints(func_file, automask=True): "\n Calculates a 'quality index' for each timepoint in the 4D functional\n dataset. Low values are good and indicate that the timepoint is not very\n different from the norm.\n " import subprocess opts = [] if automask: opts.append('-automask') opts.append(func_file) str_opts = ' '.join(opts) cmd = ('3dTqual %s' % str_opts) p = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = p.communicate() lines = out.splitlines() lines = [l for l in lines if (l[:2] != '++')] outliers = [float(l.strip()) for l in lines] return outliers<|docstring|>Calculates a 'quality index' for each timepoint in the 4D functional dataset. Low values are good and indicate that the timepoint is not very different from the norm.<|endoftext|>
8fd78071f5fc50b95a58d73e3e378b5eecc2c042e7dfac65b9b02ed77ce9d1f9
def is_oid_eq(x: ObjectIdentifier, y: ObjectIdentifier) -> bool: 'Check if two ASN.1 object identifiers are equal' if (len(x) != len(y)): return False for (i, j) in zip(x, y): i_id = (i if isinstance(i, int) else i[1]) j_id = (j if isinstance(j, int) else j[1]) if (i_id != j_id): return False return True
Check if two ASN.1 object identifiers are equal
src_py/hat/asn1/common.py
is_oid_eq
hat-open/hat-asn1
1
python
def is_oid_eq(x: ObjectIdentifier, y: ObjectIdentifier) -> bool: if (len(x) != len(y)): return False for (i, j) in zip(x, y): i_id = (i if isinstance(i, int) else i[1]) j_id = (j if isinstance(j, int) else j[1]) if (i_id != j_id): return False return True
def is_oid_eq(x: ObjectIdentifier, y: ObjectIdentifier) -> bool: if (len(x) != len(y)): return False for (i, j) in zip(x, y): i_id = (i if isinstance(i, int) else i[1]) j_id = (j if isinstance(j, int) else j[1]) if (i_id != j_id): return False return True<|docstring|>Check if two ASN.1 object identifiers are equal<|endoftext|>
31602434793f85c829c0338ef30905b8d3ba2c2520b984e6878b7d865cc8698f
def type_to_json(t: Type) -> json.Data: 'Convert type definition to JSON data' if isinstance(t, TypeRef): return ['TypeRef', t.module, t.name] if isinstance(t, BooleanType): return ['BooleanType'] if isinstance(t, IntegerType): return ['IntegerType'] if isinstance(t, BitStringType): return ['BitStringType'] if isinstance(t, OctetStringType): return ['OctetStringType'] if isinstance(t, ObjectIdentifierType): return ['ObjectIdentifierType'] if isinstance(t, NullType): return ['NullType'] if isinstance(t, StringType): return ['StringType', t.name] if isinstance(t, ExternalType): return ['ExternalType'] if isinstance(t, RealType): return ['RealType'] if isinstance(t, EnumeratedType): return ['EnumeratedType'] if isinstance(t, EmbeddedPDVType): return ['EmbeddedPDVType'] if isinstance(t, ChoiceType): return ['ChoiceType', [[i.name, type_to_json(i.type)] for i in t.choices]] if isinstance(t, SetType): return ['SetType', [[i.name, type_to_json(i.type), i.optional] for i in t.elements]] if isinstance(t, SetOfType): return ['SetOfType', type_to_json(t.type)] if isinstance(t, SequenceType): return ['SequenceType', [[i.name, type_to_json(i.type), i.optional] for i in t.elements]] if isinstance(t, SequenceOfType): return ['SequenceOfType', type_to_json(t.type)] if isinstance(t, EntityType): return ['EntityType'] if isinstance(t, UnsupportedType): return ['UnsupportedType'] if isinstance(t, PrefixedType): return ['PrefixedType', type_to_json(t.type), t.class_type.name, t.tag_number, t.implicit] raise ValueError('invalid type definition')
Convert type definition to JSON data
src_py/hat/asn1/common.py
type_to_json
hat-open/hat-asn1
1
python
def type_to_json(t: Type) -> json.Data: if isinstance(t, TypeRef): return ['TypeRef', t.module, t.name] if isinstance(t, BooleanType): return ['BooleanType'] if isinstance(t, IntegerType): return ['IntegerType'] if isinstance(t, BitStringType): return ['BitStringType'] if isinstance(t, OctetStringType): return ['OctetStringType'] if isinstance(t, ObjectIdentifierType): return ['ObjectIdentifierType'] if isinstance(t, NullType): return ['NullType'] if isinstance(t, StringType): return ['StringType', t.name] if isinstance(t, ExternalType): return ['ExternalType'] if isinstance(t, RealType): return ['RealType'] if isinstance(t, EnumeratedType): return ['EnumeratedType'] if isinstance(t, EmbeddedPDVType): return ['EmbeddedPDVType'] if isinstance(t, ChoiceType): return ['ChoiceType', [[i.name, type_to_json(i.type)] for i in t.choices]] if isinstance(t, SetType): return ['SetType', [[i.name, type_to_json(i.type), i.optional] for i in t.elements]] if isinstance(t, SetOfType): return ['SetOfType', type_to_json(t.type)] if isinstance(t, SequenceType): return ['SequenceType', [[i.name, type_to_json(i.type), i.optional] for i in t.elements]] if isinstance(t, SequenceOfType): return ['SequenceOfType', type_to_json(t.type)] if isinstance(t, EntityType): return ['EntityType'] if isinstance(t, UnsupportedType): return ['UnsupportedType'] if isinstance(t, PrefixedType): return ['PrefixedType', type_to_json(t.type), t.class_type.name, t.tag_number, t.implicit] raise ValueError('invalid type definition')
def type_to_json(t: Type) -> json.Data: if isinstance(t, TypeRef): return ['TypeRef', t.module, t.name] if isinstance(t, BooleanType): return ['BooleanType'] if isinstance(t, IntegerType): return ['IntegerType'] if isinstance(t, BitStringType): return ['BitStringType'] if isinstance(t, OctetStringType): return ['OctetStringType'] if isinstance(t, ObjectIdentifierType): return ['ObjectIdentifierType'] if isinstance(t, NullType): return ['NullType'] if isinstance(t, StringType): return ['StringType', t.name] if isinstance(t, ExternalType): return ['ExternalType'] if isinstance(t, RealType): return ['RealType'] if isinstance(t, EnumeratedType): return ['EnumeratedType'] if isinstance(t, EmbeddedPDVType): return ['EmbeddedPDVType'] if isinstance(t, ChoiceType): return ['ChoiceType', [[i.name, type_to_json(i.type)] for i in t.choices]] if isinstance(t, SetType): return ['SetType', [[i.name, type_to_json(i.type), i.optional] for i in t.elements]] if isinstance(t, SetOfType): return ['SetOfType', type_to_json(t.type)] if isinstance(t, SequenceType): return ['SequenceType', [[i.name, type_to_json(i.type), i.optional] for i in t.elements]] if isinstance(t, SequenceOfType): return ['SequenceOfType', type_to_json(t.type)] if isinstance(t, EntityType): return ['EntityType'] if isinstance(t, UnsupportedType): return ['UnsupportedType'] if isinstance(t, PrefixedType): return ['PrefixedType', type_to_json(t.type), t.class_type.name, t.tag_number, t.implicit] raise ValueError('invalid type definition')<|docstring|>Convert type definition to JSON data<|endoftext|>
a6edb52e4516a29492224ba8db818f73360975f35b291e807a39eae3e1ffeb29
def type_from_json(data: json.Data) -> Type: 'Convert JSON data to type definition' if (data[0] == 'TypeRef'): return TypeRef(module=data[1], name=data[2]) if (data[0] == 'BooleanType'): return BooleanType() if (data[0] == 'IntegerType'): return IntegerType() if (data[0] == 'BitStringType'): return BitStringType() if (data[0] == 'OctetStringType'): return OctetStringType() if (data[0] == 'NullType'): return NullType() if (data[0] == 'ObjectIdentifierType'): return ObjectIdentifierType() if (data[0] == 'StringType'): return StringType[data[1]] if (data[0] == 'ExternalType'): return ExternalType() if (data[0] == 'RealType'): return RealType() if (data[0] == 'EnumeratedType'): return EnumeratedType() if (data[0] == 'EmbeddedPDVType'): return EmbeddedPDVType() if (data[0] == 'ChoiceType'): return ChoiceType([TypeProperty(name=i[0], type=type_from_json(i[1])) for i in data[1]]) if (data[0] == 'SetType'): return SetType([TypeProperty(name=i[0], type=type_from_json(i[1]), optional=i[2]) for i in data[1]]) if (data[0] == 'SetOfType'): return SetOfType(type_from_json(data[1])) if (data[0] == 'SequenceType'): return SequenceType([TypeProperty(name=i[0], type=type_from_json(i[1]), optional=i[2]) for i in data[1]]) if (data[0] == 'SequenceOfType'): return SequenceOfType(type_from_json(data[1])) if (data[0] == 'EntityType'): return EntityType() if (data[0] == 'UnsupportedType'): return UnsupportedType() if (data[0] == 'PrefixedType'): return PrefixedType(type=type_from_json(data[1]), class_type=ClassType[data[2]], tag_number=data[3], implicit=data[4]) raise ValueError('invalid data')
Convert JSON data to type definition
src_py/hat/asn1/common.py
type_from_json
hat-open/hat-asn1
1
python
def type_from_json(data: json.Data) -> Type: if (data[0] == 'TypeRef'): return TypeRef(module=data[1], name=data[2]) if (data[0] == 'BooleanType'): return BooleanType() if (data[0] == 'IntegerType'): return IntegerType() if (data[0] == 'BitStringType'): return BitStringType() if (data[0] == 'OctetStringType'): return OctetStringType() if (data[0] == 'NullType'): return NullType() if (data[0] == 'ObjectIdentifierType'): return ObjectIdentifierType() if (data[0] == 'StringType'): return StringType[data[1]] if (data[0] == 'ExternalType'): return ExternalType() if (data[0] == 'RealType'): return RealType() if (data[0] == 'EnumeratedType'): return EnumeratedType() if (data[0] == 'EmbeddedPDVType'): return EmbeddedPDVType() if (data[0] == 'ChoiceType'): return ChoiceType([TypeProperty(name=i[0], type=type_from_json(i[1])) for i in data[1]]) if (data[0] == 'SetType'): return SetType([TypeProperty(name=i[0], type=type_from_json(i[1]), optional=i[2]) for i in data[1]]) if (data[0] == 'SetOfType'): return SetOfType(type_from_json(data[1])) if (data[0] == 'SequenceType'): return SequenceType([TypeProperty(name=i[0], type=type_from_json(i[1]), optional=i[2]) for i in data[1]]) if (data[0] == 'SequenceOfType'): return SequenceOfType(type_from_json(data[1])) if (data[0] == 'EntityType'): return EntityType() if (data[0] == 'UnsupportedType'): return UnsupportedType() if (data[0] == 'PrefixedType'): return PrefixedType(type=type_from_json(data[1]), class_type=ClassType[data[2]], tag_number=data[3], implicit=data[4]) raise ValueError('invalid data')
def type_from_json(data: json.Data) -> Type: if (data[0] == 'TypeRef'): return TypeRef(module=data[1], name=data[2]) if (data[0] == 'BooleanType'): return BooleanType() if (data[0] == 'IntegerType'): return IntegerType() if (data[0] == 'BitStringType'): return BitStringType() if (data[0] == 'OctetStringType'): return OctetStringType() if (data[0] == 'NullType'): return NullType() if (data[0] == 'ObjectIdentifierType'): return ObjectIdentifierType() if (data[0] == 'StringType'): return StringType[data[1]] if (data[0] == 'ExternalType'): return ExternalType() if (data[0] == 'RealType'): return RealType() if (data[0] == 'EnumeratedType'): return EnumeratedType() if (data[0] == 'EmbeddedPDVType'): return EmbeddedPDVType() if (data[0] == 'ChoiceType'): return ChoiceType([TypeProperty(name=i[0], type=type_from_json(i[1])) for i in data[1]]) if (data[0] == 'SetType'): return SetType([TypeProperty(name=i[0], type=type_from_json(i[1]), optional=i[2]) for i in data[1]]) if (data[0] == 'SetOfType'): return SetOfType(type_from_json(data[1])) if (data[0] == 'SequenceType'): return SequenceType([TypeProperty(name=i[0], type=type_from_json(i[1]), optional=i[2]) for i in data[1]]) if (data[0] == 'SequenceOfType'): return SequenceOfType(type_from_json(data[1])) if (data[0] == 'EntityType'): return EntityType() if (data[0] == 'UnsupportedType'): return UnsupportedType() if (data[0] == 'PrefixedType'): return PrefixedType(type=type_from_json(data[1]), class_type=ClassType[data[2]], tag_number=data[3], implicit=data[4]) raise ValueError('invalid data')<|docstring|>Convert JSON data to type definition<|endoftext|>
32c076d7c938e1414c6641bbe9bc1c27e56c65262d5952a760dadeff25f95051
def _purify_trainers(trainers: Sequence[MultilossTrainer], enn: base.EpistemicNetwork) -> Sequence[_PureTrainer]: 'Converts MultilossTrainer to have *pure* loss function including enn.' pure_trainers = [] for t in trainers: pure_trainer = _PureTrainer(pure_loss=jax.jit(functools.partial(t.loss_fn, enn)), dataset=t.dataset, should_train=t.should_train, name=t.name) pure_trainers.append(pure_trainer) return tuple(pure_trainers)
Converts MultilossTrainer to have *pure* loss function including enn.
enn/supervised/multiloss_experiment.py
_purify_trainers
deepmind/enn
130
python
def _purify_trainers(trainers: Sequence[MultilossTrainer], enn: base.EpistemicNetwork) -> Sequence[_PureTrainer]: pure_trainers = [] for t in trainers: pure_trainer = _PureTrainer(pure_loss=jax.jit(functools.partial(t.loss_fn, enn)), dataset=t.dataset, should_train=t.should_train, name=t.name) pure_trainers.append(pure_trainer) return tuple(pure_trainers)
def _purify_trainers(trainers: Sequence[MultilossTrainer], enn: base.EpistemicNetwork) -> Sequence[_PureTrainer]: pure_trainers = [] for t in trainers: pure_trainer = _PureTrainer(pure_loss=jax.jit(functools.partial(t.loss_fn, enn)), dataset=t.dataset, should_train=t.should_train, name=t.name) pure_trainers.append(pure_trainer) return tuple(pure_trainers)<|docstring|>Converts MultilossTrainer to have *pure* loss function including enn.<|endoftext|>
f523e9c0c129dcd4eece19992db24eae1bf3316be5c7509880412f98926e2554
def train(self, num_batches: int): 'Train the ENN for num_batches.' for _ in range(num_batches): self.step += 1 for t in self.pure_trainers: if t.should_train(self.step): (self.state, loss_metrics) = self._sgd_step(t.pure_loss, self.state, next(t.dataset), next(self.rng)) if ((self.step % self._train_log_freq) == 0): loss_metrics.update({'dataset': 'train', 'step': self.step, 'sgd': True, 'trainer': t.name}) self.logger.write(loss_metrics) if (self._eval_datasets and ((self.step % self._eval_log_freq) == 0)): for (name, dataset) in self._eval_datasets.items(): for t in self.pure_trainers: (loss, metrics) = t.pure_loss(self.state.params, next(dataset), next(self.rng)) metrics.update({'dataset': name, 'step': self.step, 'sgd': False, 'loss': loss, 'trainer': t.name}) self.logger.write(metrics)
Train the ENN for num_batches.
enn/supervised/multiloss_experiment.py
train
deepmind/enn
130
python
def train(self, num_batches: int): for _ in range(num_batches): self.step += 1 for t in self.pure_trainers: if t.should_train(self.step): (self.state, loss_metrics) = self._sgd_step(t.pure_loss, self.state, next(t.dataset), next(self.rng)) if ((self.step % self._train_log_freq) == 0): loss_metrics.update({'dataset': 'train', 'step': self.step, 'sgd': True, 'trainer': t.name}) self.logger.write(loss_metrics) if (self._eval_datasets and ((self.step % self._eval_log_freq) == 0)): for (name, dataset) in self._eval_datasets.items(): for t in self.pure_trainers: (loss, metrics) = t.pure_loss(self.state.params, next(dataset), next(self.rng)) metrics.update({'dataset': name, 'step': self.step, 'sgd': False, 'loss': loss, 'trainer': t.name}) self.logger.write(metrics)
def train(self, num_batches: int): for _ in range(num_batches): self.step += 1 for t in self.pure_trainers: if t.should_train(self.step): (self.state, loss_metrics) = self._sgd_step(t.pure_loss, self.state, next(t.dataset), next(self.rng)) if ((self.step % self._train_log_freq) == 0): loss_metrics.update({'dataset': 'train', 'step': self.step, 'sgd': True, 'trainer': t.name}) self.logger.write(loss_metrics) if (self._eval_datasets and ((self.step % self._eval_log_freq) == 0)): for (name, dataset) in self._eval_datasets.items(): for t in self.pure_trainers: (loss, metrics) = t.pure_loss(self.state.params, next(dataset), next(self.rng)) metrics.update({'dataset': name, 'step': self.step, 'sgd': False, 'loss': loss, 'trainer': t.name}) self.logger.write(metrics)<|docstring|>Train the ENN for num_batches.<|endoftext|>
76359575662909e9e7fda9ddeabb873cb13acc28c9ea8e990d8f77c63dd8d9c3
def predict(self, inputs: base.Array, key: base.RngKey) -> base.Array: 'Evaluate the trained model at given inputs.' return self._forward(self.state.params, inputs, key)
Evaluate the trained model at given inputs.
enn/supervised/multiloss_experiment.py
predict
deepmind/enn
130
python
def predict(self, inputs: base.Array, key: base.RngKey) -> base.Array: return self._forward(self.state.params, inputs, key)
def predict(self, inputs: base.Array, key: base.RngKey) -> base.Array: return self._forward(self.state.params, inputs, key)<|docstring|>Evaluate the trained model at given inputs.<|endoftext|>
e34edcd4f07bce0c93a68d574154aea4bf428f73d0d68b2826f3384258fbc5f7
def loss(self, batch: base.Batch, key: base.RngKey) -> base.Array: 'Evaluate the first loss for one batch of data.' pure_loss = self.pure_trainers[0].pure_loss return pure_loss(self.state.params, batch, key)
Evaluate the first loss for one batch of data.
enn/supervised/multiloss_experiment.py
loss
deepmind/enn
130
python
def loss(self, batch: base.Batch, key: base.RngKey) -> base.Array: pure_loss = self.pure_trainers[0].pure_loss return pure_loss(self.state.params, batch, key)
def loss(self, batch: base.Batch, key: base.RngKey) -> base.Array: pure_loss = self.pure_trainers[0].pure_loss return pure_loss(self.state.params, batch, key)<|docstring|>Evaluate the first loss for one batch of data.<|endoftext|>
2ad84da7ca2ae619379dafa01d7eb7616cde8555983cab1f56ee01d66687bf25
def j2_environment_params(): ' Extra parameters for the Jinja2 Environment ' return dict(block_start_string='<%', block_end_string='%>', variable_start_string='<<', variable_end_string='>>', trim_blocks=True, lstrip_blocks=True, line_statement_prefix='#', keep_trailing_newline=True, extensions=('jinja2.ext.i18n',))
Extra parameters for the Jinja2 Environment
tests/resources/customize.py
j2_environment_params
blaggacao/j2cli
641
python
def j2_environment_params(): ' ' return dict(block_start_string='<%', block_end_string='%>', variable_start_string='<<', variable_end_string='>>', trim_blocks=True, lstrip_blocks=True, line_statement_prefix='#', keep_trailing_newline=True, extensions=('jinja2.ext.i18n',))
def j2_environment_params(): ' ' return dict(block_start_string='<%', block_end_string='%>', variable_start_string='<<', variable_end_string='>>', trim_blocks=True, lstrip_blocks=True, line_statement_prefix='#', keep_trailing_newline=True, extensions=('jinja2.ext.i18n',))<|docstring|>Extra parameters for the Jinja2 Environment<|endoftext|>
5d8e6079f526c5537908d12988de50638fc8a11050daac6406a25a101bb41a8c
def j2_environment(env): ' Modify Jinja2 environment\n\n :param env: jinja2.environment.Environment\n :rtype: jinja2.environment.Environment\n ' env.globals.update(my_function=(lambda v: 'my function says "{}"'.format(v))) return env
Modify Jinja2 environment :param env: jinja2.environment.Environment :rtype: jinja2.environment.Environment
tests/resources/customize.py
j2_environment
blaggacao/j2cli
641
python
def j2_environment(env): ' Modify Jinja2 environment\n\n :param env: jinja2.environment.Environment\n :rtype: jinja2.environment.Environment\n ' env.globals.update(my_function=(lambda v: 'my function says "{}"'.format(v))) return env
def j2_environment(env): ' Modify Jinja2 environment\n\n :param env: jinja2.environment.Environment\n :rtype: jinja2.environment.Environment\n ' env.globals.update(my_function=(lambda v: 'my function says "{}"'.format(v))) return env<|docstring|>Modify Jinja2 environment :param env: jinja2.environment.Environment :rtype: jinja2.environment.Environment<|endoftext|>
afe4dec4a6884736f2a70965444ef8944a4535bc6e107fd3abb40c5eec0db149
def alter_context(context): ' Modify the context and return it ' context['ADD'] = '127' return context
Modify the context and return it
tests/resources/customize.py
alter_context
blaggacao/j2cli
641
python
def alter_context(context): ' ' context['ADD'] = '127' return context
def alter_context(context): ' ' context['ADD'] = '127' return context<|docstring|>Modify the context and return it<|endoftext|>
5892bd2df79a7ea71350e673ba07aa6e536c7bae2167c9788acbb703f538e9ed
def extra_filters(): ' Declare some custom filters.\n\n Returns: dict(name = function)\n ' return dict(parentheses=(lambda t: (('(' + t) + ')')))
Declare some custom filters. Returns: dict(name = function)
tests/resources/customize.py
extra_filters
blaggacao/j2cli
641
python
def extra_filters(): ' Declare some custom filters.\n\n Returns: dict(name = function)\n ' return dict(parentheses=(lambda t: (('(' + t) + ')')))
def extra_filters(): ' Declare some custom filters.\n\n Returns: dict(name = function)\n ' return dict(parentheses=(lambda t: (('(' + t) + ')')))<|docstring|>Declare some custom filters. Returns: dict(name = function)<|endoftext|>
0a7d9c3b9333de5dc334b84aaa1aadebd6507dc2535941dc5a0a5e89bee12d32
def extra_tests(): ' Declare some custom tests\n\n Returns: dict(name = function)\n ' return dict(custom_odd=(lambda n: (True if (n % 2) else False)))
Declare some custom tests Returns: dict(name = function)
tests/resources/customize.py
extra_tests
blaggacao/j2cli
641
python
def extra_tests(): ' Declare some custom tests\n\n Returns: dict(name = function)\n ' return dict(custom_odd=(lambda n: (True if (n % 2) else False)))
def extra_tests(): ' Declare some custom tests\n\n Returns: dict(name = function)\n ' return dict(custom_odd=(lambda n: (True if (n % 2) else False)))<|docstring|>Declare some custom tests Returns: dict(name = function)<|endoftext|>
57d99027ceffea38aef5244e27201aa618d0774018f5cf1d19e49a035473eefa
def svd_wrapper(X, rank=None): '\n Computes the (possibly partial) SVD of a matrix. Handles the case where\n X is either dense or sparse.\n\n Parameters\n ----------\n X: array-like, shape (N, D)\n\n rank: int, None\n rank of the desired SVD.\n If None, will compute the largest min(X.shape) singular value/vectors.\n\n Output\n ------\n U, D, V\n\n U: array-like, shape (N, rank)\n Orthonormal matrix of left singular vectors.\n\n D: list, shape (rank, )\n Singular values in non-increasing order (e.g. D[0] is the largest).\n\n V: array-like, shape (D, rank)\n Orthonormal matrix of right singular vectors\n\n ' if (rank is None): rank = min(X.shape) rank = int(rank) assert ((1 <= rank) and (rank <= min(X.shape))) if (rank <= (min(X.shape) - 1)): scipy_svds = svds(X, rank) (U, D, V) = fix_scipy_svds(scipy_svds) else: assert (not issparse(X)) (U, D, V) = full_svd(X, full_matrices=False) V = V.T if rank: U = U[(:, :rank)] D = D[:rank] V = V[(:, :rank)] (U, V) = svd_flip(U, V.T) V = V.T return (U, D, V)
Computes the (possibly partial) SVD of a matrix. Handles the case where X is either dense or sparse. Parameters ---------- X: array-like, shape (N, D) rank: int, None rank of the desired SVD. If None, will compute the largest min(X.shape) singular value/vectors. Output ------ U, D, V U: array-like, shape (N, rank) Orthonormal matrix of left singular vectors. D: list, shape (rank, ) Singular values in non-increasing order (e.g. D[0] is the largest). V: array-like, shape (D, rank) Orthonormal matrix of right singular vectors
ya_pca/linalg_utils.py
svd_wrapper
idc9/ya_pca
6
python
def svd_wrapper(X, rank=None): '\n Computes the (possibly partial) SVD of a matrix. Handles the case where\n X is either dense or sparse.\n\n Parameters\n ----------\n X: array-like, shape (N, D)\n\n rank: int, None\n rank of the desired SVD.\n If None, will compute the largest min(X.shape) singular value/vectors.\n\n Output\n ------\n U, D, V\n\n U: array-like, shape (N, rank)\n Orthonormal matrix of left singular vectors.\n\n D: list, shape (rank, )\n Singular values in non-increasing order (e.g. D[0] is the largest).\n\n V: array-like, shape (D, rank)\n Orthonormal matrix of right singular vectors\n\n ' if (rank is None): rank = min(X.shape) rank = int(rank) assert ((1 <= rank) and (rank <= min(X.shape))) if (rank <= (min(X.shape) - 1)): scipy_svds = svds(X, rank) (U, D, V) = fix_scipy_svds(scipy_svds) else: assert (not issparse(X)) (U, D, V) = full_svd(X, full_matrices=False) V = V.T if rank: U = U[(:, :rank)] D = D[:rank] V = V[(:, :rank)] (U, V) = svd_flip(U, V.T) V = V.T return (U, D, V)
def svd_wrapper(X, rank=None): '\n Computes the (possibly partial) SVD of a matrix. Handles the case where\n X is either dense or sparse.\n\n Parameters\n ----------\n X: array-like, shape (N, D)\n\n rank: int, None\n rank of the desired SVD.\n If None, will compute the largest min(X.shape) singular value/vectors.\n\n Output\n ------\n U, D, V\n\n U: array-like, shape (N, rank)\n Orthonormal matrix of left singular vectors.\n\n D: list, shape (rank, )\n Singular values in non-increasing order (e.g. D[0] is the largest).\n\n V: array-like, shape (D, rank)\n Orthonormal matrix of right singular vectors\n\n ' if (rank is None): rank = min(X.shape) rank = int(rank) assert ((1 <= rank) and (rank <= min(X.shape))) if (rank <= (min(X.shape) - 1)): scipy_svds = svds(X, rank) (U, D, V) = fix_scipy_svds(scipy_svds) else: assert (not issparse(X)) (U, D, V) = full_svd(X, full_matrices=False) V = V.T if rank: U = U[(:, :rank)] D = D[:rank] V = V[(:, :rank)] (U, V) = svd_flip(U, V.T) V = V.T return (U, D, V)<|docstring|>Computes the (possibly partial) SVD of a matrix. Handles the case where X is either dense or sparse. Parameters ---------- X: array-like, shape (N, D) rank: int, None rank of the desired SVD. If None, will compute the largest min(X.shape) singular value/vectors. Output ------ U, D, V U: array-like, shape (N, rank) Orthonormal matrix of left singular vectors. D: list, shape (rank, ) Singular values in non-increasing order (e.g. D[0] is the largest). V: array-like, shape (D, rank) Orthonormal matrix of right singular vectors<|endoftext|>
e674234994e1c3f1f250e20a473df852c1a42c9305b3cee6f39509024eb0751d
def fix_scipy_svds(scipy_svds): '\n scipy.sparse.linalg.svds orders the singular values backwards,\n this function fixes this insanity and returns the singular values\n in decreasing order\n\n Parameters\n ----------\n scipy_svds: the out put from scipy.sparse.linalg.svds\n\n Output\n ------\n U, D, V\n ordered in decreasing singular values\n ' (U, D, V) = scipy_svds sv_reordering = np.argsort((- D)) U = U[(:, sv_reordering)] D = D[sv_reordering] V = V.T[(:, sv_reordering)] return (U, D, V)
scipy.sparse.linalg.svds orders the singular values backwards, this function fixes this insanity and returns the singular values in decreasing order Parameters ---------- scipy_svds: the out put from scipy.sparse.linalg.svds Output ------ U, D, V ordered in decreasing singular values
ya_pca/linalg_utils.py
fix_scipy_svds
idc9/ya_pca
6
python
def fix_scipy_svds(scipy_svds): '\n scipy.sparse.linalg.svds orders the singular values backwards,\n this function fixes this insanity and returns the singular values\n in decreasing order\n\n Parameters\n ----------\n scipy_svds: the out put from scipy.sparse.linalg.svds\n\n Output\n ------\n U, D, V\n ordered in decreasing singular values\n ' (U, D, V) = scipy_svds sv_reordering = np.argsort((- D)) U = U[(:, sv_reordering)] D = D[sv_reordering] V = V.T[(:, sv_reordering)] return (U, D, V)
def fix_scipy_svds(scipy_svds): '\n scipy.sparse.linalg.svds orders the singular values backwards,\n this function fixes this insanity and returns the singular values\n in decreasing order\n\n Parameters\n ----------\n scipy_svds: the out put from scipy.sparse.linalg.svds\n\n Output\n ------\n U, D, V\n ordered in decreasing singular values\n ' (U, D, V) = scipy_svds sv_reordering = np.argsort((- D)) U = U[(:, sv_reordering)] D = D[sv_reordering] V = V.T[(:, sv_reordering)] return (U, D, V)<|docstring|>scipy.sparse.linalg.svds orders the singular values backwards, this function fixes this insanity and returns the singular values in decreasing order Parameters ---------- scipy_svds: the out put from scipy.sparse.linalg.svds Output ------ U, D, V ordered in decreasing singular values<|endoftext|>
1c6e3a85e48a86b95f4fd246aa0b6727b4c0fc3f5d85e51fa2a36b9ad69f444c
def eigh_wrapper(A, B=None, rank=None, eval_descending=True): '\n Symmetrics eigenvector or genealized eigenvector problem.\n\n A v = lambda v\n\n or\n\n A v = labmda B v\n\n where A (and B) are symmetric (hermetian).\n\n Parameters\n ----------\n A: array-like, shape (n x n)\n\n B: None, array-like, shape (n x n)\n\n rank: None, int\n Number of\n\n eval_descending: bool\n Whether or not to compute largest or smallest eigenvalues.\n If True, will compute largest rank eigenvalues and\n eigenvalues are returned in descending order. Otherwise,\n computes smallest eigenvalues and returns them in ascending order.\n\n Output\n ------\n evals, evecs\n\n ' if (rank is not None): n_max_evals = A.shape[0] if eval_descending: eigvals_idxs = ((n_max_evals - rank), (n_max_evals - 1)) else: eigvals_idxs = (0, (rank - 1)) else: eigvals_idxs = None (evals, evecs) = eigh(a=A, b=B, eigvals=eigvals_idxs) if eval_descending: ev_reordering = np.argsort((- evals)) evals = evals[ev_reordering] evecs = evecs[(:, ev_reordering)] evecs = svd_flip(evecs, evecs.T)[0] return (evals, evecs)
Symmetrics eigenvector or genealized eigenvector problem. A v = lambda v or A v = labmda B v where A (and B) are symmetric (hermetian). Parameters ---------- A: array-like, shape (n x n) B: None, array-like, shape (n x n) rank: None, int Number of eval_descending: bool Whether or not to compute largest or smallest eigenvalues. If True, will compute largest rank eigenvalues and eigenvalues are returned in descending order. Otherwise, computes smallest eigenvalues and returns them in ascending order. Output ------ evals, evecs
ya_pca/linalg_utils.py
eigh_wrapper
idc9/ya_pca
6
python
def eigh_wrapper(A, B=None, rank=None, eval_descending=True): '\n Symmetrics eigenvector or genealized eigenvector problem.\n\n A v = lambda v\n\n or\n\n A v = labmda B v\n\n where A (and B) are symmetric (hermetian).\n\n Parameters\n ----------\n A: array-like, shape (n x n)\n\n B: None, array-like, shape (n x n)\n\n rank: None, int\n Number of\n\n eval_descending: bool\n Whether or not to compute largest or smallest eigenvalues.\n If True, will compute largest rank eigenvalues and\n eigenvalues are returned in descending order. Otherwise,\n computes smallest eigenvalues and returns them in ascending order.\n\n Output\n ------\n evals, evecs\n\n ' if (rank is not None): n_max_evals = A.shape[0] if eval_descending: eigvals_idxs = ((n_max_evals - rank), (n_max_evals - 1)) else: eigvals_idxs = (0, (rank - 1)) else: eigvals_idxs = None (evals, evecs) = eigh(a=A, b=B, eigvals=eigvals_idxs) if eval_descending: ev_reordering = np.argsort((- evals)) evals = evals[ev_reordering] evecs = evecs[(:, ev_reordering)] evecs = svd_flip(evecs, evecs.T)[0] return (evals, evecs)
def eigh_wrapper(A, B=None, rank=None, eval_descending=True): '\n Symmetrics eigenvector or genealized eigenvector problem.\n\n A v = lambda v\n\n or\n\n A v = labmda B v\n\n where A (and B) are symmetric (hermetian).\n\n Parameters\n ----------\n A: array-like, shape (n x n)\n\n B: None, array-like, shape (n x n)\n\n rank: None, int\n Number of\n\n eval_descending: bool\n Whether or not to compute largest or smallest eigenvalues.\n If True, will compute largest rank eigenvalues and\n eigenvalues are returned in descending order. Otherwise,\n computes smallest eigenvalues and returns them in ascending order.\n\n Output\n ------\n evals, evecs\n\n ' if (rank is not None): n_max_evals = A.shape[0] if eval_descending: eigvals_idxs = ((n_max_evals - rank), (n_max_evals - 1)) else: eigvals_idxs = (0, (rank - 1)) else: eigvals_idxs = None (evals, evecs) = eigh(a=A, b=B, eigvals=eigvals_idxs) if eval_descending: ev_reordering = np.argsort((- evals)) evals = evals[ev_reordering] evecs = evecs[(:, ev_reordering)] evecs = svd_flip(evecs, evecs.T)[0] return (evals, evecs)<|docstring|>Symmetrics eigenvector or genealized eigenvector problem. A v = lambda v or A v = labmda B v where A (and B) are symmetric (hermetian). Parameters ---------- A: array-like, shape (n x n) B: None, array-like, shape (n x n) rank: None, int Number of eval_descending: bool Whether or not to compute largest or smallest eigenvalues. If True, will compute largest rank eigenvalues and eigenvalues are returned in descending order. Otherwise, computes smallest eigenvalues and returns them in ascending order. Output ------ evals, evecs<|endoftext|>
c708c65502bae6894a98be662430856e91dbcf531feaa74eb41220d4eed15ca5
def rand_orthog(n, K, random_state=None): '\n Samples a random orthonormal matrix. See Section A.1.1 of https://arxiv.org/pdf/0909.3052.pdf\n\n Output\n ------\n A: array-like, (n, K)\n A random, column orthonormal matrix.\n ' rng = check_random_state(random_state) Z = rng.normal(size=(n, K)) (Q, R) = np.linalg.qr(Z) s = np.ones(K) neg_mask = (rng.uniform(size=K) > 0.5) s[neg_mask] = (- 1) return (Q * s)
Samples a random orthonormal matrix. See Section A.1.1 of https://arxiv.org/pdf/0909.3052.pdf Output ------ A: array-like, (n, K) A random, column orthonormal matrix.
ya_pca/linalg_utils.py
rand_orthog
idc9/ya_pca
6
python
def rand_orthog(n, K, random_state=None): '\n Samples a random orthonormal matrix. See Section A.1.1 of https://arxiv.org/pdf/0909.3052.pdf\n\n Output\n ------\n A: array-like, (n, K)\n A random, column orthonormal matrix.\n ' rng = check_random_state(random_state) Z = rng.normal(size=(n, K)) (Q, R) = np.linalg.qr(Z) s = np.ones(K) neg_mask = (rng.uniform(size=K) > 0.5) s[neg_mask] = (- 1) return (Q * s)
def rand_orthog(n, K, random_state=None): '\n Samples a random orthonormal matrix. See Section A.1.1 of https://arxiv.org/pdf/0909.3052.pdf\n\n Output\n ------\n A: array-like, (n, K)\n A random, column orthonormal matrix.\n ' rng = check_random_state(random_state) Z = rng.normal(size=(n, K)) (Q, R) = np.linalg.qr(Z) s = np.ones(K) neg_mask = (rng.uniform(size=K) > 0.5) s[neg_mask] = (- 1) return (Q * s)<|docstring|>Samples a random orthonormal matrix. See Section A.1.1 of https://arxiv.org/pdf/0909.3052.pdf Output ------ A: array-like, (n, K) A random, column orthonormal matrix.<|endoftext|>
b35032c3836f9d007ec704f319d90e87d2f982e6c1426f40b054103d688d2307
def rand_orthog_qr(n, K, random_state=None): '\n Samples a random, column orthonormal matrix of size n x K\n using a QR decomposition.\n\n Output\n ------\n A: array-like, (n, K)\n A random, column orthonormal matrix.\n ' rng = check_random_state(random_state) A = rng.normal(size=(n, K)) (A, _) = np.linalg.qr(A) return A
Samples a random, column orthonormal matrix of size n x K using a QR decomposition. Output ------ A: array-like, (n, K) A random, column orthonormal matrix.
ya_pca/linalg_utils.py
rand_orthog_qr
idc9/ya_pca
6
python
def rand_orthog_qr(n, K, random_state=None): '\n Samples a random, column orthonormal matrix of size n x K\n using a QR decomposition.\n\n Output\n ------\n A: array-like, (n, K)\n A random, column orthonormal matrix.\n ' rng = check_random_state(random_state) A = rng.normal(size=(n, K)) (A, _) = np.linalg.qr(A) return A
def rand_orthog_qr(n, K, random_state=None): '\n Samples a random, column orthonormal matrix of size n x K\n using a QR decomposition.\n\n Output\n ------\n A: array-like, (n, K)\n A random, column orthonormal matrix.\n ' rng = check_random_state(random_state) A = rng.normal(size=(n, K)) (A, _) = np.linalg.qr(A) return A<|docstring|>Samples a random, column orthonormal matrix of size n x K using a QR decomposition. Output ------ A: array-like, (n, K) A random, column orthonormal matrix.<|endoftext|>
ec14aa576d5fa105a8eaeb6a728abdae65ac3671fd435f7154e75fabb8565168
def test_create_file(self): '\n Test the creation of a outlines in a XlsxWriter file. These tests are\n based on the outline programs in the examples directory.\n ' filename = self.got_filename workbook = Workbook(filename) worksheet4 = workbook.add_worksheet('Outline levels') levels = ['Level 1', 'Level 2', 'Level 3', 'Level 4', 'Level 5', 'Level 6', 'Level 7', 'Level 6', 'Level 5', 'Level 4', 'Level 3', 'Level 2', 'Level 1'] worksheet4.write_column('A1', levels) worksheet4.set_row(0, None, None, {'level': 1}) worksheet4.set_row(1, None, None, {'level': 2}) worksheet4.set_row(2, None, None, {'level': 3}) worksheet4.set_row(3, None, None, {'level': 4}) worksheet4.set_row(4, None, None, {'level': 5}) worksheet4.set_row(5, None, None, {'level': 6}) worksheet4.set_row(6, None, None, {'level': 7}) worksheet4.set_row(7, None, None, {'level': 6}) worksheet4.set_row(8, None, None, {'level': 5}) worksheet4.set_row(9, None, None, {'level': 4}) worksheet4.set_row(10, None, None, {'level': 3}) worksheet4.set_row(11, None, None, {'level': 2}) worksheet4.set_row(12, None, None, {'level': 1}) workbook.close() (got, exp) = _compare_xlsx_files(self.got_filename, self.exp_filename, self.ignore_files, self.ignore_elements) self.assertEqual(got, exp)
Test the creation of a outlines in a XlsxWriter file. These tests are based on the outline programs in the examples directory.
xlsxwriter/test/comparison/test_outline04.py
test_create_file
sontek/XlsxWriter
1
python
def test_create_file(self): '\n Test the creation of a outlines in a XlsxWriter file. These tests are\n based on the outline programs in the examples directory.\n ' filename = self.got_filename workbook = Workbook(filename) worksheet4 = workbook.add_worksheet('Outline levels') levels = ['Level 1', 'Level 2', 'Level 3', 'Level 4', 'Level 5', 'Level 6', 'Level 7', 'Level 6', 'Level 5', 'Level 4', 'Level 3', 'Level 2', 'Level 1'] worksheet4.write_column('A1', levels) worksheet4.set_row(0, None, None, {'level': 1}) worksheet4.set_row(1, None, None, {'level': 2}) worksheet4.set_row(2, None, None, {'level': 3}) worksheet4.set_row(3, None, None, {'level': 4}) worksheet4.set_row(4, None, None, {'level': 5}) worksheet4.set_row(5, None, None, {'level': 6}) worksheet4.set_row(6, None, None, {'level': 7}) worksheet4.set_row(7, None, None, {'level': 6}) worksheet4.set_row(8, None, None, {'level': 5}) worksheet4.set_row(9, None, None, {'level': 4}) worksheet4.set_row(10, None, None, {'level': 3}) worksheet4.set_row(11, None, None, {'level': 2}) worksheet4.set_row(12, None, None, {'level': 1}) workbook.close() (got, exp) = _compare_xlsx_files(self.got_filename, self.exp_filename, self.ignore_files, self.ignore_elements) self.assertEqual(got, exp)
def test_create_file(self): '\n Test the creation of a outlines in a XlsxWriter file. These tests are\n based on the outline programs in the examples directory.\n ' filename = self.got_filename workbook = Workbook(filename) worksheet4 = workbook.add_worksheet('Outline levels') levels = ['Level 1', 'Level 2', 'Level 3', 'Level 4', 'Level 5', 'Level 6', 'Level 7', 'Level 6', 'Level 5', 'Level 4', 'Level 3', 'Level 2', 'Level 1'] worksheet4.write_column('A1', levels) worksheet4.set_row(0, None, None, {'level': 1}) worksheet4.set_row(1, None, None, {'level': 2}) worksheet4.set_row(2, None, None, {'level': 3}) worksheet4.set_row(3, None, None, {'level': 4}) worksheet4.set_row(4, None, None, {'level': 5}) worksheet4.set_row(5, None, None, {'level': 6}) worksheet4.set_row(6, None, None, {'level': 7}) worksheet4.set_row(7, None, None, {'level': 6}) worksheet4.set_row(8, None, None, {'level': 5}) worksheet4.set_row(9, None, None, {'level': 4}) worksheet4.set_row(10, None, None, {'level': 3}) worksheet4.set_row(11, None, None, {'level': 2}) worksheet4.set_row(12, None, None, {'level': 1}) workbook.close() (got, exp) = _compare_xlsx_files(self.got_filename, self.exp_filename, self.ignore_files, self.ignore_elements) self.assertEqual(got, exp)<|docstring|>Test the creation of a outlines in a XlsxWriter file. These tests are based on the outline programs in the examples directory.<|endoftext|>
4fcd4df4de9cc730e776d5a0302c0ff94a37b2313892ed812afbc6baa859d048
def test_suite(): 'Allows testing of only this module with the command::\n\n python setup.py test -m <modulename>\n ' return unittest.defaultTestLoader.loadTestsFromName(__name__)
Allows testing of only this module with the command:: python setup.py test -m <modulename>
py/surveysim/test/test_util.py
test_suite
mlandriau/surveysim
0
python
def test_suite(): 'Allows testing of only this module with the command::\n\n python setup.py test -m <modulename>\n ' return unittest.defaultTestLoader.loadTestsFromName(__name__)
def test_suite(): 'Allows testing of only this module with the command::\n\n python setup.py test -m <modulename>\n ' return unittest.defaultTestLoader.loadTestsFromName(__name__)<|docstring|>Allows testing of only this module with the command:: python setup.py test -m <modulename><|endoftext|>
189e53ba0271983de5df8419201f0ed0f3269bb07047457e86cb28b096af0f78
def test_add_calibration_exposures(self): 'Test adding calibration exposures to science exposures.\n ' config = desisurvey.config.Configuration() tiles = desisurvey.tiles.get_tiles() tileID = tiles.tileID[0] exposures = surveysim.exposures.ExposureList() exposures.add(58849.0, 1.0, tileID, 1.0, 1.0, 1.0, 1.1, 0.9, 1.0) exposures.add(58850.0, 1.0, tileID, 1.0, 1.0, 1.0, 1.1, 0.9, 1.0) for mode in ('obj', 'recarray', 'table'): if (mode == 'obj'): input = exposures elif (mode == 'recarray'): input = exposures._exposures[:exposures.nexp] elif (mode == 'table'): exposures.save('exposures.fits') input = astropy.table.Table.read(config.get_path('exposures.fits'), hdu='EXPOSURES') output = add_calibration_exposures(input) self.assertEqual(len(output), 14) self.assertEqual('EXPID', output.colnames[0]) self.assertTrue(np.all((output['EXPID'] == np.arange(14, dtype=np.int32)))) self.assertTrue(np.all((np.diff(output['MJD']) >= 0))) self.assertTrue(np.all((np.diff(output['EXPID']) == 1))) bad_exposures = surveysim.exposures.ExposureList() bad_exposures.add(58851.0, 1.0, tileID, 1.0, 1.0, 1.0, 1.1, 0.9, 1.0) bad_exposures.add(58850.0, 1.0, tileID, 1.0, 1.0, 1.0, 1.1, 0.9, 1.0) with self.assertRaises(ValueError): output = add_calibration_exposures(bad_exposures)
Test adding calibration exposures to science exposures.
py/surveysim/test/test_util.py
test_add_calibration_exposures
mlandriau/surveysim
0
python
def test_add_calibration_exposures(self): '\n ' config = desisurvey.config.Configuration() tiles = desisurvey.tiles.get_tiles() tileID = tiles.tileID[0] exposures = surveysim.exposures.ExposureList() exposures.add(58849.0, 1.0, tileID, 1.0, 1.0, 1.0, 1.1, 0.9, 1.0) exposures.add(58850.0, 1.0, tileID, 1.0, 1.0, 1.0, 1.1, 0.9, 1.0) for mode in ('obj', 'recarray', 'table'): if (mode == 'obj'): input = exposures elif (mode == 'recarray'): input = exposures._exposures[:exposures.nexp] elif (mode == 'table'): exposures.save('exposures.fits') input = astropy.table.Table.read(config.get_path('exposures.fits'), hdu='EXPOSURES') output = add_calibration_exposures(input) self.assertEqual(len(output), 14) self.assertEqual('EXPID', output.colnames[0]) self.assertTrue(np.all((output['EXPID'] == np.arange(14, dtype=np.int32)))) self.assertTrue(np.all((np.diff(output['MJD']) >= 0))) self.assertTrue(np.all((np.diff(output['EXPID']) == 1))) bad_exposures = surveysim.exposures.ExposureList() bad_exposures.add(58851.0, 1.0, tileID, 1.0, 1.0, 1.0, 1.1, 0.9, 1.0) bad_exposures.add(58850.0, 1.0, tileID, 1.0, 1.0, 1.0, 1.1, 0.9, 1.0) with self.assertRaises(ValueError): output = add_calibration_exposures(bad_exposures)
def test_add_calibration_exposures(self): '\n ' config = desisurvey.config.Configuration() tiles = desisurvey.tiles.get_tiles() tileID = tiles.tileID[0] exposures = surveysim.exposures.ExposureList() exposures.add(58849.0, 1.0, tileID, 1.0, 1.0, 1.0, 1.1, 0.9, 1.0) exposures.add(58850.0, 1.0, tileID, 1.0, 1.0, 1.0, 1.1, 0.9, 1.0) for mode in ('obj', 'recarray', 'table'): if (mode == 'obj'): input = exposures elif (mode == 'recarray'): input = exposures._exposures[:exposures.nexp] elif (mode == 'table'): exposures.save('exposures.fits') input = astropy.table.Table.read(config.get_path('exposures.fits'), hdu='EXPOSURES') output = add_calibration_exposures(input) self.assertEqual(len(output), 14) self.assertEqual('EXPID', output.colnames[0]) self.assertTrue(np.all((output['EXPID'] == np.arange(14, dtype=np.int32)))) self.assertTrue(np.all((np.diff(output['MJD']) >= 0))) self.assertTrue(np.all((np.diff(output['EXPID']) == 1))) bad_exposures = surveysim.exposures.ExposureList() bad_exposures.add(58851.0, 1.0, tileID, 1.0, 1.0, 1.0, 1.1, 0.9, 1.0) bad_exposures.add(58850.0, 1.0, tileID, 1.0, 1.0, 1.0, 1.1, 0.9, 1.0) with self.assertRaises(ValueError): output = add_calibration_exposures(bad_exposures)<|docstring|>Test adding calibration exposures to science exposures.<|endoftext|>
96cb21f7c0aa216f3d0b8bc02c58c17921f5dd29825a1441cb29211980a1b72c
def binaryTreePaths(self, root): '\n :type root: TreeNode\n :rtype: List[str]\n ' if (not root): return [] res = [] curr = [] self.helper(res, curr, root) return res
:type root: TreeNode :rtype: List[str]
Easy/257.py
binaryTreePaths
Hellofafar/Leetcode
6
python
def binaryTreePaths(self, root): '\n :type root: TreeNode\n :rtype: List[str]\n ' if (not root): return [] res = [] curr = [] self.helper(res, curr, root) return res
def binaryTreePaths(self, root): '\n :type root: TreeNode\n :rtype: List[str]\n ' if (not root): return [] res = [] curr = [] self.helper(res, curr, root) return res<|docstring|>:type root: TreeNode :rtype: List[str]<|endoftext|>
15ae76a1077654cde649a9a92c72407738a0857963ed1b0281ffdca71dd62e6f
def ShowFormat(): 'Input File format example:' print('\n input vcf example(abstracted):\n----------------------\nGT:AD:DP:GQ:PL 0/0:11,0:11:33:0,33,484 ./. 0/0\n\n out vcf example: -n 9\n----------------------\nPL:GT:GQ 0/0:11,0:11:33:0,33,484 . .\n ')
Input File format example:
Exome/VCFDPFilter/VCFDPFilter.py
ShowFormat
wavefancy/BIDMC-PYTHON
0
python
def ShowFormat(): print('\n input vcf example(abstracted):\n----------------------\nGT:AD:DP:GQ:PL 0/0:11,0:11:33:0,33,484 ./. 0/0\n\n out vcf example: -n 9\n----------------------\nPL:GT:GQ 0/0:11,0:11:33:0,33,484 . .\n ')
def ShowFormat(): print('\n input vcf example(abstracted):\n----------------------\nGT:AD:DP:GQ:PL 0/0:11,0:11:33:0,33,484 ./. 0/0\n\n out vcf example: -n 9\n----------------------\nPL:GT:GQ 0/0:11,0:11:33:0,33,484 . .\n ')<|docstring|>Input File format example:<|endoftext|>
e4ef048fbea328bc8778c28277087565dca99bbfb4b78e9b5438b343aa77972e
def reformat(geno): 'mask geno type according DP value.' if (geno[0] == '.'): return '.' else: ss = geno.split(':') try: DPvalue = int(ss[DPIndex]) if (DPvalue < minDP): return '.' else: return geno except ValueError: return '.'
mask geno type according DP value.
Exome/VCFDPFilter/VCFDPFilter.py
reformat
wavefancy/BIDMC-PYTHON
0
python
def reformat(geno): if (geno[0] == '.'): return '.' else: ss = geno.split(':') try: DPvalue = int(ss[DPIndex]) if (DPvalue < minDP): return '.' else: return geno except ValueError: return '.'
def reformat(geno): if (geno[0] == '.'): return '.' else: ss = geno.split(':') try: DPvalue = int(ss[DPIndex]) if (DPvalue < minDP): return '.' else: return geno except ValueError: return '.'<|docstring|>mask geno type according DP value.<|endoftext|>
ea4b893f638d773b1161aaf1bdeb4743a7295f5ab53092ce05f86d1267c089b7
def parse_json(json_file): "JSON poem parser for 'Metrique en ligne' corpus.\n We read the data and find elements like title, author, year, etc. Then\n we iterate over the poem text and we look for each stanza and line data.\n\n :param json_file: Path for the json file\n :return: Dict with the data obtained from the poem\n :rtype: dict\n " corpus = json.loads(json_file.read_text()) corpus_name = json_file.parts[(- 3)] for work in corpus: poem = {} title = work['title'] author = work['author'] year = work['date'] structure = work['structure'] manually_checked = False stanza_list = [] line_number = 0 for (stanza_number, stanza) in enumerate(work['text']): line_list = [] for line in stanza: line_text = line['verse'] line_length = line['metre'] rhyme = line['rhyme'] line_list.append({'line_number': (line_number + 1), 'line_text': line_text, 'metrical_pattern': None, 'line_length': line_length, 'rhyme': rhyme}) line_number += 1 stanza_text = '\n'.join([line['line_text'] for line in line_list]) stanza_list.append({'stanza_number': (stanza_number + 1), 'stanza_type': None, 'lines': line_list, 'stanza_text': stanza_text}) poem.update({'poem_title': title, 'author': author, 'structure': structure, 'year': year, 'manually_checked': manually_checked, 'stanzas': stanza_list, 'corpus': corpus_name}) (yield poem)
JSON poem parser for 'Metrique en ligne' corpus. We read the data and find elements like title, author, year, etc. Then we iterate over the poem text and we look for each stanza and line data. :param json_file: Path for the json file :return: Dict with the data obtained from the poem :rtype: dict
src/averell/readers/metriqueenligne.py
parse_json
linhd-postdata/dalton
2
python
def parse_json(json_file): "JSON poem parser for 'Metrique en ligne' corpus.\n We read the data and find elements like title, author, year, etc. Then\n we iterate over the poem text and we look for each stanza and line data.\n\n :param json_file: Path for the json file\n :return: Dict with the data obtained from the poem\n :rtype: dict\n " corpus = json.loads(json_file.read_text()) corpus_name = json_file.parts[(- 3)] for work in corpus: poem = {} title = work['title'] author = work['author'] year = work['date'] structure = work['structure'] manually_checked = False stanza_list = [] line_number = 0 for (stanza_number, stanza) in enumerate(work['text']): line_list = [] for line in stanza: line_text = line['verse'] line_length = line['metre'] rhyme = line['rhyme'] line_list.append({'line_number': (line_number + 1), 'line_text': line_text, 'metrical_pattern': None, 'line_length': line_length, 'rhyme': rhyme}) line_number += 1 stanza_text = '\n'.join([line['line_text'] for line in line_list]) stanza_list.append({'stanza_number': (stanza_number + 1), 'stanza_type': None, 'lines': line_list, 'stanza_text': stanza_text}) poem.update({'poem_title': title, 'author': author, 'structure': structure, 'year': year, 'manually_checked': manually_checked, 'stanzas': stanza_list, 'corpus': corpus_name}) (yield poem)
def parse_json(json_file): "JSON poem parser for 'Metrique en ligne' corpus.\n We read the data and find elements like title, author, year, etc. Then\n we iterate over the poem text and we look for each stanza and line data.\n\n :param json_file: Path for the json file\n :return: Dict with the data obtained from the poem\n :rtype: dict\n " corpus = json.loads(json_file.read_text()) corpus_name = json_file.parts[(- 3)] for work in corpus: poem = {} title = work['title'] author = work['author'] year = work['date'] structure = work['structure'] manually_checked = False stanza_list = [] line_number = 0 for (stanza_number, stanza) in enumerate(work['text']): line_list = [] for line in stanza: line_text = line['verse'] line_length = line['metre'] rhyme = line['rhyme'] line_list.append({'line_number': (line_number + 1), 'line_text': line_text, 'metrical_pattern': None, 'line_length': line_length, 'rhyme': rhyme}) line_number += 1 stanza_text = '\n'.join([line['line_text'] for line in line_list]) stanza_list.append({'stanza_number': (stanza_number + 1), 'stanza_type': None, 'lines': line_list, 'stanza_text': stanza_text}) poem.update({'poem_title': title, 'author': author, 'structure': structure, 'year': year, 'manually_checked': manually_checked, 'stanzas': stanza_list, 'corpus': corpus_name}) (yield poem)<|docstring|>JSON poem parser for 'Metrique en ligne' corpus. We read the data and find elements like title, author, year, etc. Then we iterate over the poem text and we look for each stanza and line data. :param json_file: Path for the json file :return: Dict with the data obtained from the poem :rtype: dict<|endoftext|>
8aff398929d1b51e41369a72dd222e2569f47d62e5a711c72eac4a8450699d7b
def get_features(path): ' Function to find each poem in corpus file and parse it\n\n :param path: Corpus Path\n :return: List of poem dicts\n ' corpus_file = ((path / 'metrique-en-ligne-master') / 'metrique_en_ligne.json') result = list(parse_json(corpus_file)) return result
Function to find each poem in corpus file and parse it :param path: Corpus Path :return: List of poem dicts
src/averell/readers/metriqueenligne.py
get_features
linhd-postdata/dalton
2
python
def get_features(path): ' Function to find each poem in corpus file and parse it\n\n :param path: Corpus Path\n :return: List of poem dicts\n ' corpus_file = ((path / 'metrique-en-ligne-master') / 'metrique_en_ligne.json') result = list(parse_json(corpus_file)) return result
def get_features(path): ' Function to find each poem in corpus file and parse it\n\n :param path: Corpus Path\n :return: List of poem dicts\n ' corpus_file = ((path / 'metrique-en-ligne-master') / 'metrique_en_ligne.json') result = list(parse_json(corpus_file)) return result<|docstring|>Function to find each poem in corpus file and parse it :param path: Corpus Path :return: List of poem dicts<|endoftext|>
1df445ebdac00769f66a2ed72948370963bae2ffdcfef2718423c2e067a820e6
def setUp(self): 'set up the test\n ' self.test_path = os.path.abspath(os.path.join(os.sep, 'mnt', 'S', 'Some', 'Path', 'to', 'a', 'file', 'with', 'numbers', 'file.0010.exr'))
set up the test
tests/test_pyseq.py
setUp
dougrizeakos/pyseq
87
python
def setUp(self): '\n ' self.test_path = os.path.abspath(os.path.join(os.sep, 'mnt', 'S', 'Some', 'Path', 'to', 'a', 'file', 'with', 'numbers', 'file.0010.exr'))
def setUp(self): '\n ' self.test_path = os.path.abspath(os.path.join(os.sep, 'mnt', 'S', 'Some', 'Path', 'to', 'a', 'file', 'with', 'numbers', 'file.0010.exr'))<|docstring|>set up the test<|endoftext|>
03018c134f8f262059454ba5a3d17f8dc4b8084601547d2a3f6ec3a960fa50a9
def test_initializing_with_a_string(self): 'testing if initializing an Item with a string showing the path of a\n file is working properly\n ' i = Item(self.test_path) self.assertTrue(isinstance(i, Item))
testing if initializing an Item with a string showing the path of a file is working properly
tests/test_pyseq.py
test_initializing_with_a_string
dougrizeakos/pyseq
87
python
def test_initializing_with_a_string(self): 'testing if initializing an Item with a string showing the path of a\n file is working properly\n ' i = Item(self.test_path) self.assertTrue(isinstance(i, Item))
def test_initializing_with_a_string(self): 'testing if initializing an Item with a string showing the path of a\n file is working properly\n ' i = Item(self.test_path) self.assertTrue(isinstance(i, Item))<|docstring|>testing if initializing an Item with a string showing the path of a file is working properly<|endoftext|>
4defd740c5f546f69b0db467325edfa3236276f25e2b461bc19fd15def20a9aa
def test_path_attribute_is_working_properly(self): 'testing if the path attribute is working properly\n ' i = Item(self.test_path) self.assertEqual(self.test_path, i.path)
testing if the path attribute is working properly
tests/test_pyseq.py
test_path_attribute_is_working_properly
dougrizeakos/pyseq
87
python
def test_path_attribute_is_working_properly(self): '\n ' i = Item(self.test_path) self.assertEqual(self.test_path, i.path)
def test_path_attribute_is_working_properly(self): '\n ' i = Item(self.test_path) self.assertEqual(self.test_path, i.path)<|docstring|>testing if the path attribute is working properly<|endoftext|>
79463f4e995688efd4a0be4d9408b6e89e78f122380f6ee9b0983820e6e7f5af
def test_path_attribute_is_read_only(self): 'testing if the path attribute is read only\n ' i = Item(self.test_path) with self.assertRaises(AttributeError) as cm: setattr(i, 'path', 'some value') self.assertEqual(str(cm.exception), "can't set attribute")
testing if the path attribute is read only
tests/test_pyseq.py
test_path_attribute_is_read_only
dougrizeakos/pyseq
87
python
def test_path_attribute_is_read_only(self): '\n ' i = Item(self.test_path) with self.assertRaises(AttributeError) as cm: setattr(i, 'path', 'some value') self.assertEqual(str(cm.exception), "can't set attribute")
def test_path_attribute_is_read_only(self): '\n ' i = Item(self.test_path) with self.assertRaises(AttributeError) as cm: setattr(i, 'path', 'some value') self.assertEqual(str(cm.exception), "can't set attribute")<|docstring|>testing if the path attribute is read only<|endoftext|>
a965eb6d4af00735f0b8b5a0ef1376618a1c53da3c7a0234d879422ae1663489
def test_name_attribute_is_working_properly(self): 'testing if the name attribute is working properly\n ' i = Item(self.test_path) self.assertEqual(i.name, 'file.0010.exr')
testing if the name attribute is working properly
tests/test_pyseq.py
test_name_attribute_is_working_properly
dougrizeakos/pyseq
87
python
def test_name_attribute_is_working_properly(self): '\n ' i = Item(self.test_path) self.assertEqual(i.name, 'file.0010.exr')
def test_name_attribute_is_working_properly(self): '\n ' i = Item(self.test_path) self.assertEqual(i.name, 'file.0010.exr')<|docstring|>testing if the name attribute is working properly<|endoftext|>
a974c1dff1d866ab2b984e5770b87ad50ab436b3d195ddfb8307c5a5eaa82f16
def test_name_attribute_is_read_only(self): 'testing if the name attribute is read only\n ' i = Item(self.test_path) with self.assertRaises(AttributeError) as cm: setattr(i, 'name', 'some value') self.assertEqual(str(cm.exception), "can't set attribute")
testing if the name attribute is read only
tests/test_pyseq.py
test_name_attribute_is_read_only
dougrizeakos/pyseq
87
python
def test_name_attribute_is_read_only(self): '\n ' i = Item(self.test_path) with self.assertRaises(AttributeError) as cm: setattr(i, 'name', 'some value') self.assertEqual(str(cm.exception), "can't set attribute")
def test_name_attribute_is_read_only(self): '\n ' i = Item(self.test_path) with self.assertRaises(AttributeError) as cm: setattr(i, 'name', 'some value') self.assertEqual(str(cm.exception), "can't set attribute")<|docstring|>testing if the name attribute is read only<|endoftext|>
6addccde7bd768c4dffa6618a58a8916ef91d3e736422326fce6d20879ff94d2
def test_dirname_attribute_is_working_properly(self): 'testing if the dirname attribute is working properly\n ' i = Item(self.test_path) self.assertEqual(i.dirname, os.path.dirname(self.test_path))
testing if the dirname attribute is working properly
tests/test_pyseq.py
test_dirname_attribute_is_working_properly
dougrizeakos/pyseq
87
python
def test_dirname_attribute_is_working_properly(self): '\n ' i = Item(self.test_path) self.assertEqual(i.dirname, os.path.dirname(self.test_path))
def test_dirname_attribute_is_working_properly(self): '\n ' i = Item(self.test_path) self.assertEqual(i.dirname, os.path.dirname(self.test_path))<|docstring|>testing if the dirname attribute is working properly<|endoftext|>
fda1e71d97b2c6b44b1a7915a57ddb23aee615dbbe6b4861a7778a6ae26a58e4
def test_dirname_attribute_is_read_only(self): 'testing if the dirname attribute is read only\n ' i = Item(self.test_path) with self.assertRaises(AttributeError) as cm: setattr(i, 'dirname', 'some value') self.assertEqual(str(cm.exception), "can't set attribute")
testing if the dirname attribute is read only
tests/test_pyseq.py
test_dirname_attribute_is_read_only
dougrizeakos/pyseq
87
python
def test_dirname_attribute_is_read_only(self): '\n ' i = Item(self.test_path) with self.assertRaises(AttributeError) as cm: setattr(i, 'dirname', 'some value') self.assertEqual(str(cm.exception), "can't set attribute")
def test_dirname_attribute_is_read_only(self): '\n ' i = Item(self.test_path) with self.assertRaises(AttributeError) as cm: setattr(i, 'dirname', 'some value') self.assertEqual(str(cm.exception), "can't set attribute")<|docstring|>testing if the dirname attribute is read only<|endoftext|>
b545448293e9dae7738cb611a09a84d89ac82da5f6ec8fd192c280a7fc98fab1
def test_digits_attribute_is_working_properly(self): 'testing if the digits attribute is working properly\n ' i = Item(self.test_path) self.assertEqual(i.digits, ['0010'])
testing if the digits attribute is working properly
tests/test_pyseq.py
test_digits_attribute_is_working_properly
dougrizeakos/pyseq
87
python
def test_digits_attribute_is_working_properly(self): '\n ' i = Item(self.test_path) self.assertEqual(i.digits, ['0010'])
def test_digits_attribute_is_working_properly(self): '\n ' i = Item(self.test_path) self.assertEqual(i.digits, ['0010'])<|docstring|>testing if the digits attribute is working properly<|endoftext|>
970274445471742d9e66fff9c245f9ce4ddefb046ab9afde63b77397a76d21a3
def test_digits_attribute_is_read_only(self): 'testing if the digits attribute is read only\n ' i = Item(self.test_path) with self.assertRaises(AttributeError) as cm: setattr(i, 'digits', 'some value') self.assertEqual(str(cm.exception), "can't set attribute")
testing if the digits attribute is read only
tests/test_pyseq.py
test_digits_attribute_is_read_only
dougrizeakos/pyseq
87
python
def test_digits_attribute_is_read_only(self): '\n ' i = Item(self.test_path) with self.assertRaises(AttributeError) as cm: setattr(i, 'digits', 'some value') self.assertEqual(str(cm.exception), "can't set attribute")
def test_digits_attribute_is_read_only(self): '\n ' i = Item(self.test_path) with self.assertRaises(AttributeError) as cm: setattr(i, 'digits', 'some value') self.assertEqual(str(cm.exception), "can't set attribute")<|docstring|>testing if the digits attribute is read only<|endoftext|>
d6bf23c432f5d9f0504700718be792544ed20f98e3683339fb11d70ccaaf108e
def test_parts_attribute_is_working_properly(self): 'testing if the parts attribute is working properly\n ' i = Item(self.test_path) self.assertEqual(i.parts, ['file.', '.exr'])
testing if the parts attribute is working properly
tests/test_pyseq.py
test_parts_attribute_is_working_properly
dougrizeakos/pyseq
87
python
def test_parts_attribute_is_working_properly(self): '\n ' i = Item(self.test_path) self.assertEqual(i.parts, ['file.', '.exr'])
def test_parts_attribute_is_working_properly(self): '\n ' i = Item(self.test_path) self.assertEqual(i.parts, ['file.', '.exr'])<|docstring|>testing if the parts attribute is working properly<|endoftext|>
b3f45c6357967726799bb28e8d2ccd4090cfaab700082e757f9cb0ecab669566
def test_parts_attribute_is_read_only(self): 'testing if the parts attribute is read only\n ' i = Item(self.test_path) with self.assertRaises(AttributeError) as cm: setattr(i, 'parts', 'some value') self.assertEqual(str(cm.exception), "can't set attribute")
testing if the parts attribute is read only
tests/test_pyseq.py
test_parts_attribute_is_read_only
dougrizeakos/pyseq
87
python
def test_parts_attribute_is_read_only(self): '\n ' i = Item(self.test_path) with self.assertRaises(AttributeError) as cm: setattr(i, 'parts', 'some value') self.assertEqual(str(cm.exception), "can't set attribute")
def test_parts_attribute_is_read_only(self): '\n ' i = Item(self.test_path) with self.assertRaises(AttributeError) as cm: setattr(i, 'parts', 'some value') self.assertEqual(str(cm.exception), "can't set attribute")<|docstring|>testing if the parts attribute is read only<|endoftext|>
75ba83aba92e82419eb2c829b1a076a83af8c9af3c16d98c65bb19035a404eed
def test_is_sibling_method_is_working_properly(self): 'testing if the is_sibling() is working properly\n ' item1 = Item('/mnt/S/Some/Path/to/a/file/with/numbers/file.0010.exr') item2 = Item('/mnt/S/Some/Path/to/a/file/with/numbers/file.0101.exr') self.assertTrue(item1.is_sibling(item2)) self.assertTrue(item2.is_sibling(item1))
testing if the is_sibling() is working properly
tests/test_pyseq.py
test_is_sibling_method_is_working_properly
dougrizeakos/pyseq
87
python
def test_is_sibling_method_is_working_properly(self): '\n ' item1 = Item('/mnt/S/Some/Path/to/a/file/with/numbers/file.0010.exr') item2 = Item('/mnt/S/Some/Path/to/a/file/with/numbers/file.0101.exr') self.assertTrue(item1.is_sibling(item2)) self.assertTrue(item2.is_sibling(item1))
def test_is_sibling_method_is_working_properly(self): '\n ' item1 = Item('/mnt/S/Some/Path/to/a/file/with/numbers/file.0010.exr') item2 = Item('/mnt/S/Some/Path/to/a/file/with/numbers/file.0101.exr') self.assertTrue(item1.is_sibling(item2)) self.assertTrue(item2.is_sibling(item1))<|docstring|>testing if the is_sibling() is working properly<|endoftext|>
54dd64218a01c82f62a423e06d1ce4c4d8b4cb89a0655427114d4c0706189173
def setUp(self): 'set the test up\n ' self.files = ['file.0001.jpg', 'file.0002.jpg', 'file.0003.jpg']
set the test up
tests/test_pyseq.py
setUp
dougrizeakos/pyseq
87
python
def setUp(self): '\n ' self.files = ['file.0001.jpg', 'file.0002.jpg', 'file.0003.jpg']
def setUp(self): '\n ' self.files = ['file.0001.jpg', 'file.0002.jpg', 'file.0003.jpg']<|docstring|>set the test up<|endoftext|>
69d69fa773a33d56d665543edcc0afde15a3d899b0acce859849089711e45ce9
def test_from_list(self): 'testing if Sequence instance can be initialized with a list of file\n names\n ' seq = Sequence(self.files) self.assertEqual(str(seq), 'file.1-3.jpg')
testing if Sequence instance can be initialized with a list of file names
tests/test_pyseq.py
test_from_list
dougrizeakos/pyseq
87
python
def test_from_list(self): 'testing if Sequence instance can be initialized with a list of file\n names\n ' seq = Sequence(self.files) self.assertEqual(str(seq), 'file.1-3.jpg')
def test_from_list(self): 'testing if Sequence instance can be initialized with a list of file\n names\n ' seq = Sequence(self.files) self.assertEqual(str(seq), 'file.1-3.jpg')<|docstring|>testing if Sequence instance can be initialized with a list of file names<|endoftext|>
8d3007b5c821ff4ae50aab5be160f6c03c7a1a7dcc36b8559429c54a20b7f80a
def test_appending_a_new_file(self): 'testing if it is possible to append a new item to the list by giving\n the file name\n ' seq = Sequence(self.files) test_file = 'file.0006.jpg' seq.append(test_file) self.assertTrue(seq.contains('file.0005.jpg')) self.assertTrue(seq.contains(test_file)) self.assertFalse(seq.contains('file.0015.jpg'))
testing if it is possible to append a new item to the list by giving the file name
tests/test_pyseq.py
test_appending_a_new_file
dougrizeakos/pyseq
87
python
def test_appending_a_new_file(self): 'testing if it is possible to append a new item to the list by giving\n the file name\n ' seq = Sequence(self.files) test_file = 'file.0006.jpg' seq.append(test_file) self.assertTrue(seq.contains('file.0005.jpg')) self.assertTrue(seq.contains(test_file)) self.assertFalse(seq.contains('file.0015.jpg'))
def test_appending_a_new_file(self): 'testing if it is possible to append a new item to the list by giving\n the file name\n ' seq = Sequence(self.files) test_file = 'file.0006.jpg' seq.append(test_file) self.assertTrue(seq.contains('file.0005.jpg')) self.assertTrue(seq.contains(test_file)) self.assertFalse(seq.contains('file.0015.jpg'))<|docstring|>testing if it is possible to append a new item to the list by giving the file name<|endoftext|>
2d8ab67b8cae6cb8bb461ab6c4af2b484aba980dd09f22ad90209c4dcd1f19c7
def test_includes_is_working_properly(self): 'testing if Sequence.includes() method is working properly\n ' seq = Sequence(self.files) self.assertTrue(seq.includes('file.0009.jpg')) self.assertFalse(seq.includes('file.0009.pic'))
testing if Sequence.includes() method is working properly
tests/test_pyseq.py
test_includes_is_working_properly
dougrizeakos/pyseq
87
python
def test_includes_is_working_properly(self): '\n ' seq = Sequence(self.files) self.assertTrue(seq.includes('file.0009.jpg')) self.assertFalse(seq.includes('file.0009.pic'))
def test_includes_is_working_properly(self): '\n ' seq = Sequence(self.files) self.assertTrue(seq.includes('file.0009.jpg')) self.assertFalse(seq.includes('file.0009.pic'))<|docstring|>testing if Sequence.includes() method is working properly<|endoftext|>
a2d5a542ecf01a5193f022522e03d9bde19d304ade1197d2874465d58da79b6e
def test_contains_is_working_properly(self): 'testing if Sequence.contains() method is working properly\n ' seq = Sequence(self.files) self.assertFalse(seq.contains('file.0009.jpg')) self.assertFalse(seq.contains('file.0009.pic'))
testing if Sequence.contains() method is working properly
tests/test_pyseq.py
test_contains_is_working_properly
dougrizeakos/pyseq
87
python
def test_contains_is_working_properly(self): '\n ' seq = Sequence(self.files) self.assertFalse(seq.contains('file.0009.jpg')) self.assertFalse(seq.contains('file.0009.pic'))
def test_contains_is_working_properly(self): '\n ' seq = Sequence(self.files) self.assertFalse(seq.contains('file.0009.jpg')) self.assertFalse(seq.contains('file.0009.pic'))<|docstring|>testing if Sequence.contains() method is working properly<|endoftext|>
ca5ce809e7b326003f20309143fe785e43339c12dd56ca2e59a0c969c24e2da8
def test_format_is_working_properly_1(self): 'testing if format is working properly\n ' seq = Sequence(self.files) seq.append('file.0006.jpg') self.assertEqual(seq.format('%h%p%t %r (%R)'), 'file.%04d.jpg 1-6 ([1-3, 6])')
testing if format is working properly
tests/test_pyseq.py
test_format_is_working_properly_1
dougrizeakos/pyseq
87
python
def test_format_is_working_properly_1(self): '\n ' seq = Sequence(self.files) seq.append('file.0006.jpg') self.assertEqual(seq.format('%h%p%t %r (%R)'), 'file.%04d.jpg 1-6 ([1-3, 6])')
def test_format_is_working_properly_1(self): '\n ' seq = Sequence(self.files) seq.append('file.0006.jpg') self.assertEqual(seq.format('%h%p%t %r (%R)'), 'file.%04d.jpg 1-6 ([1-3, 6])')<|docstring|>testing if format is working properly<|endoftext|>
b5e9bfd1b1e6a0f19e4de33910b62081e4f5644edd009c40fcb9ac4a1b109b36
def test_format_is_working_properly_2(self): 'testing if format is working properly\n ' seq = Sequence(self.files) seq.append('file.0006.jpg') self.assertEqual('file.0001-0006.jpg', seq.format('%h%04s-%04e%t')) self.assertEqual('file. 1- 6.jpg', seq.format('%h%4s-%4e%t'))
testing if format is working properly
tests/test_pyseq.py
test_format_is_working_properly_2
dougrizeakos/pyseq
87
python
def test_format_is_working_properly_2(self): '\n ' seq = Sequence(self.files) seq.append('file.0006.jpg') self.assertEqual('file.0001-0006.jpg', seq.format('%h%04s-%04e%t')) self.assertEqual('file. 1- 6.jpg', seq.format('%h%4s-%4e%t'))
def test_format_is_working_properly_2(self): '\n ' seq = Sequence(self.files) seq.append('file.0006.jpg') self.assertEqual('file.0001-0006.jpg', seq.format('%h%04s-%04e%t')) self.assertEqual('file. 1- 6.jpg', seq.format('%h%4s-%4e%t'))<|docstring|>testing if format is working properly<|endoftext|>
2822a2ab20f2d8c58161cdfd405f16f7172bb427d235e66fb61941872b10e421
def test_format_is_working_properly_3(self): 'testing if format is working properly\n ' seq = Sequence(self.files) seq.append('file.0006.jpg') seq.append('file.0010.jpg') self.assertEqual(seq.format('%h%p%t %r (missing %M)'), 'file.%04d.jpg 1-10 (missing [4-5, 7-9])')
testing if format is working properly
tests/test_pyseq.py
test_format_is_working_properly_3
dougrizeakos/pyseq
87
python
def test_format_is_working_properly_3(self): '\n ' seq = Sequence(self.files) seq.append('file.0006.jpg') seq.append('file.0010.jpg') self.assertEqual(seq.format('%h%p%t %r (missing %M)'), 'file.%04d.jpg 1-10 (missing [4-5, 7-9])')
def test_format_is_working_properly_3(self): '\n ' seq = Sequence(self.files) seq.append('file.0006.jpg') seq.append('file.0010.jpg') self.assertEqual(seq.format('%h%p%t %r (missing %M)'), 'file.%04d.jpg 1-10 (missing [4-5, 7-9])')<|docstring|>testing if format is working properly<|endoftext|>
2ee61b301b11dcd57fa877246ea15a3409d271bdc1945d931f517bf4f2ba60e0
def test__get_missing(self): ' test that _get_missing works\n ' seq = Sequence(['file.00010.jpg']) self.assertEqual(seq._get_missing(), []) seq = Sequence(self.files) seq.append('file.0006.jpg') self.assertEqual(seq._get_missing(), [4, 5]) seq = Sequence([('file.%04d.jpg' % i) for i in range(20)]) seq.pop(10) seq.pop(10) seq.pop(10) seq.pop(14) seq.pop(14) missing = [10, 11, 12, 17, 18] self.assertEqual(seq._get_missing(), missing) missing = [] seq = Sequence(['file.0001.jpg']) for i in range(2, 50): if (random.randint(0, 1) == 1): seq.append(('file.%04d.jpg' % i)) else: missing.append(i) while (missing[(- 1)] > int(re.search('file\\.(\\d{4})\\.jpg', seq[(- 1)]).group(1))): missing.pop((- 1)) self.assertEqual(seq._get_missing(), missing)
test that _get_missing works
tests/test_pyseq.py
test__get_missing
dougrizeakos/pyseq
87
python
def test__get_missing(self): ' \n ' seq = Sequence(['file.00010.jpg']) self.assertEqual(seq._get_missing(), []) seq = Sequence(self.files) seq.append('file.0006.jpg') self.assertEqual(seq._get_missing(), [4, 5]) seq = Sequence([('file.%04d.jpg' % i) for i in range(20)]) seq.pop(10) seq.pop(10) seq.pop(10) seq.pop(14) seq.pop(14) missing = [10, 11, 12, 17, 18] self.assertEqual(seq._get_missing(), missing) missing = [] seq = Sequence(['file.0001.jpg']) for i in range(2, 50): if (random.randint(0, 1) == 1): seq.append(('file.%04d.jpg' % i)) else: missing.append(i) while (missing[(- 1)] > int(re.search('file\\.(\\d{4})\\.jpg', seq[(- 1)]).group(1))): missing.pop((- 1)) self.assertEqual(seq._get_missing(), missing)
def test__get_missing(self): ' \n ' seq = Sequence(['file.00010.jpg']) self.assertEqual(seq._get_missing(), []) seq = Sequence(self.files) seq.append('file.0006.jpg') self.assertEqual(seq._get_missing(), [4, 5]) seq = Sequence([('file.%04d.jpg' % i) for i in range(20)]) seq.pop(10) seq.pop(10) seq.pop(10) seq.pop(14) seq.pop(14) missing = [10, 11, 12, 17, 18] self.assertEqual(seq._get_missing(), missing) missing = [] seq = Sequence(['file.0001.jpg']) for i in range(2, 50): if (random.randint(0, 1) == 1): seq.append(('file.%04d.jpg' % i)) else: missing.append(i) while (missing[(- 1)] > int(re.search('file\\.(\\d{4})\\.jpg', seq[(- 1)]).group(1))): missing.pop((- 1)) self.assertEqual(seq._get_missing(), missing)<|docstring|>test that _get_missing works<|endoftext|>
4876bc9daf186d456f1e69e5b11dd6d5d7b1733f59d6dc08eae83e1e2f69d7dc
def test_diff_is_working_properly_1(self): 'testing if diff is working properly\n ' self.assertEqual(diff('file01_0040.rgb', 'file01_0041.rgb'), [{'frames': ('0040', '0041'), 'start': 7, 'end': 11}])
testing if diff is working properly
tests/test_pyseq.py
test_diff_is_working_properly_1
dougrizeakos/pyseq
87
python
def test_diff_is_working_properly_1(self): '\n ' self.assertEqual(diff('file01_0040.rgb', 'file01_0041.rgb'), [{'frames': ('0040', '0041'), 'start': 7, 'end': 11}])
def test_diff_is_working_properly_1(self): '\n ' self.assertEqual(diff('file01_0040.rgb', 'file01_0041.rgb'), [{'frames': ('0040', '0041'), 'start': 7, 'end': 11}])<|docstring|>testing if diff is working properly<|endoftext|>
4f01be2d8e27b1340ba11829bcb7a7c19ee7f7e11d652c9d210015c018af050d
def test_diff_is_working_properly_2(self): 'testing if diff is working properly\n ' self.assertEqual(diff('file3.03.rgb', 'file4.03.rgb'), [{'frames': ('3', '4'), 'start': 4, 'end': 5}])
testing if diff is working properly
tests/test_pyseq.py
test_diff_is_working_properly_2
dougrizeakos/pyseq
87
python
def test_diff_is_working_properly_2(self): '\n ' self.assertEqual(diff('file3.03.rgb', 'file4.03.rgb'), [{'frames': ('3', '4'), 'start': 4, 'end': 5}])
def test_diff_is_working_properly_2(self): '\n ' self.assertEqual(diff('file3.03.rgb', 'file4.03.rgb'), [{'frames': ('3', '4'), 'start': 4, 'end': 5}])<|docstring|>testing if diff is working properly<|endoftext|>
2cbfcedd1d412d2fb0247c5450a731bfb516629ddf81ecf57d6cc5b2f0e4649f
def test_uncompress_is_working_properly_1(self): 'testing if uncompress is working properly\n ' seq = uncompress('./tests/files/012_vb_110_v001.%04d.png 1-10', fmt='%h%p%t %r') self.assertEqual('012_vb_110_v001.1-10.png', str(seq)) self.assertEqual(10, len(seq))
testing if uncompress is working properly
tests/test_pyseq.py
test_uncompress_is_working_properly_1
dougrizeakos/pyseq
87
python
def test_uncompress_is_working_properly_1(self): '\n ' seq = uncompress('./tests/files/012_vb_110_v001.%04d.png 1-10', fmt='%h%p%t %r') self.assertEqual('012_vb_110_v001.1-10.png', str(seq)) self.assertEqual(10, len(seq))
def test_uncompress_is_working_properly_1(self): '\n ' seq = uncompress('./tests/files/012_vb_110_v001.%04d.png 1-10', fmt='%h%p%t %r') self.assertEqual('012_vb_110_v001.1-10.png', str(seq)) self.assertEqual(10, len(seq))<|docstring|>testing if uncompress is working properly<|endoftext|>
ec4a7564b0822aa14d081e0177f40e73d6dfece80b93151da36ae7609493c553
def test_uncompress_is_working_properly_2(self): 'testing if uncompress is working properly\n ' seq2 = uncompress('./tests/files/a.%03d.tga [1-3, 10, 12-14]', fmt='%h%p%t %R') self.assertEqual('a.1-14.tga', str(seq2)) self.assertEqual(7, len(seq2))
testing if uncompress is working properly
tests/test_pyseq.py
test_uncompress_is_working_properly_2
dougrizeakos/pyseq
87
python
def test_uncompress_is_working_properly_2(self): '\n ' seq2 = uncompress('./tests/files/a.%03d.tga [1-3, 10, 12-14]', fmt='%h%p%t %R') self.assertEqual('a.1-14.tga', str(seq2)) self.assertEqual(7, len(seq2))
def test_uncompress_is_working_properly_2(self): '\n ' seq2 = uncompress('./tests/files/a.%03d.tga [1-3, 10, 12-14]', fmt='%h%p%t %R') self.assertEqual('a.1-14.tga', str(seq2)) self.assertEqual(7, len(seq2))<|docstring|>testing if uncompress is working properly<|endoftext|>
93482b61c7f1a0ca1dfdc20866934edb7438a71a9d21764b17fdbc20845cb441
def test_uncompress_is_working_properly_3(self): 'testing if uncompress is working properly\n ' seq3 = uncompress('a.%03d.tga 1-14 ([1-3, 10, 12-14])', fmt='%h%p%t %r (%R)') self.assertEqual('a.1-14.tga', str(seq3)) self.assertEqual(7, len(seq3))
testing if uncompress is working properly
tests/test_pyseq.py
test_uncompress_is_working_properly_3
dougrizeakos/pyseq
87
python
def test_uncompress_is_working_properly_3(self): '\n ' seq3 = uncompress('a.%03d.tga 1-14 ([1-3, 10, 12-14])', fmt='%h%p%t %r (%R)') self.assertEqual('a.1-14.tga', str(seq3)) self.assertEqual(7, len(seq3))
def test_uncompress_is_working_properly_3(self): '\n ' seq3 = uncompress('a.%03d.tga 1-14 ([1-3, 10, 12-14])', fmt='%h%p%t %r (%R)') self.assertEqual('a.1-14.tga', str(seq3)) self.assertEqual(7, len(seq3))<|docstring|>testing if uncompress is working properly<|endoftext|>
d782aae1fdd41e763b5778b7aaf6feb4ddcec2da3669eda77c43377bc1f6770b
def test_uncompress_is_working_properly_4(self): 'testing if uncompress is working properly\n ' seq4 = uncompress('a.%03d.tga 1-14 ([1-3, 10, 12-14])', fmt='%h%p%t %s-%e (%R)') self.assertEqual('a.1-14.tga', str(seq4))
testing if uncompress is working properly
tests/test_pyseq.py
test_uncompress_is_working_properly_4
dougrizeakos/pyseq
87
python
def test_uncompress_is_working_properly_4(self): '\n ' seq4 = uncompress('a.%03d.tga 1-14 ([1-3, 10, 12-14])', fmt='%h%p%t %s-%e (%R)') self.assertEqual('a.1-14.tga', str(seq4))
def test_uncompress_is_working_properly_4(self): '\n ' seq4 = uncompress('a.%03d.tga 1-14 ([1-3, 10, 12-14])', fmt='%h%p%t %s-%e (%R)') self.assertEqual('a.1-14.tga', str(seq4))<|docstring|>testing if uncompress is working properly<|endoftext|>
0a6a5d74cdb249f46f3d59cd2e217f71c8e4de14b01e75f56dfc0357819fdf13
def test_uncompress_is_working_properly_5(self): 'testing if uncompress is working properly\n ' seq5 = uncompress('a.%03d.tga 1-14 [1-14]', fmt='%h%p%t %r %R') self.assertEqual('a.1-14.tga', str(seq5)) self.assertEqual(14, len(seq5))
testing if uncompress is working properly
tests/test_pyseq.py
test_uncompress_is_working_properly_5
dougrizeakos/pyseq
87
python
def test_uncompress_is_working_properly_5(self): '\n ' seq5 = uncompress('a.%03d.tga 1-14 [1-14]', fmt='%h%p%t %r %R') self.assertEqual('a.1-14.tga', str(seq5)) self.assertEqual(14, len(seq5))
def test_uncompress_is_working_properly_5(self): '\n ' seq5 = uncompress('a.%03d.tga 1-14 [1-14]', fmt='%h%p%t %r %R') self.assertEqual('a.1-14.tga', str(seq5)) self.assertEqual(14, len(seq5))<|docstring|>testing if uncompress is working properly<|endoftext|>
85746eaf731062419c8d128b17c43b5f406de0c8455224a2dc18a9a97366a2ba
def test_uncompress_is_working_properly_6(self): 'testing if uncompress is working properly\n ' seq6 = uncompress('a.%03d.tga 1-14 ([1-14])', fmt='%h%p%t %r (%R)') self.assertEqual('a.1-14.tga', str(seq6)) self.assertEqual(14, len(seq6))
testing if uncompress is working properly
tests/test_pyseq.py
test_uncompress_is_working_properly_6
dougrizeakos/pyseq
87
python
def test_uncompress_is_working_properly_6(self): '\n ' seq6 = uncompress('a.%03d.tga 1-14 ([1-14])', fmt='%h%p%t %r (%R)') self.assertEqual('a.1-14.tga', str(seq6)) self.assertEqual(14, len(seq6))
def test_uncompress_is_working_properly_6(self): '\n ' seq6 = uncompress('a.%03d.tga 1-14 ([1-14])', fmt='%h%p%t %r (%R)') self.assertEqual('a.1-14.tga', str(seq6)) self.assertEqual(14, len(seq6))<|docstring|>testing if uncompress is working properly<|endoftext|>
b1327a713b83659dc35b7bbf435f3a00ef1c4e4e331f04a3a7d0ab66f356dc89
def test_uncompress_is_working_properly_7(self): 'testing if uncompress is working properly,\n the frame 100000 does not fit inside the pad length\n ' seq7 = uncompress('a.%03d.tga 1-100000 ([1-10, 100000])', fmt='%h%p%t %r (%R)') self.assertEqual('a.1-10.tga', str(seq7)) self.assertEqual(10, len(seq7))
testing if uncompress is working properly, the frame 100000 does not fit inside the pad length
tests/test_pyseq.py
test_uncompress_is_working_properly_7
dougrizeakos/pyseq
87
python
def test_uncompress_is_working_properly_7(self): 'testing if uncompress is working properly,\n the frame 100000 does not fit inside the pad length\n ' seq7 = uncompress('a.%03d.tga 1-100000 ([1-10, 100000])', fmt='%h%p%t %r (%R)') self.assertEqual('a.1-10.tga', str(seq7)) self.assertEqual(10, len(seq7))
def test_uncompress_is_working_properly_7(self): 'testing if uncompress is working properly,\n the frame 100000 does not fit inside the pad length\n ' seq7 = uncompress('a.%03d.tga 1-100000 ([1-10, 100000])', fmt='%h%p%t %r (%R)') self.assertEqual('a.1-10.tga', str(seq7)) self.assertEqual(10, len(seq7))<|docstring|>testing if uncompress is working properly, the frame 100000 does not fit inside the pad length<|endoftext|>
737e5c33f96cf04154d60aa6ff7bcc855a7483e5cf7361b3a138ea6deaa08914
def test_uncompress_is_working_properly_8(self): 'testing if uncompress is working properly\n ' seq8 = uncompress('a.%03d.tga 1-100 ([10, 20, 40, 50])', fmt='%h%p%t %r (%m)') self.assertEqual('a.1-100.tga', str(seq8)) self.assertEqual(96, len(seq8))
testing if uncompress is working properly
tests/test_pyseq.py
test_uncompress_is_working_properly_8
dougrizeakos/pyseq
87
python
def test_uncompress_is_working_properly_8(self): '\n ' seq8 = uncompress('a.%03d.tga 1-100 ([10, 20, 40, 50])', fmt='%h%p%t %r (%m)') self.assertEqual('a.1-100.tga', str(seq8)) self.assertEqual(96, len(seq8))
def test_uncompress_is_working_properly_8(self): '\n ' seq8 = uncompress('a.%03d.tga 1-100 ([10, 20, 40, 50])', fmt='%h%p%t %r (%m)') self.assertEqual('a.1-100.tga', str(seq8)) self.assertEqual(96, len(seq8))<|docstring|>testing if uncompress is working properly<|endoftext|>
bb1ce6012d3170653830082a3a41679ee53412f8129b809d7162cf5623364fc6
def test_get_sequences_is_working_properly_1(self): 'testing if get_sequences is working properly\n ' seqs = get_sequences('./files/') expected_results = ['012_vb_110_v001.1-10.png', '012_vb_110_v002.1-10.png', 'a.1-14.tga', 'alpha.txt', 'bnc01_TinkSO_tx_0_ty_0.101-105.tif', 'bnc01_TinkSO_tx_0_ty_1.101-105.tif', 'bnc01_TinkSO_tx_1_ty_0.101-105.tif', 'bnc01_TinkSO_tx_1_ty_1.101-105.tif', 'file.1-2.tif', 'file.info.03.rgb', 'file01.1-4.j2k', 'file01_40-43.rgb', 'file02_44-47.rgb', 'file1-4.03.rgb', 'fileA.1-3.jpg', 'fileA.1-3.png', 'file_02.tif', 'z1_001_v1.1-4.png', 'z1_002_v1.1-4.png', 'z1_002_v2.1-4.png'] for (seq, expected_result) in zip(seqs, expected_results): self.assertEqual(expected_result, str(seq))
testing if get_sequences is working properly
tests/test_pyseq.py
test_get_sequences_is_working_properly_1
dougrizeakos/pyseq
87
python
def test_get_sequences_is_working_properly_1(self): '\n ' seqs = get_sequences('./files/') expected_results = ['012_vb_110_v001.1-10.png', '012_vb_110_v002.1-10.png', 'a.1-14.tga', 'alpha.txt', 'bnc01_TinkSO_tx_0_ty_0.101-105.tif', 'bnc01_TinkSO_tx_0_ty_1.101-105.tif', 'bnc01_TinkSO_tx_1_ty_0.101-105.tif', 'bnc01_TinkSO_tx_1_ty_1.101-105.tif', 'file.1-2.tif', 'file.info.03.rgb', 'file01.1-4.j2k', 'file01_40-43.rgb', 'file02_44-47.rgb', 'file1-4.03.rgb', 'fileA.1-3.jpg', 'fileA.1-3.png', 'file_02.tif', 'z1_001_v1.1-4.png', 'z1_002_v1.1-4.png', 'z1_002_v2.1-4.png'] for (seq, expected_result) in zip(seqs, expected_results): self.assertEqual(expected_result, str(seq))
def test_get_sequences_is_working_properly_1(self): '\n ' seqs = get_sequences('./files/') expected_results = ['012_vb_110_v001.1-10.png', '012_vb_110_v002.1-10.png', 'a.1-14.tga', 'alpha.txt', 'bnc01_TinkSO_tx_0_ty_0.101-105.tif', 'bnc01_TinkSO_tx_0_ty_1.101-105.tif', 'bnc01_TinkSO_tx_1_ty_0.101-105.tif', 'bnc01_TinkSO_tx_1_ty_1.101-105.tif', 'file.1-2.tif', 'file.info.03.rgb', 'file01.1-4.j2k', 'file01_40-43.rgb', 'file02_44-47.rgb', 'file1-4.03.rgb', 'fileA.1-3.jpg', 'fileA.1-3.png', 'file_02.tif', 'z1_001_v1.1-4.png', 'z1_002_v1.1-4.png', 'z1_002_v2.1-4.png'] for (seq, expected_result) in zip(seqs, expected_results): self.assertEqual(expected_result, str(seq))<|docstring|>testing if get_sequences is working properly<|endoftext|>
8af1bb24a5a6f6e44dd00d535a6d3ced0f230cf2a5ca5f3033087bfe0b94ab60
def test_get_sequences_is_working_properly_2(self): 'testing if get_sequences is working properly\n ' seqs = get_sequences(['fileA.1.rgb', 'fileA.2.rgb', 'fileB.1.rgb']) expected_results = ['fileA.1-2.rgb', 'fileB.1.rgb'] for (seq, expected_result) in zip(seqs, expected_results): self.assertEqual(expected_result, str(seq))
testing if get_sequences is working properly
tests/test_pyseq.py
test_get_sequences_is_working_properly_2
dougrizeakos/pyseq
87
python
def test_get_sequences_is_working_properly_2(self): '\n ' seqs = get_sequences(['fileA.1.rgb', 'fileA.2.rgb', 'fileB.1.rgb']) expected_results = ['fileA.1-2.rgb', 'fileB.1.rgb'] for (seq, expected_result) in zip(seqs, expected_results): self.assertEqual(expected_result, str(seq))
def test_get_sequences_is_working_properly_2(self): '\n ' seqs = get_sequences(['fileA.1.rgb', 'fileA.2.rgb', 'fileB.1.rgb']) expected_results = ['fileA.1-2.rgb', 'fileB.1.rgb'] for (seq, expected_result) in zip(seqs, expected_results): self.assertEqual(expected_result, str(seq))<|docstring|>testing if get_sequences is working properly<|endoftext|>
3c4745548260d75e5b178639964faaaa6015619eb065410794ba352567fa3349
def test_get_sequences_is_working_properly_3(self): 'testing if get_sequences is working properly\n ' seqs = get_sequences('./tests/files/bnc*') expected_results = ['bnc01_TinkSO_tx_0_ty_0.%04d.tif 101-105', 'bnc01_TinkSO_tx_0_ty_1.%04d.tif 101-105', 'bnc01_TinkSO_tx_1_ty_0.%04d.tif 101-105', 'bnc01_TinkSO_tx_1_ty_1.%04d.tif 101-105'] for (seq, expected_result) in zip(seqs, expected_results): self.assertEqual(expected_result, seq.format('%h%p%t %r'))
testing if get_sequences is working properly
tests/test_pyseq.py
test_get_sequences_is_working_properly_3
dougrizeakos/pyseq
87
python
def test_get_sequences_is_working_properly_3(self): '\n ' seqs = get_sequences('./tests/files/bnc*') expected_results = ['bnc01_TinkSO_tx_0_ty_0.%04d.tif 101-105', 'bnc01_TinkSO_tx_0_ty_1.%04d.tif 101-105', 'bnc01_TinkSO_tx_1_ty_0.%04d.tif 101-105', 'bnc01_TinkSO_tx_1_ty_1.%04d.tif 101-105'] for (seq, expected_result) in zip(seqs, expected_results): self.assertEqual(expected_result, seq.format('%h%p%t %r'))
def test_get_sequences_is_working_properly_3(self): '\n ' seqs = get_sequences('./tests/files/bnc*') expected_results = ['bnc01_TinkSO_tx_0_ty_0.%04d.tif 101-105', 'bnc01_TinkSO_tx_0_ty_1.%04d.tif 101-105', 'bnc01_TinkSO_tx_1_ty_0.%04d.tif 101-105', 'bnc01_TinkSO_tx_1_ty_1.%04d.tif 101-105'] for (seq, expected_result) in zip(seqs, expected_results): self.assertEqual(expected_result, seq.format('%h%p%t %r'))<|docstring|>testing if get_sequences is working properly<|endoftext|>
41f69e4743e6eddf99d2016191664890e03c030bb89fee30789fe1afd4091b6e
def run_command(self, *args): 'a simple wrapper for subprocess.Popen\n ' process = subprocess.Popen(args, stdout=subprocess.PIPE, universal_newlines=True) (stdout, _) = process.communicate() return stdout
a simple wrapper for subprocess.Popen
tests/test_pyseq.py
run_command
dougrizeakos/pyseq
87
python
def run_command(self, *args): '\n ' process = subprocess.Popen(args, stdout=subprocess.PIPE, universal_newlines=True) (stdout, _) = process.communicate() return stdout
def run_command(self, *args): '\n ' process = subprocess.Popen(args, stdout=subprocess.PIPE, universal_newlines=True) (stdout, _) = process.communicate() return stdout<|docstring|>a simple wrapper for subprocess.Popen<|endoftext|>
a0cb7a597d903f01eb0682dd7c12e6f4b5045c3cc1fda3002d54a3154f980600
def test_lss_is_working_properly_1(self): 'testing if the lss command is working properly\n ' test_files = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'files') result = self.run_command(self.lss, test_files) self.assertEqual(' 10 012_vb_110_v001.%04d.png [1-10]\n 10 012_vb_110_v002.%04d.png [1-10]\n 7 a.%03d.tga [1-3, 10, 12-14]\n 1 alpha.txt \n 5 bnc01_TinkSO_tx_0_ty_0.%04d.tif [101-105]\n 5 bnc01_TinkSO_tx_0_ty_1.%04d.tif [101-105]\n 5 bnc01_TinkSO_tx_1_ty_0.%04d.tif [101-105]\n 5 bnc01_TinkSO_tx_1_ty_1.%04d.tif [101-105]\n 2 file.%02d.tif [1-2]\n 1 file.info.03.rgb \n 3 file01.%03d.j2k [1-2, 4]\n 4 file01_%04d.rgb [40-43]\n 4 file02_%04d.rgb [44-47]\n 4 file%d.03.rgb [1-4]\n 3 fileA.%04d.jpg [1-3]\n 3 fileA.%04d.png [1-3]\n 1 file_02.tif \n 4 z1_001_v1.%d.png [1-4]\n 4 z1_002_v1.%d.png [1-4]\n 4 z1_002_v2.%d.png [9-12]\n', result)
testing if the lss command is working properly
tests/test_pyseq.py
test_lss_is_working_properly_1
dougrizeakos/pyseq
87
python
def test_lss_is_working_properly_1(self): '\n ' test_files = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'files') result = self.run_command(self.lss, test_files) self.assertEqual(' 10 012_vb_110_v001.%04d.png [1-10]\n 10 012_vb_110_v002.%04d.png [1-10]\n 7 a.%03d.tga [1-3, 10, 12-14]\n 1 alpha.txt \n 5 bnc01_TinkSO_tx_0_ty_0.%04d.tif [101-105]\n 5 bnc01_TinkSO_tx_0_ty_1.%04d.tif [101-105]\n 5 bnc01_TinkSO_tx_1_ty_0.%04d.tif [101-105]\n 5 bnc01_TinkSO_tx_1_ty_1.%04d.tif [101-105]\n 2 file.%02d.tif [1-2]\n 1 file.info.03.rgb \n 3 file01.%03d.j2k [1-2, 4]\n 4 file01_%04d.rgb [40-43]\n 4 file02_%04d.rgb [44-47]\n 4 file%d.03.rgb [1-4]\n 3 fileA.%04d.jpg [1-3]\n 3 fileA.%04d.png [1-3]\n 1 file_02.tif \n 4 z1_001_v1.%d.png [1-4]\n 4 z1_002_v1.%d.png [1-4]\n 4 z1_002_v2.%d.png [9-12]\n', result)
def test_lss_is_working_properly_1(self): '\n ' test_files = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'files') result = self.run_command(self.lss, test_files) self.assertEqual(' 10 012_vb_110_v001.%04d.png [1-10]\n 10 012_vb_110_v002.%04d.png [1-10]\n 7 a.%03d.tga [1-3, 10, 12-14]\n 1 alpha.txt \n 5 bnc01_TinkSO_tx_0_ty_0.%04d.tif [101-105]\n 5 bnc01_TinkSO_tx_0_ty_1.%04d.tif [101-105]\n 5 bnc01_TinkSO_tx_1_ty_0.%04d.tif [101-105]\n 5 bnc01_TinkSO_tx_1_ty_1.%04d.tif [101-105]\n 2 file.%02d.tif [1-2]\n 1 file.info.03.rgb \n 3 file01.%03d.j2k [1-2, 4]\n 4 file01_%04d.rgb [40-43]\n 4 file02_%04d.rgb [44-47]\n 4 file%d.03.rgb [1-4]\n 3 fileA.%04d.jpg [1-3]\n 3 fileA.%04d.png [1-3]\n 1 file_02.tif \n 4 z1_001_v1.%d.png [1-4]\n 4 z1_002_v1.%d.png [1-4]\n 4 z1_002_v2.%d.png [9-12]\n', result)<|docstring|>testing if the lss command is working properly<|endoftext|>
4cf86665d494209f97c6ba9ae8cc592706be3eb923b956db293b44a2e3c85a73
def test_issue_60(self): 'tests issue 60. with strict padding disabled,\n padding should be %d' pyseq.strict_pad = False items = ['file.7.jpg', 'file.8.jpg', 'file.9.jpg', 'file.10.jpg', 'file.11.jpg', 'file.12.jpg', 'file.87.jpg', 'file.99.jpg', 'file.111.jpg'] seq = pyseq.get_sequences(items)[0] self.assertEqual(len(items), len(seq)) self.assertEqual(seq._get_padding(), '%d') item = ['file.7.jpg', 'file.8.jpg', 'file.9.jpg', 'file.10.jpg', 'file.11.jpg', 'file.12.jpg'] seq = pyseq.get_sequences(items)[0] self.assertEqual(len(items), len(seq)) self.assertEqual(seq._get_padding(), '%d') seq = pyseq.get_sequences(['file.1.jpg', 'file.100.jpg', 'file.101.jpg'])[0] self.assertEqual(len(seq), 3) self.assertEqual(seq._get_padding(), '%d') seq = pyseq.get_sequences(['file.10.jpg', 'file.11.jpg', 'file.12.jpg'])[0] self.assertEqual(len(seq), 3) self.assertEqual(seq._get_padding(), '%d') seq = pyseq.get_sequences(['file.100.jpg', 'file.101.jpg', 'file.102.jpg'])[0] self.assertEqual(len(seq), 3) self.assertEqual(seq._get_padding(), '%d') seq = pyseq.get_sequences(['file.9.jpg', 'file.99.jpg', 'file.999.jpg', 'file.9999.jpg'])[0] self.assertEqual(len(seq), 4) self.assertEqual(seq._get_padding(), '%d') seq = pyseq.get_sequences(['file.007.jpg', 'file.010.jpg', 'file.101.jpg'])[0] self.assertEqual(len(seq), 3) self.assertEqual(seq._get_padding(), '%03d') pyseq.strict_pad = True seq = pyseq.get_sequences(['file.007.jpg', 'file.010.jpg', 'file.101.jpg'])[0] self.assertEqual(len(seq), 3) self.assertEqual(seq._get_padding(), '%03d')
tests issue 60. with strict padding disabled, padding should be %d
tests/test_pyseq.py
test_issue_60
dougrizeakos/pyseq
87
python
def test_issue_60(self): 'tests issue 60. with strict padding disabled,\n padding should be %d' pyseq.strict_pad = False items = ['file.7.jpg', 'file.8.jpg', 'file.9.jpg', 'file.10.jpg', 'file.11.jpg', 'file.12.jpg', 'file.87.jpg', 'file.99.jpg', 'file.111.jpg'] seq = pyseq.get_sequences(items)[0] self.assertEqual(len(items), len(seq)) self.assertEqual(seq._get_padding(), '%d') item = ['file.7.jpg', 'file.8.jpg', 'file.9.jpg', 'file.10.jpg', 'file.11.jpg', 'file.12.jpg'] seq = pyseq.get_sequences(items)[0] self.assertEqual(len(items), len(seq)) self.assertEqual(seq._get_padding(), '%d') seq = pyseq.get_sequences(['file.1.jpg', 'file.100.jpg', 'file.101.jpg'])[0] self.assertEqual(len(seq), 3) self.assertEqual(seq._get_padding(), '%d') seq = pyseq.get_sequences(['file.10.jpg', 'file.11.jpg', 'file.12.jpg'])[0] self.assertEqual(len(seq), 3) self.assertEqual(seq._get_padding(), '%d') seq = pyseq.get_sequences(['file.100.jpg', 'file.101.jpg', 'file.102.jpg'])[0] self.assertEqual(len(seq), 3) self.assertEqual(seq._get_padding(), '%d') seq = pyseq.get_sequences(['file.9.jpg', 'file.99.jpg', 'file.999.jpg', 'file.9999.jpg'])[0] self.assertEqual(len(seq), 4) self.assertEqual(seq._get_padding(), '%d') seq = pyseq.get_sequences(['file.007.jpg', 'file.010.jpg', 'file.101.jpg'])[0] self.assertEqual(len(seq), 3) self.assertEqual(seq._get_padding(), '%03d') pyseq.strict_pad = True seq = pyseq.get_sequences(['file.007.jpg', 'file.010.jpg', 'file.101.jpg'])[0] self.assertEqual(len(seq), 3) self.assertEqual(seq._get_padding(), '%03d')
def test_issue_60(self): 'tests issue 60. with strict padding disabled,\n padding should be %d' pyseq.strict_pad = False items = ['file.7.jpg', 'file.8.jpg', 'file.9.jpg', 'file.10.jpg', 'file.11.jpg', 'file.12.jpg', 'file.87.jpg', 'file.99.jpg', 'file.111.jpg'] seq = pyseq.get_sequences(items)[0] self.assertEqual(len(items), len(seq)) self.assertEqual(seq._get_padding(), '%d') item = ['file.7.jpg', 'file.8.jpg', 'file.9.jpg', 'file.10.jpg', 'file.11.jpg', 'file.12.jpg'] seq = pyseq.get_sequences(items)[0] self.assertEqual(len(items), len(seq)) self.assertEqual(seq._get_padding(), '%d') seq = pyseq.get_sequences(['file.1.jpg', 'file.100.jpg', 'file.101.jpg'])[0] self.assertEqual(len(seq), 3) self.assertEqual(seq._get_padding(), '%d') seq = pyseq.get_sequences(['file.10.jpg', 'file.11.jpg', 'file.12.jpg'])[0] self.assertEqual(len(seq), 3) self.assertEqual(seq._get_padding(), '%d') seq = pyseq.get_sequences(['file.100.jpg', 'file.101.jpg', 'file.102.jpg'])[0] self.assertEqual(len(seq), 3) self.assertEqual(seq._get_padding(), '%d') seq = pyseq.get_sequences(['file.9.jpg', 'file.99.jpg', 'file.999.jpg', 'file.9999.jpg'])[0] self.assertEqual(len(seq), 4) self.assertEqual(seq._get_padding(), '%d') seq = pyseq.get_sequences(['file.007.jpg', 'file.010.jpg', 'file.101.jpg'])[0] self.assertEqual(len(seq), 3) self.assertEqual(seq._get_padding(), '%03d') pyseq.strict_pad = True seq = pyseq.get_sequences(['file.007.jpg', 'file.010.jpg', 'file.101.jpg'])[0] self.assertEqual(len(seq), 3) self.assertEqual(seq._get_padding(), '%03d')<|docstring|>tests issue 60. with strict padding disabled, padding should be %d<|endoftext|>
652254594e8269298b2b3213256b2e48a7811e9757043e64e79f5ca2f6eb716e
def reduce_var(x, axis=None, keepdims=False): 'Variance of a tensor, alongside the specified axis.\n\n # Arguments\n x: A tensor or variable.\n axis: An integer, the axis to compute the variance.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n # Returns\n A tensor with the variance of elements of `x`.\n ' m = tf.reduce_mean(x, axis=axis, keep_dims=True) devs_squared = tf.square((x - m)) return tf.reduce_mean(devs_squared, axis=axis, keep_dims=keepdims)
Variance of a tensor, alongside the specified axis. # Arguments x: A tensor or variable. axis: An integer, the axis to compute the variance. keepdims: A boolean, whether to keep the dimensions or not. If `keepdims` is `False`, the rank of the tensor is reduced by 1. If `keepdims` is `True`, the reduced dimension is retained with length 1. # Returns A tensor with the variance of elements of `x`.
Code/stackedAutoencoder.py
reduce_var
mChataign/smileCompletion
4
python
def reduce_var(x, axis=None, keepdims=False): 'Variance of a tensor, alongside the specified axis.\n\n # Arguments\n x: A tensor or variable.\n axis: An integer, the axis to compute the variance.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n # Returns\n A tensor with the variance of elements of `x`.\n ' m = tf.reduce_mean(x, axis=axis, keep_dims=True) devs_squared = tf.square((x - m)) return tf.reduce_mean(devs_squared, axis=axis, keep_dims=keepdims)
def reduce_var(x, axis=None, keepdims=False): 'Variance of a tensor, alongside the specified axis.\n\n # Arguments\n x: A tensor or variable.\n axis: An integer, the axis to compute the variance.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n # Returns\n A tensor with the variance of elements of `x`.\n ' m = tf.reduce_mean(x, axis=axis, keep_dims=True) devs_squared = tf.square((x - m)) return tf.reduce_mean(devs_squared, axis=axis, keep_dims=keepdims)<|docstring|>Variance of a tensor, alongside the specified axis. # Arguments x: A tensor or variable. axis: An integer, the axis to compute the variance. keepdims: A boolean, whether to keep the dimensions or not. If `keepdims` is `False`, the rank of the tensor is reduced by 1. If `keepdims` is `True`, the reduced dimension is retained with length 1. # Returns A tensor with the variance of elements of `x`.<|endoftext|>
5fca1c7ff2fbdba8b8b7f6912e7746156dfc04fdab51da5a960c7ba699f25422
def reduce_std(x, axis=None, keepdims=False): 'Standard deviation of a tensor, alongside the specified axis.\n\n # Arguments\n x: A tensor or variable.\n axis: An integer, the axis to compute the standard deviation.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n # Returns\n A tensor with the standard deviation of elements of `x`.\n ' return tf.sqrt(reduce_var(x, axis=axis, keepdims=keepdims))
Standard deviation of a tensor, alongside the specified axis. # Arguments x: A tensor or variable. axis: An integer, the axis to compute the standard deviation. keepdims: A boolean, whether to keep the dimensions or not. If `keepdims` is `False`, the rank of the tensor is reduced by 1. If `keepdims` is `True`, the reduced dimension is retained with length 1. # Returns A tensor with the standard deviation of elements of `x`.
Code/stackedAutoencoder.py
reduce_std
mChataign/smileCompletion
4
python
def reduce_std(x, axis=None, keepdims=False): 'Standard deviation of a tensor, alongside the specified axis.\n\n # Arguments\n x: A tensor or variable.\n axis: An integer, the axis to compute the standard deviation.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n # Returns\n A tensor with the standard deviation of elements of `x`.\n ' return tf.sqrt(reduce_var(x, axis=axis, keepdims=keepdims))
def reduce_std(x, axis=None, keepdims=False): 'Standard deviation of a tensor, alongside the specified axis.\n\n # Arguments\n x: A tensor or variable.\n axis: An integer, the axis to compute the standard deviation.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n # Returns\n A tensor with the standard deviation of elements of `x`.\n ' return tf.sqrt(reduce_var(x, axis=axis, keepdims=keepdims))<|docstring|>Standard deviation of a tensor, alongside the specified axis. # Arguments x: A tensor or variable. axis: An integer, the axis to compute the standard deviation. keepdims: A boolean, whether to keep the dimensions or not. If `keepdims` is `False`, the rank of the tensor is reduced by 1. If `keepdims` is `True`, the reduced dimension is retained with length 1. # Returns A tensor with the standard deviation of elements of `x`.<|endoftext|>
8b6371df0a2cb76c5b7ec693ff8e57f771f09747f3370c425dfe007c9a1cd9d4
def shape(self, tensor): ' get the shape of a tensor\n ' s = tensor.get_shape() return tuple([s[i].value for i in range(0, len(s))])
get the shape of a tensor
Code/stackedAutoencoder.py
shape
mChataign/smileCompletion
4
python
def shape(self, tensor): ' \n ' s = tensor.get_shape() return tuple([s[i].value for i in range(0, len(s))])
def shape(self, tensor): ' \n ' s = tensor.get_shape() return tuple([s[i].value for i in range(0, len(s))])<|docstring|>get the shape of a tensor<|endoftext|>
8a475c746c6848cb114c4b88e7ce6e680ccc8b5a2c0b0a3bb400e3895955f662
def squared_dist(A): '\n Computes the pairwise distance between points\n #http://stackoverflow.com/questions/37009647/compute-pairwise-distance-in-a-batch-without-replicating-tensor-in-tensorflow\n ' expanded_a = tf.expand_dims(A, 1) expanded_b = tf.expand_dims(A, 0) distances = tf.reduce_mean(tf.squared_difference(expanded_a, expanded_b), 2) return distances
Computes the pairwise distance between points #http://stackoverflow.com/questions/37009647/compute-pairwise-distance-in-a-batch-without-replicating-tensor-in-tensorflow
Code/stackedAutoencoder.py
squared_dist
mChataign/smileCompletion
4
python
def squared_dist(A): '\n Computes the pairwise distance between points\n #http://stackoverflow.com/questions/37009647/compute-pairwise-distance-in-a-batch-without-replicating-tensor-in-tensorflow\n ' expanded_a = tf.expand_dims(A, 1) expanded_b = tf.expand_dims(A, 0) distances = tf.reduce_mean(tf.squared_difference(expanded_a, expanded_b), 2) return distances
def squared_dist(A): '\n Computes the pairwise distance between points\n #http://stackoverflow.com/questions/37009647/compute-pairwise-distance-in-a-batch-without-replicating-tensor-in-tensorflow\n ' expanded_a = tf.expand_dims(A, 1) expanded_b = tf.expand_dims(A, 0) distances = tf.reduce_mean(tf.squared_difference(expanded_a, expanded_b), 2) return distances<|docstring|>Computes the pairwise distance between points #http://stackoverflow.com/questions/37009647/compute-pairwise-distance-in-a-batch-without-replicating-tensor-in-tensorflow<|endoftext|>
03b15f6ced73b41a1412430dd6fb420fe1ab3e1d9158126f9cf0a78523818225
def distance_loss(self, x, z_x): ' Loss based on the distance between elements in a batch\n ' z_x = tf.reshape(z_x, [shape(z_x)[0], np.prod(shape(z_x)[1:])]) sdx = squared_dist(x) sdx = (sdx / tf.reduce_mean(sdx)) sdz = squared_dist(z_x) sdz = (sdz / tf.reduce_mean(sdz)) return tf.reduce_mean(tf.square((tf.log((tf.constant(1.0) + sdx)) - tf.log((tf.constant(1.0) + sdz)))))
Loss based on the distance between elements in a batch
Code/stackedAutoencoder.py
distance_loss
mChataign/smileCompletion
4
python
def distance_loss(self, x, z_x): ' \n ' z_x = tf.reshape(z_x, [shape(z_x)[0], np.prod(shape(z_x)[1:])]) sdx = squared_dist(x) sdx = (sdx / tf.reduce_mean(sdx)) sdz = squared_dist(z_x) sdz = (sdz / tf.reduce_mean(sdz)) return tf.reduce_mean(tf.square((tf.log((tf.constant(1.0) + sdx)) - tf.log((tf.constant(1.0) + sdz)))))
def distance_loss(self, x, z_x): ' \n ' z_x = tf.reshape(z_x, [shape(z_x)[0], np.prod(shape(z_x)[1:])]) sdx = squared_dist(x) sdx = (sdx / tf.reduce_mean(sdx)) sdz = squared_dist(z_x) sdz = (sdz / tf.reduce_mean(sdz)) return tf.reduce_mean(tf.square((tf.log((tf.constant(1.0) + sdx)) - tf.log((tf.constant(1.0) + sdz)))))<|docstring|>Loss based on the distance between elements in a batch<|endoftext|>
dd100b2ae0b39b583eb222a262c2cc2739c0a71009bc9a575133d6057c0c114a
def distance_loss_true(self, x, z_x): ' Loss based on the distance between elements in a batch\n ' sdx = squared_dist(x) sdz = squared_dist(z_x) return tf.reduce_mean(tf.abs((sdz - sdx)))
Loss based on the distance between elements in a batch
Code/stackedAutoencoder.py
distance_loss_true
mChataign/smileCompletion
4
python
def distance_loss_true(self, x, z_x): ' \n ' sdx = squared_dist(x) sdz = squared_dist(z_x) return tf.reduce_mean(tf.abs((sdz - sdx)))
def distance_loss_true(self, x, z_x): ' \n ' sdx = squared_dist(x) sdz = squared_dist(z_x) return tf.reduce_mean(tf.abs((sdz - sdx)))<|docstring|>Loss based on the distance between elements in a batch<|endoftext|>
8b6371df0a2cb76c5b7ec693ff8e57f771f09747f3370c425dfe007c9a1cd9d4
def shape(self, tensor): ' get the shape of a tensor\n ' s = tensor.get_shape() return tuple([s[i].value for i in range(0, len(s))])
get the shape of a tensor
Code/stackedAutoencoder.py
shape
mChataign/smileCompletion
4
python
def shape(self, tensor): ' \n ' s = tensor.get_shape() return tuple([s[i].value for i in range(0, len(s))])
def shape(self, tensor): ' \n ' s = tensor.get_shape() return tuple([s[i].value for i in range(0, len(s))])<|docstring|>get the shape of a tensor<|endoftext|>
cc1292ad627c27da1af278d0d90018b582ecac0eb7d9e5aa6349aada101a6b6b
def distance_loss(self, x, z_x): ' Loss based on the distance between elements in a batch\n ' sdx = self.squared_dist(x) sdx = (sdx / tf.reduce_mean(sdx)) sdz = self.squared_dist(z_x) sdz = (sdz / tf.reduce_mean(sdz)) return tf.reduce_mean(tf.square((tf.log((tf.constant(1.0) + sdx)) - tf.log((tf.constant(1.0) + sdz)))))
Loss based on the distance between elements in a batch
Code/stackedAutoencoder.py
distance_loss
mChataign/smileCompletion
4
python
def distance_loss(self, x, z_x): ' \n ' sdx = self.squared_dist(x) sdx = (sdx / tf.reduce_mean(sdx)) sdz = self.squared_dist(z_x) sdz = (sdz / tf.reduce_mean(sdz)) return tf.reduce_mean(tf.square((tf.log((tf.constant(1.0) + sdx)) - tf.log((tf.constant(1.0) + sdz)))))
def distance_loss(self, x, z_x): ' \n ' sdx = self.squared_dist(x) sdx = (sdx / tf.reduce_mean(sdx)) sdz = self.squared_dist(z_x) sdz = (sdz / tf.reduce_mean(sdz)) return tf.reduce_mean(tf.square((tf.log((tf.constant(1.0) + sdx)) - tf.log((tf.constant(1.0) + sdz)))))<|docstring|>Loss based on the distance between elements in a batch<|endoftext|>
54063f5b6ada7a09e7b6bcf613bc07f38a5a6a9c4f97a5fd02709a254ec363f0
def distance_loss_true(self, x, z_x): ' Loss based on the distance between elements in a batch\n ' sdx = self.squared_dist(x) sdz = self.squared_dist(z_x) return tf.reduce_mean(tf.abs((sdz - sdx)))
Loss based on the distance between elements in a batch
Code/stackedAutoencoder.py
distance_loss_true
mChataign/smileCompletion
4
python
def distance_loss_true(self, x, z_x): ' \n ' sdx = self.squared_dist(x) sdz = self.squared_dist(z_x) return tf.reduce_mean(tf.abs((sdz - sdx)))
def distance_loss_true(self, x, z_x): ' \n ' sdx = self.squared_dist(x) sdz = self.squared_dist(z_x) return tf.reduce_mean(tf.abs((sdz - sdx)))<|docstring|>Loss based on the distance between elements in a batch<|endoftext|>
3d9005e62b8e965e94ec788fcf7bfe4aed4e11b603f157ffa3ccf43437c617ad
@staticmethod def _parse(): ' Arguments parsing method\n\n :return: Namespace object the parsed argument by ArgumentParser\n ' parser = ArgumentParser(description='Example script for Undine.') parser.add_argument('--type', dest='input_type', action='store', choices=['file', 'id'], default='file', help='Input argument type') parser.add_argument('-c', '--config', dest='config_file', action='store', metavar='PATH', help='Config file path', required=True) parser.add_argument('-r', '--result', dest='result_file', action='store', metavar='PATH', help='Result file path', required=True) parser.add_argument('inputs', metavar='INPUTS', nargs=REMAINDER, help='List of input files or IDs') return parser.parse_args()
Arguments parsing method :return: Namespace object the parsed argument by ArgumentParser
example/example.py
_parse
Sungup/Undine
1
python
@staticmethod def _parse(): ' Arguments parsing method\n\n :return: Namespace object the parsed argument by ArgumentParser\n ' parser = ArgumentParser(description='Example script for Undine.') parser.add_argument('--type', dest='input_type', action='store', choices=['file', 'id'], default='file', help='Input argument type') parser.add_argument('-c', '--config', dest='config_file', action='store', metavar='PATH', help='Config file path', required=True) parser.add_argument('-r', '--result', dest='result_file', action='store', metavar='PATH', help='Result file path', required=True) parser.add_argument('inputs', metavar='INPUTS', nargs=REMAINDER, help='List of input files or IDs') return parser.parse_args()
@staticmethod def _parse(): ' Arguments parsing method\n\n :return: Namespace object the parsed argument by ArgumentParser\n ' parser = ArgumentParser(description='Example script for Undine.') parser.add_argument('--type', dest='input_type', action='store', choices=['file', 'id'], default='file', help='Input argument type') parser.add_argument('-c', '--config', dest='config_file', action='store', metavar='PATH', help='Config file path', required=True) parser.add_argument('-r', '--result', dest='result_file', action='store', metavar='PATH', help='Result file path', required=True) parser.add_argument('inputs', metavar='INPUTS', nargs=REMAINDER, help='List of input files or IDs') return parser.parse_args()<|docstring|>Arguments parsing method :return: Namespace object the parsed argument by ArgumentParser<|endoftext|>
8be9f96f17a7ed2fbe3f5dd3416bd8fe27ecd3d2f556ee2267cc9a8787ea892c
def __init__(self): ' Constructor\n ' self._config = self._parse() if (self._config.input_type == 'file'): self._listing_input = self._listing_input_files else: self._listing_input = self._listing_input_ids self._config_file = self._config.config_file self._result_file = self._config.result_file self._inputs = self._config.inputs
Constructor
example/example.py
__init__
Sungup/Undine
1
python
def __init__(self): ' \n ' self._config = self._parse() if (self._config.input_type == 'file'): self._listing_input = self._listing_input_files else: self._listing_input = self._listing_input_ids self._config_file = self._config.config_file self._result_file = self._config.result_file self._inputs = self._config.inputs
def __init__(self): ' \n ' self._config = self._parse() if (self._config.input_type == 'file'): self._listing_input = self._listing_input_files else: self._listing_input = self._listing_input_ids self._config_file = self._config.config_file self._result_file = self._config.result_file self._inputs = self._config.inputs<|docstring|>Constructor<|endoftext|>
acf72e7b9c93919812eaea2ffb655a19a5248fff4f21859884c9963cd0ef4dfa
def run(self): ' Task run method\n\n :return: Nothing\n ' try: random_sleep = randrange(1, 10) with open(self._result_file, 'w') as f_out: f_out.write('Executed script: {0}\n'.format(__file__)) f_out.write('Working Directory: {0}\n'.format(os.getcwd())) f_out.write('Random Sleep: {0}\n'.format(random_sleep)) f_out.writelines(self._listing_args()) f_out.writelines(self._listing_conf()) f_out.writelines(self._listing_input()) sleep(random_sleep) except IOError: stderr.write(self._FILE_CREATE_FAIL.format(self._result_file)) raise
Task run method :return: Nothing
example/example.py
run
Sungup/Undine
1
python
def run(self): ' Task run method\n\n :return: Nothing\n ' try: random_sleep = randrange(1, 10) with open(self._result_file, 'w') as f_out: f_out.write('Executed script: {0}\n'.format(__file__)) f_out.write('Working Directory: {0}\n'.format(os.getcwd())) f_out.write('Random Sleep: {0}\n'.format(random_sleep)) f_out.writelines(self._listing_args()) f_out.writelines(self._listing_conf()) f_out.writelines(self._listing_input()) sleep(random_sleep) except IOError: stderr.write(self._FILE_CREATE_FAIL.format(self._result_file)) raise
def run(self): ' Task run method\n\n :return: Nothing\n ' try: random_sleep = randrange(1, 10) with open(self._result_file, 'w') as f_out: f_out.write('Executed script: {0}\n'.format(__file__)) f_out.write('Working Directory: {0}\n'.format(os.getcwd())) f_out.write('Random Sleep: {0}\n'.format(random_sleep)) f_out.writelines(self._listing_args()) f_out.writelines(self._listing_conf()) f_out.writelines(self._listing_input()) sleep(random_sleep) except IOError: stderr.write(self._FILE_CREATE_FAIL.format(self._result_file)) raise<|docstring|>Task run method :return: Nothing<|endoftext|>
e72ac101fb912d1e9f260df98b12a37dd06494a724daa011306f421625f4db1a
def exercise_01(prefix='tst_mi_ligands_test_01'): '\n Simple run to a completion with reference map. no SS annotations.\n ' pdb_file = open(('%s_start.pdb' % prefix), 'w') pdb_file.write(pdb_lines) pdb_file.close() cif_file = open(('%s_start.cif' % prefix), 'w') cif_file.write(cif_lines) cif_file.close() cmd = ' '.join(['phenix.model_idealization', ('%s_start.pdb' % prefix), ('%s_start.cif' % prefix), 'use_map_for_reference=True', 'number_of_refinement_cycles=1', 'run_minimization_first=False', 'loop_idealization.number_of_ccd_trials=1', 'n_macro=1', 'debug=True', ('>%s.log' % prefix)]) print(cmd) assert (not easy_run.call(cmd)) res_log = open(('%s.log' % prefix), 'r') log_lines = res_log.readlines() for l in [' Minimizing...\n', 'Using map as reference\n', 'All done.\n']: assert (l in log_lines), ("'%s' not in log file." % l) res_log.close()
Simple run to a completion with reference map. no SS annotations.
mmtbx/regression/model_idealization/tst_ligands.py
exercise_01
RAPD/cctbx_project
155
python
def exercise_01(prefix='tst_mi_ligands_test_01'): '\n \n ' pdb_file = open(('%s_start.pdb' % prefix), 'w') pdb_file.write(pdb_lines) pdb_file.close() cif_file = open(('%s_start.cif' % prefix), 'w') cif_file.write(cif_lines) cif_file.close() cmd = ' '.join(['phenix.model_idealization', ('%s_start.pdb' % prefix), ('%s_start.cif' % prefix), 'use_map_for_reference=True', 'number_of_refinement_cycles=1', 'run_minimization_first=False', 'loop_idealization.number_of_ccd_trials=1', 'n_macro=1', 'debug=True', ('>%s.log' % prefix)]) print(cmd) assert (not easy_run.call(cmd)) res_log = open(('%s.log' % prefix), 'r') log_lines = res_log.readlines() for l in [' Minimizing...\n', 'Using map as reference\n', 'All done.\n']: assert (l in log_lines), ("'%s' not in log file." % l) res_log.close()
def exercise_01(prefix='tst_mi_ligands_test_01'): '\n \n ' pdb_file = open(('%s_start.pdb' % prefix), 'w') pdb_file.write(pdb_lines) pdb_file.close() cif_file = open(('%s_start.cif' % prefix), 'w') cif_file.write(cif_lines) cif_file.close() cmd = ' '.join(['phenix.model_idealization', ('%s_start.pdb' % prefix), ('%s_start.cif' % prefix), 'use_map_for_reference=True', 'number_of_refinement_cycles=1', 'run_minimization_first=False', 'loop_idealization.number_of_ccd_trials=1', 'n_macro=1', 'debug=True', ('>%s.log' % prefix)]) print(cmd) assert (not easy_run.call(cmd)) res_log = open(('%s.log' % prefix), 'r') log_lines = res_log.readlines() for l in [' Minimizing...\n', 'Using map as reference\n', 'All done.\n']: assert (l in log_lines), ("'%s' not in log file." % l) res_log.close()<|docstring|>Simple run to a completion with reference map. no SS annotations.<|endoftext|>
07944d0c36f3266aceffca812dde825c18adde96f3b210ad4258921ff547728d
def build(self): 'The application layout is loaded from the main.kv file.' return Builder.load_file('main.kv')
The application layout is loaded from the main.kv file.
main.py
build
Yaaash93/Consolidate
18
python
def build(self): return Builder.load_file('main.kv')
def build(self): return Builder.load_file('main.kv')<|docstring|>The application layout is loaded from the main.kv file.<|endoftext|>
2102482886c88f1c51ad0a5b680649dc08f7c3307f6e89ca88ae55251c1d4c61
def set_color_item(self, instance_item): 'Called when the menu item is clicked.' for item in self.children: if (item.text_color == self.theme_cls.primary_color): item.text_color = self.theme_cls.text_color break instance_item.text_color = self.theme_cls.primary_color
Called when the menu item is clicked.
main.py
set_color_item
Yaaash93/Consolidate
18
python
def set_color_item(self, instance_item): for item in self.children: if (item.text_color == self.theme_cls.primary_color): item.text_color = self.theme_cls.text_color break instance_item.text_color = self.theme_cls.primary_color
def set_color_item(self, instance_item): for item in self.children: if (item.text_color == self.theme_cls.primary_color): item.text_color = self.theme_cls.text_color break instance_item.text_color = self.theme_cls.primary_color<|docstring|>Called when the menu item is clicked.<|endoftext|>
2edfef5ceff9aaaa26f47d02a2d84698a4e97471951d5f3dbe3c0126031c547f
@property def target_os(self): 'Target OS, the browser will run on.' return self._target_os
Target OS, the browser will run on.
tools/telemetry/telemetry/core/possible_browser.py
target_os
boundarydevices/android_external_chromium_org
2
python
@property def target_os(self): return self._target_os
@property def target_os(self): return self._target_os<|docstring|>Target OS, the browser will run on.<|endoftext|>
8048ec814fb9f8f7ead4d73db4ad098aaeb619f1edb24986809201a44daad0b9
def SupportsOptions(self, finder_options): 'Tests for extension support.' raise NotImplementedError()
Tests for extension support.
tools/telemetry/telemetry/core/possible_browser.py
SupportsOptions
boundarydevices/android_external_chromium_org
2
python
def SupportsOptions(self, finder_options): raise NotImplementedError()
def SupportsOptions(self, finder_options): raise NotImplementedError()<|docstring|>Tests for extension support.<|endoftext|>
7e45144130d4a1642aa18096cce88a98f0f1fe3420d52aaa92d7c618eb97a891
def enqueue(self, item): 'Add item to queue if not already full.' if (self.size() < self.maxsize): self.queue.append(item) self.determine_next_leaving_time()
Add item to queue if not already full.
elvis/waiting_queue.py
enqueue
dailab/elvis
5
python
def enqueue(self, item): if (self.size() < self.maxsize): self.queue.append(item) self.determine_next_leaving_time()
def enqueue(self, item): if (self.size() < self.maxsize): self.queue.append(item) self.determine_next_leaving_time()<|docstring|>Add item to queue if not already full.<|endoftext|>
75bda411361b666bb87afed6abfefb683982fc8746a6f96903031a4119ddfc5c
def dequeue(self): 'Get next item from queue if not empty.' if (len(self.queue) < 1): return None self.determine_next_leaving_time() return self.queue.pop(0)
Get next item from queue if not empty.
elvis/waiting_queue.py
dequeue
dailab/elvis
5
python
def dequeue(self): if (len(self.queue) < 1): return None self.determine_next_leaving_time() return self.queue.pop(0)
def dequeue(self): if (len(self.queue) < 1): return None self.determine_next_leaving_time() return self.queue.pop(0)<|docstring|>Get next item from queue if not empty.<|endoftext|>
d15c46e41f4f7139630a2aa323b4ef9d1c6a01ff13b38511ea5f57e6d7efe900
def size(self): 'Get number of item in queue.' return len(self.queue)
Get number of item in queue.
elvis/waiting_queue.py
size
dailab/elvis
5
python
def size(self): return len(self.queue)
def size(self): return len(self.queue)<|docstring|>Get number of item in queue.<|endoftext|>
141bdf197804bf993ff13d3a65f8f2d37cb13d0dfa4f216526aa1b1949081f7b
def determine_next_leaving_time(self): 'Determine the next departure time of all queued vehicles.' if (self.size() > 0): leaving_times = [] for event in self.queue: arrival_time = event.arrival_time parking_time = datetime.timedelta(hours=event.parking_time) leaving_times.append((arrival_time + parking_time)) self.next_leave = sorted(leaving_times)[0] else: self.next_leave = datetime.datetime(9999, 1, 1)
Determine the next departure time of all queued vehicles.
elvis/waiting_queue.py
determine_next_leaving_time
dailab/elvis
5
python
def determine_next_leaving_time(self): if (self.size() > 0): leaving_times = [] for event in self.queue: arrival_time = event.arrival_time parking_time = datetime.timedelta(hours=event.parking_time) leaving_times.append((arrival_time + parking_time)) self.next_leave = sorted(leaving_times)[0] else: self.next_leave = datetime.datetime(9999, 1, 1)
def determine_next_leaving_time(self): if (self.size() > 0): leaving_times = [] for event in self.queue: arrival_time = event.arrival_time parking_time = datetime.timedelta(hours=event.parking_time) leaving_times.append((arrival_time + parking_time)) self.next_leave = sorted(leaving_times)[0] else: self.next_leave = datetime.datetime(9999, 1, 1)<|docstring|>Determine the next departure time of all queued vehicles.<|endoftext|>