Ejemplo n.º 1
0
 def getDriver(cls, driverType, connType):
     """take driverType and connType to return the corresponding class imported from the file system.
     Used internally and can be used for the connections where no authentification is needed (sqlite for instance)
     USAGE:
         with a context manager:
             drv = connectionManager.ConnectionManager.getDriver(driverType="sql", connType="sqlite")
             with drv(test="test") as c:
                 c.exec("execTest")
         without a context manager:
             drv = connectionManager.ConnectionManager.getDriver(driverType="sql", connType="sqlite")
             d = drv(test="test")
             d.connect()
             d.exec("execTest")
             d.close()
     """
     calcPath = _join(_realpath(_dirname(__file__)), "drivers", driverType,
                      connType + ".py")
     # we first check if the driver has already been imported and stored in the class to buy time
     try:
         try:
             return cls.drivers[driverType][connType]
         except KeyError:
             driver = _utils.importFromPath(calcPath)
             driver = driver.Driver
             if not cls.drivers.get(driverType):
                 cls.drivers[driverType] = {}
             cls.drivers[driverType][connType] = driver
             return driver
     except FileNotFoundError:
         raise FileNotFoundError("aucun driver trouvé dans " + calcPath)
Ejemplo n.º 2
0
def get_python_package_entry_point(package, entry_point):
    """
    Find an CLI entry point from a Python package.

    Args:
        package (str): Package name.
        entry_point (str): Entry point name.

    Returns:
        str or None: Path to entry point, or None if nothing found.
    """
    site_packages_path = _dirname(_import_module(package).__path__[0])

    # Find package info
    # Can be a directory ending by ".dist-info" or ".egg-info"
    with _scandir(site_packages_path) as entries:
        for entry in entries:
            if (entry.name.startswith(f'{package}-') and
                    _splitext(entry.name)[1] in ('.dist-info', '.egg-info')):
                package_info_path = entry.path
                break

        else:
            # Package is not installed or do not have package info
            return None

    # Find manifest file
    # Can be a "RECORD" or a "installed-files.txt" file in package info folder
    for name in ('RECORD', 'installed-files.txt'):
        manifest_path = _join(package_info_path, name)
        if _isfile(manifest_path):
            break

    else:
        # Package do not have manifest file
        return None

    # Find entry point relative path in manifest file
    # Possibles manifest file lines formats: "path\n" or "path,checksum\n"
    with open(manifest_path, 'rt') as manifest:

        for line in manifest:
            entry_point_rel_path = line.strip().split(',', 1)[0]
            if _basename(entry_point_rel_path) == entry_point:
                break

        else:
            # Entry point is not present in manifest
            return None

    # Convert to absolute path
    # Paths in manifest are relative to site-packages or package info
    for prefix in (site_packages_path, package_info_path):
        entry_point_path = _realpath(_join(prefix, entry_point_rel_path))

        if _isfile(entry_point_path):
            return entry_point_path
Ejemplo n.º 3
0
Archivo: setup.py Proyecto: uhle/solaar
def _data_files():
	from os.path import dirname as _dirname

	yield 'share/solaar/icons', _glob('share/solaar/icons/solaar*.svg')
	yield 'share/solaar/icons', _glob('share/solaar/icons/light_*.png')
	yield 'share/icons/hicolor/scalable/apps', ['share/solaar/icons/solaar.svg']

	for mo in _glob('share/locale/*/LC_MESSAGES/solaar.mo'):
		yield _dirname(mo), [mo]

	yield 'share/applications', ['share/applications/solaar.desktop']
	yield autostart_path, ['share/autostart/solaar.desktop']

	del _dirname
Ejemplo n.º 4
0
def _data_files():
    from os.path import dirname as _dirname

    yield 'share/solaar/icons', _glob('share/solaar/icons/solaar*.svg')
    yield 'share/solaar/icons', _glob('share/solaar/icons/light_*.png')
    yield 'share/icons/hicolor/scalable/apps', ['share/solaar/icons/solaar.svg']

    for mo in _glob('share/locale/*/LC_MESSAGES/solaar.mo'):
        yield _dirname(mo), [mo]

    yield 'share/applications', ['share/applications/solaar.desktop']
    yield 'share/solaar/udev-rules.d', ['rules.d/42-logitech-unify-permissions.rules']

    del _dirname
Ejemplo n.º 5
0
def _data_files():
	from os.path import dirname as _dirname

	yield 'share/solaar/icons', _glob('share/solaar/icons/solaar*.svg')
	yield 'share/solaar/icons', _glob('share/solaar/icons/light_*.png')
	yield 'share/icons/hicolor/scalable/apps', ['share/solaar/icons/solaar.svg']

	for mo in _glob('share/locale/*/LC_MESSAGES/solaar.mo'):
		yield _dirname(mo), [mo]

	yield 'share/applications', ['share/applications/solaar.desktop']
	yield autostart_path, ['share/applications/solaar.desktop']

	del _dirname
def _make_sure_path_not_exists_but_parent_directory_does(path):
    from os.path import isdir, exists

    if exists(path):
        return _no(f"path already exists - {path!r}")

    parent_dir = _dirname(path)
    if parent_dir == path:  # e.g. '' or '/'
        return _no(f"weird parent dir of path ({parent_dir!r} of {path!r})")
    if '' == parent_dir:
        parent_dir = '.'

    if not isdir(parent_dir):
        details = "Parent directory must exist - {parent_dir!r}"
        return _no(f"won't create more than one directory. {details}")
Ejemplo n.º 7
0
def _build_bitmap_data():
    '''
    Build an SFrame from 10 saved drawings.
    '''
    from os.path import join as _join, realpath as _realpath
    from os.path import splitext as _splitext, basename as _basename
    from os.path import dirname as _dirname
    drawings_dir = _join(_dirname(_realpath(__file__)), "drawings")
    sf = _tc.image_analysis.load_images(drawings_dir, with_path=True)
    sf = sf.rename({"image": "drawing", "path": "label"})
    sf["label"] = sf["label"].apply(
        lambda filepath: _splitext(_basename(filepath))[0][:-1]
        # Extract the class name from the filename, "check1.png" -> "check"
        # [:-1] is to get "check" out of "check1"
        )
    return sf
Ejemplo n.º 8
0
def render_template(src, dst, show=True, **kwargs):
    """
    Render a file from a template using Jinja2.

    Args:
        src (str): Source template.
        dst (str): Destination file.
        show (bool): If true, print result.
        kwargs: Template arguments.
    """
    from jinja2 import Environment, FileSystemLoader

    env = Environment(loader=FileSystemLoader(_dirname(src)))
    template = env.get_template(_basename(src))
    rendered = template.render(**kwargs)
    if show:
        print("\033[34m== START RENDERED ==\033[30m\n"
              f"{rendered}"
              "\n\033[34m== END RENDERED ==\033[30m")
    with open(dst, "wt") as file:
        file.write(rendered)
Ejemplo n.º 9
0
Requires XRT: https://github.com/Xilinx/XRT
"""
from ctypes import (cdll as _cdll, POINTER as _POINTER, c_char_p as _c_char_p,
                    c_uint as _c_uint, c_uint64 as _c_uint64, c_int as _c_int,
                    c_void_p as _c_void_p, c_size_t as _c_size_t)
from os import environ as _environ, fsdecode as _fsdecode
from os.path import isfile as _isfile, join as _join, realpath as _realpath, basename as _basename, dirname as _dirname
from re import match as _match
from subprocess import run as _run, PIPE as _PIPE, STDOUT as _STDOUT
from threading import Lock as _Lock

from tests.fpga_drivers import FpgaDriverBase as _FpgaDriverBase

__all__ = ['FpgaDriver']

SCRIPT_DIR = _dirname(_realpath(__file__))


class XrtLock():
    def __init__(self, driver):
        self.driver = driver
        # Define Lock function
        self.xcl_lock = driver._fpga_library.xclLockDevice
        self.xcl_lock.restype = _c_int
        self.xcl_lock.argtype = _c_void_p
        # Define Unlock function
        self.xcl_unlock = driver._fpga_library.xclLockDevice
        self.xcl_unlock.restype = _c_int
        self.xcl_unlock.argtype = _c_void_p

    def __enter__(self):
Ejemplo n.º 10
0
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNE A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses. 
#

from distutils.core import setup, Extension
from os import walk as _walk
from os.path import join as _join, dirname as _dirname
from glob import glob as _glob

NAME = 'simpleorderbook'
SOURCE_DIR = _join(_dirname(__file__),'src')

setup_dict = {
    "name":NAME,
    "version":'0.6',
    "description": "financial-market orderbook and matching engine",
    "author":"Jonathon Ogden",
    "author_email":"*****@*****.**"
} 

cpp_sources = [f for d,_,files in _walk(SOURCE_DIR) \
               for f in _glob(_join(d, "*.cpp")) + _glob(_join(d, "*.c"))]

cpp_include_dirs = ["../include", "./include"]
cpp_compile_flags = ["-std=c++11", "-Wno-invalid-offsetof"]
Ejemplo n.º 11
0
from os.path import dirname as _dirname

path_examples = _dirname(__file__) + '/data'
Ejemplo n.º 12
0
from os.path import join as _join

try:
    import winsound as _winsound
except ImportError:
    _winsound = None
try:
    # Python2
    import Tkinter as _tk
except ImportError:
    # Python3
    import tkinter as _tk

__all__ = ['YouDidntSayTheMagicWord', 'getpass', 'access_main_program']

_PATH = _dirname(_abspath(__file__))


class YouDidntSayTheMagicWord(Exception):
    """
        Custom YouDidntSayTheMagicWord exception that spams the console with
        "YOU DIDN'T SAY THE MAGIC WORD!" while displaying an animated gif of
        Dennis Nedry wagging his finger with "Uh uh uh, you didn't say the
        magic word." repeating in the background. Why? Because.

    """
    def __init__(self):
        self._console_spam()
        _sleep(0.8)
        self._audio_spam()
        self._gif_spam()
Ejemplo n.º 13
0
"""
This file contains variables defining the filesystem paths to various
directories within the Junos PyEZ microframework
"""
from os.path import dirname as _dirname
from os.path import join as _join

MODULEDIR = _dirname(__file__)
CFGDIR = _join(MODULEPATH,'cfg')
OPDIR = _join(MODULEPATH,'op')
CFGRODIR = _join(MODULEPATH,'cfgro')
Ejemplo n.º 14
0
#-*- coding: utf-8 -*-
import re as _re
from os.path import (dirname as _dirname, sep as _sep)
from . import cdict as _cdict

_sections = "(?:\[(?P<section>[a-z]+)\](?:\r\n)?)(?P<body>(?:(?:\r\n)?[\s0-9A-Za-z._+\-=\\/?]+)(?:\r\n)?)+"
_tags = r"(?:(?P<key>(?:[a-z]+))(?:(?: +)?=(?: +)?))(?P<value>(?:[\-+]?[^\s]+))"

projdir = '{}'.format(_sep).join(_dirname(__file__).split(_sep)[:-2])

def _load_file(cfgfile='app.ini'):
	filedir = '{}{}{}'.format(projdir, _sep, cfgfile)
	return open(filedir, 'rb').read()

_ofile = _load_file()
#print _ofile
_checktype = lambda val: eval(val) if val.isdigit() else val

_paramsDict = lambda match: _cdict((k.group('key'),_checktype(k.group('value'))) for k in _re.finditer(_tags, match.group('body')))

conf = _cdict((mt.group('section'),_paramsDict(mt)) for mt in _re.finditer(_sections, _ofile))
Ejemplo n.º 15
0
# -*- coding: utf-8 -*-

from __future__ import absolute_import

# set the warning format to be on a single line
import warnings as _warnings
from os import name as _name
from os.path import abspath as _abspath
from os.path import dirname as _dirname

# set the warning format to be prettier and fit on one line
_metabolicmodelgapfilling_path = _dirname(_abspath(__file__))
if _name == "posix":
    _warning_base = "%s:%s \x1b[1;31m%s\x1b[0m: %s\n"  # colors
else:
    _warning_base = "%s:%s %s: %s\n"


def _warn_format(message, category, filename, lineno, file=None, line=None):
    shortname = filename.replace(_metabolicmodelgapfilling_path,
                                 "MetabolicModelGapfilling", 1)
    return _warning_base % (shortname, lineno, category.__name__, message)


_warnings.formatwarning = _warn_format

import sys

from MetabolicModelGapfilling.core import (BaseModule, GapfillingModule)

__version__ = "0.1.0"
Ejemplo n.º 16
0
from os.path import join as _join, dirname as _dirname
from os.path import abspath as _abspath
import pandas as _pandas

datadir = _abspath(_join(_dirname(__file__), '..', 'ohmyyeast-data'))


def load_optpub():
    _cols = [
        'AID', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'e10', 'S',
        'k_SA', 'K_SA', 'k_BA', 'K_BA', 'ki_BA', 'Ki_BA', 'k_CA', 'K_CA',
        'ki_CA', 'Ki_CA', 'k_AA', 'K_AA', 'ki_AA', 'Ki_AA', 'k_AB', 'K_AB',
        'ki_AB', 'Ki_AB', 'k_CB', 'K_CB', 'ki_CB', 'Ki_CB', 'k_BB', 'K_BB',
        'ki_BB', 'Ki_BB', 'k_BC', 'K_BC', 'ki_BC', 'Ki_BC', 'k_AC', 'K_AC',
        'ki_AC', 'Ki_AC', 'k_CC', 'K_CC', 'ki_CC', 'Ki_CC', 'ki_EA', 'Ki_EA',
        'ki_EB', 'Ki_EB', 'ki_EC', 'Ki_EC', 'k_FA', 'K_FA', 'k_FB', 'K_FB',
        'k_FC', 'K_FC', 'FUS1MAX', 'Ke50_FUS1', 'kd', 'ks', 'n', 'At', 'Bt',
        'Ct', 'E', 'F', 'fVal'
    ]

    myfile = _join(datadir, 'opt/pub', 'reduced.mat.csv')
    dataset = _pandas.read_csv(myfile, names=_cols)

    for edge in ['e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'e10']:
        dataset[edge] = dataset[edge].astype(int)

    return dataset


def load_optsnu():
    myfile = _join(datadir, 'opt/snu', 'reduced.mat.csv')
Ejemplo n.º 17
0
"""
This library provides some DMR library specific CI/CD pipeline utilities.
"""
from os.path import (
    basename as _basename,
    dirname as _dirname,
    realpath as _realpath,
    join as _join,
)

DEPLOYMENT_DIR = _realpath(_dirname(__file__))
PROJECT_DIR = _dirname(DEPLOYMENT_DIR)


def setvariable(name, value, is_output=True):
    """
    Set a Azure pipeline variable.

    Args:
        name (str): Variable name.
        value (str): Variable value.
        is_output (bool): Make variable available to future jobs.
    """
    print(f"##vso[task.setvariable variable={name}"
          f'{";isOutput=true" if is_output else ""}]{value}')


def render_template(src, dst, show=True, **kwargs):
    """
    Render a file from a template using Jinja2.
Ejemplo n.º 18
0
# -*- coding: utf-8 -*-
"""
Parse PSE and config data.
Tries user-config, if not found, falls back to default
"""

from collections import OrderedDict as _ODict
from os.path import dirname as _dirname, expanduser as _expanduser
from json import load as _load, dump as _dump

with open(_dirname(__file__) + '/default.json') as _f:
    default = _load(_f, object_pairs_hook=_ODict)
try:
    with open(_expanduser('~/.vipster.json')) as _f:
        _cfile = _load(_f, object_pairs_hook=_ODict)
except:
    from copy import deepcopy as _deepcopy
    _cfile = _deepcopy(default)
pse = _cfile['PSE']
config = _cfile['General']
_paramdict = _cfile['Parameters']


def saveConfig():
    """Write config and PSE to json-file"""
    with open(_expanduser('~/.vipster.json'), 'w') as f:
        _dump(_ODict([('PSE', pse), ('General', config),
              ('Parameters', _paramdict)]), f, indent=2)

__all__ = ["pse", "config", "default", "saveConfig"]
Ejemplo n.º 19
0
def to_dirname(*paths):
    return _dirname(to_abspath(*paths))
Ejemplo n.º 20
0
def open_html(f_name, method="r"):
    html = _join(_dirname(_realpath(__file__)), "html")
    test_dir(html)
    return open(_join(html, f_name), method)
Ejemplo n.º 21
0
from os import listdir as _listdir
from os.path import dirname as _dirname
from importlib import import_module as _import_module

base_package = __name__.replace('.base', '')


def _not_implemented_conversion(item):
    raise NotImplementedError("This conversion has not been implemented yet")


list_api_forms = [
    filename.split('.')[0] for filename in _listdir(_dirname(__file__))
    if filename.startswith('api')
]

dict_api_forms = {}
list_forms = []
dict_converter = {}
dict_is_form = {}

for api_form in list_api_forms:
    module_api_form = _import_module('.' + api_form, base_package)
    form_name = module_api_form.form_name
    list_forms.append(form_name)
    dict_api_forms[form_name] = module_api_form
    dict_is_form.update(module_api_form.is_form)

for form_name in list_forms:
    dict_converter[form_name] = {}
    for method in dict_api_forms[form_name].__dict__.keys():
Ejemplo n.º 22
0
# -*- coding: utf-8 -*-
from os.path import (abspath as _abspath, dirname as _dirname, join as _join)

BASEDIR = _dirname(_dirname(_abspath(__file__)))
DATADIR = _join(BASEDIR, 'tests', 'data')
Ejemplo n.º 23
0
"""
Simple recipe maker module.
"""


from os.path import dirname as _dirname
from pysrc.snippets import unique_name

# noinspection PyTypeChecker
__DEFAULT_SAVE_DIR__ = _dirname(__file__).replace("/", "\\") + "\\created"


def save_recipe(recipe, fpath=None):
    """
    @param recipe: recipe to save
    @type recipe: Recipe
    @param fpath: filepath to save recipe as
    @type fpath: str
    @return: filepath to saved recipe
    @rtype: str
    """

    if fpath is None:
        name = getattr(recipe, 'Name', '')
        if not name:
            name = "PBSRecipe.txt"
        fpath = '\\'.join((__DEFAULT_SAVE_DIR__, name))
    fpath = unique_name(fpath)

    with open(fpath, 'w') as f:
        recipe.print_steps(f)
Ejemplo n.º 24
0
File autogenerated from C:/Users/PBS Biotech/Documents/Personal/PBS_Office/MSOffice/pbslib/recipemaker/makevars.py.

Python file to map pynames to recipe variable instances.
The list of variables should (almost) never change, except if
A different protocol is used to generate pynames from var names.
Instead of needing to import and generate at runtime, just import
this python file. This file will automatically raise ValueError
if it detects that the corresponding csv file is out of date.

"""

from os.path import getmtime as _getmtime, dirname as _dirname, join as _join

# Filenames as passed to makevars.make_vars_py()
__curdir = _dirname(__file__)
__module = _join(__curdir, "recipe_vars.py")
__csv = _join(__curdir, "vars_db", "recipe_vars.csv")

if _getmtime(__csv) > _getmtime(__module):
    raise ImportError("Warning! Pyfile is outdated. Regenerate from makevars.py.")

from pbslib.recipemaker import RecipeVariable


pHDeadband = RecipeVariable("pHDeadband")
AlarmBuzzerActual = RecipeVariable("AlarmBuzzerActual")
MFCN2OutRawOn = RecipeVariable("MFCN2OutRaw(V).On(iter)")
PumpsValvesPumpSmplRevrsReq = RecipeVariable("Pumps&ValvesPumpSmplRevrsReq")
CalTempASlope = RecipeVariable("CalTempA.Slope")
AgMainGasUser = RecipeVariable("AgMainGasUser(LPM)")
Ejemplo n.º 25
0
from os.path import join as _path_join, dirname as _dirname, realpath as _realpath                    
from os import system as _system, getcwd as _getcwd, remove as _remove
from shutil import rmtree as _rmtree


NAME = 'tosdb'
VERSION = '0.9'
DESCRIPTION = "Python Front-End / Wrapper for TOSDataBridge"
AUTHOR = "Jonathon Ogden"
AUTHOR_EMAIL = "*****@*****.**"
PACKAGES = ['tosdb','tosdb/cli_scripts','tosdb/intervalize', 'tosdb/streaming']  


_AUTO_EXT = '_tosdb' 
# everything should be relative to the python/setup.py
_OUR_PATH = _dirname(_realpath(__file__))
_HEADER_NAME = 'tos_databridge.h'
_HEADER_PATH = _path_join(_OUR_PATH, '..', 'include', _HEADER_NAME)
_OUTPUT_PATH = _path_join(_OUR_PATH, NAME, _AUTO_EXT + '.py')

if _OUR_PATH != _getcwd():
    _sys.stderr.write("fatal: setup.py must be run from its own directory(python/)\n")
    exit(1)


#string that should bookmark the topics in Topic_Enum_Wrapper::TOPICS<T> 
_MAGIC_TOPIC_STR = 'ksxaw9834hr84hf;esij?><'

#regex for finding our header #define consts 
#TODO: adjust so we can pull non-ints
_REGEX_HEADER_CONST = "#define[\s]+([\w]+)[\s]+.*?(-?[\d][\w]*)"
Ejemplo n.º 26
0
# -*- coding: utf-8 -*-
# Copyright © 2017 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from __future__ import print_function as _
from __future__ import division as _
from __future__ import absolute_import as _
import ctypes as _ctypes
import glob as _glob
import sys as _sys
from os.path import dirname as _dirname, join as _join

_thismodule = _sys.modules[__name__]
_current_path = _dirname(_thismodule.__file__)
library_locations = _glob.glob(_join(_current_path, 'libminipsutil.so'))
library_locations += _glob.glob(_join(_current_path, 'libminipsutil.dylib'))
library_locations += _glob.glob(_join(_current_path, 'libminipsutil.dll'))

_totalmem = 0
_ncpus = 0
_lib = None
try:
    _lib = _ctypes.cdll.LoadLibrary(library_locations[0])
    _lib.num_cpus.restype = _ctypes.c_int32
    _lib.total_mem.restype = _ctypes.c_uint64
    _lib.pid_is_running.restype = _ctypes.c_int32
    _lib.kill_process.restype = _ctypes.c_int32
    _ncpus = _lib.num_cpus()
    _totalmem = _lib.total_mem()
except:
Ejemplo n.º 27
0
from os.path import dirname as _dirname, basename as _basename, isfile as _isfile
import glob as _glob

exec("\n".join(
    map(
        lambda name: "from ." + name + " import *",
        [
            _basename(f)[:-3]
            for f in _glob.glob(_dirname(__file__) + "/*.py")
            if _isfile(f) and not _basename(f).startswith("_")
        ],
    )))
Ejemplo n.º 28
0
"""
iracema is a python package aimed at the extraction of expressive music
information from audio signals
"""
from os.path import dirname as _dirname

import iracema.core.timeseries
import iracema.core.audio
import iracema.core.point
import iracema.core.segment

from iracema.core.timeseries import TimeSeries
from iracema.core.audio import Audio
from iracema.core.point import Point, PointList
from iracema.core.segment import Segment, SegmentList

import iracema.features
import iracema.pitch
import iracema.harmonics
import iracema.segmentation
import iracema.spectral
import iracema.plot
import iracema.util

import iracema.segmentation.onsets

__version__ = u'0.2.1'

root = _dirname(__spec__.origin)
Ejemplo n.º 29
0
from re import match as _match, search as _search
from time import asctime as _asctime
from os.path import join as _path_join, dirname as _dirname, realpath as _realpath
from os import system as _system, getcwd as _getcwd, remove as _remove
from shutil import rmtree as _rmtree

NAME = 'tosdb'
VERSION = '0.8'
DESCRIPTION = "Python Front-End / Wrapper for TOSDataBridge"
AUTHOR = "Jonathon Ogden"
AUTHOR_EMAIL = "*****@*****.**"
PACKAGES = ['tosdb', 'tosdb/cli_scripts', 'tosdb/intervalize']

_AUTO_EXT = '_tosdb'
# everything should be relative to the python/setup.py
_OUR_PATH = _dirname(_realpath(__file__))
_HEADER_NAME = 'tos_databridge.h'
_HEADER_PATH = _path_join(_OUR_PATH, '..', 'include', _HEADER_NAME)
_OUTPUT_PATH = _path_join(_OUR_PATH, NAME, _AUTO_EXT + '.py')

if _OUR_PATH != _getcwd():
    _sys.stderr.write(
        "fatal: setup.py must be run from its own directory(python/)\n")
    exit(1)

#string that should bookmark the topics in Topic_Enum_Wrapper::TOPICS<T>
_MAGIC_TOPIC_STR = 'ksxaw9834hr84hf;esij?><'

#regex for finding our header #define consts
#TODO: adjust so we can pull non-ints
_REGEX_HEADER_CONST = "#define[\s]+([\w]+)[\s]+.*?(-?[\d][\w]*)"
Ejemplo n.º 30
0
"""The GeoKit library is a collection of general geospatial operations"""

__version__ = "1.2.0"

# maybe set GDAL_DATA variable
from os import environ as _environ
from os.path import join as _join, dirname as _dirname, basename as _basename
# from warnings import warn as _warn

if not "GDAL_DATA" in _environ:
    from os.path import isdir as _isdir
    from sys import executable as _executable
    
    for d in [_join(_dirname(_executable),"Library","share","gdal"), # Common location on windows
              _join(_dirname(_executable),"..","share","gdal")]: # Common location on linux
        if _isdir(d):
            # _warn("Setting GDAL_DATA to: "+d, UserWarning)
            _environ["GDAL_DATA"] = d
            break

    if not "GDAL_DATA" in _environ:
        raise RuntimeError("Could not locate GDAL_DATA folder. Please set this as an environment variable pointing to the GDAL static files")
    

# import the utilities
import geokit.util
import geokit.srs
import geokit.geom
import geokit.raster
import geokit.vector
Ejemplo n.º 31
0
from os.path import abspath as _abspath, dirname as _dirname
_PROJECT_ROOT = _dirname(_abspath(__file__))

ADMINS = (
    # ('Your Name', '*****@*****.**'),
)

MANAGERS = ADMINS

LOGIN_URL = '/openid/login/'
LOGIN_REDIRECT_URL = '/publish/'

OPENID_USE_AS_ADMIN_LOGIN = True

DATABASES = {
	'default': {
		'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
		'NAME': 'data',					  # Or path to database file if using sqlite3.
		'USER': '',					  # Not used with sqlite3.
		'PASSWORD': '',				  # Not used with sqlite3.
		'HOST': '',					  # Set to empty string for localhost. Not used with sqlite3.
		'PORT': '',					  # Set to empty string for default. Not used with sqlite3.
	}
}

USE_TZ=True

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
Ejemplo n.º 32
0
# THE SOFTWARE.

"""
This module holds configuration settings parsed from TritonScraper's configuration file (:file:`config.cfg`).

:copyright: (c) 2010 by Christopher Rebert.
:license: MIT, see :file:`LICENSE.txt` for more details.
"""

from ConfigParser import RawConfigParser as _RawConfigParser
from os.path import dirname as _dirname, join as _pathjoin

### Fetch configuration settings
CONFIG_FILENAME = 'config.cfg'
#: Full path to configuration file
CONFIG_FILEPATH = _pathjoin(_dirname(__file__), CONFIG_FILENAME)
cfg = _RawConfigParser()
with open(CONFIG_FILEPATH, 'r') as config_file:
    cfg.readfp(config_file)
del config_file

#: Name of main section in INI config file
_MAIN_SECT = 'main'
#: HTTP User-Agent to use
USER_AGENT = cfg.get(_MAIN_SECT, 'useragent')
#: Python logger name to use
LOGGER_NAME = cfg.get(_MAIN_SECT, 'loggername')
#: How many seconds to wait before retrying upon encountering a transient error.
RETRY_DELAY = float(cfg.get(_MAIN_SECT, 'waitbeforeretry'))
#: Socket timeout (in seconds) to set
SOCKET_TIMEOUT = float(cfg.get(_MAIN_SECT, 'socktimeout'))
Ejemplo n.º 33
0
"""The Geospatial Land Availability for Energy Systems (GLAES) model is intended for land eligbility analysis in any context"""

__version__ = "1.1.8"

from .core import util
from .core.priors import Priors
from .core.ExclusionCalculator import ExclusionCalculator
from .core.WeightedCriterionCalculator import WeightedCriterionCalculator
from .predefinedExclusions import ExclusionSets

from os.path import join as _join, dirname as _dirname, basename as _basename
from collections import OrderedDict as _OrderedDict
from glob import glob as _glob
_test_data_ = _OrderedDict()

for f in _glob(_join(_dirname(__file__), "test", "data", "*")):
    _test_data_[_basename(f)] = f
Ejemplo n.º 34
0
# -*- coding: utf-8 -*-

from __future__ import absolute_import

# set the warning format to be on a single line
import warnings as _warnings
from os import name as _name
from os.path import abspath as _abspath
from os.path import dirname as _dirname

from cobra import flux_analysis, io
from cobra.core import (
    DictList, Gene, Metabolite, Model, Object, Reaction, Species)
from cobra.util.version_info import show_versions

__version__ = "0.11.2"

# set the warning format to be prettier and fit on one line
_cobra_path = _dirname(_abspath(__file__))
if _name == "posix":
    _warning_base = "%s:%s \x1b[1;31m%s\x1b[0m: %s\n"  # colors
else:
    _warning_base = "%s:%s %s: %s\n"


def _warn_format(message, category, filename, lineno, file=None, line=None):
    shortname = filename.replace(_cobra_path, "cobra", 1)
    return _warning_base % (shortname, lineno, category.__name__, message)
_warnings.formatwarning = _warn_format
Ejemplo n.º 35
0
from typing import TypeVar
from os.path import join as _join
from os.path import dirname as _dirname

with open(_join(_dirname(__file__), "VERSION")) as _f:
    __version__ = _f.read().strip()

_T = TypeVar("_T")


class _Indexable:
    __slots__ = ()

    def __getitem__(self, index: _T) -> _T:
        return index


index = _Indexable()

from .tensor import Tensor  # noqa: F401,E402
from .tensor import TensorType  # noqa: F401,E402
from .tensor import istensor  # noqa: F401,E402

from .tensor import PyTorchTensor  # noqa: F401,E402
from .tensor import TensorFlowTensor  # noqa: F401,E402
from .tensor import NumPyTensor  # noqa: F401,E402
from .tensor import JAXTensor  # noqa: F401,E402

from . import types  # noqa: F401,E402

from .astensor import astensor  # noqa: F401,E402
Ejemplo n.º 36
0
def open_local(f_name, method="r"):
    try:
        return open(_join(_expanduser("~"), ".klb/" + f_name), method)
    except:
        folder = _dirname(_realpath(__file__))
        return open(_join(folder, "blank_file"))
Ejemplo n.º 37
0
def open_local(f_name, method="r"):
    try:
        return open(_join(_expanduser("~"), ".klb/" + f_name),method)
    except:
        folder = _dirname(_realpath(__file__))
        return open(_join(folder, "blank_file"))
Ejemplo n.º 38
0
"""
Copyright (C) 2016 Turi
All rights reserved.

This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
import ctypes as _ctypes
import glob as _glob
import sys as _sys
from os.path import dirname as _dirname, join as _join

_thismodule = _sys.modules[__name__]
_current_path = _dirname(_thismodule.__file__)
library_locations = _glob.glob(_join(_current_path, "libminipsutil.so"))
library_locations += _glob.glob(_join(_current_path, "libminipsutil.dylib"))
library_locations += _glob.glob(_join(_current_path, "libminipsutil.dll"))

_totalmem = 0
_ncpus = 0
_lib = None
try:
    _lib = _ctypes.cdll.LoadLibrary(library_locations[0])
    _lib.num_cpus.restype = _ctypes.c_int32
    _lib.total_mem.restype = _ctypes.c_uint64
    _lib.pid_is_running.restype = _ctypes.c_int32
    _lib.kill_process.restype = _ctypes.c_int32
    _ncpus = _lib.num_cpus()
    _totalmem = _lib.total_mem()
except:
    pass
Ejemplo n.º 39
0
from os.path import dirname as _dirname, basename as _basename, isfile as _isfile
import glob as _glob

exec('\n'.join(map(lambda name: "from ." + name + " import *", 
                   [_basename(f)[:-3] for f in _glob.glob(_dirname(__file__) + "/*.py") \
                    if _isfile(f) and not _basename(f).startswith('_')])))
Ejemplo n.º 40
0
"""The GeoKit library is a collection of general geospatial operations"""

__version__ = "1.2.9"

# maybe set GDAL_DATA variable
from os import environ as _environ
from os.path import join as _join, dirname as _dirname, basename as _basename

# from warnings import warn as _warn

if not "GDAL_DATA" in _environ:
    from os.path import isdir as _isdir
    from sys import executable as _executable

    for d in [
            _join(_dirname(_executable), "Library", "share",
                  "gdal"),  # Common location on windows
            _join(_dirname(_executable), "..", "share", "gdal"),
    ]:  # Common location on linux
        if _isdir(d):
            # _warn("Setting GDAL_DATA to: "+d, UserWarning)
            _environ["GDAL_DATA"] = d
            break

    if not "GDAL_DATA" in _environ:
        raise RuntimeError(
            "Could not locate GDAL_DATA folder. Please set this as an environment variable pointing to the GDAL static files"
        )

# import the utilities
import geokit.util
Ejemplo n.º 41
0
from os.path import join as _join
from os.path import dirname as _dirname

with open(_join(_dirname(__file__), 'VERSION')) as _f:
    __version__ = _f.read().strip()

from .server import model_server  # noqa: F401
from .client import TinyImageNetBSONModel  # noqa: F401
from .utils import load_model  # noqa: F401
from .utils import read_images  # noqa: F401
from .utils import store_adversarial  # noqa: F401
from .utils import get_test_data  # noqa: F401
from .utils import attack_complete  # noqa: F401
from .notifier import ModelNotifications, AttackNotifications  # noqa: F401
Ejemplo n.º 42
0
from __future__ import absolute_import

# set the warning format to be on a single line
import warnings as _warnings
from os import name as _name
from os.path import abspath as _abspath
from os.path import dirname as _dirname

from cobra.core import (Configuration, DictList, Gene, Metabolite, Model,
                        Object, Reaction, Species)
from cobra import flux_analysis
from cobra import io
from cobra.util import show_versions

__version__ = "0.14.2"

# set the warning format to be prettier and fit on one line
_cobra_path = _dirname(_abspath(__file__))
if _name == "posix":
    _warning_base = "%s:%s \x1b[1;31m%s\x1b[0m: %s\n"  # colors
else:
    _warning_base = "%s:%s %s: %s\n"


def _warn_format(message, category, filename, lineno, file=None, line=None):
    shortname = filename.replace(_cobra_path, "cobra", 1)
    return _warning_base % (shortname, lineno, category.__name__, message)


_warnings.formatwarning = _warn_format
Ejemplo n.º 43
0
# Importing the dependencies
from os.path import dirname as _dirname, basename as _basename,\
        isfile as _isfile
import glob as _glob

exec('\n'.join(
    map(lambda name: "from ." + name + " import *", [
        _basename(f)[:-3] for f in _glob.glob(_dirname(__file__) + "/*.py")
        if _isfile(f) and not _basename(f).startswith('_')
    ])))