Get similar images by vector

@param vector
@param threshold
@return
7665
public JsonResultSet getSimilarImagesAndIndex(String id, double[] vector, double threshold) {

    	JsonResultSet similar = new JsonResultSet();

        byte[] vectorInBytes = new byte[8 * vector.length];
        ByteBuffer bbuf = ByteBuffer.wrap(vectorInBytes);
        for (double value : vector) {
            bbuf.putDouble(value);
        }

        PostMethod queryMethod = null;
        String response = null;
        try {
            ByteArrayPartSource source = new ByteArrayPartSource("bytes", vectorInBytes);
            Part[] parts = {
            	new StringPart("id", id),
                new FilePart("vector", source),
                new StringPart("threshold", String.valueOf(threshold))
            };

            queryMethod = new PostMethod(webServiceHost + "/rest/visual/qindex/" + collectionName);
            queryMethod.setRequestEntity(new MultipartRequestEntity(parts, queryMethod.getParams()));
            int code = httpClient.executeMethod(queryMethod);
            if (code == 200) {
                InputStream inputStream = queryMethod.getResponseBodyAsStream();
                StringWriter writer = new StringWriter();
                IOUtils.copy(inputStream, writer);
                response = writer.toString();
                queryMethod.releaseConnection();

                similar = parseResponse(response);
            }
        } catch (Exception e) {
        	_logger.error("Exception for vector of length " + vector.length, e);
            response = null;
        } finally {
            if (queryMethod != null) {
                queryMethod.releaseConnection();
            }
        }
        return similar;
    }
738565
def threshold(np, acc, stream_raster, threshold=100., workingdir=None,
                  mpiexedir=None, exedir=None, log_file=None, runtime_file=None, hostfile=None):
        """"""
        fname = TauDEM.func_name('threshold')
        return TauDEM.run(FileClass.get_executable_fullpath(fname, exedir),
                          {'-ssa': acc}, workingdir,
                          {'-thresh': threshold},
                          {'-src': stream_raster},
                          {'mpipath': mpiexedir, 'hostfile': hostfile, 'n': np},
                          {'logfile': log_file, 'runtimefile': runtime_file})
662896
public INDArray asRowVector(BufferedImage image) {
        if (centerCropIfNeeded) {
            image = centerCropIfNeeded(image);
        }
        image = scalingIfNeed(image, true);
        if (channels == 3) {
            return toINDArrayBGR(image).ravel();
        }
        int[][] ret = toIntArrayArray(image);
        return NDArrayUtil.toNDArray(ArrayUtil.flatten(ret));
    }
819197
protected ImageDescriptor imageDescriptor(SarlConstructor element) {
		if (element.isStatic()) {
			return this.images.forStaticConstructor();
		}
		return this.images.forConstructor(
				element.getVisibility(),
				this.adornments.get(this.jvmModelAssociations.getInferredConstructor(element)));
	}
1150098
public List<RunT> getLastBuildsOverThreshold(int numberOfBuilds, Result threshold) {
        
        List<RunT> result = new ArrayList<>(numberOfBuilds);
        
        RunT r = getLastBuild();
        while (r != null && result.size() < numberOfBuilds) {
            if (!r.isBuilding() && 
                 (r.getResult() != null && r.getResult().isBetterOrEqualTo(threshold))) {
                result.add(r);
            }
            r = r.getPreviousBuild();
        }
        
        return result;
    }
1093044
public ImageVectorizationResult getImageVectorizationResult() throws Exception {
		Future<ImageVectorizationResult> future = pool.poll();
		if (future == null) {
			return null;
		} else {
			try {
				ImageVectorizationResult imvr = future.get();
				return imvr;
			} catch (Exception e) {
				throw e;
			} finally {
				// in any case (Exception or not) the numPendingTask should be reduced
				numPendingTasks--;
			}
		}
	}
141152
def threshold(self, vmin=None, vmax=None, replaceWith=None):
        
        th = vtk.vtkImageThreshold()
        th.SetInputData(self.image)
        
        if vmin is not None and vmax is not None:
            th.ThresholdBetween(vmin, vmax)
        elif vmin is not None:
            th.ThresholdByUpper(vmin)
        elif vmax is not None:
            th.ThresholdByLower(vmax)       

        if replaceWith:
            th.ReplaceOutOn()
            th.SetOutValue(replaceWith)
        th.Update()
        
        self.image = th.GetOutput()
        self.mapper.SetInputData(self.image)
        self.mapper.Modified()
        return self
102021
public float similarity(String what, String with)
    {
        Vector A = query(what);
        if (A == null) return -1f;
        Vector B = query(with);
        if (B == null) return -1f;
        return A.cosineForUnitVector(B);
    }
854878
public static SparseVector fromCollection(Collection<? extends Number> list) {
        return Vector.fromCollection(list).to(Vectors.SPARSE);
    }
289781
def get_thresholds(points=100, power=3) -> list:
    """"""
    return [(i / (points + 1)) ** power for i in range(1, points + 1)]
24694
def get_similar(self, limit=None):
        """"""

        params = self._get_params()
        if limit:
            params["limit"] = limit

        doc = self._request(self.ws_prefix + ".getSimilar", True, params)

        names = _extract_all(doc, "name")
        matches = _extract_all(doc, "match")

        artists = []
        for i in range(0, len(names)):
            artists.append(
                SimilarItem(Artist(names[i], self.network), _number(matches[i]))
            )

        return artists
1362424
def _match_auto(self, screen, search_img, threshold):
        
        # 1. try template first
        ret = ac.find_template(screen, search_img)
        if ret and ret['confidence'] > threshold:
            return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_TMPL, matched=True)

        # 2. try sift
        ret = ac.find_sift(screen, search_img, min_match_count=10)
        if ret is None:
            return None

        matches, total = ret['confidence']
        if 1.0*matches/total > 0.5: # FIXME(ssx): sift just write here
            return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_SIFT, matched=True)
        return None
831581
function (img, downScaleSize, threshold) {
        if (!img || !img.width || !img.height) {
            return false;
        }

        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        var size = downScaleSize || 32;
        threshold = threshold || 20;
        canvas.width = canvas.height = size;
        ctx.drawImage(img, 0, 0, size, size);
        var srcData = ctx.getImageData(0, 0, size, size);
        for (var i = 0; i < srcData.data.length; i += 4) {
            var r = srcData.data[i];
            var g = srcData.data[i + 1];
            var b = srcData.data[i + 2];
            var diff = Math.abs(r - g) + Math.abs(g - b);
            if (diff > threshold) {
                return false;
            }
        }
        return true;
    }
93359
public List<Match> matches(List<String> desired, int threshold) {
    return matchesImpl(parse(desired), threshold);
  }
647920
public Iterable<DConnection> queryByImageUrl(java.lang.String imageUrl) {
    return queryByField(null, DConnectionMapper.Field.IMAGEURL.getFieldName(), imageUrl);
  }
822097
public JsonResultSet getSimilarImages(String imageId, double threshold) {

    	JsonResultSet similar = new JsonResultSet();
        PostMethod queryMethod = null;
        String response = null;
        try {

            Part[] parts = {
                new StringPart("id", imageId),
                new StringPart("threshold", String.valueOf(threshold))
            };

            queryMethod = new PostMethod(webServiceHost + "/rest/visual/query_id/" + collectionName);
            queryMethod.setRequestEntity(new MultipartRequestEntity(parts, queryMethod.getParams()));
            int code = httpClient.executeMethod(queryMethod);
            if (code == 200) {
                InputStream inputStream = queryMethod.getResponseBodyAsStream();
                StringWriter writer = new StringWriter();
                IOUtils.copy(inputStream, writer);
                response = writer.toString();

                queryMethod.releaseConnection();

                similar = parseResponse(response);
            }
            else {
            	_logger.error("Http returned code: " + code);
            }
        } catch (Exception e) {
        	_logger.error("Exception for ID: " + imageId, e);
            response = null;
        } finally {
            if (queryMethod != null) {
                queryMethod.releaseConnection();
            }
        }
        return similar;
    }
98485
function dither(cb) {
  const rgb565Matrix = [1, 9, 3, 11, 13, 5, 15, 7, 4, 12, 2, 10, 16, 8, 14, 6];
  this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(
    x,
    y,
    idx
  ) {
    const thresholdId = ((y & 3) << 2) + (x % 4);
    const dither = rgb565Matrix[thresholdId];
    this.bitmap.data[idx] = Math.min(this.bitmap.data[idx] + dither, 0xff);
    this.bitmap.data[idx + 1] = Math.min(
      this.bitmap.data[idx + 1] + dither,
      0xff
    );
    this.bitmap.data[idx + 2] = Math.min(
      this.bitmap.data[idx + 2] + dither,
      0xff
    );
  });

  if (isNodePattern(cb)) {
    cb.call(this, null, this);
  }

  return this;
}