def __init__(self, exp, parameters):
        """ Initialize the experiment object. """

        # Create Task and Model objects
        self.task = Task(exp, parameters)
        self.model = self.Model(exp, parameters)
Exemplo n.º 2
0
import telebot
import bs4
from Task import Task
import parser
import markups as m

#main variables
TOKEN = '509706011:AAF7aaaaaaaaaaaaaaaaaaaAAAaaAAaAaAAAaa'
bot = telebot.TeleBot(TOKEN)
task = Task()


#handlers
@bot.message_handler(commands=['start', 'go'])
def start_handler(message):
    if not task.isRunning:
        chat_id = message.chat.id
        msg = bot.send_message(chat_id,
                               'Откуда парсить?',
                               reply_markup=m.source_markup)
        bot.register_next_step_handler(msg, askSource)
        task.isRunning = True


def askSource(message):
    chat_id = message.chat.id
    text = message.text.lower()
    if text in task.names[0]:
        task.mySource = 'top'
        msg = bot.send_message(chat_id,
                               'За какой временной промежуток?',
Exemplo n.º 3
0
Arquivo: Tests.py Projeto: WeekFax/TDD
 def testCreatingTask(self):
     task = Task()
     self.assertIsNotNone(task)
Exemplo n.º 4
0
 def addTask(self, t):
     nt = Task(t)
     nt.connect("taskSelected", self.taskSelected)
     self.tasks.pack_start(nt.main, True, True, 0)
     self.taskList.append(nt)
     nt.main.show_all()
Exemplo n.º 5
0
 def create_task_ui(self, container):
     task = Task(container, self)
     task.grid(row=1, column=0, sticky="nsew")
                            break
                    while True:
                        descricao = input("Digite a descrição da tarefa:\n")
                        if (descricao != ""):
                            break
                    prioridade = ""
                    while (prioridade != "1" and prioridade != "2"
                           and prioridade != "3"):
                        prioridade = input(
                            "Digite a prioridade da tarefa:\n1- Alta \n2- Média \n3- Baixa\n"
                        )

                    os.system("cls")
                    ultimoId = getUltimoId(user.login)
                    id_task = ultimoId + 1
                    task = Task(titulo, descricao, prioridade, id_task,
                                user.login)
                    task.insertTask(user)

                #Bloco de código para visualizar as tarefas do usuário logado
                elif (option == 2):
                    os.system("cls")
                    dicttasks = Task.getDicTask(Task, user.login)
                    if (dicttasks):
                        tasks = OrdenaTask(user, dicttasks)
                        print(tasks)
                    else:
                        print("Não há tarefas cadastradas")
                    input("Aperte enter para voltar ao menu de tarefas.")
                    os.system("cls")

                #Bloco de código para alterar informações das tarefas do usuário
Exemplo n.º 7
0
    def __run__(self):
        """ Service.__run__()
            runs the service cycle
        """

        # setup
        name = self.name
        if self.verbose:
            print 'Starting %s' % name
            sys.stdout.flush()

        # --------------------------------------------------------------
        #   Main Cycle - Continue until Death
        # --------------------------------------------------------------
        while True:

            # --------------------------------------------------------------
            #   Check parent process status
            # --------------------------------------------------------------
            if not check_pid(self.parentpid):
                break

            # --------------------------------------------------------------
            #   Check inbox queue
            # --------------------------------------------------------------
            # try to get a task
            try:
                this_task = self.inbox.get(block=True, timeout=1.0)
            # handle exceptions
            except (
                    mp.queues.Empty,  # empty queue
                    EOFError,
                    IOError):  # happens on python exit
                continue
            # raise exceptions for python exit
            except (KeyboardInterrupt, SystemExit):
                raise
            # print any other exception
            except Exception as exc:
                if self.verbose:
                    sys.stderr.write('%s: Get Failed \n' % name)
                    sys.stderr.write(traceback.format_exc())
                    sys.stderr.write('\n')
                    sys.stderr.flush()
                continue

            # report
            if self.verbose:
                print '%s: Got task' % name
                sys.stdout.flush()

            # --------------------------------------------------------------
            #   Execute Task
            # --------------------------------------------------------------
            try:
                # check task object type
                if not isinstance(this_task, Task):
                    #raise Exception, 'Task must be of type VyPy.Task'
                    this_task = Task(this_task, self.function)

                # unpack task
                this_input = this_task.inputs
                this_function = this_task.function or self.function
                this_owner = this_task.owner
                this_folder = this_task.folder

                # --------------------------------------------------------------
                #   Check for kill signal
                # --------------------------------------------------------------
                if isinstance(this_input, KillTask.__class__):
                    self.inbox.task_done()
                    break

                # report
                if self.verbose:
                    print '%s: Inputs = %s, Operation = %s' % (
                        name, this_input, self.function)
                    sys.stdout.flush()

                # --------------------------------------------------------------
                #   Call Task Function
                # --------------------------------------------------------------
                # in the folder it was created
                with redirect.folder(this_folder):
                    # report
                    if self.verbose:
                        print os.getcwd()
                        sys.stdout.flush()

                    # the function call!
                    this_output = self.__func__(this_input, this_function)

                # report
                if self.verbose:
                    print '%s: Task complete' % name
                    sys.stdout.flush()

                # make sure we get std's
                sys.stdout.flush()
                sys.stderr.flush()

            # --------------------------------------------------------------
            #   Task Exception Catching
            # --------------------------------------------------------------
            # system exits
            except (KeyboardInterrupt, SystemExit):
                raise
            # all other exceptions
            except Exception as exc:
                trace_str = traceback.format_exc()
                sys.stderr.write('%s: Task Failed \n' % name)
                sys.stderr.write(trace_str)
                sys.stderr.write('\n')
                sys.stderr.flush()
                exc.args = (trace_str, )
                this_output = exc

            #: end try task

            # --------------------------------------------------------------
            #   Wrap Up Task
            # --------------------------------------------------------------

            # store output
            this_task.outputs = this_output

            # pick outbox
            this_outbox = this_task.outbox or self.outbox
            # avoid serialization error with managed outboxes
            this_task.outbox = None

            # put task
            if this_outbox: this_outbox.put(this_task)

            # end joinable inbox task
            self.inbox.task_done()

        #: end while alive

        # --------------------------------------------------------------
        #   End of Process
        # --------------------------------------------------------------

        # report
        if self.verbose:
            print '%s: Ending' % name
            sys.stdout.flush()

        return
Exemplo n.º 8
0
 def setup(self):
     self.task = Task()
     self.stage.requirements = []
     self.stage.actions = []
     pass
Exemplo n.º 9
0
from Grid import Grid
from Agent import Agent
from Task import Task
from TaskList import TaskList
from Score import Score
from Qlearning import Qlearning
import random

grid1 = Grid()
grid2 = Grid()
for i in range(10):
    agent1 = Agent(grid1, 0, 2)
    task1 = Task(grid2, 2, 0)

    Agent.agentView()

    #Grid.printGrid(grid1)
    #Grid.printGrid(grid2)
    ALPHA = 0.8
    GAMMA = 0.2
    count = 0
    while count < 5000:
        qtimes = 0
        tempQListID = -1
        n = random.randint(0, Agent.new_id)
        #print(n)

        if (n == 'q'):
            break
        elif (int(n) <= Agent.new_id and int(n) >= 0):
            for a in Agent.AgentList:
Exemplo n.º 10
0
 def create_n_randon_tasks(self, quantity):
     for i in range(quantity):
         task = Task(self.next_id())
         self.scheduler.queue(task)
Exemplo n.º 11
0
 def load(self, id, className):
     self.tasks[id] = Task(self.driverID, self.client, id, className)
Exemplo n.º 12
0
def check_tasks_to_schedule(start_daemon=start_daemon):

    cur_time = current_milli_time()
    window_left = cur_time
    window_right = window_left + 20 * MINUTE
    mylogger.info('start checking tasks at ' + str(milliseconds_to_string(window_left)))
    mylogger.info('tasks interval to be included: ' + str(milliseconds_to_string(window_left)) +  ' and ' +  str(milliseconds_to_string(window_right)))
    task_list = list(map(Task, tasks.aggregate([
        {
            '$match': {'assigned': False}
        },
        {
            '$addFields': {
                'time2': {
                    '$add': [
                        '$time',
                        {'$multiply': ['$tolerance', 0.5]}
                    ]
                },
                'time3': {
                    '$subtract': [
                        '$time',
                        {'$multiply': ['$tolerance', 0.5]}
                    ]
                }
            }
        },
        {
            '$match': {
                'time2': {'$gte': window_left},
                'time3': {'$lt': window_right}
            }
        },
        {
            '$sort': {'time': 1}
        }
    ])))

    mylogger.info("task_list:" + str([str(t) for t in task_list]))

    if len(task_list) > 0:
        un_finished_tasks = schedule_tasks(task_list, cur_time)
        resumed = False
        for task in sorted(un_finished_tasks, key=lambda t: t.time):
            soonest = task.time - window_left - task.tolerance / 2
            latest = task.time - window_left + task.tolerance / 2 - 10 * SECOND
            # Note: latest cannot be the exact task.time + tolerance/2, because of the processing delay, when reschedule, the right bound will not be included.
            interval = max( MINUTE, soonest)

            if latest > interval:
                mylogger.info("recall check_task_to_schedule due to" + str(task.id) + ' after ' + str(interval/SECOND) + ' seconds. Now is ' + str(milliseconds_to_string(window_left)))
                start_daemon(interval / SECOND, check_tasks_to_schedule, [])
                resumed = True
                break
            else:

                mylogger.info("task " + str(task.id) +" is compromised")
                tasks.update_one({"_id": task.id}, {'$set': {"compromised": True, "num_devices": len(task.assignment_list)}})

        if not resumed:
            next_time = (window_right - window_left) / SECOND
            mylogger.info("tasks are scheduled, next calling is" + str(next_time) + ' seconds ' + ' Now is '+ str(milliseconds_to_string(window_left)))
            start_daemon(next_time, check_tasks_to_schedule, [])
    else:
        next_tasks = list(tasks.find({
            "finished": False,
            "assigned": False,
            "time": {"$gte": window_right}
        }).sort('time', 1).limit(1))

        mylogger.info('next_tasks: ' + str([str(t) for t in next_tasks]))

        if len(next_tasks) > 0:
            next_task = Task(next_tasks[0])
            gap = (next_task.time - next_task.tolerance / 2 - window_left)
            mylogger.info('start next check_tasks_to_schedule after' + str(gap/SECOND))
            start_daemon(gap / SECOND, check_tasks_to_schedule, [])
        else:
            mylogger.info('start next check_tasks_to_schedule after 20 minutes')
            start_daemon(20 * 60,  check_tasks_to_schedule, [])
Exemplo n.º 13
0
Mvns.remove(Mvns[10])
Mvns.remove(Mvns[12])
Mvns.remove(Mvns[6])

hh = 0

# thiết lập các thông số cho mỗi MVN

for i in Mvns:
    i.set_rm()
    i.get_rm()
    hh = hh + 1
    i.set_id(hh)

# tạo MecServer
MECServer = Server(Config.F_MEC)

# khoi tao remote Cloud
remoteCloud = Cloud_remote(Config.F_RM, Config.R0)

for i in range(100):
    tasks.append(
        Task(random.randint(Config.Wi[0], Config.Wi[1]),
             random.randint(Config.Di[0], Config.Di[1]),
             random.randint(Config.response[0], Config.response[1])))

with open("./data/task.p", "wb") as task:
    pickle.dump(tasks, task)
with open("./data/fog_device.p", "wb") as mvn:
    pickle.dump((Mvns, MECServer, remoteCloud), mvn)
Exemplo n.º 14
0
 def update(self):
     self.box.clear_widgets()
     for task in self.c.execute("SELECT * FROM tasks WHERE date = ?",
                                [self.currentDate]):
         self.box.add_widget(Task(task[0], task[1], task[2], task[3]))
Exemplo n.º 15
0
def main():
    # All possible Flags
    fAdd = False
    fView = False
    fDelete = False
    fModify = False
    fMarkFinished = False
    fAddTaskName = ""
    fAddTaskDesc = ""
    fViewTaskName = ""

    # Mode Parsing Flags
    pfFoundMode = False

    # Overall Mode Flags
    needsWrite = False # Set to true to write to the changed files

    if len(sys.argv) <= 1:
        print(consoleDocs.help)
        return
    else:
        # Print Help and Quit
        if sys.argv[1] == "-h" or sys.argv[1] == "--help" or sys.argv[1] =="/h":
            print(consoleDocs.help)
            return

        tree = readwrite.getTaskTree()
        #print(tree)

        if sys.argv[1] == "-i" or sys.argv[1] == "--interactive" or sys.argv[1] == "/i":
            console.interactive()
            return
        ignore = sys.argv[0]
        for arg in sys.argv:
            # Ignore the first argument, as this is the name of the program
            if arg == ignore:
                continue

            # Find Mode to operate in
            if not pfFoundMode and (arg == "-a" or arg == "--add" or arg == "/a" or arg == "+"):
                fAdd = True
                pfFoundMode = True
                continue
            elif not pfFoundMode and (arg == "-m" or arg == "--modify" or arg == "/m"):
                fModify = True
                pfFoundMode = True
                print("NOT IMPLEMENTED", file=sys.stderr)
                continue
            elif not pfFoundMode and (arg == "-v" or arg == "--view" or arg == "/v"):
                fView = True
                pfFoundMode = True
                print("NOT COMPLETELY IMPLEMENTED", file=sys.stderr)
                continue
            elif not pfFoundMode and (arg == "-d" or arg == "--delete" or arg == "/d" or arg == "-"):
                fDelete = True
                pfFoundMode = True
                print("NOT IMPLEMENTED", file=sys.stderr)
                continue
            elif not pfFoundMode:
                print("Invalid Syntax on ", arg, " in ", getArgsAsString(sys.argv), consoleDocs.help, file=sys.stderr)
                return

            # Add a new entry
            if pfFoundMode and fAdd and fAddTaskName == "":
                fAddTaskName = arg
                continue
            if pfFoundMode and fAdd and fAddTaskName != "" and fAddTaskDesc == "":
                fAddTaskDesc = arg
                # At this point entry is finished.
                t = Task(fAddTaskName, fAddTaskDesc)
                t.changed = True
                t.created = datetime.datetime.now()
                taskName = fAddTaskName
                if taskName in tree:
                    idx = 1
                    while taskName + str(idx) in tree:
                        idx += 1
                    taskName += str(idx)
                t.path = taskName
                tree[taskName] = t.getDictObject()
                # Reset so that we can parse more arguments
                pfFoundMode = False
                fAdd = False
                needsWrite = True
                continue

            # View a specific Task
            if pfFoundMode and fView and fViewTaskName == "":
                fViewTaskName = arg
                pfFoundMode = False
                if fViewTaskName == "":
                    lines = console.getPrettyTextForAll(tree)
                    for line in lines:
                        print(line)
                else:
                    if fViewTaskName in tree:
                        print(console.getPrettyText(tree[fViewTaskName]))
                    else:
                        results = proc.findTasksByName(fViewTaskName, tree)
                        if len(results) == 1:
                            print(console.getPrettyText(tree[results[0]]))
                        elif len(results) > 1:
                            print("Multiple Results Found... Pick a Number to view more")
                            for res in results:
                                print(console.getPrettyText(tree[res[1]]))
                    
        # If View was the only argument
        if pfFoundMode and fView:
            lines = console.getPrettyTextForAll(tree)
            for line in lines:
                print(line)

        # Perform Writes only if something was changed
        if needsWrite:
            readwrite.writeTaskTree(tree)
Exemplo n.º 16
0
def build(objtId, p):
    if (p.__class__.__name__ == 'AttackerParameters'):
        return Attacker(objtId, p.name(), p.description(), p.image(), p.tags(),
                        p.environmentProperties())
    if (p.__class__.__name__ == 'PersonaParameters'):
        return Persona(objtId, p.name(), p.activities(), p.attitudes(),
                       p.aptitudes(), p.motivations(),
                       p.skills(), p.intrinsic(), p.contextual(), p.image(),
                       p.assumption(), p.type(), p.tags(),
                       p.environmentProperties(), p.codes())
    if (p.__class__.__name__ == 'AssetParameters'):
        return Asset(objtId, p.name(), p.shortCode(), p.description(),
                     p.significance(), p.type(), p.critical(),
                     p.criticalRationale(), p.tags(), p.interfaces(),
                     p.environmentProperties())
    if (p.__class__.__name__ == 'TemplateAssetParameters'):
        return TemplateAsset(objtId, p.name(), p.shortCode(), p.description(),
                             p.significance(), p.type(), p.surfaceType(),
                             p.accessRight(), p.properties(), p.tags(),
                             p.interfaces())
    if (p.__class__.__name__ == 'TemplateRequirementParameters'):
        return TemplateRequirement(objtId, p.name(), p.asset(), p.type(),
                                   p.description(), p.rationale(),
                                   p.fitCriterion())
    if (p.__class__.__name__ == 'TemplateGoalParameters'):
        return TemplateGoal(objtId, p.name(), p.definition(), p.rationale(),
                            p.concerns(), p.responsibilities())
    if (p.__class__.__name__ == 'SecurityPatternParameters'):
        return SecurityPattern(objtId, p.name(), p.context(), p.problem(),
                               p.solution(), p.requirements(),
                               p.associations())
    if (p.__class__.__name__ == 'ComponentParameters'):
        return Component(objtId, p.name(), p.description(), p.interfaces(),
                         p.structure(), p.requirements(), p.goals(),
                         p.associations())
    if (p.__class__.__name__ == 'ComponentViewParameters'):
        return ComponentView(objtId, p.name(), p.synopsis(), p.components(),
                             p.connectors(), p.attackSurfaceMetric())
    if (p.__class__.__name__ == 'ValueTypeParameters'):
        return ValueType(objtId, p.name(), p.description(), p.type(),
                         p.score(), p.rationale())
    if (p.__class__.__name__ == 'ClassAssociationParameters'):
        return ClassAssociation(objtId, p.environment(), p.headAsset(),
                                p.headDimension(), p.headNavigation(),
                                p.headType(), p.headMultiplicity(),
                                p.headRole(), p.tailRole(),
                                p.tailMultiplicity(), p.tailType(),
                                p.tailNavigation(), p.tailDimension(),
                                p.tailAsset(), p.rationale())
    if (p.__class__.__name__ == 'DomainAssociationParameters'):
        return DomainAssociation(objtId, p.headDomain(), p.tailDomain(),
                                 p.phenomena(), p.connectionDomain())
    if (p.__class__.__name__ == 'GoalAssociationParameters'):
        return GoalAssociation(objtId, p.environment(), p.goal(),
                               p.goalDimension(), p.type(), p.subGoal(),
                               p.subGoalDimension(), p.alternative(),
                               p.rationale())
    if (p.__class__.__name__ == 'DependencyParameters'):
        return Dependency(objtId, p.environment(), p.depender(), p.dependee(),
                          p.dependencyType(), p.dependency(), p.rationale())
    if (p.__class__.__name__ == 'GoalParameters'):
        return Goal(objtId, p.name(), p.originator(), p.tags(),
                    p.environmentProperties())
    if (p.__class__.__name__ == 'ObstacleParameters'):
        return Obstacle(objtId, p.name(), p.originator(), p.tags(),
                        p.environmentProperties())
    if (p.__class__.__name__ == 'DomainPropertyParameters'):
        return DomainProperty(objtId, p.name(), p.description(), p.type(),
                              p.originator(), p.tags())
    if (p.__class__.__name__ == 'ThreatParameters'):
        return Threat(objtId, p.name(), p.type(), p.method(), p.tags(),
                      p.environmentProperties())
    if (p.__class__.__name__ == 'VulnerabilityParameters'):
        return Vulnerability(objtId, p.name(), p.description(), p.type(),
                             p.tags(), p.environmentProperties())
    if (p.__class__.__name__ == 'RiskParameters'):
        return Risk(objtId, p.name(), p.threat(), p.vulnerability(), p.tags(),
                    p.misuseCase())
    if (p.__class__.__name__ == 'ResponseParameters'):
        return Response(objtId, p.name(), p.risk(), p.tags(),
                        p.environmentProperties(), p.responseType())
    if (p.__class__.__name__ == 'CountermeasureParameters'):
        return Countermeasure(objtId, p.name(), p.description(), p.type(),
                              p.tags(), p.environmentProperties())
    if (p.__class__.__name__ == 'TaskParameters'):
        return Task(objtId, p.name(), p.shortCode(), p.objective(),
                    p.assumption(), p.author(), p.tags(),
                    p.environmentProperties())
    if (p.__class__.__name__ == 'UseCaseParameters'):
        return UseCase(objtId, p.name(), p.author(), p.code(), p.actors(),
                       p.description(), p.tags(), p.environmentProperties())
    if (p.__class__.__name__ == 'MisuseCaseParameters'):
        return MisuseCase(objtId, p.name(), p.environmentProperties(),
                          p.risk())
    if (p.__class__.__name__ == 'TraceParameters'):
        return Trace(p.fromObject(), p.fromName(), p.fromId(), p.toObject(),
                     p.toName(), p.toId())
    if (p.__class__.__name__ == 'DotTraceParameters'):
        return DotTrace(p.fromObject(), p.fromName(), p.toObject(), p.toName())
    if (p.__class__.__name__ == 'UpdateTraceParameters'):
        return Trace(p.fromObject(), p.fromName(), p.fromId(), p.toObject(),
                     p.toName(), p.toId())
    if (p.__class__.__name__ == 'EnvironmentParameters'):
        return Environment(objtId, p.name(), p.shortCode(), p.description(),
                           p.environments(), p.duplicateProperty(),
                           p.overridingEnvironment(), p.tensions())
    if (p.__class__.__name__ == 'RoleParameters'):
        return Role(objtId, p.name(), p.type(), p.shortCode(), p.description(),
                    p.environmentProperties())
    if (p.__class__.__name__ == 'ResponsibilityParameters'):
        return Responsibility(objtId, p.name())
    if (p.__class__.__name__ == 'DomainParameters'):
        return Domain(objtId, p.name(), p.shortCode(), p.description(),
                      p.type(), p.given(), p.domains())
    if (p.__class__.__name__ == 'ExternalDocumentParameters'):
        return ExternalDocument(objtId, p.name(), p.version(), p.date(),
                                p.authors(), p.description())
    if (p.__class__.__name__ == 'InternalDocumentParameters'):
        return InternalDocument(objtId, p.name(), p.description(), p.content(),
                                p.codes(), p.memos())
    if (p.__class__.__name__ == 'CodeParameters'):
        return Code(objtId, p.name(), p.type(), p.description(),
                    p.inclusionCriteria(), p.example())
    if (p.__class__.__name__ == 'MemoParameters'):
        return Memo(objtId, p.name(), p.description())
    if (p.__class__.__name__ == 'DocumentReferenceParameters'):
        return DocumentReference(objtId, p.name(), p.document(),
                                 p.contributor(), p.description())
    if (p.__class__.__name__ == 'ConceptReferenceParameters'):
        return ConceptReference(objtId, p.name(), p.dimension(),
                                p.objectName(), p.description())
    if (p.__class__.__name__ == 'PersonaCharacteristicParameters'):
        return PersonaCharacteristic(objtId, p.persona(), p.qualifier(),
                                     p.behaviouralVariable(),
                                     p.characteristic(), p.grounds(),
                                     p.warrant(), p.backing(), p.rebuttal())
    if (p.__class__.__name__ == 'TaskCharacteristicParameters'):
        return TaskCharacteristic(objtId, p.task(), p.qualifier(),
                                  p.characteristic(), p.grounds(), p.warrant(),
                                  p.backing(), p.rebuttal())
    if (p.__class__.__name__ == 'ImpliedProcessParameters'):
        return ImpliedProcess(objtId, p.name(), p.description(), p.persona(),
                              p.network(), p.specification(), p.channels())
    else:
        raise UnknownParameterClass(str(objtId))
Exemplo n.º 17
0
def load_tasks(task_csv):
    with open(task_csv, 'rb') as f:
        reader = csv.reader(f, delimiter=',', quotechar='"')
        next(reader, None)
        return [Task().from_list(row) for row in reader]
Exemplo n.º 18
0
def main():
    gp = GP()
    problems = []
    task_list = [Task(period=0, release=6, deadline=14, exec_time=5, blk_st=2, blk_dur=2),
                 Task(period=0, release=2, deadline=17, exec_time=7, blk_st=2, blk_dur=4),
                 Task(period=0, release=0, deadline=18, exec_time=6, blk_st=1, blk_dur=4)]
    problems.append(Problem(task_list, 20))

    task_list = [Task(period=2, deadline=2, exec_time=1),
                 Task(period=3, deadline=3, exec_time=2),
                 Task(period=7, deadline=7, exec_time=3)]
    problems.append(Problem(task_list, 42))

    task_list = [Task(period=2.5, exec_time=2, deadline=3),
                 Task(period=4,   exec_time=1, deadline=4),
                 Task(period=5,   exec_time=2, deadline=5)]
    problems.append(Problem(task_list, 20))

    task_list = [Task(period=3, exec_time=1, deadline=3),
                 Task(period=4, exec_time=1, deadline=4),
                 Task(period=5, exec_time=1, deadline=5),
                 Task(exec_time=12),
                 Task(exec_time=10)]
    problems.append(Problem(task_list, 60))

    task_list = [Task(period=5, exec_time=6, deadline=5),
                 Task(period=6, exec_time=5, deadline=5),
                 Task(period=9, exec_time=4, deadline=5),
                 Task(exec_time=24),
                 Task(exec_time=7, deadline=12)]
    problems.append(Problem(task_list, 90))
    gp.run(problems)
Exemplo n.º 19
0
    outbox = ShareableQueue()

    function = test_func

    service = Service(function,
                      inbox,
                      outbox,
                      name='TestService',
                      verbose=False)

    service.start()

    inbox.put(10.)
    inbox.put(20.)

    print outbox.get().outputs
    print outbox.get().outputs

    remote = service.remote()

    print remote(30.)

    print 'this will print an exception traceback:'
    task = Task(inputs=20, function=fail_func)
    print remote(task)

    inbox.put(KillTask)

    inbox.join()

    print 'test done!'
Exemplo n.º 20
0
# schedule.put_act("Lunch", "12:00", "13:00")
# schedule.put_act("Dinner", "17:00", "18:00")

# Take in tasks
tasks = set()

while True:
    task_name = input("Name of Task: ")
    prio = input("Priority (1-3):")
    end_date = input("Deadline (YYYY-MM-DD): ")
    estimated_time = input("Number of hours estimated to finish the task: ")
    category = input("Nature of Task: ")
    tasks.add(
        Task(task_name,
             priority=int(prio),
             end_date=end_date,
             estimated_time=float(estimated_time) * 60,
             category=category))
    next_step = input(
        "Type Y and press ENTER if done. Else type any key and press ENTER.\n")
    if next_step == "Y":
        break

# tasks.add(Task("Essay", priority=3, end_date="2018-01-20", estimated_time=10*60, category="Assignment"))
# tasks.add(Task("Programming", priority=3, end_date="2018-01-20", estimated_time=10*60, category="Assignment"))
# tasks.add(Task("Writing", priority=3, end_date="2018-01-20", estimated_time=10*60, category="Assignment"))
# tasks.add(Task("Manga", priority=3, end_date="2018-01-20", estimated_time=10*60, category="Assignment"))

training_x = []
training_y = []
Exemplo n.º 21
0
        # Save Best permutation
        BestPermutation = copy.deepcopy(Result)
        NbOfTasks = NbOfTasks - 1

    return Cmax


Tasks = []
NbOfTasks = 0
NbOfMachines = 0

# Reading from file and storing data in the list of NsetTasks
file = open("NEH2.DAT", "r")

if file.readable():
    linecount = 0
    column = csv.reader(file, delimiter=' ')
    for row in column:
        if linecount == 0:
            NbOfTasks = row[0]
            NbOfMachines = row[1]
        else:
            # Filling a list with Task objects in format Task(TimeOfExecution)
            Tasks.append(Task(row, linecount))
        linecount += 1
    file.close()

SortedTasks = sorted(Tasks, key=lambda x: x.SumOfTimes, reverse=True)

print(NEH(SortedTasks))
Exemplo n.º 22
0
 def __init__(self):
     self.task = Task()
Exemplo n.º 23
0
def add_task(flags):
    if flags  == 'a':
        name = input(Fore.GREEN + "Enter the task's name: " + Fore.WHITE)
    else: name = flags
    tasklist.append(Task(name))
Exemplo n.º 24
0
    for i in range(1000):
        num += i
    return num


def commonTask():
    num = 0
    for i in range(1000):
        num += i
    print(num)


# 实例化一个线程池
pool = ThreadPool()

# 先将线程池中所有线程启动,一开始没有任务,所以所有线程启动之后立即进入等待状态
pool.start()

# 添加100000个任务给线程池,里面的线程会自动获取任务执行
print("开始执行任务")
task_list = []
for i in range(100000):
    task = Task(commonTask)
    # task = AsyncTask(asyncTask)
    pool.put_task(task)
    task_list.append(task)

# 在此处可以进行一些主线程的逻辑处理,在主线程处理自己的逻辑的时候,线程池中的线程也在异步处理任务队列中的任务。

for task in task_list:
    print(task.get_result())
Exemplo n.º 25
0
        for j in range(0, len(tasks)):
            # If task is within this combination
            if i & (1 << j):
                # Bit operator ~ means NOT
                # Check OPT for combination without this task and add punishment
                tmp = OptimalPunishments[i & (~(1 << j))] + punishment(
                    tasks[j], EndOfExecution)
                # If it's smallest, then it is optimal
                OptimalPunishments[i] = min(OptimalPunishments[i], tmp)

    # return Optimal value for execution of all tasks
    return OptimalPunishments[NumberOfCombinations - 1]


# It's a list for unordered tasks (not ready to be executed)
Tasks = []

# Reeading from file and storing data in the list of NsetTasks
file = open("WiTi1.txt", "r")

if file.readable():
    n = file.readline()
    column = csv.reader(file, delimiter=' ')
    for row in column:
        # Filling a list with Task objects in format Task(p,w,d)
        Tasks.append(Task(row[0], row[1], row[2]))
    file.close()

result = WiTi(Tasks)
print(result)
Exemplo n.º 26
0
import sys
from os import getcwd
from os.path import join, abspath

current_folder = getcwd()
source_folder = abspath(join(current_folder, '..'))
sys.path.append(source_folder)

from Task import Task

insert_document_service_uri = 'http://localhost:3020/api/insertFromPipe'
send_task_service_uri = 'http://localhost:3020/api/sendPipeTask'
input_test_document_path = abspath(
    join(current_folder, '..', '..', 'output', 'p15350224'))
t = Task(insert_document_service_uri, send_task_service_uri)

d = t.create_document(input_test_document_path)
saved_document = t.insert_document(d)

if saved_document:
    task_result = t.send_task(saved_document['_id'], saved_document['name'],
                              'uic', 'uic')
    if task_result:
        print "Great!"
    else:
        print "Too bad"

#print(str(res))
    def _zmq_send(self, msg):
        self.mq_socket.send_json(msg)

    def _rabbitmq_send(self, msg):
        self.mq_socket.basic_publish(
            exchange='',
            routing_key=self.q_name,
            body=json.dumps(msg),
            properties=pika.BasicProperties(
                delivery_mode=2,  # make message persistent
            ))

    def new_tid(self):
        self.tid += 1
        return self.tid


if __name__ == "__main__":

    tasks = [
        Task(function="example_compute.compute_flops",
             params=[1, 2048],
             resources=1) for task in range(TOTAL_TASKS)
    ]

    obj = Dispatcher()
    tasks.sort(key=attrgetter('resources'))
    for task in tasks:
        obj.send(task)
Exemplo n.º 28
0
 def __load_task_from_line(self, index: int, line: str):
     filtered_line_data = filter(lambda element: len(element) > 0, line.strip().split())
     data = list(map(lambda element: int(element), filtered_line_data))
     self.tasks.append(Task(index, data[0], data[1], data[2]))
Exemplo n.º 29
0
        self.args = args
        if args.yaml:
            with open(args.yaml) as f:
                data = yaml.load(f, Loader=yaml.Loader)
            # Reset mq from yaml
            if self.mq != data['mq']:
                self.__init__(data['mq'])
            self.task = data['task']
            return data['task']
        return None


if __name__ == "__main__":
    tasks = [
        Task(function="example_compute.compute_flops",
             params=[1, 2048],
             resources=1),
        Task(function="example_compute.compute_flops",
             params=[1, 4096],
             resources=2),
        Task(function="example_compute.compute_flops",
             params=[1, 8192],
             resources=4),
        Task(function="example_compute.compute_flops",
             params=[1, 8192],
             resources=8)
    ]

    obj = Dispatcher()
    # Overriden by cmd params
    tasks_from_yaml = obj.set_argument()
Exemplo n.º 30
0
    #print('The task called "{}" takes {} days'.format(my_task.task_name, my_task.get_duration()))
    #print('You need to complete {} {} per day'.format(my_task.get_required_rate(), my_task.units_name))

    # Testing Task class with user input
    input_task_name = input('Enter task name: ')
    input_units_name = input('Enter name of units (plural): ')
    input_units_count = int(input('Enter number of units: '))

    input_starty = int(input('Enter start year: '))
    input_startm = int(input('Enter start month: '))
    input_startd = int(input('Enter start day: '))

    input_endy = int(input('Enter end year: '))
    input_endm = int(input('Enter end month: '))
    input_endd = int(input('Enter end day: '))

    my_task = Task( input_task_name,
                    input_units_name,
                    input_units_count,
                    input_starty,
                    input_startm,
                    input_startd,
                    input_endy,
                    input_endm,
                    input_endd,)
    print('The task called "{}" takes {} days'.format(my_task.task_name, my_task.get_duration()))
    print('You need to complete {} {} per day'.format(my_task.get_required_rate(), my_task.units_name))

    # Testing save_to_file method
    my_task.save_to_file()