class ColumnsTask(Task):
    '''
    The ColumnsTask provides a structure for generating metadata. The only
    required method is :meth:`~.ColumnsTask.columns`.
    The keys may be used as human-readable column names in tables based off
    this metadata, although that is not always the case. If the id of the
    :class:`OBSColumn <tasks.meta.OBSColumn>` is left blank, the dict's key will be used to
    generate it (qualified by the module).

    Also, conventionally there will be a requires method that brings in our
    standard tags: :class:`SectionTags <tasks.tags.SectionTags>`,
    :class:`SubsectionTags <tasks.tags.SubsectionTags>`, and
    :class:`UnitTags <tasks.tags.UnitTags>`.
    This is an example of defining several tasks as prerequisites: the outputs
    of those tasks will be accessible via ``self.input()[<key>]`` in other
    methods.

    This will update-or-create columns defined in it when run.  Whether a
    column is updated or not depends on whether it exists in the database with
    the same :meth:`~.ColumnsTask.version` number.
    '''

    def columns(self):
        '''
        This method must be overriden in subclasses.  It must return a
        :py:class:`collections.OrderedDict` whose values are all instances of
        :class:`OBSColumn <tasks.meta.OBSColumn>` and whose keys are all strings.
        '''
        raise NotImplementedError('Must return iterable of OBSColumns')

    def on_failure(self, ex):
        session_rollback(self, ex)
        super(ColumnsTask, self).on_failure(ex)

    def on_success(self):
        session_commit(self)

    def run(self):
        for _, coltarget in self.output().items():
            coltarget.update_or_create()

    def version(self):
        '''
        Returns a number that will be linked to the all
        :py:attr:`tasks.meta.OBSColumn.version` objects resulting from this
        task.  If this is identical to what's already in the database, the
        :class:`OBSColumn <tasks.meta.OBSColumn>` will not be replaced.
        '''
        return 0

    def prefix(self):
        if self.task_namespace and self.task_namespace != '__not_user_specified':
            splitted_namespace = self.task_namespace.split('.')
            # Backward compatibility to avoid rerun all the tasks
            # to me removed for the next rebuild
            if splitted_namespace[0] == 'tasks':
                splitted_namespace.pop(0)
                return '.'.join(splitted_namespace)
            else:
                return self.task_namespace
        else:
            return classpath(self)

    def output(self):
        session = current_session()

        # Return columns from database if the task is already finished
        if hasattr(self, '_colids') and self.complete():
            return OrderedDict([
                (colkey, ColumnTarget(session.query(OBSColumn).get(cid), self))
                for colkey, cid in self.colids.items()
            ])

        # Otherwise, run `columns` (slow!) to generate output
        already_in_session = [obj for obj in session]
        output = OrderedDict()

        input_ = self.input()
        for col_key, col in self.columns().items():
            if not isinstance(col, OBSColumn):
                raise RuntimeError(
                    'Values in `.columns()` must be of type OBSColumn, but '
                    '"{col}" is type {type}'.format(col=col_key, type=type(col)))
            if not col.version:
                col.version = self.version()
            col.id = '.'.join([self.prefix(), col.id or col_key])
            tags = self.tags(input_, col_key, col)
            if isinstance(tags, TagTarget):
                col.tags.append(tags)
            else:
                col.tags.extend(tags)

            output[col_key] = ColumnTarget(col, self)
        now_in_session = [obj for obj in session]
        for obj in now_in_session:
            if obj not in already_in_session:
                if obj in session:
                    session.expunge(obj)
        return output

    @property
    def colids(self):
        '''
        Return colids for the output columns, this can be cached
        '''
        if not hasattr(self, '_colids'):
            self._colids = OrderedDict([
                (colkey, ct._id) for colkey, ct in self.output().items()
            ])
        return self._colids

    def complete(self):
        '''
        Custom complete method that attempts to check if output exists, as is
        default, but in case of failure allows attempt to run dependencies (a
        missing dependency could result in exception on `output`).
        '''
        deps = self.deps()
        if deps and not all([d.complete() for d in deps]):
            return False
        else:
            # bulk check that all columns exist at proper version
            cnt = current_session().execute(
                '''
                SELECT COUNT(*)
                FROM observatory.obs_column
                WHERE id IN ('{ids}') AND version = '{version}'
                '''.format(
                    ids="', '".join(list(self.colids.values())),
                    version=self.version()
                )).fetchone()[0]
            return cnt == len(list(self.colids.values()))

    def tags(self, input_, col_key, col):
        '''
        Replace with an iterable of :class:`OBSColumn <tasks.meta.OBSColumn>`
        that should be applied to each column

        :param input_: A saved version of this class's :meth:`input <luigi.Task.input>`
        :param col_key: The key of the column this will be applied to.
        :param column: The :class:`OBSColumn <tasks.meta.OBSColumn>` these tags
                       will be applied to.
        '''
        return [] class TempTableTask(Task):
    '''
    A Task that generates a table that will not be referred to in metadata.

    This is useful for intermediate processing steps that can benefit from the
    session guarantees of the ETL, as well as automatic table naming.

    :param force: Optional Boolean, ``False`` by default.  If ``True``, will
                  overwrite output table even if it exists already.
    '''

    force = BoolParameter(default=False, significant=False)

    def on_failure(self, ex):
        session_rollback(self, ex)
        super(TempTableTask, self).on_failure(ex)

    def on_success(self):
        session_commit(self)

    def target_tablename(self):
        '''
        Can be overriden to expose a different table name
        :return:
        '''
        return unqualified_task_id(self.task_id)[:MAX_PG_IDENTIFIER_LENGTH]

    def run(self):
        '''
        Must be overriden by subclass.  Should create and populate a table
        named from ``self.output().table``

        If this completes without exceptions, the :func:`~.util.current_session
        will be committed; if there is an exception, it will be rolled back.
        '''
        raise Exception('Must override `run`')

    def output(self):
        '''
        By default, returns a :class:`~.targets.TableTarget` whose associated
        table lives in a special-purpose schema in Postgres derived using
        :func:`~.util.classpath`.
        '''
        return PostgresTarget(classpath(self), self.target_tablename()) class TableTask(Task):
    '''
    This task creates a single output table defined by its name, path, and
    defined columns.

    :meth:`~.TableTask.timespan`, :meth:`~.TableTask.columns`, and
    :meth:`~.TableTask.populate` must be overwritten in subclasses.

    When run, this task will automatically create the table with a schema
    corresponding to the defined columns, with a unique name.  It will also
    generate all relevant metadata for the table, and link it to the columns.
    '''

    def _requires(self):
        reqs = super(TableTask, self)._requires()
        if self._testmode:
            return [r for r in reqs if isinstance(r, (TagsTask, TableTask, ColumnsTask))]
        else:
            return reqs

    def version(self):
        '''
        Must return a version control number, which is useful for forcing a
        re-run/overwrite without having to track down and delete output
        artifacts.
        '''
        return 0

    def on_failure(self, ex):
        session_rollback(self, ex)
        super(TableTask, self).on_failure(ex)

    def on_success(self):
        session_commit(self)
        super(TableTask, self).on_success()

    def columns(self):
        '''
        Must be overriden by subclasses.  Columns returned from this function
        determine the schema of the resulting :class:`~tasks.targets.TableTarget`.

        The return for this function should be constructed by selecting the
        desired columns from :class:`~tasks.base_tasks.ColumnTask`s, specified as
        inputs in :meth:`~.tasks.TableTask.requires()`

        Must return a :py:class:`~collections.OrderedDict` of
        (colname, :class:`~tasks.targets.ColumnTarget`) pairs.

        '''
        raise NotImplementedError('Must implement columns method that returns '
                                  'a dict of ColumnTargets')

    def populate(self):
        '''
        This method must populate (most often via ``INSERT``) the output table.

        For example:
        '''
        raise NotImplementedError('Must implement populate method that '
                                  'populates the table')

    def fake_populate(self, output):
        '''
        Put one empty row in the table
        '''
        session = current_session()
        session.execute('INSERT INTO {output} ({col}) VALUES (NULL)'.format(
            output=output.table,
            col=list(self._columns.keys())[0]
        ))

    def description(self):
        '''
        Optional description for the :class:`~tasks.meta.OBSTable`.  Not
        currently used anywhere.
        '''
        return None

    def targets(self):
        return {}

    def table_timespan(self):
        '''
        Must return an OBSTimespan instance that identifies the date range
        or point-in-time for this table.
        Must be implemented by subclass.
        '''
        raise NotImplementedError('Must return an OBSTimespan for table')

    def the_geom(self, output, colname):
        session = current_session()
        return session.execute(
            'SELECT ST_AsText( '
            '  ST_Intersection( '
            '    ST_MakeEnvelope(-179.999, -89.999, 179.999, 89.999, 4326), '
            '    ST_Multi( '
            '      ST_CollectionExtract( '
            '        ST_MakeValid( '
            '          ST_SnapToGrid( '
            '            ST_Buffer( '
            '              ST_Union( '
            '                ST_MakeValid( '
            '                  ST_Simplify( '
            '                    ST_SnapToGrid({geom_colname}, 0.3) '
            '                  , 0) '
            '                ) '
            '              ) '
            '            , 0.3, 2) '
            '          , 0.3) '
            '        ) '
            '      , 3) '
            '    ) '
            '  ) '
            ') the_geom '
            'FROM {output}'.format(
                geom_colname=colname,
                output=output.table
            )).fetchone()['the_geom']

    @property
    def _testmode(self):
        if os.environ.get('ENVIRONMENT') == 'test':
            return True
        return getattr(self, '_test', False)

    def run(self):
        LOGGER.info('getting output()')
        before = time.time()
        output = self.output()
        after = time.time()
        LOGGER.info('time: %s', after - before)

        LOGGER.info('update_or_create_table')
        before = time.time()
        output.update_or_create_table()
        after = time.time()
        LOGGER.info('time: %s', after - before)

        if self._testmode:
            LOGGER.info('fake_populate')
            before = time.time()
            self.fake_populate(output)
            after = time.time()
            LOGGER.info('time: %s', after - before)
        else:
            LOGGER.info('populate')
            before = time.time()
            self.populate()
            after = time.time()
            LOGGER.info('time: %s', after - before)

        before = time.time()
        LOGGER.info('update_or_create_metadata')
        output.update_or_create_metadata(_testmode=self._testmode)
        after = time.time()
        LOGGER.info('time: %s', after - before)

        LOGGER.info('analyzing the table %s', self.output().table)
        session = current_session()
        session.execute('ANALYZE {table}'.format(table=self.output().table))

        if not self._testmode:
            LOGGER.info('checking for null columns on %s', self.output().table)
            self.check_null_columns()

            LOGGER.info('checking for medians/averages without universe target on %s',
                        self.output().table)
            self.check_universe_in_aggregations()

            LOGGER.info('checking for table_to_table relations on %s',
                        self.output().table)
            self.check_table_to_table_relations()

            LOGGER.info('create_indexes')
            self.create_indexes(output)
            current_session().flush()

            LOGGER.info('create_geom_summaries')
            self.create_geom_summaries(output)

            LOGGER.info('checking for null columns on %s', self.output().table)
            self.check_null_columns()

            LOGGER.info('checking for medians/averages without universe target on %s',
                        self.output().table)
            self.check_universe_in_aggregations()

    def create_indexes(self, output):
        session = current_session()
        tablename = output.table
        for colname, coltarget in self._columns.items():
            col = coltarget._column
            index_type = col.index_type
            if index_type:
                index_name = '{}_{}_idx'.format(tablename.split('.')[-1], colname)
                session.execute('CREATE {unique} INDEX IF NOT EXISTS {index_name} ON {table} '
                                'USING {index_type} ({colname})'.format(
                                    unique='',
                                    index_type=index_type,
                                    index_name=index_name,
                                    table=tablename, colname=colname))

    def create_geom_summaries(self, output):
        geometry_columns = [
            (colname, coltarget._id) for colname, coltarget in
            self.columns().items() if coltarget._column.type.lower().startswith('geometry')
        ]

        if len(geometry_columns) == 0:
            return
        elif len(geometry_columns) > 1:
            raise Exception('Having more than one geometry column in one table '
                            'could lead to problematic behavior ')
        colname, colid = geometry_columns[0]
        # Use SQL directly instead of SQLAlchemy because we need the_geom set
        # on obs_table in this session
        current_session().execute("UPDATE observatory.obs_table "
                                  "SET the_geom = ST_GeomFromText('{the_geom}', 4326) "
                                  "WHERE id = '{id}'".format(
                                      the_geom=self.the_geom(output, colname),
                                      id=output._id
                                  ))
        generate_tile_summary(current_session(),
                              output._id, colid, output.table, colname)

    def check_null_columns(self):
        session = current_session()
        query = ('''
                 SELECT attname FROM pg_stats WHERE schemaname = 'observatory'
                 AND tablename = '{table}' AND null_frac = 1
                 '''.format(table=self.output()._tablename))
        result = session.execute(query).fetchall()

        if result:
            raise ValueError('The following columns of the table "{table}" contain only NULL values: {columns}'.format(
                table=self.output().table, columns=', '.join([x[0] for x in result])))

    def check_universe_in_aggregations(self):
        session = current_session()
        query = ('''
                 SELECT c.id, c.aggregate, STRING_AGG(COALESCE(cc.reltype,''), ',') reltype
                 FROM observatory.obs_table t
                 INNER JOIN observatory.obs_column_table ct ON t.id = ct.table_id
                 INNER JOIN observatory.obs_column c ON ct.column_id = c.id
                 FULL JOIN observatory.obs_column_to_column cc ON c.id = cc.source_id
                 WHERE t.tablename = '{table}'
                 AND c.aggregate IN ('average', 'median')
                 GROUP BY 1, 2
                 HAVING 'universe' <> ANY(ARRAY_AGG(COALESCE(LOWER(cc.reltype),'')))
                 '''.format(table=self.output()._tablename))
        result = session.execute(query).fetchall()

        if result:
            raise ValueError("The following columns of the table \"{table}\" are aggregated as 'median' or 'average' "
                             "but lack of 'universe' target: {columns}".format(
                                table=self.output().table, columns=', '.join([x[0] for x in result])))

    def check_table_to_table_relations(self):
        session = current_session()
        # Relations between tables defined as follows:
        # TABLE(SOURCE) -- COLUMN_TABLE(source) -- COLUMN_TO_COLUMN -- COLUMN_TABLE(target) -- TABLE(target)
        # that are not in OBS_TABLE_TO_TABLE
        check_missing_relations_query = ('''
                 SELECT DISTINCT ts.id || '.' || cs.id ||
                 ' / ' || tt.id || '.' || ct.id || ' (' || cc.reltype || ')' relation
                 FROM observatory.obs_table ts, observatory.obs_column_table cts, observatory.obs_column cs,
                 observatory.obs_column_to_column cc,
                 observatory.obs_table tt, observatory.obs_column_table ctt, observatory.obs_column ct
                 WHERE cc.reltype = 'geom_ref'  -- WARNING! only geom_ref reltype ATM
                 AND ts.tablename = '{table}'
                 AND ts.id = cts.table_id
                 AND cts.column_id = cs.id
                 AND cs.id = cc.source_id
                 AND cc.target_id = ct.id
                 AND ct.id = ctt.column_id
                 AND ctt.table_id = tt.id
                 AND NOT EXISTS (
                 SELECT 1
                 FROM observatory.obs_table_to_table ttt
                 WHERE ttt.source_id = ts.id
                 AND ttt.target_id = tt.id)
                 ''').format(table=self.output()._tablename)
        result = session.execute(check_missing_relations_query).fetchall()

        if result:
            raise ValueError('The table "{table}" lacks some table_to_table relations: {relations}'.format(
                table=self.output().table, relations=', '.join([x[0] for x in result])))

        # Relations in OBS_TABLE_TO_TABLE
        # that are not in the relations between tables defined as follows:
        # TABLE(SOURCE) -- COLUMN_TABLE(source) -- COLUMN_TO_COLUMN -- COLUMN_TABLE(target) -- TABLE(target)
        check_excess_relation_query = ('''
                 SELECT DISTINCT ttt.source_id || ' / '
                 || ttt.target_id || ' (' || ttt.reltype || ')' relation
                 FROM observatory.obs_table_to_table ttt, observatory.obs_table t
                 WHERE ttt.source_id = t.id
                 AND t.tablename = '{table}'
                 AND ttt.source_id <> ttt.target_id
                 AND NOT EXISTS (
                 SELECT 1
                 FROM observatory.obs_table ts, observatory.obs_column_table cts, observatory.obs_column cs,
                 observatory.obs_column_to_column cc,
                 observatory.obs_table tt, observatory.obs_column_table ctt, observatory.obs_column ct
                 WHERE cc.reltype = 'geom_ref'  -- WARNING! only geom_ref reltype ATM
                 AND ts.tablename = t.tablename
                 AND ts.id = cts.table_id
                 AND cts.column_id = cs.id
                 AND cs.id = cc.source_id
                 AND cc.target_id = ct.id
                 AND ct.id = ctt.column_id
                 AND ctt.table_id = tt.id
                 AND ts.id <> tt.id  -- avoid relationships between columns of the same table
                 AND NOT EXISTS (  -- avoid columns with the same id as columns in the target table
                 SELECT 1
                 FROM observatory.obs_column_table oct
                 WHERE oct.table_id = ts.id
                 AND oct.column_id = ct.id)
                 AND ttt.source_id = ts.id
                 AND ttt.reltype = cc.reltype
                 AND ttt.target_id = tt.id)
                 ''').format(table=self.output()._tablename)
        result = session.execute(check_excess_relation_query).fetchall()

        if result:
            raise ValueError('The following relations for table "{table}" need to be removed: {relations}'.format(
                table=self.output().table, relations=', '.join([x[0] for x in result])))

    def schema(self):
        return classpath(self)

    def name(self):
        return underscore_slugify(unqualified_task_id(self.task_id))

    def output(self):
        if not hasattr(self, '_columns'):
            self._columns = self.columns()

        tt = TableTarget(self.schema(),
                         self.name(),
                         OBSTable(description=self.description(),
                                  version=self.version(),
                                  table_timespan=self.table_timespan(),
                                  targets=self.targets()),
                         self._columns, self)
        return tt

    def complete(self):
        return TableTarget(self.schema(),
                           self.name(),
                           OBSTable(description=self.description(),
                                    version=self.version(),
                                    table_timespan=self.table_timespan()),
                           [], self).exists() class RepoFileUnzipTask(RepoFileUncompressTask):
    '''
    Download a zip file to location {output}.zip and unzip it to the folder
    {output}.
    '''
    compressed_extension = 'zip'

    def uncompress(self):
        uncompress_file(self.output().path) class TagsTask(Task):
    '''
    This will update-or-create :class:`OBSTag <tasks.meta.OBSTag>` objects
    int the database when run.

    The :meth:`~.TagsTask.tags` method must be overwritten.

    :meth:`~TagsTask.version` is used to control updates to the database.
    '''

    def tags(self):
        '''
        This method must be overwritten in subclasses.

        The return value must be an iterable of instances of
        :class:`OBSTag <tasks.meta.OBSTag>`.
        '''
        raise NotImplementedError('Must return iterable of OBSTags')

    def on_failure(self, ex):
        session_rollback(self, ex)
        super(TagsTask, self).on_failure(ex)

    def on_success(self):
        session_commit(self)

    def run(self):
        for _, tagtarget in self.output().items():
            tagtarget.update_or_create()

    def version(self):
        return 0

    def output(self):
        # if self.deps() and not all([d.complete() for d in self.deps()]):
        #    raise Exception('Must run prerequisites first')
        output = {}
        for tag in self.tags():
            orig_id = tag.id
            tag.id = '.'.join([classpath(self), orig_id])
            if not tag.version:
                tag.version = self.version()
            output[orig_id] = TagTarget(tag, self)
        return output class CSV2TempTableTask(TempTableTask):
    '''
    A task that loads :meth:`~.tasks.CSV2TempTableTask.input_csv` into a
    temporary Postgres table.  That method must be overriden.

    Optionally, :meth:`~tasks.CSV2TempTableTask.coldef` can be overriden.

    Under the hood, uses postgres's ``COPY``.

    :param delimiter: Delimiter separating fields in the CSV.  Defaults to
                      ``,``.  Must be one character.
    :param has_header: Boolean as to whether first row has column names.
                       Defaults to ``True``.
    :param force: Boolean as to whether the task should be run even if the
                  temporary output already exists.
    '''

    delimiter = Parameter(default=',', significant=False)
    has_header = BoolParameter(default=True, significant=False)
    encoding = Parameter(default='utf8', significant=False)

    def input_csv(self):
        '''
        Must be overriden with a method that returns either a path to a CSV
        or an iterable of paths to CSVs.
        '''
        raise NotImplementedError("Must specify `input_csv` method")

    def coldef(self):
        '''
        Override this function to customize the column definitions in the table.
        Expected is an iterable of two-tuples.

        If not overriden:

        * All column types will be ``Text``
        * If :attr:`~.tasks.CSV2TempTableTask.has_header` is ``True``, then
          column names will come from the headers.
        * If :attr:`~.tasks.CSV2TempTableTask.has_header` is ``False``, then
          column names will be the postgres defaults.
        '''
        if isinstance(self.input_csv(), str):
            csvfile = self.input_csv()
        else:
            raise NotImplementedError("Cannot automatically determine colnames "
                                      "if several input CSVs.")

        with open('{csv}'.format(csv=csvfile), 'r', encoding=self.encoding) as f:
            header_row = next(csv.reader(f, delimiter=self.delimiter))
        return [(h, 'Text') for h in header_row]

    def read_method(self, fname):
        return 'cat "{input}"'.format(input=fname)

    def run(self):
        if isinstance(self.input_csv(), str):
            csvs = [self.input_csv()]
        else:
            csvs = self.input_csv()

        session = current_session()
        session.execute('CREATE TABLE {output} ({coldef})'.format(
            output=self.output().table,
            coldef=', '.join(['"{}" {}'.format(c[0], c[1]) for c in self.coldef()])
        ))
        session.commit()
        options = ['''
           DELIMITER '"'{delimiter}'"' ENCODING '"'{encoding}'"'
        '''.format(delimiter=self.delimiter,
                   encoding=self.encoding)]
        if self.has_header:
            options.append('CSV HEADER')
        try:
            for csvfile in csvs:
                shell(r'''{read_method} | psql -c '\copy {table} FROM STDIN {options}' '''.format(
                    read_method=self.read_method(csvfile),
                    table=self.output().table,
                    options=' '.join(options)
                ))
            self.after_copy()
        except:
            session.rollback()
            session.execute('DROP TABLE IF EXISTS {output}'.format(
                output=self.output().table))
            session.commit()
            raise

    def after_copy(self):
        pass def underscore_slugify(txt):
    '''
    Given a string, converts from camelcase to underscore style, and then
    slugifies.

    >>> underscore_slugify('FooBarBaz')
    'foo_bar_baz'

    >>> underscore_slugify('Foo, bar, baz')
    'foo_bar_baz'

    >>> underscore_slugify('Foo_Bar_Baz')
    'foo_bar_baz'

    >>> underscore_slugify('Foo:barBaz')
    'foo_bar_baz'
    '''
    return slugify(camel_to_underscore(re.sub(
        r'[^a-zA-Z0-9]+', '_', txt))).replace('-', '_') def copyfile(src, dst):
    # From http://luigi.readthedocs.io/en/stable/_modules/luigi/local_target.html#LocalTarget.makedirs
    normpath = os.path.normpath(dst)
    parentfolder = os.path.dirname(normpath)
    if parentfolder:
        try:
            os.makedirs(parentfolder, exist_ok=True)
        except OSError as e:
            LOGGER.error('Error making dirs for copyfile: %s', e)
            pass

    shutil.copyfile(src, dst) def current_session():
    '''
    Returns the session relevant to the currently operating :class:`Task`, if
    any.  Outside the context of a :class:`Task`, this can still be used for
    manual session management.
    '''
    return _current_session.get() DENOMINATOR = 'denominator' UNIVERSE = 'universe' NAICS_CODES = dict([
    ('10', "Total, all industries"),
    ('101', "Goods-producing"),
    ('1011', "Natural resources and mining"),
    ('1012', "Construction"),
    ('1013', "Manufacturing"),
    ('102', "Service-providing"),
    ('1021', "Trade, transportation, and utilities"),
    ('1022', "Information"),
    ('1023', "Financial activities"),
    ('1024', "Professional and business services"),
    ('1025', "Education and health services"),
    ('1026', "Leisure and hospitality"),
    ('1027', "Other services"),
    ('1028', "Public administration"),
    ('1029', "Unclassified"),
    ('11', "Agriculture, forestry, fishing and hunting"),
    ('111', "Crop production"),
    ('1111', "Oilseed and grain farming"),
    ('11111', "Soybean farming"),
    ('111110', "Soybean farming"),
    ('11112', "Oilseed, except soybean, farming"),
    ('111120', "Oilseed, except soybean, farming"),
    ('11113', "Dry pea and bean farming"),
    ('111130', "Dry pea and bean farming"),
    ('11114', "Wheat farming"),
    ('111140', "Wheat farming"),
    ('11115', "Corn farming"),
    ('111150', "Corn farming"),
    ('11116', "Rice farming"),
    ('111160', "Rice farming"),
    ('11119', "Other grain farming"),
    ('111191', "Oilseed and grain combination farming"),
    ('111199', "All other grain farming"),
    ('1112', "Vegetable and melon farming"),
    ('11121', "Vegetable and melon farming"),
    ('111211', "Potato farming"),
    ('111219', "Other vegetable and melon farming"),
    ('1113', "Fruit and tree nut farming"),
    ('11131', "Orange groves"),
    ('111310', "Orange groves"),
    ('11132', "Citrus, except orange, groves"),
    ('111320', "Citrus, except orange, groves"),
    ('11133', "Noncitrus fruit and tree nut farming"),
    ('111331', "Apple orchards"),
    ('111332', "Grape vineyards"),
    ('111333', "Strawberry farming"),
    ('111334', "Berry, except strawberry, farming"),
    ('111335', "Tree nut farming"),
    ('111336', "Fruit and tree nut combination farming"),
    ('111339', "Other noncitrus fruit farming"),
    ('1114', "Greenhouse and nursery production"),
    ('11141', "Food crops grown under cover"),
    ('111411', "Mushroom production"),
    ('111419', "Other food crops grown under cover"),
    ('11142', "Nursery and floriculture production"),
    ('111421', "Nursery and tree production"),
    ('111422', "Floriculture production"),
    ('1119', "Other crop farming"),
    ('11191', "Tobacco farming"),
    ('111910', "Tobacco farming"),
    ('11192', "Cotton farming"),
    ('111920', "Cotton farming"),
    ('11193', "Sugarcane farming"),
    ('111930', "Sugarcane farming"),
    ('11194', "Hay farming"),
    ('111940', "Hay farming"),
    ('11199', "All other crop farming"),
    ('111991', "Sugar beet farming"),
    ('111992', "Peanut farming"),
    ('111998', "All other miscellaneous crop farming"),
    ('112', "Animal production and aquaculture"),
    ('1121', "Cattle ranching and farming"),
    ('11211', "Beef cattle ranching, farming, and feedlots"),
    ('112111', "Beef cattle ranching and farming"),
    ('112112', "Cattle feedlots"),
    ('11212', "Dairy cattle and milk production"),
    ('112120', "Dairy cattle and milk production"),
    ('1122', "Hog and pig farming"),
    ('11221', "Hog and pig farming"),
    ('112210', "Hog and pig farming"),
    ('1123', "Poultry and egg production"),
    ('11231', "Chicken egg production"),
    ('112310', "Chicken egg production"),
    ('11232', "Broilers and meat type chicken production"),
    ('112320', "Broilers and meat type chicken production"),
    ('11233', "Turkey production"),
    ('112330', "Turkey production"),
    ('11234', "Poultry hatcheries"),
    ('112340', "Poultry hatcheries"),
    ('11239', "Other poultry production"),
    ('112390', "Other poultry production"),
    ('1124', "Sheep and goat farming"),
    ('11241', "Sheep farming"),
    ('112410', "Sheep farming"),
    ('11242', "Goat farming"),
    ('112420', "Goat farming"),
    ('1125', "Aquaculture"),
    ('11251', "Aquaculture"),
    ('112511', "Finfish farming and fish hatcheries"),
    ('112512', "Shellfish farming"),
    ('112519', "Other aquaculture"),
    ('1129', "Other animal production"),
    ('11291', "Apiculture"),
    ('112910', "Apiculture"),
    ('11292', "Horses and other equine production"),
    ('112920', "Horses and other equine production"),
    ('11293', "Fur-bearing animal and rabbit production"),
    ('112930', "Fur-bearing animal and rabbit production"),
    ('11299', "All other animal production"),
    ('112990', "All other animal production"),
    ('113', "Forestry and logging"),
    ('1131', "Timber tract operations"),
    ('11311', "Timber tract operations"),
    ('113110', "Timber tract operations"),
    ('1132', "Forest nursery and gathering forest products"),
    ('11321', "Forest nursery and gathering forest products"),
    ('113210', "Forest nursery and gathering forest products"),
    ('1133', "Logging"),
    ('11331', "Logging"),
    ('113310', "Logging"),
    ('114', "Fishing, hunting and trapping"),
    ('1141', "Fishing"),
    ('11411', "Fishing"),
    ('114111', "Finfish fishing"),
    ('114112', "Shellfish fishing"),
    ('114119', "Other marine fishing"),
    ('1142', "Hunting and trapping"),
    ('11421', "Hunting and trapping"),
    ('114210', "Hunting and trapping"),
    ('115', "Agriculture and forestry support activities"),
    ('1151', "Support activities for crop production"),
    ('11511', "Support activities for crop production"),
    ('115111', "Cotton ginning"),
    ('115112', "Soil preparation, planting, and cultivating"),
    ('115113', "Crop harvesting, primarily by machine"),
    ('115114', "Other postharvest crop activities"),
    ('115115', "Farm labor contractors and crew leaders"),
    ('115116', "Farm management services"),
    ('1152', "Support activities for animal production"),
    ('11521', "Support activities for animal production"),
    ('115210', "Support activities for animal production"),
    ('1153', "Support activities for forestry"),
    ('11531', "Support activities for forestry"),
    ('115310', "Support activities for forestry"),
    ('21', "Mining, quarrying, and oil and gas extraction"),
    ('211', "Oil and gas extraction"),
    ('2111', "Oil and gas extraction"),
    ('21111', "Oil and gas extraction"),
    ('211111', "Crude petroleum and natural gas extraction"),
    ('211112', "Natural gas liquid extraction"),
    ('212', "Mining, except oil and gas"),
    ('2121', "Coal mining"),
    ('21211', "Coal mining"),
    ('212111', "Bituminous coal and lignite surface mining"),
    ('212112', "Bituminous coal underground mining"),
    ('212113', "Anthracite mining"),
    ('2122', "Metal ore mining"),
    ('21221', "Iron ore mining"),
    ('212210', "Iron ore mining"),
    ('21222', "Gold ore and silver ore mining"),
    ('212221', "Gold ore mining"),
    ('212222', "Silver ore mining"),
    ('21223', "Copper, nickel, lead, and zinc mining"),
    ('212231', "Lead ore and zinc ore mining"),
    ('212234', "Copper ore and nickel ore mining"),
    ('21229', "Other metal ore mining"),
    ('212291', "Uranium-radium-vanadium ore mining"),
    ('212299', "All other metal ore mining"),
    ('2123', "Nonmetallic mineral mining and quarrying"),
    ('21231', "Stone mining and quarrying"),
    ('212311', "Dimension stone mining and quarrying"),
    ('212312', "Crushed and broken limestone mining"),
    ('212313', "Crushed and broken granite mining"),
    ('212319', "Other crushed and broken stone mining"),
    ('21232', "Sand, gravel, clay, and refractory mining"),
    ('212321', "Construction sand and gravel mining"),
    ('212322', "Industrial sand mining"),
    ('212324', "Kaolin and ball clay mining"),
    ('212325', "Clay, ceramic, and refractory minerals mining"),
    ('21239', "Other nonmetallic mineral mining"),
    ('212391', "Potash, soda, and borate mineral mining"),
    ('212392', "Phosphate rock mining"),
    ('212393', "Other chemical and fertilizer mineral mining"),
    ('212399', "All other nonmetallic mineral mining"),
    ('213', "Support activities for mining"),
    ('2131', "Support activities for mining"),
    ('21311', "Support activities for mining"),
    ('213111', "Drilling oil and gas wells"),
    ('213112', "Support activities for oil and gas operations"),
    ('213113', "Support activities for coal mining"),
    ('213114', "Support activities for metal mining"),
    ('213115', "Support activities for nonmetallic minerals"),
    ('23', "Construction"),
    ('236', "Construction of buildings"),
    ('2361', "Residential building construction"),
    ('23611', "Residential building construction"),
    ('236115', "New single-family general contractors"),
    ('236116', "New multifamily general contractors"),
    ('236117', "New housing for-sale builders"),
    ('236118', "Residential remodelers"),
    ('2362', "Nonresidential building construction"),
    ('23621', "Industrial building construction"),
    ('236210', "Industrial building construction"),
    ('23622', "Commercial building construction"),
    ('236220', "Commercial building construction"),
    ('237', "Heavy and civil engineering construction"),
    ('2371', "Utility system construction"),
    ('23711', "Water and sewer system construction"),
    ('237110', "Water and sewer system construction"),
    ('23712', "Oil and gas pipeline construction"),
    ('237120', "Oil and gas pipeline construction"),
    ('23713', "Power and communication system construction"),
    ('237130', "Power and communication system construction"),
    ('2372', "Land subdivision"),
    ('23721', "Land subdivision"),
    ('237210', "Land subdivision"),
    ('2373', "Highway, street, and bridge construction"),
    ('23731', "Highway, street, and bridge construction"),
    ('237310', "Highway, street, and bridge construction"),
    ('2379', "Other heavy construction"),
    ('23799', "Other heavy construction"),
    ('237990', "Other heavy construction"),
    ('238', "Specialty trade contractors"),
    ('2381', "Building foundation and exterior contractors"),
    ('23811', "Poured concrete structure contractors"),
    ('238111', "Residential poured foundation contractors"),
    ('238112', "Nonresidential poured foundation contractors"),
    ('23812', "Steel and precast concrete contractors"),
    ('238121', "Residential structural steel contractors"),
    ('238122', "Nonresidential structural steel contractors"),
    ('23813', "Framing contractors"),
    ('238131', "Residential framing contractors"),
    ('238132', "Nonresidential framing contractors"),
    ('23814', "Masonry contractors"),
    ('238141', "Residential masonry contractors"),
    ('238142', "Nonresidential masonry contractors"),
    ('23815', "Glass and glazing contractors"),
    ('238151', "Residential glass and glazing contractors"),
    ('238152', "Nonresidential glass and glazing contractors"),
    ('23816', "Roofing contractors"),
    ('238161', "Residential roofing contractors"),
    ('238162', "Nonresidential roofing contractors"),
    ('23817', "Siding contractors"),
    ('238171', "Residential siding contractors"),
    ('238172', "Nonresidential siding contractors"),
    ('23819', "Other building exterior contractors"),
    ('238191', "Other residential exterior contractors"),
    ('238192', "Other nonresidential exterior contractors"),
    ('2382', "Building equipment contractors"),
    ('23821', "Electrical and wiring contractors"),
    ('238211', "Residential electrical contractors"),
    ('238212', "Nonresidential electrical contractors"),
    ('23822', "Plumbing and hvac contractors"),
    ('238221', "Residential plumbing and hvac contractors"),
    ('238222', "Nonresidential plumbing and hvac contractors"),
    ('23829', "Other building equipment contractors"),
    ('238291', "Other residential equipment contractors"),
    ('238292', "Other nonresidential equipment contractors"),
    ('2383', "Building finishing contractors"),
    ('23831', "Drywall and insulation contractors"),
    ('238311', "Residential drywall contractors"),
    ('238312', "Nonresidential drywall contractors"),
    ('23832', "Painting and wall covering contractors"),
    ('238321', "Residential painting contractors"),
    ('238322', "Nonresidential painting contractors"),
    ('23833', "Flooring contractors"),
    ('238331', "Residential flooring contractors"),
    ('238332', "Nonresidential flooring contractors"),
    ('23834', "Tile and terrazzo contractors"),
    ('238341', "Residential tile and terrazzo contractors"),
    ('238342', "Nonresidential tile and terrazzo contractors"),
    ('23835', "Finish carpentry contractors"),
    ('238351', "Residential finish carpentry contractors"),
    ('238352', "Nonresidential finish carpentry contractors"),
    ('23839', "Other building finishing contractors"),
    ('238391', "Other residential finishing contractors"),
    ('238392', "Other nonresidential finishing contractors"),
    ('2389', "Other specialty trade contractors"),
    ('23891', "Site preparation contractors"),
    ('238911', "Residential site preparation contractors"),
    ('238912', "Nonresidential site preparation contractors"),
    ('23899', "All other specialty trade contractors"),
    ('238991', "All other residential trade contractors"),
    ('238992', "All other nonresidential trade contractors"),
    ('31-33', "Manufacturing"),
    ('311', "Food manufacturing"),
    ('3111', "Animal food manufacturing"),
    ('31111', "Animal food manufacturing"),
    ('311111', "Dog and cat food manufacturing"),
    ('311119', "Other animal food manufacturing"),
    ('3112', "Grain and oilseed milling"),
    ('31121', "Flour milling and malt manufacturing"),
    ('311211', "Flour milling"),
    ('311212', "Rice milling"),
    ('311213', "Malt manufacturing"),
    ('31122', "Starch and vegetable oil manufacturing"),
    ('311221', "Wet corn milling"),
    ('311222', "Soybean processing"),
    ('311223', "Other oilseed processing"),
    ('311224', "Soybean and other oilseed processing"),
    ('311225', "Fats and oils refining and blending"),
    ('31123', "Breakfast cereal manufacturing"),
    ('311230', "Breakfast cereal manufacturing"),
    ('3113', "Sugar and confectionery product manufacturing"),
    ('31131', "Sugar manufacturing"),
    ('311311', "Sugarcane mills"),
    ('311312', "Cane sugar refining"),
    ('311313', "Beet sugar manufacturing"),
    ('311314', "Cane sugar manufacturing"),
    ('31132', "Confectionery manufacturing from cacao beans"),
    ('311320', "Confectionery manufacturing from cacao beans"),
    ('31133', "Confectionery mfg. from purchased chocolate"),
    ('311330', "Confectionery mfg. from purchased chocolate"),
    ('31134', "Nonchocolate confectionery manufacturing"),
    ('311340', "Nonchocolate confectionery manufacturing"),
    ('31135', "Confectionery mfg. from cacao or chocolate"),
    ('311351', "Confectionery manufacturing from cacao beans"),
    ('311352', "Confectionery mfg. from purchased chocolate"),
    ('3114', "Fruit and vegetable preserving and specialty"),
    ('31141', "Frozen food manufacturing"),
    ('311411', "Frozen fruit and vegetable manufacturing"),
    ('311412', "Frozen specialty food manufacturing"),
    ('31142', "Fruit and vegetable canning and drying"),
    ('311421', "Fruit and vegetable canning"),
    ('311422', "Specialty canning"),
    ('311423', "Dried and dehydrated food manufacturing"),
    ('3115', "Dairy product manufacturing"),
    ('31151', "Dairy product, except frozen, manufacturing"),
    ('311511', "Fluid milk manufacturing"),
    ('311512', "Creamery butter manufacturing"),
    ('311513', "Cheese manufacturing"),
    ('311514', "Dry, condensed, and evaporated dairy products"),
    ('31152', "Ice cream and frozen dessert manufacturing"),
    ('311520', "Ice cream and frozen dessert manufacturing"),
    ('3116', "Animal slaughtering and processing"),
    ('31161', "Animal slaughtering and processing"),
    ('311611', "Animal, except poultry, slaughtering"),
    ('311612', "Meat processed from carcasses"),
    ('311613', "Rendering and meat byproduct processing"),
    ('311615', "Poultry processing"),
    ('3117', "Seafood product preparation and packaging"),
    ('31171', "Seafood product preparation and packaging"),
    ('311710', "Seafood product preparation and packaging"),
    ('311711', "Seafood canning"),
    ('311712', "Fresh and frozen seafood processing"),
    ('3118', "Bakeries and tortilla manufacturing"),
    ('31181', "Bread and bakery product manufacturing"),
    ('311811', "Retail bakeries"),
    ('311812', "Commercial bakeries"),
    ('311813', "Frozen cakes and other pastries manufacturing"),
    ('31182', "Cookie, cracker, and pasta manufacturing"),
    ('311821', "Cookie and cracker manufacturing"),
    ('311822', "Mixes and dough made from purchased flour"),
    ('311823', "Dry pasta manufacturing"),
    ('311824', "Dry pasta and mixes from purchased flour"),
    ('31183', "Tortilla manufacturing"),
    ('311830', "Tortilla manufacturing"),
    ('3119', "Other food manufacturing"),
    ('31191', "Snack food manufacturing"),
    ('311911', "Roasted nuts and peanut butter manufacturing"),
    ('311919', "Other snack food manufacturing"),
    ('31192', "Coffee and tea manufacturing"),
    ('311920', "Coffee and tea manufacturing"),
    ('31193', "Flavoring syrup and concentrate manufacturing"),
    ('311930', "Flavoring syrup and concentrate manufacturing"),
    ('31194', "Seasoning and dressing manufacturing"),
    ('311941', "Mayonnaise, dressing, and sauce manufacturing"),
    ('311942', "Spice and extract manufacturing"),
    ('31199', "All other food manufacturing"),
    ('311991', "Perishable prepared food manufacturing"),
    ('311999', "All other miscellaneous food manufacturing"),
    ('312', "Beverage and tobacco product manufacturing"),
    ('3121', "Beverage manufacturing"),
    ('31211', "Soft drink and ice manufacturing"),
    ('312111', "Soft drink manufacturing"),
    ('312112', "Bottled water manufacturing"),
    ('312113', "Ice manufacturing"),
    ('31212', "Breweries"),
    ('312120', "Breweries"),
    ('31213', "Wineries"),
    ('312130', "Wineries"),
    ('31214', "Distilleries"),
    ('312140', "Distilleries"),
    ('3122', "Tobacco manufacturing"),
    ('31221', "Tobacco stemming and redrying"),
    ('312210', "Tobacco stemming and redrying"),
    ('31222', "Tobacco product manufacturing"),
    ('312221', "Cigarette manufacturing"),
    ('312229', "Other tobacco product manufacturing"),
    ('31223', "Tobacco manufacturing"),
    ('312230', "Tobacco manufacturing"),
    ('313', "Textile mills"),
    ('3131', "Fiber, yarn, and thread mills"),
    ('31311', "Fiber, yarn, and thread mills"),
    ('313110', "Fiber, yarn, and thread mills"),
    ('313111', "Yarn spinning mills"),
    ('313112', "Yarn texturizing and twisting mills"),
    ('313113', "Thread mills"),
    ('3132', "Fabric mills"),
    ('31321', "Broadwoven fabric mills"),
    ('313210', "Broadwoven fabric mills"),
    ('31322', "Narrow fabric mills and schiffli embroidery"),
    ('313220', "Narrow fabric mills and schiffli machine emb."),
    ('313221', "Narrow fabric mills"),
    ('313222', "Schiffli machine embroidery"),
    ('31323', "Nonwoven fabric mills"),
    ('313230', "Nonwoven fabric mills"),
    ('31324', "Knit fabric mills"),
    ('313240', "Knit fabric mills"),
    ('313241', "Weft knit fabric mills"),
    ('313249', "Other knit fabric and lace mills"),
    ('3133', "Textile and fabric finishing mills"),
    ('31331', "Textile and fabric finishing mills"),
    ('313310', "Textile and fabric finishing mills"),
    ('313311', "Broadwoven fabric finishing mills"),
    ('313312', "Other textile and fabric finishing mills"),
    ('31332', "Fabric coating mills"),
    ('313320', "Fabric coating mills"),
    ('314', "Textile product mills"),
    ('3141', "Textile furnishings mills"),
    ('31411', "Carpet and rug mills"),
    ('314110', "Carpet and rug mills"),
    ('31412', "Curtain and linen mills"),
    ('314120', "Curtain and linen mills"),
    ('314121', "Curtain and drapery mills"),
    ('314129', "Other household textile product mills"),
    ('3149', "Other textile product mills"),
    ('31491', "Textile bag and canvas mills"),
    ('314910', "Textile bag and canvas mills"),
    ('314911', "Textile bag mills"),
    ('314912', "Canvas and related product mills"),
    ('31499', "All other textile product mills"),
    ('314991', "Rope, cordage, and twine mills"),
    ('314992', "Tire cord and tire fabric mills"),
    ('314994', "Rope, cordage, twine, and tire fabric mills"),
    ('314999', "All other miscellaneous textile product mills"),
    ('315', "Apparel manufacturing"),
    ('3151', "Apparel knitting mills"),
    ('31511', "Hosiery and sock mills"),
    ('315110', "Hosiery and sock mills"),
    ('315111', "Sheer hosiery mills"),
    ('315119', "Other hosiery and sock mills"),
    ('31519', "Other apparel knitting mills"),
    ('315190', "Other apparel knitting mills"),
    ('315191', "Outerwear knitting mills"),
    ('315192', "Underwear and nightwear knitting mills"),
    ('3152', "Cut and sew apparel manufacturing"),
    ('31521', "Cut and sew apparel contractors"),
    ('315210', "Cut and sew apparel contractors"),
    ('315211', "Men's and boys' apparel contractors"),
    ('315212', "Women's, girls', infants' apparel contractors"),
    ('31522', "Men's and boys' cut and sew apparel mfg."),
    ('315220', "Men's and boys' cut and sew apparel mfg."),
    ('315221', "Men's and boys' underwear and nightwear mfg"),
    ('315222', "Men's and boys' suit, coat, and overcoat mfg"),
    ('315223', "Men's and boys' shirt, except work shirt, mfg"),
    ('315224', "Men's and boys' pants, except work pants, mfg"),
    ('315225', "Men's and boys' work clothing manufacturing"),
    ('315228', "Other men's and boys' outerwear manufacturing"),
    ('31523', "Women's and girls' cut and sew apparel mfg"),
    ('315231', "Women's and girls' lingerie and nightwear mfg"),
    ('315232', "Women's and girls' blouse and shirt mfg"),
    ('315233', "Women's and girls' dress manufacturing"),
    ('315234', "Women's and girls' suit, coat, and skirt mfg"),
    ('315239', "Other women's and girls' outerwear mfg"),
    ('31524', "Women's and infants' cut and sew apparel mfg."),
    ('315240', "Women's cut and sew apparel manufacturing"),
    ('31528', "Other cut and sew apparel manufacturing"),
    ('315280', "Other cut and sew apparel manufacturing"),
    ('31529', "Other cut and sew apparel manufacturing"),
    ('315291', "Infants' cut and sew apparel manufacturing"),
    ('315292', "Fur and leather apparel manufacturing"),
    ('315299', "All other cut and sew apparel manufacturing"),
    ('3159', "Accessories and other apparel manufacturing"),
    ('31599', "Accessories and other apparel manufacturing"),
    ('315990', "Apparel accessories and other apparel mfg."),
    ('315991', "Hat, cap, and millinery manufacturing"),
    ('315992', "Glove and mitten manufacturing"),
    ('315993', "Men's and boys' neckwear manufacturing"),
    ('315999', "All other accessory and apparel manufacturing"),
    ('316', "Leather and allied product manufacturing"),
    ('3161', "Leather and hide tanning and finishing"),
    ('31611', "Leather and hide tanning and finishing"),
    ('316110', "Leather and hide tanning and finishing"),
    ('3162', "Footwear manufacturing"),
    ('31621', "Footwear manufacturing"),
    ('316210', "Footwear manufacturing"),
    ('316211', "Rubber and plastics footwear manufacturing"),
    ('316212', "House slipper manufacturing"),
    ('316213', "Men's nonathletic footwear manufacturing"),
    ('316214', "Women's nonathletic footwear manufacturing"),
    ('316219', "Other footwear manufacturing"),
    ('3169', "Other leather product manufacturing"),
    ('31699', "Other leather product manufacturing"),
    ('316991', "Luggage manufacturing"),
    ('316992', "Women's handbag and purse manufacturing"),
    ('316993', "Other personal leather good manufacturing"),
    ('316998', "Other leather good and allied product mfg."),
    ('316999', "All other leather and allied good mfg."),
    ('321', "Wood product manufacturing"),
    ('3211', "Sawmills and wood preservation"),
    ('32111', "Sawmills and wood preservation"),
    ('321113', "Sawmills"),
    ('321114', "Wood preservation"),
    ('3212', "Plywood and engineered wood product mfg."),
    ('32121', "Plywood and engineered wood product mfg."),
    ('321211', "Hardwood veneer and plywood manufacturing"),
    ('321212', "Softwood veneer and plywood manufacturing"),
    ('321213', "Engineered wood member manufacturing"),
    ('321214', "Truss manufacturing"),
    ('321219', "Reconstituted wood product manufacturing"),
    ('3219', "Other wood product manufacturing"),
    ('32191', "Millwork"),
    ('321911', "Wood window and door manufacturing"),
    ('321912', "Cut stock, resawing lumber, and planing"),
    ('321918', "Other millwork, including flooring"),
    ('32192', "Wood container and pallet manufacturing"),
    ('321920', "Wood container and pallet manufacturing"),
    ('32199', "All other wood product manufacturing"),
    ('321991', "Manufactured home, mobile home, manufacturing"),
    ('321992', "Prefabricated wood building manufacturing"),
    ('321999', "All other miscellaneous wood product mfg."),
    ('322', "Paper manufacturing"),
    ('3221', "Pulp, paper, and paperboard mills"),
    ('32211', "Pulp mills"),
    ('322110', "Pulp mills"),
    ('32212', "Paper mills"),
    ('322121', "Paper, except newsprint, mills"),
    ('322122', "Newsprint mills"),
    ('32213', "Paperboard mills"),
    ('322130', "Paperboard mills"),
    ('3222', "Converted paper product manufacturing"),
    ('32221', "Paperboard container manufacturing"),
    ('322211', "Corrugated and solid fiber box manufacturing"),
    ('322212', "Folding paperboard box manufacturing"),
    ('322213', "Setup paperboard box manufacturing"),
    ('322214', "Fiber can, tube, and drum manufacturing"),
    ('322215', "Nonfolding sanitary food container mfg."),
    ('322219', "Other paperboard container manufacturing"),
    ('32222', "Paper bag and coated and treated paper mfg."),
    ('322220', "Paper bag and coated and treated paper mfg."),
    ('322221', "Coated and laminated packaging paper mfg."),
    ('322222', "Coated and laminated paper manufacturing"),
    ('322223', "Coated paper bag and pouch manufacturing"),
    ('322224', "Uncoated paper and multiwall bag mfg."),
    ('322225', "Flexible packaging foil manufacturing"),
    ('322226', "Surface-coated paperboard manufacturing"),
    ('32223', "Stationery product manufacturing"),
    ('322230', "Stationery product manufacturing"),
    ('322231', "Die-cut paper office supplies manufacturing"),
    ('322232', "Envelope manufacturing"),
    ('322233', "Stationery and related product manufacturing"),
    ('32229', "Other converted paper product manufacturing"),
    ('322291', "Sanitary paper product manufacturing"),
    ('322299', "All other converted paper product mfg."),
    ('323', "Printing and related support activities"),
    ('3231', "Printing and related support activities"),
    ('32311', "Printing"),
    ('323110', "Commercial lithographic printing"),
    ('323111', "Commercial printing (exc. screen and books)"),
    ('323112', "Commercial flexographic printing"),
    ('323113', "Commercial screen printing"),
    ('323114', "Quick printing"),
    ('323115', "Digital printing"),
    ('323116', "Manifold business forms printing"),
    ('323117', "Books printing"),
    ('323118', "Blankbook and looseleaf binder manufacturing"),
    ('323119', "Other commercial printing"),
    ('32312', "Support activities for printing"),
    ('323120', "Support activities for printing"),
    ('323121', "Tradebinding and related work"),
    ('323122', "Prepress services"),
    ('324', "Petroleum and coal products manufacturing"),
    ('3241', "Petroleum and coal products manufacturing"),
    ('32411', "Petroleum refineries"),
    ('324110', "Petroleum refineries"),
    ('32412', "Asphalt paving and roofing materials mfg."),
    ('324121', "Asphalt paving mixture and block mfg."),
    ('324122', "Asphalt shingle and coating materials mfg."),
    ('32419', "Other petroleum and coal products mfg."),
    ('324191', "Petroleum lubricating oil and grease mfg."),
    ('324199', "All other petroleum and coal products mfg."),
    ('325', "Chemical manufacturing"),
    ('3251', "Basic chemical manufacturing"),
    ('32511', "Petrochemical manufacturing"),
    ('325110', "Petrochemical manufacturing"),
    ('32512', "Industrial gas manufacturing"),
    ('325120', "Industrial gas manufacturing"),
    ('32513', "Synthetic dye and pigment manufacturing"),
    ('325130', "Synthetic dye and pigment manufacturing"),
    ('325131', "Inorganic dye and pigment manufacturing"),
    ('325132', "Synthetic organic dye and pigment mfg."),
    ('32518', "Other basic inorganic chemical manufacturing"),
    ('325180', "Other basic inorganic chemical manufacturing"),
    ('325181', "Alkalies and chlorine manufacturing"),
    ('325182', "Carbon black manufacturing"),
    ('325188', "All other basic inorganic chemical mfg."),
    ('32519', "Other basic organic chemical manufacturing"),
    ('325191', "Gum and wood chemical manufacturing"),
    ('325192', "Cyclic crude and intermediate manufacturing"),
    ('325193', "Ethyl alcohol manufacturing"),
    ('325194', "Cyclic crude, and gum and wood chemical mfg."),
    ('325199', "All other basic organic chemical mfg."),
    ('3252', "Resin, rubber, and artificial fibers mfg."),
    ('32521', "Resin and synthetic rubber manufacturing"),
    ('325211', "Plastics material and resin manufacturing"),
    ('325212', "Synthetic rubber manufacturing"),
    ('32522', "Artificial fibers and filaments manufacturing"),
    ('325220', "Artificial and synthetic fibers manufacturing"),
    ('325221', "Cellulosic organic fiber manufacturing"),
    ('325222', "Noncellulosic organic fiber manufacturing"),
    ('3253', "Agricultural chemical manufacturing"),
    ('32531', "Fertilizer manufacturing"),
    ('325311', "Nitrogenous fertilizer manufacturing"),
    ('325312', "Phosphatic fertilizer manufacturing"),
    ('325314', "Fertilizer, mixing only, manufacturing"),
    ('32532', "Pesticide and other ag. chemical mfg."),
    ('325320', "Pesticide and other ag. chemical mfg."),
    ('3254', "Pharmaceutical and medicine manufacturing"),
    ('32541', "Pharmaceutical and medicine manufacturing"),
    ('325411', "Medicinal and botanical manufacturing"),
    ('325412', "Pharmaceutical preparation manufacturing"),
    ('325413', "In-vitro diagnostic substance manufacturing"),
    ('325414', "Other biological product manufacturing"),
    ('3255', "Paint, coating, and adhesive manufacturing"),
    ('32551', "Paint and coating manufacturing"),
    ('325510', "Paint and coating manufacturing"),
    ('32552', "Adhesive manufacturing"),
    ('325520', "Adhesive manufacturing"),
    ('3256', "Soap, cleaning compound, and toiletry mfg."),
    ('32561', "Soap and cleaning compound manufacturing"),
    ('325611', "Soap and other detergent manufacturing"),
    ('325612', "Polish and other sanitation good mfg."),
    ('325613', "Surface active agent manufacturing"),
    ('32562', "Toilet preparation manufacturing"),
    ('325620', "Toilet preparation manufacturing"),
    ('3259', "Other chemical product and preparation mfg."),
    ('32591', "Printing ink manufacturing"),
    ('325910', "Printing ink manufacturing"),
    ('32592', "Explosives manufacturing"),
    ('325920', "Explosives manufacturing"),
    ('32599', "All other chemical preparation manufacturing"),
    ('325991', "Custom compounding of purchased resins"),
    ('325992', "Photographic film and chemical manufacturing"),
    ('325998', "Other miscellaneous chemical product mfg."),
    ('326', "Plastics and rubber products manufacturing"),
    ('3261', "Plastics product manufacturing"),
    ('32611', "Plastics packaging materials, film and sheet"),
    ('326111', "Plastics bag and pouch manufacturing"),
    ('326112', "Plastics packaging film and sheet mfg."),
    ('326113', "Nonpackaging plastics film and sheet mfg."),
    ('32612', "Plastics pipe, fittings, and profile shapes"),
    ('326121', "Unlaminated plastics profile shape mfg."),
    ('326122', "Plastics pipe and pipe fitting manufacturing"),
    ('32613', "Laminated plastics plate, sheet, and shapes"),
    ('326130', "Laminated plastics plate, sheet, and shapes"),
    ('32614', "Polystyrene foam product manufacturing"),
    ('326140', "Polystyrene foam product manufacturing"),
    ('32615', "Urethane and other foam product manufacturing"),
    ('326150', "Urethane and other foam product manufacturing"),
    ('32616', "Plastics bottle manufacturing"),
    ('326160', "Plastics bottle manufacturing"),
    ('32619', "Other plastics product manufacturing"),
    ('326191', "Plastics plumbing fixture manufacturing"),
    ('326192', "Resilient floor covering manufacturing"),
    ('326199', "All other plastics product manufacturing"),
    ('3262', "Rubber product manufacturing"),
    ('32621', "Tire manufacturing"),
    ('326211', "Tire manufacturing, except retreading"),
    ('326212', "Tire retreading"),
    ('32622', "Rubber and plastics hose and belting mfg."),
    ('326220', "Rubber and plastics hose and belting mfg."),
    ('32629', "Other rubber product manufacturing"),
    ('326291', "Rubber product mfg. for mechanical use"),
    ('326299', "All other rubber product manufacturing"),
    ('327', "Nonmetallic mineral product manufacturing"),
    ('3271', "Clay product and refractory manufacturing"),
    ('32711', "Pottery, ceramics, and plumbing fixture mfg."),
    ('327110', "Pottery, ceramics, and plumbing fixture mfg."),
    ('327111', "Vitreous china plumbing fixture manufacturing"),
    ('327112', "Vitreous china and earthenware articles mfg."),
    ('327113', "Porcelain electrical supply manufacturing"),
    ('32712', "Clay building material and refractories mfg."),
    ('327120', "Clay building material and refractories mfg."),
    ('327121', "Brick and structural clay tile manufacturing"),
    ('327122', "Ceramic wall and floor tile manufacturing"),
    ('327123', "Other structural clay product manufacturing"),
    ('327124', "Clay refractory manufacturing"),
    ('327125', "Nonclay refractory manufacturing"),
    ('3272', "Glass and glass product manufacturing"),
    ('32721', "Glass and glass product manufacturing"),
    ('327211', "Flat glass manufacturing"),
    ('327212', "Other pressed and blown glass and glassware"),
    ('327213', "Glass container manufacturing"),
    ('327215', "Glass product mfg. made of purchased glass"),
    ('3273', "Cement and concrete product manufacturing"),
    ('32731', "Cement manufacturing"),
    ('327310', "Cement manufacturing"),
    ('32732', "Ready-mix concrete manufacturing"),
    ('327320', "Ready-mix concrete manufacturing"),
    ('32733', "Concrete pipe, brick, and block manufacturing"),
    ('327331', "Concrete block and brick manufacturing"),
    ('327332', "Concrete pipe manufacturing"),
    ('32739', "Other concrete product manufacturing"),
    ('327390', "Other concrete product manufacturing"),
    ('3274', "Lime and gypsum product manufacturing"),
    ('32741', "Lime manufacturing"),
    ('327410', "Lime manufacturing"),
    ('32742', "Gypsum product manufacturing"),
    ('327420', "Gypsum product manufacturing"),
    ('3279', "Other nonmetallic mineral products"),
    ('32791', "Abrasive product manufacturing"),
    ('327910', "Abrasive product manufacturing"),
    ('32799', "All other nonmetallic mineral products mfg."),
    ('327991', "Cut stone and stone product manufacturing"),
    ('327992', "Ground or treated minerals and earths mfg."),
    ('327993', "Mineral wool manufacturing"),
    ('327999', "Miscellaneous nonmetallic mineral products"),
    ('331', "Primary metal manufacturing"),
    ('3311', "Iron and steel mills and ferroalloy mfg."),
    ('33111', "Iron and steel mills and ferroalloy mfg."),
    ('331110', "Iron and steel mills and ferroalloy mfg."),
    ('331111', "Iron and steel mills"),
    ('331112', "Ferroalloy and related product manufacturing"),
    ('3312', "Steel product mfg. from purchased steel"),
    ('33121', "Iron, steel pipe and tube from purchase steel"),
    ('331210', "Iron, steel pipe and tube from purchase steel"),
    ('33122', "Rolling and drawing of purchased steel"),
    ('331221', "Rolled steel shape manufacturing"),
    ('331222', "Steel wire drawing"),
    ('3313', "Alumina and aluminum production"),
    ('33131', "Alumina and aluminum production"),
    ('331311', "Alumina refining"),
    ('331312', "Primary aluminum production"),
    ('331313', "Primary production of alumina and aluminum"),
    ('331314', "Secondary smelting and alloying of aluminum"),
    ('331315', "Aluminum sheet, plate, and foil manufacturing"),
    ('331316', "Aluminum extruded product manufacturing"),
    ('331318', "Other al rolling, drawing, and extruding"),
    ('331319', "Other aluminum rolling and drawing"),
    ('3314', "Other nonferrous metal production"),
    ('33141', "Other nonferrous metal production"),
    ('331410', "Nonferrous (exc. al) smelting and refining"),
    ('331411', "Primary smelting and refining of copper"),
    ('331419', "Primary nonferrous metal, except cu and al"),
    ('33142', "Rolled, drawn, extruded, and alloyed copper"),
    ('331420', "Cu rolling, drawing, extruding, and alloying"),
    ('331421', "Copper rolling, drawing, and extruding"),
    ('331422', "Copper wire, except mechanical, drawing"),
    ('331423', "Secondary processing of copper"),
    ('33149', "Nonferrous metal, except cu and al, shaping"),
    ('331491', "Nonferrous metal, except cu and al, shaping"),
    ('331492', "Secondary processing of other nonferrous"),
    ('3315', "Foundries"),
    ('33151', "Ferrous metal foundries"),
    ('331511', "Iron foundries"),
    ('331512', "Steel investment foundries"),
    ('331513', "Steel foundries, except investment"),
    ('33152', "Nonferrous metal foundries"),
    ('331521', "Aluminum die-casting foundries"),
    ('331522', "Nonferrous, except al, die-casting foundries"),
    ('331523', "Nonferrous metal die-casting foundries"),
    ('331524', "Aluminum foundries, except die-casting"),
    ('331525', "Copper foundries, except die-casting"),
    ('331528', "Other nonferrous foundries, exc. die-casting"),
    ('331529', "Other nonferrous foundries, exc. die-casting"),
    ('332', "Fabricated metal product manufacturing"),
    ('3321', "Forging and stamping"),
    ('33211', "Forging and stamping"),
    ('332111', "Iron and steel forging"),
    ('332112', "Nonferrous forging"),
    ('332114', "Custom roll forming"),
    ('332115', "Crown and closure manufacturing"),
    ('332116', "Metal stamping"),
    ('332117', "Powder metallurgy part manufacturing"),
    ('332119', "Metal crown and other stamping, exc. auto"),
    ('3322', "Cutlery and handtool manufacturing"),
    ('33221', "Cutlery and handtool manufacturing"),
    ('332211', "Cutlery and flatware, except precious, mfg."),
    ('332212', "Hand and edge tool manufacturing"),
    ('332213', "Saw blade and handsaw manufacturing"),
    ('332214', "Kitchen utensil, pot, and pan manufacturing"),
    ('332215', "Cutlery, flatware and kitchen utensil mfg."),
    ('332216', "Saw blade and handtool manufacturing"),
    ('3323', "Architectural and structural metals mfg."),
    ('33231', "Plate work and fabricated structural products"),
    ('332311', "Prefabricated metal buildings and components"),
    ('332312', "Fabricated structural metal manufacturing"),
    ('332313', "Plate work manufacturing"),
    ('33232', "Ornamental and architectural metal products"),
    ('332321', "Metal window and door manufacturing"),
    ('332322', "Sheet metal work manufacturing"),
    ('332323', "Ornamental and architectural metal work mfg."),
    ('3324', "Boiler, tank, and shipping container mfg."),
    ('33241', "Power boiler and heat exchanger manufacturing"),
    ('332410', "Power boiler and heat exchanger manufacturing"),
    ('33242', "Metal tank, heavy gauge, manufacturing"),
    ('332420', "Metal tank, heavy gauge, manufacturing"),
    ('33243', "Metal can, box, and other container mfg."),
    ('332431', "Metal can manufacturing"),
    ('332439', "Other metal container manufacturing"),
    ('3325', "Hardware manufacturing"),
    ('33251', "Hardware manufacturing"),
    ('332510', "Hardware manufacturing"),
    ('3326', "Spring and wire product manufacturing"),
    ('33261', "Spring and wire product manufacturing"),
    ('332611', "Spring, heavy gauge, manufacturing"),
    ('332612', "Spring, light gauge, manufacturing"),
    ('332613', "Spring manufacturing"),
    ('332618', "Other fabricated wire product manufacturing"),
    ('3327', "Machine shops and threaded product mfg."),
    ('33271', "Machine shops"),
    ('332710', "Machine shops"),
    ('33272', "Turned product and screw, nut, and bolt mfg."),
    ('332721', "Precision turned product manufacturing"),
    ('332722', "Bolt, nut, screw, rivet, and washer mfg."),
    ('3328', "Coating, engraving, and heat treating metals"),
    ('33281', "Coating, engraving, and heat treating metals"),
    ('332811', "Metal heat treating"),
    ('332812', "Metal coating and nonprecious engraving"),
    ('332813', "Electroplating, anodizing, and coloring metal"),
    ('3329', "Other fabricated metal product manufacturing"),
    ('33291', "Metal valve manufacturing"),
    ('332911', "Industrial valve manufacturing"),
    ('332912', "Fluid power valve and hose fitting mfg."),
    ('332913', "Plumbing fixture fitting and trim mfg."),
    ('332919', "Other metal valve and pipe fitting mfg."),
    ('33299', "All other fabricated metal product mfg."),
    ('332991', "Ball and roller bearing manufacturing"),
    ('332992', "Small arms ammunition manufacturing"),
    ('332993', "Ammunition, except small arms, manufacturing"),
    ('332994', "Small arms, ordnance, and accessories mfg."),
    ('332995', "Other ordnance and accessories manufacturing"),
    ('332996', "Fabricated pipe and pipe fitting mfg."),
    ('332997', "Industrial pattern manufacturing"),
    ('332998', "Enameled iron and metal sanitary ware mfg."),
    ('332999', "Miscellaneous fabricated metal product mfg."),
    ('333', "Machinery manufacturing"),
    ('3331', "Ag., construction, and mining machinery mfg."),
    ('33311', "Agricultural implement manufacturing"),
    ('333111', "Farm machinery and equipment manufacturing"),
    ('333112', "Lawn and garden equipment manufacturing"),
    ('33312', "Construction machinery manufacturing"),
    ('333120', "Construction machinery manufacturing"),
    ('33313', "Mining and oil and gas field machinery mfg."),
    ('333131', "Mining machinery and equipment manufacturing"),
    ('333132', "Oil and gas field machinery and equipment"),
    ('3332', "Industrial machinery manufacturing"),
    ('33321', "Sawmill and woodworking machinery"),
    ('333210', "Sawmill and woodworking machinery"),
    ('33322', "Plastics and rubber industry machinery"),
    ('333220', "Plastics and rubber industry machinery"),
    ('33324', "Industrial machinery manufacturing"),
    ('333241', "Food product machinery manufacturing"),
    ('333242', "Semiconductor machinery manufacturing"),
    ('333243', "Sawmill, woodworking, and paper machinery mfg"),
    ('333244', "Printing machinery and equipment mfg."),
    ('333249', "Other industrial machinery manufacturing"),
    ('33329', "Other industrial machinery manufacturing"),
    ('333291', "Paper industry machinery manufacturing"),
    ('333292', "Textile machinery manufacturing"),
    ('333293', "Printing machinery and equipment mfg."),
    ('333294', "Food product machinery manufacturing"),
    ('333295', "Semiconductor machinery manufacturing"),
    ('333298', "All other industrial machinery manufacturing"),
    ('3333', "Commercial and service industry machinery"),
    ('33331', "Commercial and service industry machinery"),
    ('333311', "Automatic vending machine manufacturing"),
    ('333312', "Commercial laundry and drycleaning machinery"),
    ('333313', "Office machinery manufacturing"),
    ('333314', "Optical instrument and lens manufacturing"),
    ('333315', "Photographic and photocopying equipment mfg."),
    ('333316', "Photographic and photocopying equipment mfg."),
    ('333318', "Other industry machinery manufacturing"),
    ('333319', "Other commercial and service machinery mfg."),
    ('3334', "Hvac and commercial refrigeration equipment"),
    ('33341', "Hvac and commercial refrigeration equipment"),
    ('333411', "Air purification equipment manufacturing"),
    ('333412', "Industrial and commercial fan and blower mfg."),
    ('333413', "Air purification, fan and blower equip. mfg."),
    ('333414', "Heating equipment, except warm air furnaces"),
    ('333415', "Ac, refrigeration, and forced air heating"),
    ('3335', "Metalworking machinery manufacturing"),
    ('33351', "Metalworking machinery manufacturing"),
    ('333511', "Industrial mold manufacturing"),
    ('333512', "Metal cutting machine tool manufacturing"),
    ('333513', "Metal forming machine tool manufacturing"),
    ('333514', "Special tool, die, jig, and fixture mfg."),
    ('333515', "Cutting tool and machine tool accessory mfg."),
    ('333516', "Rolling mill machinery and equipment mfg."),
    ('333517', "Machine tool manufacturing"),
    ('333518', "Other metalworking machinery manufacturing"),
    ('333519', "Rolling mill and other machinery mfg."),
    ('3336', "Turbine and power transmission equipment mfg."),
    ('33361', "Turbine and power transmission equipment mfg."),
    ('333611', "Turbine and turbine generator set units mfg."),
    ('333612', "Speed changer, drive, and gear manufacturing"),
    ('333613', "Mechanical power transmission equipment mfg."),
    ('333618', "Other engine equipment manufacturing"),
    ('3339', "Other general purpose machinery manufacturing"),
    ('33391', "Pump and compressor manufacturing"),
    ('333911', "Pump and pumping equipment manufacturing"),
    ('333912', "Air and gas compressor manufacturing"),
    ('333913', "Measuring and dispensing pump manufacturing"),
    ('33392', "Material handling equipment manufacturing"),
    ('333921', "Elevator and moving stairway manufacturing"),
    ('333922', "Conveyor and conveying equipment mfg."),
    ('333923', "Overhead cranes, hoists, and monorail systems"),
    ('333924', "Industrial truck, trailer, and stacker mfg."),
    ('33399', "All other general purpose machinery mfg."),
    ('333991', "Power-driven handtool manufacturing"),
    ('333992', "Welding and soldering equipment manufacturing"),
    ('333993', "Packaging machinery manufacturing"),
    ('333994', "Industrial process furnace and oven mfg."),
    ('333995', "Fluid power cylinder and actuator mfg."),
    ('333996', "Fluid power pump and motor manufacturing"),
    ('333997', "Scale and balance manufacturing"),
    ('333999', "Miscellaneous general purpose machinery mfg."),
    ('334', "Computer and electronic product manufacturing"),
    ('3341', "Computer and peripheral equipment mfg."),
    ('33411', "Computer and peripheral equipment mfg."),
    ('334111', "Electronic computer manufacturing"),
    ('334112', "Computer storage device manufacturing"),
    ('334113', "Computer terminal manufacturing"),
    ('334118', "Computer terminal and peripheral equip. mfg."),
    ('334119', "Other computer peripheral equipment mfg."),
    ('3342', "Communications equipment manufacturing"),
    ('33421', "Telephone apparatus manufacturing"),
    ('334210', "Telephone apparatus manufacturing"),
    ('33422', "Broadcast and wireless communications equip."),
    ('334220', "Broadcast and wireless communications equip."),
    ('33429', "Other communications equipment manufacturing"),
    ('334290', "Other communications equipment manufacturing"),
    ('3343', "Audio and video equipment manufacturing"),
    ('33431', "Audio and video equipment manufacturing"),
    ('334310', "Audio and video equipment manufacturing"),
    ('3344', "Semiconductor and electronic component mfg."),
    ('33441', "Semiconductor and electronic component mfg."),
    ('334411', "Electron tube manufacturing"),
    ('334412', "Bare printed circuit board manufacturing"),
    ('334413', "Semiconductors and related device mfg."),
    ('334414', "Electronic capacitor manufacturing"),
    ('334415', "Electronic resistor manufacturing"),
    ('334416', "Capacitor, transformer, and inductor mfg."),
    ('334417', "Electronic connector manufacturing"),
    ('334418', "Printed circuit assembly manufacturing"),
    ('334419', "Other electronic component manufacturing"),
    ('3345', "Electronic instrument manufacturing"),
    ('33451', "Electronic instrument manufacturing"),
    ('334510', "Electromedical apparatus manufacturing"),
    ('334511', "Search, detection, and navigation instruments"),
    ('334512', "Automatic environmental control manufacturing"),
    ('334513', "Industrial process variable instruments"),
    ('334514', "Totalizing fluid meters and counting devices"),
    ('334515', "Electricity and signal testing instruments"),
    ('334516', "Analytical laboratory instrument mfg."),
    ('334517', "Irradiation apparatus manufacturing"),
    ('334518', "Watch, clock, and part manufacturing"),
    ('334519', "Other measuring and controlling device mfg."),
    ('3346', "Magnetic media manufacturing and reproducing"),
    ('33461', "Magnetic media manufacturing and reproducing"),
    ('334611', "Software reproducing"),
    ('334612', "Audio and video media reproduction"),
    ('334613', "Magnetic and optical recording media mfg."),
    ('334614', "Software and other prerecorded reproducing"),
    ('335', "Electrical equipment and appliance mfg."),
    ('3351', "Electric lighting equipment manufacturing"),
    ('33511', "Electric lamp bulb and part manufacturing"),
    ('335110', "Electric lamp bulb and part manufacturing"),
    ('33512', "Lighting fixture manufacturing"),
    ('335121', "Residential electric lighting fixture mfg."),
    ('335122', "Nonresidential electric lighting fixture mfg."),
    ('335129', "Other lighting equipment manufacturing"),
    ('3352', "Household appliance manufacturing"),
    ('33521', "Small electrical appliance manufacturing"),
    ('335210', "Small electrical appliance manufacturing"),
    ('335211', "Electric housewares and household fan mfg."),
    ('335212', "Household vacuum cleaner manufacturing"),
    ('33522', "Major appliance manufacturing"),
    ('335221', "Household cooking appliance manufacturing"),
    ('335222', "Household refrigerator and home freezer mfg."),
    ('335224', "Household laundry equipment manufacturing"),
    ('335228', "Other major household appliance manufacturing"),
    ('3353', "Electrical equipment manufacturing"),
    ('33531', "Electrical equipment manufacturing"),
    ('335311', "Electric power and specialty transformer mfg."),
    ('335312', "Motor and generator manufacturing"),
    ('335313', "Switchgear and switchboard apparatus mfg."),
    ('335314', "Relay and industrial control manufacturing"),
    ('3359', "Other electrical equipment and component mfg."),
    ('33591', "Battery manufacturing"),
    ('335911', "Storage battery manufacturing"),
    ('335912', "Primary battery manufacturing"),
    ('33592', "Communication and energy wire and cable mfg."),
    ('335921', "Fiber optic cable manufacturing"),
    ('335929', "Other communication and energy wire mfg."),
    ('33593', "Wiring device manufacturing"),
    ('335931', "Current-carrying wiring device manufacturing"),
    ('335932', "Noncurrent-carrying wiring device mfg."),
    ('33599', "Other electrical equipment and component mfg."),
    ('335991', "Carbon and graphite product manufacturing"),
    ('335999', "Miscellaneous electrical equipment mfg."),
    ('336', "Transportation equipment manufacturing"),
    ('3361', "Motor vehicle manufacturing"),
    ('33611', "Automobile and light truck manufacturing"),
    ('336111', "Automobile manufacturing"),
    ('336112', "Light truck and utility vehicle manufacturing"),
    ('33612', "Heavy duty truck manufacturing"),
    ('336120', "Heavy duty truck manufacturing"),
    ('3362', "Motor vehicle body and trailer manufacturing"),
    ('33621', "Motor vehicle body and trailer manufacturing"),
    ('336211', "Motor vehicle body manufacturing"),
    ('336212', "Truck trailer manufacturing"),
    ('336213', "Motor home manufacturing"),
    ('336214', "Travel trailer and camper manufacturing"),
    ('3363', "Motor vehicle parts manufacturing"),
    ('33631', "Motor vehicle gasoline engine and parts mfg."),
    ('336310', "Motor vehicle gasoline engine and parts mfg."),
    ('336311', "Carburetor, piston, ring, and valve mfg."),
    ('336312', "Gasoline engine and engine parts mfg."),
    ('33632', "Motor vehicle electric equipment"),
    ('336320', "Motor vehicle electrical and equipment mfg."),
    ('336321', "Vehicular lighting equipment manufacturing"),
    ('336322', "Other motor vehicle electric equipment mfg."),
    ('33633', "Motor vehicle steering and suspension parts"),
    ('336330', "Motor vehicle steering and suspension parts"),
    ('33634', "Motor vehicle brake system manufacturing"),
    ('336340', "Motor vehicle brake system manufacturing"),
    ('33635', "Motor vehicle power train components mfg."),
    ('336350', "Motor vehicle power train components mfg."),
    ('33636', "Motor vehicle seating and interior trim mfg."),
    ('336360', "Motor vehicle seating and interior trim mfg."),
    ('33637', "Motor vehicle metal stamping"),
    ('336370', "Motor vehicle metal stamping"),
    ('33639', "Other motor vehicle parts manufacturing"),
    ('336390', "Other motor vehicle parts manufacturing"),
    ('336391', "Motor vehicle air-conditioning manufacturing"),
    ('336399', "All other motor vehicle parts manufacturing"),
    ('3364', "Aerospace product and parts manufacturing"),
    ('33641', "Aerospace product and parts manufacturing"),
    ('336411', "Aircraft manufacturing"),
    ('336412', "Aircraft engine and engine parts mfg."),
    ('336413', "Other aircraft parts and equipment"),
    ('336414', "Guided missile and space vehicle mfg."),
    ('336415', "Space vehicle propulsion units and parts mfg."),
    ('336419', "Other guided missile and space vehicle parts"),
    ('3365', "Railroad rolling stock manufacturing"),
    ('33651', "Railroad rolling stock manufacturing"),
    ('336510', "Railroad rolling stock manufacturing"),
    ('3366', "Ship and boat building"),
    ('33661', "Ship and boat building"),
    ('336611', "Ship building and repairing"),
    ('336612', "Boat building"),
    ('3369', "Other transportation equipment manufacturing"),
    ('33699', "Other transportation equipment manufacturing"),
    ('336991', "Motorcycle, bicycle, and parts manufacturing"),
    ('336992', "Military armored vehicles and tank parts mfg."),
    ('336999', "All other transportation equipment mfg."),
    ('337', "Furniture and related product manufacturing"),
    ('3371', "Household and institutional furniture mfg."),
    ('33711', "Wood kitchen cabinet and countertop mfg."),
    ('337110', "Wood kitchen cabinet and countertop mfg."),
    ('33712', "Other household and institutional furniture"),
    ('337121', "Upholstered household furniture manufacturing"),
    ('337122', "Nonupholstered wood household furniture mfg."),
    ('337124', "Metal household furniture manufacturing"),
    ('337125', "Household furniture, exc. wood or metal, mfg."),
    ('337127', "Institutional furniture manufacturing"),
    ('337129', "Wood tv, radio, and sewing machine housings"),
    ('3372', "Office furniture and fixtures manufacturing"),
    ('33721', "Office furniture and fixtures manufacturing"),
    ('337211', "Wood office furniture manufacturing"),
    ('337212', "Custom architectural woodwork and millwork"),
    ('337214', "Office furniture, except wood, manufacturing"),
    ('337215', "Showcases, partitions, shelving, and lockers"),
    ('3379', "Other furniture related product manufacturing"),
    ('33791', "Mattress manufacturing"),
    ('337910', "Mattress manufacturing"),
    ('33792', "Blind and shade manufacturing"),
    ('337920', "Blind and shade manufacturing"),
    ('339', "Miscellaneous manufacturing"),
    ('3391', "Medical equipment and supplies manufacturing"),
    ('33911', "Medical equipment and supplies manufacturing"),
    ('339111', "Laboratory apparatus and furniture mfg."),
    ('339112', "Surgical and medical instrument manufacturing"),
    ('339113', "Surgical appliance and supplies manufacturing"),
    ('339114', "Dental equipment and supplies manufacturing"),
    ('339115', "Ophthalmic goods manufacturing"),
    ('339116', "Dental laboratories"),
    ('3399', "Other miscellaneous manufacturing"),
    ('33991', "Jewelry and silverware manufacturing"),
    ('339910', "Jewelry and silverware manufacturing"),
    ('339911', "Jewelry, except costume, manufacturing"),
    ('339912', "Silverware and hollowware manufacturing"),
    ('339913', "Jewelers' material and lapidary work mfg."),
    ('339914', "Costume jewelry and novelty manufacturing"),
    ('33992', "Sporting and athletic goods manufacturing"),
    ('339920', "Sporting and athletic goods manufacturing"),
    ('33993', "Doll, toy, and game manufacturing"),
    ('339930', "Doll, toy, and game manufacturing"),
    ('339931', "Doll and stuffed toy manufacturing"),
    ('339932', "Game, toy, and children's vehicle mfg."),
    ('33994', "Office supplies, except paper, manufacturing"),
    ('339940', "Office supplies (except paper) manufacturing"),
    ('339941', "Pen and mechanical pencil manufacturing"),
    ('339942', "Lead pencil and art good manufacturing"),
    ('339943', "Marking device manufacturing"),
    ('339944', "Carbon paper and inked ribbon manufacturing"),
    ('33995', "Sign manufacturing"),
    ('339950', "Sign manufacturing"),
    ('33999', "All other miscellaneous manufacturing"),
    ('339991', "Gasket, packing, and sealing device mfg."),
    ('339992', "Musical instrument manufacturing"),
    ('339993', "Fastener, button, needle, and pin mfg."),
    ('339994', "Broom, brush, and mop manufacturing"),
    ('339995', "Burial casket manufacturing"),
    ('339999', "All other miscellaneous manufacturing"),
    ('22', "Utilities"),
    ('221', "Utilities"),
    ('2211', "Power generation and supply"),
    ('22111', "Electric power generation"),
    ('221111', "Hydroelectric power generation"),
    ('221112', "Fossil fuel electric power generation"),
    ('221113', "Nuclear electric power generation"),
    ('221114', "Solar electric power generation"),
    ('221115', "Wind electric power generation"),
    ('221116', "Geothermal electric power generation"),
    ('221117', "Biomass electric power generation"),
    ('221118', "Other electric power generation"),
    ('221119', "Other electric power generation"),
    ('22112', "Electric power transmission and distribution"),
    ('221121', "Electric bulk power transmission and control"),
    ('221122', "Electric power distribution"),
    ('2212', "Natural gas distribution"),
    ('22121', "Natural gas distribution"),
    ('221210', "Natural gas distribution"),
    ('2213', "Water, sewage and other systems"),
    ('22131', "Water supply and irrigation systems"),
    ('221310', "Water supply and irrigation systems"),
    ('22132', "Sewage treatment facilities"),
    ('221320', "Sewage treatment facilities"),
    ('22133', "Steam and air-conditioning supply"),
    ('221330', "Steam and air-conditioning supply"),
    ('42', "Wholesale trade"),
    ('423', "Merchant wholesalers, durable goods"),
    ('4231', "Motor vehicle and parts merchant wholesalers"),
    ('42311', "Motor vehicle merchant wholesalers"),
    ('423110', "Motor vehicle merchant wholesalers"),
    ('42312', "New motor vehicle parts merchant wholesalers"),
    ('423120', "New motor vehicle parts merchant wholesalers"),
    ('42313', "Tire and tube merchant wholesalers"),
    ('423130', "Tire and tube merchant wholesalers"),
    ('42314', "Used motor vehicle parts merchant wholesalers"),
    ('423140', "Used motor vehicle parts merchant wholesalers"),
    ('4232', "Furniture and furnishing merchant wholesalers"),
    ('42321', "Furniture merchant wholesalers"),
    ('423210', "Furniture merchant wholesalers"),
    ('42322', "Home furnishing merchant wholesalers"),
    ('423220', "Home furnishing merchant wholesalers"),
    ('4233', "Lumber and const. supply merchant wholesalers"),
    ('42331', "Lumber and wood merchant wholesalers"),
    ('423310', "Lumber and wood merchant wholesalers"),
    ('42332', "Masonry material merchant wholesalers"),
    ('423320', "Masonry material merchant wholesalers"),
    ('42333', "Roofing and siding merchant wholesalers"),
    ('423330', "Roofing and siding merchant wholesalers"),
    ('42339', "Other const. material merchant wholesalers"),
    ('423390', "Other const. material merchant wholesalers"),
    ('4234', "Commercial equip. merchant wholesalers"),
    ('42341', "Photographic equip. merchant wholesalers"),
    ('423410', "Photographic equip. merchant wholesalers"),
    ('42342', "Office equipment merchant wholesalers"),
    ('423420', "Office equipment merchant wholesalers"),
    ('42343', "Computer and software merchant wholesalers"),
    ('423430', "Computer and software merchant wholesalers"),
    ('42344', "Other commercial equip. merchant wholesalers"),
    ('423440', "Other commercial equip. merchant wholesalers"),
    ('42345', "Medical equipment merchant wholesalers"),
    ('423450', "Medical equipment merchant wholesalers"),
    ('42346', "Ophthalmic goods merchant wholesalers"),
    ('423460', "Ophthalmic goods merchant wholesalers"),
    ('42349', "Other professional equip. merchant wholesaler"),
    ('423490', "Other professional equip. merchant wholesaler"),
    ('4235', "Metal and mineral merchant wholesalers"),
    ('42351', "Metal merchant wholesalers"),
    ('423510', "Metal merchant wholesalers"),
    ('42352', "Coal and other mineral merchant wholesalers"),
    ('423520', "Coal and other mineral merchant wholesalers"),
    ('4236', "Electric goods merchant wholesalers"),
    ('42361', "Elec. equip. and wiring merchant wholesalers"),
    ('423610', "Elec. equip. and wiring merchant wholesalers"),
    ('42362', "Electric appliance merchant wholesalers"),
    ('423620', "Appliances and electronics merch. whls."),
    ('42369', "Other electronic parts merchant wholesalers"),
    ('423690', "Other electronic parts merchant wholesalers"),
    ('4237', "Hardware and plumbing merchant wholesalers"),
    ('42371', "Hardware merchant wholesalers"),
    ('423710', "Hardware merchant wholesalers"),
    ('42372', "Plumbing equip. merchant wholesalers"),
    ('423720', "Plumbing and heating equip. merch. whls."),
    ('42373', "Hvac equip. merchant wholesalers"),
    ('423730', "Hvac equip. merchant wholesalers"),
    ('42374', "Refrigeration equip. merchant wholesalers"),
    ('423740', "Refrigeration equip. merchant wholesalers"),
    ('4238', "Machinery and supply merchant wholesalers"),
    ('42381', "Construction equipment merchant wholesalers"),
    ('423810', "Construction equipment merchant wholesalers"),
    ('42382', "Farm and garden equip. merchant wholesalers"),
    ('423820', "Farm and garden equip. merchant wholesalers"),
    ('42383', "Industrial machinery merchant wholesalers"),
    ('423830', "Industrial machinery merchant wholesalers"),
    ('42384', "Industrial supplies merchant wholesalers"),
    ('423840', "Industrial supplies merchant wholesalers"),
    ('42385', "Service estab. equip. merchant wholesalers"),
    ('423850', "Service estab. equip. merchant wholesalers"),
    ('42386', "Other transport. goods merchant wholesalers"),
    ('423860', "Other transport. goods merchant wholesalers"),
    ('4239', "Misc. durable goods merchant wholesalers"),
    ('42391', "Sporting goods merchant wholesalers"),
    ('423910', "Sporting goods merchant wholesalers"),
    ('42392', "Toy and hobby goods merchant wholesalers"),
    ('423920', "Toy and hobby goods merchant wholesalers"),
    ('42393', "Recyclable material merchant wholesalers"),
    ('423930', "Recyclable material merchant wholesalers"),
    ('42394', "Jewelry merchant wholesalers"),
    ('423940', "Jewelry merchant wholesalers"),
    ('42399', "All other durable goods merchant wholesalers"),
    ('423990', "All other durable goods merchant wholesalers"),
    ('424', "Merchant wholesalers, nondurable goods"),
    ('4241', "Paper and paper product merchant wholesalers"),
    ('42411', "Printing and writing paper merch. whls."),
    ('424110', "Printing and writing paper merch. whls."),
    ('42412', "Office supplies merchant wholesalers"),
    ('424120', "Office supplies merchant wholesalers"),
    ('42413', "Industrial paper merchant wholesalers"),
    ('424130', "Industrial paper merchant wholesalers"),
    ('4242', "Druggists' goods merchant wholesalers"),
    ('42421', "Druggists' goods merchant wholesalers"),
    ('424210', "Druggists' goods merchant wholesalers"),
    ('4243', "Apparel and piece goods merchant wholesalers"),
    ('42431', "Piece goods merchant wholesalers"),
    ('424310', "Piece goods merchant wholesalers"),
    ('42432', "Men's and boys' clothing merchant wholesalers"),
    ('424320', "Men's and boys' clothing merchant wholesalers"),
    ('42433', "Women's and children's clothing merch. whls."),
    ('424330', "Women's and children's clothing merch. whls."),
    ('42434', "Footwear merchant wholesalers"),
    ('424340', "Footwear merchant wholesalers"),
    ('4244', "Grocery and related product wholesalers"),
    ('42441', "General line grocery merchant wholesalers"),
    ('424410', "General line grocery merchant wholesalers"),
    ('42442', "Packaged frozen food merchant wholesalers"),
    ('424420', "Packaged frozen food merchant wholesalers"),
    ('42443', "Dairy product merchant wholesalers"),
    ('424430', "Dairy product merchant wholesalers"),
    ('42444', "Poultry product merchant wholesalers"),
    ('424440', "Poultry product merchant wholesalers"),
    ('42445', "Confectionery merchant wholesalers"),
    ('424450', "Confectionery merchant wholesalers"),
    ('42446', "Fish and seafood merchant wholesalers"),
    ('424460', "Fish and seafood merchant wholesalers"),
    ('42447', "Meat and meat product merchant wholesalers"),
    ('424470', "Meat and meat product merchant wholesalers"),
    ('42448', "Fruit and vegetable merchant wholesalers"),
    ('424480', "Fruit and vegetable merchant wholesalers"),
    ('42449', "Other grocery product merchant wholesalers"),
    ('424490', "Other grocery product merchant wholesalers"),
    ('4245', "Farm product raw material merch. whls."),
    ('42451', "Grain and field bean merchant wholesalers"),
    ('424510', "Grain and field bean merchant wholesalers"),
    ('42452', "Livestock merchant wholesalers"),
    ('424520', "Livestock merchant wholesalers"),
    ('42459', "Other farm product raw material merch. whls."),
    ('424590', "Other farm product raw material merch. whls."),
    ('4246', "Chemical merchant wholesalers"),
    ('42461', "Plastics materials merchant wholesalers"),
    ('424610', "Plastics materials merchant wholesalers"),
    ('42469', "Other chemicals merchant wholesalers"),
    ('424690', "Other chemicals merchant wholesalers"),
    ('4247', "Petroleum merchant wholesalers"),
    ('42471', "Petroleum bulk stations and terminals"),
    ('424710', "Petroleum bulk stations and terminals"),
    ('42472', "Other petroleum merchant wholesalers"),
    ('424720', "Other petroleum merchant wholesalers"),
    ('4248', "Alcoholic beverage merchant wholesalers"),
    ('42481', "Beer and ale merchant wholesalers"),
    ('424810', "Beer and ale merchant wholesalers"),
    ('42482', "Wine and spirit merchant wholesalers"),
    ('424820', "Wine and spirit merchant wholesalers"),
    ('4249', "Misc. nondurable goods merchant wholesalers"),
    ('42491', "Farm supplies merchant wholesalers"),
    ('424910', "Farm supplies merchant wholesalers"),
    ('42492', "Book and periodical merchant wholesalers"),
    ('424920', "Book and periodical merchant wholesalers"),
    ('42493', "Nursery and florist merchant wholesalers"),
    ('424930', "Nursery and florist merchant wholesalers"),
    ('42494', "Tobacco and tobacco product merch. whls."),
    ('424940', "Tobacco and tobacco product merch. whls."),
    ('42495', "Paint and supplies merchant wholesalers"),
    ('424950', "Paint and supplies merchant wholesalers"),
    ('42499', "Other nondurable goods merchant wholesalers"),
    ('424990', "Other nondurable goods merchant wholesalers"),
    ('425', "Electronic markets and agents and brokers"),
    ('4251', "Electronic markets and agents and brokers"),
    ('42511', "Business to business electronic markets"),
    ('425110', "Business to business electronic markets"),
    ('42512', "Wholesale trade agents and brokers"),
    ('425120', "Wholesale trade agents and brokers"),
    ('44-45', "Retail trade"),
    ('441', "Motor vehicle and parts dealers"),
    ('4411', "Automobile dealers"),
    ('44111', "New car dealers"),
    ('441110', "New car dealers"),
    ('44112', "Used car dealers"),
    ('441120', "Used car dealers"),
    ('4412', "Other motor vehicle dealers"),
    ('44121', "Recreational vehicle dealers"),
    ('441210', "Recreational vehicle dealers"),
    ('44122', "Motorcycle, boat, and other vehicle dealers"),
    ('441221', "Motorcycle, atv, personal watercraft dealers"),
    ('441222', "Boat dealers"),
    ('441228', "Motorcycle and other motor vehicle dealers"),
    ('441229', "All other motor vehicle dealers"),
    ('4413', "Auto parts, accessories, and tire stores"),
    ('44131', "Automotive parts and accessories stores"),
    ('441310', "Automotive parts and accessories stores"),
    ('44132', "Tire dealers"),
    ('441320', "Tire dealers"),
    ('442', "Furniture and home furnishings stores"),
    ('4421', "Furniture stores"),
    ('44211', "Furniture stores"),
    ('442110', "Furniture stores"),
    ('4422', "Home furnishings stores"),
    ('44221', "Floor covering stores"),
    ('442210', "Floor covering stores"),
    ('44229', "Other home furnishings stores"),
    ('442291', "Window treatment stores"),
    ('442299', "All other home furnishings stores"),
    ('443', "Electronics and appliance stores"),
    ('4431', "Electronics and appliance stores"),
    ('44311', "Appliance, tv, and other electronics stores"),
    ('443111', "Household appliance stores"),
    ('443112', "Radio, tv, and other electronics stores"),
    ('44312', "Computer and software stores"),
    ('443120', "Computer and software stores"),
    ('44313', "Camera and photographic supplies stores"),
    ('443130', "Camera and photographic supplies stores"),
    ('44314', "Electronics and appliances stores"),
    ('443141', "Household appliance stores"),
    ('443142', "Electronics stores"),
    ('444', "Building material and garden supply stores"),
    ('4441', "Building material and supplies dealers"),
    ('44411', "Home centers"),
    ('444110', "Home centers"),
    ('44412', "Paint and wallpaper stores"),
    ('444120', "Paint and wallpaper stores"),
    ('44413', "Hardware stores"),
    ('444130', "Hardware stores"),
    ('44419', "Other building material dealers"),
    ('444190', "Other building material dealers"),
    ('4442', "Lawn and garden equipment and supplies stores"),
    ('44421', "Outdoor power equipment stores"),
    ('444210', "Outdoor power equipment stores"),
    ('44422', "Nursery, garden, and farm supply stores"),
    ('444220', "Nursery, garden, and farm supply stores"),
    ('445', "Food and beverage stores"),
    ('4451', "Grocery stores"),
    ('44511', "Supermarkets and other grocery stores"),
    ('445110', "Supermarkets and other grocery stores"),
    ('44512', "Convenience stores"),
    ('445120', "Convenience stores"),
    ('4452', "Specialty food stores"),
    ('44521', "Meat markets"),
    ('445210', "Meat markets"),
    ('44522', "Fish and seafood markets"),
    ('445220', "Fish and seafood markets"),
    ('44523', "Fruit and vegetable markets"),
    ('445230', "Fruit and vegetable markets"),
    ('44529', "Other specialty food stores"),
    ('445291', "Baked goods stores"),
    ('445292', "Confectionery and nut stores"),
    ('445299', "All other specialty food stores"),
    ('4453', "Beer, wine, and liquor stores"),
    ('44531', "Beer, wine, and liquor stores"),
    ('445310', "Beer, wine, and liquor stores"),
    ('446', "Health and personal care stores"),
    ('4461', "Health and personal care stores"),
    ('44611', "Pharmacies and drug stores"),
    ('446110', "Pharmacies and drug stores"),
    ('44612', "Cosmetic and beauty supply stores"),
    ('446120', "Cosmetic and beauty supply stores"),
    ('44613', "Optical goods stores"),
    ('446130', "Optical goods stores"),
    ('44619', "Other health and personal care stores"),
    ('446191', "Food, health, supplement stores"),
    ('446199', "All other health and personal care stores"),
    ('447', "Gasoline stations"),
    ('4471', "Gasoline stations"),
    ('44711', "Gasoline stations with convenience stores"),
    ('447110', "Gasoline stations with convenience stores"),
    ('44719', "Other gasoline stations"),
    ('447190', "Other gasoline stations"),
    ('448', "Clothing and clothing accessories stores"),
    ('4481', "Clothing stores"),
    ('44811', "Men's clothing stores"),
    ('448110', "Men's clothing stores"),
    ('44812', "Women's clothing stores"),
    ('448120', "Women's clothing stores"),
    ('44813', "Children's and infants' clothing stores"),
    ('448130', "Children's and infants' clothing stores"),
    ('44814', "Family clothing stores"),
    ('448140', "Family clothing stores"),
    ('44815', "Clothing accessories stores"),
    ('448150', "Clothing accessories stores"),
    ('44819', "Other clothing stores"),
    ('448190', "Other clothing stores"),
    ('4482', "Shoe stores"),
    ('44821', "Shoe stores"),
    ('448210', "Shoe stores"),
    ('4483', "Jewelry, luggage, and leather goods stores"),
    ('44831', "Jewelry stores"),
    ('448310', "Jewelry stores"),
    ('44832', "Luggage and leather goods stores"),
    ('448320', "Luggage and leather goods stores"),
    ('451', "Sporting goods, hobby, book and music stores"),
    ('4511', "Sporting goods and musical instrument stores"),
    ('45111', "Sporting goods stores"),
    ('451110', "Sporting goods stores"),
    ('45112', "Hobby, toy, and game stores"),
    ('451120', "Hobby, toy, and game stores"),
    ('45113', "Sewing, needlework, and piece goods stores"),
    ('451130', "Sewing, needlework, and piece goods stores"),
    ('45114', "Musical instrument and supplies stores"),
    ('451140', "Musical instrument and supplies stores"),
    ('4512', "Book, periodical, and music stores"),
    ('45121', "Book stores and news dealers"),
    ('451211', "Book stores"),
    ('451212', "News dealers and newsstands"),
    ('45122', "Precorded tape, cd, and record stores"),
    ('451220', "Precorded tape, cd, and record stores"),
    ('452', "General merchandise stores"),
    ('4521', "Department stores"),
    ('45211', "Department stores"),
    ('452111', "Department stores, except discount"),
    ('452112', "Discount department stores"),
    ('4529', "Other general merchandise stores"),
    ('45291', "Warehouse clubs and supercenters"),
    ('452910', "Warehouse clubs and supercenters"),
    ('45299', "All other general merchandise stores"),
    ('452990', "All other general merchandise stores"),
    ('453', "Miscellaneous store retailers"),
    ('4531', "Florists"),
    ('45311', "Florists"),
    ('453110', "Florists"),
    ('4532', "Office supplies, stationery, and gift stores"),
    ('45321', "Office supplies and stationery stores"),
    ('453210', "Office supplies and stationery stores"),
    ('45322', "Gift, novelty, and souvenir stores"),
    ('453220', "Gift, novelty, and souvenir stores"),
    ('4533', "Used merchandise stores"),
    ('45331', "Used merchandise stores"),
    ('453310', "Used merchandise stores"),
    ('4539', "Other miscellaneous store retailers"),
    ('45391', "Pet and pet supplies stores"),
    ('453910', "Pet and pet supplies stores"),
    ('45392', "Art dealers"),
    ('453920', "Art dealers"),
    ('45393', "Manufactured, mobile, home dealers"),
    ('453930', "Manufactured, mobile, home dealers"),
    ('45399', "All other miscellaneous store retailers"),
    ('453991', "Tobacco stores"),
    ('453998', "Store retailers not specified elsewhere"),
    ('454', "Nonstore retailers"),
    ('4541', "Electronic shopping and mail-order houses"),
    ('45411', "Electronic shopping and mail-order houses"),
    ('454111', "Electronic shopping"),
    ('454112', "Electronic auctions"),
    ('454113', "Mail-order houses"),
    ('4542', "Vending machine operators"),
    ('45421', "Vending machine operators"),
    ('454210', "Vending machine operators"),
    ('4543', "Direct selling establishments"),
    ('45431', "Fuel dealers"),
    ('454310', "Fuel dealers"),
    ('454311', "Heating oil dealers"),
    ('454312', "Liquefied petroleum gas, bottled gas, dealers"),
    ('454319', "Other fuel dealers"),
    ('45439', "Other direct selling establishments"),
    ('454390', "Other direct selling establishments"),
    ('48-49', "Transportation and warehousing"),
    ('481', "Air transportation"),
    ('4811', "Scheduled air transportation"),
    ('48111', "Scheduled air transportation"),
    ('481111', "Scheduled passenger air transportation"),
    ('481112', "Scheduled freight air transportation"),
    ('4812', "Nonscheduled air transportation"),
    ('48121', "Nonscheduled air transportation"),
    ('481211', "Nonscheduled air passenger chartering"),
    ('481212', "Nonscheduled air freight chartering"),
    ('481219', "Other nonscheduled air transportation"),
    ('482', "Rail transportation"),
    ('4821', "Rail transportation"),
    ('48211', "Rail transportation"),
    ('482111', "Line-haul railroads"),
    ('482112', "Short line railroads"),
    ('483', "Water transportation"),
    ('4831', "Sea, coastal, and great lakes transportation"),
    ('48311', "Sea, coastal, and great lakes transportation"),
    ('483111', "Deep sea freight transportation"),
    ('483112', "Deep sea passenger transportation"),
    ('483113', "Coastal and great lakes freight transport."),
    ('483114', "Coastal and great lakes passenger transport."),
    ('4832', "Inland water transportation"),
    ('48321', "Inland water transportation"),
    ('483211', "Inland water freight transportation"),
    ('483212', "Inland water passenger transportation"),
    ('484', "Truck transportation"),
    ('4841', "General freight trucking"),
    ('48411', "General freight trucking, local"),
    ('484110', "General freight trucking, local"),
    ('48412', "General freight trucking, long-distance"),
    ('484121', "General freight trucking, long-distance tl"),
    ('484122', "General freight trucking, long-distance ltl"),
    ('4842', "Specialized freight trucking"),
    ('48421', "Used household and office goods moving"),
    ('484210', "Used household and office goods moving"),
    ('48422', "Other specialized trucking, local"),
    ('484220', "Other specialized trucking, local"),
    ('48423', "Other specialized trucking, long-distance"),
    ('484230', "Other specialized trucking, long-distance"),
    ('485', "Transit and ground passenger transportation"),
    ('4851', "Urban transit systems"),
    ('48511', "Urban transit systems"),
    ('485111', "Mixed mode transit systems"),
    ('485112', "Commuter rail systems"),
    ('485113', "Bus and other motor vehicle transit systems"),
    ('485119', "Other urban transit systems"),
    ('4852', "Interurban and rural bus transportation"),
    ('48521', "Interurban and rural bus transportation"),
    ('485210', "Interurban and rural bus transportation"),
    ('4853', "Taxi and limousine service"),
    ('48531', "Taxi service"),
    ('485310', "Taxi service"),
    ('48532', "Limousine service"),
    ('485320', "Limousine service"),
    ('4854', "School and employee bus transportation"),
    ('48541', "School and employee bus transportation"),
    ('485410', "School and employee bus transportation"),
    ('4855', "Charter bus industry"),
    ('48551', "Charter bus industry"),
    ('485510', "Charter bus industry"),
    ('4859', "Other ground passenger transportation"),
    ('48599', "Other ground passenger transportation"),
    ('485991', "Special needs transportation"),
    ('485999', "All other ground passenger transportation"),
    ('486', "Pipeline transportation"),
    ('4861', "Pipeline transportation of crude oil"),
    ('48611', "Pipeline transportation of crude oil"),
    ('486110', "Pipeline transportation of crude oil"),
    ('4862', "Pipeline transportation of natural gas"),
    ('48621', "Pipeline transportation of natural gas"),
    ('486210', "Pipeline transportation of natural gas"),
    ('4869', "Other pipeline transportation"),
    ('48691', "Refined petroleum product pipeline transport."),
    ('486910', "Refined petroleum product pipeline transport."),
    ('48699', "All other pipeline transportation"),
    ('486990', "All other pipeline transportation"),
    ('487', "Scenic and sightseeing transportation"),
    ('4871', "Scenic and sightseeing transportation, land"),
    ('48711', "Scenic and sightseeing transportation, land"),
    ('487110', "Scenic and sightseeing transportation, land"),
    ('4872', "Scenic and sightseeing transportation, water"),
    ('48721', "Scenic and sightseeing transportation, water"),
    ('487210', "Scenic and sightseeing transportation, water"),
    ('4879', "Scenic and sightseeing transportation, other"),
    ('48799', "Scenic and sightseeing transportation, other"),
    ('487990', "Scenic and sightseeing transportation, other"),
    ('488', "Support activities for transportation"),
    ('4881', "Support activities for air transportation"),
    ('48811', "Airport operations"),
    ('488111', "Air traffic control"),
    ('488119', "Other airport operations"),
    ('48819', "Other support activities for air transport."),
    ('488190', "Other support activities for air transport."),
    ('4882', "Support activities for rail transportation"),
    ('48821', "Support activities for rail transportation"),
    ('488210', "Support activities for rail transportation"),
    ('4883', "Support activities for water transportation"),
    ('48831', "Port and harbor operations"),
    ('488310', "Port and harbor operations"),
    ('48832', "Marine cargo handling"),
    ('488320', "Marine cargo handling"),
    ('48833', "Navigational services to shipping"),
    ('488330', "Navigational services to shipping"),
    ('48839', "Other support activities for water transport."),
    ('488390', "Other support activities for water transport."),
    ('4884', "Support activities for road transportation"),
    ('48841', "Motor vehicle towing"),
    ('488410', "Motor vehicle towing"),
    ('48849', "Other support activities for road transport."),
    ('488490', "Other support activities for road transport."),
    ('4885', "Freight transportation arrangement"),
    ('48851', "Freight transportation arrangement"),
    ('488510', "Freight transportation arrangement"),
    ('4889', "Other support activities for transportation"),
    ('48899', "Other support activities for transportation"),
    ('488991', "Packing and crating"),
    ('488999', "All other support activities for transport."),
    ('491', "Postal service"),
    ('4911', "Postal service"),
    ('49111', "Postal service"),
    ('491110', "Postal service"),
    ('492', "Couriers and messengers"),
    ('4921', "Couriers and express delivery services"),
    ('49211', "Couriers and express delivery services"),
    ('492110', "Couriers and express delivery services"),
    ('4922', "Local messengers and local delivery"),
    ('49221', "Local messengers and local delivery"),
    ('492210', "Local messengers and local delivery"),
    ('493', "Warehousing and storage"),
    ('4931', "Warehousing and storage"),
    ('49311', "General warehousing and storage"),
    ('493110', "General warehousing and storage"),
    ('49312', "Refrigerated warehousing and storage"),
    ('493120', "Refrigerated warehousing and storage"),
    ('49313', "Farm product warehousing and storage"),
    ('493130', "Farm product warehousing and storage"),
    ('49319', "Other warehousing and storage"),
    ('493190', "Other warehousing and storage"),
    ('51', "Information"),
    ('511', "Publishing industries, except internet"),
    ('5111', "Newspaper, book, and directory publishers"),
    ('51111', "Newspaper publishers"),
    ('511110', "Newspaper publishers"),
    ('51112', "Periodical publishers"),
    ('511120', "Periodical publishers"),
    ('51113', "Book publishers"),
    ('511130', "Book publishers"),
    ('51114', "Directory and mailing list publishers"),
    ('511140', "Directory and mailing list publishers"),
    ('51119', "Other publishers"),
    ('511191', "Greeting card publishers"),
    ('511199', "All other publishers"),
    ('5112', "Software publishers"),
    ('51121', "Software publishers"),
    ('511210', "Software publishers"),
    ('512', "Motion picture and sound recording industries"),
    ('5121', "Motion picture and video industries"),
    ('51211', "Motion picture and video production"),
    ('512110', "Motion picture and video production"),
    ('51212', "Motion picture and video distribution"),
    ('512120', "Motion picture and video distribution"),
    ('51213', "Motion picture and video exhibition"),
    ('512131', "Motion picture theaters, except drive-ins"),
    ('512132', "Drive-in motion picture theaters"),
    ('51219', "Postproduction and other related industries"),
    ('512191', "Teleproduction and postproduction services"),
    ('512199', "Other motion picture and video industries"),
    ('5122', "Sound recording industries"),
    ('51221', "Record production"),
    ('512210', "Record production"),
    ('51222', "Integrated record production and distribution"),
    ('512220', "Integrated record production and distribution"),
    ('51223', "Music publishers"),
    ('512230', "Music publishers"),
    ('51224', "Sound recording studios"),
    ('512240', "Sound recording studios"),
    ('51229', "Other sound recording industries"),
    ('512290', "Other sound recording industries"),
    ('515', "Broadcasting, except internet"),
    ('5151', "Radio and television broadcasting"),
    ('51511', "Radio broadcasting"),
    ('515111', "Radio networks"),
    ('515112', "Radio stations"),
    ('51512', "Television broadcasting"),
    ('515120', "Television broadcasting"),
    ('5152', "Cable and other subscription programming"),
    ('51521', "Cable and other subscription programming"),
    ('515210', "Cable and other subscription programming"),
    ('516', "Internet publishing and broadcasting"),
    ('5161', "Internet publishing and broadcasting"),
    ('51611', "Internet publishing and broadcasting"),
    ('516110', "Internet publishing and broadcasting"),
    ('517', "Telecommunications"),
    ('5171', "Wired telecommunications carriers"),
    ('51711', "Wired telecommunications carriers"),
    ('517110', "Wired telecommunications carriers"),
    ('5172', "Wireless telecommunications carriers"),
    ('51721', "Wireless telecommunications carriers"),
    ('517210', "Wireless telecommunications carriers"),
    ('517211', "Paging"),
    ('517212', "Cellular and other wireless carriers"),
    ('5173', "Telecommunications resellers"),
    ('51731', "Telecommunications resellers"),
    ('517310', "Telecommunications resellers"),
    ('5174', "Satellite telecommunications"),
    ('51741', "Satellite telecommunications"),
    ('517410', "Satellite telecommunications"),
    ('5175', "Cable and other program distribution"),
    ('51751', "Cable and other program distribution"),
    ('517510', "Cable and other program distribution"),
    ('5179', "Other telecommunications"),
    ('51791', "Other telecommunications"),
    ('517910', "Other telecommunications"),
    ('517911', "Telecommunications resellers"),
    ('517919', "All other telecommunications"),
    ('518', "Data processing, hosting and related services"),
    ('5181', "Isps and web search portals"),
    ('51811', "Isps and web search portals"),
    ('518111', "Internet service providers"),
    ('518112', "Web search portals"),
    ('5182', "Data processing, hosting and related services"),
    ('51821', "Data processing and related services"),
    ('518210', "Data processing, hosting and related services"),
    ('519', "Other information services"),
    ('5191', "Other information services"),
    ('51911', "News syndicates"),
    ('519110', "News syndicates"),
    ('51912', "Libraries and archives"),
    ('519120', "Libraries and archives"),
    ('51913', "Internet publishing and web search portals"),
    ('519130', "Internet publishing and web search portals"),
    ('51919', "All other information services"),
    ('519190', "All other information services"),
    ('52', "Finance and insurance"),
    ('521', "Monetary authorities - central bank"),
    ('5211', "Monetary authorities - central bank"),
    ('52111', "Monetary authorities - central bank"),
    ('521110', "Monetary authorities - central bank"),
    ('522', "Credit intermediation and related activities"),
    ('5221', "Depository credit intermediation"),
    ('52211', "Commercial banking"),
    ('522110', "Commercial banking"),
    ('52212', "Savings institutions"),
    ('522120', "Savings institutions"),
    ('52213', "Credit unions"),
    ('522130', "Credit unions"),
    ('52219', "Other depository credit intermediation"),
    ('522190', "Other depository credit intermediation"),
    ('5222', "Nondepository credit intermediation"),
    ('52221', "Credit card issuing"),
    ('522210', "Credit card issuing"),
    ('52222', "Sales financing"),
    ('522220', "Sales financing"),
    ('52229', "Other nondepository credit intermediation"),
    ('522291', "Consumer lending"),
    ('522292', "Real estate credit"),
    ('522293', "International trade financing"),
    ('522294', "Secondary market financing"),
    ('522298', "All other nondepository credit intermediation"),
    ('5223', "Activities related to credit intermediation"),
    ('52231', "Mortgage and nonmortgage loan brokers"),
    ('522310', "Mortgage and nonmortgage loan brokers"),
    ('52232', "Financial transaction processing and clearing"),
    ('522320', "Financial transaction processing and clearing"),
    ('52239', "Other credit intermediation activities"),
    ('522390', "Other credit intermediation activities"),
    ('523', "Securities, commodity contracts, investments"),
    ('5231', "Securities and commodity contracts brokerage"),
    ('52311', "Investment banking and securities dealing"),
    ('523110', "Investment banking and securities dealing"),
    ('52312', "Securities brokerage"),
    ('523120', "Securities brokerage"),
    ('52313', "Commodity contracts dealing"),
    ('523130', "Commodity contracts dealing"),
    ('52314', "Commodity contracts brokerage"),
    ('523140', "Commodity contracts brokerage"),
    ('5232', "Securities and commodity exchanges"),
    ('52321', "Securities and commodity exchanges"),
    ('523210', "Securities and commodity exchanges"),
    ('5239', "Other financial investment activities"),
    ('52391', "Miscellaneous intermediation"),
    ('523910', "Miscellaneous intermediation"),
    ('52392', "Portfolio management"),
    ('523920', "Portfolio management"),
    ('52393', "Investment advice"),
    ('523930', "Investment advice"),
    ('52399', "All other financial investment activities"),
    ('523991', "Trust, fiduciary, and custody activities"),
    ('523999', "Miscellaneous financial investment activities"),
    ('524', "Insurance carriers and related activities"),
    ('5241', "Insurance carriers"),
    ('52411', "Direct life and health insurance carriers"),
    ('524113', "Direct life insurance carriers"),
    ('524114', "Direct health and medical insurance carriers"),
    ('52412', "Direct insurers, except life and health"),
    ('524126', "Direct property and casualty insurers"),
    ('524127', "Direct title insurance carriers"),
    ('524128', "Other direct insurance carriers"),
    ('52413', "Reinsurance carriers"),
    ('524130', "Reinsurance carriers"),
    ('5242', "Insurance agencies and brokerages"),
    ('52421', "Insurance agencies and brokerages"),
    ('524210', "Insurance agencies and brokerages"),
    ('52429', "Other insurance related activities"),
    ('524291', "Claims adjusting"),
    ('524292', "Third party administration of insurance funds"),
    ('524298', "All other insurance related activities"),
    ('525', "Funds, trusts, and other financial vehicles"),
    ('5251', "Insurance and employee benefit funds"),
    ('52511', "Pension funds"),
    ('525110', "Pension funds"),
    ('52512', "Health and welfare funds"),
    ('525120', "Health and welfare funds"),
    ('52519', "Other insurance funds"),
    ('525190', "Other insurance funds"),
    ('5259', "Other investment pools and funds"),
    ('52591', "Open-end investment funds"),
    ('525910', "Open-end investment funds"),
    ('52592', "Trusts, estates, and agency accounts"),
    ('525920', "Trusts, estates, and agency accounts"),
    ('52593', "Real estate investment trusts"),
    ('525930', "Real estate investment trusts"),
    ('52599', "Other financial vehicles"),
    ('525990', "Other financial vehicles"),
    ('53', "Real estate and rental and leasing"),
    ('531', "Real estate"),
    ('5311', "Lessors of real estate"),
    ('53111', "Lessors of residential buildings"),
    ('531110', "Lessors of residential buildings"),
    ('53112', "Lessors of nonresidential buildings"),
    ('531120', "Lessors of nonresidential buildings"),
    ('53113', "Miniwarehouse and self-storage unit operators"),
    ('531130', "Miniwarehouse and self-storage unit operators"),
    ('53119', "Lessors of other real estate property"),
    ('531190', "Lessors of other real estate property"),
    ('5312', "Offices of real estate agents and brokers"),
    ('53121', "Offices of real estate agents and brokers"),
    ('531210', "Offices of real estate agents and brokers"),
    ('5313', "Activities related to real estate"),
    ('53131', "Real estate property managers"),
    ('531311', "Residential property managers"),
    ('531312', "nonresidential property managers"),
    ('53132', "Offices of real estate appraisers"),
    ('531320', "Offices of real estate appraisers"),
    ('53139', "Other activities related to real estate"),
    ('531390', "Other activities related to real estate"),
    ('532', "Rental and leasing services"),
    ('5321', "Automotive equipment rental and leasing"),
    ('53211', "Passenger car rental and leasing"),
    ('532111', "Passenger car rental"),
    ('532112', "Passenger car leasing"),
    ('53212', "Truck, trailer, and rv rental and leasing"),
    ('532120', "Truck, trailer, and rv rental and leasing"),
    ('5322', "Consumer goods rental"),
    ('53221', "Consumer electronics and appliances rental"),
    ('532210', "Consumer electronics and appliances rental"),
    ('53222', "Formal wear and costume rental"),
    ('532220', "Formal wear and costume rental"),
    ('53223', "Video tape and disc rental"),
    ('532230', "Video tape and disc rental"),
    ('53229', "Other consumer goods rental"),
    ('532291', "Home health equipment rental"),
    ('532292', "Recreational goods rental"),
    ('532299', "All other consumer goods rental"),
    ('5323', "General rental centers"),
    ('53231', "General rental centers"),
    ('532310', "General rental centers"),
    ('5324', "Machinery and equipment rental and leasing"),
    ('53241', "Heavy machinery rental and leasing"),
    ('532411', "Transportation equipment rental and leasing"),
    ('532412', "Other heavy machinery rental and leasing"),
    ('53242', "Office equipment rental and leasing"),
    ('532420', "Office equipment rental and leasing"),
    ('53249', "Other machinery rental and leasing"),
    ('532490', "Other machinery rental and leasing"),
    ('533', "Lessors of nonfinancial intangible assets"),
    ('5331', "Lessors of nonfinancial intangible assets"),
    ('53311', "Lessors of nonfinancial intangible assets"),
    ('533110', "Lessors of nonfinancial intangible assets"),
    ('54', "Professional and technical services"),
    ('541', "Professional and technical services"),
    ('5411', "Legal services"),
    ('54111', "Offices of lawyers"),
    ('541110', "Offices of lawyers"),
    ('54119', "Other legal services"),
    ('541191', "Title abstract and settlement offices"),
    ('541199', "All other legal services"),
    ('5412', "Accounting and bookkeeping services"),
    ('54121', "Accounting and bookkeeping services"),
    ('541211', "Offices of certified public accountants"),
    ('541213', "Tax preparation services"),
    ('541214', "Payroll services"),
    ('541219', "Other accounting services"),
    ('5413', "Architectural and engineering services"),
    ('54131', "Architectural services"),
    ('541310', "Architectural services"),
    ('54132', "Landscape architectural services"),
    ('541320', "Landscape architectural services"),
    ('54133', "Engineering services"),
    ('541330', "Engineering services"),
    ('54134', "Drafting services"),
    ('541340', "Drafting services"),
    ('54135', "Building inspection services"),
    ('541350', "Building inspection services"),
    ('54136', "Geophysical surveying and mapping services"),
    ('541360', "Geophysical surveying and mapping services"),
    ('54137', "Other surveying and mapping services"),
    ('541370', "Other surveying and mapping services"),
    ('54138', "Testing laboratories"),
    ('541380', "Testing laboratories"),
    ('5414', "Specialized design services"),
    ('54141', "Interior design services"),
    ('541410', "Interior design services"),
    ('54142', "Industrial design services"),
    ('541420', "Industrial design services"),
    ('54143', "Graphic design services"),
    ('541430', "Graphic design services"),
    ('54149', "Other specialized design services"),
    ('541490', "Other specialized design services"),
    ('5415', "Computer systems design and related services"),
    ('54151', "Computer systems design and related services"),
    ('541511', "Custom computer programming services"),
    ('541512', "Computer systems design services"),
    ('541513', "Computer facilities management services"),
    ('541519', "Other computer related services"),
    ('5416', "Management and technical consulting services"),
    ('54161', "Management consulting services"),
    ('541611', "Administrative management consulting services"),
    ('541612', "Human resources consulting services"),
    ('541613', "Marketing consulting services"),
    ('541614', "Process and logistics consulting services"),
    ('541618', "Other management consulting services"),
    ('54162', "Environmental consulting services"),
    ('541620', "Environmental consulting services"),
    ('54169', "Other technical consulting services"),
    ('541690', "Other technical consulting services"),
    ('5417', "Scientific research and development services"),
    ('54171', "Physical, engineering and biological research"),
    ('541710', "Physical, engineering and biological research"),
    ('541711', "Research and development in biotechnology"),
    ('541712', "Other physical and biological research"),
    ('54172', "Social science and humanities research"),
    ('541720', "Social science and humanities research"),
    ('5418', "Advertising, pr, and related services"),
    ('54181', "Advertising agencies"),
    ('541810', "Advertising agencies"),
    ('54182', "Public relations agencies"),
    ('541820', "Public relations agencies"),
    ('54183', "Media buying agencies"),
    ('541830', "Media buying agencies"),
    ('54184', "Media representatives"),
    ('541840', "Media representatives"),
    ('54185', "Outdoor advertising"),
    ('541850', "Outdoor advertising"),
    ('54186', "Direct mail advertising"),
    ('541860', "Direct mail advertising"),
    ('54187', "Advertising material distribution services"),
    ('541870', "Advertising material distribution services"),
    ('54189', "Other services related to advertising"),
    ('541890', "Other services related to advertising"),
    ('5419', "Other professional and technical services"),
    ('54191', "Marketing research and public opinion polling"),
    ('541910', "Marketing research and public opinion polling"),
    ('54192', "Photographic services"),
    ('541921', "Photography studios, portrait"),
    ('541922', "Commercial photography"),
    ('54193', "Translation and interpretation services"),
    ('541930', "Translation and interpretation services"),
    ('54194', "Veterinary services"),
    ('541940', "Veterinary services"),
    ('54199', "All other professional and technical services"),
    ('541990', "All other professional and technical services"),
    ('55', "Management of companies and enterprises"),
    ('551', "Management of companies and enterprises"),
    ('5511', "Management of companies and enterprises"),
    ('55111', "Management of companies and enterprises"),
    ('551111', "Offices of bank holding companies"),
    ('551112', "Offices of other holding companies"),
    ('551114', "Managing offices"),
    ('56', "Administrative and waste services"),
    ('561', "Administrative and support services"),
    ('5611', "Office administrative services"),
    ('56111', "Office administrative services"),
    ('561110', "Office administrative services"),
    ('5612', "Facilities support services"),
    ('56121', "Facilities support services"),
    ('561210', "Facilities support services"),
    ('5613', "Employment services"),
    ('56131', "Employment placement and executive search"),
    ('561310', "Employment placement agencies"),
    ('561311', "Employment placement agencies"),
    ('561312', "Executive search services"),
    ('56132', "Temporary help services"),
    ('561320', "Temporary help services"),
    ('56133', "Professional employer organizations"),
    ('561330', "Professional employer organizations"),
    ('5614', "Business support services"),
    ('56141', "Document preparation services"),
    ('561410', "Document preparation services"),
    ('56142', "Telephone call centers"),
    ('561421', "Telephone answering services"),
    ('561422', "Telemarketing and other contact centers"),
    ('56143', "Business service centers"),
    ('561431', "Private mail centers"),
    ('561439', "Other business service centers"),
    ('56144', "Collection agencies"),
    ('561440', "Collection agencies"),
    ('56145', "Credit bureaus"),
    ('561450', "Credit bureaus"),
    ('56149', "Other business support services"),
    ('561491', "Repossession services"),
    ('561492', "Court reporting and stenotype services"),
    ('561499', "All other business support services"),
    ('5615', "Travel arrangement and reservation services"),
    ('56151', "Travel agencies"),
    ('561510', "Travel agencies"),
    ('56152', "Tour operators"),
    ('561520', "Tour operators"),
    ('56159', "Other travel arrangement services"),
    ('561591', "Convention and visitors bureaus"),
    ('561599', "All other travel arrangement services"),
    ('5616', "Investigation and security services"),
    ('56161', "Security and armored car services"),
    ('561611', "Investigation services"),
    ('561612', "Security guards and patrol services"),
    ('561613', "Armored car services"),
    ('56162', "Security systems services"),
    ('561621', "Security systems services, except locksmiths"),
    ('561622', "Locksmiths"),
    ('5617', "Services to buildings and dwellings"),
    ('56171', "Exterminating and pest control services"),
    ('561710', "Exterminating and pest control services"),
    ('56172', "Janitorial services"),
    ('561720', "Janitorial services"),
    ('56173', "Landscaping services"),
    ('561730', "Landscaping services"),
    ('56174', "Carpet and upholstery cleaning services"),
    ('561740', "Carpet and upholstery cleaning services"),
    ('56179', "Other services to buildings and dwellings"),
    ('561790', "Other services to buildings and dwellings"),
    ('5619', "Other support services"),
    ('56191', "Packaging and labeling services"),
    ('561910', "Packaging and labeling services"),
    ('56192', "Convention and trade show organizers"),
    ('561920', "Convention and trade show organizers"),
    ('56199', "All other support services"),
    ('561990', "All other support services"),
    ('562', "Waste management and remediation services"),
    ('5621', "Waste collection"),
    ('56211', "Waste collection"),
    ('562111', "Solid waste collection"),
    ('562112', "Hazardous waste collection"),
    ('562119', "Other waste collection"),
    ('5622', "Waste treatment and disposal"),
    ('56221', "Waste treatment and disposal"),
    ('562211', "Hazardous waste treatment and disposal"),
    ('562212', "Solid waste landfill"),
    ('562213', "Solid waste combustors and incinerators"),
    ('562219', "Other nonhazardous waste disposal"),
    ('5629', "Remediation and other waste services"),
    ('56291', "Remediation services"),
    ('562910', "Remediation services"),
    ('56292', "Materials recovery facilities"),
    ('562920', "Materials recovery facilities"),
    ('56299', "All other waste management services"),
    ('562991', "Septic tank and related services"),
    ('562998', "Miscellaneous waste management services"),
    ('61', "Educational services"),
    ('611', "Educational services"),
    ('6111', "Elementary and secondary schools"),
    ('61111', "Elementary and secondary schools"),
    ('611110', "Elementary and secondary schools"),
    ('6112', "Junior colleges"),
    ('61121', "Junior colleges"),
    ('611210', "Junior colleges"),
    ('6113', "Colleges and universities"),
    ('61131', "Colleges and universities"),
    ('611310', "Colleges and universities"),
    ('6114', "Business, computer and management training"),
    ('61141', "Business and secretarial schools"),
    ('611410', "Business and secretarial schools"),
    ('61142', "Computer training"),
    ('611420', "Computer training"),
    ('61143', "Management training"),
    ('611430', "Management training"),
    ('6115', "Technical and trade schools"),
    ('61151', "Technical and trade schools"),
    ('611511', "Cosmetology and barber schools"),
    ('611512', "Flight training"),
    ('611513', "Apprenticeship training"),
    ('611519', "Other technical and trade schools"),
    ('6116', "Other schools and instruction"),
    ('61161', "Fine arts schools"),
    ('611610', "Fine arts schools"),
    ('61162', "Sports and recreation instruction"),
    ('611620', "Sports and recreation instruction"),
    ('61163', "Language schools"),
    ('611630', "Language schools"),
    ('61169', "All other schools and instruction"),
    ('611691', "Exam preparation and tutoring"),
    ('611692', "Automobile driving schools"),
    ('611699', "Miscellaneous schools and instruction"),
    ('6117', "Educational support services"),
    ('61171', "Educational support services"),
    ('611710', "Educational support services"),
    ('62', "Health care and social assistance"),
    ('621', "Ambulatory health care services"),
    ('6211', "Offices of physicians"),
    ('62111', "Offices of physicians"),
    ('621111', "Offices of physicians, except mental health"),
    ('621112', "Offices of mental health physicians"),
    ('6212', "Offices of dentists"),
    ('62121', "Offices of dentists"),
    ('621210', "Offices of dentists"),
    ('6213', "Offices of other health practitioners"),
    ('62131', "Offices of chiropractors"),
    ('621310', "Offices of chiropractors"),
    ('62132', "Offices of optometrists"),
    ('621320', "Offices of optometrists"),
    ('62133', "Offices of mental health practitioners"),
    ('621330', "Offices of mental health practitioners"),
    ('62134', "Offices of specialty therapists"),
    ('621340', "Offices of specialty therapists"),
    ('62139', "Offices of all other health practitioners"),
    ('621391', "Offices of podiatrists"),
    ('621399', "Offices of miscellaneous health practitioners"),
    ('6214', "Outpatient care centers"),
    ('62141', "Family planning centers"),
    ('621410', "Family planning centers"),
    ('62142', "Outpatient mental health centers"),
    ('621420', "Outpatient mental health centers"),
    ('62149', "Other outpatient care centers"),
    ('621491', "Hmo medical centers"),
    ('621492', "Kidney dialysis centers"),
    ('621493', "Freestanding emergency medical centers"),
    ('621498', "All other outpatient care centers"),
    ('6215', "Medical and diagnostic laboratories"),
    ('62151', "Medical and diagnostic laboratories"),
    ('621511', "Medical laboratories"),
    ('621512', "Diagnostic imaging centers"),
    ('6216', "Home health care services"),
    ('62161', "Home health care services"),
    ('621610', "Home health care services"),
    ('6219', "Other ambulatory health care services"),
    ('62191', "Ambulance services"),
    ('621910', "Ambulance services"),
    ('62199', "All other ambulatory health care services"),
    ('621991', "Blood and organ banks"),
    ('621999', "Miscellaneous ambulatory health care services"),
    ('622', "Hospitals"),
    ('6221', "General medical and surgical hospitals"),
    ('62211', "General medical and surgical hospitals"),
    ('622110', "General medical and surgical hospitals"),
    ('6222', "Psychiatric and substance abuse hospitals"),
    ('62221', "Psychiatric and substance abuse hospitals"),
    ('622210', "Psychiatric and substance abuse hospitals"),
    ('6223', "Other hospitals"),
    ('62231', "Other hospitals"),
    ('622310', "Other hospitals"),
    ('623', "Nursing and residential care facilities"),
    ('6231', "Nursing care facilities"),
    ('62311', "Nursing care facilities"),
    ('623110', "Nursing care facilities"),
    ('6232', "Residential mental health facilities"),
    ('62321', "Residential disability facilities"),
    ('623210', "Residential disability facilities"),
    ('62322', "Residential mental and substance abuse care"),
    ('623220', "Residential mental and substance abuse care"),
    ('6233', "Community care facilities for the elderly"),
    ('62331', "Community care facilities for the elderly"),
    ('623311', "Continuing care retirement communities"),
    ('623312', "Assisted living facilities for the elderly"),
    ('6239', "Other residential care facilities"),
    ('62399', "Other residential care facilities"),
    ('623990', "Other residential care facilities"),
    ('624', "Social assistance"),
    ('6241', "Individual and family services"),
    ('62411', "Child and youth services"),
    ('624110', "Child and youth services"),
    ('62412', "Services for the elderly and disabled"),
    ('624120', "Services for the elderly and disabled"),
    ('62419', "Other individual and family services"),
    ('624190', "Other individual and family services"),
    ('6242', "Emergency and other relief services"),
    ('62421', "Community food services"),
    ('624210', "Community food services"),
    ('62422', "Community housing services"),
    ('624221', "Temporary shelters"),
    ('624229', "Other community housing services"),
    ('62423', "Emergency and other relief services"),
    ('624230', "Emergency and other relief services"),
    ('6243', "Vocational rehabilitation services"),
    ('62431', "Vocational rehabilitation services"),
    ('624310', "Vocational rehabilitation services"),
    ('6244', "Child day care services"),
    ('62441', "Child day care services"),
    ('624410', "Child day care services"),
    ('71', "Arts, entertainment, and recreation"),
    ('711', "Performing arts and spectator sports"),
    ('7111', "Performing arts companies"),
    ('71111', "Theater companies and dinner theaters"),
    ('711110', "Theater companies and dinner theaters"),
    ('71112', "Dance companies"),
    ('711120', "Dance companies"),
    ('71113', "Musical groups and artists"),
    ('711130', "Musical groups and artists"),
    ('71119', "Other performing arts companies"),
    ('711190', "Other performing arts companies"),
    ('7112', "Spectator sports"),
    ('71121', "Spectator sports"),
    ('711211', "Sports teams and clubs"),
    ('711212', "Racetracks"),
    ('711219', "Other spectator sports"),
    ('7113', "Promoters of performing arts and sports"),
    ('71131', "Promoters with facilities"),
    ('711310', "Promoters with facilities"),
    ('71132', "Promoters without facilities"),
    ('711320', "Promoters without facilities"),
    ('7114', "Agents and managers for public figures"),
    ('71141', "Agents and managers for public figures"),
    ('711410', "Agents and managers for public figures"),
    ('7115', "Independent artists, writers, and performers"),
    ('71151', "Independent artists, writers, and performers"),
    ('711510', "Independent artists, writers, and performers"),
    ('712', "Museums, historical sites, zoos, and parks"),
    ('7121', "Museums, historical sites, zoos, and parks"),
    ('71211', "Museums"),
    ('712110', "Museums"),
    ('71212', "Historical sites"),
    ('712120', "Historical sites"),
    ('71213', "Zoos and botanical gardens"),
    ('712130', "Zoos and botanical gardens"),
    ('71219', "Nature parks and other similar institutions"),
    ('712190', "Nature parks and other similar institutions"),
    ('713', "Amusements, gambling, and recreation"),
    ('7131', "Amusement parks and arcades"),
    ('71311', "Amusement and theme parks"),
    ('713110', "Amusement and theme parks"),
    ('71312', "Amusement arcades"),
    ('713120', "Amusement arcades"),
    ('7132', "Gambling industries"),
    ('71321', "Casinos, except casino hotels"),
    ('713210', "Casinos, except casino hotels"),
    ('71329', "Other gambling industries"),
    ('713290', "Other gambling industries"),
    ('7139', "Other amusement and recreation industries"),
    ('71391', "Golf courses and country clubs"),
    ('713910', "Golf courses and country clubs"),
    ('71392', "Skiing facilities"),
    ('713920', "Skiing facilities"),
    ('71393', "Marinas"),
    ('713930', "Marinas"),
    ('71394', "Fitness and recreational sports centers"),
    ('713940', "Fitness and recreational sports centers"),
    ('71395', "Bowling centers"),
    ('713950', "Bowling centers"),
    ('71399', "All other amusement and recreation industries"),
    ('713990', "All other amusement and recreation industries"),
    ('72', "Accommodation and food services"),
    ('721', "Accommodation"),
    ('7211', "Traveler accommodation"),
    ('72111', "Hotels and motels, except casino hotels"),
    ('721110', "Hotels and motels, except casino hotels"),
    ('72112', "Casino hotels"),
    ('721120', "Casino hotels"),
    ('72119', "Other traveler accommodation"),
    ('721191', "Bed-and-breakfast inns"),
    ('721199', "All other traveler accommodation"),
    ('7212', "Rv parks and recreational camps"),
    ('72121', "Rv parks and recreational camps"),
    ('721211', "Rv parks and campgrounds"),
    ('721214', "Recreational and vacation camps"),
    ('7213', "Rooming and boarding houses"),
    ('72131', "Rooming and boarding houses"),
    ('721310', "Rooming and boarding houses"),
    ('722', "Food services and drinking places"),
    ('7221', "Full-service restaurants"),
    ('72211', "Full-service restaurants"),
    ('722110', "Full-service restaurants"),
    ('7222', "Limited-service eating places"),
    ('72221', "Limited-service eating places"),
    ('722211', "Limited-service restaurants"),
    ('722212', "Cafeterias, grill buffets, and buffets"),
    ('722213', "Snack and nonalcoholic beverage bars"),
    ('7223', "Special food services"),
    ('72231', "Food service contractors"),
    ('722310', "Food service contractors"),
    ('72232', "Caterers"),
    ('722320', "Caterers"),
    ('72233', "Mobile food services"),
    ('722330', "Mobile food services"),
    ('7224', "Drinking places, alcoholic beverages"),
    ('72241', "Drinking places, alcoholic beverages"),
    ('722410', "Drinking places, alcoholic beverages"),
    ('7225', "Restaurants"),
    ('72251', "Restaurants"),
    ('722511', "Full-service restaurants"),
    ('722513', "Limited-service restaurants"),
    ('722514', "Cafeterias, grill buffets, and buffets"),
    ('722515', "Snack and nonalcoholic beverage bars"),
    ('81', "Other services, except public administration"),
    ('811', "Repair and maintenance"),
    ('8111', "Automotive repair and maintenance"),
    ('81111', "Automotive mechanical and electrical repair"),
    ('811111', "General automotive repair"),
    ('811112', "Automotive exhaust system repair"),
    ('811113', "Automotive transmission repair"),
    ('811118', "Other automotive mechanical and elec. repair"),
    ('81112', "Automotive body, interior, and glass repair"),
    ('811121', "Automotive body and interior repair"),
    ('811122', "Automotive glass replacement shops"),
    ('81119', "Other automotive repair and maintenance"),
    ('811191', "Automotive oil change and lubrication shops"),
    ('811192', "Car washes"),
    ('811198', "All other automotive repair and maintenance"),
    ('8112', "Electronic equipment repair and maintenance"),
    ('81121', "Electronic equipment repair and maintenance"),
    ('811211', "Consumer electronics repair and maintenance"),
    ('811212', "Computer and office machine repair"),
    ('811213', "Communication equipment repair"),
    ('811219', "Other electronic equipment repair"),
    ('8113', "Commercial machinery repair and maintenance"),
    ('81131', "Commercial machinery repair and maintenance"),
    ('811310', "Commercial machinery repair and maintenance"),
    ('8114', "Household goods repair and maintenance"),
    ('81141', "Home and garden equip. and appliance repair"),
    ('811411', "Home and garden equipment repair"),
    ('811412', "Appliance repair and maintenance"),
    ('81142', "Reupholstery and furniture repair"),
    ('811420', "Reupholstery and furniture repair"),
    ('81143', "Footwear and leather goods repair"),
    ('811430', "Footwear and leather goods repair"),
    ('81149', "Other household goods repair and maintenance"),
    ('811490', "Other household goods repair and maintenance"),
    ('812', "Personal and laundry services"),
    ('8121', "Personal care services"),
    ('81211', "Hair, nail, and skin care services"),
    ('812111', "Barber shops"),
    ('812112', "Beauty salons"),
    ('812113', "Nail salons"),
    ('81219', "Other personal care services"),
    ('812191', "Diet and weight reducing centers"),
    ('812199', "Other personal care services"),
    ('8122', "Death care services"),
    ('81221', "Funeral homes and funeral services"),
    ('812210', "Funeral homes and funeral services"),
    ('81222', "Cemeteries and crematories"),
    ('812220', "Cemeteries and crematories"),
    ('8123', "Drycleaning and laundry services"),
    ('81231', "Coin-operated laundries and drycleaners"),
    ('812310', "Coin-operated laundries and drycleaners"),
    ('81232', "Drycleaning and laundry services"),
    ('812320', "Drycleaning and laundry services"),
    ('81233', "Linen and uniform supply"),
    ('812331', "Linen supply"),
    ('812332', "Industrial launderers"),
    ('8129', "Other personal services"),
    ('81291', "Pet care, except veterinary, services"),
    ('812910', "Pet care, except veterinary, services"),
    ('81292', "Photofinishing"),
    ('812921', "Photofinishing laboratories, except one-hour"),
    ('812922', "One-hour photofinishing"),
    ('81293', "Parking lots and garages"),
    ('812930', "Parking lots and garages"),
    ('81299', "All other personal services"),
    ('812990', "All other personal services"),
    ('813', "Membership associations and organizations"),
    ('8131', "Religious organizations"),
    ('81311', "Religious organizations"),
    ('813110', "Religious organizations"),
    ('8132', "Grantmaking and giving services"),
    ('81321', "Grantmaking and giving services"),
    ('813211', "Grantmaking foundations"),
    ('813212', "Voluntary health organizations"),
    ('813219', "Other grantmaking and giving services"),
    ('8133', "Social advocacy organizations"),
    ('81331', "Social advocacy organizations"),
    ('813311', "Human rights organizations"),
    ('813312', "Environment and conservation organizations"),
    ('813319', "Other social advocacy organizations"),
    ('8134', "Civic and social organizations"),
    ('81341', "Civic and social organizations"),
    ('813410', "Civic and social organizations"),
    ('8139', "Professional and similar organizations"),
    ('81391', "Business associations"),
    ('813910', "Business associations"),
    ('81392', "Professional organizations"),
    ('813920', "Professional organizations"),
    ('81393', "Labor unions and similar labor organizations"),
    ('813930', "Labor unions and similar labor organizations"),
    ('81394', "Political organizations"),
    ('813940', "Political organizations"),
    ('81399', "Other similar organizations"),
    ('813990', "Other similar organizations"),
    ('814', "Private households"),
    ('8141', "Private households"),
    ('81411', "Private households"),
    ('814110', "Private households"),
    ('92', "Public administration"),
    ('921', "Executive, legislative and general government"),
    ('9211', "Executive, legislative and general government"),
    ('92111', "Executive offices"),
    ('921110', "Executive offices"),
    ('92112', "Legislative bodies"),
    ('921120', "Legislative bodies"),
    ('92113', "Public finance activities"),
    ('921130', "Public finance activities"),
    ('92114', "Executive and legislative offices, combined"),
    ('921140', "Executive and legislative offices, combined"),
    ('92115', "Tribal governments"),
    ('921150', "Tribal governments"),
    ('92119', "Other general government support"),
    ('921190', "Other general government support"),
    ('922', "Justice, public order, and safety activities"),
    ('9221', "Justice, public order, and safety activities"),
    ('92211', "Courts"),
    ('922110', "Courts"),
    ('92212', "Police protection"),
    ('922120', "Police protection"),
    ('92213', "Legal counsel and prosecution"),
    ('922130', "Legal counsel and prosecution"),
    ('92214', "Correctional institutions"),
    ('922140', "Correctional institutions"),
    ('92215', "Parole offices and probation offices"),
    ('922150', "Parole offices and probation offices"),
    ('92216', "Fire protection"),
    ('922160', "Fire protection"),
    ('92219', "Other justice and safety activities"),
    ('922190', "Other justice and safety activities"),
    ('923', "Administration of human resource programs"),
    ('9231', "Administration of human resource programs"),
    ('92311', "Administration of education programs"),
    ('923110', "Administration of education programs"),
    ('92312', "Administration of public health programs"),
    ('923120', "Administration of public health programs"),
    ('92313', "Other human resource programs administration"),
    ('923130', "Other human resource programs administration"),
    ('92314', "Administration of veterans' affairs"),
    ('923140', "Administration of veterans' affairs"),
    ('924', "Administration of environmental programs"),
    ('9241', "Administration of environmental programs"),
    ('92411', "Air, water, and waste program administration"),
    ('924110', "Air, water, and waste program administration"),
    ('92412', "Administration of conservation programs"),
    ('924120', "Administration of conservation programs"),
    ('925', "Community and housing program administration"),
    ('9251', "Community and housing program administration"),
    ('92511', "Administration of housing programs"),
    ('925110', "Administration of housing programs"),
    ('92512', "Urban and rural development administration"),
    ('925120', "Urban and rural development administration"),
    ('926', "Administration of economic programs"),
    ('9261', "Administration of economic programs"),
    ('92611', "Administration of general economic programs"),
    ('926110', "Administration of general economic programs"),
    ('92612', "Transportation program administration"),
    ('926120', "Transportation program administration"),
    ('92613', "Utility regulation and administration"),
    ('926130', "Utility regulation and administration"),
    ('92614', "Agricultural market and commodity regulation"),
    ('926140', "Agricultural market and commodity regulation"),
    ('92615', "Licensing and regulating commercial sectors"),
    ('926150', "Licensing and regulating commercial sectors"),
    ('927', "Space research and technology"),
    ('9271', "Space research and technology"),
    ('92711', "Space research and technology"),
    ('927110', "Space research and technology"),
    ('928', "National security and international affairs"),
    ('9281', "National security and international affairs"),
    ('92811', "National security"),
    ('928110', "National security"),
    ('92812', "International affairs"),
    ('928120', "International affairs"),
    ('99', "Unclassified"),
    ('999', "Unclassified"),
    ('9999', "Unclassified"),
    ('99999', "Unclassified"),
    ('999999', "Unclassified"),
]) def is_supersector(code):
    '''
    Returns True if this is a NAICS supersector, False otherwise
    '''
    return len(code) == 4 and code[0:2] == '10' def is_sector(code):
    '''
    Returns True if this is a NAICS sector, False otherwise
    '''
    if len(code) == 2 and code != '10':
        return True
    elif len(code) == 5 and '-' in code:
        return True
    return False def is_public_administration(code):
    return code in ('1028', '92') def get_parent_code(code):
    '''
    Return the parent code of the passed code.  For the root ('10'), returns
    None
    '''
    if is_supersector(code) or is_sector(code):
        return '10'
    elif code == '10':
        return None
    elif len(code) == 3 and code[0:2] in ('31', '32', '33', ):
        return '31-33'
    elif len(code) == 3 and code[0:2] in ('44', '45', ):
        return '44-45'
    elif len(code) == 3 and code[0:2] in ('48', '49', ):
        return '48-49'
    else:
        return code[0:len(code)-1] class OBSColumn(Base):
    '''
    Describes the characteristics of data in a column, which can exist in
    multiple physical tables.

    These should *only* be instantiated to generate the return value of
    :meth:`.ColumnsTask.columns`.  Any other usage could have unexpected
    consequences.

    .. py:attribute:: id

       The unique identifier for this column.  Should be qualified by
       the module name of the class that created it.  Is automatically
       generated by :class:`~.tasks.ColumnsTask` if left unspecified,
       and automatically qualified by module name either way.

    .. py:attribute:: type

       The type of this column -- for example, ``Text``, ``Numeric``,
       ``Geometry``, etc.  This is used to generate a schema for any
       table using this column.

    .. py:attribute:: name

       The human-readable name of this column.  This is used in the
       catalog and API.

    .. py:attribute:: description

       The human-readable description of this column.  THis is
       used in the catalog.

    .. py:attribute:: weight

       A numeric weight for this column.  Higher weights are favored
       in certain rankings done by the API. Defaults to zero, which hides
       the column from catalog.

    .. py:attribute:: aggregate

       How this column can be aggregated.  For example,
       populations can be summed, so a population column should
       be ``sum``. Should be left blank if it is not to
       aggregate.

    .. py:attribute:: tables

       Iterable of all linked :class:`~.meta.OBSColumnTable`s, which could be
       traversed to find all tables with this column.

    .. py:attribute:: tags

       Iterable of all linked :class:`~.meta.OBSColumnTag`s, which could be
       traversed to find all tags applying to this column.

    .. py:attribute:: targets

       Dict of all related columns.  Format is ``<OBSColumn>: <reltype>``.

    .. py:attribute:: version

       A version control number, used to determine whether the column and its
       metadata should be updated.

    .. py:attribute:: extra

       Arbitrary additional information about this column stored as JSON.

    '''
    __tablename__ = 'obs_column'

    id = Column(Text, primary_key=True) # fully-qualified id like '"us.census.acs".b01001001'

    type = Column(Text, nullable=False) # postgres type, IE numeric, string, geometry, etc.
    name = Column(Text) # human-readable name to provide in bigmetadata

    description = Column(Text) # human-readable description to provide in
                                 # bigmetadata

    weight = Column(Numeric, default=1)
    aggregate = Column(Text) # what aggregate operation to use when adding
                               # these together across geoms: AVG, SUM etc.

    tables = relationship("OBSColumnTable", back_populates="column", cascade="all,delete")
    session = current_session()
    # Passing the same session object to the creator saves thousands
    # of `select 1` queries, because each use of the session was pinging
    tag_creator_with_session = functools.partial(tag_creator, session=session)
    tags = association_proxy('column_column_tags', 'tag', creator=tag_creator_with_session)

    targets = association_proxy('tgts', 'reltype', creator=coltocoltargets_creator)

    version = Column(Numeric, default=0, nullable=False)
    extra = Column(JSON)

    @property
    def sources(self):
        sources = {}
        session = current_session()
        for c2c in session.query(OBSColumnToColumn).filter_by(target_id=self.id):
            sources[c2c.source] = c2c.reltype
        return sources

    @property
    def index_type(self):
        if hasattr(self, '_index_type'):
            pass
        elif 'geom_ref' in list(self.targets.values()):
            self._index_type = 'btree'
        elif self.type.lower() == 'geometry':
            self._index_type = 'gist'
        else:
            self._index_type = None

        return self._index_type

    def children(self):
        children = [col for col, reltype in self.sources.items() if reltype == DENOMINATOR]
        children.sort(key=lambda x: natural_sort_key(x.name))
        return children

    def is_cartographic(self):
        '''
        Returns True if this column is a geometry that can be used for cartography.
        '''
        for tag in self.tags:
            if 'cartographic_boundary' in tag.id:
                return True
        return False

    def is_interpolation(self):
        '''
        Returns True if this column is a geometry that can be used for interpolation.
        '''
        for tag in self.tags:
            if 'interpolation_boundary' in tag.id:
                return True
        return False

    def is_geomref(self):
        '''
        Returns True if the column is a geomref, else Null
        '''
        return GEOM_REF in list(self.targets.values())

    def has_children(self):
        '''
        Returns True if this column has children, False otherwise.
        '''
        return len(self.children()) > 0

    def has_denominators(self):
        '''
        Returns True if this column has no denominator, False otherwise.
        '''
        return DENOMINATOR in list(self.targets.values())

    def has_catalog_image(self):
        '''
        Returns True if this column has a pre-generated image for the catalog.
        '''
        return os.path.exists(os.path.join('catalog', 'img', self.id + '.png'))

    def denominators(self):
        '''
        Return the :class:`~.meta.OBSColumn` denominator of this column.
        '''
        if not self.has_denominators():
            return []
        return [k for k, v in self.targets.items() if v == DENOMINATOR]

    def unit(self):
        '''
        Return the :class:`~.meta.OBSTag` unit of this column.
        '''
        units = [tag for tag in self.tags if tag.type == 'unit']
        if units:
            return units[0]

    def summable(self):
        '''
        Returns True if we can sum this column and calculate for arbitrary
        areas.
        '''
        return self.aggregate == 'sum'

    def catalog_lonlat(self):
        '''
        Return tuple (longitude, latitude) for the catalog for this measurement.
        '''
        return catalog_lonlat(self.id)

    def geom_timespans(self):
        '''
        Return a dict of geom columns and timespans that this measure is
        available for.
        '''
        geom_timespans = {}
        for table in self.tables:
            table = table.table
            geomref_column = table.geomref_column()
            geom_column = [t for t, rt in geomref_column.targets.items()
                           if rt == GEOM_REF][0]
            if geom_column not in geom_timespans:
                geom_timespans[geom_column] = []
            geom_timespans[geom_column].append(table.timespan)
        return geom_timespans

    def source_tags(self):
        '''
        Return source tags.
        '''
        return [tag for tag in self.tags if tag.type.lower() == 'source']

    def license_tags(self):
        '''
        Return license tags.
        '''
        return [tag for tag in self.tags if tag.type.lower() == 'license'] class OBSTag(Base):
    '''
    Tags permit arbitrary groupings of columns.

    They should only be created as part of a :meth:`~.tasks.TagsTask.tags`
    implementation.

    .. py:attribute:: id

       The unique identifier for this table.  Is always qualified by
       the module name of the :class:`~.tasks.TagsTask` that created it, and
       should never be specified manually.

    .. py:attribute:: name

       The name of this tag.  This is exposed in the API and user interfaces.

    .. py:attribute:: type

       The type of this tag.  This is used to provide more information about
       what the tag means.  Examples are ``section``, ``subsection``,
       ``license``, ``unit``, although any arbitrary type can be defined.

    .. py:attribute:: description

       Description of this tag.  This may be exposed in the API and catalog.

    .. py:attribute:: columns

       An iterable of all the :class:`~.meta.OBSColumn`s tagged with this tag.

    .. py:attribute:: version

       A version control number, used to determine whether the tag and its
       metadata should be updated.

    '''
    __tablename__ = 'obs_tag'

    id = Column(Text, primary_key=True)

    name = Column(Text, nullable=False)
    type = Column(Text, nullable=False)
    description = Column(Text)

    columns = association_proxy('tag_column_tags', 'column')

    version = Column(Numeric, default=0, nullable=False) GEOM_REF = 'geom_ref' class SectionTags(TagsTask):

    def version(self):
        return 5

    def tags(self):
        return [
            OBSTag(id='global',
                   name='Global',
                   type='section',
                   description=''),
            OBSTag(id='eu',
                   name='European Union',
                   type='section',
                   description=''),
            OBSTag(id='united_states',
                   name='United States',
                   type='section',
                   description=''),
            OBSTag(id='spain',
                   name='Spain',
                   type='section',
                   description=''),
            OBSTag(id='mx',
                   name='Mexico',
                   type='section',
                   description=''),
            OBSTag(id='uk',
                   name='United Kingdom',
                   type='section',
                   description=''),
            OBSTag(id='fr',
                   name='France',
                   type='section',
                   description=''),
            OBSTag(id='ca',
                   name='Canada',
                   type='section',
                   description=''),
            OBSTag(id='th',
                   name='Thailand',
                   type='section',
                   description=''),
            OBSTag(id='au',
                   name='Australia',
                   type='section',
                   description=''),
            OBSTag(id='br',
                   name='Brazil',
                   type='section',
                   description='')
        ] class SubsectionTags(TagsTask):

    def version(self):
        return 24

    def tags(self):
        return [
            OBSTag(id='housing',
                   name='Housing',
                   type='subsection',
                   description='What type of housing exists and how do people live in it?'),
            OBSTag(id='income',
                   name='Income',
                   type='subsection',
                   description='''How much people earn.'''),
            OBSTag(id='education',
                   name='Education',
                   type='subsection',
                   description='Educational attainment and enrollment.'),
            OBSTag(id='employment',
                   name='Employment',
                   type='subsection',
                   description='How people are employed.'),
            OBSTag(id='families',
                   name="Families",
                   type='subsection',
                   description='Familial arrangements of people and households.'),
            OBSTag(id='language',
                   name="Language",
                   type='subsection',
                   description='What languages people speak.'),
            OBSTag(id='age_gender',
                   name='Age and Gender',
                   type='subsection',
                   description='Population breakdowns by age and gender.'),
            OBSTag(id='nationality',
                   name='Nationality',
                   type='subsection',
                   description='''Population breakdowns by nationality and place of birth.''',),
            OBSTag(id='race_ethnicity',
                   name='Race and Ethnicity',
                   type='subsection',
                   description='''Population breakdowns by race and ethnicity. '''),
            OBSTag(id='transportation',
                   name='Transportation',
                   type='subsection',
                   description='How do people move from place to place?'),
            OBSTag(id='boundary',
                   name='Boundaries',
                   type='subsection',
                   description='Political, administrative, and census-based boundaries.'),
            OBSTag(id='religion',
                   name='Religion',
                   type='subsection',
                   description='Breakdowns of the population by religion.'),
            OBSTag(id='migration',
                   name='Migration',
                   type='subsection',
                   description='Patterns of migration.'),
            OBSTag(id='health',
                   name='Health',
                   type='subsection',
                   description='Breakdowns of the population by health.'),
            OBSTag(id='commerce_economy',
                   name='Commerce and Economy',
                   type='subsection',
                   description='Broader measures of economic and commercial activity.'),
            OBSTag(id='business_demography',
                   name='Business Demography',
                   type='subsection',
                   description='Measures of enterprise growth and decline.'),
            OBSTag(id='segments',
                   name='Population segments',
                   type='subsection',
                   description='Segmentations of the population.'),
            OBSTag(id='society',
                   name='Society',
                   type='subsection',
                   description='Measures of society quality of life'),
            OBSTag(id='energy',
                   name='Energy',
                   type='subsection',
                   description='Measures related to energy production and consumption.'),
            OBSTag(id='environmental',
                   name='Environmental',
                   type='subsection',
                   description='Attributes of the natural environment'),
            OBSTag(id='roads',
                   name='Roads',
                   type='subsection',
                   description=''),
            OBSTag(id='names',
                   name='Proper names',
                   type='subsection',
                   description='Proper names for boundaries and other features'),
            OBSTag(id='poi',
                   name='Points of Interest',
                   type='subsection',
                   description=''),
        ] class UnitTags(TagsTask):

    def version(self):
        return 11

    def tags(self):
        return [
            OBSTag(id='index',
                   name='Index',
                   type='unit',
                   description=''),
            OBSTag(id='people',
                   name='People',
                   type='unit',
                   description=''),
            OBSTag(id='households',
                   name='Households',
                   type='unit',
                   description=''),
            OBSTag(id='housing_units',
                   name='Housing Units',
                   type='unit',
                   description=''),
            OBSTag(id='money',
                   name='Money',
                   type='unit',
                   description=''),
            OBSTag(id='ratio',
                   name='Ratio',
                   type='unit',
                   description=''),
            OBSTag(id='years',
                   name='Years',
                   type='unit',
                   description=''),
            OBSTag(id='minutes',
                   name='Minutes',
                   type='unit',
                   description=''),
            OBSTag(id='days',
                   name='Days',
                   type='unit',
                   description=''),
            OBSTag(id='weeks',
                   name='Weeks',
                   type='unit',
                   description=''),
            OBSTag(id='nights',
                   name='Nights',
                   type='unit',
                   description=''),
            OBSTag(id='telephones',
                   name='Telephones',
                   type='unit',
                   description=''),
            OBSTag(id='vehicles',
                   name='Vehicles',
                   type='unit',
                   description=''),
            OBSTag(id='businesses',
                   name='Businesses',
                   type='unit',
                   description=''),
            OBSTag(id='education_level',
                   name='Level of education',
                   type='unit',
                   description=''),
            OBSTag(id='segmentation',
                   name='Segmentation',
                   type='unit',
                   description=''),
            OBSTag(id='rooms',
                   name='Rooms',
                   type='unit',
                   description=''),
            OBSTag(id='beds',
                   name='Beds',
                   type='unit',
                   description=''),
            OBSTag(id='family_unit',
                   name='Families',
                   type='unit',
                   description=''),
            OBSTag(id='hours',
                   name='Hours',
                   type='unit',
                   description=''),
            OBSTag(id='crimes',
                   name='Crimes',
                   type='unit',
                   description=''),
            OBSTag(id='tonnes',
                   name='Metric Tonnes',
                   type='unit',
                   description=''),
            OBSTag(id='kilometres',
                   name='Kilometres',
                   type='unit',
                   description=''),
            OBSTag(id='inches',
                   name='Inches',
                   type='unit',
                   description=''),
            OBSTag(id='km2',
                   name='Kilometers squared',
                   type='unit',
                   description=''),
            OBSTag(id='tax_consumption_units',
                   name='Tax Consumption Units',
                   type='unit',
                   description=' CU for the first adult in the household, '
                               ' 0.5 CU for the other persons aged 14 years or older, '
                               ' 0.3 CU for the children under 14 years. '),
        ] class LicenseTags(TagsTask):

    def version(self):
        return 3

    def tags(self):
        return [
            OBSTag(id='cc-by-4',
                   name='CC-BY 4.0',
                   type='license',
                   description=''),
            OBSTag(id='no-restrictions',
                   name='Unrestricted',
                   type='license',
                   description='You may do whatever you want with this information'),
            OBSTag(id='uk_ogl',
                   name='UK Open Government Licence (OGL)',
                   type='license',
                   description='The Licensor grants you a worldwide, royalty-free, perpetual, non-exclusive licence to use the Information subject to the conditions `here <http://www.nationalarchives.gov.uk/doc/open-government-licence/version/2/>`_.'),
            OBSTag(id='uk_ed_datashare',
                   name='Edinburgh DataShare',
                   type='license',
                   description='Conditions `here <https://datashare.is.ed.ac.uk/bitstream/handle/10283/2405/license.txt?sequence=3&isAllowed=y>`_.'),
            OBSTag(id='ine_property',
                   name='National Statistics Institute (INE) Property',
                   type='license',
                   description='http://www.ine.es/ss/Satellite?L=1&c=Page&cid=1254735849170&p=1254735849170&pagename=Ayuda%2FINELayout#'),
            OBSTag(id='zillow',
                   name='Zillow Group Data',
                   type='license',
                   description='http://www.zillow.com/research/data/. All data accessed and downloaded from this page is free for public use by consumers, media, analysts, academics etc., consistent with our published Terms of Use. Proper and clear attribution of all data to Zillow is required.'),
            OBSTag(id='eurostat_copyright',
                   name='Eurostat Copyright',
                   type='license',
                   description='''
                               Eurostat has a policy of encouraging free re-use of its data, both for
                               non-commercial and commercial purposes. All statistical
                               data, metadata, content of web pages or other dissemination
                               tools, official publications and other documents published
                               on its website, with the exceptions listed below, can be
                               reused without any payment or written licence provided that:
                               the source is indicated as Eurostat; when re-use involves
                               modifications to the data or text, this must be stated
                               clearly to the end user of the information. `Full copyright
                               notice
                               <http://ec.europa.eu/eurostat/about/our-partners/copyright>`_.'''),
            OBSTag(id='us_government_works',
                   name='U.S. Government Works',
                   type='license',
                   description='''
                               United States government creative works, including writing, images,
                               and computer code, are usually prepared by officers or employees
                               of the United States government as part of their official duties.
                               A government work is generally not subject to copyright in the United States
                               and there is generally no copyright restriction on reproduction,
                               derivative works, distribution, performance, or display of a government work.
                               Unless the work falls under an exception, anyone may, without restriction under
                               U.S. copyright laws, reproduce the work in print or digital form,
                               create derivative works, perform the work publicly, display the work,
                               distribute copies or digitally transfer the work to the public by sale
                               or other transfer of ownership, or by rental, lease, or lending.
                               `Full copyright notice
                               <https://www.usa.gov/government-works>`_.'''),
        ] class GeoidColumns(ColumnsTask):
    '''
    Used for external dependencies on Tiger.

    This creates two different geoid columns
    (GEOID_SUMLEVEL_COLUMN for the SumLevels geometries and
    GEOID_SHORELINECLIPPED_COLUMN for the ShorelineClipped geometries).

    This allows external tables to depend on both shoreline clipped and non-shoreline clipped geometries.
    '''

    year = IntParameter()

    def version(self):
        return 8

    def requires(self):
        return {
            'raw': GeomColumns(year=self.year),
            'clipped': ClippedGeomColumns(year=self.year)
        }

    def columns(self):
        cols = OrderedDict()
        clipped = self.input()['clipped']
        for colname, coltarget in self.input()['raw'].items():
            col = coltarget._column
            cols[colname + GEOID_SHORELINECLIPPED_COLUMN] = OBSColumn(
                type='Text',
                name=col.name + ' Geoids',
                weight=0,
                targets={
                    clipped[colname + '_clipped']._column: GEOM_REF
                }
            )
            cols[colname + GEOID_SUMLEVEL_COLUMN] = OBSColumn(
                type='Text',
                name=col.name + ' Geoids',
                weight=0,
                targets={
                    col: GEOM_REF,
                }
            )

        return cols class SumLevel(TableTask):

    geography = Parameter()
    year = IntParameter()

    @property
    def geoid(self):
        return SUMLEVELS[self.geography]['fields']['geoid']

    @property
    def aland(self):
        return SUMLEVELS[self.geography]['fields']['aland']

    @property
    def awater(self):
        return SUMLEVELS[self.geography]['fields']['awater']

    @property
    def input_tablename(self):
        return SUMLEVELS[self.geography]['table'] + SIMPLIFIED_SUFFIX

    def version(self):
        return 15

    def requires(self):
        if self.geography == BLOCK:
            tiger = SimplifyGeoByState(geography=self.geography, year=self.year)
        else:
            tiger = SimplifiedDownloadTiger(geography=self.geography, year=self.year)
        return {
            'attributes': Attributes(),
            'geoids': GeoidColumns(year=self.year),
            'geoms': GeomColumns(year=self.year),
            'data': tiger,
        }

    def columns(self):
        input_ = self.input()
        return OrderedDict([
            ('geoid', input_['geoids'][self.geography + '_{}'.format(self.year) + GEOID_SUMLEVEL_COLUMN]),
            ('the_geom', input_['geoms'][self.geography + '_{}'.format(self.year)]),
            ('aland', input_['attributes']['aland']),
            ('awater', input_['attributes']['awater']),
        ])

    def table_timespan(self):
        return get_timespan(str(self.year))

    # TODO: https://github.com/CartoDB/bigmetadata/issues/435
    def targets(self):
        return {
            OBSTable(id='.'.join([self.schema(), self.name()])): GEOM_REF,
        }

    def populate(self):
        session = current_session()
        from_clause = '{inputschema}.{input_tablename}'.format(
            inputschema='tiger' + str(self.year),
            input_tablename=self.input_tablename,
        )
        in_colnames = [self.geoid, 'geom', self.aland, self.awater]

        out_colnames = list(self.columns().keys())
        session.execute('INSERT INTO {output} ({out_colnames}) '
                        'SELECT {in_colnames} '
                        'FROM {from_clause} '.format(
                            output=self.output().table,
                            in_colnames=', '.join(in_colnames),
                            out_colnames=', '.join(out_colnames),
                            from_clause=from_clause
                        )) class ShorelineClip(TableTask):
    '''
    Clip the provided geography to shoreline.
    '''

    # MTFCC meanings:
    # http://www2.census.gov/geo/pdfs/maps-data/data/tiger/tgrshp2009/TGRSHP09AF.pdf

    year = IntParameter()
    geography = Parameter()

    def version(self):
        return 10

    def requires(self):
        if self.geography == BLOCK:
            tiger = SimplifiedUnionTigerWaterGeomsByState(year=self.year, geography=self.geography)
        else:
            tiger = SimplifiedUnionTigerWaterGeoms(year=self.year, geography=self.geography)
        return {
            'data': tiger,
            'geoms': ClippedGeomColumns(year=self.year),
            'geoids': GeoidColumns(year=self.year),
            'attributes': Attributes(),
            'geonames': GeonameColumns(year=self.year),
        }

    def columns(self):
        return OrderedDict([
            ('geoid', self.input()['geoids'][self.geography + '_{}'.format(self.year) + GEOID_SHORELINECLIPPED_COLUMN]),
            ('the_geom', self.input()['geoms'][self.geography + '_{}'.format(self.year) + '_clipped']),
            ('aland', self.input()['attributes']['aland'])
        ])

    def table_timespan(self):
        return get_timespan(str(self.year))

    # TODO: https://github.com/CartoDB/bigmetadata/issues/435
    def targets(self):
        return {
            OBSTable(id='.'.join([self.schema(), self.name()])): GEOM_REF,
        }

    def populate(self):
        session = current_session()

        stmt = ('''INSERT INTO {output}
                   SELECT
                     geoid,
                     ST_Union(ARRAY(
                       SELECT ST_MakePolygon(ST_ExteriorRing(
                         (ST_Dump(ST_CollectionExtract(the_geom, 3))).geom
                       ))
                     )),
                     aland
                   FROM {input}'''.format(
                    output=self.output().table,
                    input=self.input()['data'].table), )[0]
        session.execute(stmt) GEOID_SUMLEVEL_COLUMN = "_geoidsl" GEOID_SHORELINECLIPPED_COLUMN = "_geoidsc" def get_timespan(timespan_id):
    ts_id, ts_alias, ts_name, ts_description, ts_timespan = parse_timespan(timespan_id)
    session = current_session()
    return OBSTimespan.as_unique(session, ts_id, id=ts_id, alias=ts_alias, name=ts_name,
                                 description=ts_description, timespan=ts_timespan)
from tasks.base_tasks import (ColumnsTask, TempTableTask, TableTask, RepoFileUnzipTask, TagsTask,
                              CSV2TempTableTask)
from tasks.util import underscore_slugify, copyfile
from tasks.meta import current_session, DENOMINATOR, UNIVERSE
from tasks.us.naics import (NAICS_CODES, is_supersector, is_sector, is_public_administration,
                            get_parent_code)
from tasks.meta import OBSColumn, OBSTag, GEOM_REF
from tasks.tags import SectionTags, SubsectionTags, UnitTags, LicenseTags
from tasks.us.census.tiger import (GeoidColumns, SumLevel, ShorelineClip,
                                   GEOID_SUMLEVEL_COLUMN, GEOID_SHORELINECLIPPED_COLUMN)
from lib.timespan import get_timespan
from collections import OrderedDict
from luigi import IntParameter, Parameter, WrapperTask
import os
import glob
            weight=5,
            # How this measure was derived, for example "sum", "median", "average", etc.
            # In cases of "sum", this means functions downstream can construct estimates
            # for arbitrary geographies
            aggregate='average',
            # Tags are our way of noting aspects of this measure like its unit, the country
            # it's relevant to, and which section(s) of the catalog it should appear in.
            tags=[units['money'], sections['united_states'], subsections['income']],
            targets={cols['qtrly_estabs']: UNIVERSE},
        )
        cols['month3_emplvl'] = OBSColumn(
            id=underscore_slugify('month3_emplvl_{}'.format(code)),
            type='Numeric',
            name='Employees in {} establishments'.format(name),
            description='Number of employees in the third month of a given quarter with the {name} '
                        'industry (NAICS {code}). {name} is {description}.'.format(
                            name=name, code=code, description=description),
            weight=5,
            aggregate='sum',
            tags=[units['people'], sections['united_states'], subsections['employment']],
            targets={parent['month3_emplvl']: DENOMINATOR} if parent else {},
        )
        cols['lq_avg_wkly_wage'] = OBSColumn(
            id=underscore_slugify('lq_avg_wkly_wage_{}'.format(code)),
            type='Numeric',
            name='Average weekly wage location quotient for {} establishments'.format(name),
            description='Location quotient of the average weekly wage for a given quarter relative to '
                        'the U.S. (Rounded to the hundredths place) within the {name} industry (NAICS {code}).'
                        '{name} is {description}.'.format(name=name, code=code, description=description),
            weight=3,
            aggregate=None,
            tags=[units['ratio'], sections['united_states'], subsections['income']],
        )
        cols['lq_qtrly_estabs'] = OBSColumn(
            id=underscore_slugify('lq_qtrly_estabs_{}'.format(code)),
            type='Numeric',
            name='Location quotient of establishments in {}'.format(name),
            description='Location quotient of the quarterly establishment count relative to '
                        'the U.S. (Rounded to the hundredths place) within the {name} industry (NAICS {code}).'
                        '{name} is {description}.'.format(name=name, code=code, description=description),
            weight=3,
            aggregate=None,
            tags=[units['ratio'], sections['united_states'], subsections['commerce_economy']],
        )
        cols['lq_month3_emplvl'] = OBSColumn(
            id=underscore_slugify('lq_month3_emplvl_{}'.format(code)),
            type='Numeric',
            name='Employment level location quotient in {} establishments'.format(name),
            description='Location quotient of the employment level for the third month of a given quarter '
                        'relative to the U.S. (Rounded to the hundredths place) within the {name} '
                        'industry (NAICS {code}). {name} is {description}.'.format(
                            name=name, code=code, description=description),
            weight=3,
            aggregate=None,
            tags=[units['ratio'], sections['united_states'], subsections['employment']],
        )

        source = input_['source']['qcew']
        license = input_['license']['no-restrictions']
        for colname, col in cols.items():
            col.tags.append(source)
            col.tags.append(license)
        return cols


class QCEW(TableTask):

    year = IntParameter()
    qtr = IntParameter()

    def version(self):
        return 4

    def requires(self):
        requirements = {
            'data': SimpleQCEW(year=self.year, qtr=self.qtr),
            'geoid_cols': GeoidColumns(year=TIGER_YEAR),
            'naics': OrderedDict(),
            'sumlevel': SumLevel(year=TIGER_YEAR, geography='county'),
            'shorelineclip': ShorelineClip(year=TIGER_YEAR, geography='county'),
        }
        for naics_code in NAICS_CODES.keys():
            if not is_public_administration(naics_code):
                # Only include the more general NAICS codes
                if is_supersector(naics_code) or is_sector(naics_code) or naics_code == '10':
                    requirements['naics'][naics_code] = QCEWColumns(
                        naics_code=naics_code
                    )
        return requirements

    def targets(self):
        return {
            self.input()['shorelineclip'].obs_table: GEOM_REF,
            self.input()['sumlevel'].obs_table: GEOM_REF,
        }

    def table_timespan(self):
        return get_timespan('{year}Q{qtr}'.format(year=self.year, qtr=self.qtr))

    def columns(self):
        # Here we assemble an OrderedDict using our requirements to specify the
        # columns that go into this table.
        # The column name
        input_ = self.input()
        cols = OrderedDict([
            ('area_fipssl', input_['geoid_cols']['county_{}{}'.format(TIGER_YEAR, GEOID_SUMLEVEL_COLUMN)]),
            ('area_fipssc', input_['geoid_cols']['county_{}{}'.format(TIGER_YEAR, GEOID_SHORELINECLIPPED_COLUMN)])
        ])
        for naics_code, naics_cols in input_['naics'].items():
            for key, coltarget in naics_cols.items():
                naics_name = NAICS_CODES[naics_code]
                colname = underscore_slugify('{}_{}_{}'.format(
                        key, naics_code, naics_name))
                cols[colname] = coltarget
        return cols

    def populate(self):
        # This select statement transforms the input table, taking advantage of our
        # new column names.
        # The session is automatically committed if there are no errors.

        session = current_session()