text:
'''
Hartree-Fock for periodic systems with k-point sampling

See Also:
    hf.py : Hartree-Fock for periodic systems at a single k-point
'''

import sys

from functools import reduce
import numpy as np
import scipy.linalg
import h5py
from pyscf.pbc.scf import hf as pbchf
from pyscf import lib
from pyscf.scf import hf as mol_hf
from pyscf.lib import logger
from pyscf.pbc.gto import ecp
from pyscf.pbc.scf import addons
from pyscf.pbc.scf import chkfile  # noqa
from pyscf.pbc import tools
from pyscf.pbc import df
from pyscf.pbc.scf.rsjk import RangeSeparatedJKBuilder
from pyscf.pbc.lib.kpts import KPoints
from pyscf import __config__

WITH_META_LOWDIN = getattr(__config__, 'pbc_scf_analyze_with_meta_lowdin', True)
PRE_ORTH_METHOD = getattr(__config__, 'pbc_scf_analyze_pre_orth_method', 'ANO')
CHECK_COULOMB_IMAG = getattr(__config__, 'pbc_scf_check_coulomb_imag', True)

def get_ovlp(mf, cell=None, kpts=None):
    '''Get the overlap AO matrices at sampled k-points.

    Args:
        kpts : (nkpts, 3) ndarray

    Returns:
        ovlp_kpts : (nkpts, nao, nao) ndarray
    '''
    if cell is None: cell = mf.cell
    if kpts is None: kpts = mf.kpts
    # Avoid pbcopt's prescreening in the lattice sum, for better accuracy
    s = cell.pbc_intor('int1e_ovlp', hermi=0, kpts=kpts,
                       pbcopt=lib.c_null_ptr())
    s = lib.asarray(s)
    hermi_error = abs(s - s.conj().transpose(0,2,1)).max()
    if hermi_error > cell.precision and hermi_error > 1e-12:
        logger.warn(mf, '%.4g error found in overlap integrals. '
                    'cell.precision  or  cell.rcut  can be adjusted to '
                    'improve accuracy.', hermi_error)

    cond = np.max(lib.cond(s))
    if cond * cell.precision > 1e2:
        prec = 1e2 / cond
        rmin = max([cell.bas_rcut(ib, prec) for ib in range(cell.nbas)])
        if cell.rcut < rmin:
            logger.warn(mf, 'Singularity detected in overlap matrix.  '
                        'Integral accuracy may be not enough.\n      '
                        'You can adjust  cell.precision  or  cell.rcut  to '
                        'improve accuracy.  Recommended values are\n      '
                        'cell.precision = %.2g  or smaller.\n      '
                        'cell.rcut = %.4g  or larger.', prec, rmin)
    return s

def get_hcore(mf, cell=None, kpts=None):
    '''Get the core Hamiltonian AO matrices at sampled k-points.

    Args:
        kpts : (nkpts, 3) ndarray

    Returns:
        hcore : (nkpts, nao, nao) ndarray
    '''
    if cell is None: cell = mf.cell
    if kpts is None: kpts = mf.kpts
    if cell.pseudo:
        nuc = lib.asarray(mf.with_df.get_pp(kpts))
    else:
        nuc = lib.asarray(mf.with_df.get_nuc(kpts))
    if len(cell._ecpbas) > 0:
        nuc += lib.asarray(ecp.ecp_int(cell, kpts))
    t = lib.asarray(cell.pbc_intor('int1e_kin', 1, 1, kpts))
    return nuc + t

def get_j(mf, cell, dm_kpts, kpts, kpts_band=None):
    '''Get the Coulomb (J) AO matrix at sampled k-points.

    Args:
        dm_kpts : (nkpts, nao, nao) ndarray or a list of (nkpts,nao,nao) ndarray
            Density matrix at each k-point.  If a list of k-point DMs, eg,
            UHF alpha and beta DM, the alpha and beta DMs are contracted
            separately.  It needs to be Hermitian.

    Kwargs:
        kpts_band : (k,3) ndarray
            A list of arbitrary "band" k-points at which to evalute the matrix.

    Returns:
        vj : (nkpts, nao, nao) ndarray
        or list of vj if the input dm_kpts is a list of DMs
    '''
    return df.FFTDF(cell).get_jk(dm_kpts, kpts, kpts_band, with_k=False)[0]

def get_jk(mf, cell, dm_kpts, kpts, kpts_band=None, with_j=True, with_k=True,
           omega=None, **kwargs):
    '''Get the Coulomb (J) and exchange (K) AO matrices at sampled k-points.

    Args:
        dm_kpts : (nkpts, nao, nao) ndarray
            Density matrix at each k-point. It needs to be Hermitian.

    Kwargs:
        kpts_band : (3,) ndarray
            A list of arbitrary "band" k-point at which to evalute the matrix.

    Returns:
        vj : (nkpts, nao, nao) ndarray
        vk : (nkpts, nao, nao) ndarray
        or list of vj and vk if the input dm_kpts is a list of DMs
    '''
    return df.FFTDF(cell).get_jk(dm_kpts, kpts, kpts_band, with_j, with_k,
                                 omega, exxdiv=mf.exxdiv)

def get_fock(mf, h1e=None, s1e=None, vhf=None, dm=None, cycle=-1, diis=None,
             diis_start_cycle=None, level_shift_factor=None, damp_factor=None):
    h1e_kpts, s_kpts, vhf_kpts, dm_kpts = h1e, s1e, vhf, dm
    if h1e_kpts is None: h1e_kpts = mf.get_hcore()
    if vhf_kpts is None: vhf_kpts = mf.get_veff(mf.cell, dm_kpts)
    f_kpts = h1e_kpts + vhf_kpts
    if cycle < 0 and diis is None:  # Not inside the SCF iteration
        return f_kpts

    if diis_start_cycle is None:
        diis_start_cycle = mf.diis_start_cycle
    if level_shift_factor is None:
        level_shift_factor = mf.level_shift
    if damp_factor is None:
        damp_factor = mf.damp
    if s_kpts is None: s_kpts = mf.get_ovlp()
    if dm_kpts is None: dm_kpts = mf.make_rdm1()

    if 0 <= cycle < diis_start_cycle-1 and abs(damp_factor) > 1e-4:
        f_kpts = [mol_hf.damping(s1e, dm_kpts[k] * 0.5, f_kpts[k], damp_factor)
                  for k, s1e in enumerate(s_kpts)]
    if diis and cycle >= diis_start_cycle:
        f_kpts = diis.update(s_kpts, dm_kpts, f_kpts, mf, h1e_kpts, vhf_kpts)
    if abs(level_shift_factor) > 1e-4:
        f_kpts = [mol_hf.level_shift(s, dm_kpts[k], f_kpts[k], level_shift_factor)
                  for k, s in enumerate(s_kpts)]
    return lib.asarray(f_kpts)

def get_fermi(mf, mo_energy_kpts=None, mo_occ_kpts=None):
    '''Fermi level
    '''
    if mo_energy_kpts is None: mo_energy_kpts = mf.mo_energy
    if mo_occ_kpts is None: mo_occ_kpts = mf.mo_occ

    # mo_energy_kpts and mo_occ_kpts are k-point RHF quantities
    assert (mo_energy_kpts[0].ndim == 1)
    assert (mo_occ_kpts[0].ndim == 1)

    # occ array in mo_occ_kpts may have different size. See issue #250
    nocc = sum(mo_occ.sum() for mo_occ in mo_occ_kpts) / 2
    # nocc may not be perfect integer when smearing is enabled
    nocc = int(nocc.round(3))
    fermi = np.sort(np.hstack(mo_energy_kpts))[nocc-1]

    for k, mo_e in enumerate(mo_energy_kpts):
        mo_occ = mo_occ_kpts[k]
        if mo_occ[mo_e > fermi].sum() > 1.:
            logger.warn(mf, 'Occupied band above Fermi level: \n'
                        'k=%d, mo_e=%s, mo_occ=%s', k, mo_e, mo_occ)
    return fermi

def get_occ(mf, mo_energy_kpts=None, mo_coeff_kpts=None):
    '''Label the occupancies for each orbital for sampled k-points.

    This is a k-point version of scf.hf.SCF.get_occ
    '''
    if mo_energy_kpts is None: mo_energy_kpts = mf.mo_energy

    nkpts = len(mo_energy_kpts)
    nocc = mf.cell.tot_electrons(nkpts) // 2

    mo_energy = np.sort(np.hstack(mo_energy_kpts))
    fermi = mo_energy[nocc-1]
    mo_occ_kpts = []
    for mo_e in mo_energy_kpts:
        mo_occ_kpts.append((mo_e <= fermi).astype(np.double) * 2)

    if nocc < mo_energy.size:
        logger.info(mf, 'HOMO = %.12g  LUMO = %.12g',
                    mo_energy[nocc-1], mo_energy[nocc])
        if mo_energy[nocc-1]+1e-3 > mo_energy[nocc]:
            logger.warn(mf, 'HOMO %.12g == LUMO %.12g',
                        mo_energy[nocc-1], mo_energy[nocc])
    else:
        logger.info(mf, 'HOMO = %.12g', mo_energy[nocc-1])

    if mf.verbose >= logger.DEBUG:
        np.set_printoptions(threshold=len(mo_energy))
        logger.debug(mf, '     k-point                  mo_energy')
        for k,kpt in enumerate(mf.cell.get_scaled_kpts(mf.kpts)):
            logger.debug(mf, '  %2d (%6.3f %6.3f %6.3f)   %s %s',
                         k, kpt[0], kpt[1], kpt[2],
                         mo_energy_kpts[k][mo_occ_kpts[k]> 0],
                         mo_energy_kpts[k][mo_occ_kpts[k]==0])
        np.set_printoptions(threshold=1000)

    return mo_occ_kpts

def get_grad(mo_coeff_kpts, mo_occ_kpts, fock):
    '''
    returns 1D array of gradients, like non K-pt version
    note that occ and virt indices of different k pts now occur
    in sequential patches of the 1D array
    '''
    nkpts = len(mo_occ_kpts)
    grad_kpts = [mol_hf.get_grad(mo_coeff_kpts[k], mo_occ_kpts[k], fock[k])
                 for k in range(nkpts)]
    return np.hstack(grad_kpts)

def make_rdm1(mo_coeff_kpts, mo_occ_kpts, **kwargs):
    '''One particle density matrices for all k-points.

    Returns:
        dm_kpts : (nkpts, nao, nao) ndarray
    '''
    nkpts = len(mo_occ_kpts)
    dm_kpts = [mol_hf.make_rdm1(mo_coeff_kpts[k], mo_occ_kpts[k])
               for k in range(nkpts)]
    return lib.asarray(dm_kpts)

def energy_elec(mf, dm_kpts=None, h1e_kpts=None, vhf_kpts=None):
    '''Following pyscf.scf.hf.energy_elec()
    '''
    if dm_kpts is None: dm_kpts = mf.make_rdm1()
    if h1e_kpts is None: h1e_kpts = mf.get_hcore()
    if vhf_kpts is None: vhf_kpts = mf.get_veff(mf.cell, dm_kpts)

    nkpts = len(dm_kpts)
    e1 = 1./nkpts * np.einsum('kij,kji', dm_kpts, h1e_kpts)
    e_coul = 1./nkpts * np.einsum('kij,kji', dm_kpts, vhf_kpts) * 0.5
    mf.scf_summary['e1'] = e1.real
    mf.scf_summary['e2'] = e_coul.real
    logger.debug(mf, 'E1 = %s  E_coul = %s', e1, e_coul)
    if CHECK_COULOMB_IMAG and abs(e_coul.imag > mf.cell.precision*10):
        logger.warn(mf, "Coulomb energy has imaginary part %s. "
                    "Coulomb integrals (e-e, e-N) may not converge !",
                    e_coul.imag)
    return (e1+e_coul).real, e_coul.real

def analyze(mf, verbose=logger.DEBUG, with_meta_lowdin=WITH_META_LOWDIN,
            **kwargs):
    '''Analyze the given SCF object:  print orbital energies, occupancies;
    print orbital coefficients; Mulliken population analysis; Dipole moment
    '''
    mf.dump_scf_summary(verbose)

    mo_occ = mf.mo_occ
    mo_coeff = mf.mo_coeff
    ovlp_ao = mf.get_ovlp()
    dm = mf.make_rdm1(mo_coeff, mo_occ)
    if with_meta_lowdin:
        return mf.mulliken_meta(mf.cell, dm, s=ovlp_ao, verbose=verbose)
    else:
        raise NotImplementedError
        #return mf.mulliken_pop(mf.cell, dm, s=ovlp_ao, verbose=verbose)

def mulliken_meta(cell, dm_ao_kpts, verbose=logger.DEBUG,
                  pre_orth_method=PRE_ORTH_METHOD, s=None):
    '''A modified Mulliken population analysis, based on meta-Lowdin AOs.

    Note this function only computes the Mulliken population for the gamma
    point density matrix.
    '''
    from pyscf.lo import orth
    if s is None:
        s = get_ovlp(cell)
    log = logger.new_logger(cell, verbose)
    log.note('Analyze output for *gamma point*')
    log.info('    To include the contributions from k-points, transform to a '
             'supercell then run the population analysis on the supercell\n'
             '        from pyscf.pbc.tools import k2gamma\n'
             '        k2gamma.k2gamma(mf).mulliken_meta()')
    log.note("KRHF mulliken_meta")
    dm_ao_gamma = dm_ao_kpts[0,:,:].real
    s_gamma = s[0,:,:].real
    orth_coeff = orth.orth_ao(cell, 'meta_lowdin', pre_orth_method, s=s_gamma)
    c_inv = np.dot(orth_coeff.T, s_gamma)
    dm = reduce(np.dot, (c_inv, dm_ao_gamma, c_inv.T.conj()))

    log.note(' ** Mulliken pop on meta-lowdin orthogonal AOs **')
    return mol_hf.mulliken_pop(cell, dm, np.eye(orth_coeff.shape[0]), log)

def canonicalize(mf, mo_coeff_kpts, mo_occ_kpts, fock=None):
    if fock is None:
        dm = mf.make_rdm1(mo_coeff_kpts, mo_occ_kpts)
        fock = mf.get_fock(dm=dm)
    mo_coeff = []
    mo_energy = []
    for k, mo in enumerate(mo_coeff_kpts):
        mo1 = np.empty_like(mo)
        mo_e = np.empty_like(mo_occ_kpts[k])
        occidx = mo_occ_kpts[k] == 2
        viridx = ~occidx
        for idx in (occidx, viridx):
            if np.count_nonzero(idx) > 0:
                orb = mo[:,idx]
                f1 = reduce(np.dot, (orb.T.conj(), fock[k], orb))
                e, c = scipy.linalg.eigh(f1)
                mo1[:,idx] = np.dot(orb, c)
                mo_e[idx] = e
        mo_coeff.append(mo1)
        mo_energy.append(mo_e)
    return mo_energy, mo_coeff

def init_guess_by_chkfile(cell, chkfile_name, project=None, kpts=None):
    '''Read the KHF results from checkpoint file, then project it to the
    basis defined by ``cell``

    Returns:
        Density matrix, 3D ndarray
    '''
    from pyscf.pbc.scf import kuhf
    dm = kuhf.init_guess_by_chkfile(cell, chkfile_name, project, kpts)
    return dm[0] + dm[1]

def dip_moment(cell, dm_kpts, unit='Debye', verbose=logger.NOTE,
               grids=None, rho=None, kpts=np.zeros((1,3))):
    ''' Dipole moment in the cell (is it well defined)?

    Args:
         cell : an instance of :class:`Cell`

         dm_kpts (a list of ndarrays) : density matrices of k-points

    Return:
        A list: the dipole moment on x, y and z components
    '''
    from pyscf.pbc.dft import gen_grid
    from pyscf.pbc.dft import numint
    if grids is None:
        grids = gen_grid.UniformGrids(cell)
    if rho is None:
        rho = numint.KNumInt().get_rho(cell, dm_kpts, grids, kpts, cell.max_memory)
    return pbchf.dip_moment(cell, dm_kpts, unit, verbose, grids, rho, kpts)

def get_rho(mf, dm=None, grids=None, kpts=None):
    '''Compute density in real space
    '''
    from pyscf.pbc.dft import gen_grid
    from pyscf.pbc.dft import numint
    if dm is None:
        dm = mf.make_rdm1()
    if getattr(dm[0], 'ndim', None) != 2:  # KUHF
        dm = dm[0] + dm[1]
    if grids is None:
        grids = gen_grid.UniformGrids(mf.cell)
    if kpts is None:
        kpts = mf.kpts
    ni = numint.KNumInt()
    return ni.get_rho(mf.cell, dm, grids, kpts, mf.max_memory)

def as_scanner(mf):
    import copy
    if isinstance(mf, lib.SinglePointScanner):
        return mf

    logger.info(mf, 'Create scanner for %s', mf.__class__)

    class SCF_Scanner(mf.__class__, lib.SinglePointScanner):
        def __init__(self, mf_obj):
            self.__dict__.update(mf_obj.__dict__)

        def __call__(self, cell_or_geom, **kwargs):
            from pyscf.pbc import gto
            if isinstance(cell_or_geom, gto.Cell):
                cell = cell_or_geom
            else:
                cell = self.cell.set_geom_(cell_or_geom, inplace=False)

            # Cleanup intermediates associated to the pervious mol object
            self.reset(cell)

            if 'dm0' in kwargs:
                dm0 = kwargs.pop('dm0')
            elif self.mo_coeff is None:
                dm0 = None
            elif self.chkfile and h5py.is_hdf5(self.chkfile):
                dm0 = self.from_chk(self.chkfile)
            else:
                dm0 = self.make_rdm1()
                # dm0 form last calculation cannot be used in the current
                # calculation if a completely different system is given.
                # Obviously, the systems are very different if the number of
                # basis functions are different.
                # TODO: A robust check should include more comparison on
                # various attributes between current `mol` and the `mol` in
                # last calculation.
                if dm0.shape[-1] != cell.nao_nr():
                    #TODO:
                    #from pyscf.scf import addons
                    #if numpy.any(last_mol.atom_charges() != mol.atom_charges()):
                    #    dm0 = None
                    #elif non-relativistic:
                    #    addons.project_dm_nr2nr(last_mol, dm0, last_mol)
                    #else:
                    #    addons.project_dm_r2r(last_mol, dm0, last_mol)
                    dm0 = None
            self.mo_coeff = None  # To avoid last mo_coeff being used by SOSCF
            e_tot = self.kernel(dm0=dm0, **kwargs)
            return e_tot

    return SCF_Scanner(mf)

class KSCF(pbchf.SCF):
    '''SCF base class with k-point sampling.

    Compared to molecular SCF, some members such as mo_coeff, mo_occ
    now have an additional first dimension for the k-points,
    e.g. mo_coeff is (nkpts, nao, nao) ndarray

    Attributes:
        kpts : (nks,3) ndarray
            The sampling k-points in Cartesian coordinates, in units of 1/Bohr.
    '''
    conv_tol_grad = getattr(__config__, 'pbc_scf_KSCF_conv_tol_grad', None)
    direct_scf = getattr(__config__, 'pbc_scf_SCF_direct_scf', True)

    def __init__(self, cell, kpts=np.zeros((1,3)),
                 exxdiv=getattr(__config__, 'pbc_scf_SCF_exxdiv', 'ewald')):
        if not cell._built:
            sys.stderr.write('Warning: cell.build() is not called in input\n')
            cell.build()
        self.cell = cell
        mol_hf.SCF.__init__(self, cell)

        self.with_df = df.FFTDF(cell)
        # Range separation JK builder
        self.rsjk = None

        self.exxdiv = exxdiv
        self.kpts = kpts
        self.conv_tol = cell.precision * 10

        self.exx_built = False
        self._keys = self._keys.union(['cell', 'exx_built', 'exxdiv', 'with_df', 'rsjk'])

    @property
    def kpts(self):
        if 'kpts' in self.__dict__:
            # To handle the attribute kpt loaded from chkfile
            self.kpt = self.__dict__.pop('kpts')
        return self.with_df.kpts

    @kpts.setter
    def kpts(self, x):
        self.with_df.kpts = np.reshape(x, (-1,3))
        if self.rsjk:
            self.rsjk.kpts = self.with_df.kpts

    @property
    def mo_energy_kpts(self):
        return self.mo_energy

    @property
    def mo_coeff_kpts(self):
        return self.mo_coeff

    @property
    def mo_occ_kpts(self):
        return self.mo_occ

    def dump_flags(self, verbose=None):
        mol_hf.SCF.dump_flags(self, verbose)
        logger.info(self, '\n')
        logger.info(self, '******** PBC SCF flags ********')
        logger.info(self, 'N kpts = %d', len(self.kpts))
        logger.debug(self, 'kpts = %s', self.kpts)
        logger.info(self, 'Exchange divergence treatment (exxdiv) = %s', self.exxdiv)
        # "vcut_ws" precomputing is triggered by pbc.tools.pbc.get_coulG
        #if self.exxdiv == 'vcut_ws':
        #    if self.exx_built is False:
        #        self.precompute_exx()
        #    logger.info(self, 'WS alpha = %s', self.exx_alpha)
        cell = self.cell
        if ((cell.dimension >= 2 and cell.low_dim_ft_type != 'inf_vacuum') and
            isinstance(self.exxdiv, str) and self.exxdiv.lower() == 'ewald'):
            madelung = tools.pbc.madelung(cell, [self.kpts])
            logger.info(self, '    madelung (= occupied orbital energy shift) = %s', madelung)
            nkpts = len(self.kpts)
            # FIXME: consider the fractional num_electron or not? This maybe
            # relates to the charged system.
            nelectron = float(self.cell.tot_electrons(nkpts)) / nkpts
            logger.info(self, '    Total energy shift due to Ewald probe charge'
                        ' = -1/2 * Nelec*madelung = %.12g',
                        madelung*nelectron * -.5)
        if getattr(self, 'smearing_method', None) is not None:
            logger.info(self, 'Smearing method = %s', self.smearing_method)
        logger.info(self, 'DF object = %s', self.with_df)
        if not getattr(self.with_df, 'build', None):
            # .dump_flags() is called in pbc.df.build function
            self.with_df.dump_flags(verbose)
        return self

    def check_sanity(self):
        mol_hf.SCF.check_sanity(self)
        self.with_df.check_sanity()
        if (isinstance(self.exxdiv, str) and self.exxdiv.lower() != 'ewald' and
            isinstance(self.with_df, df.df.DF)):
            logger.warn(self, 'exxdiv %s is not supported in DF or MDF',
                        self.exxdiv)
        return self

    def build(self, cell=None):
        if cell is None:
            cell = self.cell
        #if self.exxdiv == 'vcut_ws':
        #    self.precompute_exx()

        if 'kpts' in self.__dict__:
            # To handle the attribute kpts loaded from chkfile
            self.kpts = self.__dict__.pop('kpts')

        if self.rsjk:
            if not np.all(self.rsjk.kpts == self.kpts):
                self.rsjk = self.rsjk.__class__(cell, self.kpts)
            self.rsjk.build(direct_scf_tol=self.direct_scf_tol)

        if self.verbose >= logger.WARN:
            self.check_sanity()
        return self

    def get_init_guess(self, cell=None, key='minao'):
        if cell is None:
            cell = self.cell
        dm_kpts = None
        key = key.lower()
        if key == '1e' or key == 'hcore':
            dm_kpts = self.init_guess_by_1e(cell)
        elif getattr(cell, 'natm', 0) == 0:
            logger.info(self, 'No atom found in cell. Use 1e initial guess')
            dm_kpts = self.init_guess_by_1e(cell)
        elif key == 'atom':
            dm = self.init_guess_by_atom(cell)
        elif key[:3] == 'chk':
            try:
                dm_kpts = self.from_chk()
            except (IOError, KeyError):
                logger.warn(self, 'Fail to read %s. Use MINAO initial guess',
                            self.chkfile)
                dm = self.init_guess_by_minao(cell)
        else:
            dm = self.init_guess_by_minao(cell)

        if dm_kpts is None:
            dm_kpts = lib.asarray([dm]*len(self.kpts))

        ne = np.einsum('kij,kji->', dm_kpts, self.get_ovlp(cell)).real
        # FIXME: consider the fractional num_electron or not? This maybe
        # relate to the charged system.
        nkpts = len(self.kpts)
        nelectron = float(self.cell.tot_electrons(nkpts))
        if abs(ne - nelectron) > 1e-7*nkpts:
            logger.debug(self, 'Big error detected in the electron number '
                         'of initial guess density matrix (Ne/cell = %g)!\n'
                         '  This can cause huge error in Fock matrix and '
                         'lead to instability in SCF for low-dimensional '
                         'systems.\n  DM is normalized wrt the number '
                         'of electrons %s', ne/nkpts, nelectron/nkpts)
            dm_kpts *= (nelectron / ne).reshape(-1,1,1)
        return dm_kpts

    def init_guess_by_1e(self, cell=None):
        if cell is None: cell = self.cell
        if cell.dimension < 3:
            logger.warn(self, 'Hcore initial guess is not recommended in '
                        'the SCF of low-dimensional systems.')
        return mol_hf.SCF.init_guess_by_1e(self, cell)

    get_hcore = get_hcore
    get_ovlp = get_ovlp
    get_fock = get_fock
    get_occ = get_occ
    energy_elec = energy_elec
    get_fermi = get_fermi

    def get_j(self, cell=None, dm_kpts=None, hermi=1, kpts=None,
              kpts_band=None, omega=None):
        return self.get_jk(cell, dm_kpts, hermi, kpts, kpts_band,
                           with_k=False, omega=omega)[0]

    def get_k(self, cell=None, dm_kpts=None, hermi=1, kpts=None,
              kpts_band=None, omega=None):
        return self.get_jk(cell, dm_kpts, hermi, kpts, kpts_band,
                           with_j=False, omega=omega)[1]

    def get_jk(self, cell=None, dm_kpts=None, hermi=1, kpts=None, kpts_band=None,
               with_j=True, with_k=True, omega=None, **kwargs):
        if cell is None: cell = self.cell
        if kpts is None: kpts = self.kpts
        if dm_kpts is None: dm_kpts = self.make_rdm1()
        cpu0 = (logger.process_clock(), logger.perf_counter())
        if self.rsjk:
            vj, vk = self.rsjk.get_jk(dm_kpts, hermi, kpts, kpts_band,
                                      with_j, with_k, omega, self.exxdiv)
        else:
            vj, vk = self.with_df.get_jk(dm_kpts, hermi, kpts, kpts_band,
                                         with_j, with_k, omega, self.exxdiv)
        logger.timer(self, 'vj and vk', *cpu0)
        return vj, vk

    def get_veff(self, cell=None, dm_kpts=None, dm_last=0, vhf_last=0, hermi=1,
                 kpts=None, kpts_band=None):
        '''Hartree-Fock potential matrix for the given density matrix.
        See :func:`scf.hf.get_veff` and :func:`scf.hf.RHF.get_veff`
        '''
        if dm_kpts is None:
            dm_kpts = self.make_rdm1()
        if self.rsjk and self.direct_scf:
            # Enable direct-SCF for real space JK builder
            ddm = dm_kpts - dm_last
            vj, vk = self.get_jk(cell, ddm, hermi, kpts, kpts_band)
            return vhf_last + vj - vk * .5
        else:
            vj, vk = self.get_jk(cell, dm_kpts, hermi, kpts, kpts_band)
            return vj - vk * .5

    def analyze(self, verbose=None, with_meta_lowdin=WITH_META_LOWDIN,
                **kwargs):
        if verbose is None: verbose = self.verbose
        return analyze(self, verbose, with_meta_lowdin, **kwargs)

    def get_grad(self, mo_coeff_kpts, mo_occ_kpts, fock=None):
        '''
        returns 1D array of gradients, like non K-pt version
        note that occ and virt indices of different k pts now occur
        in sequential patches of the 1D array
        '''
        if fock is None:
            dm1 = self.make_rdm1(mo_coeff_kpts, mo_occ_kpts)
            fock = self.get_hcore(self.cell, self.kpts) + self.get_veff(self.cell, dm1)
        return get_grad(mo_coeff_kpts, mo_occ_kpts, fock)

    def eig(self, h_kpts, s_kpts):
        nkpts = len(h_kpts)
        eig_kpts = []
        mo_coeff_kpts = []

        for k in range(nkpts):
            e, c = self._eigh(h_kpts[k], s_kpts[k])
            eig_kpts.append(e)
            mo_coeff_kpts.append(c)
        return eig_kpts, mo_coeff_kpts

    def make_rdm1(self, mo_coeff_kpts=None, mo_occ_kpts=None, **kwargs):
        if mo_coeff_kpts is None:
            # Note: this is actually "self.mo_coeff_kpts"
            # which is stored in self.mo_coeff of the scf.hf.RHF superclass
            mo_coeff_kpts = self.mo_coeff
        if mo_occ_kpts is None:
            # Note: this is actually "self.mo_occ_kpts"
            # which is stored in self.mo_occ of the scf.hf.RHF superclass
            mo_occ_kpts = self.mo_occ

        return make_rdm1(mo_coeff_kpts, mo_occ_kpts, **kwargs)

    def get_bands(self, kpts_band, cell=None, dm_kpts=None, kpts=None):
        '''Get energy bands at the given (arbitrary) 'band' k-points.

        Returns:
            mo_energy : (nmo,) ndarray or a list of (nmo,) ndarray
                Bands energies E_n(k)
            mo_coeff : (nao, nmo) ndarray or a list of (nao,nmo) ndarray
                Band orbitals psi_n(k)
        '''
        if cell is None: cell = self.cell
        if dm_kpts is None: dm_kpts = self.make_rdm1()
        if kpts is None: kpts = self.kpts

        kpts_band = np.asarray(kpts_band)
        single_kpt_band = (kpts_band.ndim == 1)
        kpts_band = kpts_band.reshape(-1,3)

        fock = self.get_hcore(cell, kpts_band)
        fock = fock + self.get_veff(cell, dm_kpts, kpts=kpts, kpts_band=kpts_band)
        s1e = self.get_ovlp(cell, kpts_band)
        mo_energy, mo_coeff = self.eig(fock, s1e)
        if single_kpt_band:
            mo_energy = mo_energy[0]
            mo_coeff = mo_coeff[0]
        return mo_energy, mo_coeff

    def init_guess_by_chkfile(self, chk=None, project=None, kpts=None):
        if chk is None: chk = self.chkfile
        if kpts is None: kpts = self.kpts
        return init_guess_by_chkfile(self.cell, chk, project, kpts)
    def from_chk(self, chk=None, project=None, kpts=None):
        return self.init_guess_by_chkfile(chk, project, kpts)

    def dump_chk(self, envs):
        if self.chkfile:
            mol_hf.SCF.dump_chk(self, envs)
            with h5py.File(self.chkfile, 'a') as fh5:
                fh5['scf/kpts'] = self.kpts
        return self

    def mulliken_meta(self, cell=None, dm=None, verbose=logger.DEBUG,
                      pre_orth_method=PRE_ORTH_METHOD, s=None):
        if cell is None: cell = self.cell
        if dm is None: dm = self.make_rdm1()
        if s is None: s = self.get_ovlp(cell)
        return mulliken_meta(cell, dm, s=s, verbose=verbose,
                             pre_orth_method=pre_orth_method)

    def mulliken_pop(self):
        raise NotImplementedError

    get_rho = get_rho

    @lib.with_doc(dip_moment.__doc__)
    def dip_moment(self, cell=None, dm=None, unit='Debye', verbose=logger.NOTE,
                   **kwargs):
        rho = kwargs.pop('rho', None)
        if rho is None:
            rho = self.get_rho(dm)
        if cell is None:
            cell = self.cell
        return dip_moment(cell, dm, unit, verbose, rho=rho, kpts=self.kpts, **kwargs)

    canonicalize = canonicalize

    def density_fit(self, auxbasis=None, with_df=None):
        from pyscf.pbc.df import df_jk
        return df_jk.density_fit(self, auxbasis, with_df=with_df)

    def rs_density_fit(self, auxbasis=None, with_df=None):
        from pyscf.pbc.df import rsdf_jk
        return rsdf_jk.density_fit(self, auxbasis, with_df=with_df)

    def mix_density_fit(self, auxbasis=None, with_df=None):
        from pyscf.pbc.df import mdf_jk
        return mdf_jk.density_fit(self, auxbasis, with_df=with_df)

    def jk_method(self, J='FFTDF', K=None):
        '''
        Set up the schemes to evaluate Coulomb and exchange matrix

        FFTDF: planewave density fitting using Fast Fourier Transform
        AFTDF: planewave density fitting using analytic Fourier Transform
        GDF: Gaussian density fitting
        MDF: Gaussian and planewave mix density fitting
        RS: range-separation JK builder
        RSDF: range-separation density fitting
        '''
        if K is None:
            K = J

        if J != K:
            raise NotImplementedError('J != K')

        if 'DF' in J or 'DF' in K:
            if 'DF' in J and 'DF' in K:
                assert J == K
            else:
                df_method = J if 'DF' in J else K
                self.with_df = getattr(df, df_method)(self.cell, self.kpts)

        if 'RS' in J or 'RS' in K:
            self.rsjk = RangeSeparatedJKBuilder(self.cell, self.kpts)
            self.rsjk.verbose = self.verbose

        # For nuclear attraction
        if J == 'RS' and K == 'RS' and not isinstance(self.with_df, df.GDF):
            self.with_df = df.GDF(self.cell, self.kpts)

        nuc = self.with_df.__class__.__name__
        logger.debug1(self, 'Apply %s for J, %s for K, %s for nuc', J, K, nuc)
        return self

    def stability(self,
                  internal=getattr(__config__, 'pbc_scf_KSCF_stability_internal', True),
                  external=getattr(__config__, 'pbc_scf_KSCF_stability_external', False),
                  verbose=None):
        from pyscf.pbc.scf.stability import rhf_stability
        return rhf_stability(self, internal, external, verbose)

    def newton(self):
        from pyscf.pbc.scf import newton_ah
        return newton_ah.newton(self)

    def sfx2c1e(self):
        from pyscf.pbc.x2c import sfx2c1e
        return sfx2c1e.sfx2c1e(self)
    x2c = x2c1e = sfx2c1e

    def to_rhf(self, mf=None):
        '''Convert the input mean-field object to a KRHF/KROHF/KRKS/KROKS object'''
        return addons.convert_to_rhf(self, mf)

    def to_uhf(self, mf=None):
        '''Convert the input mean-field object to a KUHF/KUKS object'''
        return addons.convert_to_uhf(self, mf)

    def to_ghf(self, mf=None):
        '''Convert the input mean-field object to a KGHF/KGKS object'''
        return addons.convert_to_ghf(self, mf)

    as_scanner = as_scanner

class KRHF(KSCF, pbchf.RHF):
    def check_sanity(self):
        cell = self.cell
        if isinstance(self.kpts, KPoints):
            nkpts = self.kpts.nkpts
        else:
            nkpts = len(self.kpts)
        if cell.spin != 0 and nkpts % 2 != 0:
            logger.warn(self, 'Problematic nelec %s and number of k-points %d '
                        'found in KRHF method.', cell.nelec, nkpts)
        return KSCF.check_sanity(self)

    def convert_from_(self, mf):
        '''Convert given mean-field object to KRHF'''
        addons.convert_to_rhf(mf, self)
        return self

    def nuc_grad_method(self):
        from pyscf.pbc.grad import krhf
        return krhf.Gradients(self)

del (WITH_META_LOWDIN, PRE_ORTH_METHOD)

if __name__ == '__main__':
    from pyscf.pbc import gto
    cell = gto.Cell()
    cell.atom = '''
    He 0 0 1
    He 1 0 1
    '''
    cell.basis = '321g'
    cell.a = np.eye(3) * 3
    cell.mesh = [11] * 3
    cell.verbose = 5
    cell.build()
    mf = KRHF(cell, [2,1,1])
    mf.kernel()
    mf.analyze()


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Delegate (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="org.omg.PortableServer.portable.Delegate interface">
<meta name="keywords" content="orb()">
<meta name="keywords" content="this_object()">
<meta name="keywords" content="poa()">
<meta name="keywords" content="object_id()">
<meta name="keywords" content="default_POA()">
<meta name="keywords" content="is_a()">
<meta name="keywords" content="non_existent()">
<meta name="keywords" content="get_interface_def()">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.omg.PortableServer.portable

Interface Delegate

public interface Delegate

The portability package contains interfaces and classes
 that are designed for and intended to be used by ORB
 implementor. It exposes the publicly defined APIs that
 are used to connect stubs and skeletons to the ORB.
 The Delegate interface provides the ORB vendor specific
 implementation of PortableServer::Servant.
 Conformant to spec CORBA V2.3.1, ptc/00-01-08.pdf

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

POA
default_POA(Servant Self)

The default behavior of this function is to return the
 root POA from the ORB instance associated with the servant.

Object
get_interface_def(Servant self)

This operation returns an object in the Interface Repository
 which provides type information that may be useful to a program.

boolean
is_a(Servant Self,
    String Repository_Id)

This method checks to see if the specified repid is present
 on the list returned by _all_interfaces() or is the
 repository id for the generic CORBA Object.

boolean
non_existent(Servant Self)

This operation is used to check for the existence of the
 Object.

byte[]
object_id(Servant Self)

The method _object_id() is equivalent
 to calling PortableServer::Current::get_object_id.

ORB
orb(Servant Self)

Convenience method that returns the instance of the ORB
 currently associated with the Servant.

POA
poa(Servant Self)

The method _poa() is equivalent to
 calling PortableServer::Current:get_POA.

Object
this_object(Servant Self)

This allows the servant to obtain the object reference for
 the target CORBA Object it is incarnating for that request.

Method Detail

orb

ORB orb(Servant Self)

Convenience method that returns the instance of the ORB
 currently associated with the Servant.

Parameters:

Self - the servant.

Returns:

ORB associated with the Servant.

this_object

Object this_object(Servant Self)

This allows the servant to obtain the object reference for
 the target CORBA Object it is incarnating for that request.

Parameters:

Self - the servant.

Returns:

Object reference associated with the request.

poa

POA poa(Servant Self)

The method _poa() is equivalent to
 calling PortableServer::Current:get_POA.

Parameters:

Self - the servant.

Returns:

POA associated with the servant.

object_id

byte[] object_id(Servant Self)

The method _object_id() is equivalent
 to calling PortableServer::Current::get_object_id.

Parameters:

Self - the servant.

Returns:

ObjectId associated with this servant.

default_POA

POA default_POA(Servant Self)

The default behavior of this function is to return the
 root POA from the ORB instance associated with the servant.

Parameters:

Self - the servant.

Returns:

POA associated with the servant class.

is_a

boolean is_a(Servant Self,
             String Repository_Id)

This method checks to see if the specified repid is present
 on the list returned by _all_interfaces() or is the
 repository id for the generic CORBA Object.

Parameters:

Self - the servant.

Repository_Id - the repository_id to be checked in the
            repository list or against the id of generic CORBA
            object.

Returns:

boolean indicating whether the specified repid is
         in the list or is same as that got generic CORBA
         object.

non_existent

boolean non_existent(Servant Self)

This operation is used to check for the existence of the
 Object.

Parameters:

Self - the servant.

Returns:

boolean true to indicate that object does not exist,
                 and false otherwise.

get_interface_def

Object get_interface_def(Servant self)

This operation returns an object in the Interface Repository
 which provides type information that may be useful to a program.

Parameters:

self - the servant.

Returns:

type information corresponding to the object.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.

redpajama_set_name: RedPajamaGithub


text:
package org.mpisws.p2p.transport.util;

import java.io.IOException;

public class InsufficientBytesException extends IOException {
  private int needed;
  private int available;
  public InsufficientBytesException(int needed, int available) {
    super("Not enough bytes available.  Need "+needed+" have "+available);
    this.needed = needed;
    this.available = available;
  }

  private int getBytesAvailable() {
    return available;
  }

  private int getBytesNeeded() {
    return needed;
  }

}


text:
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';
async function main(
  projectId = 'YOUR_PROJECT_ID',
  computeRegion = 'YOUR_REGION_NAME',
  filter = 'FILTER_EXPRESSION'
) {
  // [START automl_tables_list_datasets]
  const automl = require('@google-cloud/automl');
  const util = require('util');
  const client = new automl.v1beta1.AutoMlClient();

  /**
   * Demonstrates using the AutoML client to list all datasets.
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = '[PROJECT_ID]' e.g., "my-gcloud-project";
  // const computeRegion = '[REGION_NAME]' e.g., "us-central1";
  // const filter = '[FILTER_EXPRESSIONS]' e.g., "tablesDatasetMetadata:*";

  // A resource that represents Google Cloud Platform location.
  const projectLocation = client.locationPath(projectId, computeRegion);

  // List all the datasets available in the region by applying filter.
  client
    .listDatasets({parent: projectLocation, filter: filter})
    .then(responses => {
      const dataset = responses[0];

      // Display the dataset information.
      console.log('List of datasets:');
      for (let i = 0; i < dataset.length; i++) {
        const tablesDatasetMetadata = dataset[i].tablesDatasetMetadata;

        console.log(`Dataset name: ${dataset[i].name}`);
        console.log(`Dataset Id: ${dataset[i].name.split('/').pop(-1)}`);
        console.log(`Dataset display name: ${dataset[i].displayName}`);
        console.log(`Dataset example count: ${dataset[i].exampleCount}`);
        console.log('Tables dataset metadata:');
        console.log(
          `\tTarget column correlations: ${util.inspect(
            tablesDatasetMetadata.targetColumnCorrelations,
            false,
            null
          )}`
        );
        console.log(
          `\tPrimary table spec Id: ${tablesDatasetMetadata.primaryTableSpecId}`
        );
        console.log(
          `\tTarget column spec Id: ${tablesDatasetMetadata.targetColumnSpecId}`
        );
        console.log(
          `\tWeight column spec Id: ${tablesDatasetMetadata.weightColumnSpecId}`
        );
        console.log(
          `\tMl use column spec Id: ${tablesDatasetMetadata.mlUseColumnSpecId}`
        );
      }
    })
    .catch(err => {
      console.error(err);
    });
  // [END automl_tables_list_datasets]
}
main(...process.argv.slice(2)).catch(console.error());


text:
<?php

namespace CO\EShopBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * CO\EShopBundle\Entity\Order
 *
 * @ORM\Table("orders")
 * @ORM\Entity(repositoryClass="CO\EShopBundle\Entity\OrderRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Order
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="order")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
     */
     protected $user;

    /**
     * @ORM\ManyToOne(targetEntity="OrderUserData", inversedBy="order")
     * @ORM\JoinColumn(name="order_user_data_id", referencedColumnName="id", nullable=false)
     */
     protected $orderUserData;

    /**
     * @var float $total
     *
     * @ORM\Column(name="total", type="float")
     */
    private $total;

    /**
     * @var datetime $createTimestamp
     *
     * @ORM\Column(name="create_timestamp", type="datetime", nullable=false)
     */
    private $createTimestamp;

	/**
	* @ORM\OneToMany(targetEntity="OrderItem", mappedBy="order", cascade={"persist"})
	*/
	private $items;

	/**
     * @ORM\Column(type="text", nullable=true)
     */
	private $obs;

    /**
     * @var integer $status
     *
     * @ORM\Column(name="status", type="integer")
     */
    private $status;

    /**
     * @var string $awb
     *
     * @ORM\Column(name="awb", type="string", length=100, nullable=true)
     */
    private $awb;

    /**
     * @var integer $shippingcomp
     *
     * @ORM\Column(name="shippingcomp", type="integer")
     */
    private $shippingcomp;

    /**
     * @var string $cancelObs
     *
     * @ORM\Column(name="cancel_obs", type="string", length=300, nullable=true)
     */
    private $cancelObs;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->items = new \Doctrine\Common\Collections\ArrayCollection();
        $this->shippingcomp = 0;
    }

    /**
     * @ORM\PrePersist
     */
    public function prePersist()
    {
        $this->setCreateTimestamp(new \DateTime());
    }

		//--------------------------------------------------------------------------

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set total
     *
     * @param float $total
     * @return Order
     */
    public function setTotal($total)
    {
        $this->total = $total;

        return $this;
    }

    /**
     * Get total
     *
     * @return float
     */
    public function getTotal()
    {
        return $this->total;
    }

    /**
     * Set createTimestamp
     *
     * @param \DateTime $createTimestamp
     * @return Order
     */
    public function setCreateTimestamp($createTimestamp)
    {
        $this->createTimestamp = $createTimestamp;

        return $this;
    }

    /**
     * Get createTimestamp
     *
     * @return \DateTime
     */
    public function getCreateTimestamp()
    {
        return $this->createTimestamp;
    }

    /**
     * Set status
     *
     * @param integer $status
     * @return Order
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * Get status
     *
     * @return integer
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Get awb
     *
     * @return string
     */
    public function getAwb()
    {
        return $this->awb;
    }

    /**
     * Set awb
     *
     * @param string $awb
     * @return Order
     */
    public function setAwb($awb)
    {
        $this->awb = $awb;

        return $this;
    }

    /**
     * Set shippingcomp
     *
     * @param integer $shippingcomp
     * @return Order
     */
    public function setShippingcomp($shippingcomp)
    {
        $this->shippingcomp = $shippingcomp;

        return $this;
    }

    /**
     * Get shippingcomp
     *
     * @return integer
     */
    public function getShippingcomp()
    {
        return $this->shippingcomp;
    }

    /**
     * Set user
     *
     * @param CO\EShopBundle\Entity\User $user
     * @return Order
     */
    public function setUser(\CO\EShopBundle\Entity\User $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return CO\EShopBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * Set orderUserData
     *
     * @param CO\EShopBundle\Entity\OrderUserData $orderUserData
     * @return Order
     */
    public function setOrderUserData(\CO\EShopBundle\Entity\OrderUserData $orderUserData)
    {
        $this->orderUserData = $orderUserData;

        return $this;
    }

    /**
     * Get orderUserData
     *
     * @return CO\EShopBundle\Entity\OrderUserData
     */
    public function getOrderUserData()
    {
        return $this->orderUserData;
    }

    /**
     * Add items
     *
     * @param CO\EShopBundle\Entity\OrderItem $items
     * @return Order
     */
    public function addItem(\CO\EShopBundle\Entity\OrderItem $items)
    {
        $this->items[] = $items;

        return $this;
    }

    /**
     * Remove items
     *
     * @param CO\EShopBundle\Entity\OrderItem $items
     */
    public function removeItem(\CO\EShopBundle\Entity\OrderItem $items)
    {
        $this->items->removeElement($items);
    }

    /**
     * Get items
     *
     * @return Doctrine\Common\Collections\Collection
     */
    public function getItems()
    {
        return $this->items;
    }

    /**
     * @return text
     */
	public function getObs() {
		return $this->obs;
	}

    /**
     * @param string $obs
     * @return User
     */
	public function setObs($obs) {
		$this->obs = $obs;
	}

    /**
     * @return text
     */
	public function getCancelObs() {
		return $this->cancelObs;
	}

    /**
     * @param string $obs
     * @return User
     */
	public function setCancelObs($obs) {
		$this->cancelObs = $obs;
	}
}


text:
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}

module IHaskell.Display.Juicypixels (module IHaskell.Display, module Codec.Picture) where

import qualified Codec.Picture as P
import           Codec.Picture (Image(..))
import           Codec.Picture.Png (PngSavable, encodePng)
import           IHaskell.Display (IHaskellDisplay, Display(..), display, png, base64)
import           Data.ByteString.Lazy (ByteString, toStrict)

instance IHaskellDisplay (Image P.Pixel8) where
  display = return . format

instance IHaskellDisplay (Image P.Pixel16) where
  display = return . format

instance IHaskellDisplay (Image P.PixelYA8) where
  display = return . format

instance IHaskellDisplay (Image P.PixelYA16) where
  display = return . format

instance IHaskellDisplay (Image P.PixelRGB8) where
  display = return . format

instance IHaskellDisplay (Image P.PixelRGB16) where
  display = return . format

instance IHaskellDisplay (Image P.PixelRGBA8) where
  display = return . format

instance IHaskellDisplay (Image P.PixelRGBA16) where
  display = return . format

format :: PngSavable a => Image a -> Display
format im@(Image w h _) = Display [png w h . base64 . toStrict . encodePng $ im]


text:
"""
Created on Mon Apr  4 13:59:18 2016

Script to clean IODP coordinates and translate to decimal degrees

@author: rickdberg
"""
import pandas as pd
import numpy as np

coorddata = pd.read_csv(r'C:\Users\rickdberg\Documents\UW Projects\Magnesium uptake\Data\317-360\hole_summary_317-360.txt', sep="\t", header=None, skiprows=None)

latorig = coorddata.iloc[1:,3]
lonorig = coorddata.iloc[1:,4]

latnum = [n.replace('N', '') for n in latorig]
latnum = [s.replace('S', '') for s in latnum]
latnum = pd.Series(latnum)
lonnum = [e.replace('E', '') for e in lonorig]
lonnum = [w.replace('W', '') for w in lonnum]
lonnum = pd.Series(lonnum)

latdegrees = latnum.str[:2].astype(float)
latdecimals = latnum.str[3:11].astype(float)
latdecimals = latdecimals/60
lat = latdegrees + latdecimals

londegrees = lonnum.str[:3].astype(float)
londecimals = lonnum.str[4:12].astype(float)
londecimals = londecimals/60
lon = londegrees + londecimals

for x in np.arange(len(latorig)):
    if 'S' in latorig[x+1]:
        lat[x] = lat[x]*-1

for y in np.arange(len(lonorig)):
    if 'W' in lonorig[y+1]:
        lon[y] = lon[y]*-1

coords = pd.concat([lat, lon], axis=1).reset_index()
coords.to_csv("iodpcoords.csv")


text:
package com.turbo.whack;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

// Full screen activity
public class FullscreenActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		ActivityHelper.app_init(this);
		ActivityHelper.activity_init(this);

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fullscreen);

		Button start_button = (Button) findViewById(R.id.start_button);
		Button high_score = (Button) findViewById(R.id.high_score_button);
		Button settings = (Button) findViewById(R.id.settings_button);

		OnClickListener clickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				int id = v.getId();
				Intent intent;
				switch(id) {
				case R.id.start_button:
					intent = new Intent(FullscreenActivity.this, GamePlayActivity.class);
					FullscreenActivity.this.startActivity(intent);
					break;
				case R.id.high_score_button:
					intent = new Intent(FullscreenActivity.this, HighScoreActivity.class);
					FullscreenActivity.this.startActivity(intent);
					break;
				case R.id.settings_button:
					intent = new Intent(FullscreenActivity.this, SettingsActivity.class);
					FullscreenActivity.this.startActivity(intent);
					break;
				default:
					break;
				}
			}
		};

		start_button.setOnClickListener(clickListener);
		high_score.setOnClickListener(clickListener);
		settings.setOnClickListener(clickListener);
	}
}


text:
"""train_imagenet."""
import os
import argparse
import random
import numpy as np
from mind_dataset import create_dataset
from mindspore import context
from mindspore import Tensor
from mindspore.parallel._auto_parallel_context import auto_parallel_context
from mindspore.train.model import ParallelMode
from mindspore.train.callback import TimeMonitor
from mindspore.train.loss_scale_manager import FixedLossScaleManager
import mindspore.dataset.engine as de
from mindspore.communication.management import init
import mindspore.nn as nn

from metric import DistAccuracy, ClassifyCorrectCell
from mlperf_logging import mllog
from callback import StateMonitor
from model.model_thor import Model
from model.resnet import resnet50
from model.thor import THOR
import math

import moxing as mox
import time

np.random.seed(1)
os.environ['MINDSPORE_HCCL_CONFIG_PATH'] = os.getenv('RANK_TABLE_FILE')
os.environ['GLOG_v'] = '3'

parser = argparse.ArgumentParser(description='Image classification')
# cloud
parser.add_argument('--data_url', type=str, default=None, help='data_url')
parser.add_argument('--train_url', type=str, default=None, help='train_url')

# train datasets
parser.add_argument('--dataset_path', type=str, default='/home/work/datasets/minddataset/train', help='Dataset path')
parser.add_argument('--batch_size', type=int, default=128, help='batch_size')
parser.add_argument('--image_size', type=int, default=224, help='image_size')

# eval datasets
parser.add_argument('--eval_path', type=str, default='/home/work/datasets/minddataset/eval', help='Eval dataset path')
# parser.add_argument('--eval_path', type=str, default='/cache/eval_data/', help='Eval dataset path')
parser.add_argument('--eval_batch_size', type=int, default=50, help='eval_batch_size')
parser.add_argument('--eval_image_size', type=int, default=224, help='eval_image_size')
parser.add_argument('--eval_interval', type=int, default=1, help='eval_interval')

# network
parser.add_argument('--class_num', type=int, default=1000, help='class_num')

# lr
parser.add_argument('--lr_init', type=float, default=0.14, help='learning rate init.')
parser.add_argument('--lr_decay', type=float, default=6, help='learning rate decay.')
parser.add_argument('--epoch_end', type=int, default=70, help='learning rate end epoch')
parser.add_argument('--damping_init', type=float, default=0.14, help='damping init.')
parser.add_argument('--damping_decay', type=float, default=0.85, help='damping decay rate.')
parser.add_argument('--step_per_epoch', type=int, default=625, help='step per epoch.')
parser.add_argument('--frequency', type=int, default=625, help='update frequency')
parser.add_argument('--warmup_epoch', type=int, default=0, help='warmup epoch')
parser.add_argument('--lr_warmup', type=float, default=0.01, help='lr warmup')
parser.add_argument('--epoch_size', type=int, default=50, help='train epoch size')
parser.add_argument('--lr_mode', type=str, default="poly", help='lr mode')

# optimizer
parser.add_argument('--momentum', type=float, default=0.9, help='momentum')
parser.add_argument('--weight_decay', type=float, default=5e-4, help='weight_decay')

# loss
parser.add_argument('--loss_scale', type=int, default=128, help='loss_scale')
parser.add_argument('--use_label_smooth', type=int, default=1, help='use_label_smooth')
parser.add_argument('--label_smooth_factor', type=float, default=0.1, help='label_smooth_factor')

parser.add_argument('--resnet_d', type=int, default=0, help='use_resnet_d')
parser.add_argument('--init_new', type=int, default=0, help='use_new_init')

args = parser.parse_args()

device_id = int(os.getenv('DEVICE_ID'))
device_num = int(os.getenv('RANK_SIZE'))
global_rank_id = int(os.getenv('RANK_ID').split("-")[-1])
local_rank_id = global_rank_id * 8 + device_id
log_filename = os.path.join(os.getcwd(), "result.log")
s3_rank_ready_file = os.path.join(args.train_url, 'rank_{}.txt'.format(local_rank_id))
if mox.file.exists(s3_rank_ready_file):
    mox.file.remove(s3_rank_ready_file, recursive=False)

def sync_all_rank(device_num=8):
    mox.file.write(s3_rank_ready_file, "ready")
    while local_rank_id == 0:
        all_rank_exist = True
        for rank_item in range(device_num):
            rank_fn_item = os.path.join(args.train_url, 'rank_{}.txt'.format(rank_item))
            if not mox.file.exists(rank_fn_item):
                all_rank_exist = False
        if all_rank_exist:
            break
        else:
            time.sleep(1)  # delay 1 sec

context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", save_graphs=True)
context.set_context(device_id=device_id)

def get_model_lr_warmup(global_step, lr_init, decay, total_epochs, steps_per_epoch, warmup_epoch=0, lr_warmup=0.01):
    """get_model_lr"""
    lr_each_step = []
    total_steps = steps_per_epoch * total_epochs
    warmup_steps = steps_per_epoch * warmup_epoch
    for i in range(total_steps):
        if i < warmup_steps:
            lr_inc = (float(lr_init) - float(lr_warmup)) / float(warmup_steps)
            lr_local = float(lr_warmup) + lr_inc * (i + 1)
        else:
            epoch = (i + 1) / steps_per_epoch - warmup_epoch
            base = (1.0 - float(epoch) / total_epochs) ** decay
            lr_local = lr_init * base
        lr_each_step.append(lr_local)
    current_step = global_step
    lr_each_step = np.array(lr_each_step).astype(np.float32)
    learning_rate = lr_each_step[current_step:]
    return learning_rate

def warmup_cosine_annealing_lr(lr, max_epoch, steps_per_epoch, warmup_epochs, warmup_init_lr):
    base_lr = lr
    total_steps = int(max_epoch * steps_per_epoch)
    warmup_steps = int(warmup_epochs * steps_per_epoch)
    decay_steps = total_steps - warmup_steps
    lr_each_step = []
    for i in range(total_steps):
        if i < warmup_steps:
            lr_inc = (float(base_lr) - float(warmup_init_lr)) / float(warmup_steps)
            lr = float(warmup_init_lr) + lr_inc * (i + 1)
        else:
            linear_decay = (total_steps - i) / decay_steps
            cosine_decay = 0.5 * (1 + math.cos(math.pi * 2 * 0.47 * i / decay_steps))
            decayed = linear_decay * cosine_decay + 0.00001
            lr = base_lr * decayed
        lr_each_step.append(lr)
    return np.array(lr_each_step).astype(np.float32)

def warmup_cosine_annealing_lr_new(lr, max_epoch, steps_per_epoch, warmup_epochs, warmup_init_lr):
    base_lr = lr
    total_steps = int(max_epoch * steps_per_epoch)
    warmup_steps = int(warmup_epochs * steps_per_epoch)
    decay_steps = total_steps - warmup_steps
    lr_each_step = []
    for i in range(total_steps):
        if i < warmup_steps:
            lr_inc = (float(base_lr) - float(warmup_init_lr)) / float(warmup_steps)
            lr = float(warmup_init_lr) + lr_inc * (i + 1)
        else:
            linear_decay = (total_steps - i) / decay_steps
            cosine_decay = 0.5 * (1 + math.cos(math.pi * 2 * 0.47 * (i - warmup_steps) / decay_steps))
            decayed = linear_decay * cosine_decay + 0.00001
            lr = base_lr * decayed
        lr_each_step.append(lr)
    return np.array(lr_each_step).astype(np.float32)

def get_model_damping(global_step, damping_init, decay_rate, total_epochs, steps_per_epoch):
    """get_model_damping"""
    damping_each_step = []
    total_steps = steps_per_epoch * total_epochs
    for step in range(total_steps):
        epoch = (step + 1) / steps_per_epoch
        damping_here = damping_init * (decay_rate ** (epoch / 10))
        damping_each_step.append(damping_here)

    current_step = global_step
    damping_each_step = np.array(damping_each_step).astype(np.float32)
    damping_now = damping_each_step[current_step:]
    return damping_now

if __name__ == '__main__':
    context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL,
                                      mirror_mean=True, parameter_broadcast=True)
    auto_parallel_context().set_all_reduce_fusion_split_indices([43], "hccl_world_groupsum1")
    auto_parallel_context().set_all_reduce_fusion_split_indices([27], "hccl_world_groupsum2")
    auto_parallel_context().set_all_reduce_fusion_split_indices([27], "hccl_world_groupsum3")
    auto_parallel_context().set_all_reduce_fusion_split_indices([27], "hccl_world_groupsum4")
    auto_parallel_context().set_all_reduce_fusion_split_indices([27], "hccl_world_groupsum5")

    # add mllog
    mllog.config(filename=log_filename)
    mllog.config(
        default_namespace="mindspore",
        default_stack_offset=1,
        default_clear_line=False,
        root_dir=os.path.normpath(
            os.path.dirname(os.path.realpath(__file__))))
    mllogger = mllog.get_mllogger()
    # submission
    mllogger.event(key=mllog.constants.SUBMISSION_BENCHMARK, value="resnet")
    mllogger.event(key=mllog.constants.SUBMISSION_DIVISION, value="open")
    mllogger.event(key=mllog.constants.SUBMISSION_ORG, value="SIAT")
    mllogger.event(key=mllog.constants.SUBMISSION_PLATFORM, value="Ascend 910")
    mllogger.event(key=mllog.constants.SUBMISSION_STATUS, value="cloud")
    mllogger.event(key=mllog.constants.CACHE_CLEAR)

    # init the distribute env
    init()

    # network
    damping = get_model_damping(0, args.damping_init, args.damping_decay, 70, args.step_per_epoch)
    net = resnet50(class_num=1000, damping=damping, loss_scale=args.loss_scale,
                   frequency=args.frequency, batch_size=args.batch_size, resnet_d=args.resnet_d,
                   init_new=args.init_new)

    # evaluation network
    dist_eval_network = ClassifyCorrectCell(net)

    # loss
    if not args.use_label_smooth:
        args.label_smooth_factor = 0.0
    loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean", smooth_factor=args.label_smooth_factor,
                                            num_classes=args.class_num)

    # train dataset
    epoch_size = args.epoch_size
    dataset = create_dataset(dataset_path=args.dataset_path, do_train=True,
                             repeat_num=epoch_size, batch_size=args.batch_size)
    step_size = dataset.get_dataset_size()
    eval_interval = args.eval_interval

    # evalutation dataset
    eval_dataset = create_dataset(dataset_path=args.eval_path, do_train=False,
                                  repeat_num=epoch_size // eval_interval, batch_size=args.eval_batch_size)
    eval_step_size = eval_dataset.get_dataset_size()

    # loss scale
    loss_scale = FixedLossScaleManager(args.loss_scale, drop_overflow_update=False)
    if args.lr_mode == "poly":
        lr_array = get_model_lr_warmup(0, args.lr_init, args.lr_decay, args.epoch_end, args.step_per_epoch,
                                       args.warmup_epoch, args.lr_warmup)
    elif args.lr_mode == "cos":
        lr_array = warmup_cosine_annealing_lr(args.lr_init, args.epoch_end, args.step_per_epoch, args.warmup_epoch,
                                              args.lr_warmup)
    else:
        lr_array = warmup_cosine_annealing_lr_new(args.lr_init, args.epoch_end, args.step_per_epoch, args.warmup_epoch,
                                                  args.lr_warmup)

    lr = Tensor(lr_array)
    opt = THOR(filter(lambda x: x.requires_grad, net.get_parameters()), lr, args.momentum,
               filter(lambda x: 'matrix_A' in x.name, net.get_parameters()),
               filter(lambda x: 'matrix_G' in x.name, net.get_parameters()),
               filter(lambda x: 'A_inv_max' in x.name, net.get_parameters()),
               filter(lambda x: 'G_inv_max' in x.name, net.get_parameters()),
               args.weight_decay, args.loss_scale)

    # model
    model = Model(net, loss_fn=loss, optimizer=opt, loss_scale_manager=loss_scale, amp_level="O2",
                  keep_batchnorm_fp32=False,
                  metrics={'acc': DistAccuracy(batch_size=args.eval_batch_size, device_num=device_num)},
                  eval_network=dist_eval_network, frequency=args.frequency)

    # set event
    mllogger.start(key=mllog.constants.INIT_START)
    mllogger.event(key=mllog.constants.GLOBAL_BATCH_SIZE, value=args.batch_size * device_num)
    mllogger.event(key="opt_name", value="THOR")
    mllogger.event(key="base_learning_rate", value=args.lr_init)
    mllogger.event(key="learning_rate_decay_steps", value=step_size * (args.epoch_size - args.warmup_epoch))
    mllogger.event(key="learning_rate_warmup_epochs", value=args.warmup_epoch)
    mllogger.event(key="momentum", value=args.momentum)
    mllogger.event(key="weight_decay", value=args.weight_decay)

    model.init(dataset, eval_dataset)
    sync_all_rank(device_num=device_num)

    mllogger.end(key=mllog.constants.INIT_STOP)

#     # callbacks
#     state_cb = StateMonitor(data_size=step_size,
#                             tot_batch_size=args.batch_size * device_num,
#                             lrs=lr_array,
#                             device_id=device_id)
    # callbacks
    state_cb = StateMonitor(data_size=step_size,
                        mllogger=mllogger,
                        tot_batch_size=args.batch_size*device_num,
                        lrs=lr_array,
                        device_id=device_id,
                        model=model,
                        eval_dataset=eval_dataset,
                        eval_interval=eval_interval)

    cb = [state_cb, ]
    eval_time_cb = TimeMonitor(data_size=eval_step_size)

    # train and eval
    mllogger.start(key=mllog.constants.RUN_START)
    mllogger.event(key="train_samples", value=args.batch_size * device_num * step_size)
    mllogger.event(key="eval_samples", value=args.eval_batch_size * device_num * eval_step_size)

    model.train(epoch_size, dataset, callbacks=cb)

    mllogger.end(key=mllog.constants.RUN_STOP, metadata={"status": "success"})
    if local_rank_id == 0:
        mox.file.copy_parallel(log_filename, os.path.join(args.train_url, "result.log"))


text:
module.exports = function(grunt) {
    grunt.registerTask('default', ['availabletasks:main']);
};


text:
global_q = False

# Import all the necessary modules

# In[3]:

# -*- coding: utf-8 -*-
"""
Written by Daniel M. Aukes
Email: danaukes<at>gmail.com
Please see LICENSE for full license.
"""

import pynamics
from pynamics.frame import Frame
from pynamics.variable_types import Differentiable,Constant
from pynamics.system import System
from pynamics.body import Body
from pynamics.dyadic import Dyadic
from pynamics.output import Output,PointsOutput
from pynamics.particle import Particle
import pynamics.integration
import numpy
import matplotlib.pyplot as plt
plt.ion()
from math import pi
import scipy.interpolate
import sympy

# The next two lines create a new system object and set that system as the global system within the module so that other variables can use and find it.

# In[4]:

system = System()
pynamics.set_system(__name__,system)

# ## Parameterization
#
# ### Constants
#
# Declare constants and seed them with their default value.  This can be changed at integration time but is often a nice shortcut when you don't want the value to change but you want it to be represented symbolically in calculations

# In[5]:

lA = Constant(1,'lA',system)
lB = Constant(1,'lB',system)
lC = Constant(6*25.4/1000,'lC',system)

mA = Constant(1,'mA',system)
mB = Constant(1,'mB',system)
mC = Constant(1,'mC',system)
m1 = Constant(2,'m1',system)

g = Constant(9.81,'g',system)
b = Constant(1e1,'b',system)
k1 = Constant(1e2,'k1',system)
k2 = Constant(1e1,'k2',system)

preload1 = Constant(0*pi/180,'preload1',system)
preload2 = Constant(0*pi/180,'preload2',system)
preload3 = Constant(0*pi/180,'preload3',system)

Ixx_A = Constant(1,'Ixx_A',system)
Iyy_A = Constant(1,'Iyy_A',system)
Izz_A = Constant(1,'Izz_A',system)
Ixx_B = Constant(1,'Ixx_B',system)
Iyy_B = Constant(1,'Iyy_B',system)
Izz_B = Constant(1,'Izz_B',system)
Ixx_C = Constant(1,'Ixx_C',system)
Iyy_C = Constant(1,'Iyy_C',system)
Izz_C = Constant(1,'Izz_C',system)

k_constraint = Constant(1e4,'k_constraint',system)
b_constraint = Constant(1e2,'b_constraint',system)

force_var = sympy.Symbol('fv')

# ## Integration Tolerance
# Specify the precision of the integration

# In[6]:

tol = 1e-11

# ### Time
# Define variables for time that can be used throughout the script.  These get used to create the t array, a list of every time value that is solved for during integration

# In[7]:

tinitial = 0
tfinal = 10
fps = 30
tstep = 1/fps
t = numpy.r_[tinitial:tfinal:tstep]

force = t*0
ii = (t==3).nonzero()[0][0]
jj = (t==5).nonzero()[0][0]
force[ii:jj] = 10
f_force = scipy.interpolate.interp1d(t, force,fill_value='extrapolate')

# ### Differentiable State Variables
#
# Define your differentiable state variables that you will use to model the state of the system.  In this case $qA$, $qB$, and $qC$ are the rotation angles of a three-link mechanism

# In[8]:

x,x_d,x_dd = Differentiable('x',system)
y,y_d,y_dd = Differentiable('y',system)
qA,qA_d,qA_dd = Differentiable('qA',system)
qB,qB_d,qB_dd = Differentiable('qB',system)
qC,qC_d,qC_dd = Differentiable('qC',system)
x2,x2_d,x2_dd = Differentiable('x2',system)

# ### Initial Values
# Define a set of initial values for the position and velocity of each of your state variables.  It is necessary to define a known.  This code create a dictionary of initial values.

# In[9]:

initialvalues = {}
initialvalues[x]=0
initialvalues[x_d]=0
initialvalues[y]=2.01
initialvalues[y_d]=0
initialvalues[qA]=0*pi/180
initialvalues[qA_d]=0*pi/180
initialvalues[qB]=0*pi/180
initialvalues[qB_d]=0*pi/180
initialvalues[qC]=0*pi/180
initialvalues[qC_d]=0*pi/180
initialvalues[x2]=-1.5
initialvalues[x2_d]=.5

# These two lines of code order the initial values in a list in such a way that the integrator can use it in the same order that it expects the variables to be supplied

# In[10]:

statevariables = system.get_state_variables()
ini = [initialvalues[item] for item in statevariables]

# ## Kinematics
#
# ### Frames
# Define the reference frames of the system

# In[11]:

N = Frame('N',system)
A = Frame('A',system)
B = Frame('B',system)
C = Frame('C',system)

# ### Newtonian Frame
#
# It is important to define the Newtonian reference frame as a reference frame that is not accelerating, otherwise the dynamic equations will not be correct

# In[12]:

system.set_newtonian(N)

# This is the first time that the "global_q" variable is used.  If you choose to rotate each frame with reference to the base frame, there is the potential for a representational simplification.  If you use a relative rotation, this can also be simpler in some cases.  Try running the code either way to see which one is simpler in this case.

# In[13]:

A.rotate_fixed_axis(N,[0,0,1],qA,system)
B.rotate_fixed_axis(A,[0,0,1],qB,system)
C.rotate_fixed_axis(B,[0,0,1],qC,system)

# ### Vectors
# Define the vectors that describe the kinematics of a series of connected lengths
#
# * pNA - This is a vector with position at the origin.
# * pAB - This vector is length $l_A$ away from the origin along the A.x unit vector
# * pBC - This vector is length $l_B$ away from the pAB along the B.x unit vector
# * pCtip - This vector is length $l_C$ away from the pBC along the C.x unit vector

# In[14]:

pNA=x*N.x+y*N.y
pAB=pNA-lA*A.y
pBC=pAB-lB*B.y
pC1 = pBC - lC/2*C.x
pC2 = pBC + lC/2*C.x

pm1 = x2*N.x+2*N.y

vNA = pNA.time_derivative()
vC1 = pC1.time_derivative()
vC2 = pC2.time_derivative()
vm1 = pm1.time_derivative()

# ## Centers of Mass
#
# It is important to define the centers of mass of each link.  In this case, the center of mass of link A, B, and C is halfway along the length of each

# In[15]:

pAcm=pNA-lA/2*A.y
pBcm=pAB-lB/2*B.y
pCcm=pBC

# ## Calculating Velocity
#
# The angular velocity between frames, and the time derivatives of vectors are extremely useful in calculating the equations of motion and for determining many of the forces that need to be applied to your system (damping, drag, etc).  Thus, it is useful, once kinematics have been defined, to take or find the derivatives of some of those vectors for calculating  linear or angular velocity vectors
#
# ### Angular Velocity
# The following three lines of code computes and returns the angular velocity between frames N and A (${}^N\omega^A$), A and B (${}^A\omega^B$), and B and C (${}^B\omega^C$).  In other cases, if the derivative expression is complex or long,  you can supply pynamics with a given angular velocity between frames to speed up computation time.

# In[16]:

wNA = N.get_w_to(A)
wAB = A.get_w_to(B)
wBC = B.get_w_to(C)

# ### Vector derivatives
# The time derivatives of vectors may also be

# vCtip = pCtip.time_derivative(N,system)

# ### Define Inertias and Bodies
# The next several lines compute the inertia dyadics of each body and define a rigid body on each frame.  In the case of frame C, we represent the mass as a particle located at point pCcm.

# In[17]:

IA = Dyadic.build(A,Ixx_A,Iyy_A,Izz_A)
IB = Dyadic.build(B,Ixx_B,Iyy_B,Izz_B)
IC = Dyadic.build(B,Ixx_C,Iyy_C,Izz_C)

BodyA = Body('BodyA',A,pAcm,mA,IA,system)
BodyB = Body('BodyB',B,pBcm,mB,IB,system)
BodyC = Body('BodyC',C,pCcm,mC,IC,system)
ParticleM = Particle(pm1,m1,'ParticleM',system)

# ## Forces and Torques
# Forces and torques are added to the system with the generic ```addforce``` method.  The first parameter supplied is a vector describing the force applied at a point or the torque applied along a given rotational axis.  The second parameter is the  vector describing the linear speed (for an applied force) or the angular velocity(for an applied torque)

# In[18]:

stretch1 = -pC1.dot(N.y)
stretch1_s = (stretch1+abs(stretch1))
on = stretch1_s/(2*stretch1+1e-10)
system.add_spring_force1(k_constraint,-stretch1_s*N.y,vC1)
system.addforce(-b_constraint*vC1*on,vC1)

toeforce = k_constraint*-stretch1_s

stretch2 = -pC2.dot(N.y)
stretch2_s = (stretch2+abs(stretch2))
on = stretch2_s/(2*stretch2+1e-10)
system.add_spring_force1(k_constraint,-stretch2_s*N.y,vC2)
system.addforce(-b_constraint*vC2*on,vC2)

system.addforce(-b*wNA,wNA)
system.addforce(-b*wAB,wAB)
system.addforce(-b*wBC,wBC)

# system.addforce(force_var*N.x,vNA)

stretch3_v = (pm1 - pNA)
stretch3_uv = 1/(stretch3_v.length() + 1e-10)* stretch3_v

stretch3 = 1-(pm1 - pNA).length()
stretch3_s = (stretch3+abs(stretch3))
on = stretch3_s/(2*stretch3+1e-10)
system.add_spring_force2(k_constraint,-stretch3_uv*stretch3_s,vm1,-vNA)
# system.addforce(-b_constraint*vC2*on,vC2)

# ### Spring Forces
#
# Spring forces are a special case because the energy stored in springs is conservative and should be considered when calculating the system's potential energy.  To do this, use the ```add_spring_force``` command.  In this method, the first value is the linear spring constant.  The second value is the "stretch" vector, indicating the amount of deflection from the neutral point of the spring.  The final parameter is, as above, the linear or angluar velocity vector (depending on whether your spring is a linear or torsional spring)
#
# In this case, the torques applied to each joint are dependent upon whether qA, qB, and qC are absolute or relative rotations, as defined above.

# In[19]:

# system.add_spring_force1(k1,(qA-preload1)*N.z,wNA)
system.add_spring_force1(k2,(qB-preload2)*A.z,wAB)
system.add_spring_force1(k1,(qC-preload3)*B.z,wBC)

# ### Gravity
# Again, like springs, the force of gravity is conservative and should be applied to all bodies.  To globally apply the force of gravity to all particles and bodies, you can use the special ```addforcegravity``` method, by supplying the acceleration due to gravity as a vector.  This will get applied to all bodies defined in your system.

# In[20]:

system.addforcegravity(-g*N.y)

# ## Constraints
# Constraints may be defined that prevent the motion of certain elements.  Try uncommenting the commented out line to see what happens.

# In[21]:

# ## F=ma
# This is where the symbolic expressions for F and ma are calculated.  This must be done after all parts of the system have been defined.  The ```getdynamics``` function uses Kane's method to derive the equations of motion.

# In[22]:

f,ma = system.getdynamics()

# In[23]:

f

# In[24]:

ma

# ## Solve for Acceleration
#
# The next line of code solves the system of equations F=ma plus any constraint equations that have been added above.  It returns one or two variables.  func1 is the function that computes the velocity and acceleration given a certain state, and lambda1(optional) supplies the function that computes the constraint forces as a function of the resulting states
#
# There are a few ways of solveing for a.  The below function inverts the mass matrix numerically every time step.  This can be slower because the matrix solution has to be solved for, but is sometimes more tractable than solving the highly nonlinear symbolic expressions that can be generated from the previous step.  The other options would be to use ```state_space_pre_invert```, which pre-inverts the equations symbolically before generating a numerical function, or ```state_space_post_invert2```, which adds Baumgarte's method for intermittent constraints.

# In[25]:

func1,lambda1 = system.state_space_post_invert(f,ma,return_lambda = True,variable_functions={force_var:f_force})

# ## Integrate
#
# The next line of code integrates the function calculated

# In[26]:

states=pynamics.integration.integrate_odeint(func1,ini,t,rtol=tol,atol=tol,hmin=tol, args=({'constants':system.constant_values},))

# ## Outputs
#
#
# The next section simply calculates and plots a variety of data from the previous simulation
# ### States

# In[27]:

plt.figure()
artists = plt.plot(t,states[:,:5])
plt.legend(artists,['x','y','qA','qB','qC'])

# ### Energy

# In[28]:

# KE = system.get_KE()
# PE = system.getPEGravity(pNA) - system.getPESprings()
# energy_output = Output([KE-PE],system)
# energy_output.calc(states,t)
# energy_output.plot_time()

# ### Motion

# In[29]:

points = [pm1,pNA,pAB,pBC,pC1,pC2]
points_output = PointsOutput(points,system)
y = points_output.calc(states,t)
points_output.plot_time(5)

# #### Motion Animation
# in normal Python the next lines of code produce an animation using matplotlib

# In[30]:

#points_output.animate(fps = fps,movie_name = 'render.mp4',lw=2,marker='o',color=(1,0,0,1),linestyle='-')
#a()

# To plot the animation in jupyter you need a couple extra lines of code...

# In[31]:

# from matplotlib import animation, rc
# from IPython.display import HTML
# HTML(points_output.anim.to_html5_video())

# ### Constraint Forces

# This line of code computes the constraint forces once the system's states have been solved for.

# In[32]:

# lambda2 = numpy.array([lambda1(item1,item2,system.constant_values) for item1,item2 in zip(t,states)])
# plt.figure()
# plt.plot(t, lambda2)

# In[ ]:


text:
package laughinglen.control;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.netflix.config.ConcurrentMapConfiguration;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicPropertyFactory;
import org.junit.Test;
import rx.Subscription;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import static org.assertj.core.api.Assertions.*;

public class ArchaiusControlTest {

	@Test(expected = IllegalArgumentException.class)
	public void shouldNotCreateWithNullProperty() {
		new ArchaiusControl(null, null);
	}

	@Test(expected = NullPointerException.class)
	public void shouldNotCreateWithNullFactory() {
		new ArchaiusControl("test", null);
	}

	@Test
	public void shouldCreateSuccessfully() {
		assertThat(new ArchaiusControl("test", DynamicPropertyFactory.getInstance())).isNotNull();
	}

	@Test
	public void shouldObserveState() throws InterruptedException {
		final ConcurrentMapConfiguration configuration = new ConcurrentMapConfiguration(Maps.newHashMap());
		configuration.setProperty("archaius.fixedDelayPollingScheduler.initialDelayMills", 10);
		configuration.setProperty("archaius.fixedDelayPollingScheduler.delayMills", 100);
		configuration.setProperty("test", true);

		ConfigurationManager.install(configuration);

		final DynamicPropertyFactory factory = DynamicPropertyFactory.getInstance();
		final ArchaiusControl control = new ArchaiusControl("test", factory);

		final ArrayList<State> states = Lists.newArrayList();
		final Subscription subscription = control.changes().subscribe(states::add);

		configuration.setProperty("test", false);
		TimeUnit.MILLISECONDS.sleep(5);

		configuration.setProperty("test", true);
		TimeUnit.MILLISECONDS.sleep(5);

		configuration.setProperty("test", false);
		TimeUnit.MILLISECONDS.sleep(5);

		configuration.setProperty("test", true);
		TimeUnit.MILLISECONDS.sleep(5);

		assertThat(control.current().active).isTrue();
		assertThat(states.size()).isEqualTo(4);
		assertThat(states.get(0).active).isFalse();
		assertThat(states.get(1).active).isTrue();
		assertThat(states.get(2).active).isFalse();
		assertThat(states.get(3).active).isTrue();

		subscription.unsubscribe();

	}
}


text:
<!--
Copyright 2019 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

-->
<SharedFlowBundle revision="1" name="authcode-externaltoken">
    <ConfigurationVersion majorVersion="4" minorVersion="0"/>
    <CreatedAt>1557476854363</CreatedAt>
    <CreatedBy>davissean@google.com</CreatedBy>
    <Description></Description>
    <DisplayName>Shared-Flow</DisplayName>
    <LastModifiedAt>1557476854363</LastModifiedAt>
    <LastModifiedBy>davissean@google.com</LastModifiedBy>
    <ManifestVersion>SHA-512:c50b4ed1dd6522c918a0e270caf9415b0d859698bc8c94c728bba1b3d0464ee98e4cb43d12f442c2b6ee38014a8cc7ce87f11ba396e1f9f7d51820c8e5f57811:eu-west-1</ManifestVersion>
    <Policies>
        <Policy>AttachExternalToken</Policy>
        <Policy>DecodeBasicAuth</Policy>
        <Policy>ExtractExternalToken</Policy>
        <Policy>GenerateToken</Policy>
        <Policy>SetOAuthVariables</Policy>
        <Policy>ValidateClient</Policy>
    </Policies>
    <Resources/>
    <Spec></Spec>
    <subType>SharedFlow</subType>
    <SharedFlows>
        <SharedFlow>default</SharedFlow>
    </SharedFlows>
</SharedFlowBundle>


text:
/*
 * Created on 21-dic-2004
 *
 *
 */
package it.finsiel.siged.mvc.integration;

import it.finsiel.siged.dao.fs.RepositoryException;
import it.finsiel.siged.mvc.plugin.DataProvider;
import it.finsiel.siged.mvc.vo.protocollo.DocumentoVO;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Almaviva sud
 *
 */
public interface DocumentManagerDAO extends DataProvider {

    public Object startTransaction() throws IOException;

    public void commitTransaction(Object txId) throws IOException;

    public void rollbackTransaction(Object txId) throws IOException;

    public void saveDocumentsRepository(DocumentoVO[] documenti, Object txId)
            throws IOException;

    public InputStream getDocumentInputStreamRepository(Integer id)
            throws RepositoryException;

}


text:
Node::Node(unsigned int val)
{
  data = val;
}

void Node::setData(unsigned int d)
{
    data = d;
}

void Node::setLeftChild(boost::shared_ptr<Node> child)
{
    leftChild = child;
}

void Node::setRightChild(boost::shared_ptr<Node> child)
{
    rightChild = child;
}

unsigned int Node::getData()
{
    return data;
}

boost::shared_ptr<Node> Node::getLeftChild()
{
    return leftChild;
}

boost::shared_ptr<Node> Node::getRightChild()
{
    return rightChild;
}

Node::~Node()
{
}


text:
#############################################
# File: register_device_ps.ps1
# Author: Chase Bradley
# Description: The following PowerScript file performs 2 functions
#   (1) It registers a device record in AirWatch
#   (2) It enrolls the Windows 10 machine
#############################################

#Test to see if we are running from the script or if we are running from the ISE
if($PSScriptRoot -eq ""){
    #PSScriptRoot only popuates if the script is being run.  Default to default location if empty
    $current_path = "C:\Installs\AirWatch\";
}
else{
    #Only works if running from the file
    $current_path = $PSScriptRoot;
}

#Validation that the file exists on the local drive.
#Recommendation is to setup the file in the image, but can be downloaded on the fly.
$agentMSI = $current_path + "\AirWatchAgent.msi";
$tempMSI = $current_path + "\setupfiles\AirWatchAgent.msi";
$agentPS = $current_path + "\setupfiles\download_latest_agent.ps1";
if(Test-Path $agentMSI){
    echo "AirWatch Agent Exists"
} else {
    #Download the latest agent
    PowerShell.exe -ExecutionPolicy Bypass -File $agentPS;
    Move-Item $tempMSI $agentMSI;
}

#Import some utility functions
$utility =  $current_path + "\includes\utility_functions.psm1";
$module = Import-Module $utility -ErrorAction Stop -PassThru -Force;

#Import C# file
cd $current_path;
$RegistrationModule = $current_path + '\Registration.cs';

$CompilerParameters = New-Object -TypeName System.CodeDom.Compiler.CompilerParameters;
$dllPath = $current_path + '\bin\System.Web.Helpers.dll'
$CompilerParameters.CompilerOptions = '/reference:System.dll /reference:Microsoft.CSharp.dll' +
    ' /reference:System.Core.dll /reference:WebHelpers=' + $dllPath ;
if (-not ([System.Management.Automation.PSTypeName]'LocalDevice').Type)
{
Add-Type -Path $RegistrationModule -ErrorAction Stop -CompilerParameters $CompilerParameters;
}

#Creates the new Csharp object
$Register = New-Object LocalDevice.Registration;
$Register.initialize($current_path + "\");

#Process the settings
$iniSettings = Get-IniContent($current_path + "\localdevice.ini");

$allowedStagingUsers = "";
#Get potential staging users
if($iniSettings["Staging"]["AllowedStagingUsers"]){
    $allowedStagingUsers = $iniSettings["Staging"]["AllowedStagingUsers"].Split(",");
}

#Get current logged in user && computer name
$user = Get-WmiObject -Class Win32_ComputerSystem | select username
$username = $user.username
#######################################
# Testing credential
if($iniSettings.ContainsKey("Debug")){
    if($iniSettings["Debug"]["EnableDebug"] -eq 1){
        $username = $iniSettings["Debug"]["DebugUser"];
    }
}
#
#######################################

$computer = Get-WmiObject -Class Win32_ComputerSystem | select Name
$computername = $computer.name
if($allowedStagingUsers -ne ""){
    foreach ($stagingUser in $allowedStagingUsers)
    {
        $sanitized_user = $username.Replace($computername,'.')
        if($stagingUser -eq $sanitized_user){
            echo "User is staging user. Exiting.";
            return;
        }
    }
}

#Get serial number from WMIC
$serialnumber = wmic bios get serialnumber
$serialARR = $serialnumber[2]

#Sanitize extremely long Serial Numbers (any over 50 get truncated)
if($serialARR.Length -gt 50){
    $serialARR = $serialARR.Substring(0,50);
}
$serialARR = $serialARR.Trim();

#Get AirWatch information from the INI file
$server = $iniSettings["Config"]["Enrollment_Server"];
$groupId = $iniSettings["Config"]["GroupID"];
$stagingUsername = $iniSettings["Config"]["StagingUser"];
$stagingPassword = $iniSettings["Config"]["StagingPassword"];

$regArgs
$regArgs = @{Username=$username;SerialNumber=$serialARR;CreateUser=1};

$isRegister = $Register.RegisterDeviceArg($regArgs);

#only enroll machine if registered
If($isRegister -eq "True"){
    $logLocation = $current_path + "\msi.log";
	msiexec.exe /i AirwatchAgent.msi /quiet ENROLL=Y IMAGE=N SERVER=$server LGName=$groupId USERNAME=$stagingUsername PASSWORD=$stagingPassword /L*V C:\Installs\AirWatch\msi.log
	schtasks /Change /TN "\AirWatch MDM\Enrollment\AirWatch_Registration" /DISABLE
} Else {
	Write-Host "Do not enroll device and email IT"
    if($iniSettings["SMTP"]["UseSMTP"] -eq 1){
        $smtpServer = $iniSettings["SMTP"]["SMTPServer"];
        $recipient = $iniSettings["Config"]["AdminEmailAddress"];
        $sender = $iniSettings["SMTP"]["Sender"];
        $subject = "Failed to enroll $username. The registration script will run on next login!";
        Send-MailMessage -SmtpServer 'smtp.glgroup.com' -from $sender -to $recipient -Subject $subject
    }
}


text:
package com.genexplain.api.app;

import java.io.OutputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
import com.genexplain.api.core.GxColumnDef;
import com.genexplain.api.core.GxHttpClient;
import com.genexplain.api.core.GxHttpConnection;

/**
 * @author pst
 *
 */
public class GxHttpClientStub implements GxHttpClient {

    private GxHttpConnection con;

    private int listAppStatus      = 0;
    private int getAppParamsStatus = 0;

    private boolean calledListApps  = false;
    private boolean appParamsExcept = false;

    private Set<String> gotAnalysisParams = new HashSet<>();

    public boolean calledListApps() { return calledListApps; }

    public Set<String> gotAnalysisParams() { return gotAnalysisParams; }

    public void setAppParamsExcept(boolean e) {
        appParamsExcept = e;
    }

    public void setListAppStatus(int s) {
        listAppStatus = s;
    }

    public void setGetAppParamsStatus(int s) {
        getAppParamsStatus = s;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#createProject(java.util.Map)
     */
    @Override
    public JsonObject createProject(Map<String, String> params)
            throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#createFolder(java.lang.String, java.lang.String)
     */
    @Override
    public JsonObject createFolder(String path, String name) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#deleteElement(java.lang.String, java.lang.String)
     */
    @Override
    public JsonObject deleteElement(String folder, String name)
            throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#list(java.lang.String)
     */
    @Override
    public JsonObject list(String folder) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#getTable(java.lang.String)
     */
    @Override
    public JsonObject getTable(String tablePath) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#putTable(java.lang.String, com.eclipsesource.json.JsonArray, java.util.List)
     */
    @Override
    public JsonObject putTable(String path, JsonArray data,
            List<GxColumnDef> columns) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#analyze(java.lang.String, java.util.Map, boolean, boolean, boolean)
     */
    @Override
    public JsonObject analyze(String appName, JsonValue params,
            boolean isWorkflow, boolean wait, boolean progress)
            throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#getJobStatus(java.lang.String)
     */
    @Override
    public JsonObject getJobStatus(String jobId) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#listApplications()
     */
    @Override
    public JsonObject listApplications() throws Exception {
        calledListApps = true;
        return new JsonObject().add("type", listAppStatus)
                .add("values",new JsonArray().add("app1").add("app2").add("app3"));
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#listExporters()
     */
    @Override
    public JsonObject listExporters() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#listImporters()
     */
    @Override
    public JsonObject listImporters() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#getExporterParameters(java.lang.String, java.lang.String)
     */
    @Override
    public JsonObject getExporterParameters(String path, String exporter)
            throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#getImporterParameters(java.lang.String, java.lang.String)
     */
    @Override
    public JsonObject getImporterParameters(String path, String importer)
            throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#getAnalysisParameters(java.lang.String)
     */
    @Override
    public JsonObject getAnalysisParameters(String appName) throws Exception {
        if (appParamsExcept) {
            throw new RuntimeException("Test exception");
        }
        gotAnalysisParams.add(appName);
        JsonObject params = new JsonObject()
                                .add("type",getAppParamsStatus)
                                .add("values", new JsonArray()
                                        .add(new JsonObject()
                                                .add("name", appName + "-param")
                                                .add("displayName", appName + "-displayName")
                                                .add("description", appName + "-description")
                                         )
                                 );

        return params;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#export(java.lang.String, java.lang.String, java.io.OutputStream, java.util.Map)
     */
    @Override
    public void export(String path, String exporter, OutputStream fs,
            JsonValue params) throws Exception {
        // TODO Auto-generated method stub

    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#imPort(java.lang.String, java.lang.String, java.lang.String, java.util.Map)
     */
    @Override
    public JsonObject imPort(String file, String parentPath, String importer,
            JsonValue params) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#getConnection()
     */
    @Override
    public GxHttpConnection getConnection() {
        return con;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#setConnection(com.genexplain.api.core.GxHttpConnection)
     */
    @Override
    public GxHttpClient setConnection(GxHttpConnection con) throws Exception {
        this.con = con;
        return this;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#getVerbose()
     */
    @Override
    public boolean getVerbose() {
        // TODO Auto-generated method stub
        return false;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#setVerbose(boolean)
     */
    @Override
    public GxHttpClient setVerbose(boolean verbose) {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.genexplain.api.core.GxHttpClient#existsElement(java.lang.String, java.lang.String)
     */
    @Override
    public JsonObject existsElement(String element, String folder)
            throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public JsonObject importTable(String file, String folder, String tableName, boolean processQuotes,
            ColumnDelimiter delim, int headerRow, int dataRow, String commentString, String columnForID,
            boolean addSuffix, String tableType, String species) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }
}