Beispiel #1
0
def trigger(pipeline_name):
    get_repo_url = "{}registries/{}/{}/repositories/{}".format(settings.API_URL, settings.CLAAS_NAMESPACE,
                                                               settings.PRIVATE_REGISTRY, get_repo().get("service_repo", "houchao-test"))
    r = requests.get(get_repo_url, headers=headers)
    if r.status_code != 200:
        return {"success": False,
                "total": "get repositories return code error: {}, error text:{}".format(r.status_code, r.text)}
    repo_detail = json.loads(r.text)
    registry_uuid = repo_detail['registry']['uuid']
    repo_uuid = repo_detail['uuid']
    url = "{}pipelines/{}/history/{}".format(settings.API_URL, settings.CLAAS_NAMESPACE, pipeline_name)
    payload = {
        "namespace": settings.CLAAS_NAMESPACE,
        "pipeline": pipeline_name,
        "trigger": "repository",
        "data":{
            "image_tag": "latest",
            "registry_uuid": registry_uuid,
            "registry": settings.PRIVATE_REGISTRY,
            "repository": "{}/{}".format(settings.CLAAS_NAMESPACE, get_repo().get("service_repo", "houchao-test")),
            "repository_uuid": repo_uuid,
            "type": "repository"
        }
    }
    r = requests.post(url, data=json.dumps(payload), headers=headers)
    if r.status_code != 200:
        return {"success":False, "total": "trigger pipeline return code error: {}, error text:{}".format(r.status_code, r.text)}
    uuid = json.loads(r.text)["uuid"]
    if not get_events(uuid, "create"):
        return {"success": False, "total": "this action do not have events"}
    return {
        "success": True,
        "uuid": uuid
    }
Beispiel #2
0
    def load_shares(self, check_contract_phase=True):
        """ Called after waiting until the sharing phase has ended and all submitted shares have
            sufficiently been confirmed in the blockchain.
            All events are proceed, an the shares for the node itself are decrypted, verified and stored.
        """
        if check_contract_phase:
            assert self.contract.sharing_confirmed()

        events = utils.get_events(self.contract, EVENT_KEY_SHARING)
        error = False
        for e in events:
            args = e['args']

            issuer_id = args['issuer']
            if self.id == issuer_id:
                continue

            # load and convert public coefficients to points from group G1
            C = args['public_coefficients']
            C = [(C[i], C[i + 1]) for i in range(0, len(C), 2)]
            try:
                super().load_shares(issuer_id,
                                    args['encrypted_shares'],
                                    public_coefficients=C)
            except ValueError:
                error = True
                pass
        if error:
            raise ValueError('loading of shares triggered verification errors')
Beispiel #3
0
def trigger_build_pipeline(pipeline_name,build_name):
    time1 = time()
    get_build_url = "{}private-build-configs/{}/{}/".format(settings.API_URL, settings.CLAAS_NAMESPACE,
                                                            build_name)

    r = requests.get(get_build_url, headers=headers)
    if r.status_code != 200:
        return {"success": False,
                "total": "get build config return code error: {}, error text:{}".format(r.status_code, r.text)}
    build_detail = json.loads(r.text)
    build_uuid = build_detail['config_id']
    url = "{}pipelines/{}/history/{}".format(settings.API_URL, settings.CLAAS_NAMESPACE, pipeline_name)
    payload = {
        "namespace": settings.CLAAS_NAMESPACE,
        "pipeline": pipeline_name,
        "trigger": "build",
        "data": {
            "build_config_uuid": build_uuid,
            "build_config_name": build_name,
            "type": "build",
            "active": True
        }
    }
    r = requests.post(url, data=json.dumps(payload), headers=headers)
    if r.status_code != 200:
        return {"success": False,
                "total": "trigger pipeline return code error: {}, error text:{}".format(r.status_code, r.text)}
    uuid = json.loads(r.text)["uuid"]
    if not get_events(uuid, "create"):
        return {"success": False, "total": "this action do not have events"}
    resultSet = get_pipeline_info(pipeline_name, uuid)
    if resultSet['success']:
        return {"success": True, "total": time() - time1}
    else:
        return resultSet
Beispiel #4
0
def update_alarms(alarm_name, payload):
    time1 = time()
    url = "{}alarms/{}/{}".format(settings.API_URL, settings.CLAAS_NAMESPACE, alarm_name)
    print "UPDATE ALARM---"
    print "URL - {}".format(url)
    print "PAYLOAD - \n{}".format(payload)
    r = requests.put(url, data=json.dumps(payload), headers=headers)
    print r
    if r.status_code != 204:
        return {
            "success": False,
            "total": "update alarm return code error: {}, error text:{}".format(r.status_code, r.text),
            'payload': payload, 'url': url
        }
    sleep(1)
    r = requests.get(url, headers=headers)
    if r.status_code != 200:
        return {"success":False, "total": "get alarm return code error: {}, error text:{}".format(r.status_code, r.text)}
    sleep(5)
    if not get_events(alarm_name, "update"):
        return {"success": False, "total": "this action do not have events"}
    if "description" in json.loads(r.text):
        description = json.loads(r.text)['description']
        if description == "update alarm":
            time2 = time()
            return {
                "success": True,
                "total": time2 - time1,
                'payload': payload, 'url': url
            }
        else:
            return {"success": False, "total": "update message error", 'payload': payload, 'url': url}
    else:
        return {"success": False, "total": "description not in alarm", 'payload': payload, 'url': url}
def test_registration_prohibt_multiple_attemps():
    node, contract = setup_single()
    node.register()
    with pytest.raises(ValueError, match='.*registration failed.*'):
        node.register()
    events = utils.get_events(contract, EVENT_REGISTRATION)
    assert len(events) == 1
Beispiel #6
0
def wait_for(event_type, target_block_number, target_description):
    logging.info(
        f'waiting for {event_type} events until {target_description} starts...'
    )

    events = []
    num_events = 0
    last_checked = None

    while True:
        t = w3.eth.blockNumber
        if t == last_checked:
            time.sleep(1)
            continue
        last_checked = t

        events = utils.get_events(contract, event_type)
        new_events = events[num_events:]
        log_events(new_events)
        num_events = len(events)
        if new_events:
            logging.info()

        if t >= target_block_number:
            break
        logging.info(
            f'waiting for {target_block_number - t} blocks until {target_description} starts...'
        )
    logging.info()
Beispiel #7
0
def delete_application(name, region):
    logger.info(region + " Start delete {}".format(name))

    time1 = time()
    (code, text) = apicall_application("delete_app", name, region_name=region)
    if code < 200 or code >= 300:
        msg = "Error in calling delete API {}:{}".format(code, text)
        return {"success": False, "total": msg}
    sleep(5)
    if not get_events(name, "destroy"):
        return {"success": False, "total": "this action do not have events"}
    print code, text
    app_url = "{}applications/{}/{}".format(settings.API_URL,
                                            settings.CLAAS_NAMESPACE, name)
    cnt = 0
    delete_status = False
    while cnt < 120 and not delete_status:
        cnt = cnt + 1
        r = requests.get(app_url, headers=headers)
        print r.status_code
        if r.status_code <= 300 and r.status_code >= 200:
            sleep(3)
            continue
        delete_status = True
    if not delete_status:
        return {"success": False, "total": "delete application failed"}
    time2 = time()
    sleep(10)

    obj = {"success": True, "total": time2 - time1}
    return obj
Beispiel #8
0
def create_application(name, files_data, region):
    delete_application(name, region)
    time1 = time()
    files = {'services': ('compose.yml', unicode(files_data))}
    (code, text) = apicall_application('create_app',
                                       name,
                                       region_name=region,
                                       files=files)
    print("application apicall returns (%d, %s)" % (code, text))
    if code < 200 or code > 300:
        msg = "Error in call create application API {}:{}".format(code, text)
        return {"success": False, "total": msg}
    sleep(5)
    if not get_events(name, "create"):
        return {"success": False, "total": "this action do not have events"}
    app_url = "{}applications/{}/{}".format(settings.API_URL,
                                            settings.CLAAS_NAMESPACE, name)
    isdeploy = True
    cnt = 0
    while cnt < 240 and isdeploy:
        cnt = cnt + 1
        print('get app status:{}'.format(app_url))
        r = requests.get(app_url, headers=headers)
        if r.status_code > 300 or r.status_code < 200:
            msg = "Get application status_code error: {}, error text:{}".format(
                r.status_code, r.text)
            return {"success": False, "total": msg}
        if json.loads(r.text)['current_status'] != "Running":
            sleep(3)
            continue
        isdeploy = False
    if isdeploy:
        msg = "Timeout in creating"
        return {"success": False, "total": msg}
    return {"success": True, "total": time() - time1}
Beispiel #9
0
def generar_csv():
    try:
        events = utils.get_events()
        con_city = events.loc[events.city != 'Unknown']
        agrupadas = con_city.groupby(['person']).city.value_counts()
        unstacked = agrupadas.unstack(fill_value=0)
        feature_city = unstacked.idxmax(axis=1)
        person_con_location = feature_city.count()
        person_totales = events.person.nunique()
        print("Hay {} de {} personas con location asignado".format(
            person_con_location, person_totales))
        events.city = events.person.map(feature_city)
        conversion = events.loc[events.event == 'conversion']
        conversions_per_city = conversion.groupby(['city']).agg(
            {'person': 'nunique'})
        unique_person_per_city = events.groupby(['city'
                                                 ]).agg({'person': 'nunique'})
        unique_person_per_city[
            'conversion'] = unique_person_per_city.index.map(
                conversions_per_city.person).fillna(value=0).astype(int)
        unique_person_per_city[
            'relacion'] = unique_person_per_city.conversion / unique_person_per_city.person
        features_location = pd.DataFrame(feature_city.copy())
        features_location.columns = ['city']
        features_location['city_ranking'] = features_location.city.map(
            unique_person_per_city.relacion)
        features_location.to_csv('features_location.csv')
        return True
    except Exception, ex:
        print(ex)
        return False
Beispiel #10
0
def stop_application(name, region):
    logger.info(name + " stop application")
    time1 = time()
    (code, text) = apicall_application('stop_app', name, region_name=region)
    logger.info(name + " apicall returns (%d, %s)" % (code, text))
    if code < 200 or code >= 300:
        msg = "Error in call stop application API {}:{}".format(code, text)
        return {"success": False, "total": msg}
    sleep(5)
    if not get_events(name, "stop"):
        return {"success": False, "total": "this action do not have events"}

    app_url = "{}applications/{}/{}".format(settings.API_URL,
                                            settings.CLAAS_NAMESPACE, name)
    isdeploy = True
    cnt = 0
    while cnt < 120 and isdeploy:
        cnt = cnt + 1
        r = requests.get(app_url, headers=headers)
        print json.loads(r.text)['current_status']
        if r.status_code > 300 or r.status_code < 200:
            msg = "Get application status_code error: {},error text:{}".format(
                r.status_code, r.text)
            return {"success": False, "total": msg}
        if json.loads(r.text)['current_status'] != "Stopped":
            sleep(3)
            continue
        isdeploy = False
    time2 = time()
    if isdeploy:
        msg = "Timeout in stopping"
        return {"success": False, "total": msg}
    obj = {"success": True, "total": time2 - time1}
    return obj
Beispiel #11
0
def start_app(name, num):
    logger.info(" start service")
    print "start_app()"

    time1 = time()
    (code, text) = apicall_claas_service('start_service', name)
    logger.info(" apicall returns (%d, %s)" % (code, text))
    if code < 200 or code >= 300:
        msg = "Error in calling start API {}:{}".format(code, text)
        return {"success": False, "total": msg}

    target = {"status": "Running", "num": num}
    if not get_events(name, "start"):
        return {"success": False, "total": "this action do not have events"}
    isdeploying = is_deploying(name, target, 180, settings.CLAAS_NAMESPACE)
    time2 = time()
    if isdeploying:
        (code, text, obj) = get_service_info(name, 0, settings.CLAAS_NAMESPACE)
        if 'current_status' in obj:
            if obj['current_status'].find('Error') >= 0:
                return {
                    "success": False,
                    "total": "restart {} service status is Error".format(name)
                }
        return {
            "success": False,
            "total": "Timeout in starting {}".format(name)
        }

    logger.info(" ==> Starting service uses {}s".format(time2 - time1))
    obj = {"success": True, "total": time2 - time1}
    return obj
def test_sharing():
    contract, nodes = setup_multiple(register=True)

    utils.run([node.share_key for node in nodes])

    events = utils.get_events(contract, EVENT_KEY_SHARING)
    assert len(events) == len(nodes)
Beispiel #13
0
    def init_secret_sharing(self, check_contract_phase=False):
        """ Called after waiting until the registration phase has ended and
            has sufficiently been confirmed in the blockchain.
            Query all registration events from the contract instance to get
               a) the local node id
               b) the number of participanting nodes
               c) the public keys of all participating nodes
        """
        if check_contract_phase:
            assert self.contract.registrations_confirmed()

        id = None
        nodes = []
        events = utils.get_events(self.contract, EVENT_REGISTRATION)
        for e in events:
            args = e['args']
            node = EthNode(
                account=args['node_adr'],
                id=args['id'],
                pk=args['pk'],
                bls_pk=args['bls_pk'],
            )
            if node.account == self.account:
                id = node.id
            nodes.append(node)

        assert id is not None
        super().init_secret_sharing(nodes, id)
Beispiel #14
0
def create_service(name, payload, service_detail='Hello', region='STAGING'):
    delete_app(name, region)
    print "create claas service"
    logger.info(region + " Start creating service")

    time1 = time()
    print payload
    (code, text) = apicall_claas_service('create_service', name, payload)
    logger.info("apicall returns (%d, %s)" % (code, text))
    print("apicall returns (%d, %s)" % (code, text))
    if code < 200 or code >= 300:
        msg = "Error in calling create Claas API {}:{}".format(code, text)
        return {"success": False, "total": msg}
    if not get_events(name, "create"):
        return {"success": False, "total": "this action do not have events"}

    # test if at least 1 instance is running
    target = {"status": "Running", "text": service_detail}
    isdeploying = is_deploying(name, target, 200, settings.CLAAS_NAMESPACE)
    time2 = time()
    logger.info(region + " is_deploying check use {}s".format(time2 - time1))
    if isdeploying:
        (code, text, obj) = get_service_info(name, 0, settings.CLAAS_NAMESPACE)
        if 'current_status' in obj:
            if obj['current_status'].find('Error') >= 0:
                return {
                    "success": False,
                    "total": "create service {} status is Error".format(name)
                }
            if "instance_ports" in json.loads(text) and len(
                    json.loads(text)['instance_ports']):
                if "endpoint_type" in json.loads(text)['instance_ports'][
                        0] and json.loads(text)['instance_ports'][0][
                            'endpoint_type'] == "internal-endpoint":
                    (code, html) = get_service_result(
                        json.loads(text)["instance_ports"][0]
                        ["default_domain"])
                    if code > 300 or code < 200:
                        return {"success": True, "total": time2 - time1}
                    else:
                        return {
                            "success":
                            False,
                            "total":
                            "internal haproxy service should not can visit"
                        }
            flag = can_visit(target, text)
            if not flag and obj['current_status'] == 'Running':
                return {
                    "success": False,
                    "total": "create service {} can not visit".format(name)
                }
        msg = "Timeout in creating {} service".format(name)
        return {"success": False, "total": msg}
    logger.info(region + " create use {}s".format(time2 - time1))

    return {"success": True, "total": time2 - time1}
Beispiel #15
0
def delete_pipeline_history(pipeline_name, uuid):
    time1 = time()
    url = "{}pipelines/{}/history/{}/{}/".format(settings.API_URL, settings.CLAAS_NAMESPACE, pipeline_name, uuid)
    r = requests.delete(url, headers=headers)
    if r.status_code != 204:
        return {"success": False, "message": "delete failed:r.status_code is {}, r.text is {}".format(r.status_code, r.text)}
    if not get_events(uuid, "destroy"):
        return {"success": False, "total": "this action do not have events"}
    time2 = time()
    return {"success": True, "total": time2 - time1}
def test_registration_prohibt_late_submission():
    node, contract = setup_single()
    utils.mine_blocks_until(lambda: not contract.in_registration_phase())

    with pytest.raises(AssertionError):
        node.register()
    with pytest.raises(ValueError, match='.*registration failed.*'):
        node.register(check_contract_phase=False)
    events = utils.get_events(contract, EVENT_REGISTRATION)
    assert len(events) == 0
Beispiel #17
0
def delete_pipeline(pipeline_name):
    time1 = time()
    url = "{}pipelines/{}/config/{}".format(settings.API_URL, settings.CLAAS_NAMESPACE, pipeline_name)
    r = requests.delete(url, headers=headers)
    if r.status_code != 204:
        return {"success":False, "total": "delete pipeline return code error: {},error text:{}".format(r.status_code, r.text)}
    if not get_events(pipeline_name, "destroy"):
        return {"success": False, "total": "this action do not have events"}
    time2 = time()
    return {"success": True, "total": time2-time0}
Beispiel #18
0
    def on_change(self, _0, _1, _2):
        # Load the events raised to the server, and handle them in order
        server_snap = self.server_doc.get()
        events = utils.get_events(server_snap)
        for event in events:
            self.handle_event(event)

        # After handling all events, clear the event queue
        doc_dict = server_snap.to_dict()
        doc_dict["events"] = []
        self.server_doc.set(doc_dict)
Beispiel #19
0
 def create_pipeline(pipeline_name, data):
    delete_pipeline(pipeline_name)
    time1 = time()
    url = "{}pipelines/{}/config".format(settings.API_URL, settings.CLAAS_NAMESPACE)
    print data, type(data)
    r = requests.post(url, data=json.dumps(data), headers=headers)
    print r.text
    if r.status_code != 201:
        return {"success":False, "total": "create pipeline return code error: {}, error text:{}".format(r.status_code,r.text)}
    if not get_events(pipeline_name, "create"):
        return {"success": False, "total": "this action do not have events"}
    result = json.loads(r.text)
    if "name" in result and result['name'] == pipeline_name:
        time2 = time()
        return {"success": True, "total": time2-time1}
    else:
        return {"success":False, "totol": "r.text is {}, r.status_code is {}".format(r.text, r.status_code)}
Beispiel #20
0
def update_service(name, num, size, service_detail='Hello'):
    print "scale_app()"
    logger.info(" Start scaling service {}".format(name))

    time1 = time()
    payload = {
        # "image_tag": "latest",
        "target_num_instances": num,
        "instance_size": size
    }
    (code, text) = apicall_claas_service('modify_service', name, payload)
    logger.info(" apicall returns (%d, %s)" % (code, text))
    if code < 200 or code >= 300:
        msg = "Error in calling scale API {}:{}".format(code, text)
        return {"success": False, "total": msg}
    if not get_events(name, "update"):
        return {"success": False, "total": "this action do not have events"}

    target = {
        "status": "Running",
        "num": num,
        "size": size,
        "text": service_detail
    }
    isdeploying = is_deploying(name, target, 240, settings.CLAAS_NAMESPACE)
    time2 = time()
    if isdeploying:
        (code, text, obj) = get_service_info(name, 0, settings.CLAAS_NAMESPACE)
        if 'current_status' in obj:
            if obj['current_status'].find('Error') >= 0:
                return {
                    "success": False,
                    "total": "update service {} status is Error".format(name)
                }
            flag = can_visit(target, text)
            if not flag and obj['current_status'] == 'Running':
                return {
                    "success": False,
                    "total": "update service {} can not visit".format(name)
                }
        msg = "Timeout in scaling {}".format(name)
        return {"success": False, "total": msg}

    logger.info(" ==> Scaling uses {}s".format(time2 - time1))
    return {"success": True, "total": time2 - time1}
Beispiel #21
0
def delete_app(name, region_name='STAGING'):
    logger.info(region_name + " start deleting {}".format(name))

    time1 = time()
    (code, text) = apicall_claas_service('delete_service', name)
    logger.info(region_name + " apicall returns (%d, %s)" % (code, text))
    if code < 200 or code >= 300:
        msg = "Error in calling delete API {}:{}".format(code, text)
        return {"success": False, "total": msg}

    time2 = time()
    logger.info(region_name + " total deletion uses %f seconds" %
                (time2 - time1))
    sleep(10)
    if not get_events(name, "destroy"):
        return {"success": False, "total": "this action do not have events"}
    obj = {"success": True, "total": time2 - time1}
    return obj
Beispiel #22
0
def delete_alarms(alarm_name):
    time1 = time()
    url = "{}alarms/{}/{}".format(settings.API_URL, settings.CLAAS_NAMESPACE, alarm_name)
    print "DELETE ALARM---"
    print "URL - {}".format(url)
    r = requests.delete(url, headers=headers)
    print r
    if r.status_code != 204:
        return {
            "success": False,
            "total": "delete alarm return code error: {}, error text:{}".format(
                r.status_code, r.text
            )
        }
    sleep(5)
    if not get_events(alarm_name, "destroy"):
        return {"success": False, "total": "this action do not have events"}
    time2 = time()
    return {"success": True, "total": time2-time1}
Beispiel #23
0
    def verify_nodes(self, check_contract_phase=True):
        """ gets all dispute events, and uses this information to derive which nodes should contribute to the group key
        """
        if check_contract_phase:
            assert self.contract.dispute_confirmed()

        dispute_events = utils.get_events(self.contract,
                                          EVENT_DISPUTE_SUCCESSFUL)
        dispute_addrs = set(e['args']['bad_issuer_addr']
                            for e in dispute_events)

        dispute_ids = set()
        for addr in dispute_addrs:
            t = [node for node in self.nodes if node.account == addr]
            assert len(
                t) == 1, 'above query should always return exactly one item'
            dispute_ids.add(t[0].id)

        super().load_dispute_infos(dispute_ids)
Beispiel #24
0
def create_alarms(alarm_name, payload):
    delete_alarms(alarm_name)
    time1 = time()
    url = "{}alarms/{}".format(settings.API_URL, settings.CLAAS_NAMESPACE)
    r = requests.post(url, data=json.dumps(payload), headers=headers)
    print r
    print r.status_code, r.text
    if r.status_code != 201:
        return {
            "success": False,
            "total": "create alarm return code error: {}, error text:{}"
            .format(r.status_code, r.text),
            'payload': payload, 'url': url
        }
    sleep(5)
    if not get_events(alarm_name, "create"):
        return {"success": False, "total": "this action do not have events"}
    time2 = time()
    return {"success": True, "total": time2-time1, 'payload': payload, 'url': url}
Beispiel #25
0
def send_events(msg):
    """Загрузка мероприятий с сервера"""
    global csrf_token
    data, csrf_token = get_events()

    markup = types.ReplyKeyboardRemove()
    bot.send_message(msg.chat.id, 'Список доступных мероприятий:', reply_markup=markup).wait()

    events = data['data']['events']
    for event in events:
        date_list = event['date'].split('-')
        markup = types.InlineKeyboardMarkup()
        markup.add(types.InlineKeyboardButton('Записаться на мероприятие', callback_data=f'follow_{event["id"]}'))
        bot.send_message(msg.chat.id,
                         f'*{event["name"]}*\n\n{event["description"]}\n\nДата окончания регистрации: ' +
                         f'{date_list[2]} {get_month(int(date_list[1]))}',
                         parse_mode='Markdown',
                         reply_markup=markup
                         ).wait()
Beispiel #26
0
def stop_pipeline(pipeline_name):
    time1 = time()
    ret = trigger(pipeline_name)
    if ret['success']:
        url = "{}pipelines/{}/history/{}/{}/stop/".format(settings.API_URL, settings.CLAAS_NAMESPACE, pipeline_name, ret['uuid'])
        print url
        r = requests.put(url, headers=headers)
        print r
        if r.status_code != 204:
            return {"success": False, "status": r.status_code,
                    "message": "stop pipeline info failed. pipeline id is {}, message:{}".format(ret['uuid'], r.text)}
        if not get_events(ret['uuid'], "stop"):
            return {"success": False, "total": "this action do not have events"}
        resultSet = get_pipeline_info(pipeline_name, ret['uuid'])
        if resultSet["status"] == "failed":
            return {"success": True, "total": time()-time1, "uuid": ret['uuid']}
        else:
            return resultSet
    else:
        return ret
Beispiel #27
0
def update_pipeline(pipeline_name, payload):
    time1 = time()
    url = "{}pipelines/{}/config/{}".format(settings.API_URL, settings.CLAAS_NAMESPACE, pipeline_name)
    r = requests.put(url, data=json.dumps(payload), headers=headers)
    if r.status_code != 204:
        return {"success":False, "total": "update template return code error: {},error text:{}".format(r.status_code, r.text)}
    if not get_events(pipeline_name, "update"):
        return {"success": False, "total": "this action do not have events"}
    r = requests.get(url, headers=headers)
    if "description" in json.loads(r.text):
        description = json.loads(r.text)['description']
        if description == "update pipeline":
            time2 = time()
            return {
                "success": True,
                "total": time2 - time1
            }
        else:
            return {"success": False, "total": "update message error,r.text is {}".format(r.text)}
    else:
        return {"success": False, "total": "description not in template, r.text is {}".format(r.text)}
Beispiel #28
0
def stop_app(name):
    logger.info(" Stopping service")
    print "stop_app()"

    time1 = time()
    (code, text) = apicall_claas_service('stop_service', name)
    logger.info(" apicall returns (%d, %s)" % (code, text))
    if code < 200 or code >= 300:
        msg = "Error in calling stop API {}:{}".format(code, text)
        return {"success": False, "total": msg}
    if not get_events(name, "stop"):
        return {"success": False, "total": "this action do not have events"}
    target = {"status": "Stopped", "num": 0}
    isdeploying = is_deploying(name, target, 120, settings.CLAAS_NAMESPACE)
    time2 = time()
    if isdeploying:
        return {
            "success": False,
            "total": "Timeout in stopping {}".format(name)
        }

    logger.info(" ==> Stopping service uses {}s".format(time2 - time1))
    obj = {"success": True, "total": time2 - time1}
    return obj
    subjects,
    data_types,
    contrasts,
    chan_types,
)

from analyses_definition_univariate import format_analysis
contrasts = [ana for ana in contrasts if ana['name'] == 'targetAngle']
analysis = format_analysis(contrasts[0])

data_path = '/media/DATA/Pro/Projects/Paris/Orientation/Niccolo/data/'
meg_fname = data_path + 'preprocessed/ak_heavily_decimated.epo'
bhv_fname = data_path + '/ak130184_fixed.mat'
meg_fname = data_path + 'preprocessed/mc_heavily_decimated.epo'
bhv_fname = data_path + '/mc130295_fixed.mat'
events = get_events(bhv_fname)
with open(meg_fname, 'r') as f:
    epochs = pickle.load(f)
#
# mat = dict()
# mat['dat'] = np.array(epochs._data)
# mat['y'] = 1. * np.array(events['orientation_target'])
# mat_fname = data_path + '/heavily_decimated.mat'
# sio.savemat(mat_fname, mat)

# force separation of magnetometers and gradiometers
if 'meg' in [i['name'] for i in chan_types]:
    chan_types = [dict(name='mag'), dict(name='grad')] + \
                 [dict(name=i['name'])
                  for i in chan_types
                  if i['name'] != 'meg']
Beispiel #30
0
def get_template(input_text):
    endDate = datetime.today().strftime('%Y-%m-%d')
    startDate = (datetime.today() - timedelta(days=30)).strftime('%Y-%m-%d')
    if input_text == "[reset]":
        return TextSendMessage(
            text='你可以輸入任何人名,例如:蔡英文,我就會統計出他/她最近最常發生的事件種類, 並提供進一步查詢。',
            quick_reply=QuickReply(
                items=[
                    QuickReplyButton(
                        action=MessageAction(label="蔡英文", text="蔡英文")
                    ),
                    QuickReplyButton(
                        action=MessageAction(label="韓國瑜", text="韓國瑜")
                    ),
                    QuickReplyButton(
                        action=MessageAction(label="郭台銘", text="郭台銘")
                    )]
            ))

    elif ":" not in input_text:
        events = get_events(input_text, startDate, endDate)
        if len(events) == 0:
            return TextSendMessage(
                text='沒有這個人,或他/她的新聞數太少QAQ')
        elif len(events) <= 9:
            all_columns = []
            all_actions = []
            for i in range(len(events)):
                all_actions.append(MessageTemplateAction(
                    label="...".join(events[i]['term'].split()) + " (" + str(events[i]["freq"]) + ")",
                    text=input_text + ":" + events[i]['term']
                ))
                if (i + 1) % 3 == 0:
                    all_columns.append(CarouselColumn(
                        title='{}相關新聞事件'.format(input_text),
                        text='點選可獲得相關新聞',
                        actions=all_actions
                    ))
                    all_actions = []
        else:
            events = events[:8]
            all_columns = []
            all_actions = []
            for i in range(9):
                if i == 8:
                    all_actions.append(MessageTemplateAction(
                        label="more",
                        text="更多事件" + ":" + str(8) + ":" + input_text
                    ))
                else:
                    all_actions.append(MessageTemplateAction(
                        label="...".join(events[i]['term'].split()) + " (" + str(events[i]["freq"]) + ")",
                        text=input_text + ":" + events[i]['term']
                    ))

                if (i + 1) % 3 == 0:
                    all_columns.append(CarouselColumn(
                        title='{}相關新聞事件'.format(input_text),
                        text='點選可獲得相關新聞',
                        actions=all_actions
                    ))
                    all_actions = []

        buttons_template = TemplateSendMessage(
            alt_text='Carousel template',
            template=CarouselTemplate(
                columns=all_columns
            )
        )
        return buttons_template

    elif "更多事件" in input_text:
        _, id_event, input_text = input_text.split(":")
        id_event = int(id_event)
        events = get_events(input_text, startDate, endDate)
        action_lst = []
        for i in range(3):
            action_lst.append(MessageTemplateAction(
                label="...".join(events[id_event + i]['term'].split()) + " (" + str(events[id_event]["freq"]) + ")",
                text=input_text + ":" + events[id_event + i]['term']
            ))
        if len(events[id_event + 3:]) > 3:
            action_lst.append(MessageTemplateAction(
                label="more",
                text="更多事件" + ":" + str(id_event + 3) + ":" + input_text
            ))
        buttons_template = TemplateSendMessage(
            alt_text='Buttons Template',
            template=ButtonsTemplate(
                title='{}相關新聞事件'.format(input_text),
                text='點選可獲得相關新聞',
                actions=action_lst
            )
        )
        return buttons_template

    elif "more" in input_text:
        _, id, key, events = input_text.split(":")
        id = int(id)
        news = get_news(key, events, startDate, endDate)
        news_lst = news["data"][id:id + 3]
        id = id + 3
        isMore = len(news["data"][id:]) != 0
        flex_template = news_template_flex(news_lst, events, key, id, isMore)
        return flex_template
    else:
        key, events = input_text.split(":")
        news = get_news(key, events, startDate, endDate)
        news_lst = news["data"][:3]
        id = 3
        isMore = len(news["data"]) > 3
        flex_template = news_template_flex(news_lst, events, key, id, isMore)
        return flex_template
Beispiel #31
0
 def get_events(self, league_id):
     return utils.get_events(league_id)