Example #1
0
    Array<uint8> zlib_decompress(uint8* input, uint32 input_length) {        
		z_stream strm; /* decompression stream */	
		strm.zalloc = Z_NULL;
		strm.zfree = Z_NULL;
		strm.opaque = Z_NULL;
        
        uint32 buffer_size = 1024;
        Array<uint8> buffer;
        buffer.resize(buffer_size);
        
		strm.next_in  = input;
		strm.avail_in = input_length;
		strm.next_out = &buffer.front();
		strm.avail_out = buffer_size;
        
		int ret = inflateInit2(&strm, 15 + 32);
        
        if (ret != Z_OK) {
            log_zlib_error(ret);
            return Array<uint8>();
        }
        
        do {
            ret = inflate(&strm, Z_NO_FLUSH);
            
            switch (ret) {
                case Z_NEED_DICT:
                case Z_STREAM_ERROR:
                    ret = Z_DATA_ERROR;
                    
                case Z_DATA_ERROR:
                case Z_MEM_ERROR:
                    inflateEnd(&strm);
                    log_zlib_error(ret);
                    return Array<uint8>();
            }
            
            if (ret != Z_STREAM_END) {
                buffer.resize(buffer_size * 2);
                
                strm.next_out = (Bytef *)(&buffer.front() + buffer_size);
                strm.avail_out = buffer_size;
                buffer_size *= 2;
            }
        }
        while (ret != Z_STREAM_END);
        
        if (strm.avail_in != 0) {
            log_zlib_error(Z_DATA_ERROR);
            return Array<uint8>();
        }
                        
        size_t outLength = buffer_size - strm.avail_out;
        inflateEnd(&strm);
        
        buffer.resize(outLength);
        
        return buffer;
    }
Example #2
0
void CommandService::_process_timeout(const int64_t now) {
    /* clear timeout command */
    if(m_queue_tb->size()>0) {
        Int64Array* ls =0;
        HashIterator* it =static_cast< HashIterator* >(m_queue_tb->iterator());
        while(it->next()) {
            const int64_t who =static_cast< Int64* >(it->getKey())->getValue();
            Array* queue =static_cast< Array* >(it->getValue());
            while(Command* cmd =dynamic_cast< Command* >(queue->front())) {
                if(cmd->isTimeout(now)) {
                    if(cmd->isProcessing()) {
                        WARN("service %s(%lld) who %lld command %lld cancel", name(), (long long)m_id, (long long)cmd->getWho(), (long long)cmd->getCommand());
                    }
                    queue->pop_front();
                }
                else {
                    break;
                }
            }
            if(Command* cmd =dynamic_cast< Command* >(queue->front())) {
                if(cmd->isProcessing()) {
                    continue;
                }
                ASSERT(cmd->isInit());
                if(!ls) {
                    ls =SafeNew<Int64Array>();
                }
                ls->push_back(who);
            }
        }
        const int64_t n= ls ? ls->size() : 0;
        for(int64_t i=0; i<n; ++i) {
            _process_request(ls->get(i));
        }
    }
    /* clear timeout rpc */
    if(m_rpc_tb->size()>0) {
        Array* ls =0;
        HashIterator* it =static_cast< HashIterator* >(m_rpc_tb->iterator());
        while(it->next()) {
            RpcInfo* ri =static_cast< RpcInfo* >(it->getValue());
            if(now >= ri->getExpireTime()) {
                if(!ls) {
                    ls =SafeNew<Array>();
                }
                ls->push_back(ri);
                it->remove();
            }
        }
        const int64_t n =ls ? ls->size() : 0;
        for(int64_t i=0; i<n; ++i) {
            RpcInfo* ri =static_cast< RpcInfo* >(ls->get(i));
            WARN("service %s(%lld) rpc %lld cancel", name(), (long long)m_id, (long long)ri->getId());
            ri->timeout();
        }
    }
}
Example #3
0
    Array<uint8> zlib_compress(uint8* input, uint32 input_length, ZlibCompressionMethod method) {

        uint32 buffer_size = 1024;
        Array<uint8> buffer;
        buffer.resize(buffer_size);
        
        int err;
        z_stream strm;
        strm.zalloc = Z_NULL;
        strm.zfree = Z_NULL;
        strm.opaque = Z_NULL;
        
        strm.next_in  = input;
		strm.avail_in = input_length;
		strm.next_out = &buffer.front();
		strm.avail_out = buffer_size;
        
        const int windowBits = (method == ZCM_Gzip) ? 15 + 16 : 15;
        
        err = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, windowBits,
                           8, Z_DEFAULT_STRATEGY);
        if (err != Z_OK) {
            log_zlib_error(err);
            return Array<uint8>();
        }
        
        do {
            err = deflate(&strm, Z_FINISH);
            mist_assert(err != Z_STREAM_ERROR);
            
            if (err == Z_OK) {
                buffer.resize(buffer_size * 2);

                strm.next_out = (Bytef *)(&buffer.front() + buffer_size);
                strm.avail_out = buffer_size;
                buffer_size *= 2;

            }
        } while (err == Z_OK);
        
        if (err != Z_STREAM_END) {
            log_zlib_error(err);
            deflateEnd(&strm);
            return Array<uint8>();
        }
        
        size_t outLength = buffer_size - strm.avail_out;
        deflateEnd(&strm);
        
        buffer.resize(outLength);

        return buffer;
    }
Example #4
0
int main()
{
	Array <int> test;
	for (int i = 0; i < 10; ++i)
	{
		test.push_back (i);
	}
	for (int i = 0; i < test.size(); ++i)
	{
		cout << test[i] << " ";
	}
	cout << endl;
	Array <int> test1 (test);
	for (int i = 0; i < test1.size(); ++i)
	{
		cout << test1[i] << " ";
	}
	cout << endl;
	Array <int> test2 = test1;
	for (int i = 0; i < test2.size(); ++i)
	{
		cout << test2[i] << " ";
	}
	cout << endl;
	test.pop_back();
	for (int i = 0; i < test.size(); ++i)
	{
		cout << test[i] << " ";
	}
	cout << endl;
	cout << test.front() << " " << test.back() << endl;
	cout << (test1 == test2) << " " << (test == test1) << endl;
}
Example #5
0
TEST(ArrayTest, testOperations)
{
	const int SIZE = 6;
	typedef Poco::Array<int,SIZE> Array;
	Array a = { { 1 } };

	// use some common STL container operations
	EXPECT_TRUE(a.size() == SIZE);
	EXPECT_TRUE(a.max_size() == SIZE);
	EXPECT_TRUE(a.empty() == false);
	EXPECT_TRUE(a.front() == a[0]);
	EXPECT_TRUE(a.back() == a[a.size()-1]);
	//EXPECT_TRUE(a.data() == &a[0]);

	// assign
	a.assign(100);
	for(int i = 0; i<a.size(); i++){
		EXPECT_TRUE(a[i] == 100);
	}

	// swap
	Array b; 
	b.assign(10);
	for(int i=0; i<SIZE; i++){
		EXPECT_TRUE(a[i] == 100);
		EXPECT_TRUE(b[i] == 10);
	}
	a.swap(b);
	for(int i=0; i<SIZE; i++){
		EXPECT_TRUE(a[i] == 10);
		EXPECT_TRUE(b[i] == 100);
	}

}
Example #6
0
godot_variant GDAPI godot_array_front(const godot_array *p_arr) {
	Array *a = (Array *)p_arr;
	godot_variant v;
	Variant *val = (Variant *)&v;
	memnew_placement(val, Variant);
	*val = a->front();
	return v;
}
Example #7
0
inline bool CheckDebugThrows(Array& Arr) {
  try {
    Arr.front();
  } catch (std::__libcpp_debug_exception const&) {
    return true;
  }
  return false;
}
Example #8
0
    void writeBinary(const Array & x, WriteBuffer & buf)
    {
        UInt8 type = Field::Types::Null;
        size_t size = x.size();
        if (size)
            type = x.front().getType();
        DB::writeBinary(type, buf);
        DB::writeBinary(size, buf);

        for (Array::const_iterator it = x.begin(); it != x.end(); ++it)
        {
            switch (type)
            {
                case Field::Types::Null: break;
                case Field::Types::UInt64:
                {
                    DB::writeVarUInt(get<UInt64>(*it), buf);
                    break;
                }
                case Field::Types::UInt128:
                {
                    DB::writeBinary(get<UInt128>(*it), buf);
                    break;
                }
                case Field::Types::Int64:
                {
                    DB::writeVarInt(get<Int64>(*it), buf);
                    break;
                }
                case Field::Types::Float64:
                {
                    DB::writeFloatBinary(get<Float64>(*it), buf);
                    break;
                }
                case Field::Types::String:
                {
                    DB::writeStringBinary(get<std::string>(*it), buf);
                    break;
                }
                case Field::Types::Array:
                {
                    DB::writeBinary(get<Array>(*it), buf);
                    break;
                }
                case Field::Types::Tuple:
                {
                    DB::writeBinary(get<Tuple>(*it), buf);
                    break;
                }
                case Field::Types::AggregateFunctionState:
                {
                    DB::writeStringBinary(it->get<AggregateFunctionStateData>().name, buf);
                    DB::writeStringBinary(it->get<AggregateFunctionStateData>().data, buf);
                    break;
                }
            }
        }
    }
Example #9
0
void CommandService::_process_request(const int64_t who) {
    // get queue
    Array* queue =static_cast< Array* >(m_queue_tb->get(who));
    if(!queue) return;

    // process
    int64_t last_pop_cmd =-1;
    while(queue->size() > 0) {
        Command* front =static_cast< Command* >(queue->front());

        // cancel timeout
        if(front->isTimeout(m_now)) {
            last_pop_cmd =front->getCommand();
            queue->pop_front();
            WARN("service %s(%lld) who %lld command %lld, timeout just remove it", name(), (long long)m_id, (long long)who, (long long)last_pop_cmd);
            continue;
        }

        // break when front is processing
        if(front->isProcessing()) {
            break;
        }

        // must be init
        ASSERT(front->isInit());

        // process front
        m_processing_command =front;
        const int64_t result =on_start_command(front);
        m_processing_command =0;
        if(result == Command::STATE_COMPLETE) {
            front->setState(Command::STATE_COMPLETE);
            last_pop_cmd =front->getCommand();
            queue->pop_front();
            INFO("service %s(%lld) who %lld command %lld complete", name(), (long long)m_id, (long long)who, (long long)last_pop_cmd);
        }
        else if(result > 0) {
            front->setState(Command::STATE_PROCESSING);
            INFO("service %s(%lld) who %lld command %lld processing", name(), (long long)m_id, (long long)who, (long long)front->getCommand());
            break;
        }
        else {
            front->setState(Command::STATE_ERROR);
            last_pop_cmd =front->getCommand();
            queue->pop_front();
            ERROR("service %s(%lld) who %lld command %lld state %lld", name(), (long long)m_id, (long long)who, (long long)last_pop_cmd, (long long)result);
        }
    }
    // post process
    if(last_pop_cmd==LOGOUT_REQUEST && queue->empty()) {
        m_queue_tb->remove(who);
    }
}
Example #10
0
 /*
  * Adds input to input queue and performs inner product of filter queues with
  * filter coefficients to produce filter output, which it appends to output queue.
  * Returns filter output.
  */
 T f(T input) {
     for (auto it = inputs.rbegin(); it != inputs.rend() - 1; ++it) {
         *it = *(it + 1);
     }
     *inputs.begin() = input;
     T output = std::inner_product(numerator.begin(), numerator.end(), inputs.begin(), 0.0);
     output -= std::inner_product(denominator.begin() + 1, denominator.end(), outputs.begin(), 0.0);
     output /= denominator.front();
     for (auto it = outputs.rbegin(); it != outputs.rend() - 1; ++it) {
         *it = *(it + 1);
     }
     *outputs.begin() = output;
     return output;
 }
Example #11
0
int main()
{
    std_log(LOG_FILENAME_LINE,"[Test Case for array1]");
    // define special type name
    typedef boost::array<float,6> Array;

    // create and initialize an array
    Array a = { { 42 } };

    // access elements
    for (unsigned i=1; i<a.size(); ++i) {
        a[i] = a[i-1]+1;
    }

    // use some common STL container operations
    std::cout << "size:     " << a.size() << std::endl;
    std::cout << "empty:    " << (a.empty() ? "true" : "false") << std::endl;
    std::cout << "max_size: " << a.max_size() << std::endl;
    std::cout << "front:    " << a.front() << std::endl;
    std::cout << "back:     " << a.back() << std::endl;
    std::cout << "elems:    ";

    // iterate through all elements
    for (Array::const_iterator pos=a.begin(); pos<a.end(); ++pos) {
        std::cout << *pos << ' ';
    }
    std::cout << std::endl;

    // check copy constructor and assignment operator
    Array b(a);
    Array c;
    c = a;
    if (a==b && a==c) {
        std::cout << "copy construction and copy assignment are OK"
                  << std::endl;
        std_log(LOG_FILENAME_LINE,"Result : Passed");          
    }
    else {
        std::cout << "copy construction and copy assignment FAILED"
                  << std::endl;
        std_log(LOG_FILENAME_LINE,"Result : Failed"); 
		assert_failed = true;          
    }
	testResultXml("array1");
	close_log_file();
    return 0;  // makes Visual-C++ compiler happy
}
Example #12
0
int main ()
{
    printf ("Results of tr1_array5_test:\n");

    // define special type name
    typedef array<float,6> Array;

    // create and initialize an array
    const Array a = { { 42.42f } };

    // use some common STL container operations
    printf ("static_size: %lu\n", a.size ());
    printf ("size:        %lu\n", a.size ());
    // Can't use std::boolalpha because it isn't portable
    printf ("empty:       %s\n", (a.empty()? "true" : "false"));
    printf ("max_size:    %lu\n", a.max_size ());
    printf ("front:       %f\n", a.front ());
    printf ("back:        %f\n", a.back ());
    printf ("[0]:         %f\n", a[0]);
    printf ("elems:       ");

    // iterate through all elements
    for (Array::const_iterator pos=a.begin(); pos<a.end(); ++pos)
        printf ("%f ", *pos);

    printf ("\n");

    test_static_size(a);

    // check copy constructor and assignment operator
    Array b(a);
    Array c;
    c = a;
    if (a==b && a==c)
      printf ("copy construction and copy assignment are OK\n");
    else
      printf ("copy construction and copy assignment are BROKEN\n");

    typedef array<double,6> DArray;
    typedef array<int,6> IArray;
    IArray ia = { { 1, 2, 3, 4, 5, 6 } } ; // extra braces silence GCC warning
    DArray da;
    da = ia;
    da.assign (42);

    return 0;
}
Example #13
0
    Disposable<Array> FdmVPPStepCondition::changeState(
                        const Real gasPrice, const Array& state, Time t) const {
        const Real startUpCost
                = startUpFixCost_ + (gasPrice + carbonPrice_)*startUpFuel_;

        Array retVal(state.size());
        const Size sss = 2*tMinUp_ + tMinDown_;
        const Size n = sss * (nStarts_ == Null<Size>() ? 1 : nStarts_+1);

        for (Size i=0; i < n; ++i) {
            const Size j = i % sss;

            if (j < tMinUp_-1) {
                retVal[i] = std::max(state[i+1], state[tMinUp_+i+1]);
            }
            else if (j == tMinUp_-1) {
                retVal[i] = std::max(state[i+tMinUp_+1],
                                     std::max(state[i], state[i+tMinUp_]));
            }
            else if (j < 2*tMinUp_) {
                retVal[i] = retVal[i-tMinUp_];
            }
            else if (j <  2*tMinUp_+tMinDown_-1) {
                retVal[i] = state[i+1];
            }
            else if (nStarts_ == Null<Size>()) {
                retVal[i] = std::max(state[i],
                    std::max(state.front(), state[tMinUp_]) - startUpCost);

            }
            else if (i >= sss) {
                retVal[i] = std::max(state[i],
                    std::max(state[i+1-2*sss], state[i+1-2*sss+tMinUp_])
                            - startUpCost);
            }
            else {
                retVal[i] = state[i];
            }
        }

        return retVal;
    }
AggregateFunctionPtr createAggregateFunctionSumMapFiltered(const std::string & name, const DataTypes & arguments, const Array & params)
{
    if (params.size() != 1)
        throw Exception("Aggregate function " + name + " requires exactly one parameter of Array type.",
            ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

    Array keys_to_keep;
    if (!params.front().tryGet<Array>(keys_to_keep))
        throw Exception("Aggregate function " + name + " requires an Array as parameter.",
            ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);

    auto [keys_type, values_types] = parseArguments(name, arguments);

    AggregateFunctionPtr res(createWithNumericBasedType<Function>(*keys_type, keys_type, values_types, keys_to_keep, arguments, params));
    if (!res)
        res.reset(createWithDecimalType<Function>(*keys_type, keys_type, values_types, keys_to_keep, arguments, params));
    if (!res)
        throw Exception("Illegal type of argument for aggregate function " + name, ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);

    return res;
}
Example #15
0
	void test_array(){
		OPH();
		DEBUG("testing array ......");

		Array* a =SafeNew<Array>();
		for(int64_t i=0; i<14; ++i){
			a->push_back(SafeNew<Int32>());
		}
		for(int64_t i=0; i<14; ++i){
			a->pop_back();
		}
		ASSERT(a->empty());
		
		// common array
		{
			Array* arr =SafeNew<Array>();

			// push_back, size, pop_front, front
			for(int i=0; i<100; ++i){
				arr->push_back(String::Format("%d", i));
			}
			for(int i=0; i<100; ++i){
				CHECK_EXIT(((String*)(arr->front()))->is(String::Format("%d", i)), 1);
				arr->pop_front();
			}
			CHECK_EXIT(arr->size()==0, 1);

			// push_front, size, pop_back, back
			for(int i=99; i>=0; --i){
				arr->push_front(String::Format("%d", i));
			}
			CHECK_EXIT(arr->size()==100, 1);
			for(int i=99; i>=0; --i){
				CHECK_EXIT(((String*)(arr->back()))->is(String::Format("%d", i)), 1);
				arr->pop_back();
			}
			CHECK_EXIT(arr->size()==0, 1);

			// insert, remove
			for(int i=0; i<100; ++i){
				arr->push_back(SafeNew<Int64, int64_t>(i));
			}
			arr->push_front(SafeNew<Int64, int64_t>(-1));
			arr->push_back(SafeNew<Int64, int64_t>(100));
			for(int i=0; i<102; ++i){
				CHECK_EXIT(((Int64*)(arr->get(i)))->getValue() == i-1, 1);
			}
			arr->insert(50, SafeNew<Int64, int64_t>(9999));
			CHECK_EXIT(((Int64*)(arr->get(50)))->getValue() == 9999, 1);
			CHECK_EXIT(((Int64*)(arr->get(51)))->getValue() == 49, 1);
			CHECK_EXIT(((Int64*)(arr->get(49)))->getValue() == 48, 1);
			arr->remove(102);
			arr->remove(50);
			arr->remove(0);
			for(int i=0; i<100; ++i){
				CHECK_EXIT(((Int64*)(arr->front()))->getValue() == i, 1);
				arr->pop_front();
			}
			CHECK_EXIT(arr->size()==0, 1);
		}

		// int64 array
		{
			Int64Array* arr =SafeNew<Int64Array>();

			// push_back, size, pop_front, front
			for(int i=0; i<100; ++i){
				arr->push_back(i);
			}
			for(int i=0; i<100; ++i){
				CHECK_EXIT(arr->front() == i, 1);
				arr->pop_front();
			}
			CHECK_EXIT(arr->size()==0, 1);

			// push_front, size, pop_back, back
			for(int i=99; i>=0; --i){
				arr->push_front(i);
			}
			CHECK_EXIT(arr->size()==100, 1);
			for(int i=99; i>=0; --i){
				CHECK_EXIT(arr->back() == i, 1);
				arr->pop_back();
			}
			CHECK_EXIT(arr->size()==0, 1);

			// insert, remove
			for(int i=0; i<100; ++i){
				arr->push_back(i);
			}
			arr->push_front(-1);
			arr->push_back(100);
			for(int i=0; i<102; ++i){
				CHECK_EXIT(arr->get(i) == i-1, 1);
			}
			arr->insert(50, 9999);
			CHECK_EXIT(arr->get(50) == 9999, 1);
			CHECK_EXIT(arr->get(51) == 49, 1);
			CHECK_EXIT(arr->get(49) == 48, 1);
			arr->remove(102);
			arr->remove(50);
			arr->remove(0);
			for(int i=0; i<100; ++i){
				CHECK_EXIT(arr->front() == i, 1);
				arr->pop_front();
			}
			CHECK_EXIT(arr->size()==0, 1);
		}
	}
Example #16
0
		inline Array<Setting> Enum(
			const Optional<Size>& targetResolution = none,
			const Optional<int32>& targetRefreshRate = 60,
			const Optional<size_t>& targetDisplayIndex = 0)
		{
			Array<Setting> results;
			{
				const auto outputs = Graphics::EnumOutputs();

				size_t displayIndex = 0;

				for (const auto& output : outputs)
				{
					Size maxResolution(0, 0);

					// Get max resolution
					for (const auto& mode : output.displayModes)
					{
						if ((maxResolution.x * maxResolution.y) < (mode.size.x * mode.size.y))
						{
							maxResolution = mode.size;
						}
					}

					const double screenAspect = static_cast<double>(maxResolution.x) / maxResolution.y;

					for (const auto& mode : output.displayModes)
					{
						const double aspect = static_cast<double>(mode.size.x) / mode.size.y;

						if (targetResolution)
						{
							if ((mode.size.x >= targetResolution->x && mode.size.y >= targetResolution->y)
								|| mode.size == maxResolution)
							{
								results.push_back({ displayIndex, mode, screenAspect / aspect });
							}
						}
						else
						{
							results.push_back({ displayIndex, mode, screenAspect / aspect });
						}
					}

					++displayIndex;
				}

				if (targetDisplayIndex && results.count_if([index = *targetDisplayIndex](const auto& result){ return result.displayIndex == index; }))
				{
					results.remove_if([index = *targetDisplayIndex](const auto& result){ return result.displayIndex != index; });
				}
			}

			Array<Setting> results2;
			{
				Array<Setting> tmps;
				std::pair<size_t, Size> previous(0, Size(0, 0));

				for (const auto& result : results)
				{
					const auto current = std::make_pair(result.displayIndex, result.dislayMode.size);

					if (previous == current)
					{
						tmps.push_back(result);
					}
					else
					{
						if (tmps.size() > 1)
						{
							if (targetRefreshRate)
							{
								results2.push_back(tmps.sorted_by([target = *targetRefreshRate](const auto& a, const auto& b)
								{
									return std::abs(target - a.dislayMode.refreshRateHz) < std::abs(target - b.dislayMode.refreshRateHz);
								}).front());

								tmps.clear();
							}
							else
							{
								results2.push_back(tmps.sorted_by([](const auto& a, const auto& b)
								{
									return a.dislayMode.refreshRateHz < b.dislayMode.refreshRateHz;
								}).back());

								tmps.clear();
							}
						}
						else if (tmps.size() == 1)
						{
							results2.push_back(tmps.front());

							tmps.clear();
						}

						previous = current;

						tmps.push_back(result);
					}
				}

				if (tmps.size() > 1)
				{
					if (targetRefreshRate)
					{
						results2.push_back(tmps.sorted_by([target = *targetRefreshRate](const auto& a, const auto& b)
						{
							return std::abs(target - a.dislayMode.refreshRateHz) < std::abs(target - b.dislayMode.refreshRateHz);
						}).front());
					}
					else
					{
						results2.push_back(tmps.sorted_by([](const auto& a, const auto& b)
						{
							return a.dislayMode.refreshRateHz < b.dislayMode.refreshRateHz;
						}).back());
					}
				}
				else if (tmps.size() == 1)
				{
					results2.push_back(tmps.front());
				}
			}

			return results2;
		}
Example #17
0
		inline std::pair<size_t, DisplayMode> Get(
			Preference preference = Preference::AspectMin,
			const Optional<Size>& targetResolution = none,
			const Optional<int32>& targetRefreshRate = 60,
			const Optional<size_t>& targetDisplayIndex = 0)
		{
			Array<Setting> results = Enum(targetResolution, targetRefreshRate, targetDisplayIndex);

			if (results.size() == 1)
			{
				const auto& reuslt = results.front();

				return{ reuslt.displayIndex, reuslt.dislayMode };
			}

			if (!targetResolution)
			{
				if (preference == Preference::AspectMin)
				{
					preference = Preference::Min;
				}
				else if (preference == Preference::AspectMin)
				{
					preference = Preference::Max;
				}
			}

			if (preference == Preference::Min)
			{
				const auto& reuslt = results.stable_sort_by([](const auto& a, const auto& b)
				{
					return (a.dislayMode.size.x * a.dislayMode.size.y) < (b.dislayMode.size.x * b.dislayMode.size.y);
				}).front();

				return{ reuslt.displayIndex, reuslt.dislayMode };
			}
			else if (preference == Preference::Max)
			{
				const auto& reuslt = results.stable_sort_by([](const auto& a, const auto& b)
				{
					return (a.dislayMode.size.x * a.dislayMode.size.y) > (b.dislayMode.size.x * b.dislayMode.size.y);
				}).front();

				return{ reuslt.displayIndex, reuslt.dislayMode };
			}
			else if (preference == Preference::AspectMin)
			{
				results.stable_sort_by([](const auto& a, const auto& b)
				{
					return (a.dislayMode.size.x * a.dislayMode.size.y) < (b.dislayMode.size.x * b.dislayMode.size.y);
				});

				const auto& reuslt = results.stable_sort_by([](const auto& a, const auto& b)
				{
					double ar = std::abs(1.0 - a.xScale);
					double br = std::abs(1.0 - b.xScale);
					
					if (ar < 0.005)
					{
						ar = 0.0;
					}

					if (br < 0.005)
					{
						br = 0.0;
					}

					return ar < br;
				}).front();

				return{ reuslt.displayIndex, reuslt.dislayMode };
			}
			else // preference == Preference::AspectMax
			{
				results.stable_sort_by([](const auto& a, const auto& b)
				{
					return (a.dislayMode.size.x * a.dislayMode.size.y) > (b.dislayMode.size.x * b.dislayMode.size.y);
				});

				const auto& reuslt = results.stable_sort_by([](const auto& a, const auto& b)
				{
					double ar = std::abs(1.0 - a.xScale);
					double br = std::abs(1.0 - b.xScale);

					if (ar < 0.005)
					{
						ar = 0.0;
					}

					if (br < 0.005)
					{
						br = 0.0;
					}

					return ar < br;
				}).front();

				return{ reuslt.displayIndex, reuslt.dislayMode };
			}
		}
Example #18
0
// Compute the convex hull using Graham Scan.
void nv::convexHull(const Array<Vector2> & input, Array<Vector2> & output, float epsilon/*=0*/)
{
    const uint inputCount = input.count();

    Array<float> coords;
    coords.resize(inputCount);

    for (uint i = 0; i < inputCount; i++) {
        coords[i] = input[i].x;
    }

    RadixSort radix;
    radix.sort(coords);

    const uint * ranks = radix.ranks();

    Array<Vector2> top(inputCount);
    Array<Vector2> bottom(inputCount);

    Vector2 P = input[ranks[0]];
    Vector2 Q = input[ranks[inputCount-1]];

    float topy = max(P.y, Q.y);
    float boty = min(P.y, Q.y);

    for (uint i = 0; i < inputCount; i++) {
        Vector2 p = input[ranks[i]];
        if (p.y >= boty) top.append(p);
    }

    for (uint i = 0; i < inputCount; i++) {
        Vector2 p = input[ranks[inputCount-1-i]];
        if (p.y <= topy) bottom.append(p);
    }

    // Filter top list.
    output.clear();
    output.append(top[0]);
    output.append(top[1]);

    for (uint i = 2; i < top.count(); ) {
        Vector2 a = output[output.count()-2];
        Vector2 b = output[output.count()-1];
        Vector2 c = top[i];

        float area = triangleArea(a, b, c);

        if (area >= -epsilon) {
            output.popBack();
        }

        if (area < -epsilon || output.count() == 1) {
            output.append(c);
            i++;
        }
    }
    
    uint top_count = output.count();
    output.append(bottom[1]);

    // Filter bottom list.
    for (uint i = 2; i < bottom.count(); ) {
        Vector2 a = output[output.count()-2];
        Vector2 b = output[output.count()-1];
        Vector2 c = bottom[i];

        float area = triangleArea(a, b, c);

        if (area >= -epsilon) {
            output.popBack();
        }

        if (area < -epsilon || output.count() == top_count) {
            output.append(c);
            i++;
        }
    }

    // Remove duplicate element.
    nvDebugCheck(output.front() == output.back());
    output.popBack();
}
Example #19
0
  T &front() {
    assert(the_size > 0);

    return data.front();
  }
Example #20
0
File: Fixed.hpp Project: jxv/Fixed
 A& front() {
     return arr.front();
 }
Example #21
0
  const T &front() const {
    assert(the_size > 0);

    return data.front();
  }
Example #22
0
File: Fixed.hpp Project: jxv/Fixed
 const A& front() const {
     return arr.front();
 }
Example #23
0
void CommandService::_process_respond(Command* rpc_res) {
    const int64_t who =static_cast<int64_t>(rpc_res->getWho());
    const int64_t rpc_id =static_cast<int64_t>(rpc_res->getSn());
    bool done =true;
    do {
        RpcInfo* rpc =_get_rpc(rpc_id);
        if(rpc == 0) {
            WARN("service %s(%lld) who %lld rpc %lld respond, not exist", name(), (long long)m_id, (long long)who, (long long)rpc_id);
            break;
        }
        if(Command* cmd=rpc->getCommand()) {
            // check & prepare command
            Array* queue =static_cast< Array* >(m_queue_tb->get(who));
            if(queue == 0) {
                WARN("service %s(%lld) who %lld rpc %lld respond, command not exist", name(), (long long)m_id, (long long)who, (long long)rpc_id);
                break;
            }
            Command* front =static_cast< Command* >(queue->front());
            if(!front) {
                WARN("service %s(%lld) who %lld rpc %lld respond, command not exist", name(), (long long)m_id, (long long)who, (long long)rpc_id);
                break;
            }
            if(front != cmd) {
                WARN("service %s(%lld) who %lld rpc %lld respond, command mismatch", name(), (long long)m_id, (long long)who, (long long)rpc_id);
                break;
            }

            // call rpc
            m_processing_command =front;
            const int64_t result =rpc->invoke(rpc_res);
            m_processing_command =0;

            // done
            if(rpc->isDone() == false) {
                done =false;
            }

            // process result
            const int64_t cmd_id =front->getCommand();
            if(result == Command::STATE_COMPLETE) {
                front->setState(Command::STATE_COMPLETE);
                queue->pop_front();
                INFO("service %s(%lld) who %lld rpc %lld respond, command %lld complete", name(), (long long)m_id, (long long)who, (long long)rpc_id, (long long)cmd_id);
            }
            else if(result > 0) {
                front->setState(Command::STATE_PROCESSING);
                INFO("service %s(%lld) who %lld rpc %lld respond, command %lld processing", name(), (long long)m_id, (long long)who, (long long)rpc_id, (long long)cmd_id);
            }
            else {
                front->setState(Command::STATE_ERROR);
                queue->pop_front();
                ERROR("service %s(%lld) who %lld rpc %lld respond, command %lld error %lld", name(), (long long)m_id, (long long)who, (long long)rpc_id, (long long)cmd_id, (long long)result);
            }

            // post process
            if(cmd_id==LOGOUT_REQUEST && queue->empty()) {
                m_queue_tb->remove(who);
            }
            else if(queue->size()) {
                _process_request(who);
            }
        }
        else {
            const int64_t result =rpc->invoke(rpc_res);
            if(result == Command::STATE_COMPLETE) {
                INFO("service %s(%lld) who %lld rpc %lld respond, complete", name(), (long long)m_id, (long long)who, (long long)rpc_id);
            }
            else if(result > 0) {
                INFO("service %s(%lld) who %lld rpc %lld respond, processing", name(), (long long)m_id, (long long)who, (long long)rpc_id);
            }
            else {
                ERROR("service %s(%lld) who %lld rpc %lld respond, error %lld", name(), (long long)m_id, (long long)who, (long long)rpc_id, (long long)result);
            }
        }
    } while(0);
    // remove rpc info
    if(done) {
        m_rpc_tb->remove(rpc_id);
    }
}