import time

import cv2 as cv
import matplotlib.image as mpimg
import numpy as np
from skimage.feature import hog

from configuration import Configuration

config = Configuration().__dict__


class FeatureExtraction:
    @staticmethod
    def bin_spatial(img, size=(32, 32)):
        color1 = cv.resize(img[:, :, 0], size).ravel()
        color2 = cv.resize(img[:, :, 1], size).ravel()
        color3 = cv.resize(img[:, :, 2], size).ravel()
        return np.hstack((color1, color2, color3))

    @staticmethod
    def color_hist(img, nbins=32):  # bins_range=(0, 256)
        # Compute the histogram of the color channels separately
        channel1_hist = np.histogram(img[:, :, 0], bins=nbins)[0]
        channel2_hist = np.histogram(img[:, :, 1], bins=nbins)[0]
        channel3_hist = np.histogram(img[:, :, 2], bins=nbins)[0]
        # Concatenate the histograms into a single feature vector
        hist_features = np.concatenate(
            (channel1_hist, channel2_hist, channel3_hist))
        # Return the individual histograms, bin_centers and feature vector
        return hist_features
Ejemplo n.º 2
0
import requests, json, os
from flask import Flask, request, jsonify
from configuration import Configuration
from CustomJSONEncoder import CustomJSONEncoder

app = Flask(__name__)
app.json_encoder = CustomJSONEncoder
configuration = Configuration()


##Test if application is up
@app.route('/')
def index():
    return "Test page the program is running. Consumer."


##Test function to read customer
@app.route('/events', methods=['GET'])
def getEvents():
    eventData = getFromEventStore(-1)
    return jsonify(eventData), 200


##Test function to read customer
@app.route('/events/<int:event_id>', methods=['GET'])
def getEventByID(event_id):
    eventData = getFromEventStore(event_id)
    return jsonify(eventData), 200


def getFromEventStore(eventID):
Ejemplo n.º 3
0
from configuration import Configuration

#test the configuration class:
#login credentials:
conf = Configuration()
us, pw = conf.getUsernamePassword('Laurenz')

#course entries:
print(us + ":" + pw)
id, date, place = conf.getCourseByName('GDPII')
print(str(id) + ", " + str(date) + " - " + str(place))
Ejemplo n.º 4
0
    def __init__(self):
        configuration = Configuration()
        self.token_bot = configuration.config['TELEGRAM']['BOT_TOKEN']
        self.admins = configuration.config["ADMINS"]
        self.users_state = dict()
        self.storage_helper = StorageHelper()
        self.updater = Updater(self.token_bot, use_context=False)

        dp = self.updater.dispatcher
        dp.add_error_handler(on_error)
        dp.add_handler(CommandHandler('start', self.start))

        dp.add_handler(
            ConversationHandler(
                entry_points=[CommandHandler('newuser', self.new_user)],
                states={
                    ASKED_NEW_USER:
                    [MessageHandler(Filters.forwarded, self.new_user_add)],
                },
                allow_reentry=True,
                fallbacks=[CommandHandler('cancel', self.start)]))

        dp.add_handler(
            ConversationHandler(
                entry_points=[
                    CommandHandler('statusers', self.change_status_user)
                ],
                states={
                    ASKED_DEACTIVATE_USER: [
                        MessageHandler(Filters.command,
                                       self.change_status_user_do)
                    ],
                },
                allow_reentry=True,
                fallbacks=[CommandHandler('cancel', self.start)]))

        dp.add_handler(
            ConversationHandler(
                entry_points=[CommandHandler('newlink', self.new_link)],
                states={
                    ASKED_NEW_LINK: [
                        MessageHandler(Filters.regex('^https://www.avito.ru/'),
                                       self.new_link_add)
                    ],
                },
                allow_reentry=True,
                fallbacks=[CommandHandler('cancel', self.start)]))
        dp.add_handler(
            ConversationHandler(
                entry_points=[CommandHandler('dellink', self.del_link)],
                states={
                    ASKED_DEL_LINK: [
                        MessageHandler(Filters.regex('^/delparser'),
                                       self.del_parser)
                    ],
                },
                allow_reentry=True,
                fallbacks=[CommandHandler('cancel', self.start)]))
        dp.add_handler(
            ConversationHandler(
                entry_points=[CommandHandler('binduser', self.binduser)],
                states={
                    ASKED_BIND_USER:
                    [MessageHandler(Filters.command, self.list_parser)],
                    ASKED_PARSER: [
                        MessageHandler(Filters.regex('^/bindparser'),
                                       self.bind_parser),
                        MessageHandler(Filters.regex('^/unbindparser'),
                                       self.unbind_parser)
                    ]
                },
                allow_reentry=True,
                fallbacks=[CommandHandler('cancel', self.start)]))

        logging.info('Starting long poll')
        self.updater.start_polling()
Ejemplo n.º 5
0
from controllers.game_api import GameApi
from configuration import Configuration

api = GameApi(Configuration())

print(api.getMissions())
Ejemplo n.º 6
0

def render(source, **kwargs):
    template = Template(source.decode('utf-8'))
    return template.render(kwargs)


def QString2str(qstring):
    return str(qstring.toUtf8()).decode('utf-8')


g_pwd = ''  #当前程序目录
g_templates = []  #当前所有可用模板列表
g_projects = []  #所有工程

g_configurations = Configuration()  #用来渲染的配置数据

g_qt_library = [{
    "name": "XML",
    "qt": "xml",
    "refer": False
}, {
    "name": "SVG",
    "qt": "svg",
    "refer": False
}, {
    "name": "Qml",
    "qt": "qml",
    "refer": False
}, {
    "name": "Quick",
Ejemplo n.º 7
0
                # h_time += te - ts

                # ts = time.time()
                if not frontier.hasValue(child):
                    frontier.enqueue(f_score[child], child)
                # te = time.time()
                # e_time += te - ts

    return Stack()


if __name__ == "__main__":
    from water_sort import create_puzzle, show, init

    tubes = create_puzzle()
    config = Configuration(tubes)
    print(config)

    # win = init(500, 400, "A-Star")
    # config.draw(win)

    # show(win)

    ts = time.time()
    sol = a_star(config, calculate_heuristic)
    te = time.time()

    # print(sol)

    print("Solution found in {}".format(te - ts))
Ejemplo n.º 8
0
    def radioState(self, b):
        c = Configuration()
        if b.text() == 'Gnome':
            if b.isChecked() == True:
                c.setSystem('gnome')
                system = c.getSystem()

                runCommand, terminalCommand, interpreterCommand = self.getCommands(
                    c, system)

                self.changeLineEdit(runCommand, terminalCommand,
                                    interpreterCommand)

        if b.text() == 'Mate':
            if b.isChecked() == True:
                c.setSystem('mate')
                system = c.getSystem()

                runCommand, terminalCommand, interpreterCommand = self.getCommands(
                    c, system)

                self.changeLineEdit(runCommand, terminalCommand,
                                    interpreterCommand)

        if b.text() == 'KDE':
            if b.isChecked() == True:
                c.setSystem('kde')
                system = c.getSystem()

                runCommand, terminalCommand, interpreterCommand = self.getCommands(
                    c, system)

                self.changeLineEdit(runCommand, terminalCommand,
                                    interpreterCommand)

        if b.text() == 'xterm':
            if b.isChecked() == True:
                c.setSystem('xterm')
                system = c.getSystem()

                runCommand, terminalCommand, interpreterCommand = self.getCommands(
                    c, system)

                self.changeLineEdit(runCommand, terminalCommand,
                                    interpreterCommand)

        if b.text() == 'Windows':
            if b.isChecked() == True:
                c.setSystem('windows')
                system = c.getSystem()

                runCommand, terminalCommand, interpreterCommand = self.getCommands(
                    c, system)

                self.changeLineEdit(runCommand, terminalCommand,
                                    interpreterCommand)

        if b.text() == 'Mac OS':
            if b.isChecked() == True:
                c.setSystem('mac')
                system = c.getSystem()

                runCommand, terminalCommand, interpreterCommand = self.getCommands(
                    c, system)

                self.changeLineEdit(runCommand, terminalCommand,
                                    interpreterCommand)
Ejemplo n.º 9
0
            self.view.show_menu()
            user_choice = input('请输入以上选项:')
            if user_choice == '1':
                self.controller.add_student()
            elif user_choice == '2':
                self.controller.list_student()
            elif user_choice == '3':
                self.controller.remove_student()
            elif user_choice == '4':
                self.controller.modify_student()
            elif user_choice == '5':
                self.controller.sort_student(list_key='score', high2low=True)
            elif user_choice == '6':
                self.controller.sort_student(list_key='score', high2low=False)
            elif user_choice == '7':
                self.controller.sort_student(list_key='age', high2low=True)
            elif user_choice == '8':
                self.controller.sort_student(list_key='age', high2low=False)
            elif user_choice == '9':
                self.controller.save_students_list()
            elif user_choice == '10':
                self.controller.load_student_list()
            elif user_choice == 'q':
                break
            else:
                print('您的输入有误,请重新输入。')


m = Main(Configuration('configuration.jc'))
m.run()
Ejemplo n.º 10
0
import os, sys
from utils import *
from configuration import Configuration

writer = codecs.open(os.path.abspath(sys.argv[2]), 'w', encoding='utf-8')
for i, sen in enumerate(read_conll(os.path.abspath(sys.argv[1]))):
    if is_projective([e.head for e in sen[1:]]):
        conf = Configuration(sen)
        while not conf.is_terminal_state():
            act, l = conf.next_gold_action()
            label = (act + ':' + l) if l else act
            wf, pf, lf = conf.features()
            writer.write(' '.join(wf) + ' ' + ' '.join(pf) + ' ' +
                         ' '.join(lf) + ' ' + label + '\n')
            conf.do(act, l)
    if (i + 1) % 100 == 0: sys.stdout.write(str(i + 1) + '...')
writer.close()
print('done!')
Ejemplo n.º 11
0
def workflow(input_name,
             input_type='video',
             roi=None,
             automatic_ap_creation=True):
    """
    Execute the whole stacking workflow for a test case. This can either use a video file (.avi .mov .mp4 .ser)
    or still images stored in a single directory.

    :param input_name: Video file (.avi .mov .mp4 .ser) or name of a directory containing still images
    :param input_type: Either "video" or "image" (see "input_name")
    :param roi: If specified, tuple (y_low, y_high, x_low, x_high) with pixel bounds for "region
                of interest"
    :return: average, [average_roi,] color_image_with_aps, stacked_image
             with: - average: global mean frame
                   - average_roi: mean frame restricted to ROI (only if roi is specified)
                   - color_image_with_aps: mean frame overlaid with alignment points and their
                                           boxes (white) and patches (green)
    """

    # Initalize the timer object used to measure execution times of program sections.
    my_timer = timer()
    # Images can either be extracted from a video file or a batch of single photographs. Select
    # the example for the test run.

    # For video file input, the Frames constructor expects the video file name for "names".
    if input_type == 'video':
        names = input_name
    # For single image input, the Frames constructor expects a list of image file names for "names".
    else:
        names = [
            os.path.join(input_name, name) for name in os.listdir(input_name)
        ]
    stacked_image_name = input_name + '.stacked.tiff'

    # The name of the alignment point visualization file is derived from the input video name or
    # the input directory name.
    ap_image_name = input_name + ".aps.jpg"

    print(
        "\n" +
        "*************************************************************************************\n"
        + "Start processing " + str(input_name) +
        "\n*************************************************************************************"
    )
    my_timer.create('Execution over all')

    # Get configuration parameters.
    configuration = Configuration()
    configuration.initialize_configuration()

    # Read the frames.
    print("+++ Start reading frames")
    my_timer.create('Read all frames')
    try:
        frames = Frames(configuration,
                        names,
                        type=input_type,
                        buffer_original=False,
                        buffer_monochrome=False,
                        buffer_gaussian=True,
                        buffer_laplacian=True)
        print("Number of images read: " + str(frames.number))
        print("Image shape: " + str(frames.shape))
    except Error as e:
        print("Error: " + str(e))
        exit()
    my_timer.stop('Read all frames')

    # Rank the frames by their overall local contrast.
    print("+++ Start ranking images")
    my_timer.create('Ranking images')
    rank_frames = RankFrames(frames, configuration)
    rank_frames.frame_score()
    my_timer.stop('Ranking images')
    print("Index of best frame: " + str(rank_frames.frame_ranks_max_index))

    # Initialize the frame alignment object.
    align_frames = AlignFrames(frames, rank_frames, configuration)

    if configuration.align_frames_mode == "Surface":
        my_timer.create('Select optimal alignment patch')
        # Select the local rectangular patch in the image where the L gradient is highest in both x
        # and y direction. The scale factor specifies how much smaller the patch is compared to the
        # whole image frame.
        (y_low_opt, y_high_opt, x_low_opt,
         x_high_opt) = align_frames.compute_alignment_rect(
             configuration.align_frames_rectangle_scale_factor)
        my_timer.stop('Select optimal alignment patch')

        print("optimal alignment rectangle, y_low: " + str(y_low_opt) +
              ", y_high: " + str(y_high_opt) + ", x_low: " + str(x_low_opt) +
              ", x_high: " + str(x_high_opt))

    # Align all frames globally relative to the frame with the highest score.
    print("+++ Start aligning all frames")
    my_timer.create('Global frame alignment')
    try:
        align_frames.align_frames()
    except NotSupportedError as e:
        print("Error: " + e.message)
        exit()
    except InternalError as e:
        print("Warning: " + e.message)
    my_timer.stop('Global frame alignment')

    print("Intersection, y_low: " + str(align_frames.intersection_shape[0][0]) + ", y_high: "
          + str(align_frames.intersection_shape[0][1]) + ", x_low: " \
          + str(align_frames.intersection_shape[1][0]) + ", x_high: " \
          + str(align_frames.intersection_shape[1][1]))

    # Compute the average frame.
    print("+++ Start computing average frame")
    my_timer.create('Compute reference frame')
    average = align_frames.average_frame()
    my_timer.stop('Compute reference frame')
    print("Average frame computed from the best " +
          str(align_frames.average_frame_number) + " frames.")

    # If the ROI is to be set to a smaller size than the whole intersection, do so.
    if roi:
        print("+++ Start setting ROI and computing new average frame")
        my_timer.create('Setting ROI and new reference')
        average_roi = align_frames.set_roi(roi[0], roi[1], roi[2], roi[3])
        my_timer.stop('Setting ROI and new reference')

    # Initialize the AlignmentPoints object.
    my_timer.create('Initialize alignment point object')
    alignment_points = AlignmentPoints(configuration, frames, rank_frames,
                                       align_frames)
    my_timer.stop('Initialize alignment point object')

    if automatic_ap_creation:
        # Create alignment points, and create an image with wll alignment point boxes and patches.
        print("+++ Start creating alignment points")
        my_timer.create('Create alignment points')

        # If a ROI is selected, alignment points are created in the ROI window only.
        alignment_points.create_ap_grid()

        my_timer.stop('Create alignment points')
        print("Number of alignment points selected: " +
              str(len(alignment_points.alignment_points)) +
              ", aps dropped because too dim: " +
              str(alignment_points.alignment_points_dropped_dim) +
              ", aps dropped because too little structure: " +
              str(alignment_points.alignment_points_dropped_structure))
    else:
        # Open the alignment point editor.
        app = QtWidgets.QApplication(sys.argv)
        alignment_point_editor = AlignmentPointEditorWidget(
            None, configuration, align_frames, alignment_points, None)
        alignment_point_editor.setMinimumSize(800, 600)
        alignment_point_editor.showMaximized()
        app.exec_()

        print("After AP editing, number of APs: " +
              str(len(alignment_points.alignment_points)))
        count_updates = 0
        for ap in alignment_points.alignment_points:
            if ap['reference_box'] is not None:
                continue
            count_updates += 1
            AlignmentPoints.set_reference_box(ap, alignment_points.mean_frame)
        print("Buffers allocated for " + str(count_updates) +
              " alignment points.")

    # Produce an overview image showing all alignment points.
    if roi:
        color_image_with_aps = alignment_points.show_alignment_points(
            average_roi)
    else:
        color_image_with_aps = alignment_points.show_alignment_points(average)

    # For each alignment point rank frames by their quality.
    my_timer.create('Rank frames at alignment points')
    print("+++ Start ranking frames at alignment points")
    alignment_points.compute_frame_qualities()
    my_timer.stop('Rank frames at alignment points')

    # Allocate StackFrames object.
    stack_frames = StackFrames(configuration, frames, align_frames,
                               alignment_points, my_timer)

    # Stack all frames.
    print("+++ Start stacking frames")
    stack_frames.stack_frames()

    # Merge the stacked alignment point buffers into a single image.
    print("+++ Start merging alignment patches")
    stacked_image = stack_frames.merge_alignment_point_buffers()

    # Save the stacked image as 16bit int (color or mono).
    my_timer.create('Saving the final image')
    Frames.save_image(stacked_image_name,
                      stacked_image,
                      color=frames.color,
                      header=configuration.global_parameters_version)
    my_timer.stop('Saving the final image')

    # Print out timer results.
    my_timer.stop('Execution over all')
    my_timer.print()

    # Write the image with alignment points.
    Frames.save_image(ap_image_name,
                      color_image_with_aps,
                      color=True,
                      header=configuration.global_parameters_version)

    # If a ROI is selected, return both the original and the reduced-size average frame.
    if roi:
        return average, average_roi, color_image_with_aps, stacked_image
    else:
        return average, color_image_with_aps, stacked_image
Ejemplo n.º 12
0
 def get_configuration(self):
     if self.parsed_arguments is None:
         self.parse_args()
     self.configuration = Configuration(self.parsed_arguments)
     return self.configuration
Ejemplo n.º 13
0
class LogService:
    config = Configuration().doc_config_dict
    INFO = logging.INFO
    ERROR = logging.ERROR
    DEBUG = logging.DEBUG
    WARNING = logging.WARNING
    CRITICAL = logging.CRITICAL
    NOTSET = logging.NOTSET
    FATAL = logging.FATAL

    def __init__(self):
        self.log_enable = None
        self.log_file_name = None
        self.only_save_once = None
        self.log_level = None
        self.log_format = None
        self.logger = None
        self.config_init()
        self.init_log_setting()

    def config_init(self):
        self.log_enable = self.config['logSaveFlag']
        self.log_file_name = self.config['logFileNameValue']
        self.only_save_once = self.config['onlyOnceLogFlag']
        self.log_level = self.config['logLevelValue']
        self.log_format = self.config['logFormatterValue']

    def log_for_call_method(self, log_level):
        def log_method(fun):
            def make_log(*args, **kwargs):
                if self.log_enable:
                    params = ''
                    for arg in args:
                        params += f'{arg},'
                    for kwarg in kwargs:
                        params += f'{kwarg}={kwargs[kwarg]},'
                    self.log(fun.__qualname__ + f'({params[:-1]})执行',
                             log_level)
                    try:
                        ret = fun(*args, **kwargs)
                    except Exception as e:
                        # ttype, tvalue, ttraceback = sys.exc_info()
                        # traceback_str = ''
                        # for traceback_info in traceback.format_exception(ttype, tvalue, ttraceback):
                        #     traceback_str += traceback_info
                        # print(ttype, tvalue, end="\n")
                        # i = 1
                        # while ttraceback:
                        #     print("第{}层堆栈信息".format(i))
                        #     tracebackCode = ttraceback.tb_frame.f_code
                        #     print("文件名:{}".format(tracebackCode.co_filename))
                        #     print("函数或者模块名:{}".format(tracebackCode.co_name))
                        #     ttraceback = ttraceback.tb_next
                        #     i += 1
                        # 等效
                        self.log(
                            fun.__qualname__ + f'({params[:-1]})' +
                            "调用出错,错误信息如下:\n" + traceback.format_exc(),
                            self.ERROR)
                        raise e
                    self.log(fun.__qualname__ + f'({params[:-1]})执行结束',
                             log_level)
                    return ret

            return make_log

        return log_method

    def log(self, message, level):
        if self.log_enable:
            if level == self.ERROR:
                self.logger.error(message)
            if level == self.CRITICAL:
                self.logger.critical(message)
            if level == self.WARNING:
                self.logger.warning(message)
            if level == self.INFO:
                self.logger.info(message)
            if level == self.FATAL:
                self.logger.fatal(message)
            if level == self.DEBUG:
                self.logger.debug(message)

    def init_log_setting(self):
        if self.log_enable:
            logger = logging.getLogger('autoCheckMysql')
            logger.setLevel(self.log_level)
            log_file_handle = logging.FileHandler(
                self.log_file_name,
                'w' if self.only_save_once else 'a',
                encoding='utf8')
            log_file_handle.setLevel(self.log_level)
            formatter = logging.Formatter(self.log_format)
            log_file_handle.setFormatter(formatter)
            logger.addHandler(log_file_handle)
            self.logger = logger
Ejemplo n.º 14
0
    exp_path = "experiments/%s" % exp_name
    if not os.path.exists(exp_path):
        os.makedirs(exp_path)
    else:
        print("Experiment %s already exists" % exp_name)
        sys.exit()

    file_names = ["data/data_batch_%d.bin" % i for i in range(1, 6)]

    pipeline = ip.DataPipeline(file_names, batch_size=batch_size)
    train_x, train_y = pipeline.get_batch_op()

    config = Configuration(
        input_size=3072,
        output_size=10,
        examples_per_epoches=examples_per_epoches,
        batch_size=batch_size,
        a_function=a_function
    )

    dropout = tf.placeholder(tf.float32)

    global_step = tf.Variable(0, trainable=False)

    convo_model = m.ConvoModel(config)
    convo_model.initialize(train_x, dropout)

    loss_op, train_op = convo_model.train_op(train_y, global_step)


    with tf.Session() as session:
Ejemplo n.º 15
0
 def __init__(self, builder, text: str) -> None:
     self._builder = Configuration().handle_request(builder)
     self._text: str = text
Ejemplo n.º 16
0
def get_configuration(db) -> Configuration:
    config = Configuration(db)

    return config
def main():

    # print disclaimer
    disclaimer.print_disclaimer()
    
    # get the full path of configuration/ini file given in the system argument
    iniFileName   = os.path.abspath(sys.argv[1])
    
    # debug option
    debug_mode = False
    if len(sys.argv) > 2: 
        if sys.argv[2] == "debug": debug_mode = True
    
    # no modification in the given ini file, use it as it is
    no_modification = True
    
    # use the output directory as given in the system argument
    if len(sys.argv) > 3 and sys.argv[3] == "--output_dir": 
        no_modification = False
        output_directory = sys.argv[4]

    # object to handle configuration/ini file
    configuration = Configuration(iniFileName = iniFileName, \
                                  debug_mode = debug_mode, \
                                  no_modification = no_modification)      
    if no_modification == False:
        configuration.main_output_directory = output_directory
        configuration.globalOptions['outputDir'] = output_directory
        configuration.set_configuration()
    
    # timeStep info: year, month, day, doy, hour, etc
    currTimeStep = ModelTime() 
    
    # object for spin_up
    spin_up = SpinUp(configuration)            

    # spinningUp
    noSpinUps = int(configuration.globalOptions['maxSpinUpsInYears'])
    initial_state = None
    if noSpinUps > 0:
        
        logger.info('Spin-Up #Total Years: '+str(noSpinUps))

        spinUpRun = 0 ; has_converged = False
        while spinUpRun < noSpinUps and has_converged == False:
            spinUpRun += 1
            currTimeStep.getStartEndTimeStepsForSpinUp(
                    configuration.globalOptions['startTime'],
                    spinUpRun, noSpinUps)
            logger.info('Spin-Up Run No. '+str(spinUpRun))
            deterministic_runner = DeterministicRunner(configuration, currTimeStep, initial_state)
            
            all_state_begin = deterministic_runner.model.getAllState() 
            
            dynamic_framework = DynamicFramework(deterministic_runner,currTimeStep.nrOfTimeSteps)
            dynamic_framework.setQuiet(True)
            dynamic_framework.run()
            
            all_state_end = deterministic_runner.model.getAllState() 
            
            has_converged = spin_up.checkConvergence(all_state_begin, all_state_end, spinUpRun, deterministic_runner.model.routing.cellArea)
            
            initial_state = deterministic_runner.model.getState()
    
    # Running the deterministic_runner (excluding DA scheme)
    currTimeStep.getStartEndTimeSteps(configuration.globalOptions['startTime'],
                                      configuration.globalOptions['endTime'])
    logger.info('Transient simulation run started.')
    deterministic_runner = DeterministicRunner(configuration, currTimeStep, initial_state)
    dynamic_framework = DynamicFramework(deterministic_runner,currTimeStep.nrOfTimeSteps)
    dynamic_framework.setQuiet(True)
    dynamic_framework.run()


    # for debugging to PCR-GLOBWB version one
    if configuration.debug_to_version_one:
    
        logger.info('\n\n\n\n\n'+'Executing PCR-GLOBWB version 1.'+'\n\n\n\n\n')

        # reset modelTime object
        currTimeStep = None; currTimeStep = ModelTime() 
        currTimeStep.getStartEndTimeSteps(configuration.globalOptions['startTime'],
                                          configuration.globalOptions['endTime'])
        
        # execute PCR-GLOBWB version 1
        # - including comparing model outputs (from versions one and two)
        pcrglobwb_one = oldcalc_framework.PCRGlobWBVersionOne(configuration, \
                                                              currTimeStep, \
                                                              deterministic_runner.model.routing.landmask, \
                                                              deterministic_runner.model.routing.cellArea)
        dynamic_framework = DynamicFramework(pcrglobwb_one, currTimeStep.nrOfTimeSteps)
        dynamic_framework.setQuiet(True)
        dynamic_framework.run()
Ejemplo n.º 18
0
        os.mkdir(c.FOLDER_CONFIGS)
    if not os.path.exists(c.FOLDER_USER_CONFIGS):
        os.mkdir(c.FOLDER_USER_CONFIGS)
    if not os.path.exists(c.FOLDER_OUTPUT_CONSOLE):
        os.mkdir(c.FOLDER_OUTPUT_CONSOLE)

    if '--no-gui' in sys.argv:
        print(sys.argv)
        input_fname = 'planet_48.9,55.703_49.317,55.871.osm'
        output_fname = 'output/console/map.jpg'
        max_dim = 6000

        # Create and save map render using the MapWidget object
        widget = MapWidget()

        # Same size as in MainWindowHandlers
        widget.resize(986, 631)
        widget.setConfiguration(Configuration())
        widget.setOSMFile(input_fname)
        widget.saveImage(max_dim, output_fname)

        # Kill application
        app.quit()
    else:
        # Start the program
        window = MainWindowHandlers()
        window.initialize()
        window.show()

        sys.exit(app.exec_())
Ejemplo n.º 19
0
import json
import collections

import helper_test

from configuration import Configuration
from helper import Helper

debug = True
configuration = Configuration('actioncam',
                              path=helper_test.config_path(),
                              debug=debug)
config_actioncam = configuration.config["actioncam"]
helper = Helper(configuration.config)
helper.state_set_start()


def test_config_default():
    print("test_config_default")
    assert configuration.config['DEFAULT'] != "", "Failed checkingd Default"
    j = configuration.config['DEFAULT']
    j = collections.OrderedDict(sorted(j.items()))
    print(json.dumps(j, indent=4, sort_keys=True))


def test_config_output_folder():
    print("test_config_output_folder")
    c_camera = configuration.config["camera"]
    type = "motion.avi"
    out = c_camera["recording_location"] + "/" + c_camera[
        'identify'] + "_" + helper.now_str() + "_" + type
Ejemplo n.º 20
0
def import_last_file():
    config = Configuration()
    files = config.read_last_file()
    import_file(files, True)
Ejemplo n.º 21
0
 def test_all_existing_settings_are_modified(self):
     configsetting = Configuration("config.ini", self.settings03)
     self.assertEqual(self.settings03, configsetting.settings)
Ejemplo n.º 22
0
def import_data(data):
    """导入数据"""
    data_query = DataQuery()
    data_query.process(Configuration(), data)
Ejemplo n.º 23
0
    def __init__(self, parent=None):
        super().__init__(parent)
        
        self.filename = None
        self.fileBrowser = None
        self.mainWindow = parent
        self.debugging = False
        
        c = Configuration()
        self.pointSize = int(c.getFontSize())
        self.tabWidth = int(c.getTab())
        
        # Scrollbars
        self.verticalScrollBar().setStyleSheet(
            """border: 20px solid black;
            background-color: darkgreen;
            alternate-background-color: #FFFFFF;""")
    
        self.horizontalScrollBar().setStyleSheet(
            """border: 20px solid black;
            background-color: darkgreen;
            alternate-background-color: #FFFFFF;""")
        
        # matched / unmatched brace color ...
        self.setMatchedBraceBackgroundColor(QColor('#000000'))
        self.setMatchedBraceForegroundColor(QColor('cyan'))
        self.setUnmatchedBraceBackgroundColor(QColor('#000000'))
        self.setUnmatchedBraceForegroundColor(QColor('red'))

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
        
        # edge mode ... line at 79 characters 
        self.setEdgeColumn(79)
        self.setEdgeMode(1)
        self.setEdgeColor(QColor('dark green'))

        # Set the default font
        self.font = QFont()
        
        system = platform.system().lower()
        if system == 'windows':
            self.font.setFamily('Consolas')
        else:
            self.font.setFamily('Monospace')
        
        self.font.setFixedPitch(True)
        self.font.setPointSize(self.pointSize)
        self.setFont(self.font)
        self.setMarginsFont(self.font)

        # Margin 0 is used for line numbers
        fontmetrics = QFontMetrics(self.font)
        self.setMarginsFont(self.font)
        self.setMarginWidth(0, fontmetrics.width("00000") + 5)
        self.setMarginLineNumbers(0, True)
        self.setMarginsBackgroundColor(QColor("#000000"))
        self.setMarginsForegroundColor(QColor("#FFFFFF"))
        
        # Margin 1 for breakpoints
        self.setMarginSensitivity(1, True)
        self.markerDefine(QsciScintilla.RightArrow, 8)
        self.setMarkerBackgroundColor(QColor('#FF0000'), 8)
        
        # variable for breakpoint
        self.breakpoint = False
        self.breakpointLine = None
        

        # FoldingBox
        self.setFoldMarginColors(QColor('dark green'), QColor('dark green'))
        
        # CallTipBox
        self.setCallTipsForegroundColor(QColor('#FFFFFF'))
        self.setCallTipsBackgroundColor(QColor('#282828'))
        self.setCallTipsHighlightColor(QColor('#3b5784'))
        self.setCallTipsStyle(QsciScintilla.CallTipsContext)
        self.setCallTipsPosition(QsciScintilla.CallTipsBelowText)
        self.setCallTipsVisible(-1)
        
        # change caret's color
        self.SendScintilla(QsciScintilla.SCI_SETCARETFORE, QColor('#98fb98'))
        self.setCaretWidth(4)

        # tab Width
        self.setIndentationsUseTabs(False)
        self.setTabWidth(self.tabWidth)
        # use Whitespaces instead tabs
        self.SendScintilla(QsciScintilla.SCI_SETUSETABS, False)
        self.setAutoIndent(True)
        self.setTabIndents(True)

        # BackTab
        self.setBackspaceUnindents(True)

        # Current line visible with special background color or not :)
        #self.setCaretLineVisible(False)
        #self.setCaretLineVisible(True)
        #self.setCaretLineBackgroundColor(QColor("#020202"))               
        self.setMinimumSize(300, 300)
        
        # get style
        self.style = None
        
        # Call the Color-Function: ...
        self.setPythonStyle()
        
        #self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)

        # Contextmenu
        self.setContextMenuPolicy(Qt.ActionsContextMenu)
        undoAction = QAction("Undo", self)
        undoAction.triggered.connect(self.undoContext)
        redoAction = QAction("Redo", self)
        redoAction.triggered.connect(self.redoContext)
        sepAction1 = QAction("", self)
        sepAction1.setSeparator(True)
        cutAction = QAction("Cut", self)
        cutAction.triggered.connect(self.cutContext)
        copyAction = QAction("Copy", self)
        copyAction.triggered.connect(self.copyContext)
        pasteAction = QAction("Paste", self)
        pasteAction.triggered.connect(self.pasteContext)
        sepAction2 = QAction("", self)
        sepAction2.setSeparator(True)
        sepAction3 = QAction("", self)
        sepAction3.setSeparator(True)
        selectAllAction = QAction("Select All", self)
        selectAllAction.triggered.connect(self.getContext)
        sepAction4 = QAction("", self)
        sepAction4.setSeparator(True)
        breakpointAction = QAction("Run until Breakpoint", self)
        breakpointAction.triggered.connect(self.breakpointContext)
        terminalAction = QAction("Open Terminal", self)
        terminalAction.triggered.connect(self.termContext)
        
        self.addAction(undoAction)
        self.addAction(redoAction)
        self.addAction(sepAction1)
        self.addAction(cutAction)
        self.addAction(copyAction)
        self.addAction(pasteAction)
        self.addAction(sepAction2)
        self.addAction(selectAllAction)
        self.addAction(sepAction3)
        self.addAction(breakpointAction)
        self.addAction(sepAction4)
        self.addAction(terminalAction)

        # signals
        self.SCN_FOCUSIN.connect(self.onFocusIn)
        self.textChanged.connect(self.onTextChanged)
        self.marginClicked.connect(self.onMarginClicked)
Ejemplo n.º 24
0
def import_resources():
    """导入资源文件"""
    data_query = DataQuery()
    data_query.import_resources(Configuration())
Ejemplo n.º 25
0
import os
import socket

import logging as log
from configuration import Configuration

config = Configuration()

#print("Using GPU {} on {}".format(config.train.cuda_device_id[socket.gethostname()], socket.gethostname()))
# os.environ["CUDA_VISIBLE_DEVICES"] = str(config.train.cuda_device_id[socket.gethostname()])

os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"  # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = str(
    config.train.cuda_device_id
)  #str(config.train.cuda_device_id[socket.gethostname()])
#os.environ["TF_CPP_MIN_LOG_LEVEL"]="2" # Silence tensorflow initialization messages

from workflow.evaluate import *

if config.eval.verbose == 0:
    log.basicConfig(format="%(levelname)s: %(message)s", level=log.WARN)
    log.warn("logging level WARN")
elif config.eval.verbose == 2:
    log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG)
    log.debug("logging level DEBUG")
else:
    log.basicConfig(format="%(levelname)s: %(message)s", level=log.INFO)
    log.info("logging level INFO")

if config.eval.verbose in [1, 2]:
    parse_configuration(config,
Ejemplo n.º 26
0
def open_config():
    # 打开配置文件
    open_file(Configuration().app_config_file)
Ejemplo n.º 27
0
import pickle
import random
from deap import base
from math import isinf

from util import DFATooLargeException
from hmm import HMM
from grammar import Grammar
from nfa_parser import nfa_parser_get_most_probable_parse
from configuration import Configuration
from uniform_encoding import UniformEncoding
from rule_set import RuleSet
from copy import deepcopy
import ga_config

configurations = Configuration()
uniform_encoding = UniformEncoding()


class HypothesisFitness(base.Fitness):
    def __init__(self):
        self.weights = (-1.0,)
        super(HypothesisFitness, self).__init__()


class Hypothesis:
    def __init__(self, grammar):
        self.grammar = grammar
        # these three fields have temporal cohesion with get_energy()
        self.energy_signature = None
        self.energy = None
Ejemplo n.º 28
0
 def builder(self, value) -> None:
     self._builder = Configuration().handle_request(value)
Ejemplo n.º 29
0
    def __init__(self):
        self.hardwConst = HardwareConstants()
        self.configs = Configuration()

        self.sampleRate = 5000
Ejemplo n.º 30
0
                if self.board[0, x, y]:
                    res += 'X' + blank
                elif self.board[1, x, y]:
                    res += 'O' + blank
                else:
                    res += '.' + blank
            if x != 2: res += '\n\n'
        return res


if __name__ == '__main__':

    from encoding import *
    from configuration import Configuration

    c = Configuration()

    randAI = randomAI.RandomAI()
    nnAI = snnAI.SnnAI(c)

    nnAI_plays = True
    human_plays = True

    s = GameState()
    while not s.finished:

        if human_plays and not nnAI_plays:
            move_str = input("\nChoose your move: ")
            move = tuple(int(x) for x in move_str.split(','))

        elif nnAI_plays: