Exemplo n.º 1
0
 def _set_param_config_depend(target_arg: argument.Argument, value: float,
                              d_func: Callable):
     if d_func is None:
         print("Depending function (d_func) is required.")
         return
     target_arg.set_status(argument.ArgStatus.DEPEND)
     target_arg.set_depend_function(d_func)
     if value is not None:
         print("Value is ignored.")
Exemplo n.º 2
0
 def from_file(self, path):
     if os.path.isfile(path+".sqlite"):
         kb = Argument.from_database(path+".sqlite")  # Bit of bad factoring.
         print("Labelled DB detected. Using that.")
     else:
         kb = Argument.from_file(path)
         print("Loaded into DB, Labelling.", time.process_time())
         Labelling.grounded(kb)
     return Game(kb)
Exemplo n.º 3
0
 def from_tokens(cls, pred_token, neg, subj_token, obj_token,
                 pobj_token_list):
     pred = Predicate.from_token(pred_token, neg=neg)
     subj = Argument.from_token(subj_token) \
         if subj_token is not None else None
     obj = Argument.from_token(obj_token) if obj_token is not None else None
     pobj_list = [(prep, Argument.from_token(pobj))
                  for prep, pobj in pobj_token_list]
     return cls(pred, subj, obj, pobj_list)
Exemplo n.º 4
0
def test_arg_modifier(args: Argument, user_args):
    args.CUDA_VISIBLE_DEVICES = -1
    args.OMP_NUM_THREADS = 1
    args.num_agent = user_args.num_agent
    args.seed = user_args.seed
    args.model_type = user_args.model_type
    args.beta = user_args.beta
    if user_args.num_agent == 4:
        args.bsize = 20
        args.num_history = 5
        args.num_rollout = 15
    return args
Exemplo n.º 5
0
def generate_arguments(num_practical, num_epistemic):
    """ Generate the Argument pool set. """

    args = set()

    # Add practical arguments (prefix argument text with `P')
    for idx_arg in range(num_practical):
        text = "P" + str(idx_arg)
        args.add(Argument(PEtype='practical', text=text))

    # Add epistemic arguments (prefix argument text with `E')
    for idx_arg in range(num_epistemic):
        text = "E" + str(idx_arg)
        args.add(Argument(PEtype='epistemic', text=text))

    return args
Exemplo n.º 6
0
def get_arguments(argumentList, variableDict):
    # TODO: Try/Catch for this section
    argumentArray = []
    XMLNamespace = re.match('\{.*\}', argumentList.tag).group(0)
    for argumentNode in argumentList.findall(XMLNamespace + 'argument'):
        name = argumentNode.find(XMLNamespace + 'name')
        if name is not None:
            name = name.text

        direction = argumentNode.find(XMLNamespace + 'direction')
        if direction is not None:
            direction = direction.text

        relatedStateVariable = argumentNode.find(XMLNamespace +
                                                 'relatedStateVariable')
        if relatedStateVariable is not None:
            relatedStateVariable = relatedStateVariable.text

        # If we already know what that variable is, we can grab the datatype and the default value!
        if relatedStateVariable in variableDict:
            relatedStateVariable = variableDict[relatedStateVariable]
        else:
            # Otherwise put them both down as unknown
            relatedStateVariable = Variable(relatedStateVariable, "?", "?")
        argumentArray.append(Argument(name, direction, relatedStateVariable))
    return argumentArray
Exemplo n.º 7
0
    def from_tokens(cls,
                    pred_token,
                    subj_token,
                    obj_token,
                    pobj_token_list,
                    neg=False,
                    prt=''):
        pred = Predicate.from_token(pred_token, neg=neg, prt=prt)
        subj = None
        if subj_token is not None:
            subj = Argument.from_token(subj_token)
        obj = None
        if obj_token is not None:
            obj = Argument.from_token(obj_token)
        pobj_list = [(prep, Argument.from_token(pobj_token))
                     for prep, pobj_token in pobj_token_list]

        return cls(pred, subj, obj, pobj_list)
Exemplo n.º 8
0
def make_single_argument(arg_tuple, toprule):
    """given a set of possible ways to create an argument, creates an argument from one of them. Note that there is a modification over the standard def - a rule is only allowed to be used once in an argument."""
    subargs = set([i for i in arg_tuple])
    for i in arg_tuple:
        subargs = subargs.union(i.subarguments)
    if len(
            set(filter(lambda x: x.toprule == toprule, subargs))
    ) > 0:  #remove this bit to allow a rule to be used more than once in an argument.
        return set()
    return Argument(toprule, subargs)
Exemplo n.º 9
0
    def make_relations(self, i, arguments):

        reason_i = arguments[i].reason
        tok_i = arguments[i].reason
        relations = []

        if reason_i is not None:
            for r in reason_i:

                rel = ArgumentRelation()
                rel.add_argument(arguments[i])
                rel.set_connection()

                if REASON_ID_PATTERN.match(r):
                    reasons = r.split("_")
                    new_argument = Argument()
                    new_argument.tokens = []
                    new_argument.text = ""
                    new_argument.posTagging = []

                    for c in reasons:
                        new_argument.text = " " + propositions[int(c)].tokens
                        new_argument.tokens.extend(propositions[int(c)].tokens)
                        new_argument.posTagging.extend(propositions[int(c)].posTagging)

                    rel.add_argument(new_argument)

                elif NUM_PATTERN.match(r):
                    rel.add_argument(propositions[int(r)])

                relations.append(rel)
        else:
            for p in propositions:
                if p != i:
                   rel = ArgumentRelation()
                   rel.add_argument(propositions[i])
                   rel.add_argument(propostions[int(p)])
                   rel.unset_connection()

                   relations.append(rel)

        return relations
Exemplo n.º 10
0
    def str2predicate(string_repr):
        lpar_index = string_repr.index('(')
        rpar_index = string_repr.index(')')
        vars_ = string_repr[lpar_index + 1:rpar_index].split(',')

        variables = []
        for var in vars_:
            if var[0] == '"' and var[-1] == '"':
                variables.append(Argument(var[1:-1], True, True, None))
            else:
                variables.append(Argument(var, False, True, None))

        if string_repr[0] == '~':
            name = string_repr[1:lpar_index]
            isneg = True
        else:
            name = string_repr[:lpar_index]
            isneg = False

        return PredicateTemplate(name, variables, isneg, True)
Exemplo n.º 11
0
 def from_text(cls, text):
     parts = [p for p in re.split(' :(?:SUBJ|OBJ|POBJ): ', text)]
     if len(parts) < 3:
         raise ParseEventError(
             'expected at least 3 parts, separated by ::, '
             'got {}: {}'.format(len(parts), text))
     pred = Predicate.from_text(parts[0])
     subj = None
     if parts[1] != 'NONE':
         subj = Argument.from_text(parts[1])
     obj = None
     if parts[2] != 'NONE':
         obj = Argument.from_text(parts[2])
     pobj_list = []
     if len(parts) > 3:
         for part in parts[3:]:
             prep, pobj = part.split(' : ')
             if prep != '':
                 pobj_list.append((prep, Argument.from_text(pobj)))
     return cls(pred, subj, obj, pobj_list)
Exemplo n.º 12
0
def generate_arguments(p, ruleset, seen):
    """Given a ruleset and a proposition, uses backwards chaining to create all arguments for the proposition."""
    arguments = set()
    if p in seen:
        return set()
    valid_rules = filter(lambda x: x.con == p, ruleset)
    for r in valid_rules:
        added = False
        args_for_pre = {}
        for pre in r.pre:
            args_for_pre[pre] = generate_arguments(pre, ruleset,
                                                   seen.union([p]))

        prod = itertools.product(*[a for (_, a) in args_for_pre.items()])
        for sa in prod:
            added = True
            a = Argument(r, set(sa))
            for sub in sa:
                a.subarguments = a.subarguments.union(sub.subarguments)
            arguments.add(a)
    return arguments
Exemplo n.º 13
0
    def from_text(cls, text):
        # TODO: change OBJ to DOBJ to avoid confusion
        parts = [p for p in re.split(' :(?:SUBJ|OBJ|POBJ): ', text)]
        assert len(parts) >= 3, \
            'expected at least 3 parts, separated by :(SUBJ|OBJ|POBJ):, ' \
            'found {}'.format(len(parts))

        pred = Predicate.from_text(parts[0])
        subj = None
        if parts[1] != 'NONE':
            subj = Argument.from_text(parts[1])
        obj = None
        if parts[2] != 'NONE':
            obj = Argument.from_text(parts[2])
        pobj_list = []
        if len(parts) > 3:
            for part in parts[3:]:
                prep, pobj = part.split(' : ')
                if prep != '':
                    pobj_list.append((prep, Argument.from_text(pobj)))

        return cls(pred, subj, obj, pobj_list)
Exemplo n.º 14
0
 def up_complete_update(self):
     counter = 0
     while True:
         counter += 1
         legally_IN = set([a for a in self.UNDEC if self.isLegallyIN(a)])
         Argument.set_all_labels(legally_IN, "In", counter)
         legally_OUT = set([a for a in self.UNDEC if self.isLegallyOUT(a)])
         Argument.set_all_labels(legally_OUT, "Out", counter)
         if not legally_IN and not legally_OUT:
             for a in self.UNDEC:
                 if a not in self.steps:
                     self.steps[a] = counter
             return self
         self.IN |= legally_IN
         self.OUT |= legally_OUT
         self.UNDEC -= legally_IN
         self.UNDEC -= legally_OUT
         # assign the number of the step to the updated arguments
         this_step = legally_IN | legally_OUT
         for a in this_step:
             if a not in self.steps:
                 self.steps[a] = counter
Exemplo n.º 15
0
def command_builder(input_args):
    (ip, transport_layer_protocol, time_per_test, reversed_transmission_direction, store_in_db,
     buffer_length, window_size, maximum_segment_size) = input_args

    if reversed_transmission_direction:
        transmission_direction_arg = reversed_transmission_direction_flag
    else:
        transmission_direction_arg = ''

    command_prefix = [command, device_type, ip, time_per_test_flag, str(time_per_test), transmission_direction_arg]

    if transport_layer_protocol == 'udp':
        opt_args = [Argument(name='buffer_length', flag=udp_args[0], min_val=udp_args_domains[0][0],
                         max_val=udp_args_domains[0][1], get_next_value_method='multiply', default_val=udp_args_default_values[0])]
        command_prefix+=udp_args_extra

    elif transport_layer_protocol == 'tcp':
        opt_args = []
        if window_size:
            opt_args.append(Argument(name='window_size', flag=tcp_args[1], min_val=tcp_args_domains[1][0],
                     max_val=tcp_args_domains[1][1], get_next_value_method='multiply'))
        if buffer_length:
         opt_args.append(Argument(name='buffer_length', flag=tcp_args[0], min_val=tcp_args_domains[0][0],
                     max_val=tcp_args_domains[0][1], get_next_value_method='multiply', default_val=tcp_args_default_values[0]))
        if maximum_segment_size:
            opt_args.append(Argument(name='maximum_segment_size', flag=tcp_args[2], min_val=tcp_args_domains[2][0],
                     max_val=tcp_args_domains[2][1], get_next_value_method='add', default_val=tcp_args_default_values[2]))
        command_prefix += tcp_args_extra

        if len(opt_args) == 0:
            print('Impossible to optimize throughput without any parameters.')
            exit(-1)

    args = (time_per_test, transport_layer_protocol, reversed_transmission_direction, store_in_db)

    return command_prefix, opt_args, args
Exemplo n.º 16
0
    def process_argument(self, arg):
        """
        Given a argument as a dictionary type, it appends the pairs of reasons  
        to the list of data_list. Each pair is a Data object.
        """

        # iterating through propositions
        arg_dict = {}
        for p in arg:
            id_p = p["id"]
            text_p = p["text"]
            reason_p = p["reasons"]

            arg_dict[id_p] = Argument(text_p, reason_p)
            arg_dict.process()

        return arg_dict
Exemplo n.º 17
0
def eval_models(args: Argument):
    args.mode = 'test'
    dc, lc, tc, model_dir = get_config_list(args)

    modes = ['test']
    dataloader = {
        'test':
        get_trajectory_data_loader(dc,
                                   test=True,
                                   batch_size=args.bsize,
                                   num_workers=args.num_workers,
                                   shuffle=True)
    }
    run_every = {'test': 1}
    gn_wrapper = fetch_model_iterator(lc, args)
    trainer = train.Trainer(gn_wrapper, modes, dataloader, run_every, tc)
    output = trainer.eval(dataloader['test'])
    return trainer.num_iter, output
Exemplo n.º 18
0
    def next_move(self):
        "Bot plays the move"

        if not self.game.last_argument:
            proposed_arg = Argument.get_random()
            return "has_to_be", proposed_arg  # Proponents first move
        possible_args = self.game.last_argument.minus()
        args = [a for a in possible_args if (a not in self.game.complete_arguments and
                                             a not in self.game.arguments and
                                             a.label == "In")]
        if not args:
            args = [a for a in possible_args if (a not in self.game.complete_arguments and
                                                 a not in self.game.arguments)]
        if not args:  # I hate python
            return None, None
        args.sort(key=lambda arg: arg.step if arg.step else 1000)
        proposed_arg = args[0]
        return "has_to_be", proposed_arg
Exemplo n.º 19
0
def test(model, dataset, path = None, beam = False, beam_size = 4, k = 6, test_mode = True) :
    if path != None : model.load_state_dict(torch.load(path))
    args = Argument()
    model.eval()
    loader = dataset.test_iter
    preds = []
    targets = []
    loss = 0
    example_num = 0
    with torch.no_grad() :
        for idx, batch in enumerate(tqdm(loader, position = 0)) :
            if idx == 0 : continue
            if beam :
                beam = model.beam_generate(batch, beam_size, k)
                beam.sort()
                gen = beam.finished_nodes[0].words
                out = torch.nn.functional.one_hot(torch.Tensor(gen).long(), num_classes = args.output_vocab_size).unsqueeze(0)
                out = out[1:, :].unsqueeze(0) #(1, seq_len, num_classes)
            else :
                out = model(batch)
                out = out [:, 1: , :]
                gen = out[0].argmax(dim = 1)
                
            target = batch.target[:, 1:]
            sen = "GEN\n" + create_sentence(dataset, gen) + "\n"
            tgt = "GOLD\n" + create_sentence(dataset, target[0]) + "\n"
            preds.append(sen)
            targets.append(tgt)
          
            if idx % 100 == 1 :
                print(sen)
                print(tgt)
                
            if test_mode :
                print(sen)
                print(tgt)
                if idx == 10 : break

        result = {"GOLD" : targets, "GEN" : preds}
        if path == None : path = "./outputs/test_result_" + "beam_size-" + str(beam_size) + "_k-" + str(k) + ".tsv" if beam else "./outputs/test_result.tsv"
        pd.DataFrame(result, columns = ["GOLD", "GEN"]).to_csv(path, sep = "\t", mode = "w")

    return preds, targets
Exemplo n.º 20
0
def train_model(args: Argument):
    args.mode = 'train'
    dc, lc, tc, _ = get_config_list(args)
    gn_wrapper = fetch_model_iterator(lc, args)
    modes = ['train', 'test']
    dataloader = {
        m: get_trajectory_data_loader(dc,
                                      test=m == 'train',
                                      batch_size=args.bsize,
                                      num_workers=args.num_workers,
                                      shuffle=True)
        for m in modes
    }
    run_every = {'train': 1, 'test': args.test_every}
    trainer = train.Trainer(gn_wrapper, modes, dataloader, run_every, tc)

    train_winding = False
    train_trajectory = True

    trainer.train(train_winding, train_trajectory)
    trainer.save(train_winding, train_trajectory)
Exemplo n.º 21
0
def merge(
    path,
    special,
    verbose,
    silent,
    name_template,
    title,
    video_codec,
    audio_codec,
    save_path,
    additional_args,
    only_compile,
    parse_name,
):
    container_list, attach_list = __scan(path, special, verbose, silent)
    command_list = []

    for i, container in enumerate(container_list, start=1):
        meta_container = MetaContainer(container,
                                       attach_list,
                                       name_template,
                                       title,
                                       parse_name=parse_name)
        command = Argument.compile_mkv(meta_container,
                                       video_codec=video_codec,
                                       audio_codec=audio_codec,
                                       additional_args=additional_args,
                                       save_path=save_path)
        command_list.append(command)
        if not silent:
            click.echo("Container №{} - {}".format(i, meta_container.name))
            if only_compile:
                click.echo("Command: ")
                click.echo(command)
            if verbose:
                click.echo("Streams: ")
                for stream in meta_container.stream_list:
                    print(stream)
        if not only_compile:
            run(command)
Exemplo n.º 22
0
    def make_relations(self, i, arguments):

        reason_i = arguments[i].reason
        tok_i = arguments[i].reason
        relations = []

        if reason_i is not None:
            for r in reason_i:

                rel = ArgumentRelation()
                rel.add_argument(arguments[i])
                rel.set_connection()

                if REASON_ID_PATTERN.match(r):
                    reasons = r.split("_")
                    new_argument = Argument()
                    new_argument.tokens = []
                    new_argument.text = ""
                    new_argument.posTagging = []

                    for c in reasons:
                        new_argument.text = " " + propositions[int(c)].tokens
                        new_argument.tokens.extend(propositions[int(c)].tokens)
                        new_argument.posTagging.extend(
                            propositions[int(c)].posTagging)

                    rel.add_argument(new_argument)

                elif NUM_PATTERN.match(r):
                    rel.add_argument(propositions[int(r)])

                relations.append(rel)
        else:
            for p in propositions:
                if p != i:
                    rel = ArgumentRelation()
                    rel.add_argument(propositions[i])
                    rel.add_argument(propostions[int(p)])
                    rel.unset_connection()

                    relations.append(rel)

        return relations
Exemplo n.º 23
0
from data import DataHelper
from model import AutoRec
from argument import Argument
import tensorflow as tf
import math
import time

print("begin!")
args = Argument()

tf.set_random_seed(args.random_seed)

data_name = 'ml-1m'

data_path = "./%s" % data_name

datahelper = DataHelper()
datahelper.read(data_path)

train_R, train_mask_R, test_R, test_mask_R = datahelper.split(args.ratio)
num_users = datahelper.get_num_user()
num_items = datahelper.get_num_item()

for _ in range(args.repeat_number):
    tf.reset_default_graph()

    with tf.Session() as sess:
        autoRec = AutoRec(sess, args, num_users, num_items, train_R,
                          train_mask_R, test_R, test_mask_R)
        autoRec.run()
Exemplo n.º 24
0
 def from_af(cls, arguments, attack_relations):
     kb = Argument.from_af(arguments, attack_relations)
     Labelling.grounded(kb)
     return Game(kb)
Exemplo n.º 25
0
 def addArg(self, arg, question=None):
     self.args.append(arg)
     if question:
         self.questions[question] = self.questions.get(
             question, []) + [Argument(arg)]
Exemplo n.º 26
0
 def concede(self, argument_name):
     argument = Argument.find(argument_name)
     return self.game.concede(argument)
Exemplo n.º 27
0
 def retract(self, argument_name):
     argument = Argument.find(argument_name)
     return self.game.retract(argument)
Exemplo n.º 28
0
    def _process_parsed_arg(self, articles, which='test'):
        arg_feat_name = FILE_PATH + '/../tmp/arg.feat'
        arg_feat_file = codecs.open(arg_feat_name, 'w', 'utf-8')
        arg_checked = []
        argParser = Argument()
        for art in articles:
            for rel in art.exp_relations:
                arg_checked.append(argParser.print_features(rel, which, arg_feat_file))
        arg_feat_file.close()
        arg_pred_name = FILE_PATH + '/../tmp/arg.pred'
        Corpus.test_with_opennlp(arg_feat_name, argParser.model_file, arg_pred_name)
        arg_res = [l.strip().split()[-1] for l in codecs.open(arg_pred_name, 'r', 'utf-8')]

        tmp_feat_name = FILE_PATH+'/../tmp/arg.prev.feat'
        tmp_file = codecs.open(tmp_feat_name, 'w', 'utf-8')
        for art in articles:
            for rel in art.exp_relations:
                conn_sid = rel.conn_leaves[0].goto_tree().sent_id
                if conn_sid > 0:
                    prev_tree = rel.article.sentences[conn_sid-1].tree
                    if not prev_tree.is_null():
                        prev_root = prev_tree.root
                        argParser.print_features(rel, which, tmp_file, prev_root)
        tmp_file.close()
        tmp_pred_name = FILE_PATH + '/../tmp/arg.prev.pred'
        Corpus.test_with_opennlp(tmp_feat_name, argParser.model_file, tmp_pred_name)
        arg_prev_res = [l.strip().split()[-1] for l in codecs.open(tmp_pred_name, 'r', 'utf-8')]

        rid = 0
        s = 0
        index = 0
        for art in articles:
            for rel in art.exp_relations:
                args = arg_checked[rid]
                labels = arg_res[s:s+len(args)]
                rid += 1
                s += len(args)
                merge_result = argParser.merge(rel, args, labels)
                rel.arg1_leaves = merge_result['arg1'] if 'arg1' in merge_result else []
                conn_sid = args[0].goto_tree().sent_id

                # if current sentence couldn't resovle any arg1 leaves, we
                # consider previous root
                if len(rel.arg1_leaves) == 0 and conn_sid > 0 and arg_prev_res[index] == 'arg1':
                    rel.arg1_leaves = rel.article.sentences[conn_sid-1].leaves

                if conn_sid > 0:
                    index += 1

                rel.arg1_leaves = self.remove_leading_tailing_punc(rel.arg1_leaves)
                rel.arg1_addr = [n.leaf_id for n in rel.arg1_leaves]
                rel.arg1_sid = rel.arg1_leaves[-1].goto_tree().sent_id if len(rel.arg1_leaves) > 0 else -1
                rel.arg1_text = ' '.join(n.value for n in rel.arg1_leaves)
                rel.arg2_leaves = merge_result['arg2'] if 'arg2' in merge_result else []
                rel.arg2_leaves = self.remove_leading_tailing_punc(rel.arg2_leaves)
                rel.arg2_addr = [n.leaf_id for n in rel.arg2_leaves]
                rel.arg2_sid = rel.arg2_leaves[0].goto_tree().sent_id if len(rel.arg2_leaves) > 0 else -1
                rel.arg2_text = ' '.join(n.value for n in rel.arg2_leaves)

        assert len(arg_prev_res) == index, 'arg prev size not match'
        assert len(arg_res) == s, 'arg candidate size not match'
Exemplo n.º 29
0
    def parse_yaml_rules(self, nodelist, base_class=None):
        abstract_nodes = []
        nodes = []

        for node in nodelist:
            # name of the ast class and it's properties as dictionary
            class_name, properties = next(iter(node.items()))

            # no need to process empty nodes
            if properties is None:
                continue

            args = Argument()
            args.url = properties.get('url', None)
            args.class_name = class_name
            args.brief = properties.get('brief', '')
            args.description = properties.get('description', '')

            # yaml file has abstract classes and their subclasses with children as a property
            if 'children' in properties:
                # recursively parse all sub-classes of current abstract class
                child_abstract_nodes, child_nodes = self.parse_yaml_rules(
                    properties['children'], class_name)

                # append all parsed subclasses
                abstract_nodes.extend(child_abstract_nodes)
                nodes.extend(child_nodes)

                # classes like Ast which don't have base class
                # are not added (we print Ast class separately)
                if base_class is not None:
                    args.base_class = base_class
                    node = Node(args)
                    abstract_nodes.append(node)
                    nodes.insert(0, node)
                    if self.debug:
                        print('Abstract {}'.format(node))
            else:
                args.base_class = base_class if base_class else 'Ast'

                # check if we need token for the node
                # todo : we will have token for every node
                args.has_token = LanguageParser.is_token(class_name)

                # name of the node while printing back to NMODL
                args.nmodl_name = properties[
                    'nmodl'] if 'nmodl' in properties else None

                # create tree node and add to the list
                node = Node(args)
                nodes.append(node)

                if self.debug:
                    print('Class {}'.format(node))

                # now process all children specification
                if 'members' in properties:
                    for child in properties['members']:
                        args = self.parse_child_rule(child)
                        node.add_child(args)

        # update the abstract nodes
        for absnode in abstract_nodes:
            for node in nodes:
                if absnode.class_name == node.class_name:
                    node.is_abstract = True
                    break

        return abstract_nodes, nodes
Exemplo n.º 30
0
        except Exception as err:
            Verbose.print_ln("Something went bad \nError: ", err)

        if first_run or db_updated:
            try:
                db_df.to_pickle('result.pkl')
            except Exception as err:
                Verbose.print_ln("Was not able to create new pkl file, Error:", err)
            self.create_or_update_view()
            Verbose.print_ln("update the view and the pkl")
        else:
            Verbose.print_ln('No changes, database table status remained same.')

    """ Documentation: create_or_update_view
       Description:
           a method used to create new view "vw_AllSurveyDataPython" and store all survey data we got from procedure object.
    """
    def create_or_update_view(self):
        procedure = Procedure(self.db)
        final_query = ' CREATE OR ALTER VIEW vw_AllSurveyData AS ' + procedure.get_all_survey_data()
        self.db.create(final_query)
        Verbose.print_ln("View updated.")


if __name__ == '__main__':
    args = Argument.get()
    Verbose.show_messages(args.verbose)

    starter = Starter()
    starter.main()
Exemplo n.º 31
0
 def has_to_be(self, argument_name):
     argument = Argument.find(argument_name)
     return self.game.has_to_be(argument)
Exemplo n.º 32
0
import json
from argument import Argument
from jenkinsutils import Job
from database import DBSession, ColumnNotFoundException
from converters import Converter
from retry import retry

configuration = dict(json.loads(open('configuration.json').read()))

arguments_dict = dict(json.loads(open('arguments.json').read()))

argument_objects = []
for argument_name, argument_information in arguments_dict.items():
    argument_objects.append(
        Argument(name=argument_name, **argument_information))

parsed_args, unparsed_remainder_args = Argument.ARGUMENTS.parse_known_args()
remainder_args = Argument.parse_unknown_args(
    remainder_list=unparsed_remainder_args)

db = DBSession(user=configuration['databaseUser'],
               password=configuration['databasePass'],
               host=configuration['hostName'],
               port=configuration['port'],
               database=configuration['databaseName'])

if parsed_args.create_table_only:
    job = Job(configuration['jobName'])
    db.execute_query(query=job.create_table_query())

Exemplo n.º 33
0
from argument import Argument

if __name__ == '__main__':
	import sys

	if len(sys.argv) != 2:
		sys.exit(1)

	with open(sys.argv[1]) as f:
		print Argument(f.read()).compile()

Exemplo n.º 34
0
trees[(env, ceco)] = lambda p: 'Environment'
trees[(time, ceco)] = trees[(time, fit)] = lambda p: 'Time'
trees[(ceco, com)] = trees[(env, com)] = trees[(time,
                                                com)] = lambda p: 'Comfort'
trees[(peco, ceco)] = lambda p: 'Personal Economy'
trees[(env, time)] = lambda p: 'Environment' if p.A <= 3.75 else 'Time'
trees[(
    peco, saf
)] = lambda p: 'Personal Economy' if p.O <= 4.25 and P.A > 4.75 else 'Safety'
trees[(saf, hea)] = lambda p: 'Safety' if p.C <= 4.75 else 'Health'
trees[(
    com, fit
)] = lambda p: 'Fitness' if p.N > 3.75 and p.O > 4.25 and p.O <= 6.25 and p.C <= 6.25 else 'Comfort'
trees[(peco, com)] = pecocom

init = Argument('init', 'Why don\'t you cycle from home to work?', 'init')
g2 = Argument(
    'g2',
    'We won\'t be able to persuade you to cycle to work. However, do you have any objection to the city investing in initiatives to increase cycling?',
    'g2')
arg1 = Argument('arg1', 'people cycle 8 miles on average to go to work', fit,
                time)
arg2 = Argument('arg2', 'pollution is everyone\'s problem', env)
arg3 = Argument('arg3', 'I live further than 8 miles away', time)
arg4 = Argument('arg4', 'I am not fit enough', fit)
# arg4 = Argument('arg4', 'I am not fit enough because of my weight', fit)
arg5 = Argument(
    'arg5',
    'many companies now have secure bike parking for the employees not to waste time on looking for one',
    time)
# arg6 = Argument('arg6', 'My home is too small to store a bike', peco)
Exemplo n.º 35
0
# test
# unit test
class Agent(object):
    def __init__(self, name):
        self.name = name

    def open(self, arg):
        print("open")

    def close(self, arg):
        print("close")

    def __repr__(self):
        return self.name


master = Agent("a master")
slave = Agent("a slave")

# create arg
arg = Argument()
arg.insert("sharability", "inner_sharable")
# create action item
ai = ActionItem()
ai.set_owner(slave)
ai.set_action("open")
ai.do()
# create a chain-action
chain_action0 = ChainAction(master, "Monday", ai, arg)

print(chain_action0)
Exemplo n.º 36
0
    def parse_child_rule(self, child):
        """parse child specification and return argument as properties

        Child specification has additional option like list, optional,
        getName method etc.
        """
        # there is only one key and it has one value
        varname, properties = next(iter(child.items()))

        args = Argument()
        args.varname = varname

        # type i.e. class of the variable
        args.class_name = properties['type']

        if self.debug:
            print('Child {}, {}'.format(args.varname, args.class_name))

        # if there is add method for member in the class
        if 'add' in properties:
            args.add_method = properties['add']

        # if variable is an optional member
        if 'optional' in properties:
            args.is_optional = properties['optional']

        # if variable is vector, the separator to use while
        # printing back to nmodl
        if 'separator' in properties:
            args.separator = properties['separator']

        # if variable is public member
        if 'public' in properties:
            args.is_public = properties['public']

        # if variable if of vector type
        if 'vector' in properties:
            args.is_vector = properties['vector']

        # if get_node_name method required
        if 'node_name' in properties:
            args.get_node_name = properties['node_name']

        # brief description of member variable
        if 'brief' in properties:
            args.brief = properties['brief']

        # description of member variable
        if 'description' in properties:
            args.description = properties['description']

        # if getter method required
        if 'getter' in properties:
            if 'name' in properties['getter']:
                args.getter_method = properties['getter']['name']
            if 'override' in properties['getter']:
                args.getter_override = properties['getter']['override']

        # if there is nmodl name
        if 'nmodl' in properties:
            args.nmodl_name = properties['nmodl']

        # prefix while printing back to NMODL
        if 'prefix' in properties:
            args.prefix = properties['prefix']['value']

            # if prefix is compulsory to print in NMODL then make suffix empty
            if 'force' in properties['prefix']:
                if properties['prefix']['force']:
                    args.force_prefix = args.prefix
                    args.prefix = ""

        # suffix while printing back to NMODL
        if 'suffix' in properties:
            args.suffix = properties['suffix']['value']

            # if suffix is compulsory to print in NMODL then make suffix empty
            if 'force' in properties['suffix']:
                if properties['suffix']['force']:
                    args.force_suffix = args.suffix
                    args.suffix = ""

        return args
Exemplo n.º 37
0
 def __init__(self):
     self.argument = Argument({})
Exemplo n.º 38
0
 def _set_param_config_free_or_freeze(target_arg: argument.Argument,
                                      value: float, d_func: Callable):
     if value is not None:
         target_arg.set_value(value)
     if d_func is not None:
         print("Depending function is ignored.")
Exemplo n.º 39
0
 def __init__(self):
     args = Argument.get()
     self.db = Connection(args.driver, args.server, args.database, args.userid, args.password)