def get_file_path(filename): """ Find the book_title excel file path. """ root_dir = d(d(abspath(__file__))) root = Path(root_dir) filepath = root / 'stateful_book' / filename return r'{}'.format(filepath)
def boot(): """Configure application startup flow""" from os import path from os.path import dirname as d, join as j, abspath as a from sys import path as p if p[0] == d(__file__): del p[0] p.insert(0, a(j(d(__file__), '..'))) import deployer
class ExternalExe(object): ''' Main class to derive others that will control the execution of external programs. Program configuration is defined in the configSBI.txt file or can be defined in a file linked to a environment variable called SBI_CONFIG_FILE. ''' __metaclass__ = ABCMeta DEFAULT_CONFIG_FILE = j(n(d(__file__)), 'configSBI.txt') # Executable configuration _CONFIG = ConfigParser.RawConfigParser(allow_no_value=True) _EXE = None def __new__(cls, *args, **kwargs): cls._CONFIG.read(os.getenv('SBI_CONFIG_FILE', cls.DEFAULT_CONFIG_FILE)) return super(ExternalExe, cls).__new__(cls, *args, **kwargs) ################### # PRIVATE METHODS # ################### def _set_default_executable(self, external_id): ''' Configure the {Executable} of the class according to the default configuration as defined in the default configSBI.txt or the SBI_CONFIG_FILE @param: external_id @pdef: name of the external program as referred in the configSBI.txt file. @ptype: {String} ''' i, e, p = external_id, 'executable', 'path' self._EXE = Executable(executable=self._CONFIG.get(i, e), path=self._CONFIG.get(i, p)) @staticmethod def _set_dynamic_executable(executable, path): ''' Manual configuration of the {Executable}. @param: executable @pdef: name of the executable file @ptype: {String} @param: path @pdef: path to the executable file @ptype: {String} ''' ExternalExe._EXE = Executable(executable=executable, path=path)
def read_uri(uri: str, allow_file=False) -> str: """ Read a file from either a url or a file uri """ url = urllib.parse.urlsplit(uri) scheme = url[0].lower() if allow_file and 'file' in scheme: path = ''.join(url[1:3]) if not os.path.isabs(path): from os.path import dirname as d path = os.path.join(d(d(d(__file__))), path) try: with open(path) as f: return f.read() except FileExistsError: raise urllib.error.URLError("Could not find file", filename=uri) elif scheme.startswith('http'): req = urllib.request.Request(urllib.parse.urlunsplit(url)) with urllib.request.urlopen(req) as f: # nosec This cannot open uris # that are not of the http scheme return f.read().decode('utf-8') raise urllib.error.URLError("unsupported uri scheme", filename=uri)
def loadRooms(config_path=None) -> RoomConfig: from os.path import dirname as d schema = RoomsConfigSchema() if not config_path: config_path = os.path.join(d(__file__), "rooms.json") with open(config_path) as file: conf_obj = dict(rooms=json.load(file)) config = schema.load(conf_obj) if config.errors: err_msg = schemas.getErrorString(config.errors) raise RuntimeError(f"Couldn't parse rooms.json\n{err_msg}") return config.data
def start_builder(short_name=None, build_setting_file=None, dir_template=None, output_dir=None, version="1.0.0", logger=None, html_setting=None, only_build_py=False, **kwargs): local_logger = logger or main_logger current_dir = d(os.path.abspath(__file__)) if not os.path.isabs(build_setting_file): build_setting_file = os.path.sep.join( [current_dir, build_setting_file]) input_setting = None with open(build_setting_file, "r") as bsf: setting_content = bsf.read() input_setting = json.loads( check_file_name(setting_content, { "short_name": short_name, "version": version })) build_components = {"html": True, "conf": True, "py": True} if only_build_py: build_components["html"] = False build_components["conf"] = False template = sep.join([current_dir, "arf_dir_templates", dir_template]) return modular_alert_builder.build(input_setting=input_setting, short_name=short_name, template=template, output_dir=output_dir, logger=local_logger, version=version, html_setting=html_setting, build_components=build_components, **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from os.path import dirname as d lib_name = os.path.basename(d(d(d(__file__)))) # logging LOG_ROOT = '.' PROJECT_ACCESS_LOG = "access_log" PROJECT_INFO_LOG = "trace_log" PROJECT_ERROR_LOG = "trace_error" PROJECT_EXCEPTION_LOG = "trace_exception" PROJECT_BASESERVICE_LOG = "baseservice_log" LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'debug_verbose': { 'format': '[%(asctime)s] %(levelname)s:\n %(module)s:%(lineno)d %(message)s' }, 'verbose': { 'format': '[%(asctime)s] %(levelname)s:\n %(message)s' }, 'exception': { 'format': '[%(asctime)s] %(levelname)s %(module)s Line:%(lineno)d:\n' }, 'trace_service': { 'format': '%(message)s' }, },
#-------------------------------------------------------------------------- # # Albow - OpenGL Demo # #-------------------------------------------------------------------------- screen_size = (640, 480) flags = 0 import os, sys from os.path import dirname as d sys.path.insert(1, d(d(os.path.abspath(sys.argv[0])))) from OpenGL.GL import * import pygame pygame.init() from pygame.color import Color from pygame.locals import * from albow.root import RootWidget from albow.controls import Button from albow.layout import Row, Frame from albow.opengl import GLOrtho, GLPerspective #-------------------------------------------------------------------------- class DemoButton(Button): bg_color = Color("brown") border_width = 2 margin = 4
############################################################################### # # Albow - Demonstration # ############################################################################### screen_size = (640, 480) flags = 0 frame_time = 50 # ms incr_time = 25 # ms import os, sys from os.path import dirname as d sys.path.insert(1, d(d(os.path.abspath(sys.argv[0])))) import pygame pygame.init() from pygame.color import Color from pygame.locals import * from pygame.event import * from pygame.key import * from math import pi from albow.widget import Widget from albow.controls import Label, Button, Image, AttrRef, \ RadioButton, ValueDisplay, ProgressBar from albow.layout import Row, Column, Grid from albow.fields import TextField, FloatField from albow.shell import Shell from albow.screen import Screen from albow.text_screen import TextScreen
# -*- coding: UTF-8 -*- # Copyright 2016 Red Hat, Inc. # Part of clufter project # Licensed under GPLv2+ (a copy included | http://gnu.org/licenses/gpl-2.0.txt) """Testing `needleqdevicexml2pcscmd' filter""" __author__ = "Jan Pokorný <jpokorny @at@ Red Hat .dot. com>" # following makes available also: TeardownFilterTestCase, rewrite_root from os.path import join, dirname as d execfile(join(d(d((__file__))), '_com')) from .filter_manager import FilterManager flt = 'needleqdevicexml2pcscmd' cib2pcscmd = FilterManager.init_lookup(flt).filters[flt] cib = cib2pcscmd.in_format class FiltersCib2pcscmdQuorumDeviceTestCase(TeardownFilterTestCase): def testQuorumDeviceNet(self): flt_obj = rewrite_root(self.flt_mgr.filters[flt], 'corosync/quorum') in_fmt = flt_obj.in_format io_strings = (('''\ <device model="net"> <net host="191.168.10.20"/> </device> ''', '''\ pcs quorum device add model net host=191.168.10.20 '''), ) for (in_str, out_str) in io_strings: in_obj = in_fmt('bytestring', in_str,
def test(): from pytest import main as m from os.path import dirname as d m(['-x', d(__file__)])
#!/usr/bin/env python from django.core.management import execute_manager from os.path import abspath, dirname as d import sys sys.path.insert(0, d(d(abspath(__file__)))) sys.path.insert(0, d(d(d(d(abspath(__file__)))))) try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
import os from . import schema from ruamel import yaml from os.path import dirname as d path = os.path.join(d(d(d(__file__))), "config.yml") def get_settings(): print("Entering First Time Setup.\n") data = dict() fields = schema.ConfigSchema._declared_fields print("Minecraft Server info") data["ip"] = input("Enter the IP/address of the server ({}): ".format( fields["ip"].missing)) data["port"] = None while data["port"] is None: p = input("Enter the port of the server ({}):".format( fields["port"].missing)) if p == "": data["port"] = "" break try: data["port"] = int(p) if data["port"] < 0 or data["port"] > 65535: data["port"] = None raise ValueError except ValueError:
from os import listdir as ld from os import makedirs as md from os.path import isdir as d from re import findall from shutil import copyfile as cp root = 'C:/Users/Ritik/Desktop/2021 Autumn Semester/Assignments/AI/ArtificialIntelligenceProject/Algorithms/' maxver = 0 for f in ld(root): if d(root + f) and f[0] == 'v': x = findall('v([0-9]*).*', f) maxver = max(maxver, int(x[0])) fmaxver = root + f + '/' if not maxver: ver = 1 md(root + f'v{ver}') else: ver = maxver + 1 md(root + f'v{ver}') for f in ld(fmaxver): if f'v{maxver}' in f: d = f.replace(f'v{maxver}', f'v{ver}') else: d = f cp(fmaxver + f, root + f'v{ver}/' + d)
EXTENSIONS = ('.png', '.jpeg', '.jpg', 'jpe', '.gif') from os.path import join, dirname as d, exists imgdir = join(d(d(d(d(__file__)))), 'doc') def mknode(handle, node): for ext in EXTENSIONS: if exists(join(imgdir, handle + ext)): return """%s [ label=<<TABLE BORDER="0"><TR><TD><IMG SRC="%s%s"/></TD><TD>%s</TD></TR></TABLE>> ]""" % (handle, handle, ext, "<BR/>".join('%s = "%s"' % entry for entry in node)) else: return '%s [label="%s"]' % (handle, node) with open(join(d(d(d(__file__))), "test", "resources", "matrix.data")) as matrix: matrix = list(matrix) edges = [ map(str.strip, line.strip().split(';')[1:]) for line in matrix if line.startswith('FRIENDS') ] nodes = dict( (edge[0].replace(' ', '_'), [('name', edge[0])]) for edge in edges) nodes.update( dict((edge[1].replace(' ', '_'), [('name', edge[1])]) for edge in edges))
from marshmallow import Schema, fields, post_load, ValidationError from os import path import json import adventurelib import time from os.path import dirname as d import os from . import schemas, cipher _game_data_file = path.join(d(d(__file__)), 'saves') if not os.path.isdir(_game_data_file): os.mkdir(_game_data_file) timeStamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getmtime(_game_data_file))) file_count = len(os.listdir(_game_data_file)) if not path.isdir(_game_data_file): os.mkdir(_game_data_file) class GameData: def __init__(self, callsign: str, turn_counter: int = 0, oxygen: int = 100, nutrition: int = 9, hydration: int = 6, vitality: int = 3, player: schemas.objects.Player = None, rooms: list = None,
EXTENSIONS=('.png','.jpeg','.jpg','jpe','.gif') from os.path import join, dirname as d, exists imgdir=join(d(d(d(d(__file__)))),'doc') def mknode(handle, node): for ext in EXTENSIONS: if exists(join(imgdir, handle + ext)): return """%s [ label=<<TABLE BORDER="0"><TR><TD><IMG SRC="%s%s"/></TD><TD>%s</TD></TR></TABLE>> ]""" % (handle,handle,ext,"<BR/>".join('%s = "%s"' % entry for entry in node)) else: return '%s [label="%s"]' % (handle, node) with open(join(d(d(d(__file__))),"test","resources","matrix.data")) as matrix: matrix = list(matrix) edges = [map(str.strip, line.strip().split(';')[1:]) for line in matrix if line.startswith('FRIENDS')] nodes = dict((edge[0].replace(' ','_'),[('name',edge[0])])for edge in edges) nodes.update( dict((edge[1].replace(' ','_'),[('name',edge[1])]) for edge in edges)) for line in matrix: if line.startswith('PROPERTY'): name, key, value = line.split(';')[1:] nodes[name.strip().replace(' ','_')].append( (key.strip(),value.strip())) for node in nodes.values(): node.append(("interests",[])) for line in matrix: if line.startswith('INTEREST'): name, interest = line.split(';')[1:] nodes[name.strip().replace(' ','_')][-1][1].append(interest.strip())
# 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. """ Import ISD/AD data from topology files """ # Stdlib import glob import os import sys from os.path import dirname as d sys.path.insert(0, d(d(os.path.abspath(__file__)))) # noqa sys.path.insert(0, d(d(d(d(os.path.abspath(__file__)))))) # noqa # Set up the Django environment os.environ['DJANGO_SETTINGS_MODULE'] = 'web_scion.settings.private' # noqa # External packages import django from django.db import transaction import yaml # SCION from lib.defines import GEN_PATH, PROJECT_ROOT from lib.topology import Topology
Example usage: python3 ./scripts/update_credentials.py --dir=<path_to_isd_folder> --isd=2 """ # Stdlib import argparse import json import os import re import sys import yaml from os.path import dirname as d WEB_SCION_DIR = d(d(os.path.abspath(__file__))) # noqa SCION_ROOT_DIR = d(d(WEB_SCION_DIR)) # noqa SCION_PYTHON_ROOT_DIR = os.path.join(SCION_ROOT_DIR, 'python') # noqa sys.path.insert(0, WEB_SCION_DIR) # noqa sys.path.insert(0, SCION_ROOT_DIR) # noqa sys.path.insert(0, SCION_PYTHON_ROOT_DIR) # noqa # Set up the Django environment os.environ['DJANGO_SETTINGS_MODULE'] = 'web_scion.settings.private' # noqa # External packages import django # SCION from lib.crypto.util import ( CERT_DIR,
# -*- coding: UTF-8 -*- # Copyright 2015 Red Hat, Inc. # Part of clufter project # Licensed under GPLv2+ (a copy included | http://gnu.org/licenses/gpl-2.0.txt) """Testing `simpleconfig2needlexml' filter""" __author__ = "Jan Pokorný <jpokorny @at@ Red Hat .dot. com>" from os.path import join, dirname as d; execfile(join(d(d((__file__))), '_go')) from os.path import dirname, join from unittest import TestCase from .filter_manager import FilterManager from .formats.simpleconfig import simpleconfig flt = 'simpleconfig2needlexml' simpleconfig2needlexml = FilterManager.init_lookup(flt).filters[flt] class FiltersSimpleconfig2NeedlexmlTestCase(TestCase): def testSimpleconfig2Needlexml(self): result = simpleconfig2needlexml(simpleconfig('struct', ('corosync-ONLY-INTERNAL-TAG-NOT-EXTERNALIZED-ANYWAY', [], [('totem', [('version', '2'), ('cluster_name', 'aus-cluster')], {}), ('nodelist', [], [('node', [('nodeid', '1'), ('ring0_addr', 'lolek.example.com')], []), ('node', [('nodeid', '2'), ('ring0_addr', 'bolek.example.com')], [])]), ('quorum',
#!/usr/bin/env python from django.core.management import execute_manager from os.path import abspath, dirname as d import sys sys.path.insert(0, d(d(abspath(__file__)))) sys.path.insert(0, d(d(d(d(abspath(__file__)))))) try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write( "Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
"""Configuration parameters for pytest.""" # pylint: disable=unused-import import sys from os.path import abspath from os.path import dirname as d from os.path import join from pytest_mock import mocker ROOT_DIR = d(d(abspath(__file__))) sys.path.insert(0, ROOT_DIR) sys.path.insert(0, abspath(join(d(__file__), 'lib'))) print(sys.path)
# -*- coding: UTF-8 -*- # Copyright 2015 Red Hat, Inc. # Part of clufter project # Licensed under GPLv2+ (a copy included | http://gnu.org/licenses/gpl-2.0.txt) """Testing `ccs-version-bump' filter""" __author__ = "Jan Pokorný <jpokorny @at@ Red Hat .dot. com>" from os.path import join, dirname as d; execfile(join(d(d((__file__))), '_go')) from os.path import dirname, join from unittest import TestCase from .filter_manager import FilterManager flt = 'ccs-version-bump' ccs_version_bump = FilterManager.init_lookup(flt).filters[flt] ccs = ccs_version_bump.in_format class FiltersCcsVersionBumpTestCase(TestCase): def testVersionBump(self): in_obj = ccs('file', join(dirname(dirname(__file__)), 'filled.conf')) ret = ccs_version_bump(in_obj) #print ret.BYTESTRING() old_ver = int(in_obj.ETREE().xpath("/cluster/@config_version")[0]) new_ver = int(ret.ETREE().xpath("/cluster/@config_version")[0]) self.assertEquals(old_ver + 1, new_ver) from os.path import join, dirname as d; execfile(join(d(d(__file__)), '_gone'))
#!/usr/bin/env python # vim: set fileencoding=utf8 shiftwidth=4 tabstop=4 textwidth=80 foldmethod=marker : # Copyright (c) 2011, Kou Man Tong. All rights reserved. # For licensing, see LICENSE file included in the package. import applepushnotification.tests, sys from os.path import realpath as r, join as j, dirname as d from optparse import OptionParser if __name__ == "__main__": parser = OptionParser(usage = \ u"""Runs applepushnotification unit test cases. usage: %prog pem_file hex_token""") options, args = parser.parse_args() if len(args) < 2: parser.print_help() sys.exit(-1) applepushnotification.tests.pem_file = j(d(__file__), args[0]) applepushnotification.tests.hex_token = args[1] applepushnotification.tests.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from os.path import dirname as d lib_name = os.path.basename(d(d(d(__file__)))) # logging LOG_ROOT = '.' PROJECT_INFO_LOG = "blog.trace_info" PROJECT_ERROR_LOG = "blog.trace_error" PROJECT_EXCEPTION_LOG = "blog.trace_exception" PROJECT_HTTPCLIENT_LOG = "blog.trace_httpclient" LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '[%(asctime)s] %(levelname)s:\n %(message)s' }, 'exception': { 'format': '[%(asctime)s] %(levelname)s %(module)s Line:%(lineno)d:\n' }, 'trace_service': { 'format': '%(message)s' }, }, 'filters': {}, 'handlers': { 'null': {
import sys import os from os import path import logging from os.path import dirname as d log_folder = path.join(d(d(__file__)), 'logs') if not path.isdir(log_folder): os.makedirs(log_folder) root_logger = logging.getLogger() def setLogLevel(lvl): root_logger.setLevel(lvl) log_formatter = logging.Formatter( '%(levelname)-5.5s [%(asctime)s: %(name)s] %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p' # Uses time.strftime format: # https://docs.python.org/3.5/library/time.html#time.strftime ) # Setup the file logger file_handler = logging.FileHandler('{0}/{1}.log'.format(log_folder, 'dnd_bot')) file_handler.setFormatter(log_formatter) root_logger.addHandler(file_handler) # Setup the console logger console_handler = logging.StreamHandler(sys.stdout)
# conftest.py import sys from os.path import dirname as d from os.path import abspath, join root_dir = d(d(abspath(__file__))) sys.path.append(root_dir)
Example usage: python3 ./scripts/update_credentials.py --dir=<path_to_isd_folder> --isd=2 """ # Stdlib import argparse import json import os import re import sys import yaml from os.path import dirname as d WEB_SCION_DIR = d(d(os.path.abspath(__file__))) # noqa sys.path.insert(0, WEB_SCION_DIR) # noqa # Set up the Django environment os.environ['DJANGO_SETTINGS_MODULE'] = 'web_scion.settings.private' # noqa # External packages import django # SCION from lib.crypto.asymcrypto import ( get_core_sig_key_file_path, get_core_sig_key_raw_file_path, get_enc_key_file_path, get_sig_key_file_path, get_sig_key_raw_file_path,
self.assertEquals(err_status, 8) self.assertTrue(service.stop()) ########NEW FILE######## __FILENAME__ = test #!/usr/bin/env python # vim: set fileencoding=utf8 shiftwidth=4 tabstop=4 textwidth=80 foldmethod=marker : # Copyright (c) 2011, Kou Man Tong. All rights reserved. # For licensing, see LICENSE file included in the package. import applepushnotification.tests, sys from os.path import realpath as r, join as j, dirname as d from optparse import OptionParser if __name__ == "__main__": parser = OptionParser(usage = \ u"""Runs applepushnotification unit test cases. usage: %prog pem_file hex_token""") options, args = parser.parse_args() if len(args)< 2: parser.print_help() sys.exit(-1) applepushnotification.tests.pem_file = j(d(__file__), args[0]) applepushnotification.tests.hex_token = args[1] applepushnotification.tests.main() ########NEW FILE########
import sys import pytest from os.path import abspath from os.path import dirname as d from multiprocessing import Event sys.path.extend([d(d(abspath(__file__))), d(abspath(__file__))]) # How many requests will be triggered in parallel PARALLEL_EXECUTOR_PROCESSES = 8 # How many second process will be alive EXECUTOR_TIMEOUT = 5 @pytest.fixture def app(): from main import app return app @pytest.fixture def base_url(): return 'http://0.0.0.0:5000' @pytest.fixture def multiproc_event(): event = Event() yield event