bool CWizDatabaseManager::openWithInfo(const QString& strKbGUID, const WIZDATABASEINFO* pInfo)
{
    Q_ASSERT(!m_strUserId.isEmpty());

    if (isOpened(strKbGUID))
        return true;

    CWizDatabase* db = new CWizDatabase();

    if (!db->Open(m_strUserId, strKbGUID)) {
        delete db;
        return false;
    }
    //
    if (pInfo)
    {
        db->InitDatabaseInfo(*pInfo);
    }

    if (strKbGUID.isEmpty()) {
        m_dbPrivate = db;

        // take ownership immediately
        connect(db, SIGNAL(databaseOpened(CWizDatabase*, const QString&)),
                SLOT(on_groupDatabaseOpened(CWizDatabase*, const QString&)),
                Qt::BlockingQueuedConnection);
    } else {
        m_mapGroups[strKbGUID] = db;
    }

    initSignals(db);

    Q_EMIT databaseOpened(strKbGUID);
    return true;
}
Exemple #2
0
	void write(const User* pUser, const std::string& content)
	{
		if (!isOpened())//если файл не открыт
		{
			log_.emplace_back("File not opened");
			throw ClosedException(name_);
		}

		if (pUser != pOwner_) //если пользователь не владеет файлом
		{
			log_.emplace_back("File belongs to '" + pOwner_->name()
				+ "' but '" + pUser->name() + "' wants to modify it");
			throw OwnerException(pOwner_->name());
		}

		if (readOnly_) //файл только для чтения
		{
			log_.emplace_back("File is read only");
			throw ReadOnlyException(name_);
		}

		log_.emplace_back("File was modified by user '" + pUser_->name() + "'");

		content_ = content;
	}
bool rspfDirectoryTree::getFirst(rspfFilename &filename, int flags)
{
   bool result = false;
   theFlags    = flags | rspfDirectory::RSPF_DIR_DIRS;
   if(theCurrentDirectoryData && isOpened())
   {
      result = theCurrentDirectoryData->theDirectory->getFirst(filename,
                                                               flags);
      while(result&&filename.isDir())
      {
         checkToPushDirectory(filename);
         result = theCurrentDirectoryData->theDirectory->getNext(filename);
      }

      if(!result)
      {
         if(!theDirectoryQueue.empty())
         {
            rspfFilename newDir = theDirectoryQueue.front();
            theDirectoryQueue.pop();
            theCurrentDirectoryData->theDirectory->open(newDir);
            
            return getFirst(filename, flags);
         }
      }
   }
   
   return result;
}
// Close OpenNI2 device
int Oni2Grabber::close() 
{
	// (1) Check
	if(!isOpened())
		return 1;

	// (2) Close camera
	try 
	{
		if(enable_depth_)
			stopAndDestroyStream_(depth_stream_);
		if(enable_infrared_)
			stopAndDestroyStream_(infrared_stream_);
		if(enable_color_)
			stopAndDestroyStream_(color_stream_);
		streams_.clear();
		device_.close();
	} 
	catch(std::exception &) 
	{
		std::cerr << openni::OpenNI::getExtendedError() << std::endl;
	}
    
	// (3) Set parameters
	if(isDebugMode())
		std::cout << " Successfully closed." << std::endl;

	setClosed_();
	return 0;
}
Exemple #5
0
void raw_serial::clearDTR()
{
    if ( !isOpened() ) return;

    uint32_t dtr_bit = TIOCM_DTR;
    ioctl(serial_fd, TIOCMBIC, &dtr_bit);
}
Exemple #6
0
bool FileHandle::open(const sys::fs::Path& pPath,
                      FileHandle::OpenMode pMode,
                      FileHandle::Permission pPerm) {
  if (isOpened() || Unknown == pMode) {
    setState(BadBit);
    return false;
  }

  m_OpenMode = pMode;
  if (System == pPerm)
    m_Handler = sys::fs::detail::open(pPath, oflag(pMode));
  else
    m_Handler = sys::fs::detail::open(pPath, oflag(pMode),
                                      static_cast<int>(pPerm));

  m_Path = pPath;
  if (m_Handler == -1) {
    m_OpenMode = OpenMode(NotOpen);
    setState(FailBit);
    return false;
  }

  if (!get_size(m_Handler, m_Size)) {
    setState(FailBit);
    return false;
  }

  return true;
}
Exemple #7
0
	void Door::interact(const Entity *interactor) {
		DoorState target;

		if(isOpened())
			target = DoorState::closed;
		else {
			if(!m_key.isDummy()) {
				const Actor *actor = dynamic_cast<const Actor*>(interactor);
				if(!actor || actor->inventory().find(m_key) == -1) {
					printf("Key required!\n");
					return;
				}
			}

			target = classId() == DoorClassId::rotating_out? DoorState::opened_out : DoorState::opened_in;
			if(classId() == DoorClassId::rotating && interactor) {
				float3 interactor_pos = interactor->boundingBox().center();
				float3 dir = boundingBox().center() - interactor_pos;
				if(dot(dir.xz(), m_open_in_dir) < 0.0f)
					target = DoorState::opened_out;
			}
		}
		
		changeState(target);
		//TODO: open direction should depend on interactor's position		
	}
Exemple #8
0
int raw_serial::waitforrecv(_u32 timeout, size_t * returned_size)
{
    if (!isOpened() ) return -1;
   
    if (returned_size) *returned_size = required_rx_cnt;
    return 0;
}
/**
	@brief	close stream
*/
void ofxKinectNui::close(){
	if(isOpened()){
		kinect.Shutdown();
		bIsOpened = false;
		bIsFrameNew = false;
	}
}
Exemple #10
0
bool StXDisplay::open() {
    hDisplay = XOpenDisplay(NULL); // get first display on server from DISPLAY in env
    //hDisplay = XOpenDisplay(":0.0");
    //hDisplay = XOpenDisplay("somehost:0.0");
    //hDisplay = XOpenDisplay("192.168.1.10:0.0");
    if(isOpened()) {
        initAtoms();

        hInputMethod = XOpenIM(hDisplay, NULL, NULL, NULL);
        if(hInputMethod == NULL) {
            return true;
        }

        XIMStyles* anIMStyles = NULL;
        char* anIMValues = XGetIMValues(hInputMethod, XNQueryInputStyle, &anIMStyles, NULL);
        if(anIMValues != NULL
        || anIMStyles == NULL
        || anIMStyles->count_styles <= 0) {
            // input method doesn't support any styles
            if(anIMStyles != NULL) {
                XFree(anIMStyles);
            }
            return true;
        }
        const XIMStyle anIMStyle = anIMStyles->supported_styles[0];
        XFree(anIMStyles);

        hInputCtx = XCreateIC(hInputMethod, XNInputStyle, anIMStyle, NULL);

        return true;
    }
    return false;
}
Exemple #11
0
bool VideoCapture::open(const String& filename, int apiPreference)
{
    CV_TRACE_FUNCTION();

    if (isOpened()) release();

    const std::vector<VideoBackendInfo> backends = cv::videoio_registry::getAvailableBackends_CaptureByFilename();
    for (size_t i = 0; i < backends.size(); i++)
    {
        const VideoBackendInfo& info = backends[i];
        if (apiPreference == CAP_ANY || apiPreference == info.id)
        {
            CvCapture* capture = NULL;
            VideoCapture_create(capture, icap, info.id, filename);
            if (!icap.empty())
            {
                if (icap->isOpened())
                    return true;
                icap.release();
            }
            if (capture)
            {
                cap.reset(capture);
                // assume it is opened
                return true;
            }
        }
    }
    return false;
}
/**
	@brief	open stream
*/
bool ofxKinectNui::open(bool nearmode /*= false */){
	if(kinect.IsConnected() && !isOpened()){
		bIsNearmode = nearmode;
		if(isInited()){
			if(!kinect.IsInited()){
				init(bGrabsVideo, bGrabsDepth, bGrabsLabel, bGrabsSkeleton, mVideoResolution, mDepthResolution);
			}
		}
		if(bGrabsVideo){
			kinect.VideoStream().Open(NUI_IMAGE_TYPE_COLOR, mVideoResolution);
		}
		if(bGrabsDepth){
			if(bGrabsLabel || bGrabsLabelCv){
				kinect.DepthStream().Open(NUI_IMAGE_TYPE_DEPTH_AND_PLAYER_INDEX, mDepthResolution, nearmode);
			}else{
				kinect.DepthStream().Open(NUI_IMAGE_TYPE_DEPTH, mDepthResolution, nearmode);
			}
		}
		if(bGrabsAudio){
			kinect.AudioStream().Open();
		}

		bIsOpened = true;
		return true;
	}
	ofLog(OF_LOG_ERROR, "ofxKinectNui: Cannot open stream.");
	return false;
}
Exemple #13
0
bool SerialPort::waitForReadyRead(int ms)
{
    if (!isOpened())
    {
        return false;
    }
#ifndef _WINDOWS
    fd_set fileSet;
    FD_ZERO(&fileSet);
    FD_SET(fd_, &fileSet);

    struct timeval timeout;
    timeout.tv_sec = 0;
    timeout.tv_usec = ms * 1000;
    int n = select(fd_ + 1, &fileSet, NULL, &fileSet, &timeout);
    if (!n)
    {
        qDebug("select timeout.");
        return false;
    }

    int queue = 0;
    if (n==-1 || ioctl(fd_, FIONREAD, &queue)==-1)
    {
        qDebug("no queue.");
        return false;
    }
#endif
    return true;
}
Exemple #14
0
bool Dl::open( const char_type *path, bool global, bool resolve )
{
	// Библиотека уже открыта
	if( isOpened() ) { return false; }
#ifdef _WIN32
	DWORD dwFlags = 0;
	global = global;
	if( !resolve ) dwFlags |= DONT_RESOLVE_DLL_REFERENCES;
	m_handle = LoadLibraryEx(path, NULL, dwFlags);
	if( !m_handle ) {
	   // report error ...
	} else {
	   // use the result in a call to GetProcAddress
	}
#else
	::dlerror(); // clear error
	m_handle = ::dlopen( path, (global ? RTLD_GLOBAL : RTLD_LOCAL) | ( resolve ? RTLD_NOW : RTLD_LAZY ) );
	if( !m_handle ) {
		JQ_ERROR( ::dlerror() );
		//DlFactory::instance()->setError(-1, ::dlerror());
	}
#endif

	return !isDlHandleInvalid();
}
void DBConn::close() {
  if (isOpened()) {
    mysql_close(m_conn);
    m_conn = nullptr;
    m_server.reset();
  }
}
Exemple #16
0
bool raw_serial::open(const char * portname, _u32 baudrate, _u32 flags)
{
    if (isOpened()) close();
    
    _serial_handle = CreateFile(
        portname,
        GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
        NULL
        );

    if (_serial_handle == INVALID_HANDLE_VALUE) return false;

    if (!SetupComm(_serial_handle, SERIAL_RX_BUFFER_SIZE, SERIAL_TX_BUFFER_SIZE))
    {
        close();
        return false;
    }
    
    _dcb.BaudRate = baudrate;
    _dcb.ByteSize = 8;
    _dcb.Parity   = NOPARITY;
    _dcb.StopBits = ONESTOPBIT;
    _dcb.fDtrControl = DTR_CONTROL_ENABLE;

    if (!SetCommState(_serial_handle, &_dcb))
    {
        close();
        return false;
    }

    //Clear the DTR bit to let the motor spin
    EscapeCommFunction(_serial_handle, CLRDTR);

    if (!SetCommTimeouts(_serial_handle, &_co))
    {
        close();
        return false;
    }

    if (!SetCommMask(_serial_handle, EV_RXCHAR | EV_ERR ))
    {
        close();
        return false;
    }

    if (!PurgeComm(_serial_handle, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR ))
    {
        close();
        return false;
    }

    Sleep(30); 
    _is_serial_opened = true;
    return true;
}
Exemple #17
0
bool DBClass::nonSelectSql( QString sqlStr  )
{
    isOpened ();
    QSqlQuery query ( sqlStr );


    return query.exec();
}
Exemple #18
0
int CRhoFile::readData(void* buffer, int bufOffset, int bytesToRead)
{
    if ( !isOpened() )
        return -1;
    
    int nSize = fread(((char*)buffer)+bufOffset, 1, bytesToRead, m_file);
    return nSize > 0 ? nSize : -1;
}
 void AudioDecoderOgg::close()
 {
     if (isOpened())
     {
         ov_clear(&_vf);
         _isOpened = false;
     }
 }
Exemple #20
0
void raw_serial::setDTR()
{
  if(!isOpened()) return;
  uint32_t status;
  ioctl(serial_fd, TIOCMGET, &status);
  status |= TIOCM_DTR;
  ioctl(serial_fd, TIOCMSET, &status);
}
Exemple #21
0
void P2pEndpoint::read()
{
    if (! isOpened()) {
        return;
    }

    (void)handle_input(0);
}
Exemple #22
0
_word_size_t raw_serial::rxqueue_count()
{
    if  ( !isOpened() ) return 0;
    size_t remaining;
    
    if (::ioctl(serial_fd, FIONREAD, &remaining) == -1) return 0;
    return remaining;
}
void Private_Impl::setRotation ( int rotation ) {
    while ( rotation < 0 )
        rotation += 360;
    if ( rotation >= 360 )
        rotation = rotation % 360;
    State.rotation = rotation;
    if ( isOpened() ) commitRotation();
}
// Copy raw data of infrared
int StructureGrabber::copyInfraredDataTo(unsigned short* infrared_data) const {
	if(!isOpened())
		return 1;
	if(!isInfraredAvailable())
		return 2;
	std::memcpy(infrared_data, getInfraredDataPtr(), getSize() * sizeof(unsigned short));
	return 0;
}
// Copy raw data of depth
int StructureGrabber::copyDepthDataTo(unsigned short* depth_data) const {
	if(!isOpened())
		return 1;
	if(!isDepthDataAvailable())
		return 2;
	std::memcpy(depth_data, getDepthDataPtr(), getSize() * sizeof(unsigned short));
	return 0;
}
Exemple #26
0
bool raw_serial::open(const char * portname, uint32_t baudrate, uint32_t flags)
{
    if (isOpened()) close();
    
    serial_fd = ::open(portname, O_RDWR | O_NOCTTY | O_NDELAY);

    if (serial_fd == -1) return false;

    struct termios options, oldopt;
    tcgetattr(serial_fd, &oldopt);
	bzero(&options,sizeof(struct termios));

    _u32 termbaud = getTermBaudBitmap(baudrate);

    if (termbaud == (_u32)-1) {
        close();
        return false;
    }
    cfsetispeed(&options, termbaud);
    cfsetospeed(&options, termbaud);
	
	// enable rx and tx
	options.c_cflag |= (CLOCAL | CREAD);


    options.c_cflag &= ~PARENB; //no checkbit
	options.c_cflag &= ~CSTOPB; //1bit stop bit

	options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8; /* Select 8 data bits */

#ifdef CNEW_RTSCTS
    options.c_cflag &= ~CNEW_RTSCTS; // no hw flow control
#endif

    options.c_iflag &= ~(IXON | IXOFF | IXANY); // no sw flow control

    // raw input mode   
    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    // raw output mode   
    options.c_oflag &= ~OPOST;
    
    tcflush(serial_fd,TCIFLUSH); 

    if (fcntl(serial_fd, F_SETFL, FNDELAY))
    {
        close();
        return false;
    }
    if (tcsetattr(serial_fd, TCSANOW, &options))
    {
        close();
        return false;
    }
    
    _is_serial_opened = true;
    return true;
}
void DBConn::open(ServerDataPtr server, int connectTimeout /* = -1 */,
                  int readTimeout /* = -1 */) {
  if (isOpened()) {
    close();
  }

  if (connectTimeout <= 0) connectTimeout = DefaultConnectTimeout;
  if (readTimeout <= 0) readTimeout = DefaultReadTimeout;

  m_conn = mysql_init(nullptr);
  MySQLUtil::set_mysql_timeout(m_conn, MySQLUtil::ConnectTimeout,
                               connectTimeout);
  MySQLUtil::set_mysql_timeout(m_conn, MySQLUtil::ReadTimeout, readTimeout);
  MYSQL *ret = mysql_real_connect(m_conn, server->getIP().c_str(),
                                  server->getUserName().c_str(),
                                  server->getPassword().c_str(),
                                  server->getDatabase().c_str(),
                                  server->getPort(), nullptr, 0);
  if (!ret) {
    int code = mysql_errno(m_conn);
    const char *msg = mysql_error(m_conn);
    string smsg = msg ? msg : "";
    mysql_close(m_conn);
    m_conn = nullptr;
    throw DBConnectionException(code, server->getIP().c_str(),
                                server->getDatabase().c_str(),
                                smsg.c_str());
  }

  // Setting session variables
  if (server->getSessionVariables().size()) {
    string sessionCmd = string("SET ");
    for (SessionVariableVec::const_iterator iter =
         server->getSessionVariables().begin(); iter !=
         server->getSessionVariables().end(); iter++) {
      if (iter != server->getSessionVariables().begin()) {
        sessionCmd += ", ";
      }
      sessionCmd += string("SESSION ") + iter->first + string("=") +
                    iter->second;
    }

    char *sessionVarSQL = (char*)Util::safe_malloc(sessionCmd.length() * 2 + 1);
    mysql_real_escape_string(m_conn, sessionVarSQL, sessionCmd.c_str(),
      sessionCmd.length());
    bool failure = mysql_query(m_conn, sessionVarSQL);
    Util::safe_free(sessionVarSQL);
    if (failure) {
      int code = mysql_errno(m_conn);
      throw DatabaseException(code, "Failed to execute SQL '%s': %s (%d)",
                              sessionCmd.c_str(), mysql_error(m_conn), code);
    }
  }

  m_server = server;
  m_connectTimeout = connectTimeout;
  m_readTimeout = readTimeout;
}
Exemple #28
0
PtrLen<char> PrintFile::do_provide(ulen)
 {
  if( !isOpened() ) 
    {
     Printf(Exception,"CCore::PrintFile::do_provide(...) : file is not opened");
    }
 
  return Range(buf);
 }
int RawSocketDevice::sendPackets(const RawPacketVector& packetVec)
{
#if defined(WIN32) || defined(WINx64) || defined(PCAPPP_MINGW_ENV)

	LOG_ERROR("Sending packets with raw socket are not supported on Windows");
	return false;

#elif LINUX

	if (!isOpened())
	{
		LOG_ERROR("Device is not open");
		return 0;
	}

	int fd = ((SocketContainer*)m_Socket)->fd;

	sockaddr_ll addr;
	memset(&addr, 0, sizeof(struct sockaddr_ll));
	addr.sll_family = htons(PF_PACKET);
	addr.sll_protocol = htons(ETH_P_ALL);
	addr.sll_halen = 6;
	addr.sll_ifindex = ((SocketContainer*)m_Socket)->interfaceIndex;

	int sendCount = 0;

	for (RawPacketVector::ConstVectorIterator iter = packetVec.begin(); iter != packetVec.end(); iter++)
	{
		Packet packet(*iter, OsiModelDataLinkLayer);
		if (!packet.isPacketOfType(pcpp::Ethernet))
		{
			LOG_DEBUG("Can't send non-Ethernet packets");
			continue;
		}

		EthLayer* ethLayer = packet.getLayerOfType<EthLayer>();
		MacAddress dstMac = ethLayer->getDestMac();
		dstMac.copyTo((uint8_t*)&(addr.sll_addr));

		if (::sendto(fd, (*iter)->getRawData(), (*iter)->getRawDataLen(), 0, (struct sockaddr*)&addr, sizeof(addr)) == -1)
		{
			LOG_DEBUG("Failed to send packet. Error was: '%s'", strerror(errno));
			continue;
		}

		sendCount++;
	}

	return sendCount;

#else

	LOG_ERROR("Raw socket are not supported on this platform");
	return false;

#endif
}
Exemple #30
0
void CRhoFile::readString(String& strData){
    if ( !isOpened() )
        return;

    int nSize = size();
    strData.resize(nSize);
    nSize = fread(&strData[0], 1, nSize, m_file);
    strData[nSize] = 0;
}