예제 #1
0
 def __init__(self,
              callback,
              options={},
              attrs={},
              choices=(),
              fk_field_name=None):
     self.fk_field_name = fk_field_name
     self.options = None
     self.callback = callback
     self.attrs = {'autocomplete': 'off'}
     if len(options) > 0:
         self.options = JSONEncoder().encode(options)
     self.attrs.update(attrs)
     self.choices = list(choices)
예제 #2
0
    def exclusion_note(self, metrics_in_error: dict, git: GitUtils,
                       logger: Logger):
        logger.info(
            'Please consult the above warnings and errors concerning discrepancies in your build compared to '
            'latest build.')
        answer = input('Do you want to accept the violations (Yes/No)? [No]: ')
        if not answer.upper() == 'YES':
            logger.info('I am treating this as a No (you typed: "%s").' %
                        answer)
            logger.error('Failing because of metrics increase.')
            return Callable.do_not_proceed

        reason = ''
        while not reason.strip():
            reason = input(
                'Provide a nonempty commit message (reason) for the increase [""]: '
            )

        username = '******' % (git.get_config_by_key('user.name'),
                                git.get_config_by_key('user.email'))
        metrics = {}
        for key, value in metrics_in_error.items():
            metrics[key] = value['is']
        exclusion = {
            'reason': reason,
            'committer': username,
            'exclusion': metrics
        }

        note = JSONEncoder().encode(exclusion)

        if git.put_notes(note, STATS_EXCLUSION_REF_NAME,
                         'HEAD') != Callable.success:
            logger.error(
                'Error encountered while setting note. Consult above messages if any.'
            )
            return Callable.do_not_proceed

        if git.push_notes(STATS_EXCLUSION_REF_NAME) != Callable.success:
            logger.error(
                'Error encountered while pushing notes. Consult above messages if any.'
            )
            return Callable.do_not_proceed

        logger.info('The exclusion note has been pushed.')
        logger.warn(
            'Remember to push your commit. DO NOT rebase (use merge instead) or the exclusion will be lost.'
        )

        return Callable.success
예제 #3
0
 def client_left_session(self):
     try:
         self.client.call(JSONEncoder().encode({
             "method": "client_left_session",
             "params": {
                 "session_id": self.__session_id,
                 "client_id": self.__client_id
             }
         }))
         self.__session_id = None
         self.__broadcast_receiver.session_id = None
         return {}
     except Exception as e:
         return {'error': e}
예제 #4
0
def load_dataset(dataset_dir: Path, as_numpy: bool = False):
    dataset_dir = Path(dataset_dir)

    train_annotations_file = dataset_dir / 'digitStruct.json'
    digits_struct_file = dataset_dir / 'digitStruct.mat'
    dataset_pkl_file = dataset_dir / (dataset_dir.name + ".pkl")

    if dataset_pkl_file.exists():
        dataset_np = pickle.load(dataset_pkl_file.open("rb"))
        print(
            f"Loaded {dataset_pkl_file.name} dataset from existing pickle file. N={len(dataset_np)}"
        )
    else:
        if not digits_struct_file.exists():
            raise FileExistsError(f"Cannot open {digits_struct_file}")

        if not train_annotations_file.exists():
            print(f"Parsing {digits_struct_file}, this may take a while")
            dsf = DigitStructFile(str(digits_struct_file))
            annotations = dsf.load()
            fout = open(train_annotations_file, 'w')
            fout.write(JSONEncoder(indent=True).encode(annotations))
            fout.close()
        else:
            print(
                f"Loading existing JSON annotations from {train_annotations_file}"
            )
            with open(train_annotations_file, 'r') as file:
                annotations = json.load(file)

        print(f"Loaded annotations for {len(annotations)} images")
        print(f"Loading images ... ")
        images = {
            Path(p).name: np.array(Image.open(p))
            for p in tqdm(glob(f"{dataset_dir}/*.png"))
        }
        dataset_np = prepare_dataset(images, annotations, dataset_pkl_file)

    num_examples = len(dataset_np)
    if as_numpy:
        return dataset_np, num_examples

    def dataset_generator(svhn_dataset):
        for element in svhn_dataset:
            yield element

    dataset = tf.data.Dataset.from_generator(
        lambda: dataset_generator(dataset_np), ImageData.dataset_dtypes(),
        ImageData.dataset_shapes())
    return dataset, num_examples
예제 #5
0
def get_business_by_id(business_id):
    """
    Locate a business by its business_id.
    :param business_id: String
    :return: Http Response
    """

    app.logger.info("get_business_by_id with business_id: {}".format(business_id))

    # First check that we have a valid JWT token if we don't send a 400 error with authorisation failure
    if request.headers.get('authorization'):
        jwt_token = request.headers.get('authorization')
        if not validate_scope(jwt_token, 'ps.read'):
            res = Response(response="Invalid token/scope to access this Microservice Resource", status=400, mimetype="text/html")
            return res
    else:
        res = Response(response="Valid token/scope is required to access this Microservice Resource", status=400, mimetype="text/html")
        return res

    # if not validate_uri(business_id, 'business'):
    #     res = Response(response="Invalid URI", status=404, mimetype="text/html")
    #     return res

    try:
        app.logger.debug("Querying DB in get_business_by_id")

        app.logger.debug("Querying DB with business_id:{}".format(business_id))

        object_list = [[rec.business_ref, rec.party_id, rec.name, rec.trading_name,
                        rec.enterprise_name, rec.contact_name, rec.address_line_1,
                        rec.address_line_2, rec.address_line_3, rec.city, rec.postcode,
                        rec.telephone, rec.employee_count, rec.facsimile, rec.fulltime_count,
                        rec.legal_status, rec.sic_2003, rec.sic_2007, rec.turnover]
                       for rec in
                       Business.query
                       .filter(Business.party_id == business_id)]

    except exc.OperationalError:
        app.logger.error("DB exception: {}".format(sys.exc_info()[0]))
        response = Response(response="Error in the Party DB.", status=500, mimetype="text/html")
        return response

    if not object_list:
        app.logger.info("Object list is empty for get_business_by_id")
        response = Response(response="Business(es) not found", status=404, mimetype="text/html")
        return response

    jobject_list = JSONEncoder().encode(object_list)
    response = Response(response=jobject_list, status=200, mimetype="collection+json")
    return response
예제 #6
0
 def __init__(self, proto, env):
     """Overloaded constructor."""
     # Link protocol
     self.protocol = proto
     self.env = env
     # Init server data
     self.clients = []
     self.named_clients = {}
     self.games = {}
     # Init decoders
     self.json_decoder = JSONDecoder()
     self.json_encoder = JSONEncoder()
     # Init configs
     serverfuncts.configLog(self.env.log_path + '/server.log')
예제 #7
0
파일: plugin.py 프로젝트: pymmrd/dexsim
 def get_json_item(cls_name, mtd_name, args):
     """
     json item 为一个json格式的解密对象。
     包含id、className、methodName、arguments。
     模拟器/手机会通过解析这个对象进行解密。
     """
     item = {
         'className': cls_name,
         'methodName': mtd_name,
         'arguments': args
     }
     item['id'] = hashlib.sha256(
         JSONEncoder().encode(item).encode('utf-8')).hexdigest()
     return item
예제 #8
0
파일: __init__.py 프로젝트: Vi-l-uc/TeleBot
    def __init__(
        self,
        client,
        version=None,
        decoder=JSONDecoder(),
        encoder=JSONEncoder(),
    ):
        """
        Create a client for talking to json.

        :param decoder:
        :type json.JSONDecoder: An instance of json.JSONDecoder

        :param encoder:
        :type json.JSONEncoder: An instance of json.JSONEncoder
        """
        # Set the module commands' callbacks
        self.MODULE_CALLBACKS = {
            "JSON.CLEAR": int,
            "JSON.DEL": int,
            "JSON.FORGET": int,
            "JSON.GET": self._decode,
            "JSON.MGET": bulk_of_jsons(self._decode),
            "JSON.SET": lambda r: r and nativestr(r) == "OK",
            "JSON.NUMINCRBY": self._decode,
            "JSON.NUMMULTBY": self._decode,
            "JSON.TOGGLE": self._decode,
            "JSON.STRAPPEND": self._decode,
            "JSON.STRLEN": self._decode,
            "JSON.ARRAPPEND": self._decode,
            "JSON.ARRINDEX": self._decode,
            "JSON.ARRINSERT": self._decode,
            "JSON.ARRLEN": self._decode,
            "JSON.ARRPOP": self._decode,
            "JSON.ARRTRIM": self._decode,
            "JSON.OBJLEN": self._decode,
            "JSON.OBJKEYS": self._decode,
            "JSON.RESP": self._decode,
            "JSON.DEBUG": self._decode,
        }

        self.client = client
        self.execute_command = client.execute_command
        self.MODULE_VERSION = version

        for key, value in self.MODULE_CALLBACKS.items():
            self.client.set_response_callback(key, value)

        self.__encoder__ = encoder
        self.__decoder__ = decoder
예제 #9
0
파일: tools.py 프로젝트: rishiloyola/WMCore
 def wrapper(self, *args, **kwds):
     """Decorator wrapper"""
     cherrypy.response.headers['Content-Type'] = "application/json"
     func._cp_config = {'response.stream': True}
     head, data = func(self, *args, **kwds)
     yield json.dumps(head)[:-1]  # do not yield }
     yield ', "data": ['
     if isinstance(data, dict):
         for chunk in JSONEncoder().iterencode(data):
             yield chunk
     elif isinstance(data, list) or isinstance(data, types.GeneratorType):
         sep = ''
         for rec in data:
             if sep:
                 yield sep
             for chunk in JSONEncoder().iterencode(rec):
                 yield chunk
             if not sep:
                 sep = ', '
     else:
         msg = 'jsonstreamer, improper data type %s' % type(data)
         raise Exception(msg)
     yield ']}'
예제 #10
0
def add_quest():
    from services.content_manager import create_quest
    name = request.form["name"]
    quest_type = request.form["quest_type"]
    public_accessibility = int(request.form["public_accessibility"])
    cid = request.form["cid"]
    try:
        code = create_quest(session.get('uid'), name, quest_type,
                            public_accessibility, cid)
    except Exception:
        code = 500
        abort(500)
    response = {'code': code}
    return JSONEncoder().encode(response)
예제 #11
0
 def process_game_move(self, move):
     try:
         self.client.call(JSONEncoder().encode({
             "method": "process_game_move",
             "params": {
                 "session_id": self.__session_id,
                 "client_id": self.__client_id,
                 "move": move
             }
         }))
         return {}
     except Exception as e:
         print(e)
         return {'error': e}
예제 #12
0
파일: tasks.py 프로젝트: eccstartup/timepaw
def sync_renren_status(did, page, new_latest):
    d = DataSource.objects.get(pk=did)
    info = JSONDecoder().decode(d.auth_info)
    sig_calc = u"access_token=%scount=1000format=jsonmethod=status.getspage=%suid=%sv=1.0%s" % (
        info['access_token'], page, info['user']['id'], RENREN_SECRET)
    sig = calc_md5(sig_calc)
    statues_url = "http://api.renren.com/restserver.do?method=status.gets&v=1.0&access_token=%s&count=1000&format=json&page=%s&uid=%s&sig=%s" % (
        info['access_token'], page, info['user']['id'], sig)
    statues = JSONDecoder().decode(urllib2.urlopen(statues_url, "").read())
    if statues:
        if (page == 1):
            new_latest = statues[0]['status_id']
        for status in statues:
            if info.has_key('latest_status'
                            ) and status['status_id'] == info['latest_status']:
                info['latest_status'] = new_latest
                d.auth_info = JSONEncoder().encode(info)
                d.save(force_update=True)
                sync_renren_status.apply_async(args=[did, 1, None],
                                               countdown=84600)
                sync_renren_albums.apply_async(args=[d.id, 1], countdown=1)
                break
            p = Paw.objects.create(source=d,\
                                   type="renren status",\
                                   content=status['message'],\
                                   create_time=datetime.strptime(status['time'], "%Y-%m-%d %H:%M:%S"))
        if not (info.has_key('latest_status')
                and status['status_id'] == info['latest_status']):
            sync_renren_status.apply_async(args=[did, page + 1, new_latest],
                                           countdown=60)
    else:
        if new_latest is not None:
            info['latest_status'] = new_latest
        d.auth_info = JSONEncoder().encode(info)
        d.save(force_update=True)
        sync_renren_status.apply_async(args=[did, 1, None], countdown=84600)
        sync_renren_albums.apply_async(args=[d.id, 1], countdown=1)
예제 #13
0
    def generate(self):
        """
        :return: `None`.

        """
        configuration = app.Configuration(self)

        try:
            with ldap3.Connection(
                    configuration.server,
                    read_only=True,
                    raise_exceptions=True,
                    user=configuration.credentials.username,
                    password=configuration.credentials.password) as connection:

                attribute_names = app.get_normalized_attribute_names(
                    self.attrs, connection, configuration)

                entry_generator = connection.extend.standard.paged_search(
                    search_base=self.basedn,
                    search_filter=self.search,
                    search_scope=self.scope,
                    attributes=self.attrs,
                    paged_size=configuration.paged_size)

                encoder = JSONEncoder(ensure_ascii=False,
                                      separators=(',', ':'))
                time_stamp = time()
                serial_number = 0

                for entry in entry_generator:
                    attributes = app.get_attributes(self, entry)
                    if attributes:
                        dn = entry['dn']
                        yield LdapSearchCommand._record(
                            serial_number, time_stamp, connection.server.host,
                            dn, attributes, attribute_names, encoder)
                        serial_number += 1
                    if self.limit and serial_number == self.limit:
                        break
                    pass

                pass

        except ldap3.LDAPException as error:
            self.error_exit(error,
                            app.get_ldap_error_message(error, configuration))

        return
예제 #14
0
    def command(self, cmd, block=False, test=lambda: True,
                 timeout=0.0, args=None):
        """
        Raw command call to directly control gripper.

        @type cmd: str
        @param cmd: string of known gripper commands
        @type block: bool
        @param block: command is blocking or non-blocking [False]
        @type test: func
        @param test: test function for command validation
        @type timeout: float
        @param timeout: timeout in seconds for command evaluation
        @type args: dict({str:float})
        @param args: dictionary of parameter:value
        """
        ee_cmd = EndEffectorCommand()
        ee_cmd.id = self.hardware_id()
        ee_cmd.command = cmd
        ee_cmd.sender = self._cmd_sender % (cmd,)
        ee_cmd.sequence = self._inc_cmd_sequence()
        ee_cmd.args = ''
        if args != None:
            ee_cmd.args = JSONEncoder().encode(args)
        seq_test = lambda: (self._state.command_sender == ee_cmd.sender and
                            (self._state.command_sequence == ee_cmd.sequence
                             or self._state.command_sequence == 0))
        self._cmd_pub.publish(ee_cmd)
        if block:
            finish_time = rospy.get_time() + timeout
            cmd_seq = baxter_dataflow.wait_for(
                          test=seq_test,
                          timeout=timeout,
                          raise_on_error=False,
                          body=lambda: self._cmd_pub.publish(ee_cmd)
                      )
            if not cmd_seq:
                seq_msg = (("Timed out on gripper command acknowledgement for"
                           " %s:%s") % (self.name, ee_cmd.command))
                rospy.logdebug(seq_msg)
            time_remain = max(0.5, finish_time - rospy.get_time())
            return baxter_dataflow.wait_for(
                       test=test,
                       timeout=time_remain,
                       raise_on_error=False,
                       body=lambda: self._cmd_pub.publish(ee_cmd)
                   )
        else:
            return True
예제 #15
0
def Format(root, lang='en', output_dir='.'):
    """Format the messages as JSON."""
    yield '{\n'

    encoder = JSONEncoder()
    format = ('  "%s": {\n' '    "message": %s%s\n' '  }')
    placeholder_format = ('      "%i": {\n'
                          '        "content": "$%i"\n'
                          '      }')
    first = True
    for child in root.ActiveDescendants():
        if isinstance(child, message.MessageNode):
            id = child.attrs['name']
            if id.startswith('IDR_') or id.startswith('IDS_'):
                id = id[4:]

            translation_missing = child.GetCliques()[0].clique.get(
                lang) is None
            if (child.ShouldFallbackToEnglish() and translation_missing
                    and lang != constants.FAKE_BIDI):
                # Skip the string if it's not translated. Chrome will fallback
                # to English automatically.
                continue

            loc_message = encoder.encode(child.ws_at_start +
                                         child.Translate(lang) +
                                         child.ws_at_end)

            # Replace $n place-holders with $n$ and add an appropriate "placeholders"
            # entry. Note that chrome.i18n.getMessage only supports 9 placeholders:
            # https://developer.chrome.com/extensions/i18n#method-getMessage
            placeholders = ''
            for i in range(1, 10):
                if loc_message.find('$%d' % i) == -1:
                    break
                loc_message = loc_message.replace('$%d' % i, '$%d$' % i)
                if placeholders:
                    placeholders += ',\n'
                placeholders += placeholder_format % (i, i)

            if not first:
                yield ',\n'
            first = False

            if placeholders:
                placeholders = ',\n    "placeholders": {\n%s\n    }' % placeholders
            yield format % (id, loc_message, placeholders)

    yield '\n}\n'
예제 #16
0
 def updateFromWMSpec(self, spec):
     # currently only update priority and siteWhitelist and output dataset
     # complex field needs to be JSON encoded
     # assuming all the toplevel tasks has the same site white lists
     #priority is priority + user priority + group priority
     fields = {
         'priority': spec.priority(),
         'site_white_list': spec.getTopLevelTask()[0].siteWhitelist(),
         'outputdatasets': spec.listOutputDatasets()
     }
     return self.couchDB.updateDocument(
         spec.name(),
         self.couchapp,
         'generalFields',
         fields={'general_fields': JSONEncoder().encode(fields)})
예제 #17
0
def activesubCandidates():
    pg = request.params[support.FieldDict['PAGE']]
    sortFilter = request.params[support.FieldDict['SEARCHMODE']]
    sortOrder = request.params[support.FieldDict['SORTORDER']]
    sortOn = request.params[support.FieldDict['SORTON']]
    sortData = None
    if support.FieldDict['SORTDATA'] in request.params:
        sortData = request.params[support.FieldDict['SORTDATA']]
    reqObj = {
        support.FieldDict['PAGE']: int(pg),
        support.FieldDict['SEARCHMODE']: int(sortFilter),
        support.FieldDict['SORTORDER']: int(sortOrder),
        support.FieldDict['SORTON']: int(sortOn)
    }
    if sortData is not None:
        reqObj[support.FieldDict['SORTDATA']] = sortData
    adid = request.get_header(support.FieldHeaderDict['ADID'], None)
    if adid is None:
        return None
    #userId = request.get_header(support.FieldDict['MODELID'], None)
    #if userId is None:
    #	return None
    data = JSONEncoder().encode(reqObj)
    print data
    msg = JSONEncoder().encode({
        support.FieldDict['APIMETHOD']:
        support.ApiMethods1.Api_ActiveSubCandidates.value - 1,
        support.FieldDict['ADID']:
        adid,
        support.FieldDict['DATA']:
        data
    })

    token = msgMgr.send(msg)
    print token
    return token
예제 #18
0
    def __init__(self, exception_object):
        if AppfluxException.before != []:
            for before_callback in AppfluxException.before:
                before_callback(exception_object,
                                exception_object.global_attributes)

        json_response = exception_object.process_default_exception_data()
        json_response['app_id'] = exception_object.app_id

        if AppfluxException.after != []:
            for after_callback in AppfluxException.after:
                after_callback(exception_object,
                               exception_object.global_attributes)

        self.send(JSONEncoder().encode(json_response))
예제 #19
0
def basic_risks_run():
    valuation_time = datetime.now()
    pricing_environment = PE_DEFAULT_INTRADAY
    headers = utils.login(ip, login_body)
    r = utils.get_redis_conn(ip)
    position_result = r.get(INTRADAY_BASIC_POSITIONS)
    positions = JSONDecoder().decode(bytes.decode(position_result))
    expiring_result = r.get(INTRADAY_BASIC_EXPIRING)
    expirings = JSONDecoder().decode(bytes.decode(expiring_result))
    risk = basic_risks.get_risks([positions, expirings], pricing_environment,
                                 valuation_time, ip, headers)[0]
    risk_result = JSONEncoder().encode(risk)

    r.set(INTRADAY_BASIC_RISKS, str(risk_result))
    print('Basic Risk Data Has Save To Redis')
예제 #20
0
 def default(self, o):
     if hasattr(o, 'to_json'):
         return getattr(o, 'to_json')()
     elif isinstance(o, set):
         return sorted(list(o))
     elif isinstance(o, timedelta):
         return o.seconds
     # Convert generators to list
     try:
         iterable = iter(o)
     except TypeError:
         pass
     else:
         return list(iterable)
     return JSONEncoder().default(o)
예제 #21
0
def getMiProximoColectivoController():
    start = datetime.datetime.now()
    params = request.args.get('bbox')
    url = 'https://miproximocolectivo.sanluis.gob.ar/MiProximoColectivo/GetMapMovilRecorrido?bbox=%s,%s,%s,%s' % (
        params[0], params[1], params[2], params[3])
    headers = {'Content-type': 'application/json'}
    response = requests.get(url, headers=headers)
    result = response.text
    end = datetime.datetime.now()
    final = end - start
    buses = filter(result)
    bs = parseObject(buses)

    print("time -> getMiProximoColectivoController: %s" % final)
    return JSONEncoder().encode(bs)
예제 #22
0
def discovery(data):
  """Converts a Python dict into a Zabbix LLD JSON string"""

  from json import JSONEncoder
  lld_data = { 'data': [] }
  for item in data:
    lld_item = {}
    for key, val in item.items():
      if val:
        lld_item[macro_name(key)] = str(val)

    if lld_item:
      lld_data['data'].append(lld_item)

  return JSONEncoder().encode(lld_data)
예제 #23
0
 def callback(self):
     try:
         #TODO support jinja template to format callback payload
         self.callback_payload = JSONEncoder().encode({
             "timestamp":
             int(time()),
             "name":
             self.name,
             "triggering_payload":
             self.triggering_payloads
         })
         logging.info('Triggered rule \'' + self.name + '\'')
         self.mqtt_client.publish(self.output_topic, self.callback_payload)
     except Exception as e:
         logging.error('Error in Rule.callback: ' + str(e))
예제 #24
0
    def __init__(self, addr):
        """
        :param Tuple[str, int] addr:
        """
        self.acceptor = None
        self.addr = addr

        # TODO move to executor?
        self.encoder = JSONEncoder(separators=(',', ':'),
                                   default=lambda x: x.as_json_object())

        dependencies = get_dependencies()
        dependencies.update({T.__name__: T for T in (ExternalException, )})
        self.decoder = JSONDecoder(
            object_hook=self._get_object_hook_handler(dependencies))
예제 #25
0
def parseResults(results):
    numRes = results.total
    titles = []
    paths = []
    contents = []
    if numRes >= 0:
        for hit in results:
            title = hit["title"].encode('utf-8')
            path = hit["path"].encode('utf-8')
            content = hit.highlights("content").encode('utf-8')

            titles.append(title)
            paths.append(path)
            contents.append(content)

        normTitles = JSONEncoder().encode(titles)
        normPaths = JSONEncoder().encode(paths)
        normContents = str(
            JSONEncoder().encode(contents)
        )  ##Not sure if str() is necessary. JSONEncoder() may return other formats
        # print normPaths

        # normTitles=', '.join(['"{}"'.format(value) for value in titles])
        # normPaths=', '.join(['"{}"'.format(value) for value in paths])
        # normContents=str(contents)

        numPages = results.pagecount
        resPerPage = results.pagelen
        currentPage = results.pagenum
        runtime = results.results.runtime

        resObj = '{"NumResults":' + str(numRes) + ', "NumPages":' + str(
            numPages) + ', "Runtime":' + str(
                runtime) + ', "ResPerPage":' + str(
                    resPerPage) + ', "CurrentPage":' + str(currentPage) + '}'
        return '{"Titles":' + normTitles + ',"Paths":' + normPaths + ',"Contents":' + normContents + ', "Result":' + resObj + '}'
예제 #26
0
def get_active_users(request):
    """
    Retrieves a list of active users which is returned as plain JSON for
    easier manipulation with JavaScript.
    """
    if request.is_ajax():
        active = Visitor.objects.active().reverse()
        now = timezone.now()

        # we don't put the session key or IP address here for security reasons
        try:
            data = {
                'users': [
                    {
                        'id':
                        v.id,
                        #'user': uc(v.user),
                        'user_agent':
                        uc(v.user_agent),
                        'referrer':
                        uc(v.referrer),
                        'url':
                        uc(v.url),
                        'page_views':
                        v.page_views,
                        'geoip':
                        v.geoip_data_json,
                        'last_update': (now - v.last_update).seconds,
                        'friendly_time':
                        ', '.join(friendly_time(
                            (now - v.last_update).seconds)),
                    } for v in active
                ]
            }
        except:
            log.error(
                'There was a problem putting all of the visitor data together:\n%s\n\n%s'
                % (traceback.format_exc(), locals()))
            return HttpResponse(content='{}', mimetype='text/javascript')

        response = HttpResponse(content=JSONEncoder().encode(data),
                                mimetype='text/javascript')
        response['Content-Length'] = len(response.content)

        return response

    # if the request was not made via AJAX, raise a 404
    raise Http404
예제 #27
0
    def runTest(self):
        #Create an object and set some values
        test1 = CounterTestContainer(None)
        test1id = test1.id

        self.dc.AddDocumentObject(test1)
        test1.testcounter.add(1)
        self.assertEqual(test1.testcounter.get(), 1)

        olddc = self.dc

        sharedcurrentnode = test1.currentnode
        #Simulate sending the object to another user via conversion to JSON and emailing
        jsontext = self.dc.asJSON()

        #Simulate making local conflicting changes
        test1.testcounter.subtract(1)
        self.assertEqual(test1.testcounter.get(), 0)

        #Simulate the other user (who received the email with the edges) getting the document and loading it into memory
        self.dc = DocumentCollection()
        self.dc.Register(CounterTestContainer)
        self.dc.LoadFromJSON(jsontext)
        self.assertEqual(jsontext, self.dc.asJSON())
        tpo1s = self.dc.GetByClass(CounterTestContainer)
        self.assertEqual(len(tpo1s), 1)
        test2 = tpo1s[0]

        self.assertEqual(sharedcurrentnode, test2.currentnode)
        #The second user makes some changes and sends them back to the first
        test2.testcounter.add(1)
        self.assertEqual(test2.testcounter.get(), 2)

        edgenext = test2.history.edgesbyendnode[test2.currentnode]

        #Simulate the first user received the second users changes out of order
        #the second edge is received first. Test it is right
        self.dc = olddc
        self.dc.LoadFromJSON(JSONEncoder().encode({
            "history": [edgenext.asTuple()],
            "immutableobjects": []
        }))
        test2s = self.dc.GetByClass(CounterTestContainer)
        self.assertEqual(len(test2s), 1)
        test2 = test2s[0]
        #print "test2 edges=",[str(edge) for edge in test2.history.GetAllEdges()]

        self.assertEqual(test2.testcounter.get(), 1)
예제 #28
0
def real_time_pnl_pd_run():
    r = utils.get_redis_conn(redis_ip)
    risk_result = r.get(INTRADAY_BASIC_RISKS)
    risk = pd.read_msgpack(risk_result)

    underlyer_position_result = r.get(INTRADAY_BASIC_UNDELRYER_POSITION)
    underlyer_position = pd.read_msgpack(underlyer_position_result)

    list_position_result = r.get(INTRADAY_BASIC_LISTED_OPTION_POSITION)
    list_position = pd.read_msgpack(list_position_result)

    cash_flow_today_result = r.get(INTRADAY_BASIC_CASH_FLOW_TODAY)
    cash_flow_today = pd.read_msgpack(cash_flow_today_result)

    live_position_index_result = r.get(INTRADAY_BASIC_POSITION_INDEX)
    live_position_index = pd.read_msgpack(live_position_index_result)

    today_terminated_position_index_result = r.get(
        INTRADAY_BASIC_TERMINATED_POSITION_INDEX)
    today_terminated_position_index = pd.read_msgpack(
        today_terminated_position_index_result)

    now_date = datetime.now().date()
    yst_date = now_date + timedelta(days=-1)
    yst_params = {
        'reportName': POSITION_REPORT,
        'valuationDate': str(yst_date)
    }
    headers = utils.login(ip, login_body)
    yst_position = utils.call_request(ip, 'report-service',
                                      'rptLatestPositionReportByNameAndDate',
                                      yst_params, headers)['result']
    yst_params['reportName'] = HST_PNL_REPORT
    yst_historical_pnl = utils.call_request(
        ip, 'report-service', 'rptLatestPnlHstReportByNameAndDate', yst_params,
        headers)['result']
    yst_position = pd.DataFrame(yst_position)
    yst_historical_pnl = pd.DataFrame(yst_historical_pnl)
    pe_description = utils.get_pricing_env_description(PE_DEFAULT_INTRADAY, ip,
                                                       headers)
    reports = intraday_daily_pnl_by_underlyer_report_pd.intraday_daily_pnl_by_underlyer_report(
        risk, cash_flow_today, underlyer_position, list_position,
        live_position_index, today_terminated_position_index, yst_position,
        yst_historical_pnl, pe_description)
    reports = utils.remove_nan_and_inf(reports.to_dict(orient='records'))
    pnl_result = JSONEncoder().encode(reports)
    r.set(PNL_QUEUE, str(pnl_result))
    r.publish(PNL_QUEUE, str(pnl_result))
예제 #29
0
def callback(ch, method, properties, body):
    #config = argv[1] if len(argv) > 1 else '{"duration":10}'
    params = JSONDecoder().decode(body) 
    duration = params["duration"]

    # initialize BPF
    b = BPF(text = bpf_text())
    # read events
    b["ipv4_events"].open_perf_buffer(capture_ipv4_event)

    start_time = time()
    while ((time() - start_time) < duration):
        b.kprobe_poll(timeout=100)

    doc = JSONEncoder().encode(events)
    send_msg(doc)
예제 #30
0
def json_settings():
    from json import JSONEncoder

    def _default(self, obj):
        if type(obj) in [ datetime.datetime, datetime.timedelta,datetime.date ]:
            return serialize_time(obj)
        if isinstance(obj,unittest.mock.MagicMock):
            return str(obj)
        try:
            ret=getattr(obj.__class__, "__serialize__", _default.default)(obj)
        except TypeError as e:
            raise JsonSerializerError(e,obj) from None
        return ret

    _default.default = JSONEncoder().default
    JSONEncoder.default = _default