Write a Table to a ROOT file
764283
def table_to_root(table, filename, **kwargs):
    
    import root_numpy
    root_numpy.array2root(table.as_array(), filename, **kwargs)
833992
def writef(notebook, nb_file, fmt=None):
    """"""
    if nb_file == '-':
        write(notebook, sys.stdout, fmt)
        return

    _, ext = os.path.splitext(nb_file)
    fmt = copy(fmt or {})
    fmt = long_form_one_format(fmt, update={'extension': ext})

    create_prefix_dir(nb_file, fmt)

    with io.open(nb_file, 'w', encoding='utf-8') as stream:
        write(notebook, stream, fmt)
812877
def write_toml(self, data, path=None):
        """"""
        if path is None:
            path = self.pipfile_location
        data = convert_toml_outline_tables(data)
        try:
            formatted_data = tomlkit.dumps(data).rstrip()
        except Exception:
            document = tomlkit.document()
            for section in ("packages", "dev-packages"):
                document[section] = tomlkit.container.Table()
                # Convert things to inline tables — fancy :)
                for package in data.get(section, {}):
                    if hasattr(data[section][package], "keys"):
                        table = tomlkit.inline_table()
                        table.update(data[section][package])
                        document[section][package] = table
                    else:
                        document[section][package] = tomlkit.string(data[section][package])
            formatted_data = tomlkit.dumps(document).rstrip()

        if (
            vistir.compat.Path(path).absolute()
            == vistir.compat.Path(self.pipfile_location).absolute()
        ):
            newlines = self._pipfile_newlines
        else:
            newlines = DEFAULT_NEWLINES
        formatted_data = cleanup_toml(formatted_data)
        with io.open(path, "w", newline=newlines) as f:
            f.write(formatted_data)
        # pipfile is mutated!
        self.clear_pipfile_cache()
192707
def write_files(template, destination='./dxf'):
    
    os.makedirs(destination)
    for key, value in template.items():
        with open(os.path.join(destination, key), 'w') as f:
            f.write(replace_whitespace(value, insert=False))
1028206
def write_tables_to_fits(filepath, tablelist, clobber=False,
                         namelist=None, cardslist=None, hdu_list=None):
    
    outhdulist = [fits.PrimaryHDU()]
    rmlist = []
    for i, table in enumerate(tablelist):
        ft_name = "%s._%i" % (filepath, i)
        rmlist.append(ft_name)
        try:
            os.unlink(ft_name)
        except:
            pass
        table.write(ft_name, format="fits")
        ft_in = fits.open(ft_name)
        if namelist:
            ft_in[1].name = namelist[i]
        if cardslist:
            for k, v in cardslist[i].items():
                ft_in[1].header[k] = v
        ft_in[1].update()
        outhdulist += [ft_in[1]]

    if hdu_list is not None:
        for h in hdu_list:
            outhdulist.append(h)

    fits.HDUList(outhdulist).writeto(filepath, overwrite=clobber)
    for rm in rmlist:
        os.unlink(rm)
421077
def write_table(self):
        

        tags = _get_tags_module()

        with self._logger:
            self._verify_property()
            self._preprocess()

            if typepy.is_not_null_string(self.table_name):
                self._table_tag = tags.table(id=sanitize_python_var_name(self.table_name))
                self._table_tag += tags.caption(MultiByteStrDecoder(self.table_name).unicode_str)
            else:
                self._table_tag = tags.table()

            try:
                self._write_header()
            except EmptyHeaderError:
                pass

            self._write_body()
882737
def writeTable(self, tableName):
        
        lock_and_call(
            lambda: self._impl.writeTable(tableName),
            self._lock
        )
943994
def build(self, root="runs"):
        

        for d, control in self.iter(root):
            _mkdirs(d)
            with open(os.path.join(d, self.control_name), 'w') as fp:
                json.dump(control, fp, indent=self.indent)
                # RJSON and some other tools like a trailing newline
                fp.write('\n')
430545
def dump2sqlite(records, output_file):
    """"""
    results_keys = list(records.results[0].keys())
    pad_data = []

    for key in REQUIRED_KEYS:
        if key not in results_keys:
            results_keys.append(key)
            pad_data.append("")

    conn = sqlite3.connect(os.path.expanduser(output_file), detect_types=sqlite3.PARSE_DECLTYPES)

    # in each row there needs to be data for every column
    # last column is current time
    pad_data.append(datetime.datetime.utcnow())

    to_db = [list(row.values()) + pad_data for row in records.results]

    cur = conn.cursor()
    cur.execute(
        "CREATE TABLE testcases ({},sqltime TIMESTAMP)".format(
            ",".join("{} TEXT".format(key) for key in results_keys)
        )
    )
    cur.executemany(
        "INSERT INTO testcases VALUES ({},?)".format(",".join(["?"] * len(results_keys))), to_db
    )

    if records.testrun:
        cur.execute("CREATE TABLE testrun (testrun TEXT)")
        cur.execute("INSERT INTO testrun VALUES (?)", (records.testrun,))

    conn.commit()
    conn.close()

    logger.info("Data written to '%s'", output_file)
1046881
def write_table_file(self, job_table_file=None, file_table_file=None):
        """"""
        if self._table is None:
            raise RuntimeError("No table to write")
        if self._table_ids is None:
            raise RuntimeError("No ID table to write")
        if job_table_file is not None:
            self._table_file = job_table_file
        if self._table_file is None:
            raise RuntimeError("No output file specified for table")
        write_tables_to_fits(self._table_file, [self._table, self._table_ids], clobber=True,
                             namelist=['JOB_ARCHIVE', 'FILE_IDS'])
        self._file_archive.write_table_file(file_table_file)
644116
def set_roots(self, uproot_with=None):
        ''' 

        '''

        # Check for TREE_DIR
        self.treedir = os.environ.get('TREE_DIR', None) if not uproot_with else uproot_with
        if not self.treedir:
            treefilepath = os.path.dirname(os.path.abspath(__file__))
            if 'python/' in treefilepath:
                self.treedir = treefilepath.rsplit('/', 2)[0]
            else:
                self.treedir = treefilepath
            self.treedir = treefilepath
            os.environ['TREE_DIR'] = self.treedir

        # Check sas_base_dir
        if 'SAS_BASE_DIR' in os.environ:
            self.sasbasedir = os.environ["SAS_BASE_DIR"]
        else:
            self.sasbasedir = os.path.expanduser('~/sas')

        # make the directories
        if not os.path.isdir(self.sasbasedir):
            os.makedirs(self.sasbasedir)
106689
def write_tree(zipf, src_directory, dst_directory):
    
    if not os.path.exists(src_directory):
        abort('Tree ' + src_directory + ' does not exist.')
    for root, _, files in os.walk(src_directory):
        for filename in files:
            if not filename.endswith(('.py', '.pem')):
                continue
            fullname = os.path.join(root, filename)
            arcname = fullname.replace(src_directory, dst_directory)
            zipf.write(fullname, arcname=arcname)
798221
def sqlite_dump_shell(self, script_path):
        """"""
        # First the schema #
        shell_output('mdb-schema "%s" sqlite >> "%s"' % (self.path, script_path))
        # Start a transaction, speeds things up when importing #
        script_path.append("\n\n\nBEGIN TRANSACTION;\n")
        # Then export every table #
        for table in self.tables:
            command = 'mdb-export -I sqlite "%s" "%s" >> "%s"'
            shell_output(command % (self.path, table, script_path))
        # End the transaction
        script_path.append("\n\n\nEND TRANSACTION;\n")
754716
def write_table_to_file(self, dtype, custom_name=None, append=False, dir_path=None):
        
        if custom_name:
            fname = custom_name
        else:
            fname = self.filenames[dtype]
        if not dir_path:
            dir_path=self.directory
        if dtype in self.tables:
            write_df = self.remove_names(dtype)
            outfile = self.tables[dtype].write_magic_file(custom_name=fname,
                                                          dir_path=dir_path,
                                                          append=append, df=write_df)
        return outfile
423777
def build(
    root, source_module, output_dir,
    json_dump=False, ignore_modules=None, index_filename='index'
):
    '''
    
    '''
    if root.endswith('/'):
        root = root[:-1]

    if ignore_modules is None:
        ignore_modules = []
    elif isinstance(ignore_modules, str):
        ignore_modules = ignore_modules.split(',')

    # Ensure output_dir format (no / at start, / at end)
    if output_dir.startswith('/'):
        output_dir = output_dir[1:]

    if not output_dir.endswith('/'):
        output_dir = '{}/'.format(output_dir)

    # Apply root to it, make the directory if not exists
    output_dir = '{}/{}'.format(root, output_dir)
    if not path.isdir(output_dir):
            makedirs(output_dir)

    if source_module == '.':
        source_dir = '{}/'.format(root)
    else:
        source_dir = '{}/{}/'.format(root, source_module.replace('.', os.sep))

    # Cd into the source directory
    chdir(source_dir)
    # And build the module list
    module_list = _build_module_list(
        source_module,
        index_filename=index_filename,
        ignore_modules=ignore_modules
    )

    # Cd back to old directory
    chdir(root)
    # And parse all the modules
    _parse_module_list(module_list)

    # Cd inot the target directory
    chdir(output_dir)
    # Finally, write the module list to our output dir
    _write_docs(module_list, output_dir)

    if json_dump:
        print json.dumps(module_list, indent=4)
1317954
def save(self, name=None, path=None):
        
        if path :
            name = os.path.join(path,name)

        try:
            self._create_table_xml_file(self.etree, name)
        except (Exception,) as e:
            print(e)
            return False

        return True
344330
def write_table(table, filename):
    
    try:
        if os.path.exists(filename):
            os.remove(filename)
        table.write(filename)
        log.info("Wrote {0}".format(filename))
    except Exception as e:
        if "Format could not be identified" not in e.message:
            raise e
        else:
            fmt = os.path.splitext(filename)[-1][1:].lower()  # extension sans '.'
            raise Exception("Cannot auto-determine format for {0}".format(fmt))
    return