예제 #1
0
def write_rows_from_tweet(csv_f, t, topic, excl_rts):
    global REPLY_COUNT  # declare that we want to change REPLY_COUNT
    try:
        ts = utils.extract_ts_s(t['created_at'])
        # dt = parser.parse(t['created_at'])
        # ts = int(calendar.timegm(dt.timetuple()))
    except TypeError as e:
        # ts = int(int(t['created_at']) / 1000 - utc_offset) #- time.timezone #+ (time.gmtime() - time.localtime()) # there's a chance this is a millseconds (twarc)
        # ts = calendar.timegm ( datetime.utcfromtimestamp(int(t['created_at']/1000.0) - utc_offset).timetuple() )
        # raise e
        ts = int(t['created_at']) / 1000
    ts = int(ts) # force it to an int
    t_id = t['id_str']
    source = utils.get_uid(t)
    if topic in ['RETWEET', 'RETWEETS', 'RT', 'RTS'] and utils.is_rt(t):
        ot = utils.get_ot_from_rt(t)
        target = utils.get_uid(ot)
        rt_id = t_id
        ot_id = utils.get_ot_from_rt(t)['id_str']
        csv_f.writerow([ts, source, target, 'RETWEET', rt_id, ot_id])
    elif topic in ['QUOTE', 'QUOTES'] and not utils.is_rt(t) and utils.is_qt(t):
        ot = t['quoted_status']
        target = utils.get_uid(ot)
        qt_id = t_id
        ot_id = ot['id_str']
        csv_f.writerow([ts, source, target, 'QUOTE', qt_id, ot_id])
    elif topic in ['REPLY', 'REPLIES']:
        target = t['in_reply_to_user_id_str']
        ot_id  = t['in_reply_to_status_id_str']
        if target and ot_id:
            csv_f.writerow([ts, source, target, 'REPLY', t_id, ot_id])
    elif topic in ['HASHTAG', 'HASHTAGS', 'ALL_HASHTAGS']:
        hashtags = utils.lowered_hashtags_from(t, include_retweet=True)
        if is_empty(hashtags):
            return
        if topic == 'ALL_HASHTAGS':
            csv_f.writerow([ts, source, ' '.join(hashtags), 'ALL_HASHTAGS', t_id])
        else:
            for ht in hashtags:
                csv_f.writerow([ts, source, ht, 'HASHTAG', t_id])
    elif topic in ['URL', 'URLS', 'POST_URL', 'POST_URLS', 'ALL_URLS', 'ALL_POST_URLS', 'DOMAIN', 'DOMAINS', 'ALL_DOMAINS']:
        for url in set(utils.expanded_urls_from(t, include_retweet=True)):
            write_url_row(csv_f, topic, url, ts, source, t_id)
    elif topic in ['MENTION', 'MENTIONS', 'ALL_MENTIONS']:
        if excl_rts and utils.is_rt(t):
            return
        mention_objs = utils.mentions_from(t, include_retweet=True)
        if is_empty(mention_objs):
            return
        if topic == 'ALL_MENTIONS':
            mentioned_ids_str = ' '.join([m['id_str'] for m in mention_objs])
            mentioned_sns_str = ' '.join([m['screen_name'] for m in mention_objs])
            csv_f.writerow([ts, source, mentioned_ids_str, 'ALL_MENTIONS', t_id, mentioned_sns_str])
        else:
            for m in mention_objs:
                csv_f.writerow([ts, source, m['id_str'], 'MENTION', t_id, m['screen_name']])
    elif topic in ['TIMESTAMP', 'TIMESTAMPS', 'TS']:
        csv_f.writerow([ts, source, t_id])
예제 #2
0
def create_song_dependencies(instance):
    instance.owner = User.objects.create(username=get_uid(30))
    instance.non_owner = User.objects.create(username=get_uid(30))
    instance.active_project = Project.objects.create(
        title="Active Project",
        owner=instance.owner,
    )
    instance.inactive_project = Project.objects.create(
        title="Inactive Project",
        owner=instance.owner,
        active=False,
        status=Project.STATUS_COMPLETE)
예제 #3
0
    def func_index (self, objs, **kwargs) :
        if type(objs) not in (types.GeneratorType, iter([]).__class__, ) :
            objs = iter([objs, ])

        try :
            for obj in objs :
                index_models = utils.get_index_models(obj)
                for index_model in index_models :
                    searcher = pylucene.Searcher(storage_path=index_model._meta.storage_path, )
                    uid = utils.get_uid(index_model._meta.model, obj.pk, )
                    doc = searcher.get_document_by_uid(uid)
                    if not doc :
                        uid = None

                    searcher.close()

                    kwargs.update({"storage_path": index_model._meta.storage_path, })
                    w = pylucene.IndexWriter(**kwargs)
                    w.index(
                        document.Document.create_document_from_object(
                            index_model, obj,
                        ),
                        uid=uid,
                    )
                    w.close()
        except Exception, e :
            raise
            return False
예제 #4
0
def create(username, domain, email, password=None):
    # domain = get_domain_top(domain)
    print(f'Creating {email}@{domain} for user {username}')
    
    if os.popen(f'grep {domain} /etc/apache2/sites-available/001-mail.conf').read().strip() == '':
        configure(username, domain)

    uid = get_uid(username)
    gid = get_gid(username)
    home = f'/home/{username}'
    if not password:
        password = random_password(12)
    password_hash = crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA256))

    global emails
    emails = []

    conn = sqlite3.connect('/etc/dovecot/authdb.sqlite')
    c = conn.cursor()
    c.execute('DELETE FROM users WHERE username = ? AND domain = ?;', (email, domain))
    c.execute('INSERT INTO users (username, domain, password, home, uid, gid) VALUES (?, ?, ?, ?, ?, ?);', (email, domain, password_hash, home, uid, gid))
    conn.commit()
    conn.close()

    print(f'\n\n\t\tNew password of {email}@{domain}: {password}')
    domain = get_domain_top(domain)
    print(f'\t\tPOP3 hostname: pop3.{domain}')
    print(f'\t\tSMTP hostname: smtp.{domain}\n\n')
    print('Restarting Dovecot...')
    os.system('service dovecot restart')
예제 #5
0
 def test_money_transfer(self):
     balanceNodeOwnerB = utils.get_balance_from_db(conf["1"]["dbHost"],
                                                   conf["1"]["dbName"],
                                                   conf["1"]["login"],
                                                   conf["1"]["pass"],
                                                   conf["2"]["keyID"])
     commisionWallet = utils.get_commission_wallet(conf["1"]["dbHost"],
                                                   conf["1"]["dbName"],
                                                   conf["1"]["login"],
                                                   conf["1"]["pass"], 1)
     balanceCommisionB = utils.get_balance_from_db(conf["1"]["dbHost"],
                                                   conf["1"]["dbName"],
                                                   conf["1"]["login"],
                                                   conf["1"]["pass"],
                                                   commisionWallet)
     tokenRunner, uid = utils.get_uid(conf["2"]["url"])
     signature = sign(keys["key2"], uid)
     pubRunner = get_public_key(keys["key2"])
     balanceRunnerB = utils.get_balance_from_db_by_pub(
         conf["1"]["dbHost"], conf["1"]["dbName"], conf["1"]["login"],
         conf["1"]["pass"], pubRunner)
     dataRunner = utils.login(conf["2"]["url"], keys["key2"], 0)
     tokenRunner = dataRunner["jwtToken"]
     data = {"Recipient": "0005-2070-2000-0006-0200", "Amount": "1000"}
     res = utils.call_contract(conf["2"]["url"], keys["key2"],
                               "MoneyTransfer", data, tokenRunner)
     hash = res["hash"]
     result = utils.txstatus(conf["2"]["url"],
                             conf["2"]["time_wait_tx_in_block"], hash,
                             tokenRunner)
     balanceRunnerMust = balanceRunnerB - 1000
     balanceRunnerB = utils.get_balance_from_db_by_pub(
         conf["1"]["dbHost"], conf["1"]["dbName"], conf["1"]["login"],
         conf["1"]["pass"], pubRunner)
예제 #6
0
 def func_unindex (self, obj, **kwargs) :
     try :
         w = pylucene.IndexWriter(**kwargs)
         w.unindex(
             pylucene.Term.new(constant.FIELD_NAME_UID, str(utils.get_uid(obj, obj.pk)))
         )
         w.close()
     except Exception, e :
         raise
         return False
예제 #7
0
 def func_unindex(self, obj, **kwargs):
     try:
         w = pylucene.IndexWriter(**kwargs)
         w.unindex(
             pylucene.Term.new(constant.FIELD_NAME_UID,
                               str(utils.get_uid(obj, obj.pk))))
         w.close()
     except Exception, e:
         raise
         return False
예제 #8
0
 def __init__(self, supported_abstract_syntaxes = None, supported_transfer_syntaxes = None):
     super(DICOMUpperLayerServiceProvider, self).__init__()
     self.reject_reason = None
     self.reject_source = None
     self.reject_result = None
     self.is_association_requestor = True # Until we se an association request
     self.state = 1
     self.ARTIM_time = 10.0
     self.ARTIM = None
     if supported_abstract_syntaxes == None:
        self.supported_abstract_syntaxes = []
     else:
        self.supported_abstract_syntaxes = supported_abstract_syntaxes
     if supported_transfer_syntaxes == None:
         self.supported_transfer_syntaxes = [get_uid("Implicit VR Little Endian"),
                                             get_uid("Explicit VR Little Endian"),
                                             get_uid("Explicit VR Big Endian")]
     else:
         self.supported_transfer_syntaxes = supported_transfer_syntaxes
예제 #9
0
    def setUpClass(cls):
        cls.staff_data = {"username": get_uid(30), "password": "******"}
        cls.staff = User.objects.create_user(**cls.staff_data)
        cls.staff.is_staff = True
        cls.staff.save()
        add_site_permission(cls.staff)

        cls.owner_data = {"username": get_uid(30), "password": "******"}
        cls.owner = User.objects.create_user(**cls.owner_data)

        # Must match with the number of tracks below
        cls.owner.profile.track_credit = 8
        cls.owner.profile.save()

        cls.project = Project.objects.create(title="Test project",
                                             owner=cls.owner,
                                             status=Project.STATUS_IN_PROGRESS)

        cls.download_url = reverse("admin:mixing_project_download",
                                   args=[cls.project.pk])
예제 #10
0
파일: views.py 프로젝트: SwoJa/ruman
def ajax_imagine():
    term = request.args.get('uid', '')
    try:
        uid = re.match(r'[\d]{10}\Z', term).group()
    except:
        try:
            #print 'ddd'
            uid = get_uid(term)
        except:
            uid = ''
    #uid = request.args.get('uid', '') # uid
    query_keywords = request.args.get('keywords', '')  # 查询字段
    submit_user = request.args.get('submit_user', '')
    query_weight = request.args.get('weight', '')  # 权重
    size = request.args.get('size', 100)
    keywords_list = query_keywords.split(',')
    weight_list = query_weight.split(',')
    print uid
    if len(keywords_list) != len(weight_list):
        return json.dumps([])

    query_fields_dict = {}
    for i in range(len(keywords_list)):
        query_fields_dict[keywords_list[i]] = int(weight_list[i])

    # 如果查询为空,获取上一次请求数据,再为空,默认领域搜索
    if not query_fields_dict:
        user_imagine_dict = {}
        imagine_setting = R_ADMIN.hget(submit_user, "imagine_setting")
        print '112', imagine_setting
        if not imagine_setting:
            user_info = es_user_portrait.get(index="user_portrait_1222",
                                             doc_type="user",
                                             id=uid,
                                             _source=False,
                                             fields=["domain"])['_source']
            user_domain = user_info['fields']['domain'][0]
            query_fields_dict[user_domain] = 1
        else:
            query_fields_dict = json.loads(imagine_setting)
    else:
        R_ADMIN.hset(submit_user, "imagine_setting",
                     json.dumps(query_fields_dict))

    query_fields_dict['size'] = int(size)

    print '125', query_fields_dict
    result = []
    if uid and query_fields_dict:
        result = imagine(submit_user, uid, query_fields_dict)
    if result:
        return json.dumps(result)

    return json.dumps([])
예제 #11
0
    def get(self, *args, **kwargs):
        if kwargs.has_key("pk"):
            searcher = pylucene.Searcher(
                storage_path=self.index_model._meta.storage_path, )
            doc = searcher.get_document_by_uid(
                utils.get_uid(self.model, kwargs.get("pk")))
            if doc is None:
                raise ObjectDoesNotExist, ""

            return document.Document(doc)

        return super(QuerySet, self).get(*args, **kwargs)
예제 #12
0
파일: app.py 프로젝트: szk01/learngit
def extcute_body(body):
    if isinstance(body, dict):

        if body.get("status") == "RING":  # 有电话接入call-in,客户端显示页面
            log(body["number"])
            log('有电话接入,显示弹窗')
            ws['tran_id'] = body['vid']  # 将来访者id写入ws字典,供满意度调查按钮使用
            seatId = body['pid']  # seatId是分机号
            room = getNumber(seatId, Seat, ws)
            socketio.emit(event='ring', data=body, room=room)

        elif isinstance(body.get('ws'), dict):
            log('通话结束传过来的body', body)
            if body['ws']['status'] == 'Cdr':
                # 通话结束,发送Cdr话单,包含录音文件的路径
                log('通话结束,停止计时')
                seatId = body['ws']['pid']
                room = getNumber(seatId, Seat, ws)
                uid = get_uid(Seat, int(seatId))
                Funcs.sql_addCallRecord(body['cr'], uid)  # 添加通话记录
                Funcs.sql_addVoiceRecord(body['vr'], uid)  # 添加录音记录
                socketio.emit(event='off', data=body['ws'], room=room)
                wget_down(body['ws']['downPath'])  # 下载录音

        elif body.get("status") == 'ANWSER':  # 分机应答,让计时器开始计时
            log('通话建立')
            seatId = body['pid']
            room = getNumber(seatId, Seat, ws)
            socketio.emit(event='anwser', data=body, room=room)

        elif body.get("status") == 'INCOMING':  # 来电转分机请求
            vid = body.get("vid")
            ws['tran_id'] = body['vid']  # 将来访者id写入ws字典,供满意度调查按钮使用
            welcome(vid)

            # if setting_phone['pid']:  # 如果设置分机的优先级,使用优先分机
            #     auto(body['vid'], setting_phone['pid'])
            # else:
            #     pid = list(Funcs.p['IDLE'])  # 如果没有设置分机的优先机,就使用allFunc中的写死的默认分机
            #     # auto(body['vid'], random.choice(pid))             # 随机分配
            #     auto(body['vid'], '212')                            # 指定分机

        elif body.get("status") == 'change_status':  # 分机状态改变
            socketio.emit(event='phone_status', data=body)  # 广播给所有客户端,显示分机的状态

        elif body.get("status") == 'lose':  # 电话漏接情况,发送漏接短信
            pid = body['pid']               # 分机号
            client_phone = body['number']
            seat = Seat.query.filter_by(number=pid).first()
            user = seat.user
            user_phone = user.phone
            log('漏接短信信息', user_phone, client_phone, pid)
            status = send_message(user_phone, client_phone, pid)
예제 #13
0
    def get (self, *args, **kwargs) :
        if kwargs.has_key("pk") :
            searcher = pylucene.Searcher(storage_path=self.index_model._meta.storage_path, )
            doc = searcher.get_document_by_uid(
                utils.get_uid(self.model, kwargs.get("pk"))
            )
            if doc is None :
                raise ObjectDoesNotExist, ""

            return document.Document(doc)

        return super(QuerySet, self).get(*args, **kwargs)
예제 #14
0
파일: views.py 프로젝트: SwoJa/ruman
def ajax_imagine():   
    term = request.args.get('uid','')
    try:
        uid = re.match(r'[\d]{10}\Z', term).group()
    except:
        try:
            #print 'ddd'
            uid = get_uid(term)
        except:
            uid = ''
    #uid = request.args.get('uid', '') # uid
    query_keywords = request.args.get('keywords','') # 查询字段
    submit_user = request.args.get('submit_user', '')
    query_weight = request.args.get('weight','') # 权重
    size = request.args.get('size', 100)
    keywords_list = query_keywords.split(',')
    weight_list = query_weight.split(',')
    print uid
    if len(keywords_list) != len(weight_list):
        return json.dumps([])

    query_fields_dict = {}
    for i in range(len(keywords_list)):
        query_fields_dict[keywords_list[i]] = int(weight_list[i])

    # 如果查询为空,获取上一次请求数据,再为空,默认领域搜索
    if not query_fields_dict:
        user_imagine_dict = {}
        imagine_setting = R_ADMIN.hget(submit_user, "imagine_setting")
        print '112',imagine_setting
        if not imagine_setting:
            user_info = es_user_portrait.get(index="user_portrait_1222", doc_type="user", id=uid, _source=False, fields=["domain"])['_source']
            user_domain = user_info['fields']['domain'][0]
            query_fields_dict[user_domain] = 1
        else:
            query_fields_dict = json.loads(imagine_setting)
    else:
        R_ADMIN.hset(submit_user, "imagine_setting", json.dumps(query_fields_dict))
        


    query_fields_dict['size'] = int(size)

    print '125',query_fields_dict
    result = []
    if uid and query_fields_dict:
        result = imagine(submit_user, uid, query_fields_dict)
    if result:
        return json.dumps(result)

    return json.dumps([])
    def setUpClass(cls):
        """
        Runs once per class, not once per test method.
        Make sure all objects defined here are NOT modified in test methods.
        Django provides it's own setUpTestData, but it appears to be buggy
        when used with Postgres, raising InterfaceError: Connection already closed.
        https://groups.google.com/d/msg/django-users/MDRcg4Fur98/cGYs8cmQLAAJ
        """
        cls.staff_data = {"username": get_uid(30), "password": "******"}
        cls.staff = User.objects.create_user(**cls.staff_data)
        cls.staff.is_staff = True
        cls.staff.save()

        cls.non_owner_data = {"username": get_uid(30), "password": "******"}
        cls.non_owner = User.objects.create_user(**cls.non_owner_data)

        cls.owner_data = {"username": get_uid(30), "password": "******"}
        cls.owner = User.objects.create_user(**cls.owner_data)
        cls.owner.profile.track_credit = 1
        cls.owner.profile.save()

        cls.track, cls.comment, cls.final = create_private_files(
            owner=cls.owner)
예제 #16
0
 def func_index_update (self, obj, **kwargs) :
     try :
         index_models = utils.get_index_models(obj)
         for index_model in index_models :
             kwargs.update({"storage_path": index_model._meta.storage_path, })
             w = pylucene.IndexWriter(**kwargs)
             w.index(
                 document.Document.create_document_from_object(index_model, obj),
                 uid=str(utils.get_uid(index_model._meta.model, obj.pk)),
             )
             w.close()
     except Exception, e :
         raise
         return False
예제 #17
0
def parse_tweet_obj(t, tweets):
    REPLY_KEY = 'in_reply_to_status_id_str'
    is_a_reply = REPLY_KEY in t and t[REPLY_KEY]

    t_id = t['id_str']
    tweets[t_id] = {
        'timestamp': utils.extract_ts_s(t['created_at']),
        'reply_id': t_id,
        'source': utils.get_uid(t),
        'interaction': 'IN_CONV',
        'target': None,
        'ot_id': None,
        'in_reply_to_t_id': t[REPLY_KEY] if is_a_reply else None,
        'in_reply_to_u_id':
        t['in_reply_to_user_id_str'] if is_a_reply else None
    }
예제 #18
0
 def func_index_update(self, obj, **kwargs):
     try:
         index_models = utils.get_index_models(obj)
         for index_model in index_models:
             kwargs.update({
                 "storage_path": index_model._meta.storage_path,
             })
             w = pylucene.IndexWriter(**kwargs)
             w.index(
                 document.Document.create_document_from_object(
                     index_model, obj),
                 uid=str(utils.get_uid(index_model._meta.model, obj.pk)),
             )
             w.close()
     except Exception, e:
         raise
         return False
예제 #19
0
def parse_tweet_obj(t, tweets):
    REPLY_KEY = 'in_reply_to_status_id_str'
    is_a_reply = REPLY_KEY in t and t[REPLY_KEY]

    t_id = t['id_str']
    tweets[t_id] = {
        'timestamp' : utils.extract_ts_s(t['created_at']),
        'reply_tid' : t_id,
        'source_uid' : utils.get_uid(t),
        'source_sn' : t['user']['screen_name'],
        'interaction' : 'IN_CONV',
        'target_tid' : None,
        'target_uid' : None,
        'orig_tid' : None,
        'in_reply_to_tid' : t[REPLY_KEY] if is_a_reply else None,
        'in_reply_to_uid' : t['in_reply_to_user_id_str'] if is_a_reply else None,
        'raw': t,
        'type': 'TWITTER'
    }
예제 #20
0
    def func_index(self, objs, **kwargs):
        if type(objs) not in (
                types.GeneratorType,
                iter([]).__class__,
        ):
            objs = iter([
                objs,
            ])

        try:
            for obj in objs:
                index_models = utils.get_index_models(obj)
                for index_model in index_models:
                    searcher = pylucene.Searcher(
                        storage_path=index_model._meta.storage_path, )
                    uid = utils.get_uid(
                        index_model._meta.model,
                        obj.pk,
                    )
                    doc = searcher.get_document_by_uid(uid)
                    if not doc:
                        uid = None

                    searcher.close()

                    kwargs.update({
                        "storage_path":
                        index_model._meta.storage_path,
                    })
                    w = pylucene.IndexWriter(**kwargs)
                    w.index(
                        document.Document.create_document_from_object(
                            index_model,
                            obj,
                        ),
                        uid=uid,
                    )
                    w.close()
        except Exception, e:
            raise
            return False
예제 #21
0
    def __init__(self, index_model, meta):
        # initialize
        self.casecade_delete = True
        self.exclude = tuple()
        self.model = None
        self.ordering = tuple()
        self.verbose_name = None
        self.verbose_name_plural = None
        self.analyzer = lucene.WhitespaceAnalyzer()
        self.field_analyzers = dict()

        self.index_model = index_model
        (
            self.index_model.local_attrs,
            __local_fields,
        ) = get_method_from_index_model_class(self.index_model)

        for i in dir(meta):
            if i.startswith("__") and i.endswith("__"):
                continue

            setattr(self, i, getattr(meta, i))

        if not hasattr(self, "model"):
            raise ImproperlyConfigured, "model must be set."

        if not self.verbose_name:
            self.verbose_name = self.model._meta.verbose_name

        if not self.verbose_name_plural:
            self.verbose_name_plural = self.model._meta.verbose_name_plural

        self.object_name = self.model._meta.object_name
        self.module_name = self.index_model.__class__.__name__
        self.app_label = self.model._meta.app_label

        self.model_name = "%s.%s" % (
            self.app_label,
            self.object_name,
        )

        pk_field = None
        self.fields = dict()
        self.fields_ordering = list()
        for f in self.model._meta.fields:
            if not isinstance(f, Field) or isinstance(f, ForeignKey):
                continue

            if f.name in self.exclude:
                continue

            (
                field_index,
                args,
                kwargs,
            ) = self.translate_model_field_to_index_field(f)

            if field_index is None:
                continue

            if f.name in __local_fields.keys():
                kk = __local_fields.get(f.name)
                if not hasattr(Fields, kk.__class__.__name__):
                    continue

                field_index = getattr(Fields, kk.__class__.__name__)
                kwargs.update(kk.__dict__)
            elif not field_index:
                continue

            fm = field_index(f.name, *args, **kwargs)
            self.fields[f.name] = fm

            if self.model._meta.pk.name == f.name:
                pk_field = fm
                self.pk = fm

            self.fields_ordering.append(f.name)
            self.field_analyzers[f.name] = fm.analyzer

            # Add sort field
            # For searching performance and reduce the index db size, TextField does not include in sort field,
            if f.__class__ not in constant.FIELDS_SKIP_TO_SORT:
                fs = Fields.Sort(fm)
                self.fields[fs.name] = fs
                self.field_analyzers[fs.name] = fs.analyzer

        # overwrite the fields from model and index_model
        for i in dir(index_model):
            f = getattr(index_model, i)
            if not isinstance(f, __INDEXFIELDBASE__):
                continue

            f.name = i
            (
                field_index,
                args,
                kwargs,
            ) = self.translate_custom_field_to_index_field(f)
            if field_index is None:
                continue

            fm = field_index(i, *args, **kwargs)
            self.fields[i] = fm

        ##################################################
        # Add default fields
        # pk field
        if pk_field:
            pk_field = Fields.Integer(
                constant.FIELD_NAME_PK,
                func_get_value_from_object=lambda obj, name: obj.pk,
                abstract=True,
            )
            self.fields[constant.FIELD_NAME_PK] = pk_field
            self.fields["pk"] = pk_field
            self.fields_ordering.append(pk_field.name)

        # uid field
        self.fields[constant.FIELD_NAME_UID] = Fields.Keyword(
            constant.FIELD_NAME_UID,
            func_get_value_from_object=lambda obj, name: utils.get_uid(
                obj, obj.pk),
            abstract=True,
        )

        # index model field
        self.fields[constant.FIELD_NAME_INDEX_MODEL] = Fields.Keyword(
            constant.FIELD_NAME_INDEX_MODEL,
            func_get_value_from_object=lambda obj, name: self.index_model.
            __class__.__name__,
            abstract=True,
        )

        # model field
        self.fields[constant.FIELD_NAME_MODEL] = Fields.Keyword(
            constant.FIELD_NAME_MODEL,
            func_get_value_from_object=lambda obj, name: utils.get_model_name(
                obj),
            abstract=True,
        )

        # unicode return field
        self.fields[constant.FIELD_NAME_UNICODE] = Fields.Keyword(
            constant.FIELD_NAME_UNICODE,
            func_get_value_from_object=lambda obj, name: unicode(obj),
            abstract=True,
        )

        self.fields_ordering.append(self.fields[constant.FIELD_NAME_UID].name)
        self.fields_ordering.append(
            self.fields[constant.FIELD_NAME_MODEL].name)
        self.fields_ordering.append(
            self.fields[constant.FIELD_NAME_UNICODE].name)

        self.fields_ordering = tuple(
            self.fields_ordering)  # make it immutable.
    def setUpClass(cls):
        cls.non_owner_data = {"username": get_uid(30), "password": "******"}
        cls.non_owner = User.objects.create_user(**cls.non_owner_data)

        cls.owner_data = {"username": get_uid(30), "password": "******"}
        cls.owner = User.objects.create_user(**cls.owner_data)
예제 #23
0
 def test_deactive_contract(self):
     if funcs.is_contract_activated(conf["2"]["url"], "CostContract",
                                    self.token) == True:
         self.deactivateContract()
     walletId = funcs.get_activated_wallet(conf["2"]["url"], "CostContract",
                                           self.token)
     sumsBefore = utils.getUserTokenAmounts(conf["1"]["dbHost"],
                                            conf["1"]["dbName"],
                                            conf["1"]["login"],
                                            conf["1"]["pass"])
     summBefore = sum(summ[0] for summ in sumsBefore)
     bNodeBalance = self.getNodeBalances()
     tokenRunner, uid = utils.get_uid(conf["2"]["url"])
     signature = sign(keys["key2"], uid)
     pubRunner = get_public_key(keys["key2"])
     balanceRunnerB = utils.get_balance_from_db_by_pub(
         conf["1"]["dbHost"], conf["1"]["dbName"], conf["1"]["login"],
         conf["1"]["pass"], pubRunner)
     dataRunner = utils.login(conf["2"]["url"], keys["key2"], 0)
     tokenRunner = dataRunner["jwtToken"]
     res = utils.call_contract(conf["2"]["url"], keys["key2"],
                               "CostContract", {"State": 1}, tokenRunner)
     result = utils.txstatus(conf["2"]["url"],
                             conf["2"]["time_wait_tx_in_block"],
                             res["hash"], tokenRunner)
     time.sleep(10)
     node = utils.get_block_gen_node(conf["1"]["dbHost"],
                                     conf["1"]["dbName"],
                                     conf["1"]["login"], conf["1"]["pass"],
                                     result["blockid"])
     sumsAfter = utils.getUserTokenAmounts(conf["1"]["dbHost"],
                                           conf["1"]["dbName"],
                                           conf["1"]["login"],
                                           conf["1"]["pass"])
     summAfter = sum(summ[0] for summ in sumsAfter)
     aNodeBalance = self.getNodeBalances()
     nodeCommission = 141620000000000000
     platformaCommission = 4380000000000000
     commission = nodeCommission + platformaCommission
     balanceRunnerA = utils.get_balance_from_db_by_pub(
         conf["1"]["dbHost"], conf["1"]["dbName"], conf["1"]["login"],
         conf["1"]["pass"], pubRunner)
     balanceContractOwnerA = utils.get_balance_from_db(
         conf["1"]["dbHost"], conf["1"]["dbName"], conf["1"]["login"],
         conf["1"]["pass"], walletId)
     inHistory = self.isCommissionsInHistory(nodeCommission,
                                             dataRunner["key_id"],
                                             platformaCommission, node)
     if node == 0:
         dictValid = dict(balanceRunner=balanceRunnerA,
                          platformBalance=aNodeBalance[0],
                          summ=summBefore,
                          history=inHistory)
         dictExpect = dict(balanceRunner=balanceRunnerB - commission,
                           platformBalance=bNodeBalance[0] + commission,
                           summ=summAfter,
                           history=True)
     else:
         dictValid = dict(balanceRunner=balanceRunnerA,
                          platformBalance=aNodeBalance[0],
                          nodeBalance=aNodeBalance[node],
                          summ=summBefore,
                          history=inHistory)
         dictExpect = dict(balanceRunner=balanceRunnerB - commission,
                           platformBalance=bNodeBalance[0] +
                           platformaCommission,
                           nodeBalance=bNodeBalance[node] + nodeCommission,
                           summ=summAfter,
                           history=True)
     self.assertDictEqual(dictValid, dictExpect,
                          "Error in comissions run deactivated contract")
예제 #24
0
 def test_deactive_contract_with_err(self):
     if funcs.is_contract_activated(conf["2"]["url"], "CostContract",
                                    self.token) == True:
         self.deactivateContract()
     walletId = funcs.get_activated_wallet(conf["2"]["url"], "CostContract",
                                           self.token)
     balanceContractOwnerB = utils.get_balance_from_db(
         conf["1"]["dbHost"], conf["1"]["dbName"], conf["1"]["login"],
         conf["1"]["pass"], walletId)
     balanceNodeOwnerB = utils.get_balance_from_db(conf["1"]["dbHost"],
                                                   conf["1"]["dbName"],
                                                   conf["1"]["login"],
                                                   conf["1"]["pass"],
                                                   conf["2"]["keyID"])
     commisionWallet = utils.get_commission_wallet(conf["1"]["dbHost"],
                                                   conf["1"]["dbName"],
                                                   conf["1"]["login"],
                                                   conf["1"]["pass"], 1)
     balanceCommisionB = utils.get_balance_from_db(conf["1"]["dbHost"],
                                                   conf["1"]["dbName"],
                                                   conf["1"]["login"],
                                                   conf["1"]["pass"],
                                                   commisionWallet)
     commission = utils.get_system_parameter(conf["1"]["dbHost"],
                                             conf["1"]["dbName"],
                                             conf["1"]["login"],
                                             conf["1"]["pass"],
                                             "commission_size")
     tokenRunner, uid = utils.get_uid(conf["2"]["url"])
     signature = sign(keys["key2"], uid)
     pubRunner = get_public_key(keys["key2"])
     balanceRunnerB = utils.get_balance_from_db_by_pub(
         conf["1"]["dbHost"], conf["1"]["dbName"], conf["1"]["login"],
         conf["1"]["pass"], pubRunner)
     dataRunner = utils.login(conf["2"]["url"], keys["key2"], 0)
     tokenRunner = dataRunner["jwtToken"]
     res = utils.call_contract(conf["2"]["url"], keys["key2"],
                               "CostContract", {"State": 0}, tokenRunner)
     time.sleep(10)
     hash = res["hash"]
     result = utils.txstatus(conf["2"]["url"],
                             conf["2"]["time_wait_tx_in_block"], hash,
                             tokenRunner)
     balanceContractOwnerA = utils.get_balance_from_db(
         conf["1"]["dbHost"], conf["1"]["dbName"], conf["1"]["login"],
         conf["1"]["pass"], walletId)
     balanceNodeOwnerA = utils.get_balance_from_db(conf["1"]["dbHost"],
                                                   conf["1"]["dbName"],
                                                   conf["1"]["login"],
                                                   conf["1"]["pass"],
                                                   conf["2"]["keyID"])
     balanceCommisionA = utils.get_balance_from_db(conf["1"]["dbHost"],
                                                   conf["1"]["dbName"],
                                                   conf["1"]["login"],
                                                   conf["1"]["pass"],
                                                   commisionWallet)
     balanceRunnerA = utils.get_balance_from_db_by_pub(
         conf["1"]["dbHost"], conf["1"]["dbName"], conf["1"]["login"],
         conf["1"]["pass"], pubRunner)
     dictValid = dict(balanceContractOwner=balanceContractOwnerA,
                      balanceNodeOwner=balanceNodeOwnerA,
                      balanceCommision=balanceCommisionA,
                      balanceRunner=balanceRunnerA)
     dictExpect = dict(balanceContractOwner=balanceContractOwnerB,
                       balanceNodeOwner=balanceNodeOwnerB,
                       balanceCommision=balanceCommisionB,
                       balanceRunner=balanceRunnerB)
     msg = "balanceContractOwnerA:" + str(balanceContractOwnerA) + "\n" +\
     "balanceContractOwnerE:" + str(balanceContractOwnerB) + "\n" +\
     "balanceNodeOwnerA:" + str(balanceNodeOwnerA) + "\n" +\
     "balanceNodeOwnerE:" + str(balanceNodeOwnerB) + "\n" +\
     "balanceCommisionA:" + str(balanceCommisionA) + "\n" +\
     "balanceCommisionE:" + str(balanceCommisionB) + "\n" +\
     "balanceRunnerA:" + str(balanceRunnerA) + "\n" +\
     "balanceRunnerE:" + str(balanceRunnerB) + "\n"
     self.assertDictEqual(dictValid, dictExpect, msg)