`normalize` C++ Examples

60 C++ code examples are found related to "normalize". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Project: electron-edge-js   Author: agracio   File: monoembedding.cpp    License: Apache License 2.0 7 votes vote down vote up
void MonoEmbedding::NormalizeException(MonoException** e) 
{
    static MonoMethod* method;

    if (!method)
    {
        method = mono_class_get_method_from_name(MonoEmbedding::GetClass(), "NormalizeException", -1);
    }

    void *params[] = { *e };
    MonoException *exc = NULL;
    MonoException *en = (MonoException*)mono_runtime_invoke(method, NULL, params, (MonoObject**)exc);
    if (NULL == exc)
    {
        *e = en;
    }
} 
Example 2
Project: apfs-fuse   Author: sgan81   File: Unicode.cpp    License: GNU General Public License v2.0 7 votes vote down vote up
int normalizeOptFoldU32Char(char32_t ch, bool case_fold, char32_t *nfd, uint8_t *ccc)
{
	char32_t ch_idx;
	uint16_t hi_res;
	uint16_t mi_res;
	uint16_t lo_res;
	const uint16_t *seq_u16 = 0;
	const uint32_t *seq_u32 = 0;
	uint32_t seq_len = 0;
	uint32_t cnt;
	char32_t c;

	ccc[0] = 0;
	if (ch >= 0xF0000)
	{
		if ((ch & 0xFFFE) == 0xFFFE)
			return -1;
		else
		{
			nfd[0] = ch;
			return 1;
		}
	} 
Example 3
Project: ZUI   Author: zero-rp   File: SkMatrix.cpp    License: MIT License 7 votes vote down vote up
static void normalize_perspective(SkScalar mat[9]) {
    // If it was interesting to never store the last element, we could divide all 8 other
    // elements here by the 9th, making it 1.0...
    //
    // When SkScalar was SkFixed, we would sometimes rescale the entire matrix to keep its
    // component values from getting too large. This is not a concern when using floats/doubles,
    // so we do nothing now.

    // Disable this for now, but it could be enabled.
#if 0
    if (0 == mat[SkMatrix::kMPersp0] && 0 == mat[SkMatrix::kMPersp1]) {
        SkScalar p2 = mat[SkMatrix::kMPersp2];
        if (p2 != 0 && p2 != 1) {
            double inv = 1.0 / p2;
            for (int i = 0; i < 6; ++i) {
                mat[i] = SkDoubleToScalar(mat[i] * inv);
            }
            mat[SkMatrix::kMPersp2] = 1;
        }
    }
#endif
} 
Example 4
Project: deepin-calculator   Author: linuxdeepin   File: rational.cpp    License: GNU General Public License v3.0 7 votes vote down vote up
void Rational::normalize()
{
    if (m_denom == 0) {
        m_valid = false;
        return;
    }
    if (m_num == 0) {
        m_denom = 1;
        return;
    }
    int g = gcd(abs(m_num), abs(m_denom));
    m_num /= g;
    m_denom /= g;
    if (m_denom < 0) {
        m_num = -m_num;
        m_denom = -m_denom;
    }
} 
Example 5
Project: YACCLAB   Author: prittt   File: yacclab_tensor.cc    License: BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
void YacclabTensorOutput2D::NormalizeLabels() {
    std::map<int, int> map_new_labels;
    int i_max_new_label = 0;

    for (int r = 0; r < mat_.rows; ++r) {
        unsigned * const mat_row = mat_.ptr<unsigned>(r);
        for (int c = 0; c < mat_.cols; ++c) {
            int iCurLabel = mat_row[c];
            if (iCurLabel > 0) {
                if (map_new_labels.find(iCurLabel) == map_new_labels.end()) {
                    map_new_labels[iCurLabel] = ++i_max_new_label;
                }
                mat_row[c] = map_new_labels.at(iCurLabel);
            }
        }
    }
} 
Example 6
Project: awtk   Author: zlgopen   File: SDL_x11xinput2.c    License: GNU Lesser General Public License v2.1 7 votes vote down vote up
static void
xinput2_normalize_touch_coordinates(SDL_VideoData *videodata, Window window,
    double in_x, double in_y, float *out_x, float *out_y)
{
    int i;
    for (i = 0; i < videodata->numwindows; i++) {
        SDL_WindowData *d = videodata->windowlist[i];
        if (d->xwindow == window) {
            if (d->window->w == 1) {
                *out_x = 0.5f;
            } else {
                *out_x = in_x / (d->window->w - 1);
            }
            if (d->window->h == 1) {
                *out_y = 0.5f;
            } else {
                *out_y = in_y / (d->window->h - 1);
            }
            return;
        } 
Example 7
Project: linorobot   Author: linorobot   File: duration.cpp    License: BSD 2-Clause "Simplified" License 7 votes vote down vote up
void normalizeSecNSecSigned(int32_t &sec, int32_t &nsec)
{
  int32_t nsec_part = nsec;
  int32_t sec_part = sec;

  while (nsec_part > 1000000000L)
  {
    nsec_part -= 1000000000L;
    ++sec_part;
  }
  while (nsec_part < 0)
  {
    nsec_part += 1000000000L;
    --sec_part;
  }
  sec = sec_part;
  nsec = nsec_part;
} 
Example 8
Project: ros_lecture   Author: project-srs   File: duration.cpp    License: MIT License 7 votes vote down vote up
void normalizeSecNSecSigned(int32_t &sec, int32_t &nsec)
{
  int32_t nsec_part = nsec;
  int32_t sec_part = sec;

  while (nsec_part > 1000000000L)
  {
    nsec_part -= 1000000000L;
    ++sec_part;
  }
  while (nsec_part < 0)
  {
    nsec_part += 1000000000L;
    --sec_part;
  }
  sec = sec_part;
  nsec = nsec_part;
} 
Example 9
Project: inviwo   Author: inviwo   File: eigennormalize.cpp    License: BSD 2-Clause "Simplified" License 7 votes vote down vote up
void EigenNormalize::process() {
    auto m = in_.getData();
    switch (method_.get()) {
        case Method::MaxElement: {
            auto maxV = m->maxCoeff();
            out_.setData(std::make_shared<Eigen::MatrixXf>((*m) / maxV));
            break;
        }
        case Method::MinMaxElement: {
            auto minV = m->minCoeff();
            auto maxV = m->maxCoeff();
            auto m2 = std::make_shared<Eigen::MatrixXf>(*m);
            m2->array() -= minV;
            m2->array() /= maxV - minV;
            out_.setData(m2);
            break;
        }
        case Method::Normalize:
            out_.setData(std::make_shared<Eigen::MatrixXf>(m->normalized()));
            break;
    }
} 
Example 10
Project: Marlin-2.0.x-FYSETC   Author: FYSETC   File: mixing.cpp    License: GNU General Public License v3.0 7 votes vote down vote up
void Mixer::normalize(const uint8_t tool_index) {
  float cmax = 0;
  #ifdef MIXER_NORMALIZER_DEBUG
    float csum = 0;
  #endif
  MIXER_STEPPER_LOOP(i) {
    const float v = collector[i];
    NOLESS(cmax, v);
    #ifdef MIXER_NORMALIZER_DEBUG
      csum += v;
    #endif
  }
  #ifdef MIXER_NORMALIZER_DEBUG
    SERIAL_ECHOPGM("Mixer: Old relation : [ ");
    MIXER_STEPPER_LOOP(i) {
      SERIAL_ECHO_F(collector[i] / csum, 3);
      SERIAL_CHAR(' ');
    } 
Example 11
Project: Rustla2   Author: MemeLabs   File: Channel.cpp    License: MIT License 7 votes vote down vote up
Status Channel::NormalizeAdvancedChannel(std::string *channel) {
  try {
    auto channel_uri = folly::Uri(*channel);

    if (channel_uri.scheme() != "http" && channel_uri.scheme() != "https") {
      return Status(StatusCode::VALIDATION_ERROR,
                    "invalid advanced url schema. must be http or https");
    }

    *channel = channel_uri.str();
  } catch (const std::invalid_argument &e) {
    return Status(StatusCode::VALIDATION_ERROR, "invalid advanced url");
  }

  return Status::OK;
} 
Example 12
Project: rom-properties   Author: GerbilSoft   File: lz_encoder_mf.c    License: GNU General Public License v2.0 7 votes vote down vote up
static void
normalize(lzma_mf *mf)
{
	assert(mf->read_pos + mf->offset == MUST_NORMALIZE_POS);
	uint32_t i = 0;
	// In future we may not want to touch the lowest bits, because there
	// may be match finders that use larger resolution than one byte.
	const uint32_t subvalue
			= (MUST_NORMALIZE_POS - mf->cyclic_size);
				// & (~(UINT32_C(1) << 10) - 1);

	for (i = 0; i < mf->hash_count; ++i) {
		// If the distance is greater than the dictionary size,
		// we can simply mark the hash element as empty.
		if (mf->hash[i] <= subvalue)
			mf->hash[i] = EMPTY_HASH_VALUE;
		else
			mf->hash[i] -= subvalue;
	} 
Example 13
Project: SLib   Author: SLIBIO   File: math.cpp    License: MIT License 7 votes vote down vote up
SLIB_INLINE static T normalizeDegree(T v) noexcept
			{
				if (Math::isNaN(v)) {
					return 0;
				}
				sl_int32 n = (sl_int32)v;
				T f = v - n;
				if (f < 0) {
					f = 1 + f;
					n--;
				}
				n = n % 360;
				if (n < 0) {
					n += 360;
				}
				v = (T)(n) + f;
				return v;
			} 
Example 14
Project: programming-abstractions   Author: heavy3   File: WorldGenerator.cpp    License: MIT License 7 votes vote down vote up
static void normalizeTerrain(Grid<double>& heights) {
  /* Compute the maximum and minimum heights. */
  double maxHeight = -numeric_limits<double>::infinity();
  double minHeight = numeric_limits<double>::infinity();
  for (int row = 0; row < heights.numRows(); row++) {
    for (int col = 0; col < heights.numCols(); col++) {
      maxHeight = max(maxHeight, heights[row][col]);
      minHeight = min(minHeight, heights[row][col]);
    }
  }
  
  /* Remap everything from the range [minHeight, maxHeight] to [0, 1]. */
  double range = maxHeight - minHeight;
  for (int row = 0; row < heights.numRows(); row++) {
    for (int col = 0; col < heights.numCols(); col++) {
      heights[row][col] -= minHeight;
      heights[row][col] /= range;
    }
  }
} 
Example 15
Project: zerospeech2017   Author: bootphon   File: MixBiNormal.cc    License: GNU General Public License v3.0 7 votes vote down vote up
void
MixBiNormal::normalizeAlphasWithNoise()
{
  // Normalize alphas.
  int l;
  double tmp = 0.0;
  for (l=0;l<NumMixComps;l++) {
    tmp += cur_alphas[l];
  }  

  // added to each one.
  double noise = tmp/NumMixComps;
  tmp += tmp;

  const double inv_tmp = 1.0/tmp;
  for (l=0;l<NumMixComps;l++) {
    cur_alphas[l] += noise;
    cur_alphas[l] *= inv_tmp;
  }
} 
Example 16
Project: Marlin_2.0.X_Beta_Alfawise_Ux0   Author: hobiseven   File: mixing.cpp    License: GNU General Public License v3.0 7 votes vote down vote up
void Mixer::normalize(const uint8_t tool_index) {
  float cmax = 0;
  #ifdef MIXER_NORMALIZER_DEBUG
    float csum = 0;
  #endif
  MIXER_STEPPER_LOOP(i) {
    const float v = collector[i];
    NOLESS(cmax, v);
    #ifdef MIXER_NORMALIZER_DEBUG
      csum += v;
    #endif
  }
  #ifdef MIXER_NORMALIZER_DEBUG
    SERIAL_ECHOPGM("Mixer: Old relation : [ ");
    MIXER_STEPPER_LOOP(i) {
      SERIAL_ECHO_F(collector[i] / csum, 3);
      SERIAL_CHAR(' ');
    } 
Example 17
Project: grpc-nebula-c   Author: grpc-nebula   File: channel_args.cc    License: Apache License 2.0 7 votes vote down vote up
grpc_channel_args* grpc_channel_args_normalize(const grpc_channel_args* a) {
  grpc_arg** args =
      static_cast<grpc_arg**>(gpr_malloc(sizeof(grpc_arg*) * a->num_args));
  for (size_t i = 0; i < a->num_args; i++) {
    args[i] = &a->args[i];
  }
  if (a->num_args > 1)
    qsort(args, a->num_args, sizeof(grpc_arg*), cmp_key_stable);

  grpc_channel_args* b =
      static_cast<grpc_channel_args*>(gpr_malloc(sizeof(grpc_channel_args)));
  b->num_args = a->num_args;
  b->args = static_cast<grpc_arg*>(gpr_malloc(sizeof(grpc_arg) * b->num_args));
  for (size_t i = 0; i < a->num_args; i++) {
    b->args[i] = copy_arg(args[i]);
  }

  gpr_free(args);
  return b;
} 
Example 18
Project: OrionUO   Author: Hotride   File: GLVector.cpp    License: MIT License 7 votes vote down vote up
void CVector::Normalize()
{
    WISPFUN_DEBUG("c38_f1");
    if (!X && !Y && !Z)
        return;

    double result = X * X + Y * Y + Z * Z;

    //if (result)
    {
        result = sqrtl(result);

        X /= result;
        Y /= result;
        Z /= result;
    }
} 
Example 19
Project: lullaby   Author: google   File: debug_render_impl.cc    License: Apache License 2.0 7 votes vote down vote up
static NormalizedCoordinates NormalizeScreenCoordinates(
    const mathfu::vec2& pixel_pos0, const mathfu::vec2& pixel_pos1,
    const mathfu::vec2i& dimensions) {
  // Flip Y axis from Y-down to Y-up, preserving quad winding.
  const float sx = 2.0f / dimensions.x;
  const float sy = 2.0f / dimensions.y;
  const float x0 = sx * pixel_pos0.x - 1.0f;
  const float y0 = 1.0f - sy * pixel_pos0.y;
  const float x1 = sx * pixel_pos1.x - 1.0f;
  const float y1 = 1.0f - sy * pixel_pos1.y;
  const float z = -1.0f;
  const NormalizedCoordinates coords = {
    mathfu::vec3(x0, y1, z),
    mathfu::vec3(x1, y0, z)
  };
  return coords;
} 
Example 20
Project: EventEntityExtractor   Author: bishanyang   File: Sentence.cpp    License: GNU Lesser General Public License v3.0 7 votes vote down vote up
void Sentence::NormalizeWords() {
	for (int s = 0; s < words.size(); ++s) {
		string word = words[s];

		// normalize digits
		bool is_number = true;
		for (int i = 0; i < word.size(); ++i) {
			if (!(word[i] >= '0' && word[i] <= '9')) {
				is_number = false;
				break;
			}
		}
		if (is_number) {
			lemmas[s] = "NUMNUM";
		} else if (word.find('@') != string::npos && word.find(".com") != string::npos) {
			lemmas[s] = "@EMAIL";
		} else { 
Example 21
Project: sling   Author: google   File: unicode.cc    License: Apache License 2.0 7 votes vote down vote up
int Unicode::Normalize(int c, int flags) {
  if (c & unicode_tab_mask) return c;
  if (flags & NORMALIZE_CASE) {
    c = unicode_lower_tab[c];
  }
  if (flags & NORMALIZE_LETTERS) {
    c = unicode_normalize_tab[c];
  }
  if (flags & NORMALIZE_DIGITS) {
    if (IsDigit(c)) c = '9';
  }
  if (flags & NORMALIZE_PUNCTUATION) {
    if (IsPunctuation(c)) c = 0;
  }
  if (flags & NORMALIZE_NAME) {
    if (IsNamePunctuation(c)) c = 0;
  }
  if (flags & NORMALIZE_WHITESPACE) {
    if (IsWhitespace(c)) c = 0;
  }
  return c;
} 
Example 22
Project: btrf   Author: lood339   File: matrix.c    License: BSD 2-Clause "Simplified" License 7 votes vote down vote up
void normalizeMatrix(Matrix *mat) {
	cellValueT lowest = minMatrix(mat, NULL, NULL);
	cellValueT highest = maxMatrix(mat, NULL, NULL);
	cellValueT *ptr = mat->cellValues;
	cellValueT val;
	double interval;
	matrixSizeT i = matSize(mat);

	interval = highest - lowest;

	// normalize
	ptr = mat->cellValues;
	i = matSize(mat);
	while (i--) {
		val = abs(*ptr);
		*(ptr++) = (cellValueT)(((double)(val - lowest) / interval) * 255.0);
	}
} 
Example 23
Project: VulkanDemos   Author: BobLChen   File: Q3BSPFileImporter.cpp    License: MIT License 7 votes vote down vote up
static void normalizePathName( const std::string &rPath, std::string &normalizedPath ) {
    normalizedPath = "";
    if (rPath.empty()) {
        return;
    }

#ifdef _WIN32
    std::string sep = "\\";
#else
    std::string sep = "/";
#endif

    static const unsigned int numDelimiters = 2;
    const char delimiters[ numDelimiters ] = { '/', '\\' };
    normalizedPath = rPath;
    for (const char delimiter : delimiters) {
        for ( size_t j=0; j<normalizedPath.size(); ++j ) {
            if ( normalizedPath[j] == delimiter ) {
                normalizedPath[ j ] = sep[ 0 ];
            }
        }
    }
} 
Example 24
Project: cvkit   Author: roboception   File: mesh.cc    License: BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
void Mesh::normalizeNormals()
{
  for (int i=3*(getVertexCount()-1); i>=0; i-=3)
  {
    float len=(float) sqrt(normal[i]*normal[i]+
                           normal[i+1]*normal[i+1]+
                           normal[i+2]*normal[i+2]);

    if (len > 0)
    {
      normal[i]/=len;
      normal[i+1]/=len;
      normal[i+2]/=len;
    }
  }
} 
Example 25
Project: ChromaTag   Author: CogChameleon   File: JMD_Math_Common.cpp    License: MIT License 6 votes vote down vote up
void JMD::JMD_Utils_Math::Vector_Normalize(float *vector_param, unsigned int size_param) 
{
	//get length
	float length = Vector_Length(vector_param, size_param);
	
	//normalize elements
	for( int i=0; i < size_param; i++ ) { vector_param[i] /= length; }
} 
Example 26
Project: NiuTensor   Author: NiuTrans   File: Normalize.cpp    License: Apache License 2.0 6 votes vote down vote up
void _Normalize(const XTensor * input, XTensor * output, int dim, 
                const XTensor * mean, const XTensor * var, 
                const XTensor * a, const XTensor * b, DTYPE epsilon)
{
    CheckNTErrors((_IsSameShaped(input, output)), "Unmatched input tensors!");
    CheckNTErrors((_IsSameShaped(a, b)), "Unmatched input tensors");
    CheckNTErrors((_IsSameShaped(mean, var)), "Unmatched input tensors");
    CheckNTErrors((input && output && mean && var && a && b), "Empty input tensors!");
    CheckNTErrors((dim >= 0 && dim < input->order), "Incorrect reduction dimension!");
    CheckNTErrors((input->order == mean->order + 1), "Incorrect reduction dimension!");

    int stride = 1;
    int strideNum = input->dimSize[dim];
    int blockSize = 1;
    int blockNum = 1;
    for (int i = 0; i < input->order; i++) {
        if (i < dim) {
            CheckNTErrors((input->dimSize[i] == mean->dimSize[i]), "Wrong size!");
            blockNum *= input->dimSize[i];
        }
        else if (i > dim) {
            CheckNTErrors((input->dimSize[i] == mean->dimSize[i - 1]), "Wrong size!");
            stride *= input->dimSize[i];
        }
    } 
Example 27
Project: ChromaTag   Author: CogChameleon   File: JMD_Math_Common.cpp    License: MIT License 6 votes vote down vote up
void JMD::JMD_Utils_Math::Vector_Normalize(vector<double> *vector_param) 
{
	//get length
	float length = Vector_Length(vector_param);
	
	//normalize elements
	for(vector<double>::iterator iter=vector_param->begin(); iter != vector_param->end(); ++iter)
	{
		*iter /= length;
	}
} 
Example 28
Project: EGSfM   Author: AIBluefisher   File: domset.cc    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
void Domset::deNormalizePointCloud()
{
  const size_t numPoints( points.size() );
// denormalizing points
#if OPENMVG_USE_OPENMP
#pragma omp parallel for
#endif
  for_parallel( i, numPoints )
  {
    points[ i ].pos = ( points[ i ].pos / normScale ) + pcCentre.pos;
  }

  const size_t numOldPoints( origPoints.size() );
#if OPENMVG_USE_OPENMP
#pragma omp parallel for
#endif
  for_parallel( i, numOldPoints )
  {
    origPoints[ i ].pos = ( origPoints[ i ].pos / normScale ) + pcCentre.pos;
  }

  // denormalizing camera centers
  const size_t numViews( views.size() );
#if OPENMVG_USE_OPENMP
#pragma omp parallel for
#endif
  for_parallel( i, numViews )
  {
    views[ i ].trans = ( views[ i ].trans / normScale ) + pcCentre.pos;
  }
} 
Example 29
Project: cirrus   Author: ucbrise   File: SparseDataset.cpp    License: Apache License 2.0 6 votes vote down vote up
void SparseDataset::normalize(uint64_t hash_size) {
  std::vector<FEATURE_TYPE> max_val_feature(hash_size);
  std::vector<FEATURE_TYPE> min_val_feature(hash_size,
      std::numeric_limits<FEATURE_TYPE>::max());

  for (const auto& w : data_) {
    for (const auto& v : w) {
      uint64_t index = v.first;
      FEATURE_TYPE value = v.second;

#ifdef DEBUG
      if (index >= hash_size)
        throw std::runtime_error("Index bigger than capacity");
#endif

      max_val_feature[index] = std::max(value, max_val_feature[index]);
      min_val_feature[index] = std::min(value, min_val_feature[index]);
    }
  }
  for (auto& w : data_) {
    for (auto& v : w) {
      int index = v.first;

      // only normalize if there are different values
      // in the same column
      if (max_val_feature[index] != min_val_feature[index]) {
        v.second = (v.second - min_val_feature[index]) /
                   (max_val_feature[index] - min_val_feature[index]);
      }
    }
  }
} 
Example 30
Project: xmrig-amd   Author: xmrig   File: ApiRouter.cpp    License: GNU General Public License v3.0 6 votes vote down vote up
static inline rapidjson::Value normalize(double d)
{
    using namespace rapidjson;

    if (!isnormal(d)) {
        return Value(kNullType);
    }

    return Value(floor(d * 100.0) / 100.0);
} 
Example 31
Project: YACCLAB   Author: prittt   File: yacclab_tensor.cc    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
void YacclabTensorOutput3D::NormalizeLabels() {
    std::map<int, int> map_new_labels;
    int i_max_new_label = 0;

    if (mat_.dims == 3) {
        for (int z = 0; z < mat_.size[0]; z++) {
            for (int y = 0; y < mat_.size[1]; y++) {
                unsigned int * img_labels_row = reinterpret_cast<unsigned int *>(mat_.data + z * mat_.step[0] + y * mat_.step[1]);
                for (int x = 0; x < mat_.size[2]; x++) {
                    int iCurLabel = img_labels_row[x];
                    if (iCurLabel > 0) {
                        if (map_new_labels.find(iCurLabel) == map_new_labels.end()) {
                            map_new_labels[iCurLabel] = ++i_max_new_label;
                        }
                        img_labels_row[x] = map_new_labels.at(iCurLabel);
                    }
                }
            }
        }
    }
} 
Example 32
Project: ZUI   Author: zero-rp   File: SkGaussFilter.cpp    License: MIT License 6 votes vote down vote up
static void normalize(int n, double* gauss) {
    // Carefully add from smallest to largest to calculate the normalizing sum.
    double sum = 0;
    for (int i = n-1; i >= 1; i--) {
        sum += 2 * gauss[i];
    }
    sum += gauss[0];

    // Normalize gauss.
    for (int i = 0; i < n; i++) {
        gauss[i] /= sum;
    }

    // The factors should sum to 1. Take any remaining slop, and add it to gauss[0]. Add the
    // values in such a way to maintain the most accuracy.
    sum = 0;
    for (int i = n - 1; i >= 1; i--) {
        sum += 2 * gauss[i];
    }

    gauss[0] = 1 - sum;
} 
Example 33
Project: echo   Author: timi-liuliang   File: maximal_inputs.cpp    License: MIT License 6 votes vote down vote up
void NormalizeColByMax(const arma::mat &input,
                       arma::mat &output)
{
  output.set_size(input.n_rows, input.n_cols);
  for (arma::uword i = 0; i != input.n_cols; ++i)
  {
    const double max = arma::max(arma::abs(input.col(i)));
    if (max != 0.0)
    {
      output.col(i) = input.col(i) / max;
    }
    else
    {
      output.col(i) = input.col(i);
    }
  } 
Example 34
Project: zetasql   Author: google   File: civil_time.cc    License: Apache License 2.0 6 votes vote down vote up
void NormalizeDatetime(int64_t* y, int32_t* mo, int32_t* d, int32_t* h, int32_t* m,
                       int32_t* s, int64_t* ns) {
  int64_t carry_seconds = zetasql_base::MathUtil::FloorOfRatio(*ns, kNanosPerSecond);
  absl::CivilSecond cs(*y, *mo, *d, *h, *m, *s);
  cs += carry_seconds;
  *y = cs.year();
  *mo = cs.month();
  *d = cs.day();
  *h = cs.hour();
  *m = cs.minute();
  *s = cs.second();
  *ns -= (carry_seconds * kNanosPerSecond);
  // The CivilTime constructor should have coerced all the time values to the
  // appropriate range.
  DCHECK(IsValidTimeFields(*h, *m, *s, *ns));
} 
Example 35
Project: w2rap-contigger   Author: bioinfologics   File: IntDistribution.cc    License: MIT License 6 votes vote down vote up
void IntDistribution::_normalize()
{
  const int x0 = _prob.x_min();
  const int x1 = _prob.x_max();
    
  ForceAssertGe(_prob[x0], 0.0);
  _prob_le[x0] = _prob[x0];
  for (int x = x0 + 1; x <= x1; x++) {
    const real_t p = _prob[x];
    ForceAssertGe(p, 0.0);
    _prob_le[x] = _prob_le[x - 1] + p;
  }
  
  const real_t sum = _prob_le[x1];
  if (sum == 0.0) {
    _prob = IntFunction<real_t>(); // this signals an invalid distribution
  }
  else { 
Example 36
Project: rosbots_driver   Author: ROSbots   File: duration.cpp    License: GNU General Public License v3.0 5 votes vote down vote up
void normalizeSecNSecSigned(int32_t &sec, int32_t &nsec)
  {
    int32_t nsec_part = nsec;
    int32_t sec_part = sec;

    while (nsec_part > 1000000000L)
    {
      nsec_part -= 1000000000L;
      ++sec_part;
    }
    while (nsec_part < 0)
    {
      nsec_part += 1000000000L;
      --sec_part;
    }
    sec = sec_part;
    nsec = nsec_part;
  } 
Example 37
Project: AntiDupl   Author: ermig1979   File: SimdBaseHistogram.cpp    License: MIT License 5 votes vote down vote up
void NormalizeHistogram(const uint8_t * src, size_t srcStride, size_t width, size_t height, uint8_t * dst, size_t dstStride)
        {
            uint32_t histogram[HISTOGRAM_SIZE];
            Histogram(src, width, height, srcStride, histogram);

            uint8_t colors[HISTOGRAM_SIZE];
            NormalizedColors(histogram, colors);

            ChangeColors(src, srcStride, width, height, colors, dst, dstStride);
        } 
Example 38
Project: xmrig   Author: xmrig   File: Json.cpp    License: GNU General Public License v3.0 5 votes vote down vote up
rapidjson::Value xmrig::Json::normalize(double value, bool zero)
{
    using namespace rapidjson;

    if (!std::isnormal(value)) {
        return zero ? Value(0.0) : Value(kNullType);
    }

    return Value(floor(value * 100.0) / 100.0);
} 
Example 39
Project: BabylonCpp   Author: samdauwe   File: DetourObstacleAvoidance.cpp    License: Apache License 2.0 5 votes vote down vote up
void dtObstacleAvoidanceDebugData::normalizeSamples()
{
	normalizeArray(m_pen, m_nsamples);
	normalizeArray(m_vpen, m_nsamples);
	normalizeArray(m_vcpen, m_nsamples);
	normalizeArray(m_spen, m_nsamples);
	normalizeArray(m_tpen, m_nsamples);
} 
Example 40
Project: basalt-mirror   Author: VladyslavUsenko   File: FloatImage.cc    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void FloatImage::normalize() {
  const float maxVal = *max_element(pixels.begin(),pixels.end());
  const float minVal = *min_element(pixels.begin(),pixels.end());
  const float range = maxVal - minVal;
  const float rescale = 1 / range;
  for ( unsigned int i = 0; i < pixels.size(); i++ )
    pixels[i] = (pixels[i]-minVal) * rescale;
} 
Example 41
Project: sentencepiece   Author: google   File: io_win32.cc    License: Apache License 2.0 5 votes vote down vote up
wstring normalize(wstring path) {
  if (has_longpath_prefix(path.c_str())) {
    path = path.substr(4);
  }

  static const wstring dot(L".");
  static const wstring dotdot(L"..");
  const WCHAR* p = path.c_str();

  std::vector<wstring> segments;
  int segment_start = -1;
  // Find the path segments in `path` (separated by "/").
  for (int i = 0;; ++i) {
    if (!is_separator(p[i]) && p[i] != L'\0') {
      // The current character does not end a segment, so start one unless it's
      // already started.
      if (segment_start < 0) {
        segment_start = i;
      }
    } else if (segment_start >= 0 && i > segment_start) {
      // The current character is "/" or "\0", so this ends a segment.
      // Add that to `segments` if there's anything to add; handle "." and "..".
      wstring segment(p, segment_start, i - segment_start);
      segment_start = -1;
      if (segment == dotdot) {
        if (!segments.empty() &&
            (!has_drive_letter(segments[0].c_str()) || segments.size() > 1)) {
          segments.pop_back();
        }
      } else if (segment != dot && !segment.empty()) {
        segments.push_back(segment);
      }
    } 
Example 42
void ZChessboardCalibrationPatternFinder::setNormalizeImage(bool normalizeImage)
{
    if (this->normalizeImage() != normalizeImage) {
        if (normalizeImage)
            m_findChessboardFlags |=  cv::CALIB_CB_NORMALIZE_IMAGE;
        else
            m_findChessboardFlags &= ~cv::CALIB_CB_NORMALIZE_IMAGE;
        emit normalizeImageChanged(normalizeImage);
    } 
Example 43
Project: libscapi   Author: cryptobiu   File: GF2EX.cpp    License: MIT License 5 votes vote down vote up
void GF2EX::normalize()
{
   long n;
   const GF2E* p;

   n = rep.length();
   if (n == 0) return;
   p = rep.elts() + n;
   while (n > 0 && IsZero(*--p)) {
      n--;
   }
   rep.SetLength(n);
} 
Example 44
Project: supra   Author: IFL-CAMP   File: duration.cpp    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
void normalizeSecNSecSigned(int32_t &sec, int32_t &nsec)
  {
    int32_t nsec_part = nsec;
    int32_t sec_part = sec;

    while (nsec_part > 1000000000L)
    {
      nsec_part -= 1000000000L;
      ++sec_part;
    }
    while (nsec_part < 0)
    {
      nsec_part += 1000000000L;
      --sec_part;
    }
    sec = sec_part;
    nsec = nsec_part;
  } 
Example 45
Project: qtltools   Author: qtltools   File: rep_management.cpp    License: GNU General Public License v3.0 5 votes vote down vote up
void rep_data::normalize(vector < float > & X) {
	double mean = 0.0, sum = 0.0;
	for (int s = 0; s < sample_count ; s ++) mean += X[s];
	mean /= sample_count;
	for (int s = 0; s < sample_count ; s ++) {
		X[s] -= mean;
		sum += X[s] * X[s];
	}
	sum = sqrt(sum);
	if (sum == 0) sum = 1;
	for (int s = 0; s < sample_count ; s ++) X[s] /= sum;
} 
Example 46
Project: BlueshiftEngine   Author: PolygonTek   File: cd_hull.cpp    License: Apache License 2.0 5 votes vote down vote up
void Quaternion::Normalize()
{
	float m = sqrtf(sqr(w) + sqr(x) + sqr(y) + sqr(z));
	if (m < 0.000000001f)
	{
		w = 1.0f;
		x = y = z = 0.0f;
		return;
	}
	(*this) *= (1.0f / m);
} 
Example 47
Project: scantailor-advanced   Author: 4lex4   File: ArcLengthMapper.cpp    License: GNU General Public License v3.0 5 votes vote down vote up
void ArcLengthMapper::normalizeRange(double totalArcLen) {
  if (m_samples.size() <= 1) {
    // If size == 1, samples.back().arcLen below will be 0.
    return;
  }

  assert(totalArcLen != 0);

  const double scale = totalArcLen / m_samples.back().arcLen;
  for (Sample& sample : m_samples) {
    sample.arcLen *= scale;
  }
} 
Example 48
Project: tinygizmo   Author: ddiakopoulos   File: winmm_joystick.c    License: The Unlicense 5 votes vote down vote up
static float normalizeAxis(DWORD pos, DWORD min, DWORD max)
{
    float fpos = (float) pos;
    float fmin = (float) min;
    float fmax = (float) max;

    return (2.f * (fpos - fmin) / (fmax - fmin)) - 1.f;
} 
Example 49
Project: tensorflow   Author: rockchip-linux   File: normalize_test.cc    License: Apache License 2.0 5 votes vote down vote up
explicit NormalizeOpModel(const string& input) {
    input_ = AddInput(TensorType_STRING);
    output_ = AddOutput(TensorType_STRING);

    SetCustomOp("Normalize", {}, Register_NORMALIZE);
    BuildInterpreter({{static_cast<int>(input.size())}});
    PopulateStringTensor(input_, {input});
  } 
Example 50
Project: edge-js   Author: agracio   File: monoembedding.cpp    License: Apache License 2.0 5 votes vote down vote up
void MonoEmbedding::NormalizeException(MonoException** e) 
{
    static MonoMethod* method;

    if (!method)
    {
        method = mono_class_get_method_from_name(MonoEmbedding::GetClass(), "NormalizeException", -1);
    }

    void *params[] = { *e };
    MonoException *exc = NULL;
    MonoException *en = (MonoException*)mono_runtime_invoke(method, NULL, params, (MonoObject**)exc);
    if (NULL == exc)
    {
        *e = en;
    }
} 
Example 51
Project: megamol   Author: UniStuttgart-VISUS   File: RMS.cpp    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void protein_cuda::Normalize(double a[3])
{
    double b;

    b = 1.0/sqrt((double)(a[0]*a[0] + a[1]*a[1] + a[2]*a[2]));
    a[0] *= b;
    a[1] *= b;
    a[2] *= b;
} 
Example 52
Project: apollo   Author: ApolloAuto   File: util.cc    License: Apache License 2.0 5 votes vote down vote up
void NormalizeRow(Matrixd* prob) {
  double sum = 0.0;
  for (size_t row = 0; row < VALID_OBJECT_TYPE; ++row) {
    sum = 0.0;
    for (size_t col = 0; col < VALID_OBJECT_TYPE; ++col) {
      sum += (*prob)(row, col);
    }
    sum = sum < 1e-9 ? 1e-9 : sum;
    for (size_t col = 0; col < VALID_OBJECT_TYPE; ++col) {
      (*prob)(row, col) /= sum;
    }
  }
} 
Example 53
Project: neoGFX   Author: i42output   File: hb-ot-var.cc    License: GNU General Public License v3.0 5 votes vote down vote up
void
hb_ot_var_normalize_coords (hb_face_t    *face,
			    unsigned int coords_length,
			    const float *design_coords, /* IN */
			    int *normalized_coords /* OUT */)
{
  const OT::fvar &fvar = *face->table.fvar;
  for (unsigned int i = 0; i < coords_length; i++)
    normalized_coords[i] = fvar.normalize_axis_value (i, design_coords[i]);

  face->table.avar->map_coords (normalized_coords, coords_length);
} 
Example 54
Project: PerfectShow   Author: KAlO2   File: opencv_utility.cpp    License: Apache License 2.0 5 votes vote down vote up
cv::Mat normalize(const cv::Mat& mat, double* max/* = nullptr */)
{
	double x = 1.0;
	Mat mat2;
	switch(mat.depth())
	{
	case CV_8U:  x = std::numeric_limits<uint8_t>::max();  mat.convertTo(mat2, CV_32F, 1/x); break;
	case CV_8S:  x = std::numeric_limits<int8_t>::max();   mat.convertTo(mat2, CV_32F, 1/x); break;
	case CV_16U: x = std::numeric_limits<uint16_t>::max(); mat.convertTo(mat2, CV_32F, 1/x); break;
	case CV_16S: x = std::numeric_limits<int16_t>::max();  mat.convertTo(mat2, CV_32F, 1/x); break;
	case CV_32S: x = std::numeric_limits<int32_t>::max();  mat.convertTo(mat2, CV_32F, 1/x); break;

	case CV_32F: mat.copyTo(mat2);                 break;
	case CV_64F: mat.convertTo(mat2, CV_32F, 1.0); break;

	default:
		assert(false);
		break;
	}

	if(max != nullptr)
		*max = x;
	return mat2;
} 
Example 55
Project: cnrig   Author: cnrig   File: ApiRouter.cpp    License: GNU General Public License v3.0 5 votes vote down vote up
static inline double normalize(double d)
{
    if (!isnormal(d)) {
        return 0.0;
    }

    return floor(d * 100.0) / 100.0;
} 
Example 56
Project: RosettaStone   Author: utilForever   File: InputDataConverter.cpp    License: GNU Affero General Public License v3.0 5 votes vote down vote up
float InputDataConverter::NormalizeBool(bool v) const
{
    double vv;

    if (v)
    {
        vv = 1.0;
    }
    else
    { 
Example 57
Project: openweave-core   Author: openweave   File: PairingCodeSupport.cpp    License: Apache License 2.0 5 votes vote down vote up
jstring PairingCodeSupport::normalizePairingCode(JNIEnv * env, jclass cls, jstring pairingCodeJStr)
{
    WEAVE_ERROR err = WEAVE_NO_ERROR;
    const char * pairingCode = NULL;
    size_t pairingCodeLen;
    char * normalizedPairingCode = NULL;
    jstring normalizedPairingCodeJStr = NULL;

    VerifyOrExit(pairingCodeJStr != NULL, err = WEAVE_ERROR_INVALID_ARGUMENT);

    pairingCode = env->GetStringUTFChars(pairingCodeJStr, NULL);
    pairingCodeLen = env->GetStringUTFLength(pairingCodeJStr);

    normalizedPairingCode = strdup(pairingCode);
    VerifyOrExit(normalizedPairingCode != NULL, err = WEAVE_ERROR_NO_MEMORY);

    NormalizePairingCode(normalizedPairingCode, pairingCodeLen);

    normalizedPairingCode[pairingCodeLen] = 0;
    normalizedPairingCodeJStr = env->NewStringUTF((const char *)normalizedPairingCode);
    VerifyOrExit(normalizedPairingCodeJStr != NULL, err = WEAVE_JNI_ERROR_EXCEPTION_THROWN);

exit:
    if (pairingCode != NULL)
    {
        env->ReleaseStringUTFChars(pairingCodeJStr, pairingCode);
    }
    if (normalizedPairingCode != NULL)
    {
        free(normalizedPairingCode);
    }
    if (err != WEAVE_NO_ERROR)
    {
        JNIUtils::ThrowError(env, err);
    }
    return normalizedPairingCodeJStr;
} 
Example 58
Project: N64-Tools   Author: jombo23   File: AN8XMath_Quaternion.cpp    License: The Unlicense 5 votes vote down vote up
AN8XQUATERNION * AN8XQuaternionNormalize(AN8XQUATERNION * out,AN8XQUATERNION * in)
{
	float mag = AN8XQuaternionLength(in);
	out->x = in->x / mag;
	out->y = in->y / mag;
	out->z = in->z / mag;
	out->w = in->w / mag;
	return out;
} 
Example 59
Project: sys-con   Author: cathery   File: Dualshock4Controller.cpp    License: GNU General Public License v3.0 5 votes vote down vote up
void Dualshock4Controller::NormalizeAxis(uint8_t x,
                                         uint8_t y,
                                         uint8_t deadzonePercent,
                                         float *x_out,
                                         float *y_out)
{
    float x_val = x - 127.0f;
    float y_val = 127.0f - y;
    // Determine how far the stick is pushed.
    //This will never exceed 32767 because if the stick is
    //horizontally maxed in one direction, vertically it must be neutral(0) and vice versa
    float real_magnitude = std::sqrt(x_val * x_val + y_val * y_val);
    float real_deadzone = (127 * deadzonePercent) / 100;
    // Check if the controller is outside a circular dead zone.
    if (real_magnitude > real_deadzone)
    {
        // Clip the magnitude at its expected maximum value.
        float magnitude = std::min(127.0f, real_magnitude);
        // Adjust magnitude relative to the end of the dead zone.
        magnitude -= real_deadzone;
        // Normalize the magnitude with respect to its expected range giving a
        // magnitude value of 0.0 to 1.0
        //ratio = (currentValue / maxValue) / realValue
        float ratio = (magnitude / (127 - real_deadzone)) / real_magnitude;
        *x_out = x_val * ratio;
        *y_out = y_val * ratio;
    }
    else
    { 
Example 60
Project: O-CNN   Author: microsoft   File: octree.cpp    License: MIT License 5 votes vote down vote up
void Octree::normalize_pts(vector<float>& pts_scaled, const Points& point_cloud) {
  const float* bbmin = oct_info_.bbmin();
  const float* pts = point_cloud.ptr(PointsInfo::kPoint);
  const int npt = point_cloud.info().pt_num();
  const float mul = float(1 << oct_info_.depth()) / oct_info_.bbox_max_width();
  pts_scaled.resize(3 * npt);

  // normalize the points into the range [0, 1 << depth_) using bbox_width
  #pragma omp parallel for
  for (int i = 0; i < npt; i++) {
    int i3 = i * 3;
    for (int j = 0; j < 3; j++) {
      pts_scaled[i3 + j] = (pts[i3 + j] - bbmin[j]) * mul;
    }
  }
}