コード例 #1
0
BOOL CIocpServer::Start(LPCTSTR pszBindAddress, USHORT usPort)
{
	if(!CheckParams() || !CheckStarting())
		return FALSE;

	//创建监听套接字开始监听端口
	if(CreateListenSocket(pszBindAddress, usPort))
	{
		if(CreateCompletePort())
		{
			if(CreateWorkerThreads())
			{
				if(StartAcceptThread())
				{
					m_enState = SS_STARTED;
					return TRUE;
				}
			}
		}
	}


	Stop();

	return FALSE;
}
コード例 #2
0
ファイル: KronGen.cpp プロジェクト: KronGen/KronTest
// generates Kronecker model using configuration model of small model network
// and compare it to big network
void KroneckerBySample(vector<TStr> CommandLineArgs){
    Try
        Env = TEnv(CommandLineArgs[KRONTEST], TNotify::NullNotify);
    // generation of big model and its Kronecker product is required
    const TStr Gen = Env.GetIfArgPrefixStr("-gen:", "model+kron", "Generation of sample or/and its Kronecker product (model, kron, model+kron)");
    // plot type
    const TStr Plt = Env.GetIfArgPrefixStr("-plt:", "all", "Type of plots (cum, noncum, all)");
    // time estimates file name
    const TStr StatFile = Env.GetIfArgPrefixStr("-ot:", "stat.tab", "Name of output file with statistics");

    TFile = OpenFile(StatFile.CStr());
    CheckParams(Gen, Plt);
    
    PyInit("PySettings.txt");
      

    if (Gen != "none")
    {
        vector <TStr> Parameters;
        GetParameters(CommandLineArgs, Parameters);
        // name is empty
        Parameters.push_back("");
        GetGraphs(Parameters, Gen, Plt);
    }
    

    Py_Finalize();

    Catch
}
コード例 #3
0
ファイル: TcpClient.cpp プロジェクト: cxc3214/HP-Socket
BOOL CTcpClient::Start(LPCTSTR pszRemoteAddress, USHORT usPort, BOOL bAsyncConnect)
{
	if(!CheckParams() || !CheckStarting())
		return FALSE;

	BOOL isOK		= FALSE;
	m_bAsyncConnect	= bAsyncConnect;

	if(CreateClientSocket())
	{
		if(FirePrepareConnect(m_dwConnID, m_soClient) != HR_ERROR)
		{
			if(ConnectToServer(pszRemoteAddress, usPort))
			{
				if(CreateWorkerThread())
					isOK = TRUE;
				else
					SetLastError(SE_WORKER_THREAD_CREATE, __FUNCTION__, ERROR_CREATE_FAILED);
			}
			else
				SetLastError(SE_CONNECT_SERVER, __FUNCTION__, ::WSAGetLastError());
		}
		else
			SetLastError(SE_SOCKET_PREPARE, __FUNCTION__, ERROR_FUNCTION_FAILED);
	}
	else
		SetLastError(SE_SOCKET_CREATE, __FUNCTION__, ::WSAGetLastError());

	if(!isOK) Stop();

	return isOK;
}
コード例 #4
0
unsigned int optimize(PanoramaData& pano,
                      const char * userScript)
{
    char * script = 0;
    unsigned int retval = 0;

    if (userScript == 0) {
        std::ostringstream scriptbuf;
        UIntSet allImg;
        fill_set(allImg,0, unsigned(pano.getNrOfImages()-1));
        pano.printPanoramaScript(scriptbuf, pano.getOptimizeVector(), pano.getOptions(), allImg, true);
        script = strdup(scriptbuf.str().c_str());
    } else {
        script = const_cast<char *>(userScript);
    }

    OptInfo		opt;
	AlignInfo	ainf;

    if (ParseScript( script, &ainf ) == 0)
	{
		if( CheckParams( &ainf ) == 0 )
		{
			ainf.fcn	= fcnPano;
			
			SetGlobalPtr( &ainf ); 
			
			opt.numVars 		= ainf.numParam;
			opt.numData 		= ainf.numPts;
			opt.SetVarsToX		= SetLMParams;
			opt.SetXToVars		= SetAlignParams;
			opt.fcn			= ainf.fcn;
			*opt.message		= 0;

			RunLMOptimizer( &opt );
			ainf.data		= opt.message;
            // get results from align info.
#ifdef DEBUG_WRITE_OPTIM_OUTPUT
            fullPath path;
            StringtoFullPath(&path, DEBUG_WRITE_OPTIM_OUTPUT_FILE );

		    ainf.data		= opt.message;
            WriteResults( script, &path, &ainf, distSquared, 0);
#endif
            pano.updateVariables( GetAlignInfoVariables(ainf) );
            pano.updateCtrlPointErrors( GetAlignInfoCtrlPoints(ainf) );
		} else {
            std::cerr << "Bad params" << std::endl;
            retval = 2;
        }
		DisposeAlignInfo( &ainf );
    } else {
        std::cerr << "Bad params" << std::endl;
        retval = 1;
    }
    if (! userScript) {
        free(script);
    }
    return retval;
}
コード例 #5
0
int main(int argc,char *argv[])
{
	aPrefs		aP;

	char*		script;
	OptInfo		opt;
	AlignInfo	ainf;

	fullPath	infile;
	//fullPath	outfile;

	//	

	SetAdjustDefaults(&aP);

	if(argc != 2)
	{
		printf(PT_OPTIMIZER_VERSION);
		printf("Usage: %s /path/to/script.txt\n", argv[0]);
		exit(1);
	}

	StringtoFullPath(&infile, argv[1]);

	script = LoadScript( &infile );
	if( script != NULL )
	{
		if (ParseScript( script, &ainf ) == 0)
		{
			if( CheckParams( &ainf ) == 0 )
			{
				ainf.fcn	= fcnPano;
				
				SetGlobalPtr( &ainf ); 
				
				opt.numVars 		= ainf.numParam;
				opt.numData 		= ainf.numPts;
				opt.SetVarsToX		= SetLMParams;
				opt.SetXToVars		= SetAlignParams;
				opt.fcn			= ainf.fcn;
				*opt.message		= 0;

				RunLMOptimizer( &opt );
				ainf.data		= opt.message;
				WriteResults( script, &infile, &ainf, distSquared, 0);
				exit(0);
			}
      //TODO: if optCreatePano is 1 then should call stitcher  OR  the option removed
      //if (ainf.sP.optCreatePano == 1)
      //{
      //   Stitch();
      //}
			DisposeAlignInfo( &ainf );
		}
		free( script );
	}
	exit(1);
}
コード例 #6
0
ファイル: hyperlinkg.cpp プロジェクト: syneryder/winsparkle
bool wxGenericHyperlinkCtrl::Create(wxWindow *parent, wxWindowID id,
                                    const wxString& label, const wxString& url, const wxPoint& pos,
                                    const wxSize& size, long style, const wxString& name)
{
    // do validation checks:
    CheckParams(label, url, style);

    if ((style & wxHL_ALIGN_LEFT) == 0)
        style |= wxFULL_REPAINT_ON_RESIZE;

    if (!wxControl::Create(parent, id, pos, size, style, wxDefaultValidator, name))
        return false;

    // set to non empty strings both the url and the label
    SetURL(url.empty() ? label : url);
    SetLabel(label.empty() ? url : label);

    m_rollover = false;
    m_clicking = false;
    m_visited = false;

    // colours
    m_normalColour = *wxBLUE;
    m_hoverColour = *wxRED;
    m_visitedColour = wxColour("#551a8b");
    SetForegroundColour(m_normalColour);

    // by default the font of an hyperlink control is underlined
    wxFont f = GetFont();
    f.SetUnderlined(true);
    SetFont(f);

    SetInitialSize(size);


    // connect our event handlers:
    // NOTE: since this class is the base class of the GTK+'s native implementation
    //       of wxHyperlinkCtrl, we cannot use the static macros in BEGIN/END_EVENT_TABLE
    //       blocks, otherwise the GTK+'s native impl of wxHyperlinkCtrl would not
    //       behave correctly (as we intercept events doing things which interfere
    //       with GTK+'s native handling):

    Connect( wxEVT_PAINT, wxPaintEventHandler(wxGenericHyperlinkCtrl::OnPaint) );
    Connect( wxEVT_LEAVE_WINDOW, wxMouseEventHandler(wxGenericHyperlinkCtrl::OnLeaveWindow) );

    Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler(wxGenericHyperlinkCtrl::OnLeftDown) );
    Connect( wxEVT_LEFT_UP, wxMouseEventHandler(wxGenericHyperlinkCtrl::OnLeftUp) );
    Connect( wxEVT_RIGHT_UP, wxMouseEventHandler(wxGenericHyperlinkCtrl::OnRightUp) );
    Connect( wxEVT_MOTION, wxMouseEventHandler(wxGenericHyperlinkCtrl::OnMotion) );

    Connect( wxHYPERLINK_POPUP_COPY_ID, wxEVT_COMMAND_MENU_SELECTED,
             wxCommandEventHandler(wxGenericHyperlinkCtrl::OnPopUpCopy) );

    return true;
}
コード例 #7
0
ファイル: hyperlink.cpp プロジェクト: jonntd/dynamica
bool wxHyperlinkCtrl::Create(wxWindow *parent, wxWindowID id,
    const wxString& label, const wxString& url, const wxPoint& pos,
    const wxSize& size, long style, const wxString& name)
{
    if ( UseNative() )
    {
        // do validation checks:
        CheckParams(label, url, style);

        if (!PreCreation( parent, pos, size ) ||
            !CreateBase( parent, id, pos, size, style, wxDefaultValidator, name ))
        {
            wxFAIL_MSG( wxT("wxHyperlinkCtrl creation failed") );
            return false;
        }

        m_widget = gtk_link_button_new("asdfsaf asdfdsaf asdfdsa");
        g_object_ref(m_widget);
        gtk_widget_show(m_widget);

        // alignment
        float x_alignment = 0.5;
        if (HasFlag(wxHL_ALIGN_LEFT))
            x_alignment = 0.0;
        else if (HasFlag(wxHL_ALIGN_RIGHT))
            x_alignment = 1.0;
        gtk_button_set_alignment(GTK_BUTTON(m_widget), x_alignment, 0.5);

        // set to non empty strings both the url and the label
        SetURL(url.empty() ? label : url);
        SetLabel(label.empty() ? url : label);

        // our signal handlers:
        g_signal_connect_after (m_widget, "clicked",
                                G_CALLBACK (gtk_hyperlink_clicked_callback),
                                this);

        m_parent->DoAddChild( this );

        PostCreation(size);
        SetInitialSize(size);

        // wxWindowGTK will connect to the enter_notify and leave_notify GTK+ signals
        // thus overriding GTK+'s internal signal handlers which set the cursor of
        // the widget - thus we need to manually set it here:
        SetCursor(wxCursor(wxCURSOR_HAND));
    }
    else
        return wxGenericHyperlinkCtrl::Create(parent, id, label, url, pos, size, style, name);

    return true;
}
コード例 #8
0
ファイル: UpwindSolver.cpp プロジェクト: certik/nektar
/**
 * @brief Upwind Riemann solver
 *
 * @param pL     Perturbation pressure left state
 * @param rhoL   Perturbation density left state
 * @param pR     Perturbation pressure right state
 * @param rhoR   Perturbation density right state
 * @param uL     x perturbation velocity component left state
 * @param uR     x perturbation velocity component right state
 * @param vL     y perturbation velocity component left state
 * @param vR     y perturbation velocity component right state
 * @param wL     z perturbation velocity component left state
 * @param wR     z perturbation velocity component right state
 * @param p0     Base pressure
 * @param rho0   Base density
 * @param u0     Base x velocity component
 * @param v0     Base y velocity component
 * @param w0     Base z velocity component
 * @param pF     Computed Riemann flux for perturbation pressure
 * @param rhoF   Computed Riemann flux for perturbation density
 * @param uF     Computed Riemann flux for x perturbation velocity component
 * @param vF     Computed Riemann flux for y perturbation velocity component
 * @param wF     Computed Riemann flux for z perturbation velocity component
 */
void UpwindSolver::v_PointSolve(
    NekDouble  pL, NekDouble  rhoL, NekDouble  uL, NekDouble  vL, NekDouble  wL,
    NekDouble  pR, NekDouble  rhoR, NekDouble  uR, NekDouble  vR, NekDouble  wR,
    NekDouble  p0, NekDouble  rho0, NekDouble  u0, NekDouble  v0, NekDouble  w0,
    NekDouble &pF, NekDouble &rhoF, NekDouble &uF, NekDouble &vF, NekDouble &wF)
{
    // fetch params
    ASSERTL1(CheckParams("Gamma"), "Gamma not defined.");
    const NekDouble &gamma = m_params["Gamma"]();

    // Speed of sound
    NekDouble c = sqrt(gamma * p0 / rho0);

    Array<OneD, NekDouble> characteristic(4);
    Array<OneD, NekDouble> W(2);
    Array<OneD, NekDouble> lambda(2);

    // compute the wave speeds
    lambda[0] = u0 + c;
    lambda[1] = u0 - c;

    // calculate the caracteristic variables
    //left characteristics
    characteristic[0] = pL/2 + uL*c*rho0/2;
    characteristic[1] = pL/2 - uL*c*rho0/2;
    //right characteristics
    characteristic[2] = pR/2 + uR*c*rho0/2;
    characteristic[3] = pR/2 - uR*c*rho0/2;

    //take left or right value of characteristic variable
    for (int j = 0; j < 2; j++)
    {
        if (lambda[j] >= 0)
        {
            W[j] = characteristic[j];
        }
        if (lambda[j] < 0)
        {
            W[j] = characteristic[j+2];
        }
    }

    //calculate conservative variables from characteristics
    NekDouble p = W[0] + W[1];
    NekDouble u = (W[0] - W[1])/(c*rho0);

    // assemble the fluxes
    pF = rho0*u + u0*p/(c*c);
    uF = p/rho0 + u0*u + v0*vL + w0*wL;
    vF = 0.0;
    wF = 0.0;
}
コード例 #9
0
void handle_method_token_auth(per_session_data_eqemu *session, rapidjson::Document &document, std::string &method)
{
	CheckParams(1, "[token]");
	if(!document.HasMember("params") || document.HasMember("params") && document["params"].Empty() && !document["params"].IsString())
		return;

	session->auth = document["params"][(rapidjson::SizeType)0].GetString();
	if (!CheckTokenAuthorization(session)) {
		WriteWebCallResponseBoolean(session, document, false, false);
	} else {
		WriteWebCallResponseBoolean(session, document, true, false);
	}
}
コード例 #10
0
ファイル: UdpCast.cpp プロジェクト: xiaxiaoyun926/HP-Socket
BOOL CUdpCast::Start(LPCTSTR lpszRemoteAddress, USHORT usPort, BOOL bAsyncConnect, LPCTSTR lpszBindAddress)
{
	if(!CheckParams() || !CheckStarting())
		return FALSE;

	PrepareStart();
	m_ccContext.Reset();

	BOOL isOK = FALSE;
	HP_SOCKADDR bindAddr(AF_UNSPEC, TRUE);

	if(CreateClientSocket(lpszRemoteAddress, usPort, lpszBindAddress, bindAddr))
	{
		if(BindClientSocket(bindAddr))
		{
			if(FirePrepareConnect(m_soClient) != HR_ERROR)
			{
				if(ConnectToGroup(bindAddr))
				{
					if(CreateWorkerThread())
					{
							isOK = TRUE;
					}
					else
						SetLastError(SE_WORKER_THREAD_CREATE, __FUNCTION__, ERROR_CREATE_FAILED);
				}
				else
					SetLastError(SE_CONNECT_SERVER, __FUNCTION__, ::WSAGetLastError());
			}
			else
				SetLastError(SE_SOCKET_PREPARE, __FUNCTION__, ERROR_CANCELLED);
			}
		else
			SetLastError(SE_SOCKET_BIND, __FUNCTION__, ::WSAGetLastError());
	}
	else
		SetLastError(SE_SOCKET_CREATE, __FUNCTION__, ::WSAGetLastError());

	if(!isOK)
	{
		DWORD dwCode = ::GetLastError();

		m_ccContext.Reset(FALSE);
		Stop();

		::SetLastError(dwCode);
	}

	return isOK;
}
コード例 #11
0
bool wxGenericHyperlinkCtrl::Create(wxWindow *parent, wxWindowID id,
    const wxString& label, const wxString& url, const wxPoint& pos,
    const wxSize& size, long style, const wxString& name)
{
    // do validation checks:
    CheckParams(label, url, style);

    if ((style & wxHL_ALIGN_LEFT) == 0)
        style |= wxFULL_REPAINT_ON_RESIZE;

    if (!wxControl::Create(parent, id, pos, size, style, wxDefaultValidator, name))
        return false;

    // set to non empty strings both the url and the label
    SetURL(url.empty() ? label : url);
    SetLabel(label.empty() ? url : label);

    Init();
    SetForegroundColour(m_normalColour);

    // by default the font of an hyperlink control is underlined
    wxFont f = GetFont();
    f.SetUnderlined(true);
    SetFont(f);

    SetInitialSize(size);


    // connect our event handlers:
    // NOTE: since this class is the base class of the GTK+'s native implementation
    //       of wxHyperlinkCtrl, we cannot use the static macros in BEGIN/END_EVENT_TABLE
    //       blocks, otherwise the GTK+'s native impl of wxHyperlinkCtrl would not
    //       behave correctly (as we intercept events doing things which interfere
    //       with GTK+'s native handling):

    Connect( wxEVT_PAINT, wxPaintEventHandler(wxGenericHyperlinkCtrl::OnPaint) );
    Connect( wxEVT_SET_FOCUS, wxFocusEventHandler(wxGenericHyperlinkCtrl::OnFocus) );
    Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler(wxGenericHyperlinkCtrl::OnFocus) );
    Connect( wxEVT_CHAR, wxKeyEventHandler(wxGenericHyperlinkCtrl::OnChar) );
    Connect( wxEVT_LEAVE_WINDOW, wxMouseEventHandler(wxGenericHyperlinkCtrl::OnLeaveWindow) );

    Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler(wxGenericHyperlinkCtrl::OnLeftDown) );
    Connect( wxEVT_LEFT_UP, wxMouseEventHandler(wxGenericHyperlinkCtrl::OnLeftUp) );
    Connect( wxEVT_MOTION, wxMouseEventHandler(wxGenericHyperlinkCtrl::OnMotion) );

    ConnectMenuHandlers();

    return true;
}
コード例 #12
0
ファイル: fnnlm_base.cpp プロジェクト: hao-fang/NLMRepo
void FNeuralNetLMBase::ExtractWordOutputEmbedding(const string &filename) {
  CheckParams();

  cout << "writing " << filename << endl;
  ofstream ofs;
  ofs.open(filename, ios::out);
  if (ofs.fail()) {
    cout << "unable to open " << filename << endl;
    exit(EXIT_FAILURE);
  }

  ExtractWordOutputEmbeddingImpl(ofs);

  ofs.close();
}
コード例 #13
0
ファイル: TcpClient.cpp プロジェクト: huazhipeng/HP-Socket
BOOL CTcpClient::Start(LPCTSTR lpszRemoteAddress, USHORT usPort, BOOL bAsyncConnect, LPCTSTR lpszBindAddress, USHORT usLocalPort)
{
	if(!CheckParams() || !CheckStarting())
		return FALSE;

	PrepareStart();
	m_ccContext.Reset();

	BOOL isOK = FALSE;

	HP_SOCKADDR addrRemote, addrBind;

	if(CreateClientSocket(lpszRemoteAddress, addrRemote, usPort, lpszBindAddress, addrBind))
	{
		if(BindClientSocket(addrBind, addrRemote, usLocalPort))
		{
			if(TRIGGER(FirePrepareConnect(m_soClient)) != HR_ERROR)
			{
				if(ConnectToServer(addrRemote, bAsyncConnect))
				{
					if(CreateWorkerThread())
						isOK = TRUE;
					else
						SetLastError(SE_WORKER_THREAD_CREATE, __FUNCTION__, ERROR_CREATE_FAILED);
				}
				else
					SetLastError(SE_CONNECT_SERVER, __FUNCTION__, ::WSAGetLastError());
			}
			else
				SetLastError(SE_SOCKET_PREPARE, __FUNCTION__, ENSURE_ERROR_CANCELLED);
		}
		else
			SetLastError(SE_SOCKET_BIND, __FUNCTION__, ::WSAGetLastError());
	}
	else
		SetLastError(SE_SOCKET_CREATE, __FUNCTION__, ::WSAGetLastError());

	if(!isOK)
	{
		m_ccContext.Reset(FALSE);
		EXECUTE_RESTORE_ERROR(Stop());
	}

	return isOK;
}
コード例 #14
0
ファイル: TcpAgent.cpp プロジェクト: MatzYang/HP-Socket
BOOL CTcpAgent::Start(LPCTSTR pszBindAddress, BOOL bAsyncConnect)
{
	if(!CheckParams() || !CheckStarting())
		return FALSE;

	if(ParseBindAddress(pszBindAddress, bAsyncConnect))
		if(CreateCompletePort())
			if(CreateWorkerThreads())
			{
				m_bAsyncConnect	= bAsyncConnect;
				m_enState		= SS_STARTED;

				return TRUE;
			}

	Stop();

	return FALSE;
}
コード例 #15
0
ファイル: TcpServer.cpp プロジェクト: huazhipeng/HP-Socket
BOOL CTcpServer::Start(LPCTSTR lpszBindAddress, USHORT usPort)
{
	if(!CheckParams() || !CheckStarting())
		return FALSE;

	PrepareStart();

	if(CreateListenSocket(lpszBindAddress, usPort))
		if(CreateCompletePort())
			if(CreateWorkerThreads())
				if(StartAccept())
				{
					m_enState = SS_STARTED;
					return TRUE;
				}

	EXECUTE_RESTORE_ERROR(Stop());

	return FALSE;
}
コード例 #16
0
VExpression* VInvocation::DoResolve(VEmitContext& ec)
{
	guard(VInvocation::DoResolve);
	if (ec.Package->Name == NAME_decorate)
	{
		CheckDecorateParams(ec);
	}

	//	Resolve arguments
	bool ArgsOk = true;
	for (int i = 0; i < NumArgs; i++)
	{
		if (Args[i] != NULL)
		{
			Args[i] = Args[i]->Resolve(ec);
			if (Args[i] == NULL)
			{
				ArgsOk = false;
			}
		}
	}
	if (ArgsOk == false)
	{
		delete this;
		return NULL;
	}

	CheckParams(ec);

	Type  = Func->ReturnType;
	if (Type.Type == TYPE_Byte || Type.Type == TYPE_Bool)
	{
		Type = VFieldType(TYPE_Int);
	}
	if (Func->Flags & FUNC_Spawner)
	{
		Type.Class = Args[0]->Type.Class;
	}
	return this;
	unguard;
}
コード例 #17
0
void calcCtrlPointErrors (PanoramaData& pano) 
{
    if(pano.getNrOfImages()>0 && pano.getNrOfCtrlPoints()>0)
    {
        char * p=setlocale(LC_ALL,NULL);
#ifndef ANDROID
        char * oldlocale=strdup(p);
#else
	char * oldlocale="";
#endif
        setlocale(LC_ALL,"C");
        UIntSet allImg;
        std::ostringstream scriptbuf;
        fill_set(allImg,0, unsigned(pano.getNrOfImages()-1));
        //create temporary non-empty optimize vector
        OptimizeVector optVec;
        std::set<std::string> opt;
        opt.insert("y");
        for(unsigned int i=0;i<pano.getNrOfImages();i++)
        {
            optVec.push_back(opt);
        };
        pano.printPanoramaScript(scriptbuf, optVec, 
                pano.getOptions(), allImg, true);

        char * script = 0;
        script = strdup(scriptbuf.str().c_str());
        AlignInfo ainf;
        if (ParseScript( script, &ainf ) == 0)
        {
            if( CheckParams( &ainf ) == 0 )
            {
                ainf.fcn = fcnPano;
                SetGlobalPtr( &ainf ); 
                pano.updateCtrlPointErrors( GetAlignInfoCtrlPoints(ainf) );
            }
        }
        setlocale(LC_ALL,oldlocale);
        free(oldlocale);
    };
}
コード例 #18
0
void handle_method_world_to_client(per_session_data_eqemu *session, rapidjson::Document &document, std::string &method) {
	CheckParams(5, "[zone_id, instance_id, opcode, size, data]");
	VerifyID();
	CalculateSize();
	ServerPacket *pack = new ServerPacket(ServerOP_WIRemoteOpcodeFromClient, sz);
	pack->WriteUInt32((uint32)id.size()); \
	pack->WriteString(id.c_str()); \
	pack->WriteUInt32((uint32)session->uuid.size()); \
	pack->WriteString(session->uuid.c_str()); \
	pack->WriteUInt32((uint32)method.size()); \
	pack->WriteString(method.c_str()); \
	auto &params = document["params"]; \
	auto params_sz = params.Size(); \
	pack->WriteUInt32(params_sz); \
	for(rapidjson::SizeType i = 0; i < params_sz; ++i) { \
		auto &param = params[(rapidjson::SizeType)i]; \
		pack->WriteUInt32((uint32)strlen(param.GetString())); \
		pack->WriteString(param.GetString()); \
	} \
	worldserver->SendPacket(pack); \
	safe_delete(pack); \
}
コード例 #19
0
ファイル: test.cpp プロジェクト: openhpi1/openhpitest
SaErrorT cTest::Start( SaHpiUint8T nparams,
                       const SaHpiDimiTestVariableParamsT * params )
{
    SaHpiDimiReadyT ready;
    SaErrorT rv = GetReadiness( ready );
    if ( rv != SA_OK ) {
        return rv;
    }
    if ( ready != SAHPI_DIMI_READY ) {
        return SA_ERR_HPI_INVALID_STATE;
    }
    bool rc= CheckParams( nparams, params );
    if ( !rc ) {
        return SA_ERR_HPI_INVALID_DATA;
    }

    ChangeStatus( SAHPI_DIMITEST_STATUS_RUNNING );

    m_handler.SetTimer( this, m_next.run_duration );

    return SA_OK;
}
コード例 #20
0
MultilayerNET* CreateNewMultilayerNET(uint layersCount, uint inputDimension, ActivationFunctionPtr actFunction, uint* layersParams)
{
	uint i;
	MultilayerNET* newNET;

	if(!CheckParams(layersCount, inputDimension, actFunction, layersParams))
	{
		newNET = ALLOC_OBJ(MultilayerNET);

		newNET->InputDimension = inputDimension;
		newNET->LayersCount = layersCount;
		newNET->OutputDimension = layersParams[layersCount-1];
		newNET->Layers = ALLOC_ARRAY(Layer*, layersCount);

		newNET->Layers[0] = CreateLayer(layersParams[0], actFunction, inputDimension);
		for(i = 1; i < newNET->LayersCount; i++)
		{
			newNET->Layers[i] = CreateLayer(layersParams[i], actFunction, newNET->Layers[i-1]->NeuronsCount);
		}
		newNET->LastOutput = newNET->Layers[newNET->LayersCount-1]->LastOutput; // output of NET is output of her last layer

		return newNET;
	}
コード例 #21
0
ファイル: TcpServer.cpp プロジェクト: ExpLife0011/JsModule
BOOL CTcpServer::Start(LPCTSTR lpszBindAddress, USHORT usPort)
{
	if(!CheckParams() || !CheckStarting())
		return FALSE;

	PrepareStart();

	if(CreateListenSocket(lpszBindAddress, usPort))
		if(CreateCompletePort())
			if(CreateWorkerThreads())
				if(StartAccept())
				{
					m_enState = SS_STARTED;
					return TRUE;
				}

	DWORD dwCode = ::GetLastError();

	Stop();

	::SetLastError(dwCode);

	return FALSE;
}
コード例 #22
0
ファイル: options.c プロジェクト: BijanZarif/HiFiLES-solver
ctrl_t *SetupCtrl(moptype_et optype, idx_t *options, idx_t ncon, idx_t nparts, 
            real_t *tpwgts, real_t *ubvec)
{
  idx_t i, j;
  ctrl_t *ctrl;

  ctrl = (ctrl_t *)gk_malloc(sizeof(ctrl_t), "SetupCtrl: ctrl");
  
  memset((void *)ctrl, 0, sizeof(ctrl_t));

  switch (optype) {
    case METIS_OP_PMETIS:
      ctrl->objtype   = GETOPTION(options, METIS_OPTION_OBJTYPE, METIS_OBJTYPE_CUT);
      ctrl->ctype     = GETOPTION(options, METIS_OPTION_CTYPE,   METIS_CTYPE_SHEM);
      ctrl->rtype     = METIS_RTYPE_FM;
      ctrl->ncuts     = GETOPTION(options, METIS_OPTION_NCUTS,   1);
      ctrl->niter     = GETOPTION(options, METIS_OPTION_NITER,   10);
      ctrl->seed      = GETOPTION(options, METIS_OPTION_SEED,    -1);
      ctrl->dbglvl    = GETOPTION(options, METIS_OPTION_DBGLVL,  0);

      if (ncon == 1) {
        ctrl->iptype    = GETOPTION(options, METIS_OPTION_IPTYPE,  METIS_IPTYPE_GROW);
        ctrl->ufactor   = GETOPTION(options, METIS_OPTION_UFACTOR, PMETIS_DEFAULT_UFACTOR);
        ctrl->CoarsenTo = 20;
      }
      else {
        ctrl->iptype    = GETOPTION(options, METIS_OPTION_IPTYPE,  METIS_IPTYPE_RANDOM);
        ctrl->ufactor   = GETOPTION(options, METIS_OPTION_UFACTOR, MCPMETIS_DEFAULT_UFACTOR);
        ctrl->CoarsenTo = 100;
      }

      break;


    case METIS_OP_KMETIS:
      ctrl->objtype  = GETOPTION(options, METIS_OPTION_OBJTYPE, METIS_OBJTYPE_CUT);
      ctrl->ctype    = GETOPTION(options, METIS_OPTION_CTYPE,   METIS_CTYPE_SHEM);
      ctrl->iptype   = METIS_IPTYPE_METISRB;
      ctrl->rtype    = METIS_RTYPE_GREEDY;
      ctrl->ncuts    = GETOPTION(options, METIS_OPTION_NCUTS,   1);
      ctrl->niter    = GETOPTION(options, METIS_OPTION_NITER,   10);
      ctrl->ufactor  = GETOPTION(options, METIS_OPTION_UFACTOR, KMETIS_DEFAULT_UFACTOR);
      ctrl->minconn  = GETOPTION(options, METIS_OPTION_MINCONN, 0);
      ctrl->contig   = GETOPTION(options, METIS_OPTION_CONTIG,  0);
      ctrl->seed     = GETOPTION(options, METIS_OPTION_SEED,    -1);
      ctrl->dbglvl   = GETOPTION(options, METIS_OPTION_DBGLVL,  0);
      break;


    case METIS_OP_OMETIS:
      ctrl->objtype  = GETOPTION(options, METIS_OPTION_OBJTYPE,  METIS_OBJTYPE_NODE);
      ctrl->ctype    = GETOPTION(options, METIS_OPTION_CTYPE,    METIS_CTYPE_SHEM);
      ctrl->rtype    = GETOPTION(options, METIS_OPTION_RTYPE,    METIS_RTYPE_SEP1SIDED);
      ctrl->iptype   = GETOPTION(options, METIS_OPTION_IPTYPE,   METIS_IPTYPE_EDGE);
      ctrl->nseps    = GETOPTION(options, METIS_OPTION_NSEPS,    1);
      ctrl->niter    = GETOPTION(options, METIS_OPTION_NITER,    10);
      ctrl->ufactor  = GETOPTION(options, METIS_OPTION_UFACTOR,  OMETIS_DEFAULT_UFACTOR);
      ctrl->compress = GETOPTION(options, METIS_OPTION_COMPRESS, 1);
      ctrl->ccorder  = GETOPTION(options, METIS_OPTION_CCORDER,  0);
      ctrl->seed     = GETOPTION(options, METIS_OPTION_SEED,     -1);
      ctrl->dbglvl   = GETOPTION(options, METIS_OPTION_DBGLVL,   0);
      ctrl->pfactor  = 0.1*GETOPTION(options, METIS_OPTION_PFACTOR,  0);

      ctrl->CoarsenTo = 100;
      break;

    default:
      gk_errexit(SIGERR, "Unknown optype of %d\n", optype);
  }

  ctrl->numflag  = GETOPTION(options, METIS_OPTION_NUMBERING, 0);
  ctrl->optype   = optype;
  ctrl->ncon     = ncon;
  ctrl->nparts   = nparts;
  ctrl->maxvwgt  = ismalloc(ncon, 0, "SetupCtrl: maxvwgt");


  /* setup the target partition weights */
  if (ctrl->optype != METIS_OP_OMETIS) {
    ctrl->tpwgts = rmalloc(nparts*ncon, "SetupCtrl: ctrl->tpwgts");
    if (tpwgts) {
      rcopy(nparts*ncon, tpwgts, ctrl->tpwgts);
    }
    else {
      for (i=0; i<nparts; i++) {
        for (j=0; j<ncon; j++)
          ctrl->tpwgts[i*ncon+j] = 1.0/nparts;
      }
    }
  }
  else {  /* METIS_OP_OMETIS */
    /* this is required to allow the pijbm to be defined properly for
       the edge-based refinement during initial partitioning */
    ctrl->tpwgts    = rsmalloc(2, .5,  "SetupCtrl: ctrl->tpwgts");
  }


  /* setup the ubfactors */
  ctrl->ubfactors = rsmalloc(ctrl->ncon, I2RUBFACTOR(ctrl->ufactor), "SetupCtrl: ubfactors");
  if (ubvec)
    rcopy(ctrl->ncon, ubvec, ctrl->ubfactors);
  for (i=0; i<ctrl->ncon; i++)
    ctrl->ubfactors[i] += 0.0000499;

  /* Allocate memory for balance multipliers. 
     Note that for PMETIS/OMETIS routines the memory allocated is more 
     than required as balance multipliers for 2 parts is sufficient. */
  ctrl->pijbm = rmalloc(nparts*ncon, "SetupCtrl: ctrl->pijbm");

  InitRandom(ctrl->seed);

  IFSET(ctrl->dbglvl, METIS_DBG_INFO, PrintCtrl(ctrl));

  if (!CheckParams(ctrl)) {
    FreeCtrl(&ctrl);
    return NULL;
  }
  else {
    return ctrl;
  }
}
コード例 #23
0
void handle_method_zone(per_session_data_eqemu *session, rapidjson::Document &document, std::string &method) {
	CheckParams(2, "[zone_id, instance_id]");
	VerifyID();
	CalculateSize();
	WriteWebProtocolPacket();
}
コード例 #24
0
void handle_method_world(per_session_data_eqemu *session, rapidjson::Document &document, std::string &method) {
	CheckParams(0, "[]");
	VerifyID();
	CalculateSize();
	WriteWebProtocolPacket();
}
コード例 #25
0
ファイル: taskBackground.c プロジェクト: dmtrkun/mm_project
void taskBackground(void* pvParameter)
{
static unsigned int val1;
static unsigned int val2;
time_t time_sec;

//	vTaskSetApplicationTaskTag( NULL, ( void * ) 'b' );	
alarm_st = 0;
#ifndef SIM_DEBUG
//sysinit
	wdi_ena = 0;
	Spi_init();
	if(get_time_rtc(&rtc_time)== FALSE)
	{
		SetError(RTC_ERR, HARWARE_ALRM_SCR);
		reset_rtc();
		while(clear_os_rtc() == FALSE);
		init_time_rtc(&rtc_time);
		
//		rtc_time.tm_sec = 0;
 //		rtc_time.tm_min = 0;
// 		rtc_time.tm_hour = 0;
//		rtc_time.tm_mday = 1;
//		rtc_time.tm_wday = 0;
//		rtc_time.tm_mon = 0;
//		rtc_time.tm_year = 100;
//		rtc_time.tm_yday = 0;
//		rtc_time.tm_isdst = 0;
		set_time_rtc(&rtc_time)/*set_date()*/;
	}
	else if(mktime(&rtc_time)==-1)
	{
		SetError(RTC_ERR, HARWARE_ALRM_SCR);
//		reset_rtc();
		init_time_rtc(&rtc_time);
		set_time_rtc(&rtc_time)/*set_date()*/;
	}
	
	time_sec  = mktime(&rtc_time); 
	set_clock(time_sec);

//	if(get_days(&calib_date) > 365)
//	if(time_sec - calib_time >= 31536000L /*365*24*60*60*/)
//	{
//			Beep(800);
//			lcd_clear();
//			beep(800,4);
//			RTclock.timer = 2000; //10sec timeout
//			draw_text( 15, LCD_TXTLINE1, (uchar*)"SEND THE PUMP", LCD_PIXEL_ON,0);
//			draw_text( 54, LCD_TXTLINE2, (uchar*)"TO", LCD_PIXEL_ON,0);
//			draw_text( 29, LCD_TXTLINE3, (uchar*)"CALIBRATE", LCD_PIXEL_ON,0);
//			while(RTclock.timer > 0);
//	}




	SST25ProtDisable();

	SST25ReadArray(PARAM_E2PIMG_BASE, &E2pImage, sizeof(E2pImage_t));
	if(crc16((unsigned char*)&E2pImage, sizeof(E2pImage_t)) != 0)
	{
		SetError(EEPROM_ERR, HARWARE_ALRM_SCR);
		set_defaults();
	}
	SST25ReadArray(CLBR_E2PIMG_BASE, &Clbr_E2pImage, sizeof(Clbr_E2pImage_t));
	if(crc16((unsigned char*)&Clbr_E2pImage, sizeof(Clbr_E2pImage_t)) != 0)
	{
		SetError(EEPROM_ERR, HARWARE_ALRM_SCR);
		set_fact_defaults();
	}
        if(GetError() != 0)
	{
		err_code = GetError();
		ClearError();
                ((unsigned int*)&E2pImage)[sizeof(E2pImage_t)/2 - 1] = crc16(&E2pImage, sizeof(E2pImage_t) - 2);
		SST25SectorErase(PARAM_E2PIMG_BASE);
		if(!SST25WriteArray(PARAM_E2PIMG_BASE, &E2pImage, sizeof(E2pImage_t)))
			/*CriticalError("eeprom err")*/;
	}

	MCP23S08Init();
	MCP4822Write(0, zero_press1 , 0);
	MCP4822Write(1, zero_press2 , 0);

	init_motor();
	init_airdet();
#endif
	init_keypad();
	init_clock();
	CheckParams();

	/* drop task priority */	 
	vTaskPrioritySet( hBACKGRNDTask, tskIDLE_PRIORITY + 1 );	
	while (1) 
	{
            vTaskDelay( 50 / portTICK_RATE_MS );   // Wait 50ms
		 
            if(val1 > 0x0fff)
                val1 = 0;
            else
                val1++;
            if(val2 > 0x0fff)
                val1 = 0;
            else
                val2++;

            if(!wdi_ena)
                toggleExpGPO(WDI_EXTIOBIT);
//	ClrWdt();
//	WD_PIN^= 1; 			 /*toggle external watch dog */
	}	
}
コード例 #26
0
ファイル: ClientDlg.cpp プロジェクト: winghua/HP-Socket
void CClientDlg::OnBnClickedStart()
{
	CString strAddress;
	CString strPort;
	CString strTestTimes;
	CString strTestInterv;
	CString strSocketCount;
	CString strThreadCount;
	CString strDataLen;

	m_Address.GetWindowText(strAddress);
	m_Port.GetWindowText(strPort);
	m_TestTimes.GetWindowText(strTestTimes);
	m_TestInterv.GetWindowText(strTestInterv);
	m_SocketCount.GetWindowText(strSocketCount);
	m_ThreadCount.GetWindowText(strThreadCount);
	m_DataLen.GetWindowText(strDataLen);

	m_strAddress	= strAddress.Trim();
	m_usPort		= (USHORT)_ttoi(strPort);
	m_iTestTimes	= _ttoi(strTestTimes);
	m_iTestInterv	= _ttoi(strTestInterv);
	m_iSocketCount	= _ttoi(strSocketCount);
	m_iThreadCount	= _ttoi(strThreadCount);
	m_iDataLen		= _ttoi(strDataLen);

	if(!CheckParams())
		return;

	EnSendPolicy enSendPolicy = (EnSendPolicy)m_SendPolicy.GetCurSel();

	CString strMaxConnCount;
	m_MaxConnCount.GetWindowText(strMaxConnCount);
	int iMaxConnCount = _ttoi(strMaxConnCount);

	if(iMaxConnCount == 0)
		iMaxConnCount = 10;

	iMaxConnCount *= 1000;

	SetAppState(ST_STARTING);

	m_hasError			= FALSE;
	m_dwBeginTickCount	= 0;
	m_dwTimeconsuming	= 0;
	m_llTotalReceived	= 0;
	m_llTotalSent		= 0;
	m_llExpectReceived	= (LONGLONG)m_iTestTimes * (LONGLONG)m_iSocketCount * (LONGLONG)m_iDataLen;

	BOOL isOK = FALSE;

	m_Agent->SetWorkerThreadCount(m_iThreadCount);
	m_Agent->SetMaxConnectionCount(iMaxConnCount);
	m_Agent->SetSendPolicy(enSendPolicy);

	if(m_Agent->Start(LOCAL_ADDRESS, FALSE))
	{
		for(int i = 0; i < m_iSocketCount; i++)
		{
			if(m_Agent->Connect(m_strAddress, m_usPort))
			{
				if(i == m_iSocketCount - 1)
					isOK = TRUE;
			}
			else
			{
				::LogClientStartFail(::SYS_GetLastError(), ::HP_GetSocketErrorDesc(SE_CONNECT_SERVER));
				break;
			}
		}
	}
	else
		::LogClientStartFail(m_Agent->GetLastError(), m_Agent->GetLastErrorDesc());

	if(!isOK)
	{
		m_Agent->Stop();
		SetAppState(ST_STOPPED);
		return;
	}

	::LogClientStart(m_strAddress, m_usPort);

	DWORD dwSendDelay = 3;
	CString strMsg;

	strMsg.Format(_T(" *** willing to send data after %d seconds ..."), dwSendDelay);
	::LogMsg(strMsg);

	::WaitWithMessageLoop(dwSendDelay * 500);

	while((int)m_connIDs.size() < m_iSocketCount)
	{
		if(m_hasError)
		{
			m_Agent->Stop();
			SetAppState(ST_STOPPED);
			return;
		}
		else
			::WaitWithMessageLoop(1);
	}

	int iCount = m_Info.GetCount();
	if(iCount > 0) m_Info.SetCurSel(iCount - 1);
	::WaitWithMessageLoop(dwSendDelay * 500);

	m_sendBuffer.Malloc(m_iDataLen, true);
	SetAppState(ST_STARTED);

	::LogMsg(_T(" *** Go Now !"));

	m_dwBeginTickCount = ::TimeGetTime();

	BOOL bTerminated = FALSE;
	for(int i = 0; i < m_iTestTimes; i++)
	{
		for(int j = 0; j < m_iSocketCount; j++)
		{
			if(!m_Agent->Send(m_connIDs[j], m_sendBuffer, (int)m_sendBuffer.Size()))
			{
				::LogClientSendFail(i + 1, j + 1, ::SYS_GetLastError(), ::HP_GetSocketErrorDesc(SE_DATA_SEND));

				bTerminated = TRUE;
				break;
			}
		}

		if(bTerminated)
			break;

		if(m_iTestInterv > 0 && i + 1 < m_iTestTimes)
			::WaitWithMessageLoop(m_iTestInterv);
	}

	m_sendBuffer.Free();
}
コード例 #27
0
EQKAnalyzer::EQKAnalyzer( const std::string fparam, bool MoveF ) {
	LoadParams( fparam, MoveF );
	CheckParams();
}
コード例 #28
0
ファイル: eccoind.cpp プロジェクト: AltJ/ECCoin
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char *argv[])
{
    shutdown_threads.store(false);
    thread_group threadGroup(&shutdown_threads);

    bool fRet = false;

    //
    // Parameters
    //
    gArgs.ParseParameters(argc, argv);

    // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
    try
    {
        CheckParams(ChainNameFromCommandLine());
    }
    catch (const std::exception &e)
    {
        fprintf(stderr, "Error: %s\n", e.what());
        return false;
    }
    try
    {
        gArgs.ReadConfigFile();
    }
    catch (const std::exception &e)
    {
        fprintf(stderr, "Error reading configuration file: %s\n", e.what());
        return false;
    }

    GenerateNetworkTemplates();

    // Process help and version before taking care about datadir
    if (gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help") || gArgs.IsArgSet("-version"))
    {
        std::string strUsage = "Eccoind version " + FormatFullVersion() + "\n";

        if (gArgs.IsArgSet("-version"))
        {
            strUsage += LicenseInfo();
        }
        else
        {
            strUsage += "\nUsage:\neccoind [options]                     Start Eccoind\n";

            strUsage += "\n" + HelpMessage();
        }

        fprintf(stdout, "%s", strUsage.c_str());
        return false;
    }

    try
    {
        if (!fs::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n",
                gArgs.GetArg("-datadir", "").c_str());
            return false;
        }
        // Command-line RPC
        bool fCommandLine = false;
        for (int i = 1; i < argc; i++)
        {
            if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "ECC:"))
            {
                fCommandLine = true;
            }
        }
        if (fCommandLine)
        {
            int ret = CommandLineRPC(argc, argv);
            exit(ret);
        }
#ifndef WIN32
        fDaemon = gArgs.GetBoolArg("-daemon", false);
        if (fDaemon)
        {
            fprintf(stdout, "Eccoind server starting\n");

            // Daemonize
            pid_t pid = fork();
            if (pid < 0)
            {
                fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
                return false;
            }
            if (pid > 0) // Parent process, pid is child process id
            {
                return true;
            }
            // Child process falls through to rest of initialization

            pid_t sid = setsid();
            if (sid < 0)
                fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
        }
#endif
        gArgs.SoftSetBoolArg("-server", true);
        // Set this early so that parameter interactions go to console
        InitLogging();
        InitParameterInteraction();
        fRet = AppInit2(threadGroup);
    }
    catch (const std::exception &e)
    {
        PrintExceptionContinue(&e, "AppInit()");
    }
    catch (...)
    {
        PrintExceptionContinue(NULL, "AppInit()");
    }

    if (!fRet)
    {
        Interrupt(threadGroup);
    }
    else
    {
        WaitForShutdown(&threadGroup);
    }
    Shutdown();

    return fRet;
}
コード例 #29
0
ファイル: tcsip.cpp プロジェクト: sipper123/sip2
int main(int argc, char* argv[])
{
  int  len=0,
       ret=0;

  //command line argument check
  if (CheckParams(argc, argv) < 0)
      exit(0);

  printf("\033[1;32m\n");
  printf("** %s: a simple SIP based talk program **\n", argv[0]);
  printf("** Please enter help to see the command options **\n\n");

  if (oSocSIP.Initialize(SIP_PORT) < 0)
  {
    printf("Error on SIP Socket Initialize\n");
    printf("\033[0m");
    exit(1);
  }

  fd_set fds;
  memset(g_rxBuffer, 0, BUFFER_LEN);
  memset(g_txBuffer, 0, BUFFER_LEN);

  g_sip_done  = false;
  g_1stSampleDone = false;
  g_sip_done   = false;

  g_sip_state = SIP_IDLE;
  g_sip_mode  = SIP_NONE;

  double oldTime=0;
  double newTime=0;
 
  timeval tim;
  gettimeofday(&tim, NULL);
  oldTime = tim.tv_sec;

  printf("\ntcsip> ");
  fflush(stdout); 
  while (!g_sip_done)
  {
    FD_ZERO(&fds);
    FD_SET(0, &fds);
    FD_SET(oSocSIP.m_socket, &fds);

    ret = select(1+oSocSIP.m_socket, &fds, NULL, NULL, NULL);

    //some activity has happened on the socket
    if(ret < 0) 
    {
      printf("Error on on select\n");
      break;
    }
    //dump_state();
    //User entry, coming in through stdin
    if (FD_ISSET(0, &fds))
    {
      memset(g_iBuffer, 0, MAX_STR_LEN);
      memset(g_oBuffer, 0, MAX_STR_LEN);
      
      fgets(g_iBuffer, MAX_STR_LEN, stdin);
      len = strlen(g_iBuffer);
      g_iBuffer[--len] = '\0';
      printf("tcsip> "); fflush(stdout);

      gettimeofday(&tim, NULL);
      newTime = tim.tv_sec;
      if (newTime - oldTime > TIMEOUTTIME)
      {
        if (g_sip_state==SIP_CONX_PENDING || g_sip_state==SIP_DISCONX_PENDING)
        {
          printf("Timing out...\n");  
          g_sip_done = true;
          continue;
        }
      }
      else
      {
         oldTime = newTime;
      }
      
      if (len>0)
      {
         ProcessUserCommand(g_iBuffer, g_oBuffer); 
      }
      if (strlen((char*)g_oBuffer))
         printf("%s\ntcsip> ", g_oBuffer); fflush(stdout);
    }

    // Something arrived at the listening socket. read the packet, check if it is DATA type or ACK type,
    // and do the necessary.
    if (FD_ISSET(oSocSIP.m_socket, &fds))
    {

      memset(g_rxBuffer, 0, BUFFER_LEN);
      len = BUFFER_LEN;
      if (oSocSIP.RecvFrom(g_rxBuffer, &len) < 0)
      {
        printf("Error on SIP socket\n");
        return 0;
      }
      g_rxBuffer[len]='\0';
      //printf("____________________\nReceived from socket:\n%s\n_____\n", (char*)g_rxBuffer);

      int prompt=0;
      prompt = ProcessSipMsg(g_rxBuffer, g_oBuffer);
      if (strlen((char*)g_oBuffer))
      {
        if (prompt!=5)
           printf("%s\ntcsip> ", g_oBuffer); fflush(stdout);
      }
    }
  }

  // in case the audio thread did not terminate...
  if (g_au_thread_running)
  {
    pthread_join(g_au_thread, NULL);
  }

  if (g_audio_fd > 0)  
     close(g_audio_fd);

  printf("\033[0m\n");
  return 0;
}
コード例 #30
0
ファイル: ClientDlg.cpp プロジェクト: 32719913/HP-Socket
void CClientDlg::OnBnClickedStart()
{
	CString strAddress;
	CString strPort;
	CString strTestTimes;
	CString strTestInterv;
	CString strSocketCount;
	CString strDataLen;

	m_Address.GetWindowText(strAddress);
	m_Port.GetWindowText(strPort);
	m_TestTimes.GetWindowText(strTestTimes);
	m_TestInterv.GetWindowText(strTestInterv);
	m_SocketCount.GetWindowText(strSocketCount);
	m_DataLen.GetWindowText(strDataLen);

	m_strAddress	= strAddress.Trim();
	m_usPort		= (USHORT)_ttoi(strPort);
	m_iTestTimes	= _ttoi(strTestTimes);
	m_iTestInterv	= _ttoi(strTestInterv);
	m_iSocketCount	= _ttoi(strSocketCount);
	m_iDataLen		= _ttoi(strDataLen);

	if(!CheckParams())
		return;

	SetAppState(ST_STARTING);

	m_dwBeginTickCount	= 0;
	m_dwTimeconsuming	= 0;
	m_llTotalReceived	= 0;
	m_llTotalSent		= 0;
	m_llExpectReceived	= (LONGLONG)m_iTestTimes * (LONGLONG)m_iSocketCount * (LONGLONG)m_iDataLen;

	m_vtClients.Clear();

	for(int i = 0; i < m_iSocketCount; i++)
	{
		smart_simple_ptr<CUdpClientPtr> pSocket = new CUdpClientPtr(this);
		//(*pSocket)->SetDetectAttempts(0);

		if((*pSocket)->Start(m_strAddress, m_usPort))
			m_vtClients->push_back(pSocket.release());
		else
		{
			::LogClientStartFail((*pSocket)->GetLastError(), (*pSocket)->GetLastErrorDesc());
			m_vtClients.Clear();
			SetAppState(ST_STOPPED);
			return;
		}
	}

	::LogClientStart(m_strAddress, m_usPort);

	DWORD dwSendDelay = 3;
	CString strMsg;

	strMsg.Format(_T(" *** willing to send data after %d seconds ..."), dwSendDelay);
	::LogMsg(strMsg);

	::WaitWithMessageLoop(dwSendDelay * 1000);
	m_sendBuffer.Malloc(m_iDataLen, true);
	SetAppState(ST_STARTED);

	::LogMsg(_T(" *** Go Now !"));

	m_dwBeginTickCount = ::TimeGetTime();

	BOOL bTerminated = FALSE;
	for(int i = 0; i < m_iTestTimes; i++)
	{
		for(int j = 0; j < m_iSocketCount; j++)
		{
			CUdpClientPtr* pSocket = m_vtClients[j];
			if(!(*pSocket)->Send(m_sendBuffer, (int)m_sendBuffer.Size()))
			{
				::LogClientSendFail(i + 1, j + 1, ::SYS_GetLastError(), ::HP_GetSocketErrorDesc(SE_DATA_SEND));
				bTerminated = TRUE;
				break;
			}
		}

		if(bTerminated)
			break;

		if(m_iTestInterv > 0 && i + 1 < m_iTestTimes)
			::WaitWithMessageLoop(m_iTestInterv);
	}

	m_sendBuffer.Free();
}