def writetoCSV(filename, machines, sections, charging_station):
    # Define parameters
    # TODO: get from file
    space_left = 10000
    wall_to_IS = 5090
    width_IS = 5150
    distance_IS = 6610
    length_IS = 7532
    #distance_SEC = 7532/(sections+1)
    distance_SEC = 7532 / (8 + 1)
    separation_SEC = 300

    project_dir = dir(dir((__file__)))
    relative_path = 'input/coordata/{}'.format(filename)
    file_path = os.path.join(project_dir, relative_path)

    with open(file_path, "w+") as f:
        writer = csv.writer(f)

        for i in range(machines):
            label = "p{}".format(i + 1)
            x_coor_mm = space_left - 2500
            x_coor_m = x_coor_mm / 1000
            y_coor_mm = wall_to_IS + i * (width_IS + distance_IS)
            y_coor_m = y_coor_mm / 1000
            writer.writerow([label, x_coor_m, y_coor_m])

        for i in range(machines):
            for j in range(sections):
                label = "m{}{}".format(i + 1, j + 1)
                x_coor_mm = space_left + (distance_SEC * (j + 1))
                x_coor_m = x_coor_mm / 1000
                y_coor_mm = wall_to_IS + i * (width_IS + distance_IS)
                y_coor_m = y_coor_mm / 1000
                writer.writerow([label, x_coor_m, y_coor_m])
Esempio n. 2
0
def generate():
    GENERATE_FILE_PATH = os.path.join(dir(dir(__file__)), 'ctpwrapper/Trader.py')
    GENERATE_FILE = open(GENERATE_FILE_PATH, 'w')

    SOURCE_FILE_PATH = os.path.join(dir(dir(__file__)), 'ctpwrapper/TraderApi.pyx')
    SOURCE_FILE = open(SOURCE_FILE_PATH)

    GENERATE_FILE.write(BEFORE)

    line = SOURCE_FILE.readline()
    while not line.strip().startswith('# 客户端认证请求'):
        line = SOURCE_FILE.readline()

    reqs = parse_req(SOURCE_FILE)

    for req in reqs:
        GENERATE_FILE.write(req['line_doc'])
        GENERATE_FILE.write(req['method_str'])

    callbacks = parse_on(SOURCE_FILE)

    GENERATE_FILE.write('\n   # 回调函数\n\n')
    for cb in callbacks:
        GENERATE_FILE.write('    # ' + cb['doc_line'].replace("///", ""))
        GENERATE_FILE.write(cb['method_str'] + '\n')

    GENERATE_FILE.close()
    SOURCE_FILE.close()
Esempio n. 3
0
def main():
	from os.path import dirname as dir
	from sys import path
	print(dir(path[0]))
	path.append(dir(path[0]))

	gw = GateWay()
	try:
		gw.start()
	finally:
		gw.exit()
def training_model(model_path,
                   list_data_train,
                   label_dict,
                   max_length,
                   no_epoch=6,
                   no_class=2):
    # append PATHPYTHON with '../' ('Sentiment Analysis')
    import sys
    from sys import path
    from os.path import dirname as dir
    path.append(dir(path[0]))
    # import Word_Embedding and Word_Segmentation
    from Word_Embedding import word_to_vector
    from gensim.models import Word2Vec
    from Word_Segmentation.word_segmentation import Tokenizer
    tokenizer = Tokenizer()
    word2vec_model = Word2Vec.load(
        '../pretrained_models/pretrained_word2vec.bin')
    sym_dict = get_synonym_dict('../data/sentiment/synonym.txt')
    # init class text_classifier
    text_classifier = BidirectionalLSTM_text_classifier(
        tokenizer=tokenizer,
        word2vec=word2vec_model.wv,
        model_path=model_path,
        max_length=max_length,
        no_epoch=no_epoch,
        no_class=no_class,
        synonym=sym_dict)
    # load data to X,y format from file
    X, y = text_classifier.load_data(list_data_train,
                                     load_method=text_classifier.load_method)
    # train available data
    text_classifier.train(X, y)
    pass
def predict(label_dict, sentence_set, model_path, max_length):
    # append PATHPYTHON with '../' ('Sentiment Analysis')
    import sys
    from sys import path
    from os.path import dirname as dir
    path.append(dir(path[0]))
    # import Word_Embedding and Word_Segmentation
    from Word_Embedding import word_to_vector
    from gensim.models import Word2Vec
    from Word_Segmentation.word_segmentation import Tokenizer
    tokenizer = Tokenizer()
    word2vec_model = Word2Vec.load(
        '../pretrained_models/pretrained_word2vec.bin')
    sym_dict = get_synonym_dict('../data/sentiment/synonym.txt')
    # init class text_classifier
    text_classifier = BidirectionalLSTM_text_classifier(
        tokenizer=tokenizer,
        word2vec=word2vec_model.wv,
        model_path=model_path,
        max_length=max_length,
        no_epoch=15,
        synonym=sym_dict)

    labels = text_classifier.classify(sentence_set, label_dict)
    return labels
    pass
Esempio n. 6
0
    def do_ls(self, args):
        """List files"""
        if not self.check_login():
            print("Not logged in, login first")
            return

        if args == '':
            args = self.user_path
        else:
            args = os.path.normpath(os.path.join(self.user_path, args))
        path = self._get_handle_for_path(args)
        if path:
            for item in path.dir():
                drive_file = path[item]
                if drive_file.type == "file":
                    perms = "-rw-rw-rw-"
                    size = drive_file.size
                    date = drive_file.date_modified
                    if date.year == datetime.datetime.now().year:
                        filedate = date.strftime("%b %d %H:%S")
                    else:
                        filedate = date.strftime("%b %d  %Y")
                elif drive_file.type == "folder":
                    perms = "drwxrwxrwx"
                    size = 0
                    filedate = "Jan 01  1970"
                print("%s %-4s %5s %-5s %13s %s %s" %
                      (perms, 0, os.getuid(), os.getgid(), size, filedate,
                       drive_file.name))
        return
Esempio n. 7
0
 def GET(self):
     for filepath in glob(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "dit_flow", "dit_widget"), "*.py"):
         print("Found file: ", filepath)
         name = os.path.splitext(os.path.basename(filepath))[0]
         # add package prefix to name, if required
         module = __import__(name)
         for member in dir(module):
             print(member)
	def handle_noargs(self, **options):
			export_folder = join(dir(dir(dir(dir(dir(__file__))))),"documentation","model_graph")
			management.call_command('graph_models', 'tasks', outputfile=join(export_folder,'tasks.svg'))
			management.call_command('graph_models', 'tasks', outputfile=join(export_folder,'tasks.gif'))
			management.call_command('graph_models', 'solutions', outputfile=join(export_folder,'solutions.svg'))
			management.call_command('graph_models', 'solutions', outputfile=join(export_folder,'solutions.gif'))
			management.call_command('graph_models', 'attestation', outputfile=join(export_folder,'attestation.svg'))
			management.call_command('graph_models', 'attestation', outputfile=join(export_folder,'attestation.gif'))
			management.call_command('graph_models', 'accounts', outputfile=join(export_folder,'accounts.svg'))
			management.call_command('graph_models', 'accounts', outputfile=join(export_folder,'accounts.gif'))
			management.call_command('graph_models', 'checker', outputfile=join(export_folder,'checker.svg'))
			management.call_command('graph_models', 'checker', outputfile=join(export_folder,'checker.gif'))
			management.call_command('graph_models', 'tasks', 'solutions', 'attestation', 'accounts', group_models = True, disable_fields = True, outputfile=join(export_folder,'overview.svg'))
			management.call_command('graph_models', 'tasks', 'solutions', 'attestation', 'accounts', group_models = True, disable_fields = True, outputfile=join(export_folder,'overview.gif'))
			management.call_command('graph_models', all_applications = True, group_models = True, outputfile=join(export_folder,'extended_overview.svg'))
			management.call_command('graph_models', all_applications = True, group_models = True, outputfile=join(export_folder,'extended_overview.gif'))
			print 'Successfully updated model graph.'
Esempio n. 9
0
    def handle_noargs(self, **options):
        try:
            application_support_folder = settings.UPLOAD_ROOT
            demo_support_folder = join(dir(dir(dir(dir(dir(dir(__file__)))))),
                                       "examples", "PraktomatSupport")

            # create a backup
            archive_name = join(tempfile.gettempdir(), 'backup')
            archive_name = shutil.make_archive(archive_name, 'zip',
                                               application_support_folder)

            # delete old app support folder
            shutil.rmtree(application_support_folder)

            # copy demo files
            shutil.copytree(demo_support_folder, application_support_folder)

            # copy backup
            shutil.copy(archive_name, application_support_folder)

            print 'Successfully installed demo files and database. Backup of old files in "%s"' % join(
                application_support_folder, 'backup.zip')

        except:
            raise CommandError(
                'An ERROR occurred. A backup of your files can be found here: '
                % archive_name)
Esempio n. 10
0
def getAuthorReputation(arr = [[]]):
    path.append(dir(path[0]))

    max_judgement_dist = 2
    scaling_constant = 1
    scaling_function = lambda x: math.log(1.1 + x)

    test_article = Article(max_judgement_dist, scaling_constant, scaling_function)


    for version_iter in range(len(arr)):
        test_versions.append(Version(arr[version_iter], test_strings[version_iter]))
    
    for x in range(len(arr) - 2):
        for version_iter, version in enumerate(test_versions):
            test_article.add_new_version(version)
Esempio n. 11
0
	def handle_noargs(self, **options):
	   	try:
		   	application_support_folder = settings.UPLOAD_ROOT
		   	demo_support_folder = join(dir(dir(dir(dir(dir(dir(__file__)))))),"examples","PraktomatSupport")
		   	
		   	# create a backup
		   	archive_name = join(tempfile.gettempdir(), 'backup')
		   	archive_name = shutil.make_archive(archive_name, 'zip', application_support_folder)
		   	
		   	# delete old app support folder
		   	shutil.rmtree(application_support_folder)
	
		   	# copy demo files
		   	shutil.copytree(demo_support_folder, application_support_folder)
		   	
		   	# copy backup
		   	shutil.copy(archive_name, application_support_folder)
		   	
		   	print 'Successfully installed demo files and database. Backup of old files in "%s"' % join(application_support_folder, 'backup.zip')
	  	
		except:
			raise CommandError('An ERROR occurred. A backup of your files can be found here: ' % archive_name)
#
# Expose c++ data type definitions to Cython
#

import os
import re
from os.path import dirname as dir

CTP_PATH = os.path.join(dir(dir(__file__)), 'ctp')

HEADER_PATH = os.path.join(CTP_PATH, "header")

# typedef header
USERAPI_DATA_FILE = os.path.join(HEADER_PATH, "ThostFtdcUserApiDataType.h")

# Structure header
USERAPI_STRUCT_FILE = os.path.join(HEADER_PATH, "ThostFtdcUserApiStruct.h")

GENERATE_PATH = os.path.join(os.path.dirname(__file__), "ctpwrapper/pxdheader")


def generate_structure(datatype_name_set):
    """
    Generate structure file
    :param datatype_dict:
    :return:
    """
    generate_file_path = os.path.join(GENERATE_PATH, "ThostFtdcUserApiStruct.pxd")

    data_struct_file = open(generate_file_path, "w", encoding='utf-8')
    data_struct_file.write("# encoding: utf-8" + "\n" * 2)
Esempio n. 13
0
from Pieces.Rook import Rook
from Pieces.Queen import Queen
from Pieces.Pawn import Pawn
from Pieces.Knight import Knight
from Pieces.King import King
from Pieces.Bishop import Bishop
from sys import path
from os.path import dirname as dir
path.append(dir(path[0])[0:dir(path[0]).rfind('\\')])
# Make sure to appending c:\Users\Ahmed Alzubairi\Documents\Open
# Source\COMS4995


def test_pawn_move():
    """Tests if the pawn can move
    """
    playerOnePieces = set()
    board = [[None] * 8 for i in range(8)]
    color = "BLACK"
    myPiece = Pawn(board, color, playerOnePieces, 2, 'A')
    playerOnePieces.update({myPiece})
    possibleRow = {i: i - 1 for i in range(1, 9)}
    possibleCol = {chr(i): i - ord('A') for i in range(ord('A'), ord('A') + 8)}
    moveOne = "2A"
    moveTwo = "3A"
    # Now I make a move
    board[possibleRow[int(moveOne[0])]][possibleCol[moveOne[1]]].move(
        int(moveTwo[0]), moveTwo[1])
    assert board[possibleRow[int(moveTwo[0])]
                 ][possibleCol[moveTwo[1]]] == myPiece
 def handle_noargs(self, **options):
     export_folder = join(dir(dir(dir(dir(dir(__file__))))),
                          "documentation", "model_graph")
     management.call_command('graph_models',
                             'tasks',
                             outputfile=join(export_folder, 'tasks.svg'))
     management.call_command('graph_models',
                             'tasks',
                             outputfile=join(export_folder, 'tasks.gif'))
     management.call_command('graph_models',
                             'solutions',
                             outputfile=join(export_folder,
                                             'solutions.svg'))
     management.call_command('graph_models',
                             'solutions',
                             outputfile=join(export_folder,
                                             'solutions.gif'))
     management.call_command('graph_models',
                             'attestation',
                             outputfile=join(export_folder,
                                             'attestation.svg'))
     management.call_command('graph_models',
                             'attestation',
                             outputfile=join(export_folder,
                                             'attestation.gif'))
     management.call_command('graph_models',
                             'accounts',
                             outputfile=join(export_folder, 'accounts.svg'))
     management.call_command('graph_models',
                             'accounts',
                             outputfile=join(export_folder, 'accounts.gif'))
     management.call_command('graph_models',
                             'checker',
                             outputfile=join(export_folder, 'checker.svg'))
     management.call_command('graph_models',
                             'checker',
                             outputfile=join(export_folder, 'checker.gif'))
     management.call_command('graph_models',
                             'tasks',
                             'solutions',
                             'attestation',
                             'accounts',
                             group_models=True,
                             disable_fields=True,
                             outputfile=join(export_folder, 'overview.svg'))
     management.call_command('graph_models',
                             'tasks',
                             'solutions',
                             'attestation',
                             'accounts',
                             group_models=True,
                             disable_fields=True,
                             outputfile=join(export_folder, 'overview.gif'))
     management.call_command('graph_models',
                             all_applications=True,
                             group_models=True,
                             outputfile=join(export_folder,
                                             'extended_overview.svg'))
     management.call_command('graph_models',
                             all_applications=True,
                             group_models=True,
                             outputfile=join(export_folder,
                                             'extended_overview.gif'))
     print('Successfully updated model graph.')
Esempio n. 15
0
# Path hack for cross-package imports
if __name__ == "__main__" and __package__ is None:
    from sys import path
    from os.path import dirname as dir
    path.append(dir(path[0]))
Esempio n. 16
0
# Allows to run as main from any directory and import utility packages
if __name__ == "__main__" and __package__ is None:
    from sys import path
    from os.path import dirname as dir

    print(path[0])
    path.append(dir(path[0]))
    splits = path[0].split('/')

    parent = '/'.join(splits[:-3])
    path.append(dir(parent))
    parent = '/'.join(splits[:-2])
    path.append(dir(parent))
    parent = '/'.join(splits[:-1])
    path.append(dir(parent))
    __package__ = "generated_data"

import pickle
from EnhancedDCM.utilities import grad_hess_utilities as ghu
from keras.models import load_model
from swissmetro_paper import data_manager as dm
import numpy as np
from keras import backend as K
"""
    Saves in file and Writes results of all Models specified in "Cases" 
"""


def fetch_model(neuron, path, extend):
    filename = "{}swissmetro{}{}.h5".format(path, neuron, extend)
    return load_model(filename)
Esempio n. 17
0
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import sys
from os.path import dirname as dir
from django.contrib import messages
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP

WEB_SCION_DIR = dir(dir(dir(os.path.abspath(__file__))))
SCION_ROOT = dir(WEB_SCION_DIR)
sys.path.insert(0, SCION_ROOT)

# for users who don't dynamically add content root to their PATHONPATH
sys.path.insert(1, dir(SCION_ROOT))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/


# Application definition
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
Esempio n. 18
0
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import sys
from os.path import dirname as dir
from django.contrib import messages
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP

WEB_SCION_DIR = dir(dir(dir(os.path.abspath(__file__))))
SCION_ROOT = dir(WEB_SCION_DIR)
sys.path.insert(0, SCION_ROOT)

# for users who don't dynamically add content root to their PATHONPATH
sys.path.insert(1, dir(SCION_ROOT))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/


# Application definition
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
Esempio n. 19
0
import sys
import os
import redis

from os.path import dirname as dir

_root = dir(dir(dir(sys.executable)))

#_root = dir(dir(dir(__file__)))
sys.path.append(os.path.join(_root, "Node Manager"))
from admin_map_creator import main

if __name__ == "__main__":
    main()
Esempio n. 20
0
from imagegen import *
import os
from os.path import dirname as dir, splitext, basename, join
import sys
import base64
import res_info as res
from multiprocessing import Process, Pipe, Queue
import threading
import random
import time
import redis


# Need to choose depending on running from exe or py. Should point to /Server
# root = dir(dir(dir(sys.executable)))
_root = dir(dir(__file__))

# To extract database interface functions
sys.path.append(join(_root, "Redis"))
import redisDB
# Relevant file directories

# Image Assets
image_folder = os.path.join(_root, "images")
image_asset_folder = os.path.join(image_folder, "assets")
image_output_graphic_folder = os.path.join(image_folder, "output graphic")
nodeOn_path = os.path.join(image_asset_folder, "unoccupied_nodes.png")
nodeOff_path = os.path.join(image_asset_folder, "occupied_nodes.png")


# Database information
Esempio n. 21
0
def main(argv=[]):
    game = RaspgierryPi()
    game.run()
       
if __name__ == "__main__":
    from sys import argv
    from sys import path
    from os.path import dirname as dir
    path.insert(0, dir(path[0]))
    from raspgierry_pi import RaspgierryPi
    main(argv)
Esempio n. 22
0
# to import local lib - pyimgsaliency
# you need to change the path according to your environment
import os

if __name__ == '__main__' and __package__ is None:
    from sys import path
    from os.path import dirname as dir

    path.append(dir(path[0]))
    path.append(os.path.join(dir(path[0]), 'external_lib'))
    __package__ = 'final'

from final.canva import Poster

p = Poster(bg_file_path='../data/image_4_4.jpg', metrics=['saliency', 'overlap'])
p.add_slide(content='夏日特饮', category='text', font_size=128, font_path='../data/FZDBSJW.TTF')
p.add_slide(content='大促期间,第二杯半价', category='text', font_size=64, font_path='../data/FZDBSJW.TTF')
p.add_slide(content='', category='image', img_path='../data/logo.png', boundary_size=(250, 400))

p.render(pop_num=100, iter_num=10)
p.show()
Esempio n. 23
0
from tkinter import *
import classdef as spc
from tkinter import filedialog
import config as cfg
from sensor_data import *
import imgpro
import os
from os.path import dirname as dir, splitext, basename, join, abspath
import sys
import base64
from platform import system as platf

# Need to choose depending on running from exe or py. Should point to /Spacey API

if platf() == 'Linux':
    parentdir = dir(dir(sys.executable))
    print(parentdir)
    if basename(parentdir) == "Node Manager":
        _root = dir(parentdir)
    else: 
        _root = dir(dir(abspath(__file__)))



elif platf() == 'Windows':
    parentdir = basename(dir(abspath(__file__)))
    if (parentdir == "Node Manager"):
        _root = dir(dir(abspath(__file__)))
    else:
            _root = dir(dir(dir(sys.executable)))
   
Esempio n. 24
0
from lib.defines import (
    AS_CONF_FILE,
    GEN_PATH,
    PATH_POLICY_FILE,
)
from lib.errors import SCIONBaseError
from lib.packet.host_addr import HostAddrIPv4
from lib.packet.scion_addr import ISD_AS
from lib.types import (
    PathSegmentType as PST,
    ServiceType,
)
from lib.util import iso_timestamp

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SCION_ROOT = dir(dir(BASE_DIR))

# topology class definitions
topo_servers = ['BEACON', 'CERTIFICATE', 'PATH', 'SIBRA']
topo_br = ['CORE_BR', 'PARENT_BR', 'CHILD_BR', 'PEER_BR', 'BORDER']
topo_if = ['CORE_IF', 'PARENT_IF', 'CHILD_IF', 'PEER_IF']
topo_zk = ['ZOOKEEPER']
connector = {}


def init():
    '''
    Initialize logger and parse arguments.
    '''
    logger = logging.getLogger()
    handler = logging.StreamHandler()
Esempio n. 25
0
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import sys
from os.path import dirname as dir
from django.contrib import messages
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP

WEB_SCION_DIR = dir(dir(dir(os.path.abspath(__file__))))
SCION_ROOT_DIR = dir(dir(WEB_SCION_DIR))
SCION_PYTHON_ROOT_DIR = os.path.join(SCION_ROOT_DIR, 'python')
sys.path.insert(0, WEB_SCION_DIR)
sys.path.insert(0, SCION_ROOT_DIR)
sys.path.insert(0, SCION_PYTHON_ROOT_DIR)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

LOG_DIR = os.path.join(WEB_SCION_DIR, 'logs')
os.makedirs(LOG_DIR, exist_ok=True)

# Application definition
INSTALLED_APPS = (
    'django.contrib.admin',
import os
from os.path import dirname as dir

rootPath = dir(dir(__file__))

modulePath = dir(__file__)
testCasePath = f'{rootPath}/inputs'

table_names = [
    'periods', 'facilities', 'suppliers', 'customers', 'products', 'groups',
    'transportation_modes', 'transportation_lanes'
]

test_cases = []
test_case_directories = [
    f.name for f in os.scandir(testCasePath) if f.is_dir()
]
for table_name in table_names:
    print(table_name)
    for test_case in test_case_directories:
        filename = f'{testCasePath}/{test_case}/{table_name}.csv'
        if os.path.exists(filename):
            with open(filename, 'r') as file:
                columns = file.readline()
            print(f'{columns}: {test_case}')
    print('')
Esempio n. 27
0
if __name__ == "__main__" and __package__ is None:
    from sys import path
    from os.path import dirname as dir
    path.append(dir(path[0]))
    __package__ = "Test"

import unittest
from flask import Flask
from flaskapp.validate.ValidateMobileNo import validateMobileNo


class TestValidMobileNo(unittest.TestCase):
    def setUp(self):
        self.no1 = validateMobileNo('8368279')
        self.no2 = validateMobileNo('836927988')
        self.no3 = validateMobileNo('B3682798')
        self.no4 = validateMobileNo('83682798')
        self.no5 = validateMobileNo('80@77838')

    def tearDown(self):
        pass

    def test_incorrect_length_mobileno(self):
        self.assertFalse(self.no1)
        self.assertFalse(self.no2)

    def test_not_exist_mobileno(self):
        self.assertFalse(self.no3)
        self.assertFalse(self.no5)

    def test_valid_mobileno(self):
Esempio n. 28
0
"""
pyturb
Gas Mixture tests

M Rodriguez. 2020
"""

import sys
from sys import path
from os.path import dirname as dir
sys.path.append(dir(sys.path[0]))

import pyturb.utils.constants as cts
from pyturb.gas_models.perfect_ideal_gas import PerfectIdealGas
from pyturb.gas_models.gas_mixture import GasMixture
import numpy as np

air = PerfectIdealGas('Air')
gm = GasMixture(gas_model='Perfect')

gm.add_gas('O2', 0.209476)
gm.add_gas('N2', 0.78084)
gm.add_gas('Ar', 0.009365)
gm.add_gas('CO2', 0.000319)

print(
    '--------------------------------------------------------------------------------------------------------------'
)
print(gm.mixture_gases)
print(
    '--------------------------------------------------------------------------------------------------------------'
Esempio n. 29
0
if __name__ == "__main__" and (__package__ is None or __package__ is ''):
    from sys import path
    from os.path import dirname as dir

    path.append(
        dir(path[0])
    )  # allow importing from modules in parent dir, TODO: bad code design

import argparse
import os
import time

import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
from torchvision import transforms

from lib.solver import train_epoch, val_epoch, test_epoch, test_epoch_dropout
from lib.sampler import ChunkSampler
from lib.progressbar import progress_bar, format_time
from lib.plot import *

from datasets.msra_hand import MARAHandDataset
from src.dp_model import DeepPriorPPModel
from src.dp_util import DeepPriorXYTransform, DeepPriorXYTestTransform, \
                        DeepPriorYTransform, DeepPriorYTestInverseTransform, \
                        DeepPriorBatchResultCollector, PCATransform, saveKeypoints

from src.dp_augment import AugType
Esempio n. 30
0
from __future__ import annotations

from sys import path
from os.path import dirname as dir
path.append(dir(path[0]) + '\\generic_searches')

from typing import List, Optional
from generic_searches import node_to_path, bfs
from generic_data_structures import Node

MAX_NUM: int = 3

class MC_state:
    def __init__(self, missionaries: int, cannibals: int, boat: bool) -> None:
        self.left_m: int = missionaries
        self.left_c: int = cannibals
        self.right_m: int = MAX_NUM - self.left_m
        self.right_c: int = MAX_NUM - self.left_c
        self.boat: bool = boat

    def __str__(self) -> str:
        return (f'On the left bank there are {self.left_m} missionaries and {self.left_c} cannibals.\nOn the right bank there are {self.right_m} missionaries and {self.right_c} cannibals.\nThe boat is on the {"left" if self.boat else "right"} bank.')
    
    def __eq__(self, other) -> bool:
        return (self.left_m == other.left_m) and (self.left_c == other.left_c) and (self.boat == other.boat)
    
    def __hash__(self):
        return hash(str(self))

    def goal_test(self) -> bool:
        return self.islegal and self.right_m == MAX_NUM and self.right_c == MAX_NUM
Esempio n. 31
0
#   inf. Ciphertext from SHA256 such that password of the user cannot be leaked from database
# Restaurant data [hash]
#   -occupancy
#   -config


import redis
import json
import os
from os.path import dirname as dir, realpath, join, splitext, basename
import sys
import base64
import multiprocessing
import time
# File directory
root = dir(dir(realpath(__file__)))

# get session name


class redis_database(object):
    def __init__(self, root,remote_host, port, password):
        self.remote_host = remote_host
        self.port = port
        self.password = password
        self.root = root
        self.client = None
        self.res_list = []
        self.test = 3
        self.user = ""
    
Esempio n. 32
0
        texts_identifiers = [[
            dictionary.get(term_id)
            for term_id, weight in tfidf_weight[:identifiers_number]
        ] for tfidf_weight in tfidf_weights]
        texts_identifiers = [
            " ".join(text_identifiers)
            for text_identifiers in texts_identifiers
        ]
        groups = []
        for ti in texts_identifiers:
            # Create nlp object based only on text identifiers
            doc_publication = self.nlp(ti)
            similarities = []
            for gkd in groups_keywords_docs:
                similarities.append(doc_publication.similarity(gkd))
            max_value = max(similarities)
            max_position = similarities.index(max_value)
            industry_type = key_list[max_position]
            groups.append(industry_type)
        return groups


#testing
if str(cwd()).find('belearner'):
    START_PATH = dir(cwd())
    DATA_PATH = join(START_PATH + r'\data\new_file.csv')
    #testing a 100 docs sample
    df = pd.read_csv(DATA_PATH, delimiter='\t').sample(10)
    model = Model(nlp_model='en_core_web_sm')
    powersetsvc, vectorizer = model.train(data=df, X_column='text')
Esempio n. 33
0
if __name__ == "__main__":
    
    args = parseArgs()
    
    filename = args.filename
    robots = args.robots
    machines = args.machines
    sections = args.sections
    intervals = args.swabinterval
    offset = args.swaboffset
    machineassign = args.machineassign
    
    # Generate dictionary of machine assignment list
    machine_assign = generateMAdict(machineassign)
    
    # Generate dictionary of jobs for each machine
    job_dict = jobGenerator(machines, sections)
    
    # Generate dictionary with swabbing times for each machine
    swabtimes_dict = generateswabTimes(machines,intervals,offset)
    
    # Generate dictionary with joblists for each MSR
    joblist_dict = joblistGenerator(robots, job_dict, machines, machine_assign, swabtimes_dict)
    
    # Write joblists to JSON file with filename specified in command line
    project_dir = dir(dir((__file__)))
    relative_path =  'input/joblist/{}'.format(filename)
    file_path = os.path.join(project_dir, relative_path)
    with open(file_path, 'w') as f:
        json.dump(joblist_dict,f,indent=1)
Esempio n. 34
0
import datetime
import json
import requests
from imgurpython import ImgurClient
from os.path import dirname as dir
from os.path import join
from os.path import isfile
from modules.api.keywords import *

root_dir = dir(dir(dir(__file__)))
_key_path = join(root_dir, "key/key.json")


def _store(user: dict):

    with open(_key_path, "w") as f:
        f.write(json.dumps(user))


def get_key() -> dict:

    data = dict()

    with open(_key_path, "r") as f:
        try:
            data = json.load(f)
        except json.decoder.JSONDecodeError as e:
            pass

    return data
Esempio n. 35
0
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import sys
from os.path import dirname as dir
from django.contrib import messages
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP

WEB_SCION_DIR = dir(dir(dir(os.path.abspath(__file__))))
SCION_ROOT_DIR = dir(dir(WEB_SCION_DIR))
SCION_PYTHON_ROOT_DIR = os.path.join(SCION_ROOT_DIR, 'python')
sys.path.insert(0, WEB_SCION_DIR)
sys.path.insert(0, SCION_ROOT_DIR)
sys.path.insert(0, SCION_PYTHON_ROOT_DIR)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

LOG_DIR = os.path.join(WEB_SCION_DIR, 'logs')
os.makedirs(LOG_DIR, exist_ok=True)

# Application definition
INSTALLED_APPS = (
    'django.contrib.admin',
Esempio n. 36
0
from os.path import dirname as dir  # NOQA
from sys import path  # NOQA
from sys import path  # NOQA
import os  # NOQA
import sys  # NOQA
path.append(dir(path[0])[0:dir(path[0]).rfind('\\')] + r'\Vaeick_CIR')
path.append('/home/travis/build/harshhacks/quantparadise/PricingFIP/' +
            'Vaeick_CIR')  # NOQA
from Mod6 import *  # NOQA


def test_first():

    assert zero_coupon(1, 2, 3, 4, 5, model="abcd") == -1


def test_second():

    assert swapRates([1], 2, 3) == -1


def test_third():

    assert liborRates([1], 2, 3) == -1


def test_fourth():

    assert objFunc1([1, 2, 3, -8], 5, 6, 2, model="abcd") == -2

Esempio n. 37
0
import inspect
import os
import glob
import pydoc
import sys
from os.path import dirname as dir

sys.path.append(dir(sys.path[0]))

from circuits.web import Controller
from widget_loader import WidgetLoader

class Widgets(Controller):

    channel = '/widgets'

    def GET(self, *args, **kwargs):
        signatures = list()
        sys.path.append('/Users/hwilcox/Workspace/dit-3.0')
        print(sys.modules)
        members = inspect.getmembers(sys.modules['dit_flow.dit_widget'])
        widget_names = list()
        for member_key, member_value in members:
            # find widgets imported
            if member_key == '__all__':
                widget_names = member_value
                continue
            for widget_name in widget_names:
                try:
                    # Attempt import
                    mod = __import__(widget_name)