Ejemplo n.º 1
0
def selectReading():

    if not Session.getSession('signedin'):
        return redirect(url_for('signin'))

    flash(dbPath)

    form = SelectReadingForm(request.form)
    jinjadict.update(dict(form=form))
    with db_session:
        heldReadings = Readings.select(
            lambda c: c.am is not None and c.pm is None).order_by(1)
        heldReadingsList = list(heldReadings)
    numberOfHeldReadings = len(heldReadingsList)
    if numberOfHeldReadings > 0:
        heldReadingDates = []
        index = 1
        for heldReading in heldReadingsList:
            heldReadingDates.append((f'D{index}', heldReading.date))
            index += 1
        form.helddateslist.choices = heldReadingDates
        Session.putSession('heldDates', heldReadingDates)

        return render_template('SelectReading.jinja2',
                               **jinjadict)  # form=heldForm)
    else:
        return render_template('NoneHeld.jinja2', **jinjadict)
Ejemplo n.º 2
0
    def __init__(self):
        super(TermWidgetImpl, self).__init__()
        m_terminalDisplay = TerminalDisplay()
        m_session = Session()

        m_session.createSession()
        m_terminalDisplay.createTerminalDisplay(m_session, self)
Ejemplo n.º 3
0
def signin():
    # f = open('/home/bill/glucose2-dev/glucose2-dev/wdt.log', 'w')
    # f.write(f'signin() {request.method}')
    # f.close()

    log('signin', f'{request.method}')

    if request.method == 'GET':
        flash(dbPath)
        form = SigninForm(request.form)
        jinjadict.update(dict(form=form))
        log('signin', 'render_template(Signin.jinja2)')
        return render_template('Signin.jinja2', **jinjadict)
    else:
        form = SigninForm(request.form)
        jinjadict.update(dict(form=form))
        typedcode = form.data['code']
        log('signin', f'typedcode = {typedcode}')
        savedcode = System.getCode()
        log('signin', f'savedcode = {savedcode}')
        signedin = verify_password(savedcode, typedcode)
        Session.putSession('signedin', signedin)
        if signedin:
            # with db_session:
            #     numberOfHeldReadings = len(Readings.select(lambda c: (c.am is not None and c.pm is not None) or c.hold is not None))
            # log(f'signin: numberOfHeldReadings = {numberOfHeldReadings}')
            # jinjadict.update(dict(numberOfHeldReadings=numberOfHeldReadings))

            rv = redirect(url_for('admin'))
            log('signin', 'redirect(url_for("admin"))')
            return rv
        else:
            flash('Try Again')
            return redirect(url_for('signin'))
 def run(self):
     totalScore = 0.0
     for grid in MultipleSessions.grids:
         session = Session(self.robby, copy.deepcopy(grid))
         score = session.run()
         self.robby.clean()
         totalScore = totalScore + score
     return ( totalScore / len(MultipleSessions.grids) )
 def run(self):
     total_score = 0.0
     for grid in MultipleSessions.grids:
         session = Session(self.robby, copy.deepcopy(grid))
         score = session.run()
         self.robby.clean()
         total_score = total_score + score
     return total_score / len(MultipleSessions.grids)
Ejemplo n.º 6
0
def home():
    global firstTimeThrough
    if firstTimeThrough:
        Session.initSession()
        firstTimeThrough = False
    log('home', '*********************** starting **********************')
    log('home', request.method)
    Session.putSession('signedin', False)
    return render_template('Home.jinja2', title='Glucose Chart')
Ejemplo n.º 7
0
 def __init__(self, starting_id=None, pal=None, recursivity_level=1, *args, 
              **kwargs):
   super(Scrapper, self).__init__(*args, **kwargs)
   #Thread.__init__(self)
   self.kill_yourself = False
   self.starting_id = starting_id
   self.pal = pal
   self.session = Session()
   self.browser = webdriver.Firefox()
Ejemplo n.º 8
0
 def create(self, data: T.Union[T.Dict[str, T.Any], BaseModel]) -> DbBaseModel:
     json_data: T.Dict[str, T.Any]
     if isinstance(data, BaseModel):
         json_data = jsonable_encoder(data)
     else:
         json_data = data
     obj = self.model(**json_data)
     Session.add(obj)
     Session.commit()
     return obj
Ejemplo n.º 9
0
    def OnLogin(self, event):
        global PASSWORD
        PASSWORD = self.password.GetValue()
        # Valid Check
        if self.username.GetValue() == '' or self.password.GetValue() == '':
            Util.MessageBox(self, u'缺少用户名或密码!', u'错误', wx.OK | wx.ICON_ERROR)
            return

        dlg = ProgressDialog.ProgressDialog(self, u'连接服务器...')

        url = 'http://%s:5000/v2.0' % (Setting.getServer())

        RestartDeviceRequests()

        loginthread = LoginThread(dlg, url, self.username.GetValue(),
                                  self.password.GetValue())
        loginthread.start()
        #ret = dlg.ShowModal()
        #dlg.Destroy()
        if dlg.ShowModal() == wx.ID_CANCEL:
            loginthread.stop()
            return
        if loginthread:
            loginthread.stop()
        dlg.Destroy()

        Logger.info("Connect to %s", url)
        Logger.info("UserId: %s, Password: ******", self.username.GetValue())
        ret, reason, detail = loginthread.getReturnValue()
        Logger.info("Result: %s, reason: %s, detail: %s", ret, reason, detail)

        if Setting.getSign().lower() == 'false':
            self.password.SetValue('')

        self.password.SetFocus()

        if not ret:
            Util.MessageBox(self, detail, reason, wx.OK | wx.ICON_ERROR)
            Session.logout()
        else:
            Setting.setLastLogin(FirstUser['firstuser'].username)
            if self.sign.GetValue() == True:
                Setting.setPasswd(self.password.GetValue())
            else:
                Setting.setPasswd('1df#$!cd123~')
            Setting.save()
            area = wx.Display().GetGeometry()
            width = area.GetWidth()
            height = area.GetHeight()
            f = MainFrame.MainFrame(self.GetParent(), (width, height))

            f.ShowFullScreen(True)
            self.GetParent().Hide()
Ejemplo n.º 10
0
 def update(obj: DbBaseModel,
            data: T.Union[T.Dict[str, T.Any], BaseModel]) -> DbBaseModel:
     json_data: T.Dict[str, T.Any]
     if isinstance(data, BaseModel):
         json_data = jsonable_encoder(data)
     else:
         json_data = data
     for attribute, value in json_data.items():
         if hasattr(obj, attribute):
             setattr(obj, attribute, value)
     Session.commit()
     return obj
    def StartClassification(self, ArrayToClassify):

        result = 0.0
        shortest_path = ""

        # looping on every stroke in dataset and add in array for classification
        for i in TrainingFilePath:

            file = i.split()
            dataset_wave = []

            f = open(str(file), "r")

            # adding every frame data in arr2 then add all frames in dataset_wave
            for x in f:
                line = x.split()
                arr2 = []
                for l in range(15):
                    arr2.append(float(line[i]))

                    dataset_wave.append(arr2)

                dataset_wavee = np.array(dataset_wave)
                app_wavee = np.array(ArrayToClassify)
                distance = 0.0

                distance, path = fastdtw(dataset_wavee,
                                         app_wavee,
                                         dist=euclidean)

                if (result == 0.0):

                    result = distance
                    shortest_path = file
                elif (result > distance):
                    result = distance
                    shortest_path = file

        string = shortest_path.split('/')
        isMistake = False
        StrokeType = ""
        ErrorType = ""
        if (string[1] == "Wrong"):
            self.noWrong += 1
            isMistake = True
            ErrorType = string[3]
        else:
            self.noCorrect += 1

        StrokeType = string[2]

        Session.GetSessionInfo(ArrayToClassify)
        Session.InsertClassificationResult(ErrorType, isMistake, StrokeType)
Ejemplo n.º 12
0
 def validator(*args, **kwargs):
     sess = Session(session, get_database())
     Logger.dbg("validator: Request headers:\n=====\n{}\n=====\n".format(
         request.headers))
     if not sess.validate_session():
         Logger.fail('@authorized: User not authenticated.')
         return jsonify({
             'status': 401,
             'message': 'Unauthorized. Please login first.'
         })
     else:
         Logger.ok('@authorized: User authenticated.')
         return f(*args, **kwargs)
Ejemplo n.º 13
0
def setupNumberOfPartials():
    with db_session:
        numberOfHeldReadings = len(
            Readings.select(lambda c: c.am is not None and c.pm is None))
    Session.putSession('numberOfHeldReadings', numberOfHeldReadings)
    log('setUpNumberOfPartials',
        f'numberOfHeldReadings = {numberOfHeldReadings}')
    if numberOfHeldReadings == 0:
        flash('There are no partial readings.')
    elif numberOfHeldReadings == 1:
        flash('There is one partial reading.')
    else:
        flash(f'There are {numberOfHeldReadings} partial readings.')
    jinjadict.update(dict(numberOfHeldReadings=numberOfHeldReadings))
Ejemplo n.º 14
0
 def run_single(self, sample, iterations, threshold):
     if (not self.haskey) and self.evaluate:
         self.generate_key()
     if self.haskey:
         self.load_key()
     print("...Finding fds ...")
     session = Session(self.ID,
                       self.inputName,
                       self.inputData,
                       self.field,
                       self.write_loc,
                       mode="normal")
     session.config(sample[0], iterations[0], threshold[0], self.silent,
                    self.evaluate, self.key)
Ejemplo n.º 15
0
 def generate_key(self):
     print("...Genertating key ...")
     session = Session(self.ID,
                       self.evName,
                       self.evData,
                       self.evField,
                       self.write_loc,
                       mode="key")
     self.key = session.config_test()
     # save the key
     keyName = self.read_loc + "key-{}.json".format(
         self.inputName.split(".")[0])
     keyfile = open(keyName, "w+")
     keyfile.write(json.dumps(self.key))
     print(self.key)
Ejemplo n.º 16
0
 def loginWithAuthToken(self, authToken=None, appName=None):
     if authToken == None: raise Exception("Please set authToken")
     if appName == None: appName = self.APP_NAME
     self.Headers["X-Line-Application"] = appName
     self.Headers["X-Line-access"] = authToken
     self.authToken = authToken
     self.talk = Session(self.LINE_HOST_DOMAIN, self.Headers,
                         self.LINE_API_QUERY_PATH_FIR).Talk()
     self.poll = Session(self.LINE_HOST_DOMAIN, self.Headers,
                         self.LINE_POLL_QUERY_PATH_FIR).Talk()
     #self.call=Sesion(self.LINE_HOST_DOMAIN,self.Headers,self.LINE_CALL_QUERY_PATH).Call()
     #self.channel=Session(self.LINE_HOST_DOMAIN,self.Headers,self.LINE_CHAN_QUERY_PATH).Channel()
     #self.square=Session(self.LINE_HOST_DOMAIN,self.Headers,self.LINE_SQUARE_QUERY_PATH).Square()
     #self.shop=Session(self.LINE_HOST_DOMAIN,self.Headers,self.LINE_SHOP_QUERY_PATH).Shop()
     self.isLogin = True
Ejemplo n.º 17
0
    def autoLogin(self):
        if Setting.getSign().lower() == 'false':
            return False
        if Setting.getAuto().lower() == 'true':
            pass
        else:
            return False

        username = Setting.getLastLogin()
        passwd = Setting.getPasswd()
        if username == '' or passwd == '':
            Util.MessageBox(self, u'缺少用户名或密码!', u'错误', wx.OK | wx.ICON_ERROR)
            return

        dlg = ProgressDialog.ProgressDialog(self, u'连接服务器...')
        dlg.CenterOnScreen()

        url = 'http://%s:5000/v2.0' % (Setting.getServer())

        RestartDeviceRequests()

        loginthread = LoginThread(dlg, url, username, passwd)
        loginthread.start()
        #dlg.SetPosition((100,100))
        #dlg.Move((Resource.screenX-dlg.))
        #dlg.CenterOnScreen()
        #ret = dlg.ShowModal()
        #dlg.Destroy()
        if dlg.ShowModal() == wx.ID_CANCEL:
            loginthread.stop()
            return
        if loginthread:
            loginthread.stop()
        dlg.Destroy()

        Logger.info("Connect to %s", url)
        Logger.info("UserId: %s, Password: ******", username)
        ret, reason, detail = loginthread.getReturnValue()
        Logger.info("Result: %s, reason: %s, detail: %s", ret, reason, detail)

        if not ret:
            Util.MessageBox(self, detail, reason, wx.OK | wx.ICON_ERROR)
            self.ShowFullScreen(True)
            Session.logout()
        else:
            f = MainFrame.MainFrame(self.GetParent(), wx.ScreenDC().GetSize())
            f.ShowFullScreen(True)
            self.GetParent().Hide()
Ejemplo n.º 18
0
    def initUi(self):
        """Ui Setup."""
        start = Session.MultiSession(self)
        layout = QVBoxLayout()
        layout.addWidget(start)

        self.setLayout(layout)
Ejemplo n.º 19
0
    def __init__(self, application, request, **kwargs):
        super(BaseHandler, self).__init__(application, request, **kwargs)
        LOG.info('web request init')

        if self.use_session:
            self.session = Session.Session(self)
            self.session.load()
Ejemplo n.º 20
0
def getSession(self,sessionKey) :
    if self.repository.existsByKeyAndCommit(sessionKey,Session) :
        self.printWarning(f'"{sessionKey}" session key already exists')
        return self.repository.findByKeyAndCommit(sessionKey,Session)
    else :
        newSession = Session(sessionKey,FrameworkStatus[FrameworkConstant.INACTIVE],[])
        return self.repository.saveAndCommit(newSession)
Ejemplo n.º 21
0
    def run(self):
        while not self.cancel:
            if self.refresh > 0:
                self.lock.acquire()
                self.refreshVM()
                self.lock.release()
                self.refresh = self.refresh - 1
            else:
                if self.tenRefresh == 0:
                    # Del by wangderan 20150525 start
                    #Session.logout()
                    # Del by wangderan 20150525 end

                    url = 'http://%s%s' % (Setting.getServer(), ":5000/v2.0")
                    _auth_url = url

                    username = Setting.getLastLogin()
                    _user = username

                    _password = LoginFrame.PassWord()

                    ret, reason, detail = Session.login(
                        _auth_url, _user, _password)
                    Logger.info("ReLogin Status: Result: %s", ret)

                    self.lock.acquire()
                    self.refreshVM()
                    self.lock.release()
                    self.tenRefresh = 900
                else:
                    self.tenRefresh = self.tenRefresh - 1
                    wx.Sleep(2)
Ejemplo n.º 22
0
 def save(self):
     """
     Helper method to save changes to a certain object.
     """
     session = Session.object_session(self)
     session.add(self)
     session.commit()
Ejemplo n.º 23
0
 def delete(self):
     """
     Helper method to delete a certain object.
     """
     session = Session.object_session(self)
     session.delete(self)
     session.commit()
Ejemplo n.º 24
0
def main(uri):
    session = Session.Http(uri)

    ## Uncomment for extra debug info
    #session.print_status = True
    #session.print_data = True

    session.auth_user_callback()

    # Config Tree Flows...

    flows_config_tree = ConfigTree.flowsHttpAccess(session)

    print("There are {0} flows in the config tree".format(
        len(flows_config_tree.read_collection())))

    for idx, flow_config_tree in enumerate(flows_config_tree.read_collection()):
        if idx > 0:
            print("\n")
        print("Config Tree flow {0}\n{1}".format(idx, flow_config_tree.to_json()))

    print('='*50)

    flows_op_tree = OperationalTree.flowStatsHttpAccess(session)

    print("There are {0} flows in the operational tree".format(
        len(flows_op_tree.read_collection())))

    for idx, flow_op_tree in enumerate(flows_op_tree.read_collection()):
        if idx > 0:
            print("\n")
        print("Operational Tree flow {0}\n{1}".format(idx, flow_op_tree.to_json()))
Ejemplo n.º 25
0
    def get_session(self):
        '''get this scans information, return a Session object'''
        run_node = self.__dom.getElementsByTagName('nmaprun')[0]
        hosts_node = self.__dom.getElementsByTagName('hosts')[0]

        finish_time = self.__dom.getElementsByTagName(
            'finished')[0].getAttribute('timestr')

        nmap_version = run_node.getAttribute('version')
        start_time = run_node.getAttribute('startstr')
        scan_args = run_node.getAttribute('args')

        total_hosts = hosts_node.getAttribute('total')
        up_hosts = hosts_node.getAttribute('up')
        down_hosts = hosts_node.getAttribute('down')

        MySession = {
            'finish_time': finish_time,
            'nmap_version': nmap_version,
            'scan_args': scan_args,
            'start_time': start_time,
            'total_hosts': total_hosts,
            'up_hosts': up_hosts,
            'down_hosts': down_hosts
        }

        self.__session = Session.Session(MySession)

        return self.__session
Ejemplo n.º 26
0
 def clientSocket(self):
     bytes, address = self.client.recvfrom(65535)
     if bytes != 0:
         key = address[0] + ":" + str(address[1])
         if key not in self.sessions:
             print(key + "からデータが送られてきました")
             self.sessions[key] = Session.Session(self.popyip, self.serverip, self.serverport)
         self.sessions[key].send(bytes)
Ejemplo n.º 27
0
 def run(self):
     if self.cancel:
         return
     #wx.CallAfter(self.window.WorkFinished, u'下载根证书... 成功')
     wx.CallAfter(self.window.Update, 1, u'正在连接服务器 ...')
     self.ret = Session.login(self.url, self.username, self.password)
     wx.CallAfter(self.window.WorkFinished, u'认证成功')
     wx.CallAfter(self.window.Finish)
 def createSession(self, aArrayPtrSourceNodesOfTopology):
     method = "createSession"
     id = self.IDispatch.GetIDsOfNames(method, **self.currentlcid)
     aIID = '{742AC001-D1E0-40A8-8EFE-BA1A550F8805}'
     arg = []
     arg.append(aArrayPtrSourceNodesOfTopology)
     arg.append(aIID)
     return Session.Session(self.IDispatch.Invoke(id[0], *arg))
Ejemplo n.º 29
0
def backup(local_dir):
    session = Session.Session()
    drive_service = session.getService()

    files = Util.retrieve_all_files(drive_service)
    root_dir = Util.get_root_id(files)
    backup_service = DriveBackup.DriveBackup(root_dir)
    backup_service.createBackup(drive_service, local_dir)
Ejemplo n.º 30
0
 def run_batch(self, sample, iterations, threshold):
     if (not self.haskey) and self.evaluate:
         self.generate_key()
     if self.haskey:
         self.load_key()
     print("...Finding fds ...")
     for s in sample:
         for i in iterations:
             for t in threshold:
                 session = Session(self.ID,
                                   self.inputName,
                                   self.inputData,
                                   self.field,
                                   self.write_loc,
                                   mode="normal")
                 session.config(s, i, t, self.silent, self.evaluate,
                                self.key)
Ejemplo n.º 31
0
def updateUserAdEntry(obj, entry):
    session = Session.Session()
    session.click = int(entry[0])
    session.depth = int(entry[5])
    session.impression = int(entry[1])
    session.position = int(entry[6])
    session.queryId = int(entry[7])
    obj.sessionList.append(session)
Ejemplo n.º 32
0
    def process_file(self, root, file_node):
        Session.begin(self.header_jar)

        self._set_current_file(root, file_node)

        # Do not add unneeded header files
        modified = self.modified
        self.modified = False

        self._process_free_functions()
        self._process_global_constants()
        self._process_enums()

        if self.modified:
            self.header_jar.add_headers((self.header_decl,))
        else:
            self.modified = modified

        self._process_classes()
        self._process_inner_namespaces()

        Session.end()
Ejemplo n.º 33
0
def processLogin():
	fbInfo = json.loads(flask.request.values['fbInfo'])
	userID = fbInfo.get(u'userID')
	if userID == None:
		return errorResponse('no userID')
	
	with rpool.get() as R:
		sessionLifetime = 86400 * 14 # 2weeks
		(skey, secr) = Session.createSession(R, userID, sessionLifetime)
		response = {}
		ret = flask.jsonify(**response)
		ret.set_cookie(u'skey', skey, sessionLifetime)
		ret.set_cookie(u'secr', secr, sessionLifetime)
		return ret
Ejemplo n.º 34
0
def processXHR():
	try:
		# handler Dictionary
		xhrHandlers = {
			'LOG_INIT':   xhrLogInit,
			'LOG_UPDATE': xhrLogUpdate,
			'LOG_OLD':    xhrLogOld,
			'CMD':        xhrCmd,
			'CONFIG_GET': xhrConfigGet,
			'CONFIG_SET_SERVER': xhrConfigSetServer,
			}

		# json으로 넘어온 request object 파싱
		if (flask.request.method != 'GET') or ('req' not in flask.request.values):
			abort(500)
			return
		print( flask.request.values['req'] )
		reqObject = json.loads(flask.request.values['req'])

		# cookie로부터 인증 정보를 수집
		#app.logger.debug(" cookie - %s", str(flask.request.cookies))
		userID = None
		print( flask.request.cookies )
		sessionKey = flask.request.cookies.get('skey')
		secret = flask.request.cookies.get('secr')
		if sessionKey is not None and secret is not None:
			with rpool.get() as R:
				userID = Session.checkSession(R, sessionKey, secret)

		# 인증 정보가 없으면 에러 응답
		if userID is None:
			response = { u'err': u'LOGIN_REQUIRED' }
			return flask.jsonify(**response)

		# 인증을 통과함. 정상 응답
		return xhrHandlers[ reqObject['req'] ] (userID, reqObject)
	except:
		traceback.print_exc()
Ejemplo n.º 35
0
    def decode_msg_15(self, raw_data):
        session = Session()

        client_id = self.decode_int("l", raw_data, 0)
        client_netid = self.decode_int("l", raw_data, 4)
        client_type = self.decode_int("b", raw_data, 8)
        logging.debug("ClientID: %d | CLientNetworkID: %d | ClientType: %d ", 
                      client_id, client_netid, client_type)
        offset = 9
        if client_type is 1:
            client_name_len = self.decode_int("h", raw_data, offset)
            client_name = self.decode_string(raw_data, offset)
            client_hash = struct.unpack_from("<17s", raw_data, 
                                             11 + client_name_len)

            logging.debug("--- ClientName: %s (%d) | ClientHash: %s",
                          client_name, client_name_len, 
                          str.upper(binascii.hexlify("".join(client_hash))))

            offset = 28 + client_name_len;

        ip0 = self.decode_int("B", raw_data, offset)
        ip1 = self.decode_int("B", raw_data, offset+1)
        ip2 = self.decode_int("B", raw_data, offset+2)
        ip3 = self.decode_int("B", raw_data, offset+3)
        geoip = self.decode_int("B", raw_data, offset + 4)
        port = self.decode_int("H", raw_data, offset + 5)
        logging.debug("--- IP: %d.%d.%d.%d | geoip: %d | Port: %d ", ip0, ip1, 
                      ip2, ip3, geoip, port)
        offset += 7
        connection_state = self.decode_int("B", raw_data, offset)
        offset += 1
        logging.debug("--- ConnectionState: %d ", connection_state)
        if str(connection_state) in ("3", "5", "9"):
            rank = self.decode_int("l", raw_data, offset)
            logging.debug("--- Rank: %d ", rank)
            offset += 4
        client_type = self.decode_int("b", raw_data, offset)
        offset += 1
        logging.debug("--- ClientType: %d ", client_type)
        tag_list_len = self.decode_int("h", raw_data, offset)
        logging.debug("--- TagListLen: %d ", tag_list_len)
        offset += 2
        for i in range(tag_list_len):
            tag_name_len = self.decode_int("h", raw_data, offset)
            tag_name = self.decode_string(raw_data, offset)
            offset += 2 + tag_name_len
            tag_type = self.decode_int("b", raw_data, offset)
            offset += 1
            if str(tag_type) in ("0", "1", "3", "6"):
                tag_value = self.decode_int("l", raw_data, offset)
                offset += 4
            elif tag_type is 2:
                 tag_value_len = self.decode_int("h", raw_data, offset)
                 tag_value = self.decode_string(raw_data, offset)
                 offset += 2 + tag_value_len
            elif tag_type is 4:
                tag_value = self.decode_int("h", raw_data, offset)
                offset += 2
            elif tag_type is 5:
                tag_value = self.decode_int("b", raw_data, offset)
                offset += 1
            logging.debug("--- Tag %d -> %s = %s", i, tag_name, str(tag_value))

        client_name_len = self.decode_int("h", raw_data, offset)
        client_name = self.decode_string(raw_data,offset)
        offset += 2 + client_name_len
        logging.debug("--- ClientName: %s", client_name)
        client_rating = self.decode_int("l", raw_data, offset)
        offset += 4
        logging.debug("--- ClientRating: %d", client_rating)
        client_software_len = self.decode_int("h", raw_data, offset)
        client_software = self.decode_string(raw_data, offset)
        offset += 2 + client_software_len
        logging.debug("--- ClientSoftware: %s", client_software)
        downloaded = self.decode_int("L", raw_data, offset)
        offset += 8
        uploaded = self.decode_int("L", raw_data, offset)
        offset += 8
        logging.debug("--- Downloaded: %d | Uploaded: %d", downloaded, uploaded)
        upload_filename_len = self.decode_int("h", raw_data, offset)
        upload_filename = self.decode_string(raw_data, offset)
        offset += 2 + upload_filename_len
        logging.debug("--- UploadFileName: %s", upload_filename)
        connected_time = self.decode_int("l", raw_data, offset)
        offset += 4
        logging.debug("--- ConnectedTime: %d", connected_time)
        emule_mod_len = self.decode_int("h", raw_data, offset)
        emule_mod = self.decode_string(raw_data, offset)
        offset += 2 + emule_mod_len
        logging.debug("--- EMuleMod: %s", emule_mod)
        client_version_len = self.decode_int("h", raw_data, offset)
        client_version = self.decode_string(raw_data, offset)
        offset += 2 + client_version_len
        logging.debug("--- ClientVersion: %s", client_version)
        sui_verified = self.decode_int("b", raw_data, offset)
        logging.debug("--- SuiVerified: %d", sui_verified)
	if downloaded is not 0 or uploaded is not 0:
	    logging.debug(('ClientID: %d | ClientName: %s | '
                           'ClientIP: %d.%d.%d.%d | ClientPort: %d | '
                           'ClientSoftware: %s | ConnectionState: %d | '
                           'FileName: %s | Down: %d | Up: %d '), 
                           client_id, client_name, ip0, ip1, ip2, ip3, 
                           port, client_software, connection_state, 
                           upload_filename, downloaded, uploaded)

        session.address.ip = "%d.%d.%d.%d" % (ip0, ip1, ip2, ip3)
        session.address.port = port 
        session.downloaded = downloaded
        session.uploaded = uploaded
        session.source.id = client_id
        if client_type==0:
            session.kind = "lowID"
        else:
            session.kind = "highID"
    	return session
Ejemplo n.º 36
0
form = cgi.FieldStorage()

if form.has_key( "message" ):

   # create DOM for error message   
   document = implementation.createDocument( None, None, None )
   error = document.createElement( "error" )
   message = document.createElement( "message" )
   message.appendChild( document.createTextNode(
      form[ "message" ].value ) )
   error.appendChild( message )
   document.appendChild( error )
   
   # process against XSLT style sheet
   processor = Processor.Processor()
   style = open( Session.getClientType()[ 0 ] + "/error.xsl" )
   processor.appendStylesheetStream( style )
   results = processor.runNode( document )
   style.close()

   # display content type and processed XML
   print Session.getContentType() + results

########################################################################## 
# (C) Copyright 2002 by Deitel & Associates, Inc. and Prentice Hall.     #
# All Rights Reserved.                                                   #
#                                                                        #
# DISCLAIMER: The authors and publisher of this book have used their     #
# best efforts in preparing the book. These efforts include the          #
# development, research, and testing of the theories and programs        #
# to determine their effectiveness. The authors and publisher make       #
Ejemplo n.º 37
0
def print_and_clear_ignored_symbols_registry():
    Session.print_ignored_symbols_registry()
    Session.clear_ignored_symbols_registry()
Ejemplo n.º 38
0
# Fig. 23.12: displayBook.py
# Retrieve one book's XML representation, convert
# to required format using browser-specific XSLT
# stylesheet and display results.

import cgi
import sys
import Session
from xml.xslt import Processor
from xml.dom.DOMImplementation import implementation

form = cgi.FieldStorage()

# ISBN has not been specified
if not form.has_key( "isbn" ):
   Session.redirect( "error.py?message=No+ISBN+given" )
   sys.exit()

# load Session
try:
   session = Session.Session()     
except Session.SessionError, message:  # invalid/no session ID 
   Session.redirect( "error.py?message=%s" % message )
   sys.exit()
      
titles = session.data[ "titles" ]   # get titles
session.data[ "bookToAdd" ] = None  # book has not been found

# locate Book object for selected book   
for book in titles:
   
Ejemplo n.º 39
0
def run(k1, k2, listsize, reco_type):
    if reco_type == 'tf':
        Session.run(k1, k2, listsize, False, False, 'tf')
    if reco_type == 'idf':
        Session.run(k1, k2, listsize, True, False, 'idf')
    if reco_type == 'keywords':
    	Keywords.run(k1, k2, listsize, 'keywords')
    if reco_type == 'session':
    	Session.run(k1, k2, listsize, False, True, 'session')
    if reco_type == 'mailinglist':
    	MailingListRecommendation.run(k1, k2, listsize, 'mailinglist')
    if reco_type == 'all':
    	Keywords.run(k1, k2, listsize, 'keywords')
    	Session.run(k1, k2, listsize, False, True, 'session')
        Session.run(k1, k2, listsize, False, False, 'tf')
        Session.run(k1, k2, listsize, True, False, 'idf')
    	MailingListRecommendation.run(k1, k2, listsize, 'mailinglist')
Ejemplo n.º 40
0
    def generate(self):
        Session.begin(self.header_jar)

        if self._require_wrapper_class():
            self.block.write_code("class %s;" % self.get_wrapt_class_name())
            self.block.append_blank_line()

        self.block.write_code(Code.Snippets.pyobj_decl % {
            "WRAPT": self.get_wrapt_class_name(),
            "PYTYPE_NAME": self.namer.pytype(self.full_name),
            "PYOBJ_NAME": self.namer.pyobj(self.full_name),
            "BASE_PTR_FIXER": self.namer.base_ptr_fixer(self.full_name),
        })

        if not self.fptrs.empty():
            self.fptrs.generate(self.block)
            self.block.append_blank_line()

        if self._require_wrapper_class():
            self._generate_wrapper_class()

        if not self.enum_class:
            self._generate_borrower()

        if self.copy_ready():
            self._generate_copyer()

        # Use a dummy subclass as method holder to invoke protected members
        method_holder = self.namer.method_holder(self.full_name)

        if self.allows_subclassing() or self.enum_class:
            if not self.enum_class:
                method_wrapper_base = self.full_name
            else:
                method_wrapper_base = self.nester or "pbpp::ScopedEnumDummy"

            self.block.write_code("struct %s : %s {" % (
                method_holder, method_wrapper_base
            ))
        else:
            self.block.write_code("struct %s {" % method_holder)

        self.block.append_blank_line()

        self._generate_constructors()
        self._generate_destructor()
        self._generate_methods()
        self._generate_enums()
        self._generate_fields()

        self.block.write_code(Code.Snippets.method_holder_end % {
            "METHOD_HOLDER": self.namer.method_holder(self.full_name),
            "METHODS_TABLE": self.namer.methods_table(self.full_name),
            "GETSET_TABLE": self.namer.getset_table(self.full_name),
            "BASES_REGISTER": self.namer.bases_register(self.full_name),
        })

        self._generate_methods_table()
        self._generate_getset_table()

        self._generate_pytypeobject()
        self._generate_base_ptr_fixer()
        self._generate_bases_register()
        self._generate_register()

        Session.end()

        # TODO: Why can't do this in ctor?
        self.header_jar.add_headers(self.header_provider.klass(self.full_name))
        if self._require_wrapper_class():
            self.header_jar.add_headers(("<typeinfo>",))

        memblock = CodeBlock.CodeBlock()

        memblock.write_code(self.header_provider.pch())
        memblock.write_code(self.header_jar.concat_sorted())
        memblock.append_blank_line()

        # TODO: a dirty trick
        self.block.lines = memblock.lines + self.block.lines

        self.modified = False
Ejemplo n.º 41
0
session = None  # Session not yet created

# attempt to create Session three times
for i in range( 3 ):

   # create new Session
   try:
      session = Session.Session( 1 )

   # ID already exists      
   except Session.IDError:                 
      time.sleep( 0.1 )  # wait 0.1 seconds -- try again

   # missing content type
   except Session.SessionError, message:   
      Session.redirect( "error.py?message=%s" % message )
      sys.exit()

   else:
      break  # Session created successfully

# if successful, save Session and re-direct to allBooks.py
if session: 
   nextPage = "allBooks.py?ID=%s" % session.data[ "ID" ]
   session.saveSession()
   Session.redirect( nextPage )
else:
   Session.redirect( "error.py?message=Unable+to+create+Session" )

########################################################################## 
# (C) Copyright 2002 by Deitel & Associates, Inc. and Prentice Hall.     #
Ejemplo n.º 42
0
    def generate(self, outdir, ext):
        for submodule in self.submodules.values():
            submodule.generate(outdir, ext)

        full_name = self._pyside_full_name()
        output_path = "%s%s%s.py%s" % (
            outdir, os.path.sep, full_name, ext
        )

        if self.is_root():
            self._copy_helpers(outdir)

        if not self.modified and os.path.exists(output_path):
            return

        # Return this function with care:
        #   Remember to call Session.end()
        Session.begin(self.header_jar)

        fp_mem_block = CodeBlock.CodeBlock()
        fptrs = Fptr.FptrManager()
        self.free_functions.collect_function_pointer_defs(fptrs)
        if not fptrs.empty():
            fptrs.generate(fp_mem_block)
            fp_mem_block.append_blank_line()
            fp_mem_block.append_blank_line()

        ff_mem_block = CodeBlock.CodeBlock()
        ff_table_mem_block = CodeBlock.CodeBlock()
        self.free_functions.generate_methods(ff_mem_block, self.namer, self)
        self.free_functions.generate_methods_table(ff_table_mem_block, self.namer, self)

        template_args = {
            "MNAME": self.name,
            "MNAME_FULL": full_name,
            "MOD_REGISTER": self.get_register_name(),
            "HEADERS": self.header_jar.concat_sorted(),
            "FPTRS": fp_mem_block.flush(),
            "FREE_FUNCTIONS": ff_mem_block.flush(),
            "METHODS_TABLE": ff_table_mem_block.flush(),
        }

        block = CodeBlock.CodeBlock()
        block.write_code(self.header_provider.pch())

        with open(os.path.dirname(__file__) + "/Code/Header.inl") as f:
            block.write_code(f.read() % template_args)

        self._generate_global_constants_wrapper(block)
        self._generate_enums_register(block)

        module_ptr = self.namer.mod_ptr_name(full_name)

        block.write_code(Code.Snippets.define_module_ptr.format(module_ptr))
        block.write_code(Code.Snippets.module_register_header % template_args)
        block.indent()

        block.write_code(self.namer.globals_register(full_name) + "(m);")
        block.write_code(self.namer.enums_register(full_name) + "(m);")
        block.append_blank_line()

        for submodule in self.submodules.values():
            register = submodule.get_register_name()
            block.write_code("PyObject *%s(PyObject *parent);" % register)

        if len(self.submodules) > 0:
            block.append_blank_line()

        for submodule in self.submodules.values():
            block.write_code(submodule.get_register_name() + "(m);")

        if len(self.submodules) > 0:
            block.append_blank_line()

        for cls in self.classes.values():
            cls.mod = 'm' if self.is_root() else module_ptr

        if self.is_root():
            self._register_classes(block, outdir, ext)

        block.write_code(module_ptr + " = m;")
        block.write_code("return m;")
        block.unindent()
        block.write_code("}")

        if self.is_root():
            with open(os.path.dirname(__file__) + "/Code/RootMod.inl") as f:
                block.write_code(f.read() % self.name)


        ns = self._get_cxx_namespace() or self.name
        content = self.blacklist.hook_write(ns, block.flush())

        Util.smart_write(output_path, content)

        self.modified = False

        Session.end()
Ejemplo n.º 43
0
threshold = 30 # 30 minutes threshold
fname = sys.argv[1] # file with logs of only single user
lines = readFile(fname)

matrix_fname = list(reversed(fname.split('/')))[0] #Input : "xdir/../.../log/user1" , output: 'user1'
matrix_fname += "_matrix" #user1_matrix
matrix_dir = "matrix_dir"
createDir(matrix_dir) #createDir creates (if not exists) matrix_dir in current directory.
createDir("waitTimeMatrix_dir")
matrix_fname = matrix_dir+"/"+matrix_fname
# f = open(matrix_fname,'w')
# f.close()


prevtime = -1
curSession = Session()
# print "New Session..."

for line in lines:
	arr = getArray(line)
	curTime = getTime(arr)
	if prevtime==-1:
		prevtime = curTime
		
	statusCode = getStatusCode(arr)
	timeDiff = (curTime - prevtime).total_seconds()	#Time differnce in seconds
	if(timeDiff<0):
		print "Warning : Time differnce should not be negative!"
		exit(0)

	if (timeDiff/60.0 > threshold):
Ejemplo n.º 44
0
#!/usr/local/bin/python
# Fig. 23.16: viewCart.py
# Generate XML representing cart, convert
# to required format using browser-specific XSLT
# style sheet and display results.

import sys
import Session
from xml.xslt import Processor
from xml.dom.DOMImplementation import implementation

# load Session
try:
   session = Session.Session()
except Session.SessionError, message:   # invalid/no session ID
   Session.redirect( "error.py?message=%s" % message )
   sys.exit()

cart = session.data[ "cart" ]
total = 0  # total for all ordered items

# generate XML representing cart object
document = implementation.createDocument( None, None, None )
cartNode = document.createElement( "cart" )
document.appendChild( cartNode )

# add XML representation for each cart item
for cartItem in cart.values():

   # get book data, calculate subtotal and total
   book = cartItem.item
Ejemplo n.º 45
0
print 'save world to disk'
util.toFile('test', world.toTag())'''

print 'loading world from file'
worldtag = util.fromFile('test')
world = World.readWorld(worldtag)

world.players = [player]
world.crates = [crate]
Session = Session.Session()
Session.worlds.append(world)


while 1:
    Session.update()



'''
    world.buildDrawList()
    world.buildEntList()
    
    screen.fill((255,255,255))
    world.draw(screen)
    
    fps = str(int(round(clock.get_fps())))
    fpsSurf = font.render(fps, True, (0,0,0))
    fpsRect = fpsSurf.get_rect()
    fpsRect.topleft = [10,10]
    screen.blit(fpsSurf, fpsRect)
Ejemplo n.º 46
0
#!/usr/bin/env python
from Session import *
class User(object):
   user_name = None
   user_id = None
   def __init__(self, name, id):
      self.user_name = name
      self.user_id = id
user = User("vivian",2)
session = Session(user)
print session.getUserid()
condition = session.getState()
print(condition)
if condition:
	id = session.getUserid()
	user = User("vivian", id)
	print(user.user_id)
	print("cookie works!")
else:
	user = User("vivian", 1)
	print(user.user_id)
Ejemplo n.º 47
0
    def write_args_parsing_code(self, block, namer, enable_kw, err_return, pyside_debug_name):
        error_handler_label = "PBPP__ARGS_PARSING_ERROR_HANDLER_" + str(block.size())
        require_error_handler_label = False

        to_cxx = []
        count0 = 0

        for arg in self.args:
            if arg.type.cvt:
                block.write_code(arg.type.cvt.args_parsing_declare_vars(arg.type, arg.name, arg.defv))

                goto_error_return = "goto %s;" % error_handler_label
                if arg.type.cvt.args_parsing_require_error_handling(arg.type):
                    require_error_handler_label = True

                extracting_code = arg.type.cvt.args_parsing_extracting_code(
                    arg.type, arg.name, arg.defv, goto_error_return, namer
                )

                if len(extracting_code) > 0:
                    to_cxx += extracting_code.split('\n')

                Session.header_jar().add_headers(arg.type.cvt.additional_headers(arg.type))
            elif arg.type.is_built_in():
                if arg.type.is_bool():
                    block.write_code("PyObject *py__%s = nullptr;" % arg.name)

                    if arg.defv is None:
                        extracting_code = Types.extract_as_bool("py__%s" % arg.name)
                        to_cxx.append(arg.type.declare_var(arg.name, extracting_code))
                    else:
                        to_cxx.append(arg.type.declare_var(arg.name, arg.defv))

                        extracting_code = (Code.Snippets.check_and_extract_as_bool % {
                            "VAR_NAME": arg.name
                        }).split('\n')

                        to_cxx += extracting_code
                else:
                    block.write_code(arg.type.declare_var(arg.name, arg.defv))
            elif arg.type.is_ref():
                if not arg.type.is_trivial():
                    pytype = namer.pytype(arg.type.intrinsic_type())
                    block.write_code("extern PyTypeObject %s;" % pytype)

                block.write_code("PyObject *py__%s = nullptr;" % arg.name)
                cpp_ptr_type = arg.type.ref_to_ptr()

                if arg.type.is_trivial():
                    capsule_ensure_reference = (Code.Snippets.capsule_ensure_reference % {
                        "VAR_NAME": arg.name,
                        "CAP_NAME": arg.type.decl_no_const(),
                        "ERROR_RETURN": "goto %s;" % error_handler_label,
                    }).split('\n')

                    require_error_handler_label = True

                    if arg.defv is None:
                        to_cxx += capsule_ensure_reference

                        init_expr = '*((%s) PyCapsule_GetPointer(py__%s, "%s"))' % (
                            (cpp_ptr_type.decl(), arg.name, arg.type.decl_no_const(),)
                        )

                        to_cxx.append(arg.type.declare_var(arg.name, init_expr))
                    else:
                        var_ptr = "py_cxx_%s_ptr" % arg.name
                        to_cxx.append(cpp_ptr_type.declare_var(var_ptr, "&(%s)" % arg.defv))

                        to_cxx.append("if (py__%s) {" % arg.name)
                        to_cxx.append(">>>")
                        to_cxx += capsule_ensure_reference
                        to_cxx.append(var_ptr + ' = (%s) PyCapsule_GetPointer(py__%s, "%s")' % (
                            cpp_ptr_type, arg.name, arg.type.decl_no_const(),
                        ))
                        to_cxx.append("<<<")
                        to_cxx.append("}")

                        to_cxx.append(arg.type.declare_var(arg.name, '*' + var_ptr))
                else:  # reference to class
                    if arg.defv is None:
                        init_expr = '*' + Code.Snippets.external_type_real_ptr % {
                            "CLASS": arg.type.intrinsic_type(),
                            "PYOBJ_PTR": "py__" + arg.name
                        }

                        to_cxx.append(arg.type.declare_var(arg.name, init_expr))
                    else:
                        defv_rv = "py_cxx_%s_defv_rv" % arg.name
                        var_ptr = "py_cxx_%s_ref2ptr" % arg.name

                        to_cxx.append("auto &&%s = %s;" % (defv_rv, arg.defv))
                        to_cxx.append(cpp_ptr_type.declare_var(var_ptr, '&' + defv_rv))

                        to_cxx.append("if (py__%s) {" % arg.name)
                        to_cxx.append(">>>")
                        to_cxx.append(var_ptr + ' = ' + Code.Snippets.external_type_real_ptr % {
                                "CLASS": arg.type.intrinsic_type(),
                                "PYOBJ_PTR": "py__" + arg.name
                            } + ';')
                        to_cxx.append("<<<")
                        to_cxx.append("}")

                        to_cxx.append(arg.type.declare_var(arg.name, '*' + var_ptr))
            elif arg.type.decl_no_const() == "PyObject *":
                init_expr = "nullptr"
                if arg.defv is not None:
                    init_expr = arg.defv

                block.write_code(arg.type.declare_var(arg.name, init_expr))
            else:  # pointer or argument pass by value
                if arg.type.is_trivial():  # trivial pointer
                    pytype = "PyCapsule_Type"

                    block.write_code("PyObject *py__%s = nullptr;" % arg.name)
                    extracting_code = '(%s) PyCapsule_GetPointer(py__%s, "%s")' % (
                        (arg.type.decl(), arg.name, arg.type.decl_no_const(),)
                    )

                    to_cxx.append(arg.type.declare_var(arg.name, arg.defv if arg.defv else "nullptr"))
                else:
                    pytype = namer.pytype(arg.type.intrinsic_type())

                    block.write_code("extern PyTypeObject %s;" % pytype)
                    block.write_code("PyObject *py__%s = nullptr;" % arg.name)

                    extracting_code = Code.Snippets.external_type_real_ptr % {
                        "CLASS": arg.type.intrinsic_type(),
                        "PYOBJ_PTR": "py__" + arg.name
                    }

                    if not arg.type.is_ptr():  # args pass by value
                        extracting_code = '*' + extracting_code

                        if not arg.defv:
                            init_expr = extracting_code
                            extracting_code = None  # DONE processing
                        else:
                            init_expr = arg.defv

                        to_cxx.append(arg.type.declare_var(arg.name, init_expr))
                    else:
                        to_cxx.append(arg.type.declare_var(arg.name, "nullptr"))

                if arg.type.is_ptr() or arg.defv is not None:
                    memblock = CodeBlock.CodeBlock()

                    if arg.defv is not None:
                        memblock.write_code("if (py__%s) {" % arg.name)
                        memblock.indent()

                    if arg.type.is_ptr():
                        memblock.write_code("if (py__%s != Py_None) {" % arg.name)
                        memblock.indent()

                        memblock.write_code(Code.Snippets.extract_pointer % {
                            "VAR_NAME": arg.name, "PYTYPE": pytype,
                            "POINTER_TYPE": arg.type.intrinsic_type(),
                            "EXTRACTING_CODE": extracting_code,
                            "ERROR_HANDLER": "goto %s;" % error_handler_label,
                        })

                        require_error_handler_label = True

                        memblock.unindent()
                        memblock.write_code("}")
                    else:
                        memblock.write_code("%s = %s;" % (arg.name, extracting_code))

                    if arg.defv is not None:
                        memblock.unindent()
                        memblock.write_code('}')

                    to_cxx += memblock.lines

            if count0 < len(to_cxx):
                to_cxx.append("")
                count0 = len(to_cxx)

        if enable_kw:
            kws = "nullptr"
            if not self.empty():
                kws = ", ".join(['"%s"' % kw for kw in self.get_keywords()] + ["nullptr"])

            block.write_code("const char *py_keywords[] = { %s };" % kws)
            block.append_blank_line()

        parser_idecl = self.build_parser_idecl(namer=namer, enable_kw=enable_kw,
                                               func_name=pyside_debug_name)

        block.write_error_check("!" + parser_idecl, handler=err_return,
                                handler_label=error_handler_label if require_error_handler_label else None)

        block.append_blank_line()
        if len(to_cxx) > 0:
            block.write_lines(to_cxx)
Ejemplo n.º 48
0
    def get_build_value_idecl(self, var_name, py_var_name=None, namer=None, raii=False):
        assert not self.is_pyobject_ptr()

        if py_var_name is None:
            if '.' in var_name:
                intrinsic_name = var_name[(var_name.rindex('.') + 1):]
            elif "->" in var_name:
                intrinsic_name = var_name[(var_name.rindex('>') + 1):]
            else:
                intrinsic_name = var_name

            py_var_name = "py_" + intrinsic_name

        if self.cvt:
            Session.header_jar().add_headers(self.cvt.additional_headers(self))
            return self.cvt.build(self, var_name, py_var_name, namer, raii)
        elif self.is_built_in():
            if self.is_enum():
                var_name = "static_cast<int>(%s)" % var_name
                builder = _built_in["int"]["builder"]
            else:
                builder = _built_in[self.decl_no_const()]["builder"]

            if raii:
                return "pbpp::PyObjectPtr %s(%s(%s));" % (py_var_name, builder, var_name)
            else:
                return "PyObject *%s = %s(%s);" % (py_var_name, builder, var_name)
        elif self.is_ptr_or_ref():
            if self.is_ref():
                ptr = "&%s" % var_name if var_name.isalnum() else "&(%s)" % var_name
                ref = var_name
            else:
                ptr = var_name
                ref = "*%s" % var_name if var_name.isalnum() else "*(%s)" % var_name

            if self.is_trivial():
                template_args = {
                    "VAR": ref if self.is_ref() else ptr,
                    "PY_VAR_NAME": py_var_name,
                    "TYPE_STR": self.decl_no_const(),
                }

                if self.is_ref():
                    if raii:
                        template = Code.Snippets.PyCapsule_New_RAII_Ref
                    else:
                        template = Code.Snippets.PyCapsule_New_Ref
                else:
                    if raii:
                        template = Code.Snippets.PyCapsule_New_RAII_Ptr
                    else:
                        template = Code.Snippets.PyCapsule_New_Ptr

                return template % template_args
            else:
                assert namer is not None

                py_raw_ptr = py_var_name[:2] + "_raw" + py_var_name[2:]
                boilerplate = Code.Snippets.borrow_from_ptr
                if self.is_ref():
                    if raii:
                        boilerplate = Code.Snippets.borrow_from_ref_raii
                    else:
                        boilerplate = Code.Snippets.borrow_from_ref

                ret = boilerplate % {
                    "VAR": var_name,
                    "PY_VAR_NAME": py_var_name,
                    "PY_RAW_PTR": py_raw_ptr,
                    "PTR": ptr, "REF": ref,
                    "CLASS": self.intrinsic_type(),
                    "BORROWER": namer.borrower(self.intrinsic_type()),
                }

                if self.is_ptr():
                    if raii:
                        ret += "\npbpp::PyObjectPtr %s(%s);" %(py_var_name, py_raw_ptr)
                    else:
                        ret += "\nPyObject *%s = %s;" %(py_var_name, py_raw_ptr)

                return ret
        else:
            assert namer is not None

            boilerplate = Code.Snippets.copy_raii if raii else Code.Snippets.copy
            return boilerplate % {
                "VAR": var_name, "PY_VAR_NAME": py_var_name,
                "CLASS": self.intrinsic_type(),
                "COPYER": namer.copyer(self.intrinsic_type()),
            }
Ejemplo n.º 49
0
    def __init__(self, root, node, module, dummy_def=None):
        assert node is not None or dummy_def is not None

        # Only effective while processing
        self.root = root
        self.node = node

        self.namer = module.namer
        self.header_provider = module.header_provider
        self.flags_assigner = module.flags_assigner
        self.blacklist = module.blacklist

        self.all_bases = None
        self.master_bases = None

        self.has_public_copy_ctor = True
        self.final = False

        # No accessible canonical ctors -> disallow subclassing
        # `canonical ctor` refers to a ctor that is not a copy ctor
        self.no_accessible_canonical_ctors = False

        # If true, requires a wrapper class
        # We only save constructors' params, so we can't determine
        # whether the class has any protected constructor when
        # generating the output
        self.has_protected_ctor = False

        # Instantiatable (new-able) != delete-able
        self.dtor_access_type = Access.PUBLIC

        self.protected_nonvirtual_members = set()
        self.public_nonvirtual_methods = []
        self.virtual_members = []
        self.base_vm_collected = False

        self.enums = Enum.Enum()

        self.ctors = []
        self.methods = MethodJar.MethodJar()
        self.fields = []
        self.fptrs = Fptr.FptrManager()

        self.header_jar = HeaderJar.HeaderJar()
        self.header_jar.add_headers(("_Python.hxx", "_Common.hxx",))
        if module.header_decl:
            self.header_jar.add_headers((module.header_decl,))

        # These properties only accessed by the Module class
        self.modified = True
        self.m = None

        # For temporary use only, avoid passing it everywhere
        self.block = CodeBlock.CodeBlock()

        if dummy_def is not None:
            self.name = dummy_def.name
            self.full_name = dummy_def.full_name

            self.enum_class = dummy_def.enum_class

            self.nester = dummy_def.nester
            self.direct_bases = []

            # TODO: namespace alias
            if (not dummy_def.namespace and
                    not dummy_def.nester and
                    not dummy_def.enum_class):
                assert self.name == self.full_name

                self.header_jar.add_global("%s %s;" % (
                    "struct" if dummy_def.is_struct else "class",
                     self.name
                ))

            # Instantiating, destroying, copying or inheriting
            # a dummy class (object) is not allowed

            self.has_public_copy_ctor = False
            self.final = True

            self.no_accessible_canonical_ctors = True
            self.dtor_access_type = Access.PRIVATE
        else:
            Session.begin(self.header_jar)

            self.name = node.attrib["name"]
            self.full_name = node.attrib["demangled"]

            self.enum_class = False

            self.nester = self._get_nester_class()
            self.direct_bases = self._collect_direct_bases()

            self.final = node.attrib.get("final") == "1"

            self._constructors()
            self._destructor()  # Check dtor's access type

            self._methods()
            self._enums(module)
            self._fields()

            Session.end()
Ejemplo n.º 50
0
    def get_extractor_code(self, var_name, py_var_name, error_return, namer=None):
        block = CodeBlock.CodeBlock()

        if self.is_ptr():
            block.write_code(self.declare_var(var_name, "nullptr"))
            block.write_code("if (%s != Py_None) {" % py_var_name)
            block.indent()

        if self.cvt is not None:
            Session.header_jar().add_headers(self.cvt.additional_headers(self))

            negative_checker = self.cvt.negative_checker(self, "(PyObject *) " + py_var_name)
            extracting_code = self.cvt.extracting_code(self, var_name, py_var_name, error_return, namer)
        elif self.is_built_in():
            if self.is_enum():
                dummy_type = "int"
            else:
                dummy_type = self.decl_no_const()

            negative_checker = "!%s((PyObject *) %s)" % (_built_in[dummy_type]["checker"], py_var_name)

            if self.is_bool():
                extracting_code = self.declare_var(var_name, extract_as_bool(py_var_name))
            else:
                extracting_code = Code.Snippets.extract_builtin_type % {
                    "CAST_ENUM": "(%s) " % self.decl() if self.is_enum() else "",
                    "EXTRACTOR": _built_in[dummy_type]["extractor"],
                    "VAR_TYPE": self.decl(),
                    "PY_VAR_NAME": py_var_name,
                    "VAR_NAME": var_name,
                }
        elif self.is_trivial():
            negative_checker = '!PyCapsule_IsValid(%s, "%s")' % (
                py_var_name, self.decl_no_const(),
            )

            extracting_code = '%s = (%s) PyCapsule_GetPointer(%s, "%s");' % (
                var_name, self.decl(), py_var_name, self.decl_no_const(),
            )
        else:
            pytype = namer.pytype(self.intrinsic_type())
            block.write_code("extern PyTypeObject %s;" % pytype)

            negative_checker = "!PyObject_TypeCheck(%s, &%s)" % (py_var_name, pytype)

            if not self.is_ptr():
                extracting_code = self.declare_var(var_name,
                    '*' + Code.Snippets.external_type_real_ptr % {
                        "CLASS": self.intrinsic_type(),
                        "PYOBJ_PTR": py_var_name,
                    })
            else:
                extracting_code = (var_name + " = " +
                   Code.Snippets.external_type_real_ptr % {
                        "CLASS": self.intrinsic_type(),
                        "PYOBJ_PTR": py_var_name,
                    } + ';')

        block.write_code(Code.Snippets.single_var_extractor % {
            "NEGATIVE_CHECKER": negative_checker,
            "VAR_TYPE": self.decl(),
            "PY_VAR_NAME": py_var_name,
            "VAR_NAME": var_name,
            "ERROR_RETURN": error_return,
            "EXTRACTING_CODE": extracting_code,
        })

        if self.is_ptr():
            block.unindent()
            block.write_code('}')

        return block.flush()
Ejemplo n.º 51
0
def _test():
    import CodeBlock
    import Converters
    import HeaderJar

    header_jar = HeaderJar.HeaderJar()
    Session.begin(header_jar)

    Converters.add(Converters.WcsConv())

    tk = TupleAndKeywords()
    tk.add_parameter(Argument.Argument(Types.Type(("int", "*",), 1, "FundamentalType"), "foo"))
    tk.add_parameter(Argument.Argument(Types.Type(("double", "&",), 2, "FundamentalType"), "bar"))
    tk.add_parameter(Argument.Argument(Types.Type(("long unsigned int", "&", "const",), 3, "FundamentalType"), "xyz"))
    tk.add_parameter(Argument.Argument(Types.Type(("X", "const", "&",), 4, "Class"), "x"))
    tk.add_parameter(Argument.Argument(Types.Type(("Y", "*",), 5, "Class"), "y"))
    tk.add_parameter(Argument.Argument(Types.Type(("Z",), 6, "Class"), "z"))
    tk.add_parameter(Argument.Argument(Types.Type(("bool",), 7, "FundamentalType"), "b"))
    tk.add_parameter(Argument.Argument(Types.Type(("wchar_t", "const", "*",), 8, "PointerType"), "str"))

    print(tk.get_fmt_specifier())
    print(tk.get_keywords())
    print(tk.build_function_signature_parameter_list())

    from Module import PythonNamer
    namer = PythonNamer()

    print(tk.build_parser_idecl(namer=namer))
    _print_empty_line()

    block = CodeBlock.CodeBlock()
    tk.write_args_parsing_code(block, namer, True, "return nullptr;", "<TEST>")

    print(block.flush())
    _print_empty_line()
    _print_empty_line()

    tk = TupleAndKeywords()
    tk.add_parameter(Argument.Argument(Types.Type(("int", "*",), 1, "FundamentalType"), "foo", "nullptr"))
    tk.add_parameter(Argument.Argument(Types.Type(("double", "&",), 2, "FundamentalType"), "bar", "PI"))
    tk.add_parameter(Argument.Argument(Types.Type(("long unsigned int", "&", "const",), 3, "FundamentalType"), "xyz", "MAXINT"))
    tk.add_parameter(Argument.Argument(Types.Type(("X", "const", "&",), 4, "Class"), "x", "_x"))
    tk.add_parameter(Argument.Argument(Types.Type(("Y", "*",), 5, "Class"), "y", "_py"))
    tk.add_parameter(Argument.Argument(Types.Type(("Z",), 6, "Class"), "z", "Z(1990)"))
    tk.add_parameter(Argument.Argument(Types.Type(("bool",), 7, "FundamentalType"), "b", "true"))
    tk.add_parameter(Argument.Argument(Types.Type(("wchar_t", "const", "*",), 8, "PointerType"), "str", 'L"Hello world!"'))
    tk.write_args_parsing_code(block, namer, True, "return nullptr;", "<TEST>")

    print(block.flush())

    integer = Types.Type(("int",), 99, "FundamentalType")
    Converters.add(Converters.ListConv(integer))

    tk = TupleAndKeywords()
    tk.add_parameter(Argument.Argument(Types.Type(("std::vector<int>", "const", "&",), 0, "Class"), "vi", "_vi"))
    tk.write_args_parsing_code(block, namer, True, "return nullptr;", "<TEST>")

    print(block.flush())

    K = Types.Type(("wchar_t", "const", "*",), 111, "PointerType")
    V = Types.Type(("wxColour", "*",), 112, "PointerType")
    Converters.add(Converters.DictConv(K, V))

    tk = TupleAndKeywords()
    tk.add_parameter(Argument.Argument(Types.Type(("std::map<wchar_t const *, wxColour *>", "&",), 0, "Class"), "m"))
    tk.write_args_parsing_code(block, namer, True, "return nullptr;", "<TEST>")

    print(block.flush())