Esempio n. 1
0
def show_io(input_dir, output_dir):
    ''' show directory structure and inputs and autputs to scoring program'''
    logger.info('=== DIRECTORIES ===')
    # Show this directory
    logger.info("-- Current directory " + pwd() + ":")
    map(logger.info, ls('.'))
    map(logger.info, ls('./*'))
    map(logger.info, ls('./*/*'))

    # List input and output directories
    logger.info("-- Input directory " + input_dir + ":")
    map(logger.info, ls(input_dir))
    map(logger.info, ls(input_dir + '/*'))
    map(logger.info, ls(input_dir + '/*/*'))
    map(logger.info, ls(input_dir + '/*/*/*'))
    logger.info("-- Output directory  " + output_dir + ":")
    map(logger.info, ls(output_dir))
    map(logger.info, ls(output_dir + '/*'))

    # write meta data to sdterr
    logger.info('=== METADATA ===')
    logger.info("-- Current directory " + pwd() + ":")
    try:
        metadata = yaml.load(open('metadata', 'r'))
        for key, value in metadata.items():
            logger.info(key + ': ' + str(value))
    except:
        logger.info("none")
    logger.info("-- Input directory " + input_dir + ":")
    try:
        metadata = yaml.load(open(os.path.join(input_dir, 'metadata'), 'r'))
        for key, value in metadata.items():
            logger.info(key + ': ' + str(value))
    except:
        logger.info("none")
Esempio n. 2
0
def scanpkg(path):
    '''
    Extract a single package to a temporary location, scan the contents and return the content data
    '''
    ret = {}
    files = []
    dirs = []
    tmp = tempfile.mkdtemp(__opts__['cachedir'])
    shutil.copy(path, tmp)
    orig = os.pwd()
    os.chdir(tmp)
    cmd = 'ar vx {0}'.format(path)
    subprocess.check_output(cmd, shell=True)
    cmd = 'tar xvf {}'.format(os.path.join(tmp, 'data.tar.*'))
    subprocess.check_output(cmd, shell=True)
    cmd = 'tar xvf {}'.format(os.path.join(tmp, 'control.tar.gz'))
    subprocess.check_output(cmd, shell=True)
    ret.update(yaml.safe_load(os.path.join(tmp, 'control')))
    ret['distro'] = 'arch'
    ret['name'] = ret['pkgname']
    ret['version'] = ret['pkgver']
    for root, dirs, files in os.walk(tmp):
        for fn_ in files:
            full = os.path.join(root, fn_)
            files.append(full[len(tmp):])
        for dn_ in dirs:
            full = os.path.join(root, dn_)
            dirs.append(full[len(tmp):])
    ret['files'] = files
    ret['dirs'] = dirs
    os.chdir(orig)
    shutil.rmtree(tmp)
    return ret
Esempio n. 3
0
def handle_args(args):
    target_vid_path = args.vp
    save_dir = args.sd
    if target_vid_path == None or save_dir == None:
        print("You must provide a path to the video (-vp) and a" \
              " destination directory (-sd) to save the frames.\n" \
              "An argument of \".\" will be interpreted as your current working directory.\n" \
              "Example 1: python vtf.py -vp ./videos/video1.mp4 -sd . \n" \
              "Example 2: python vtf.py -vp ./video1.mp4 -sd ./output-frames")
        sys.exit()
    if target_vid_path[0] == ".":
        target_vid_path = pwd()
    if save_dir[0] == ".":
        save_dir = pwd()

    return target_vid_path, save_dir
Esempio n. 4
0
def scanpkg(path):
    '''
    Extract a single package to a temporary location, scan the contents and return the content data
    '''
    ret = {}
    files = []
    dirs = []
    tmp = tempfile.mkdtemp(__opts__['cachedir'])
    shutil.copy(path, tmp)
    orig = os.pwd()
    os.chdir(tmp)
    cmd = 'ar vx {0}'.format(path)
    subprocess.check_output(cmd, shell=True)
    cmd = 'tar xvf {}'.format(os.path.join(tmp, 'data.tar.*'))
    subprocess.check_output(cmd, shell=True)
    cmd = 'tar xvf {}'.format(os.path.join(tmp, 'control.tar.gz'))
    subprocess.check_output(cmd, shell=True)
    ret.update(yaml.safe_load(os.path.join(tmp, 'control')))
    ret['distro'] = 'arch'
    ret['name'] = ret['pkgname']
    ret['version'] = ret['pkgver']
    for root, dirs, files in os.walk(tmp):
        for fn_ in files:
            full = os.path.join(root, fn_)
            files.append(full[len(tmp):])
        for dn_ in dirs:
            full = os.path.join(root, dn_)
            dirs.append(full[len(tmp):])
    ret['files'] = files
    ret['dirs'] = dirs
    os.chdir(orig)
    shutil.rmtree(tmp)
    return ret
Esempio n. 5
0
def get_temp_GSL():
    import urllib, tarfile, StringIO, tempfile

    global tdir
    u = urllib.urlopen("ftp://ftp.gnu.org/gnu/gsl/gsl-1.8.tar.gz")
    f = StringIO.StringIO(u.read())
    tar = tarfile.open(fileobj=f)
    tdir = tempfile.mkdtemp()
    cwd = os.pwd()
    os.chdir(tdir)
    tar.extractall()
    os.chdir(os.listdir()[0])
    tar.close()
    u.close()
    stat = os.system("./configure --prefix=%s --disable-shared" % tdir)
    if stat != 0:
        return 0
    stat = os.system("make")
    if stat != 0:
        return 0
    stat = os.system("make install")
    if stat != 0:
        return 0

    return (os.path.join(tdir, "include"), os.path.join(tdir, "lib"))
def fullCycleTest(config="config/TestConfig.ini", chimney="EW00", **kargs):
    reader = None
    globalTimer = stopwatch.StopWatch()
    try:

        timer = stopwatch.StopWatch()

        if not os.path.exists(config):
            relConfig = os.path.join(os.pwd(), config)
            if os.path.exists(relConfig): config = relConfig
        # if

        logging.info("fullCycleTest(): ChimneyReader setup")
        kargs['configurationFile'] = config
        kargs['chimney'] = chimney
        timer.restart()
        reader = testDriver.ChimneyReader(**kargs)
        timer.stop()
        logging.info("fullCycleTest(): ChimneyReader setup ended in {}".format(
            timer.toString()))
        if not reader.scope:
            raise RuntimeError("Failed to contact the oscilloscope.")

        logging.info("fullCycleTest(): readout loop")
        timer.restart()
        reader.start()
        iRead = 0
        while reader.readNext():
            iRead += 1
            print("Read #{}".format(iRead))
        # while
        timer.stop()
        logging.info("fullCycleTest(): readout ended in {}".format(
            timer.toString()))

        logging.info("fullCycleTest(): verification")
        timer.restart()
        success = reader.verify()
        timer.stop()
        logging.info("fullCycleTest(): verification ended in {}".format(
            timer.toString()))
        if not success:
            raise RuntimeError("Verification failed!")

        logging.info("fullCycleTest(): archival script generation")
        timer.restart()
        reader.generateArchivalScript()
        timer.stop()
        logging.info("fullCycleTest(): script generation ended in {}".format(
            timer.toString()))

    except Exception as e:
        print >> sys.stderr, e
    globalTimer.stop()
    logging.info("fullCycleTest(): test took {}".format(
        globalTimer.toString()))
    if reader:
        reader.printTimers()
    return reader
Esempio n. 7
0
        def evaluator():
            f = request.files['file']
            filename = f.filename
            file_name = 'extract_feat/' + filename
            f.save(file_name)
            # result = 'save ' + file_name + 'success!'
            result = wav2class(model, os.pwd() + '/' + file_name)

            return result
Esempio n. 8
0
def show_io(input_dir, output_dir):
    """ show directory structure and inputs and autputs to scoring program"""
    swrite("\n=== DIRECTORIES ===\n\n")
    # Show this directory
    swrite("-- Current directory " + pwd() + ":\n")
    write_list(ls("."))
    write_list(ls("./*"))
    write_list(ls("./*/*"))
    swrite("\n")

    # List input and output directories
    swrite("-- Input directory " + input_dir + ":\n")
    write_list(ls(input_dir))
    write_list(ls(input_dir + "/*"))
    write_list(ls(input_dir + "/*/*"))
    write_list(ls(input_dir + "/*/*/*"))
    swrite("\n")
    swrite("-- Output directory  " + output_dir + ":\n")
    write_list(ls(output_dir))
    write_list(ls(output_dir + "/*"))
    swrite("\n")

    # write meta data to sdterr
    swrite("\n=== METADATA ===\n\n")
    swrite("-- Current directory " + pwd() + ":\n")
    try:
        metadata = yaml.load(open("metadata", "r"))
        for key, value in metadata.items():
            swrite(key + ": ")
            swrite(str(value) + "\n")
    except:
        swrite("none\n")
    swrite("-- Input directory " + input_dir + ":\n")
    try:
        metadata = yaml.load(open(os.path.join(input_dir, "metadata"), "r"))
        for key, value in metadata.items():
            swrite(key + ": ")
            swrite(str(value) + "\n")
        swrite("\n")
    except:
        swrite("none\n")
Esempio n. 9
0
def show_io(input_dir, output_dir):  
	''' show directory structure and inputs and autputs to scoring program'''      
	swrite('\n=== DIRECTORIES ===\n\n')
	# Show this directory
	swrite("-- Current directory " + pwd() + ":\n")
	write_list(ls('.'))
	write_list(ls('./*'))
	write_list(ls('./*/*'))
	swrite("\n")
	
	# List input and output directories
	swrite("-- Input directory " + input_dir + ":\n")
	write_list(ls(input_dir))
	write_list(ls(input_dir + '/*'))
	write_list(ls(input_dir + '/*/*'))
	write_list(ls(input_dir + '/*/*/*'))
	swrite("\n")
	swrite("-- Output directory  " + output_dir + ":\n")
	write_list(ls(output_dir))
	write_list(ls(output_dir + '/*'))
	swrite("\n")
        
    # write meta data to sdterr
	swrite('\n=== METADATA ===\n\n')
	swrite("-- Current directory " + pwd() + ":\n")
	try:
		metadata = yaml.load(open('metadata', 'r'))
		for key,value in metadata.items():
			swrite(key + ': ')
			swrite(str(value) + '\n')
	except:
		swrite("none\n");
	swrite("-- Input directory " + input_dir + ":\n")
	try:
		metadata = yaml.load(open(os.path.join(input_dir, 'metadata'), 'r'))
		for key,value in metadata.items():
			swrite(key + ': ')
			swrite(str(value) + '\n')
		swrite("\n")
	except:
		swrite("none\n");
Esempio n. 10
0
def show_io(input_dir, output_dir):
    ''' show directory structure and inputs and autputs to scoring program'''
    swrite('\n=== DIRECTORIES ===\n\n')
    # Show this directory
    swrite("-- Current directory " + pwd() + ":\n")
    write_list(ls('.'))
    write_list(ls('./*'))
    write_list(ls('./*/*'))
    swrite("\n")

    # List input and output directories
    swrite("-- Input directory " + input_dir + ":\n")
    write_list(ls(input_dir))
    write_list(ls(input_dir + '/*'))
    write_list(ls(input_dir + '/*/*'))
    write_list(ls(input_dir + '/*/*/*'))
    swrite("\n")
    swrite("-- Output directory  " + output_dir + ":\n")
    write_list(ls(output_dir))
    write_list(ls(output_dir + '/*'))
    swrite("\n")

    # write meta data to sdterr
    swrite('\n=== METADATA ===\n\n')
    swrite("-- Current directory " + pwd() + ":\n")
    try:
        metadata = yaml.load(open('metadata', 'r'))
        for key, value in metadata.items():
            swrite(key + ': ')
            swrite(str(value) + '\n')
    except:
        swrite("none\n")
    swrite("-- Input directory " + input_dir + ":\n")
    try:
        metadata = yaml.load(open(os.path.join(input_dir, 'metadata'), 'r'))
        for key, value in metadata.items():
            swrite(key + ': ')
            swrite(str(value) + '\n')
        swrite("\n")
    except:
        swrite("none\n")
Esempio n. 11
0
def acilis_sayfasi():
    taban.logo_yazdir('green')
    taban.bilgi_yazdir()

    konsol.print(f"""
    [bold green][[/] [bold yellow]1[/] [bold green]][/] [bold cyan]Bunu Seçersem[/]
    [bold green][[/] [bold yellow]2[/] [bold green]][/] [bold cyan]Şunu Seçersem[/]
    """)  # Seçeneklerimizi ayarladık

    konum = pwd()
    if taban.isletim_sistemi == "Windows":
        konum = konum.split("\\")
    else:
        konum = konum.split("/")

    secenek = str(
        konsol.input(
            f"[red]{taban.oturum}[/][bright_blue]:~/../{konum[-2] + '/' + konum[-1]}[/] [bold green]>>[/] "
        ))  # Kullanıcı için input oluşturduk

    #-----------------------#
    if secenek == '1':
        taban.logo_yazdir()

        print(1)

        sleep(2)
        acilis_sayfasi()
    #-----------------------#
    elif secenek == '2':
        taban.logo_yazdir()

        print(2)

        sleep(2)
        acilis_sayfasi()
    #-----------------------#
    elif secenek == 'q':
        import sys
        sys.exit()
    #-----------------------#
    else:
        acilis_sayfasi()
Esempio n. 12
0
def zip_submission(archivename, basedir=""):
    '''Zip directory, from J.F. Sebastian http://stackoverflow.com/'''
    if not basedir: basedir = pwd()
    assert os.path.isdir(basedir)
    code_dir = os.path.join(basedir, 'sample_code')
    with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z:
        files = ['predict.sh', 'predictSpatioTemporal.py']
        for fn in files:
            absfn = os.path.join(basedir, fn)
            zfn = absfn[len(basedir) + len(os.sep):]  #XXX: relative path
            z.write(absfn, zfn)

        for root, dirs, files in os.walk(code_dir):
            #NOTE: ignore empty directories
            for fn in files:
                if fn[-3:] == '.py':
                    absfn = os.path.join(root, fn)
                    zfn = absfn[len(code_dir) +
                                len(os.sep):]  #XXX: relative path
                    z.write(absfn, zfn)
Esempio n. 13
0
def bind_service(ctx, cmd, arg):
    from os import environ as env
    from os import getcwd as pwd
    from sys import prefix
    from shutil import which
    # get servive name
    name = WinService.name()
    try:
        # verify commad
        if not which(cmd):
            raise RuntimeError(f'command ({cmd}) not found')
        # set working directory
        wu.SetServiceCustomOption(name, 'cwd', pwd())
        # get virtual environment
        wu.SetServiceCustomOption(name, 'env', env.get('VIRTUAL_ENV', prefix))
        # set command line
        wu.SetServiceCustomOption(name, 'cmd', ' '.join([cmd] + list(arg)))
        # success
        click.echo(f'BINDED: {name}')
    except ws.error as ex:
        raise click.ClickException(ex.strerror)
    except Exception as ex:
        raise click.ClickException(ex.strerror)
Esempio n. 14
0
def get_temp_GSL():
    import urllib, tarfile, StringIO, tempfile
    global tdir
    u = urllib.urlopen('ftp://ftp.gnu.org/gnu/gsl/gsl-1.8.tar.gz')
    f = StringIO.StringIO(u.read())
    tar = tarfile.open(fileobj=f)
    tdir = tempfile.mkdtemp()
    cwd = os.pwd()
    os.chdir(tdir)
    tar.extractall()
    os.chdir(os.listdir()[0])
    tar.close()
    u.close()
    stat = os.system('./configure --prefix=%s --disable-shared' % tdir)
    if stat != 0:
        return 0
    stat = os.system('make')
    if stat != 0:
        return 0
    stat = os.system('make install')
    if stat != 0:
        return 0

    return (os.path.join(tdir, 'include'), os.path.join(tdir, 'lib'))
import numpy as np
from PCP import PCP_Extractor as pcp
import pickle
import os
from sklearn.linear_model import LogisticRegression as logReg
from sklearn.neural_network import MLPClassifier
from sklearn.linear_model import SGDClassifier as SGDc
from sklearn.metrics import accuracy_score
print('Current directoy is ', os.pwd())
print('Enter target directory')
tar_dir = input()
while not os.path.isdir(tar_dir):
    print('Wrong path or directory doesn\'t exist. Try again')
    tar_dir = input()
X = pcp(tar_dir)
#print(X.shape)
y = np.zeros((X.shape)[0])
counter = 0
value = 1
for i in range((X.shape)[0]):
    if counter == 200:
        value += 1
        counter = 0
    y[i] = value
    counter += 1
#logRegr = logReg()
#logRegr.fit(X, y)
#print(logRegr.predict(X))
#model = MLPClassifier(solver='lbfgs',activation='logistic',
#                      alpha=1e-2, hidden_layer_sizes=(50,),
#                     momentum=0.25, random_state=1)
Esempio n. 16
0
# (base learners).
max_cycle = 1
max_estimators = 1000
max_samples = float('Inf')

# I/O defaults
##############
# If true, the previous output directory is not overwritten, it changes name
save_previous_results = False
# Use default location for the input and output data:
# If no arguments to run.py are provided, this is where the data will be found
# and the results written to. Change the root_dir to your local directory.
from os import getcwd as pwd
from os.path import join

root_dir = pwd()  # e.g. '../' or pwd()
default_input_dir = join(root_dir, "AutoML3_sample_data")
default_output_dir = join(root_dir, "AutoML3_sample_predictions")
default_program_dir = join(root_dir, "AutoML3_ingestion_program")
default_submission_dir = join(root_dir, "AutoML3_sample_code_submission")
default_hidden_dir = join(root_dir, "AutoML3_sample_ref")

# =============================================================================
# =========================== END USER OPTIONS ================================
# =============================================================================

# Version of the sample code
version = 1

# General purpose functions
import time
Esempio n. 17
0
#!.usr/bin/python3

import requests
from rasa.nlu.model import Interpreter
from os import path
from os import getcwd as pwd
from discourse import ConversationStateHandler

RASA_MODEL = path.join(pwd(), 'models', 'nlu')

RASA_SERVER_ENDPOINT = "http://localhost:5005/model/parse"
MIN_CONFIDENCE_THRESHOLD = .6


class RasaNluClient:
    def __init__(self, use_http=False):
        self.endpoint = RASA_SERVER_ENDPOINT
        self.min_confidence_threshold = MIN_CONFIDENCE_THRESHOLD
        self.discourse_state = ConversationStateHandler()
        self._rasa_intepreter = Interpreter.load(RASA_MODEL)

    def detectIntent(self, text):
        return self._rasa_intepreter.parse(text)

    def detectIntentFromHttp(self, text):
        r = requests.post(self.endpoint, json={"text": text})
        # TODO add error code handling
        if not r.ok:
            return {'ERROR': r.reason, 'status_code': r.status_code}
        dat = r.json()
        return dat
akwa(*arguments, **kwarguments)

spacer()

###Slicing

##Reverse string
print('hello'[::-1])

spacer()

# To write this simbol ' ~ ' use:
#option + ñ

####Importing & Using the stardard library:
###Random
import random

choice = random.choice(colors)

print(colors)
print(choice)

spacer()

###os
from os import getcwd as pwd

print(pwd())
Esempio n. 19
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("project_name", help="The name of your project.")
    
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-shared", action='store_true', help="shared library")
    group.add_argument("-exe", action='store_true', help="executable")
    group.add_argument("-static", action='store_true', help="static library")
    
    parser.add_argument("-github", action='store_true', help="ci, github")
    parser.add_argument("-noassets", action='store_true', help="don't create assets")
    parser.add_argument("-notest", action='store_true', help="don't create test")
    parser.add_argument("-basic", action='store_true', help="-noassets -notest")
    
    args = parser.parse_args()
    if not args.exe and not args.shared and not args.static:
        args.exe = True
    if args.basic:
        args.ci = False
        args.noassets = True
        args.notest = True
    
    project_name = args.project_name.strip()
    if not re.match(r"[a-zA-Z][a-zA-Z0-9_]*", project_name):
        print("Invalid project name! name pattern: [a-zA-Z][a-zA-Z0-9_]*")
        return
    mkdirs(project_name)
    cd(project_name)
    project_path = pwd()
    mkdirs("cmake", "src")
    if not args.notest:
        mkdirs("test")
    replace_project_name = lambda content: content.replace("{project_name}", project_name)
    replace_library_shared = lambda content: content.replace("{project_name}", project_name).replace(
        "{is_shared}", 'True')
    replace_library_static = lambda content: content.replace("{project_name}", project_name).replace(
        "{is_shared}", 'False')
    copy = lambda content: content
    
    cmakelists = f'''cmake_minimum_required(VERSION 3.12)
project({project_name} LANGUAGES C CXX)

set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
'''
    
    cmakelists += '\n'
    
    if not args.noassets:
        cmakelists += f'''include(${{CMAKE_CURRENT_LIST_DIR}}/cmake/symlink.cmake)
symlink(assets bin/assets)
'''
    cmakelists += '\n'
    
    cmakelists += '''include(${CMAKE_CURRENT_LIST_DIR}/cmake/conan.cmake)
conan_cmake_run(BASIC_SETUP CONANFILE conanfile.py BUILD missing)

'''
    if not args.notest:
        cmakelists += 'option(BUILD_TEST "Build test" ON)\n'
    
    if not args.exe:
        cmakelists += 'option(BUILD_SHARED "Build shared lib" ON)\n'
    
    cmakelists += '\n'
    
    cmakelists += f'set(sources src/{project_name}/main.cpp)\n\n'
    
    if args.exe:
        cmakelists += f'add_executable({project_name} ${{sources}})\n'
    else:
        cmakelists += f'''if (BUILD_SHARED)
    add_library({project_name} SHARED ${{sources}})
else()
    add_library({project_name} STATIC ${{sources}})
endif()
'''
    
    cmakelists += '\n'
    
    cmakelists += f'''target_include_directories({project_name} PUBLIC
    ${{CMAKE_CURRENT_LIST_DIR}}/src)
target_compile_definitions({project_name} PRIVATE
    $<$<CONFIG:DEBUG>:DEBUG>)
target_link_libraries({project_name}
    PUBLIC
    ${{CONAN_LIBS}}
    $<$<PLATFORM_ID:Linux>:dl>
'''
    
    if not args.exe:
        cmakelists += '''    $<$<CXX_COMPILER_ID:GNU>:-static-libstdc++>
'''
    
    cmakelists += f'''    )
install(TARGETS {project_name})

if (BUILD_TEST)
    file(GLOB_RECURSE test-sources CONFIGURE_DEPENDS "test/*.cpp")
    foreach (file ${{test-sources}})
        get_filename_component(comp ${{file}} NAME_WE)
        add_executable(${{comp}} ${{file}})
        target_include_directories(${{comp}} PUBLIC
            ${{CMAKE_CURRENT_LIST_DIR}}/test)
        target_link_libraries(${{comp}} PRIVATE {'${CONAN_LIBS}' if args.exe else project_name})
    endforeach ()
endif ()
'''
    
    W(cmakelists, 'CMakeLists.txt')
    if args.exe:
        RMW("conanfile.py", replace_library_static)
    elif args.static:
        RMW("conanfile.py", replace_library_static)
    elif args.shared:
        RMW("conanfile.py", replace_library_shared)
    else:
        raise Exception('Unknown project type! should be one of [exe, static, shared]!')
    RMW("build.py", copy)
    RMW("CMakeSettings.json", copy)
    RMW(".clang-format", copy)
    RMW("gitignore", copy, ".gitignore")
    RMW("README.md", replace_project_name)
    
    cd("src")
    mkdirs(project_name)
    cd(project_name)
    if args.exe:
        RMW("main.cpp", copy)
    else:
        RMW("mainlibrary.cpp", copy, "main.cpp")
        RMW("main.h", copy)
    cd('../..')
    
    if not args.notest:
        cd("test")
        if args.exe:
            RMW("test.cpp", copy)
        else:
            RMW("testLibrary.cpp", replace_project_name, "test.cpp")
        cd('..')
    
    cd("cmake")
    RMW("conan.cmake", copy)
    if not args.noassets:
        RMW("symlink.cmake", replace_project_name)
        RMW("symlink.py", copy)
    
    cd("..")
    
    if args.github:
        mkdirs(".github/workflows")
        RMW("export.yml", copy, ".github/workflows/export.yml")
    
    system("git init")
    system("git add .gitignore")
    system("git add -A")
    result = 'Created new '
    if args.exe:
        result += "exe"
    elif args.shared:
        result += "shared library"
    else:
        result += "static library"
    print(f'{result} project: {project_name} (located in {project_path})')
Esempio n. 20
0
 loglist = {"DEBUG": logging.DEBUG,
            "INFO": logging.INFO,
            "WARNING": logging.WARNING,
            "ERROR": logging.ERROR,
            "CRITICAL": logging.CRITICAL}
 logkey = loglist[config["Debug"]["loggerlevel"]]
 logging.info("-----------------Initialising logging-----------------")
 logger = logging.getLogger("Glitch_Heaven")
 logger.setLevel(logkey)
 fh.setLevel(logkey)
 formatter = logging.Formatter('[%(asctime)s] (%(name)s) -'
                               ' %(levelname)s --- %(message)s')
 fh.setFormatter(formatter)
 logger.addHandler(fh)
 logger.info("----------Logger initialised----------")
 logger.debug("Current Working directory is: " + str(pwd()))
 try:
     # Reads the game configuration
     # v-------------------------------------------------------------------v
     logger.info("Parsing configuration file")
     screensize = (int(config["Video"]["screenwidth"]),
                   int(config["Video"]["screenheight"]))
     logger.debug("Screensize set to: " + str(screensize))
     fullscreen = config["Video"]["fullscreen"]
     logger.debug("Fullscreen Flag Set to: "+str(fullscreen))
     doublebuffer = config["Video"]["fullscreen"]
     logger.debug("Doublebuffer Flag set to: " +
                  str(doublebuffer))
     flags = None
     # Reads the control keys
     # v-------------------------------v
Esempio n. 21
0
    dest="only_mine",
    help="Plota apenas os FIIs definidos em user.properties. (default: 0)",
    metavar='',
    default=0)

parser.add_argument("-q",
                    "--quiet",
                    action="store_false",
                    dest="verbose",
                    default=True,
                    help="don't print status messages to stdout")

if __name__ == '__main__':
    args = parser.parse_args()

    PATH_FIIS = SEP_DIR.join([pwd(), 'csvs', 'fiis'])
    filename = datetime.now().strftime("%Y-%m-%d")

    if args.get_fiis:
        # Gera CSV dos dados do FundsExplorer
        generate_csv_current_data(
            path_save_csv=f"{PATH_FIIS}{SEP_DIR}{filename}.csv")

    if args.plot_analise_fiis is not None:
        filenames = listdir(PATH_FIIS)
        filenames.sort()

        plota_fiis(
            path_to_csv=
            f"{PATH_FIIS}{SEP_DIR}{filenames[args.plot_analise_fiis]}",
            setor_auto_fit=args.setor_auto_fit,
from os import path
from os import getcwd as pwd
from os import listdir as ls
from os import chdir as cd
from numpy import isnan
import requests
import sys
from nlu_client import RasaNluClient
from discourse import *
from backends.covid.data_loader import disambiguate, death_rate, STATES_TO_ABBREVIATIONS, covid_cases
from backends.covid.utils import *
from backends.covid.plotter import CovidDataPlotter


RASA_MODEL = path.join(pwd(), 'models', 'nlu.tar.gz')

RASA_SERVER_ENDPOINT = "http://localhost:5005/model/parse"
MIN_CONFIDENCE_THRESHOLD = .6

response_bank = {
    'covid_deathrate': "CovidDeathRateResponse",
    'help_findsomething': "FindSomethingResponse",
    'covid_casecount': "CovidCaseCountResponse",
    'covid_growthcurve': "CovidGrowthCurveResponse",
    "covid_casecount": "CovidConfirmedCasesResponse",
    'PUNT': "PuntResponse"
}


class FulfillmentEngine:
Esempio n. 23
0
import os

PATH = os.pwd()

FILENAME = ''

DATAPATH = ''

MODELPATH = ''

POS = 1
NEG = 0

from collections import namedtuple

arguments = {
    'net': "fasttext",
}
ArgsClass = namedtuple('ArgsClass', [k for k in arguments.keys()])
args = ArgsClass(**arguments)
# use as  args.net
Esempio n. 24
0
    # Make article into a single string
    article = ' '.join(article_lines)

    # Make abstract into a signle string, putting <s> and </s> tags around the sentences
    abstract = ' '.join([
        "%s %s %s" % (SENTENCE_START, sent, SENTENCE_END)
        for sent in highlights
    ])

    return article, abstract


def check_num_stories(stories_dir, num_expected):
    num_stories = len(os.listdir(stories_dir))
    if num_stories != num_expected:
        raise Exception(
            "stories directory %s contains %i files but should contain %i" %
            (stories_dir, num_stories, num_expected))


if __name__ == '__main__':

    # Check the stories directories contain the correct number of .story files
    write_to_bin('vocab_prelim.txt',
                 os.path.join(os.pwd(), "test.bin"),
                 makevocab=True)
    #write_to_bin(all_val_urls, os.path.join(finished_files_dir, "val.bin"))
    #write_to_bin(all_train_urls, os.path.join(finished_files_dir, "train.bin"), makevocab=True)

    # Chunk the data. This splits each of train.bin, val.bin and test.bin into smaller chunks, each containing e.g. 1000 examples, and saves them in finished_files/chunks
    #chunk_all()
Esempio n. 25
0
suggestions:
http://paperjs.org/examples/path-simplification

DO-178B/C tool verification
"""

from flask import Flask, render_template, redirect, url_for, request
app = Flask(__name__)

from file_database.database import FileDatabase

from testcase import TestCaseContentManager as TestCase
from os import getcwd as pwd
# TODO: Allow user to choose database directories
db = FileDatabase(pwd()+'/file_testdb', obj_class=TestCase, ext='xml')

@app.route("/")
@app.route("/search")
def search():
    return render_template("search.html", obj_listing=db.get_objs()) 
    
@app.route("/add", methods=["GET", "POST"])
def add():
    error = None
    if request.method == 'POST':
        error = db.add_obj(request.form["basename"])
        if not error:
            return redirect(url_for("edit", basename=fname))
    return render_template("add.html", error=error)
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from abc import ABC
from os import chdir as cd, getcwd as pwd, listdir as ls
import sys, json
from collections import Counter
from sklearn.manifold import TSNE
from multiprocessing import pool
import numpy as np
rroot = pwd()
PUNCT = '.,;:?!'
APOST = "'"


def shannon_entropy(vec):
    n_nodes = len(vec)
    if n_nodes <= 1:
        return 0
    else:
        counts = np.bincount(vec)
        nzeros = counts[np.nonzero(counts)] / n_nodes
        n_nonzero = len(nzeros)
        if n_nonzero <= 1:
            return 0
        else:
            return -np.sum(nzeros * np.log(np.nzeros)) / np.log(n_nonzero)


def ev2norm(vec):
    '''return the square root of the sum of squares of a list'''
    return np.sqrt(sum(s**2 for s in vec))
Esempio n. 27
0
from sys import path as syspath
from os import getcwd as pwd
from time import sleep

syspath.append(pwd())

import DenisONKYO


print 'starting'

# Create a receiver object attached to the host 192.168.1.124
receiver = DenisONKYO.eISCP('192.168.10.148')

# Turn the receiver off
#receiver.writeCommandFromName('Power OFF')

# Turn the receiver on
#receiver.writeCommandFromName('Power ON')

# Select the PC input
#receiver.writeCommandFromName('Computer/PC')

print 'sleeping 7 seconds. Select a song'
#sleep(7)

# Increasing volume
print 'increasing volume'
#for _ in xrange(10):
#		receiver.writeCommandFromName('Volume Up')
#		sleep(0.5)
Esempio n. 28
0
# (base learners).
max_cycle = 1
max_estimators = 1000
max_samples = float('Inf')

# I/O defaults
##############
# If true, the previous output directory is not overwritten, it changes name
save_previous_results = False
# Use default location for the input and output data:
# If no arguments to run.py are provided, this is where the data will be found
# and the results written to. Change the root_dir to your local directory.
from os import getcwd as pwd
from os.path import join

root_dir = pwd()
print(root_dir)
default_input_dir = join(root_dir, "AutoML3_sample_data")
default_output_dir = join(root_dir, "AutoML3_sample_predictions")
default_program_dir = join(root_dir, "AutoML3_ingestion_program")
default_submission_dir = join(root_dir, "AutoML3_sample_code_submission")
default_hidden_dir = join(root_dir, "AutoML3_sample_ref")

# =============================================================================
# =========================== END USER OPTIONS ================================
# =============================================================================

# Version of the sample code
version = 1

# General purpose functions
 the License.  You may obtain a copy of the License at

      http://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.
'''
from os import getcwd as pwd, listdir as ls, system as cmd, chdir as cd
from os.path import isdir
from random import randint as rand
from cPickle import dump as save, load
import easygui, sys
ignore = pwd()

def getDir():
	return easygui.diropenbox(msg="Pick the folder where all the Simpsons Files are located", \
							 title="Ashwin's Badass Random Simpsons Player")
	
def getPlayer():
	return easygui.fileopenbox(msg="Choose your favorite Media Player", \
							 title="Ashwin's Badass Random Simpsons Player")
	
def about():
	text = """General Stuff:
			I originally wrote this program for a friend by the name of Freddy. 
			This program was meant to play a random Simpsons episode.
			As I wrote this program, however, I came to the realization that 
			it can be used to play any of a bunch of random media files.
Esempio n. 30
0
    def mover(self, map, map2, separator):
        '''
        This function gets two lists with all the things on the desktops
        and copies them into their respective folders, using a forloop and if statements
        '''
        map = map
        map2 = map2
        '''
        Extension Lists
        '''
        shortcuts_extensions = Extensions['shortcut']
        executable_extensions = Extensions['executable']

        # zip extensions source: http://bit.ly/2fnWz4D
        zip_extensions = Extensions['zip']

        # image extensions source: https://fileinfo.com/filetypes/raster_image, https://fileinfo.com/filetypes/vector_image, and https://fileinfo.com/filetypes/camera_raw
        images_extensions = Extensions['image']

        # music extensions source: https://fileinfo.com/filetypes/audio
        music_extensions = Extensions['music']

        # movie extensions source: http://bit.ly/2wvYjyr
        movie_extensions = Extensions['movie']

        # text extensions source: http://bit.ly/2wwcfZs
        text_extensions = Extensions['text']
        D3_work = Extensions['D3work']
        programming_languages_extensions = Extensions['programming']
        try:
            '''Anything from the All_users_desktop goes to shortcuts, mainly because that's all that's ever there (i think)'''
            if separator != '/':
                for item in map2:
                    '''This is a cmd command to move items from one folder to the other'''
                    rename(
                        self.Alldesktopdir + separator + item,
                        self.desktopdir + separator + self.folder_names[1] +
                        separator + item)

            for a in range(0, len(map)):
                if Globals.sc:
                    for b in shortcuts_extensions:
                        if str(map[a].lower()).endswith(b) and str(
                                map[a]) != "Clean.lnk" and str(
                                    map[a]) != "Clean.exe.lnk":
                            rename(
                                self.desktopdir + separator + map[a],
                                self.desktopdir + separator +
                                self.folder_names[1] + separator + map[a])
                            if separator == '/': os.system('cd ..')

                if Globals.exes:
                    for b in executable_extensions:
                        if str(map[a].lower()).endswith(b) and str(
                                map[a].lower()) != "Clean.exe":
                            rename(
                                self.desktopdir + separator + map[a],
                                self.desktopdir + separator +
                                self.folder_names[3] + separator + map[a])
                            if separator == '/': os.system('cd ..')

                if Globals.zips:
                    for b in zip_extensions:
                        if str(map[a].lower()).endswith(b):
                            rename(
                                self.desktopdir + separator + map[a],
                                self.desktopdir + separator +
                                self.folder_names[2] + separator + map[a])
                            if separator == '/': os.system('cd ..')

                if Globals.img:
                    for b in images_extensions:
                        if str(map[a].lower()).endswith(b):
                            rename(
                                self.desktopdir + separator + map[a],
                                self.desktopdir + separator +
                                self.folder_names[4] + separator + map[a])
                            if separator == '/': os.system('cd ..')

                if Globals.audio:
                    for b in music_extensions:
                        if str(map[a].lower()).endswith(b):
                            rename(
                                self.desktopdir + separator + map[a],
                                self.desktopdir + separator +
                                self.folder_names[5] + separator + map[a])
                            if separator == '/': os.system('cd ..')

                if Globals.mov:
                    for b in movie_extensions:
                        if str(map[a].lower()).endswith(b):
                            rename(
                                self.desktopdir + separator + map[a],
                                self.desktopdir + separator +
                                self.folder_names[6] + separator + map[a])
                            if separator == '/': os.system('cd ..')

                if Globals.txt:
                    for b in text_extensions:
                        if str(map[a].lower()).endswith(b):
                            rename(
                                self.desktopdir + separator + map[a],
                                self.desktopdir + separator +
                                self.folder_names[7] + separator + map[a])
                            if separator == '/': os.system('cd ..')

                if Globals.programming:
                    for b in programming_languages_extensions:
                        if str(map[a].lower()).endswith(b):
                            rename(
                                self.desktopdir + separator + map[a],
                                self.desktopdir + separator +
                                self.folder_names[8] + separator + map[a])
                            if separator == '/': os.system('cd ..')

                for b in shortcuts_extensions:
                    if str(map[a].lower()).endswith(b) and str(
                            map[a]) != "Clean.lnk" and str(
                                map[a]) != "Clean.exe.lnk":
                        rename(
                            self.desktopdir + separator + map[a],
                            self.desktopdir + separator +
                            self.folder_names[1] + separator + map[a])
                        if separator == '/': os.system('cd ..')

                for b in executable_extensions:
                    if str(map[a].lower()).endswith(b) and str(
                            map[a].lower()) != "Clean.exe":
                        rename(
                            self.desktopdir + separator + map[a],
                            self.desktopdir + separator +
                            self.folder_names[3] + separator + map[a])
                        if separator == '/': os.system('cd ..')

                for b in zip_extensions:
                    if str(map[a].lower()).endswith(b):
                        rename(
                            self.desktopdir + separator + map[a],
                            self.desktopdir + separator +
                            self.folder_names[2] + separator + map[a])
                        if separator == '/': os.system('cd ..')

                for b in images_extensions:
                    if str(map[a].lower()).endswith(b):
                        rename(
                            self.desktopdir + separator + map[a],
                            self.desktopdir + separator +
                            self.folder_names[4] + separator + map[a])
                        if separator == '/': os.system('cd ..')

                for b in music_extensions:
                    if str(map[a].lower()).endswith(b):
                        rename(
                            self.desktopdir + separator + map[a],
                            self.desktopdir + separator +
                            self.folder_names[5] + separator + map[a])
                        print(os.pwd())
                        if separator == '/': os.system('cd ..')

                for b in movie_extensions:
                    if str(map[a].lower()).endswith(b):
                        rename(
                            self.desktopdir + separator + map[a],
                            self.desktopdir + separator +
                            self.folder_names[6] + separator + map[a])
                        if separator == '/': os.system('cd ..')

                for b in text_extensions:
                    if str(map[a].lower()).endswith(b):
                        rename(
                            self.desktopdir + separator + map[a],
                            self.desktopdir + separator +
                            self.folder_names[7] + separator + map[a])
                        if separator == '/': os.system('cd ..')

                for b in D3_work:
                    if str(map[a].lower()).endswith(b):
                        rename(
                            self.desktopdir + separator + map[a],
                            self.desktopdir + separator +
                            self.folder_names[8] + separator + map[a])
                        if separator == '/': os.system('cd ..')

                for b in programming_languages_extensions:
                    if str(map[a].lower()).endswith(b):
                        rename(
                            self.desktopdir + separator + map[a],
                            self.desktopdir + separator +
                            self.folder_names[8] + separator + map[a])
                        if separator == '/': os.system('cd ..')
                '''This weird part looks for the ".", if its not there this must be a folder'''
                if sys.platform != 'linux':
                    if "." not in str(
                            map[a]) and map[a] not in self.folder_names:
                        rename(
                            self.desktopdir + separator + map[a],
                            self.desktopdir + separator +
                            self.folder_names[0] + separator + map[a])
                    else:
                        '''Just some error handling here'''
                        if map[a].lower() not in self.folder_names:
                            print("I do not know what to do with " + map[a] +
                                  " please update me!")
        except Exception as e:
            print(e)
Esempio n. 31
0
import os

print(os.pwd())
 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.
'''

from os import getcwd as pwd, listdir as ls, system as cmd, chdir as cd
from random import randint as rand

def pickAFile():
        '''Pick a random file or directory from the current directory and return it'''
        files = [i for i in ls('.') if not ignore in i]
        f = files[rand(0, (len(files) -1))]
        return f

def run():
        '''pick a file/dir from the current directory. If it's a file, play it. 
        Else (we picked a directory) cd into that directory and recurse.'''

        f = pickAFile()
        if '.' in f:	# f is a file\
                cmd('"C:\\Program Files\\VideoLAN\\VLC\\vlc.exe" "%s"&' %f)
        else:	# f is a dir
                cd(f)
                run()

if __name__ == "__main__":
        ignore = pwd().split('\\')[-1]
        cd("..")
        run()
Esempio n. 33
0
 def __init__(self):
     self.pwd = pwd()
     self.sys_path = sys.path