hexsha
stringlengths 40
40
| size
int64 2
1.01M
| content
stringlengths 2
1.01M
| avg_line_length
float64 1.5
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
0878294a41e13cd39a1dcc1888eab490a8c9150a | 52 | class UsersController < Restafarian::Controller
end
| 17.333333 | 47 | 0.846154 |
4a5b4df412bbf6521a9abe2269dd74ae14e05796 | 423,348 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module VisionV1p2beta1
# Response to a single file annotation request. A file may contain one or more
# images, which individually have their own responses.
class AnnotateFileResponse
include Google::Apis::Core::Hashable
# The `Status` type defines a logical error model that is suitable for different
# programming environments, including REST APIs and RPC APIs. It is used by [
# gRPC](https://github.com/grpc). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `error`
# @return [Google::Apis::VisionV1p2beta1::Status]
attr_accessor :error
# The desired input location and metadata.
# Corresponds to the JSON property `inputConfig`
# @return [Google::Apis::VisionV1p2beta1::InputConfig]
attr_accessor :input_config
# Individual responses to images found within the file. This field will be empty
# if the `error` field is set.
# Corresponds to the JSON property `responses`
# @return [Array<Google::Apis::VisionV1p2beta1::AnnotateImageResponse>]
attr_accessor :responses
# This field gives the total number of pages in the file.
# Corresponds to the JSON property `totalPages`
# @return [Fixnum]
attr_accessor :total_pages
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@error = args[:error] if args.key?(:error)
@input_config = args[:input_config] if args.key?(:input_config)
@responses = args[:responses] if args.key?(:responses)
@total_pages = args[:total_pages] if args.key?(:total_pages)
end
end
# Response to an image annotation request.
class AnnotateImageResponse
include Google::Apis::Core::Hashable
# If an image was produced from a file (e.g. a PDF), this message gives
# information about the source of that image.
# Corresponds to the JSON property `context`
# @return [Google::Apis::VisionV1p2beta1::ImageAnnotationContext]
attr_accessor :context
# Set of crop hints that are used to generate new crops when serving images.
# Corresponds to the JSON property `cropHintsAnnotation`
# @return [Google::Apis::VisionV1p2beta1::CropHintsAnnotation]
attr_accessor :crop_hints_annotation
# The `Status` type defines a logical error model that is suitable for different
# programming environments, including REST APIs and RPC APIs. It is used by [
# gRPC](https://github.com/grpc). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `error`
# @return [Google::Apis::VisionV1p2beta1::Status]
attr_accessor :error
# If present, face detection has completed successfully.
# Corresponds to the JSON property `faceAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::FaceAnnotation>]
attr_accessor :face_annotations
# TextAnnotation contains a structured representation of OCR extracted text. The
# hierarchy of an OCR extracted text structure is like this: TextAnnotation ->
# Page -> Block -> Paragraph -> Word -> Symbol Each structural component,
# starting from Page, may further have their own properties. Properties describe
# detected languages, breaks etc.. Please refer to the TextAnnotation.
# TextProperty message definition below for more detail.
# Corresponds to the JSON property `fullTextAnnotation`
# @return [Google::Apis::VisionV1p2beta1::TextAnnotation]
attr_accessor :full_text_annotation
# Stores image properties, such as dominant colors.
# Corresponds to the JSON property `imagePropertiesAnnotation`
# @return [Google::Apis::VisionV1p2beta1::ImageProperties]
attr_accessor :image_properties_annotation
# If present, label detection has completed successfully.
# Corresponds to the JSON property `labelAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::EntityAnnotation>]
attr_accessor :label_annotations
# If present, landmark detection has completed successfully.
# Corresponds to the JSON property `landmarkAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::EntityAnnotation>]
attr_accessor :landmark_annotations
# If present, localized object detection has completed successfully. This will
# be sorted descending by confidence score.
# Corresponds to the JSON property `localizedObjectAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::LocalizedObjectAnnotation>]
attr_accessor :localized_object_annotations
# If present, logo detection has completed successfully.
# Corresponds to the JSON property `logoAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::EntityAnnotation>]
attr_accessor :logo_annotations
# Results for a product search request.
# Corresponds to the JSON property `productSearchResults`
# @return [Google::Apis::VisionV1p2beta1::ProductSearchResults]
attr_accessor :product_search_results
# Set of features pertaining to the image, computed by computer vision methods
# over safe-search verticals (for example, adult, spoof, medical, violence).
# Corresponds to the JSON property `safeSearchAnnotation`
# @return [Google::Apis::VisionV1p2beta1::SafeSearchAnnotation]
attr_accessor :safe_search_annotation
# If present, text (OCR) detection has completed successfully.
# Corresponds to the JSON property `textAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::EntityAnnotation>]
attr_accessor :text_annotations
# Relevant information for the image from the Internet.
# Corresponds to the JSON property `webDetection`
# @return [Google::Apis::VisionV1p2beta1::WebDetection]
attr_accessor :web_detection
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@context = args[:context] if args.key?(:context)
@crop_hints_annotation = args[:crop_hints_annotation] if args.key?(:crop_hints_annotation)
@error = args[:error] if args.key?(:error)
@face_annotations = args[:face_annotations] if args.key?(:face_annotations)
@full_text_annotation = args[:full_text_annotation] if args.key?(:full_text_annotation)
@image_properties_annotation = args[:image_properties_annotation] if args.key?(:image_properties_annotation)
@label_annotations = args[:label_annotations] if args.key?(:label_annotations)
@landmark_annotations = args[:landmark_annotations] if args.key?(:landmark_annotations)
@localized_object_annotations = args[:localized_object_annotations] if args.key?(:localized_object_annotations)
@logo_annotations = args[:logo_annotations] if args.key?(:logo_annotations)
@product_search_results = args[:product_search_results] if args.key?(:product_search_results)
@safe_search_annotation = args[:safe_search_annotation] if args.key?(:safe_search_annotation)
@text_annotations = args[:text_annotations] if args.key?(:text_annotations)
@web_detection = args[:web_detection] if args.key?(:web_detection)
end
end
# The response for a single offline file annotation request.
class AsyncAnnotateFileResponse
include Google::Apis::Core::Hashable
# The desired output location and metadata.
# Corresponds to the JSON property `outputConfig`
# @return [Google::Apis::VisionV1p2beta1::OutputConfig]
attr_accessor :output_config
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@output_config = args[:output_config] if args.key?(:output_config)
end
end
# Response to an async batch file annotation request.
class AsyncBatchAnnotateFilesResponse
include Google::Apis::Core::Hashable
# The list of file annotation responses, one for each request in
# AsyncBatchAnnotateFilesRequest.
# Corresponds to the JSON property `responses`
# @return [Array<Google::Apis::VisionV1p2beta1::AsyncAnnotateFileResponse>]
attr_accessor :responses
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@responses = args[:responses] if args.key?(:responses)
end
end
# Response to an async batch image annotation request.
class AsyncBatchAnnotateImagesResponse
include Google::Apis::Core::Hashable
# The desired output location and metadata.
# Corresponds to the JSON property `outputConfig`
# @return [Google::Apis::VisionV1p2beta1::OutputConfig]
attr_accessor :output_config
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@output_config = args[:output_config] if args.key?(:output_config)
end
end
# A list of file annotation responses.
class BatchAnnotateFilesResponse
include Google::Apis::Core::Hashable
# The list of file annotation responses, each response corresponding to each
# AnnotateFileRequest in BatchAnnotateFilesRequest.
# Corresponds to the JSON property `responses`
# @return [Array<Google::Apis::VisionV1p2beta1::AnnotateFileResponse>]
attr_accessor :responses
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@responses = args[:responses] if args.key?(:responses)
end
end
# Metadata for the batch operations such as the current state. This is included
# in the `metadata` field of the `Operation` returned by the `GetOperation` call
# of the `google::longrunning::Operations` service.
class BatchOperationMetadata
include Google::Apis::Core::Hashable
# The time when the batch request is finished and google.longrunning.Operation.
# done is set to true.
# Corresponds to the JSON property `endTime`
# @return [String]
attr_accessor :end_time
# The current state of the batch operation.
# Corresponds to the JSON property `state`
# @return [String]
attr_accessor :state
# The time when the batch request was submitted to the server.
# Corresponds to the JSON property `submitTime`
# @return [String]
attr_accessor :submit_time
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@end_time = args[:end_time] if args.key?(:end_time)
@state = args[:state] if args.key?(:state)
@submit_time = args[:submit_time] if args.key?(:submit_time)
end
end
# Logical element on the page.
class Block
include Google::Apis::Core::Hashable
# Detected block type (text, image etc) for this block.
# Corresponds to the JSON property `blockType`
# @return [String]
attr_accessor :block_type
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results on the block. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# List of paragraphs in this block (if this blocks is of type text).
# Corresponds to the JSON property `paragraphs`
# @return [Array<Google::Apis::VisionV1p2beta1::Paragraph>]
attr_accessor :paragraphs
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::TextProperty]
attr_accessor :property
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@block_type = args[:block_type] if args.key?(:block_type)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@paragraphs = args[:paragraphs] if args.key?(:paragraphs)
@property = args[:property] if args.key?(:property)
end
end
# A bounding polygon for the detected image annotation.
class BoundingPoly
include Google::Apis::Core::Hashable
# The bounding polygon normalized vertices.
# Corresponds to the JSON property `normalizedVertices`
# @return [Array<Google::Apis::VisionV1p2beta1::NormalizedVertex>]
attr_accessor :normalized_vertices
# The bounding polygon vertices.
# Corresponds to the JSON property `vertices`
# @return [Array<Google::Apis::VisionV1p2beta1::Vertex>]
attr_accessor :vertices
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@normalized_vertices = args[:normalized_vertices] if args.key?(:normalized_vertices)
@vertices = args[:vertices] if args.key?(:vertices)
end
end
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation can
# be trivially provided to the constructor of "java.awt.Color" in Java; it can
# also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into a
# CSS "rgba()" string in JavaScript, as well. Note: this proto does not carry
# information about the absolute color space that should be used to interpret
# the RGB value (e.g. sRGB, Adobe RGB, DCI-P3, BT.2020, etc.). By default,
# applications SHOULD assume the sRGB color space. Note: when color equality
# needs to be decided, implementations, unless documented otherwise, will treat
# two colors to be equal if all their red, green, blue and alpha values each
# differ by at most 1e-5. Example (Java): import com.google.type.Color; // ...
# public static java.awt.Color fromProto(Color protocolor) ` float alpha =
# protocolor.hasAlpha() ? protocolor.getAlpha().getValue() : 1.0; return new
# java.awt.Color( protocolor.getRed(), protocolor.getGreen(), protocolor.getBlue(
# ), alpha); ` public static Color toProto(java.awt.Color color) ` float red = (
# float) color.getRed(); float green = (float) color.getGreen(); float blue = (
# float) color.getBlue(); float denominator = 255.0; Color.Builder resultBuilder
# = Color .newBuilder() .setRed(red / denominator) .setGreen(green / denominator)
# .setBlue(blue / denominator); int alpha = color.getAlpha(); if (alpha != 255)
# ` result.setAlpha( FloatValue .newBuilder() .setValue(((float) alpha) /
# denominator) .build()); ` return resultBuilder.build(); ` // ... Example (iOS /
# Obj-C): // ... static UIColor* fromProto(Color* protocolor) ` float red = [
# protocolor red]; float green = [protocolor green]; float blue = [protocolor
# blue]; FloatValue* alpha_wrapper = [protocolor alpha]; float alpha = 1.0; if (
# alpha_wrapper != nil) ` alpha = [alpha_wrapper value]; ` return [UIColor
# colorWithRed:red green:green blue:blue alpha:alpha]; ` static Color* toProto(
# UIColor* color) ` CGFloat red, green, blue, alpha; if (![color getRed:&red
# green:&green blue:&blue alpha:&alpha]) ` return nil; ` Color* result = [[Color
# alloc] init]; [result setRed:red]; [result setGreen:green]; [result setBlue:
# blue]; if (alpha <= 0.9999) ` [result setAlpha:floatWrapperWithValue(alpha)]; `
# [result autorelease]; return result; ` // ... Example (JavaScript): // ...
# var protoToCssColor = function(rgb_color) ` var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0; var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255); var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255); if (!('alpha' in rgb_color)) ` return
# rgbToCssColor_(red, green, blue); ` var alphaFrac = rgb_color.alpha.value || 0.
# 0; var rgbParams = [red, green, blue].join(','); return ['rgba(', rgbParams, ',
# ', alphaFrac, ')'].join(''); `; var rgbToCssColor_ = function(red, green, blue)
# ` var rgbNumber = new Number((red << 16) | (green << 8) | blue); var
# hexString = rgbNumber.toString(16); var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#']; for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0'); ` resultBuilder.push(hexString); return resultBuilder.
# join(''); `; // ...
class Color
include Google::Apis::Core::Hashable
# The fraction of this color that should be applied to the pixel. That is, the
# final pixel color is defined by the equation: pixel color = alpha * (this
# color) + (1.0 - alpha) * (background color) This means that a value of 1.0
# corresponds to a solid color, whereas a value of 0.0 corresponds to a
# completely transparent color. This uses a wrapper message rather than a simple
# float scalar so that it is possible to distinguish between a default value and
# the value being unset. If omitted, this color object is to be rendered as a
# solid color (as if the alpha value had been explicitly given with a value of 1.
# 0).
# Corresponds to the JSON property `alpha`
# @return [Float]
attr_accessor :alpha
# The amount of blue in the color as a value in the interval [0, 1].
# Corresponds to the JSON property `blue`
# @return [Float]
attr_accessor :blue
# The amount of green in the color as a value in the interval [0, 1].
# Corresponds to the JSON property `green`
# @return [Float]
attr_accessor :green
# The amount of red in the color as a value in the interval [0, 1].
# Corresponds to the JSON property `red`
# @return [Float]
attr_accessor :red
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@alpha = args[:alpha] if args.key?(:alpha)
@blue = args[:blue] if args.key?(:blue)
@green = args[:green] if args.key?(:green)
@red = args[:red] if args.key?(:red)
end
end
# Color information consists of RGB channels, score, and the fraction of the
# image that the color occupies in the image.
class ColorInfo
include Google::Apis::Core::Hashable
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation can
# be trivially provided to the constructor of "java.awt.Color" in Java; it can
# also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into a
# CSS "rgba()" string in JavaScript, as well. Note: this proto does not carry
# information about the absolute color space that should be used to interpret
# the RGB value (e.g. sRGB, Adobe RGB, DCI-P3, BT.2020, etc.). By default,
# applications SHOULD assume the sRGB color space. Note: when color equality
# needs to be decided, implementations, unless documented otherwise, will treat
# two colors to be equal if all their red, green, blue and alpha values each
# differ by at most 1e-5. Example (Java): import com.google.type.Color; // ...
# public static java.awt.Color fromProto(Color protocolor) ` float alpha =
# protocolor.hasAlpha() ? protocolor.getAlpha().getValue() : 1.0; return new
# java.awt.Color( protocolor.getRed(), protocolor.getGreen(), protocolor.getBlue(
# ), alpha); ` public static Color toProto(java.awt.Color color) ` float red = (
# float) color.getRed(); float green = (float) color.getGreen(); float blue = (
# float) color.getBlue(); float denominator = 255.0; Color.Builder resultBuilder
# = Color .newBuilder() .setRed(red / denominator) .setGreen(green / denominator)
# .setBlue(blue / denominator); int alpha = color.getAlpha(); if (alpha != 255)
# ` result.setAlpha( FloatValue .newBuilder() .setValue(((float) alpha) /
# denominator) .build()); ` return resultBuilder.build(); ` // ... Example (iOS /
# Obj-C): // ... static UIColor* fromProto(Color* protocolor) ` float red = [
# protocolor red]; float green = [protocolor green]; float blue = [protocolor
# blue]; FloatValue* alpha_wrapper = [protocolor alpha]; float alpha = 1.0; if (
# alpha_wrapper != nil) ` alpha = [alpha_wrapper value]; ` return [UIColor
# colorWithRed:red green:green blue:blue alpha:alpha]; ` static Color* toProto(
# UIColor* color) ` CGFloat red, green, blue, alpha; if (![color getRed:&red
# green:&green blue:&blue alpha:&alpha]) ` return nil; ` Color* result = [[Color
# alloc] init]; [result setRed:red]; [result setGreen:green]; [result setBlue:
# blue]; if (alpha <= 0.9999) ` [result setAlpha:floatWrapperWithValue(alpha)]; `
# [result autorelease]; return result; ` // ... Example (JavaScript): // ...
# var protoToCssColor = function(rgb_color) ` var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0; var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255); var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255); if (!('alpha' in rgb_color)) ` return
# rgbToCssColor_(red, green, blue); ` var alphaFrac = rgb_color.alpha.value || 0.
# 0; var rgbParams = [red, green, blue].join(','); return ['rgba(', rgbParams, ',
# ', alphaFrac, ')'].join(''); `; var rgbToCssColor_ = function(red, green, blue)
# ` var rgbNumber = new Number((red << 16) | (green << 8) | blue); var
# hexString = rgbNumber.toString(16); var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#']; for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0'); ` resultBuilder.push(hexString); return resultBuilder.
# join(''); `; // ...
# Corresponds to the JSON property `color`
# @return [Google::Apis::VisionV1p2beta1::Color]
attr_accessor :color
# The fraction of pixels the color occupies in the image. Value in range [0, 1].
# Corresponds to the JSON property `pixelFraction`
# @return [Float]
attr_accessor :pixel_fraction
# Image-specific score for this color. Value in range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@color = args[:color] if args.key?(:color)
@pixel_fraction = args[:pixel_fraction] if args.key?(:pixel_fraction)
@score = args[:score] if args.key?(:score)
end
end
# Single crop hint that is used to generate a new crop when serving an image.
class CropHint
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::BoundingPoly]
attr_accessor :bounding_poly
# Confidence of this being a salient region. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Fraction of importance of this salient region with respect to the original
# image.
# Corresponds to the JSON property `importanceFraction`
# @return [Float]
attr_accessor :importance_fraction
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@confidence = args[:confidence] if args.key?(:confidence)
@importance_fraction = args[:importance_fraction] if args.key?(:importance_fraction)
end
end
# Set of crop hints that are used to generate new crops when serving images.
class CropHintsAnnotation
include Google::Apis::Core::Hashable
# Crop hint results.
# Corresponds to the JSON property `cropHints`
# @return [Array<Google::Apis::VisionV1p2beta1::CropHint>]
attr_accessor :crop_hints
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@crop_hints = args[:crop_hints] if args.key?(:crop_hints)
end
end
# Detected start or end of a structural component.
class DetectedBreak
include Google::Apis::Core::Hashable
# True if break prepends the element.
# Corresponds to the JSON property `isPrefix`
# @return [Boolean]
attr_accessor :is_prefix
alias_method :is_prefix?, :is_prefix
# Detected break type.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@is_prefix = args[:is_prefix] if args.key?(:is_prefix)
@type = args[:type] if args.key?(:type)
end
end
# Detected language for a structural component.
class DetectedLanguage
include Google::Apis::Core::Hashable
# Confidence of detected language. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more information,
# see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@confidence = args[:confidence] if args.key?(:confidence)
@language_code = args[:language_code] if args.key?(:language_code)
end
end
# Set of dominant colors and their corresponding scores.
class DominantColorsAnnotation
include Google::Apis::Core::Hashable
# RGB color values with their score and pixel fraction.
# Corresponds to the JSON property `colors`
# @return [Array<Google::Apis::VisionV1p2beta1::ColorInfo>]
attr_accessor :colors
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@colors = args[:colors] if args.key?(:colors)
end
end
# Set of detected entity features.
class EntityAnnotation
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::BoundingPoly]
attr_accessor :bounding_poly
# **Deprecated. Use `score` instead.** The accuracy of the entity detection in
# an image. For example, for an image in which the "Eiffel Tower" entity is
# detected, this field represents the confidence that there is a tower in the
# query image. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Entity textual description, expressed in its `locale` language.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The language code for the locale in which the entity textual `description` is
# expressed.
# Corresponds to the JSON property `locale`
# @return [String]
attr_accessor :locale
# The location information for the detected entity. Multiple `LocationInfo`
# elements can be present because one location may indicate the location of the
# scene in the image, and another location may indicate the location of the
# place where the image was taken. Location information is usually present for
# landmarks.
# Corresponds to the JSON property `locations`
# @return [Array<Google::Apis::VisionV1p2beta1::LocationInfo>]
attr_accessor :locations
# Opaque entity ID. Some IDs may be available in [Google Knowledge Graph Search
# API](https://developers.google.com/knowledge-graph/).
# Corresponds to the JSON property `mid`
# @return [String]
attr_accessor :mid
# Some entities may have optional user-supplied `Property` (name/value) fields,
# such a score or string that qualifies the entity.
# Corresponds to the JSON property `properties`
# @return [Array<Google::Apis::VisionV1p2beta1::Property>]
attr_accessor :properties
# Overall score of the result. Range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
# The relevancy of the ICA (Image Content Annotation) label to the image. For
# example, the relevancy of "tower" is likely higher to an image containing the
# detected "Eiffel Tower" than to an image containing a detected distant
# towering building, even though the confidence that there is a tower in each
# image may be the same. Range [0, 1].
# Corresponds to the JSON property `topicality`
# @return [Float]
attr_accessor :topicality
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@confidence = args[:confidence] if args.key?(:confidence)
@description = args[:description] if args.key?(:description)
@locale = args[:locale] if args.key?(:locale)
@locations = args[:locations] if args.key?(:locations)
@mid = args[:mid] if args.key?(:mid)
@properties = args[:properties] if args.key?(:properties)
@score = args[:score] if args.key?(:score)
@topicality = args[:topicality] if args.key?(:topicality)
end
end
# A face annotation object contains the results of face detection.
class FaceAnnotation
include Google::Apis::Core::Hashable
# Anger likelihood.
# Corresponds to the JSON property `angerLikelihood`
# @return [String]
attr_accessor :anger_likelihood
# Blurred likelihood.
# Corresponds to the JSON property `blurredLikelihood`
# @return [String]
attr_accessor :blurred_likelihood
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::BoundingPoly]
attr_accessor :bounding_poly
# Detection confidence. Range [0, 1].
# Corresponds to the JSON property `detectionConfidence`
# @return [Float]
attr_accessor :detection_confidence
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `fdBoundingPoly`
# @return [Google::Apis::VisionV1p2beta1::BoundingPoly]
attr_accessor :fd_bounding_poly
# Headwear likelihood.
# Corresponds to the JSON property `headwearLikelihood`
# @return [String]
attr_accessor :headwear_likelihood
# Joy likelihood.
# Corresponds to the JSON property `joyLikelihood`
# @return [String]
attr_accessor :joy_likelihood
# Face landmarking confidence. Range [0, 1].
# Corresponds to the JSON property `landmarkingConfidence`
# @return [Float]
attr_accessor :landmarking_confidence
# Detected face landmarks.
# Corresponds to the JSON property `landmarks`
# @return [Array<Google::Apis::VisionV1p2beta1::Landmark>]
attr_accessor :landmarks
# Yaw angle, which indicates the leftward/rightward angle that the face is
# pointing relative to the vertical plane perpendicular to the image. Range [-
# 180,180].
# Corresponds to the JSON property `panAngle`
# @return [Float]
attr_accessor :pan_angle
# Roll angle, which indicates the amount of clockwise/anti-clockwise rotation of
# the face relative to the image vertical about the axis perpendicular to the
# face. Range [-180,180].
# Corresponds to the JSON property `rollAngle`
# @return [Float]
attr_accessor :roll_angle
# Sorrow likelihood.
# Corresponds to the JSON property `sorrowLikelihood`
# @return [String]
attr_accessor :sorrow_likelihood
# Surprise likelihood.
# Corresponds to the JSON property `surpriseLikelihood`
# @return [String]
attr_accessor :surprise_likelihood
# Pitch angle, which indicates the upwards/downwards angle that the face is
# pointing relative to the image's horizontal plane. Range [-180,180].
# Corresponds to the JSON property `tiltAngle`
# @return [Float]
attr_accessor :tilt_angle
# Under-exposed likelihood.
# Corresponds to the JSON property `underExposedLikelihood`
# @return [String]
attr_accessor :under_exposed_likelihood
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@anger_likelihood = args[:anger_likelihood] if args.key?(:anger_likelihood)
@blurred_likelihood = args[:blurred_likelihood] if args.key?(:blurred_likelihood)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@detection_confidence = args[:detection_confidence] if args.key?(:detection_confidence)
@fd_bounding_poly = args[:fd_bounding_poly] if args.key?(:fd_bounding_poly)
@headwear_likelihood = args[:headwear_likelihood] if args.key?(:headwear_likelihood)
@joy_likelihood = args[:joy_likelihood] if args.key?(:joy_likelihood)
@landmarking_confidence = args[:landmarking_confidence] if args.key?(:landmarking_confidence)
@landmarks = args[:landmarks] if args.key?(:landmarks)
@pan_angle = args[:pan_angle] if args.key?(:pan_angle)
@roll_angle = args[:roll_angle] if args.key?(:roll_angle)
@sorrow_likelihood = args[:sorrow_likelihood] if args.key?(:sorrow_likelihood)
@surprise_likelihood = args[:surprise_likelihood] if args.key?(:surprise_likelihood)
@tilt_angle = args[:tilt_angle] if args.key?(:tilt_angle)
@under_exposed_likelihood = args[:under_exposed_likelihood] if args.key?(:under_exposed_likelihood)
end
end
# The Google Cloud Storage location where the output will be written to.
class GcsDestination
include Google::Apis::Core::Hashable
# Google Cloud Storage URI prefix where the results will be stored. Results will
# be in JSON format and preceded by its corresponding input URI prefix. This
# field can either represent a gcs file prefix or gcs directory. In either case,
# the uri should be unique because in order to get all of the output files, you
# will need to do a wildcard gcs search on the uri prefix you provide. Examples:
# * File Prefix: gs://bucket-name/here/filenameprefix The output files will be
# created in gs://bucket-name/here/ and the names of the output files will begin
# with "filenameprefix". * Directory Prefix: gs://bucket-name/some/location/ The
# output files will be created in gs://bucket-name/some/location/ and the names
# of the output files could be anything because there was no filename prefix
# specified. If multiple outputs, each response is still AnnotateFileResponse,
# each of which contains some subset of the full list of AnnotateImageResponse.
# Multiple outputs can happen if, for example, the output JSON is too large and
# overflows into multiple sharded files.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@uri = args[:uri] if args.key?(:uri)
end
end
# The Google Cloud Storage location where the input will be read from.
class GcsSource
include Google::Apis::Core::Hashable
# Google Cloud Storage URI for the input file. This must only be a Google Cloud
# Storage object. Wildcards are not currently supported.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@uri = args[:uri] if args.key?(:uri)
end
end
# Response to a single file annotation request. A file may contain one or more
# images, which individually have their own responses.
class GoogleCloudVisionV1p1beta1AnnotateFileResponse
include Google::Apis::Core::Hashable
# The `Status` type defines a logical error model that is suitable for different
# programming environments, including REST APIs and RPC APIs. It is used by [
# gRPC](https://github.com/grpc). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `error`
# @return [Google::Apis::VisionV1p2beta1::Status]
attr_accessor :error
# The desired input location and metadata.
# Corresponds to the JSON property `inputConfig`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1InputConfig]
attr_accessor :input_config
# Individual responses to images found within the file. This field will be empty
# if the `error` field is set.
# Corresponds to the JSON property `responses`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1AnnotateImageResponse>]
attr_accessor :responses
# This field gives the total number of pages in the file.
# Corresponds to the JSON property `totalPages`
# @return [Fixnum]
attr_accessor :total_pages
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@error = args[:error] if args.key?(:error)
@input_config = args[:input_config] if args.key?(:input_config)
@responses = args[:responses] if args.key?(:responses)
@total_pages = args[:total_pages] if args.key?(:total_pages)
end
end
# Response to an image annotation request.
class GoogleCloudVisionV1p1beta1AnnotateImageResponse
include Google::Apis::Core::Hashable
# If an image was produced from a file (e.g. a PDF), this message gives
# information about the source of that image.
# Corresponds to the JSON property `context`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1ImageAnnotationContext]
attr_accessor :context
# Set of crop hints that are used to generate new crops when serving images.
# Corresponds to the JSON property `cropHintsAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1CropHintsAnnotation]
attr_accessor :crop_hints_annotation
# The `Status` type defines a logical error model that is suitable for different
# programming environments, including REST APIs and RPC APIs. It is used by [
# gRPC](https://github.com/grpc). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `error`
# @return [Google::Apis::VisionV1p2beta1::Status]
attr_accessor :error
# If present, face detection has completed successfully.
# Corresponds to the JSON property `faceAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1FaceAnnotation>]
attr_accessor :face_annotations
# TextAnnotation contains a structured representation of OCR extracted text. The
# hierarchy of an OCR extracted text structure is like this: TextAnnotation ->
# Page -> Block -> Paragraph -> Word -> Symbol Each structural component,
# starting from Page, may further have their own properties. Properties describe
# detected languages, breaks etc.. Please refer to the TextAnnotation.
# TextProperty message definition below for more detail.
# Corresponds to the JSON property `fullTextAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1TextAnnotation]
attr_accessor :full_text_annotation
# Stores image properties, such as dominant colors.
# Corresponds to the JSON property `imagePropertiesAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1ImageProperties]
attr_accessor :image_properties_annotation
# If present, label detection has completed successfully.
# Corresponds to the JSON property `labelAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1EntityAnnotation>]
attr_accessor :label_annotations
# If present, landmark detection has completed successfully.
# Corresponds to the JSON property `landmarkAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1EntityAnnotation>]
attr_accessor :landmark_annotations
# If present, localized object detection has completed successfully. This will
# be sorted descending by confidence score.
# Corresponds to the JSON property `localizedObjectAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1LocalizedObjectAnnotation>]
attr_accessor :localized_object_annotations
# If present, logo detection has completed successfully.
# Corresponds to the JSON property `logoAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1EntityAnnotation>]
attr_accessor :logo_annotations
# Results for a product search request.
# Corresponds to the JSON property `productSearchResults`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1ProductSearchResults]
attr_accessor :product_search_results
# Set of features pertaining to the image, computed by computer vision methods
# over safe-search verticals (for example, adult, spoof, medical, violence).
# Corresponds to the JSON property `safeSearchAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1SafeSearchAnnotation]
attr_accessor :safe_search_annotation
# If present, text (OCR) detection has completed successfully.
# Corresponds to the JSON property `textAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1EntityAnnotation>]
attr_accessor :text_annotations
# Relevant information for the image from the Internet.
# Corresponds to the JSON property `webDetection`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1WebDetection]
attr_accessor :web_detection
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@context = args[:context] if args.key?(:context)
@crop_hints_annotation = args[:crop_hints_annotation] if args.key?(:crop_hints_annotation)
@error = args[:error] if args.key?(:error)
@face_annotations = args[:face_annotations] if args.key?(:face_annotations)
@full_text_annotation = args[:full_text_annotation] if args.key?(:full_text_annotation)
@image_properties_annotation = args[:image_properties_annotation] if args.key?(:image_properties_annotation)
@label_annotations = args[:label_annotations] if args.key?(:label_annotations)
@landmark_annotations = args[:landmark_annotations] if args.key?(:landmark_annotations)
@localized_object_annotations = args[:localized_object_annotations] if args.key?(:localized_object_annotations)
@logo_annotations = args[:logo_annotations] if args.key?(:logo_annotations)
@product_search_results = args[:product_search_results] if args.key?(:product_search_results)
@safe_search_annotation = args[:safe_search_annotation] if args.key?(:safe_search_annotation)
@text_annotations = args[:text_annotations] if args.key?(:text_annotations)
@web_detection = args[:web_detection] if args.key?(:web_detection)
end
end
# The response for a single offline file annotation request.
class GoogleCloudVisionV1p1beta1AsyncAnnotateFileResponse
include Google::Apis::Core::Hashable
# The desired output location and metadata.
# Corresponds to the JSON property `outputConfig`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1OutputConfig]
attr_accessor :output_config
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@output_config = args[:output_config] if args.key?(:output_config)
end
end
# Response to an async batch file annotation request.
class GoogleCloudVisionV1p1beta1AsyncBatchAnnotateFilesResponse
include Google::Apis::Core::Hashable
# The list of file annotation responses, one for each request in
# AsyncBatchAnnotateFilesRequest.
# Corresponds to the JSON property `responses`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1AsyncAnnotateFileResponse>]
attr_accessor :responses
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@responses = args[:responses] if args.key?(:responses)
end
end
# Logical element on the page.
class GoogleCloudVisionV1p1beta1Block
include Google::Apis::Core::Hashable
# Detected block type (text, image etc) for this block.
# Corresponds to the JSON property `blockType`
# @return [String]
attr_accessor :block_type
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results on the block. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# List of paragraphs in this block (if this blocks is of type text).
# Corresponds to the JSON property `paragraphs`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1Paragraph>]
attr_accessor :paragraphs
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1TextAnnotationTextProperty]
attr_accessor :property
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@block_type = args[:block_type] if args.key?(:block_type)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@paragraphs = args[:paragraphs] if args.key?(:paragraphs)
@property = args[:property] if args.key?(:property)
end
end
# A bounding polygon for the detected image annotation.
class GoogleCloudVisionV1p1beta1BoundingPoly
include Google::Apis::Core::Hashable
# The bounding polygon normalized vertices.
# Corresponds to the JSON property `normalizedVertices`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1NormalizedVertex>]
attr_accessor :normalized_vertices
# The bounding polygon vertices.
# Corresponds to the JSON property `vertices`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1Vertex>]
attr_accessor :vertices
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@normalized_vertices = args[:normalized_vertices] if args.key?(:normalized_vertices)
@vertices = args[:vertices] if args.key?(:vertices)
end
end
# Color information consists of RGB channels, score, and the fraction of the
# image that the color occupies in the image.
class GoogleCloudVisionV1p1beta1ColorInfo
include Google::Apis::Core::Hashable
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation can
# be trivially provided to the constructor of "java.awt.Color" in Java; it can
# also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into a
# CSS "rgba()" string in JavaScript, as well. Note: this proto does not carry
# information about the absolute color space that should be used to interpret
# the RGB value (e.g. sRGB, Adobe RGB, DCI-P3, BT.2020, etc.). By default,
# applications SHOULD assume the sRGB color space. Note: when color equality
# needs to be decided, implementations, unless documented otherwise, will treat
# two colors to be equal if all their red, green, blue and alpha values each
# differ by at most 1e-5. Example (Java): import com.google.type.Color; // ...
# public static java.awt.Color fromProto(Color protocolor) ` float alpha =
# protocolor.hasAlpha() ? protocolor.getAlpha().getValue() : 1.0; return new
# java.awt.Color( protocolor.getRed(), protocolor.getGreen(), protocolor.getBlue(
# ), alpha); ` public static Color toProto(java.awt.Color color) ` float red = (
# float) color.getRed(); float green = (float) color.getGreen(); float blue = (
# float) color.getBlue(); float denominator = 255.0; Color.Builder resultBuilder
# = Color .newBuilder() .setRed(red / denominator) .setGreen(green / denominator)
# .setBlue(blue / denominator); int alpha = color.getAlpha(); if (alpha != 255)
# ` result.setAlpha( FloatValue .newBuilder() .setValue(((float) alpha) /
# denominator) .build()); ` return resultBuilder.build(); ` // ... Example (iOS /
# Obj-C): // ... static UIColor* fromProto(Color* protocolor) ` float red = [
# protocolor red]; float green = [protocolor green]; float blue = [protocolor
# blue]; FloatValue* alpha_wrapper = [protocolor alpha]; float alpha = 1.0; if (
# alpha_wrapper != nil) ` alpha = [alpha_wrapper value]; ` return [UIColor
# colorWithRed:red green:green blue:blue alpha:alpha]; ` static Color* toProto(
# UIColor* color) ` CGFloat red, green, blue, alpha; if (![color getRed:&red
# green:&green blue:&blue alpha:&alpha]) ` return nil; ` Color* result = [[Color
# alloc] init]; [result setRed:red]; [result setGreen:green]; [result setBlue:
# blue]; if (alpha <= 0.9999) ` [result setAlpha:floatWrapperWithValue(alpha)]; `
# [result autorelease]; return result; ` // ... Example (JavaScript): // ...
# var protoToCssColor = function(rgb_color) ` var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0; var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255); var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255); if (!('alpha' in rgb_color)) ` return
# rgbToCssColor_(red, green, blue); ` var alphaFrac = rgb_color.alpha.value || 0.
# 0; var rgbParams = [red, green, blue].join(','); return ['rgba(', rgbParams, ',
# ', alphaFrac, ')'].join(''); `; var rgbToCssColor_ = function(red, green, blue)
# ` var rgbNumber = new Number((red << 16) | (green << 8) | blue); var
# hexString = rgbNumber.toString(16); var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#']; for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0'); ` resultBuilder.push(hexString); return resultBuilder.
# join(''); `; // ...
# Corresponds to the JSON property `color`
# @return [Google::Apis::VisionV1p2beta1::Color]
attr_accessor :color
# The fraction of pixels the color occupies in the image. Value in range [0, 1].
# Corresponds to the JSON property `pixelFraction`
# @return [Float]
attr_accessor :pixel_fraction
# Image-specific score for this color. Value in range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@color = args[:color] if args.key?(:color)
@pixel_fraction = args[:pixel_fraction] if args.key?(:pixel_fraction)
@score = args[:score] if args.key?(:score)
end
end
# Single crop hint that is used to generate a new crop when serving an image.
class GoogleCloudVisionV1p1beta1CropHint
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1BoundingPoly]
attr_accessor :bounding_poly
# Confidence of this being a salient region. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Fraction of importance of this salient region with respect to the original
# image.
# Corresponds to the JSON property `importanceFraction`
# @return [Float]
attr_accessor :importance_fraction
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@confidence = args[:confidence] if args.key?(:confidence)
@importance_fraction = args[:importance_fraction] if args.key?(:importance_fraction)
end
end
# Set of crop hints that are used to generate new crops when serving images.
class GoogleCloudVisionV1p1beta1CropHintsAnnotation
include Google::Apis::Core::Hashable
# Crop hint results.
# Corresponds to the JSON property `cropHints`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1CropHint>]
attr_accessor :crop_hints
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@crop_hints = args[:crop_hints] if args.key?(:crop_hints)
end
end
# Set of dominant colors and their corresponding scores.
class GoogleCloudVisionV1p1beta1DominantColorsAnnotation
include Google::Apis::Core::Hashable
# RGB color values with their score and pixel fraction.
# Corresponds to the JSON property `colors`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1ColorInfo>]
attr_accessor :colors
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@colors = args[:colors] if args.key?(:colors)
end
end
# Set of detected entity features.
class GoogleCloudVisionV1p1beta1EntityAnnotation
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1BoundingPoly]
attr_accessor :bounding_poly
# **Deprecated. Use `score` instead.** The accuracy of the entity detection in
# an image. For example, for an image in which the "Eiffel Tower" entity is
# detected, this field represents the confidence that there is a tower in the
# query image. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Entity textual description, expressed in its `locale` language.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The language code for the locale in which the entity textual `description` is
# expressed.
# Corresponds to the JSON property `locale`
# @return [String]
attr_accessor :locale
# The location information for the detected entity. Multiple `LocationInfo`
# elements can be present because one location may indicate the location of the
# scene in the image, and another location may indicate the location of the
# place where the image was taken. Location information is usually present for
# landmarks.
# Corresponds to the JSON property `locations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1LocationInfo>]
attr_accessor :locations
# Opaque entity ID. Some IDs may be available in [Google Knowledge Graph Search
# API](https://developers.google.com/knowledge-graph/).
# Corresponds to the JSON property `mid`
# @return [String]
attr_accessor :mid
# Some entities may have optional user-supplied `Property` (name/value) fields,
# such a score or string that qualifies the entity.
# Corresponds to the JSON property `properties`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1Property>]
attr_accessor :properties
# Overall score of the result. Range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
# The relevancy of the ICA (Image Content Annotation) label to the image. For
# example, the relevancy of "tower" is likely higher to an image containing the
# detected "Eiffel Tower" than to an image containing a detected distant
# towering building, even though the confidence that there is a tower in each
# image may be the same. Range [0, 1].
# Corresponds to the JSON property `topicality`
# @return [Float]
attr_accessor :topicality
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@confidence = args[:confidence] if args.key?(:confidence)
@description = args[:description] if args.key?(:description)
@locale = args[:locale] if args.key?(:locale)
@locations = args[:locations] if args.key?(:locations)
@mid = args[:mid] if args.key?(:mid)
@properties = args[:properties] if args.key?(:properties)
@score = args[:score] if args.key?(:score)
@topicality = args[:topicality] if args.key?(:topicality)
end
end
# A face annotation object contains the results of face detection.
class GoogleCloudVisionV1p1beta1FaceAnnotation
include Google::Apis::Core::Hashable
# Anger likelihood.
# Corresponds to the JSON property `angerLikelihood`
# @return [String]
attr_accessor :anger_likelihood
# Blurred likelihood.
# Corresponds to the JSON property `blurredLikelihood`
# @return [String]
attr_accessor :blurred_likelihood
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1BoundingPoly]
attr_accessor :bounding_poly
# Detection confidence. Range [0, 1].
# Corresponds to the JSON property `detectionConfidence`
# @return [Float]
attr_accessor :detection_confidence
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `fdBoundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1BoundingPoly]
attr_accessor :fd_bounding_poly
# Headwear likelihood.
# Corresponds to the JSON property `headwearLikelihood`
# @return [String]
attr_accessor :headwear_likelihood
# Joy likelihood.
# Corresponds to the JSON property `joyLikelihood`
# @return [String]
attr_accessor :joy_likelihood
# Face landmarking confidence. Range [0, 1].
# Corresponds to the JSON property `landmarkingConfidence`
# @return [Float]
attr_accessor :landmarking_confidence
# Detected face landmarks.
# Corresponds to the JSON property `landmarks`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1FaceAnnotationLandmark>]
attr_accessor :landmarks
# Yaw angle, which indicates the leftward/rightward angle that the face is
# pointing relative to the vertical plane perpendicular to the image. Range [-
# 180,180].
# Corresponds to the JSON property `panAngle`
# @return [Float]
attr_accessor :pan_angle
# Roll angle, which indicates the amount of clockwise/anti-clockwise rotation of
# the face relative to the image vertical about the axis perpendicular to the
# face. Range [-180,180].
# Corresponds to the JSON property `rollAngle`
# @return [Float]
attr_accessor :roll_angle
# Sorrow likelihood.
# Corresponds to the JSON property `sorrowLikelihood`
# @return [String]
attr_accessor :sorrow_likelihood
# Surprise likelihood.
# Corresponds to the JSON property `surpriseLikelihood`
# @return [String]
attr_accessor :surprise_likelihood
# Pitch angle, which indicates the upwards/downwards angle that the face is
# pointing relative to the image's horizontal plane. Range [-180,180].
# Corresponds to the JSON property `tiltAngle`
# @return [Float]
attr_accessor :tilt_angle
# Under-exposed likelihood.
# Corresponds to the JSON property `underExposedLikelihood`
# @return [String]
attr_accessor :under_exposed_likelihood
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@anger_likelihood = args[:anger_likelihood] if args.key?(:anger_likelihood)
@blurred_likelihood = args[:blurred_likelihood] if args.key?(:blurred_likelihood)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@detection_confidence = args[:detection_confidence] if args.key?(:detection_confidence)
@fd_bounding_poly = args[:fd_bounding_poly] if args.key?(:fd_bounding_poly)
@headwear_likelihood = args[:headwear_likelihood] if args.key?(:headwear_likelihood)
@joy_likelihood = args[:joy_likelihood] if args.key?(:joy_likelihood)
@landmarking_confidence = args[:landmarking_confidence] if args.key?(:landmarking_confidence)
@landmarks = args[:landmarks] if args.key?(:landmarks)
@pan_angle = args[:pan_angle] if args.key?(:pan_angle)
@roll_angle = args[:roll_angle] if args.key?(:roll_angle)
@sorrow_likelihood = args[:sorrow_likelihood] if args.key?(:sorrow_likelihood)
@surprise_likelihood = args[:surprise_likelihood] if args.key?(:surprise_likelihood)
@tilt_angle = args[:tilt_angle] if args.key?(:tilt_angle)
@under_exposed_likelihood = args[:under_exposed_likelihood] if args.key?(:under_exposed_likelihood)
end
end
# A face-specific landmark (for example, a face feature).
class GoogleCloudVisionV1p1beta1FaceAnnotationLandmark
include Google::Apis::Core::Hashable
# A 3D position in the image, used primarily for Face detection landmarks. A
# valid Position must have both x and y coordinates. The position coordinates
# are in the same scale as the original image.
# Corresponds to the JSON property `position`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1Position]
attr_accessor :position
# Face landmark type.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@position = args[:position] if args.key?(:position)
@type = args[:type] if args.key?(:type)
end
end
# The Google Cloud Storage location where the output will be written to.
class GoogleCloudVisionV1p1beta1GcsDestination
include Google::Apis::Core::Hashable
# Google Cloud Storage URI prefix where the results will be stored. Results will
# be in JSON format and preceded by its corresponding input URI prefix. This
# field can either represent a gcs file prefix or gcs directory. In either case,
# the uri should be unique because in order to get all of the output files, you
# will need to do a wildcard gcs search on the uri prefix you provide. Examples:
# * File Prefix: gs://bucket-name/here/filenameprefix The output files will be
# created in gs://bucket-name/here/ and the names of the output files will begin
# with "filenameprefix". * Directory Prefix: gs://bucket-name/some/location/ The
# output files will be created in gs://bucket-name/some/location/ and the names
# of the output files could be anything because there was no filename prefix
# specified. If multiple outputs, each response is still AnnotateFileResponse,
# each of which contains some subset of the full list of AnnotateImageResponse.
# Multiple outputs can happen if, for example, the output JSON is too large and
# overflows into multiple sharded files.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@uri = args[:uri] if args.key?(:uri)
end
end
# The Google Cloud Storage location where the input will be read from.
class GoogleCloudVisionV1p1beta1GcsSource
include Google::Apis::Core::Hashable
# Google Cloud Storage URI for the input file. This must only be a Google Cloud
# Storage object. Wildcards are not currently supported.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@uri = args[:uri] if args.key?(:uri)
end
end
# If an image was produced from a file (e.g. a PDF), this message gives
# information about the source of that image.
class GoogleCloudVisionV1p1beta1ImageAnnotationContext
include Google::Apis::Core::Hashable
# If the file was a PDF or TIFF, this field gives the page number within the
# file used to produce the image.
# Corresponds to the JSON property `pageNumber`
# @return [Fixnum]
attr_accessor :page_number
# The URI of the file used to produce the image.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@page_number = args[:page_number] if args.key?(:page_number)
@uri = args[:uri] if args.key?(:uri)
end
end
# Stores image properties, such as dominant colors.
class GoogleCloudVisionV1p1beta1ImageProperties
include Google::Apis::Core::Hashable
# Set of dominant colors and their corresponding scores.
# Corresponds to the JSON property `dominantColors`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1DominantColorsAnnotation]
attr_accessor :dominant_colors
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@dominant_colors = args[:dominant_colors] if args.key?(:dominant_colors)
end
end
# The desired input location and metadata.
class GoogleCloudVisionV1p1beta1InputConfig
include Google::Apis::Core::Hashable
# File content, represented as a stream of bytes. Note: As with all `bytes`
# fields, protobuffers use a pure binary representation, whereas JSON
# representations use base64. Currently, this field only works for
# BatchAnnotateFiles requests. It does not work for AsyncBatchAnnotateFiles
# requests.
# Corresponds to the JSON property `content`
# NOTE: Values are automatically base64 encoded/decoded in the client library.
# @return [String]
attr_accessor :content
# The Google Cloud Storage location where the input will be read from.
# Corresponds to the JSON property `gcsSource`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1GcsSource]
attr_accessor :gcs_source
# The type of the file. Currently only "application/pdf", "image/tiff" and "
# image/gif" are supported. Wildcards are not supported.
# Corresponds to the JSON property `mimeType`
# @return [String]
attr_accessor :mime_type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@content = args[:content] if args.key?(:content)
@gcs_source = args[:gcs_source] if args.key?(:gcs_source)
@mime_type = args[:mime_type] if args.key?(:mime_type)
end
end
# Set of detected objects with bounding boxes.
class GoogleCloudVisionV1p1beta1LocalizedObjectAnnotation
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1BoundingPoly]
attr_accessor :bounding_poly
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more information,
# see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Object ID that should align with EntityAnnotation mid.
# Corresponds to the JSON property `mid`
# @return [String]
attr_accessor :mid
# Object name, expressed in its `language_code` language.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Score of the result. Range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@language_code = args[:language_code] if args.key?(:language_code)
@mid = args[:mid] if args.key?(:mid)
@name = args[:name] if args.key?(:name)
@score = args[:score] if args.key?(:score)
end
end
# Detected entity location information.
class GoogleCloudVisionV1p1beta1LocationInfo
include Google::Apis::Core::Hashable
# An object that represents a latitude/longitude pair. This is expressed as a
# pair of doubles to represent degrees latitude and degrees longitude. Unless
# specified otherwise, this must conform to the WGS84 standard. Values must be
# within normalized ranges.
# Corresponds to the JSON property `latLng`
# @return [Google::Apis::VisionV1p2beta1::LatLng]
attr_accessor :lat_lng
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@lat_lng = args[:lat_lng] if args.key?(:lat_lng)
end
end
# A vertex represents a 2D point in the image. NOTE: the normalized vertex
# coordinates are relative to the original image and range from 0 to 1.
class GoogleCloudVisionV1p1beta1NormalizedVertex
include Google::Apis::Core::Hashable
# X coordinate.
# Corresponds to the JSON property `x`
# @return [Float]
attr_accessor :x
# Y coordinate.
# Corresponds to the JSON property `y`
# @return [Float]
attr_accessor :y
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@x = args[:x] if args.key?(:x)
@y = args[:y] if args.key?(:y)
end
end
# Contains metadata for the BatchAnnotateImages operation.
class GoogleCloudVisionV1p1beta1OperationMetadata
include Google::Apis::Core::Hashable
# The time when the batch request was received.
# Corresponds to the JSON property `createTime`
# @return [String]
attr_accessor :create_time
# Current state of the batch operation.
# Corresponds to the JSON property `state`
# @return [String]
attr_accessor :state
# The time when the operation result was last updated.
# Corresponds to the JSON property `updateTime`
# @return [String]
attr_accessor :update_time
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@create_time = args[:create_time] if args.key?(:create_time)
@state = args[:state] if args.key?(:state)
@update_time = args[:update_time] if args.key?(:update_time)
end
end
# The desired output location and metadata.
class GoogleCloudVisionV1p1beta1OutputConfig
include Google::Apis::Core::Hashable
# The max number of response protos to put into each output JSON file on Google
# Cloud Storage. The valid range is [1, 100]. If not specified, the default
# value is 20. For example, for one pdf file with 100 pages, 100 response protos
# will be generated. If `batch_size` = 20, then 5 json files each containing 20
# response protos will be written under the prefix `gcs_destination`.`uri`.
# Currently, batch_size only applies to GcsDestination, with potential future
# support for other output configurations.
# Corresponds to the JSON property `batchSize`
# @return [Fixnum]
attr_accessor :batch_size
# The Google Cloud Storage location where the output will be written to.
# Corresponds to the JSON property `gcsDestination`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1GcsDestination]
attr_accessor :gcs_destination
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@batch_size = args[:batch_size] if args.key?(:batch_size)
@gcs_destination = args[:gcs_destination] if args.key?(:gcs_destination)
end
end
# Detected page from OCR.
class GoogleCloudVisionV1p1beta1Page
include Google::Apis::Core::Hashable
# List of blocks of text, images etc on this page.
# Corresponds to the JSON property `blocks`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1Block>]
attr_accessor :blocks
# Confidence of the OCR results on the page. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Page height. For PDFs the unit is points. For images (including TIFFs) the
# unit is pixels.
# Corresponds to the JSON property `height`
# @return [Fixnum]
attr_accessor :height
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1TextAnnotationTextProperty]
attr_accessor :property
# Page width. For PDFs the unit is points. For images (including TIFFs) the unit
# is pixels.
# Corresponds to the JSON property `width`
# @return [Fixnum]
attr_accessor :width
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@blocks = args[:blocks] if args.key?(:blocks)
@confidence = args[:confidence] if args.key?(:confidence)
@height = args[:height] if args.key?(:height)
@property = args[:property] if args.key?(:property)
@width = args[:width] if args.key?(:width)
end
end
# Structural unit of text representing a number of words in certain order.
class GoogleCloudVisionV1p1beta1Paragraph
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results for the paragraph. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1TextAnnotationTextProperty]
attr_accessor :property
# List of all words in this paragraph.
# Corresponds to the JSON property `words`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1Word>]
attr_accessor :words
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@property = args[:property] if args.key?(:property)
@words = args[:words] if args.key?(:words)
end
end
# A 3D position in the image, used primarily for Face detection landmarks. A
# valid Position must have both x and y coordinates. The position coordinates
# are in the same scale as the original image.
class GoogleCloudVisionV1p1beta1Position
include Google::Apis::Core::Hashable
# X coordinate.
# Corresponds to the JSON property `x`
# @return [Float]
attr_accessor :x
# Y coordinate.
# Corresponds to the JSON property `y`
# @return [Float]
attr_accessor :y
# Z coordinate (or depth).
# Corresponds to the JSON property `z`
# @return [Float]
attr_accessor :z
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@x = args[:x] if args.key?(:x)
@y = args[:y] if args.key?(:y)
@z = args[:z] if args.key?(:z)
end
end
# A Product contains ReferenceImages.
class GoogleCloudVisionV1p1beta1Product
include Google::Apis::Core::Hashable
# User-provided metadata to be stored with this product. Must be at most 4096
# characters long.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The user-provided name for this Product. Must not be empty. Must be at most
# 4096 characters long.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# The resource name of the product. Format is: `projects/PROJECT_ID/locations/
# LOC_ID/products/PRODUCT_ID`. This field is ignored when creating a product.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Immutable. The category for the product identified by the reference image.
# This should be one of "homegoods-v2", "apparel-v2", "toys-v2", "packagedgoods-
# v1" or "general-v1". The legacy categories "homegoods", "apparel", and "toys"
# are still supported, but these should not be used for new products.
# Corresponds to the JSON property `productCategory`
# @return [String]
attr_accessor :product_category
# Key-value pairs that can be attached to a product. At query time, constraints
# can be specified based on the product_labels. Note that integer values can be
# provided as strings, e.g. "1199". Only strings with integer values can match a
# range-based restriction which is to be supported soon. Multiple values can be
# assigned to the same key. One product may have up to 500 product_labels.
# Notice that the total number of distinct product_labels over all products in
# one ProductSet cannot exceed 1M, otherwise the product search pipeline will
# refuse to work for that ProductSet.
# Corresponds to the JSON property `productLabels`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1ProductKeyValue>]
attr_accessor :product_labels
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@display_name = args[:display_name] if args.key?(:display_name)
@name = args[:name] if args.key?(:name)
@product_category = args[:product_category] if args.key?(:product_category)
@product_labels = args[:product_labels] if args.key?(:product_labels)
end
end
# A product label represented as a key-value pair.
class GoogleCloudVisionV1p1beta1ProductKeyValue
include Google::Apis::Core::Hashable
# The key of the label attached to the product. Cannot be empty and cannot
# exceed 128 bytes.
# Corresponds to the JSON property `key`
# @return [String]
attr_accessor :key
# The value of the label attached to the product. Cannot be empty and cannot
# exceed 128 bytes.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@key = args[:key] if args.key?(:key)
@value = args[:value] if args.key?(:value)
end
end
# Results for a product search request.
class GoogleCloudVisionV1p1beta1ProductSearchResults
include Google::Apis::Core::Hashable
# Timestamp of the index which provided these results. Products added to the
# product set and products removed from the product set after this time are not
# reflected in the current results.
# Corresponds to the JSON property `indexTime`
# @return [String]
attr_accessor :index_time
# List of results grouped by products detected in the query image. Each entry
# corresponds to one bounding polygon in the query image, and contains the
# matching products specific to that region. There may be duplicate product
# matches in the union of all the per-product results.
# Corresponds to the JSON property `productGroupedResults`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1ProductSearchResultsGroupedResult>]
attr_accessor :product_grouped_results
# List of results, one for each product match.
# Corresponds to the JSON property `results`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1ProductSearchResultsResult>]
attr_accessor :results
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@index_time = args[:index_time] if args.key?(:index_time)
@product_grouped_results = args[:product_grouped_results] if args.key?(:product_grouped_results)
@results = args[:results] if args.key?(:results)
end
end
# Information about the products similar to a single product in a query image.
class GoogleCloudVisionV1p1beta1ProductSearchResultsGroupedResult
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1BoundingPoly]
attr_accessor :bounding_poly
# List of generic predictions for the object in the bounding box.
# Corresponds to the JSON property `objectAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1ProductSearchResultsObjectAnnotation>]
attr_accessor :object_annotations
# List of results, one for each product match.
# Corresponds to the JSON property `results`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1ProductSearchResultsResult>]
attr_accessor :results
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@object_annotations = args[:object_annotations] if args.key?(:object_annotations)
@results = args[:results] if args.key?(:results)
end
end
# Prediction for what the object in the bounding box is.
class GoogleCloudVisionV1p1beta1ProductSearchResultsObjectAnnotation
include Google::Apis::Core::Hashable
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more information,
# see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Object ID that should align with EntityAnnotation mid.
# Corresponds to the JSON property `mid`
# @return [String]
attr_accessor :mid
# Object name, expressed in its `language_code` language.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Score of the result. Range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@language_code = args[:language_code] if args.key?(:language_code)
@mid = args[:mid] if args.key?(:mid)
@name = args[:name] if args.key?(:name)
@score = args[:score] if args.key?(:score)
end
end
# Information about a product.
class GoogleCloudVisionV1p1beta1ProductSearchResultsResult
include Google::Apis::Core::Hashable
# The resource name of the image from the product that is the closest match to
# the query.
# Corresponds to the JSON property `image`
# @return [String]
attr_accessor :image
# A Product contains ReferenceImages.
# Corresponds to the JSON property `product`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1Product]
attr_accessor :product
# A confidence level on the match, ranging from 0 (no confidence) to 1 (full
# confidence).
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@image = args[:image] if args.key?(:image)
@product = args[:product] if args.key?(:product)
@score = args[:score] if args.key?(:score)
end
end
# A `Property` consists of a user-supplied name/value pair.
class GoogleCloudVisionV1p1beta1Property
include Google::Apis::Core::Hashable
# Name of the property.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Value of numeric properties.
# Corresponds to the JSON property `uint64Value`
# @return [Fixnum]
attr_accessor :uint64_value
# Value of the property.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@name = args[:name] if args.key?(:name)
@uint64_value = args[:uint64_value] if args.key?(:uint64_value)
@value = args[:value] if args.key?(:value)
end
end
# Set of features pertaining to the image, computed by computer vision methods
# over safe-search verticals (for example, adult, spoof, medical, violence).
class GoogleCloudVisionV1p1beta1SafeSearchAnnotation
include Google::Apis::Core::Hashable
# Represents the adult content likelihood for the image. Adult content may
# contain elements such as nudity, pornographic images or cartoons, or sexual
# activities.
# Corresponds to the JSON property `adult`
# @return [String]
attr_accessor :adult
# Likelihood that this is a medical image.
# Corresponds to the JSON property `medical`
# @return [String]
attr_accessor :medical
# Likelihood that the request image contains racy content. Racy content may
# include (but is not limited to) skimpy or sheer clothing, strategically
# covered nudity, lewd or provocative poses, or close-ups of sensitive body
# areas.
# Corresponds to the JSON property `racy`
# @return [String]
attr_accessor :racy
# Spoof likelihood. The likelihood that an modification was made to the image's
# canonical version to make it appear funny or offensive.
# Corresponds to the JSON property `spoof`
# @return [String]
attr_accessor :spoof
# Likelihood that this image contains violent content.
# Corresponds to the JSON property `violence`
# @return [String]
attr_accessor :violence
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@adult = args[:adult] if args.key?(:adult)
@medical = args[:medical] if args.key?(:medical)
@racy = args[:racy] if args.key?(:racy)
@spoof = args[:spoof] if args.key?(:spoof)
@violence = args[:violence] if args.key?(:violence)
end
end
# A single symbol representation.
class GoogleCloudVisionV1p1beta1Symbol
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results for the symbol. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1TextAnnotationTextProperty]
attr_accessor :property
# The actual UTF-8 representation of the symbol.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@property = args[:property] if args.key?(:property)
@text = args[:text] if args.key?(:text)
end
end
# TextAnnotation contains a structured representation of OCR extracted text. The
# hierarchy of an OCR extracted text structure is like this: TextAnnotation ->
# Page -> Block -> Paragraph -> Word -> Symbol Each structural component,
# starting from Page, may further have their own properties. Properties describe
# detected languages, breaks etc.. Please refer to the TextAnnotation.
# TextProperty message definition below for more detail.
class GoogleCloudVisionV1p1beta1TextAnnotation
include Google::Apis::Core::Hashable
# List of pages detected by OCR.
# Corresponds to the JSON property `pages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1Page>]
attr_accessor :pages
# UTF-8 text detected on the pages.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@pages = args[:pages] if args.key?(:pages)
@text = args[:text] if args.key?(:text)
end
end
# Detected start or end of a structural component.
class GoogleCloudVisionV1p1beta1TextAnnotationDetectedBreak
include Google::Apis::Core::Hashable
# True if break prepends the element.
# Corresponds to the JSON property `isPrefix`
# @return [Boolean]
attr_accessor :is_prefix
alias_method :is_prefix?, :is_prefix
# Detected break type.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@is_prefix = args[:is_prefix] if args.key?(:is_prefix)
@type = args[:type] if args.key?(:type)
end
end
# Detected language for a structural component.
class GoogleCloudVisionV1p1beta1TextAnnotationDetectedLanguage
include Google::Apis::Core::Hashable
# Confidence of detected language. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more information,
# see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@confidence = args[:confidence] if args.key?(:confidence)
@language_code = args[:language_code] if args.key?(:language_code)
end
end
# Additional information detected on the structural component.
class GoogleCloudVisionV1p1beta1TextAnnotationTextProperty
include Google::Apis::Core::Hashable
# Detected start or end of a structural component.
# Corresponds to the JSON property `detectedBreak`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1TextAnnotationDetectedBreak]
attr_accessor :detected_break
# A list of detected languages together with confidence.
# Corresponds to the JSON property `detectedLanguages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1TextAnnotationDetectedLanguage>]
attr_accessor :detected_languages
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@detected_break = args[:detected_break] if args.key?(:detected_break)
@detected_languages = args[:detected_languages] if args.key?(:detected_languages)
end
end
# A vertex represents a 2D point in the image. NOTE: the vertex coordinates are
# in the same scale as the original image.
class GoogleCloudVisionV1p1beta1Vertex
include Google::Apis::Core::Hashable
# X coordinate.
# Corresponds to the JSON property `x`
# @return [Fixnum]
attr_accessor :x
# Y coordinate.
# Corresponds to the JSON property `y`
# @return [Fixnum]
attr_accessor :y
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@x = args[:x] if args.key?(:x)
@y = args[:y] if args.key?(:y)
end
end
# Relevant information for the image from the Internet.
class GoogleCloudVisionV1p1beta1WebDetection
include Google::Apis::Core::Hashable
# The service's best guess as to the topic of the request image. Inferred from
# similar images on the open web.
# Corresponds to the JSON property `bestGuessLabels`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1WebDetectionWebLabel>]
attr_accessor :best_guess_labels
# Fully matching images from the Internet. Can include resized copies of the
# query image.
# Corresponds to the JSON property `fullMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1WebDetectionWebImage>]
attr_accessor :full_matching_images
# Web pages containing the matching images from the Internet.
# Corresponds to the JSON property `pagesWithMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1WebDetectionWebPage>]
attr_accessor :pages_with_matching_images
# Partial matching images from the Internet. Those images are similar enough to
# share some key-point features. For example an original image will likely have
# partial matching for its crops.
# Corresponds to the JSON property `partialMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1WebDetectionWebImage>]
attr_accessor :partial_matching_images
# The visually similar image results.
# Corresponds to the JSON property `visuallySimilarImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1WebDetectionWebImage>]
attr_accessor :visually_similar_images
# Deduced entities from similar images on the Internet.
# Corresponds to the JSON property `webEntities`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1WebDetectionWebEntity>]
attr_accessor :web_entities
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@best_guess_labels = args[:best_guess_labels] if args.key?(:best_guess_labels)
@full_matching_images = args[:full_matching_images] if args.key?(:full_matching_images)
@pages_with_matching_images = args[:pages_with_matching_images] if args.key?(:pages_with_matching_images)
@partial_matching_images = args[:partial_matching_images] if args.key?(:partial_matching_images)
@visually_similar_images = args[:visually_similar_images] if args.key?(:visually_similar_images)
@web_entities = args[:web_entities] if args.key?(:web_entities)
end
end
# Entity deduced from similar images on the Internet.
class GoogleCloudVisionV1p1beta1WebDetectionWebEntity
include Google::Apis::Core::Hashable
# Canonical description of the entity, in English.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# Opaque entity ID.
# Corresponds to the JSON property `entityId`
# @return [String]
attr_accessor :entity_id
# Overall relevancy score for the entity. Not normalized and not comparable
# across different image queries.
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@entity_id = args[:entity_id] if args.key?(:entity_id)
@score = args[:score] if args.key?(:score)
end
end
# Metadata for online images.
class GoogleCloudVisionV1p1beta1WebDetectionWebImage
include Google::Apis::Core::Hashable
# (Deprecated) Overall relevancy score for the image.
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
# The result image URL.
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@score = args[:score] if args.key?(:score)
@url = args[:url] if args.key?(:url)
end
end
# Label to provide extra metadata for the web detection.
class GoogleCloudVisionV1p1beta1WebDetectionWebLabel
include Google::Apis::Core::Hashable
# Label for extra metadata.
# Corresponds to the JSON property `label`
# @return [String]
attr_accessor :label
# The BCP-47 language code for `label`, such as "en-US" or "sr-Latn". For more
# information, see http://www.unicode.org/reports/tr35/#
# Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@label = args[:label] if args.key?(:label)
@language_code = args[:language_code] if args.key?(:language_code)
end
end
# Metadata for web pages.
class GoogleCloudVisionV1p1beta1WebDetectionWebPage
include Google::Apis::Core::Hashable
# Fully matching images on the page. Can include resized copies of the query
# image.
# Corresponds to the JSON property `fullMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1WebDetectionWebImage>]
attr_accessor :full_matching_images
# Title for the web page, may contain HTML markups.
# Corresponds to the JSON property `pageTitle`
# @return [String]
attr_accessor :page_title
# Partial matching images on the page. Those images are similar enough to share
# some key-point features. For example an original image will likely have
# partial matching for its crops.
# Corresponds to the JSON property `partialMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1WebDetectionWebImage>]
attr_accessor :partial_matching_images
# (Deprecated) Overall relevancy score for the web page.
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
# The result web page URL.
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@full_matching_images = args[:full_matching_images] if args.key?(:full_matching_images)
@page_title = args[:page_title] if args.key?(:page_title)
@partial_matching_images = args[:partial_matching_images] if args.key?(:partial_matching_images)
@score = args[:score] if args.key?(:score)
@url = args[:url] if args.key?(:url)
end
end
# A word representation.
class GoogleCloudVisionV1p1beta1Word
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results for the word. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1TextAnnotationTextProperty]
attr_accessor :property
# List of symbols in the word. The order of the symbols follows the natural
# reading order.
# Corresponds to the JSON property `symbols`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p1beta1Symbol>]
attr_accessor :symbols
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@property = args[:property] if args.key?(:property)
@symbols = args[:symbols] if args.key?(:symbols)
end
end
# A request to annotate one single file, e.g. a PDF, TIFF or GIF file.
class GoogleCloudVisionV1p2beta1AnnotateFileRequest
include Google::Apis::Core::Hashable
# Required. Requested features.
# Corresponds to the JSON property `features`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1Feature>]
attr_accessor :features
# Image context and/or feature-specific parameters.
# Corresponds to the JSON property `imageContext`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1ImageContext]
attr_accessor :image_context
# The desired input location and metadata.
# Corresponds to the JSON property `inputConfig`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1InputConfig]
attr_accessor :input_config
# Pages of the file to perform image annotation. Pages starts from 1, we assume
# the first page of the file is page 1. At most 5 pages are supported per
# request. Pages can be negative. Page 1 means the first page. Page 2 means the
# second page. Page -1 means the last page. Page -2 means the second to the last
# page. If the file is GIF instead of PDF or TIFF, page refers to GIF frames. If
# this field is empty, by default the service performs image annotation for the
# first 5 pages of the file.
# Corresponds to the JSON property `pages`
# @return [Array<Fixnum>]
attr_accessor :pages
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@features = args[:features] if args.key?(:features)
@image_context = args[:image_context] if args.key?(:image_context)
@input_config = args[:input_config] if args.key?(:input_config)
@pages = args[:pages] if args.key?(:pages)
end
end
# Response to a single file annotation request. A file may contain one or more
# images, which individually have their own responses.
class GoogleCloudVisionV1p2beta1AnnotateFileResponse
include Google::Apis::Core::Hashable
# The `Status` type defines a logical error model that is suitable for different
# programming environments, including REST APIs and RPC APIs. It is used by [
# gRPC](https://github.com/grpc). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `error`
# @return [Google::Apis::VisionV1p2beta1::Status]
attr_accessor :error
# The desired input location and metadata.
# Corresponds to the JSON property `inputConfig`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1InputConfig]
attr_accessor :input_config
# Individual responses to images found within the file. This field will be empty
# if the `error` field is set.
# Corresponds to the JSON property `responses`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1AnnotateImageResponse>]
attr_accessor :responses
# This field gives the total number of pages in the file.
# Corresponds to the JSON property `totalPages`
# @return [Fixnum]
attr_accessor :total_pages
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@error = args[:error] if args.key?(:error)
@input_config = args[:input_config] if args.key?(:input_config)
@responses = args[:responses] if args.key?(:responses)
@total_pages = args[:total_pages] if args.key?(:total_pages)
end
end
# Request for performing Google Cloud Vision API tasks over a user-provided
# image, with user-requested features, and with context information.
class GoogleCloudVisionV1p2beta1AnnotateImageRequest
include Google::Apis::Core::Hashable
# Requested features.
# Corresponds to the JSON property `features`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1Feature>]
attr_accessor :features
# Client image to perform Google Cloud Vision API tasks over.
# Corresponds to the JSON property `image`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1Image]
attr_accessor :image
# Image context and/or feature-specific parameters.
# Corresponds to the JSON property `imageContext`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1ImageContext]
attr_accessor :image_context
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@features = args[:features] if args.key?(:features)
@image = args[:image] if args.key?(:image)
@image_context = args[:image_context] if args.key?(:image_context)
end
end
# Response to an image annotation request.
class GoogleCloudVisionV1p2beta1AnnotateImageResponse
include Google::Apis::Core::Hashable
# If an image was produced from a file (e.g. a PDF), this message gives
# information about the source of that image.
# Corresponds to the JSON property `context`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1ImageAnnotationContext]
attr_accessor :context
# Set of crop hints that are used to generate new crops when serving images.
# Corresponds to the JSON property `cropHintsAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1CropHintsAnnotation]
attr_accessor :crop_hints_annotation
# The `Status` type defines a logical error model that is suitable for different
# programming environments, including REST APIs and RPC APIs. It is used by [
# gRPC](https://github.com/grpc). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `error`
# @return [Google::Apis::VisionV1p2beta1::Status]
attr_accessor :error
# If present, face detection has completed successfully.
# Corresponds to the JSON property `faceAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1FaceAnnotation>]
attr_accessor :face_annotations
# TextAnnotation contains a structured representation of OCR extracted text. The
# hierarchy of an OCR extracted text structure is like this: TextAnnotation ->
# Page -> Block -> Paragraph -> Word -> Symbol Each structural component,
# starting from Page, may further have their own properties. Properties describe
# detected languages, breaks etc.. Please refer to the TextAnnotation.
# TextProperty message definition below for more detail.
# Corresponds to the JSON property `fullTextAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1TextAnnotation]
attr_accessor :full_text_annotation
# Stores image properties, such as dominant colors.
# Corresponds to the JSON property `imagePropertiesAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1ImageProperties]
attr_accessor :image_properties_annotation
# If present, label detection has completed successfully.
# Corresponds to the JSON property `labelAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1EntityAnnotation>]
attr_accessor :label_annotations
# If present, landmark detection has completed successfully.
# Corresponds to the JSON property `landmarkAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1EntityAnnotation>]
attr_accessor :landmark_annotations
# If present, localized object detection has completed successfully. This will
# be sorted descending by confidence score.
# Corresponds to the JSON property `localizedObjectAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1LocalizedObjectAnnotation>]
attr_accessor :localized_object_annotations
# If present, logo detection has completed successfully.
# Corresponds to the JSON property `logoAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1EntityAnnotation>]
attr_accessor :logo_annotations
# Results for a product search request.
# Corresponds to the JSON property `productSearchResults`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1ProductSearchResults]
attr_accessor :product_search_results
# Set of features pertaining to the image, computed by computer vision methods
# over safe-search verticals (for example, adult, spoof, medical, violence).
# Corresponds to the JSON property `safeSearchAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1SafeSearchAnnotation]
attr_accessor :safe_search_annotation
# If present, text (OCR) detection has completed successfully.
# Corresponds to the JSON property `textAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1EntityAnnotation>]
attr_accessor :text_annotations
# Relevant information for the image from the Internet.
# Corresponds to the JSON property `webDetection`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1WebDetection]
attr_accessor :web_detection
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@context = args[:context] if args.key?(:context)
@crop_hints_annotation = args[:crop_hints_annotation] if args.key?(:crop_hints_annotation)
@error = args[:error] if args.key?(:error)
@face_annotations = args[:face_annotations] if args.key?(:face_annotations)
@full_text_annotation = args[:full_text_annotation] if args.key?(:full_text_annotation)
@image_properties_annotation = args[:image_properties_annotation] if args.key?(:image_properties_annotation)
@label_annotations = args[:label_annotations] if args.key?(:label_annotations)
@landmark_annotations = args[:landmark_annotations] if args.key?(:landmark_annotations)
@localized_object_annotations = args[:localized_object_annotations] if args.key?(:localized_object_annotations)
@logo_annotations = args[:logo_annotations] if args.key?(:logo_annotations)
@product_search_results = args[:product_search_results] if args.key?(:product_search_results)
@safe_search_annotation = args[:safe_search_annotation] if args.key?(:safe_search_annotation)
@text_annotations = args[:text_annotations] if args.key?(:text_annotations)
@web_detection = args[:web_detection] if args.key?(:web_detection)
end
end
# An offline file annotation request.
class GoogleCloudVisionV1p2beta1AsyncAnnotateFileRequest
include Google::Apis::Core::Hashable
# Required. Requested features.
# Corresponds to the JSON property `features`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1Feature>]
attr_accessor :features
# Image context and/or feature-specific parameters.
# Corresponds to the JSON property `imageContext`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1ImageContext]
attr_accessor :image_context
# The desired input location and metadata.
# Corresponds to the JSON property `inputConfig`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1InputConfig]
attr_accessor :input_config
# The desired output location and metadata.
# Corresponds to the JSON property `outputConfig`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1OutputConfig]
attr_accessor :output_config
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@features = args[:features] if args.key?(:features)
@image_context = args[:image_context] if args.key?(:image_context)
@input_config = args[:input_config] if args.key?(:input_config)
@output_config = args[:output_config] if args.key?(:output_config)
end
end
# The response for a single offline file annotation request.
class GoogleCloudVisionV1p2beta1AsyncAnnotateFileResponse
include Google::Apis::Core::Hashable
# The desired output location and metadata.
# Corresponds to the JSON property `outputConfig`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1OutputConfig]
attr_accessor :output_config
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@output_config = args[:output_config] if args.key?(:output_config)
end
end
# Multiple async file annotation requests are batched into a single service call.
class GoogleCloudVisionV1p2beta1AsyncBatchAnnotateFilesRequest
include Google::Apis::Core::Hashable
# Optional. Target project and location to make a call. Format: `projects/`
# project-id`/locations/`location-id``. If no parent is specified, a region will
# be chosen automatically. Supported location-ids: `us`: USA country only, `asia`
# : East asia areas, like Japan, Taiwan, `eu`: The European Union. Example: `
# projects/project-A/locations/eu`.
# Corresponds to the JSON property `parent`
# @return [String]
attr_accessor :parent
# Required. Individual async file annotation requests for this batch.
# Corresponds to the JSON property `requests`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1AsyncAnnotateFileRequest>]
attr_accessor :requests
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@parent = args[:parent] if args.key?(:parent)
@requests = args[:requests] if args.key?(:requests)
end
end
# Response to an async batch file annotation request.
class GoogleCloudVisionV1p2beta1AsyncBatchAnnotateFilesResponse
include Google::Apis::Core::Hashable
# The list of file annotation responses, one for each request in
# AsyncBatchAnnotateFilesRequest.
# Corresponds to the JSON property `responses`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1AsyncAnnotateFileResponse>]
attr_accessor :responses
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@responses = args[:responses] if args.key?(:responses)
end
end
# Request for async image annotation for a list of images.
class GoogleCloudVisionV1p2beta1AsyncBatchAnnotateImagesRequest
include Google::Apis::Core::Hashable
# The desired output location and metadata.
# Corresponds to the JSON property `outputConfig`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1OutputConfig]
attr_accessor :output_config
# Optional. Target project and location to make a call. Format: `projects/`
# project-id`/locations/`location-id``. If no parent is specified, a region will
# be chosen automatically. Supported location-ids: `us`: USA country only, `asia`
# : East asia areas, like Japan, Taiwan, `eu`: The European Union. Example: `
# projects/project-A/locations/eu`.
# Corresponds to the JSON property `parent`
# @return [String]
attr_accessor :parent
# Required. Individual image annotation requests for this batch.
# Corresponds to the JSON property `requests`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1AnnotateImageRequest>]
attr_accessor :requests
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@output_config = args[:output_config] if args.key?(:output_config)
@parent = args[:parent] if args.key?(:parent)
@requests = args[:requests] if args.key?(:requests)
end
end
# A list of requests to annotate files using the BatchAnnotateFiles API.
class GoogleCloudVisionV1p2beta1BatchAnnotateFilesRequest
include Google::Apis::Core::Hashable
# Optional. Target project and location to make a call. Format: `projects/`
# project-id`/locations/`location-id``. If no parent is specified, a region will
# be chosen automatically. Supported location-ids: `us`: USA country only, `asia`
# : East asia areas, like Japan, Taiwan, `eu`: The European Union. Example: `
# projects/project-A/locations/eu`.
# Corresponds to the JSON property `parent`
# @return [String]
attr_accessor :parent
# Required. The list of file annotation requests. Right now we support only one
# AnnotateFileRequest in BatchAnnotateFilesRequest.
# Corresponds to the JSON property `requests`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1AnnotateFileRequest>]
attr_accessor :requests
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@parent = args[:parent] if args.key?(:parent)
@requests = args[:requests] if args.key?(:requests)
end
end
# A list of file annotation responses.
class GoogleCloudVisionV1p2beta1BatchAnnotateFilesResponse
include Google::Apis::Core::Hashable
# The list of file annotation responses, each response corresponding to each
# AnnotateFileRequest in BatchAnnotateFilesRequest.
# Corresponds to the JSON property `responses`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1AnnotateFileResponse>]
attr_accessor :responses
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@responses = args[:responses] if args.key?(:responses)
end
end
# Multiple image annotation requests are batched into a single service call.
class GoogleCloudVisionV1p2beta1BatchAnnotateImagesRequest
include Google::Apis::Core::Hashable
# Optional. Target project and location to make a call. Format: `projects/`
# project-id`/locations/`location-id``. If no parent is specified, a region will
# be chosen automatically. Supported location-ids: `us`: USA country only, `asia`
# : East asia areas, like Japan, Taiwan, `eu`: The European Union. Example: `
# projects/project-A/locations/eu`.
# Corresponds to the JSON property `parent`
# @return [String]
attr_accessor :parent
# Required. Individual image annotation requests for this batch.
# Corresponds to the JSON property `requests`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1AnnotateImageRequest>]
attr_accessor :requests
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@parent = args[:parent] if args.key?(:parent)
@requests = args[:requests] if args.key?(:requests)
end
end
# Response to a batch image annotation request.
class GoogleCloudVisionV1p2beta1BatchAnnotateImagesResponse
include Google::Apis::Core::Hashable
# Individual responses to image annotation requests within the batch.
# Corresponds to the JSON property `responses`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1AnnotateImageResponse>]
attr_accessor :responses
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@responses = args[:responses] if args.key?(:responses)
end
end
# Logical element on the page.
class GoogleCloudVisionV1p2beta1Block
include Google::Apis::Core::Hashable
# Detected block type (text, image etc) for this block.
# Corresponds to the JSON property `blockType`
# @return [String]
attr_accessor :block_type
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results on the block. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# List of paragraphs in this block (if this blocks is of type text).
# Corresponds to the JSON property `paragraphs`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1Paragraph>]
attr_accessor :paragraphs
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1TextAnnotationTextProperty]
attr_accessor :property
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@block_type = args[:block_type] if args.key?(:block_type)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@paragraphs = args[:paragraphs] if args.key?(:paragraphs)
@property = args[:property] if args.key?(:property)
end
end
# A bounding polygon for the detected image annotation.
class GoogleCloudVisionV1p2beta1BoundingPoly
include Google::Apis::Core::Hashable
# The bounding polygon normalized vertices.
# Corresponds to the JSON property `normalizedVertices`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1NormalizedVertex>]
attr_accessor :normalized_vertices
# The bounding polygon vertices.
# Corresponds to the JSON property `vertices`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1Vertex>]
attr_accessor :vertices
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@normalized_vertices = args[:normalized_vertices] if args.key?(:normalized_vertices)
@vertices = args[:vertices] if args.key?(:vertices)
end
end
# Color information consists of RGB channels, score, and the fraction of the
# image that the color occupies in the image.
class GoogleCloudVisionV1p2beta1ColorInfo
include Google::Apis::Core::Hashable
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation can
# be trivially provided to the constructor of "java.awt.Color" in Java; it can
# also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into a
# CSS "rgba()" string in JavaScript, as well. Note: this proto does not carry
# information about the absolute color space that should be used to interpret
# the RGB value (e.g. sRGB, Adobe RGB, DCI-P3, BT.2020, etc.). By default,
# applications SHOULD assume the sRGB color space. Note: when color equality
# needs to be decided, implementations, unless documented otherwise, will treat
# two colors to be equal if all their red, green, blue and alpha values each
# differ by at most 1e-5. Example (Java): import com.google.type.Color; // ...
# public static java.awt.Color fromProto(Color protocolor) ` float alpha =
# protocolor.hasAlpha() ? protocolor.getAlpha().getValue() : 1.0; return new
# java.awt.Color( protocolor.getRed(), protocolor.getGreen(), protocolor.getBlue(
# ), alpha); ` public static Color toProto(java.awt.Color color) ` float red = (
# float) color.getRed(); float green = (float) color.getGreen(); float blue = (
# float) color.getBlue(); float denominator = 255.0; Color.Builder resultBuilder
# = Color .newBuilder() .setRed(red / denominator) .setGreen(green / denominator)
# .setBlue(blue / denominator); int alpha = color.getAlpha(); if (alpha != 255)
# ` result.setAlpha( FloatValue .newBuilder() .setValue(((float) alpha) /
# denominator) .build()); ` return resultBuilder.build(); ` // ... Example (iOS /
# Obj-C): // ... static UIColor* fromProto(Color* protocolor) ` float red = [
# protocolor red]; float green = [protocolor green]; float blue = [protocolor
# blue]; FloatValue* alpha_wrapper = [protocolor alpha]; float alpha = 1.0; if (
# alpha_wrapper != nil) ` alpha = [alpha_wrapper value]; ` return [UIColor
# colorWithRed:red green:green blue:blue alpha:alpha]; ` static Color* toProto(
# UIColor* color) ` CGFloat red, green, blue, alpha; if (![color getRed:&red
# green:&green blue:&blue alpha:&alpha]) ` return nil; ` Color* result = [[Color
# alloc] init]; [result setRed:red]; [result setGreen:green]; [result setBlue:
# blue]; if (alpha <= 0.9999) ` [result setAlpha:floatWrapperWithValue(alpha)]; `
# [result autorelease]; return result; ` // ... Example (JavaScript): // ...
# var protoToCssColor = function(rgb_color) ` var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0; var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255); var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255); if (!('alpha' in rgb_color)) ` return
# rgbToCssColor_(red, green, blue); ` var alphaFrac = rgb_color.alpha.value || 0.
# 0; var rgbParams = [red, green, blue].join(','); return ['rgba(', rgbParams, ',
# ', alphaFrac, ')'].join(''); `; var rgbToCssColor_ = function(red, green, blue)
# ` var rgbNumber = new Number((red << 16) | (green << 8) | blue); var
# hexString = rgbNumber.toString(16); var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#']; for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0'); ` resultBuilder.push(hexString); return resultBuilder.
# join(''); `; // ...
# Corresponds to the JSON property `color`
# @return [Google::Apis::VisionV1p2beta1::Color]
attr_accessor :color
# The fraction of pixels the color occupies in the image. Value in range [0, 1].
# Corresponds to the JSON property `pixelFraction`
# @return [Float]
attr_accessor :pixel_fraction
# Image-specific score for this color. Value in range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@color = args[:color] if args.key?(:color)
@pixel_fraction = args[:pixel_fraction] if args.key?(:pixel_fraction)
@score = args[:score] if args.key?(:score)
end
end
# Single crop hint that is used to generate a new crop when serving an image.
class GoogleCloudVisionV1p2beta1CropHint
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1BoundingPoly]
attr_accessor :bounding_poly
# Confidence of this being a salient region. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Fraction of importance of this salient region with respect to the original
# image.
# Corresponds to the JSON property `importanceFraction`
# @return [Float]
attr_accessor :importance_fraction
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@confidence = args[:confidence] if args.key?(:confidence)
@importance_fraction = args[:importance_fraction] if args.key?(:importance_fraction)
end
end
# Set of crop hints that are used to generate new crops when serving images.
class GoogleCloudVisionV1p2beta1CropHintsAnnotation
include Google::Apis::Core::Hashable
# Crop hint results.
# Corresponds to the JSON property `cropHints`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1CropHint>]
attr_accessor :crop_hints
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@crop_hints = args[:crop_hints] if args.key?(:crop_hints)
end
end
# Parameters for crop hints annotation request.
class GoogleCloudVisionV1p2beta1CropHintsParams
include Google::Apis::Core::Hashable
# Aspect ratios in floats, representing the ratio of the width to the height of
# the image. For example, if the desired aspect ratio is 4/3, the corresponding
# float value should be 1.33333. If not specified, the best possible crop is
# returned. The number of provided aspect ratios is limited to a maximum of 16;
# any aspect ratios provided after the 16th are ignored.
# Corresponds to the JSON property `aspectRatios`
# @return [Array<Float>]
attr_accessor :aspect_ratios
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@aspect_ratios = args[:aspect_ratios] if args.key?(:aspect_ratios)
end
end
# Set of dominant colors and their corresponding scores.
class GoogleCloudVisionV1p2beta1DominantColorsAnnotation
include Google::Apis::Core::Hashable
# RGB color values with their score and pixel fraction.
# Corresponds to the JSON property `colors`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1ColorInfo>]
attr_accessor :colors
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@colors = args[:colors] if args.key?(:colors)
end
end
# Set of detected entity features.
class GoogleCloudVisionV1p2beta1EntityAnnotation
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1BoundingPoly]
attr_accessor :bounding_poly
# **Deprecated. Use `score` instead.** The accuracy of the entity detection in
# an image. For example, for an image in which the "Eiffel Tower" entity is
# detected, this field represents the confidence that there is a tower in the
# query image. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Entity textual description, expressed in its `locale` language.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The language code for the locale in which the entity textual `description` is
# expressed.
# Corresponds to the JSON property `locale`
# @return [String]
attr_accessor :locale
# The location information for the detected entity. Multiple `LocationInfo`
# elements can be present because one location may indicate the location of the
# scene in the image, and another location may indicate the location of the
# place where the image was taken. Location information is usually present for
# landmarks.
# Corresponds to the JSON property `locations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1LocationInfo>]
attr_accessor :locations
# Opaque entity ID. Some IDs may be available in [Google Knowledge Graph Search
# API](https://developers.google.com/knowledge-graph/).
# Corresponds to the JSON property `mid`
# @return [String]
attr_accessor :mid
# Some entities may have optional user-supplied `Property` (name/value) fields,
# such a score or string that qualifies the entity.
# Corresponds to the JSON property `properties`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1Property>]
attr_accessor :properties
# Overall score of the result. Range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
# The relevancy of the ICA (Image Content Annotation) label to the image. For
# example, the relevancy of "tower" is likely higher to an image containing the
# detected "Eiffel Tower" than to an image containing a detected distant
# towering building, even though the confidence that there is a tower in each
# image may be the same. Range [0, 1].
# Corresponds to the JSON property `topicality`
# @return [Float]
attr_accessor :topicality
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@confidence = args[:confidence] if args.key?(:confidence)
@description = args[:description] if args.key?(:description)
@locale = args[:locale] if args.key?(:locale)
@locations = args[:locations] if args.key?(:locations)
@mid = args[:mid] if args.key?(:mid)
@properties = args[:properties] if args.key?(:properties)
@score = args[:score] if args.key?(:score)
@topicality = args[:topicality] if args.key?(:topicality)
end
end
# A face annotation object contains the results of face detection.
class GoogleCloudVisionV1p2beta1FaceAnnotation
include Google::Apis::Core::Hashable
# Anger likelihood.
# Corresponds to the JSON property `angerLikelihood`
# @return [String]
attr_accessor :anger_likelihood
# Blurred likelihood.
# Corresponds to the JSON property `blurredLikelihood`
# @return [String]
attr_accessor :blurred_likelihood
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1BoundingPoly]
attr_accessor :bounding_poly
# Detection confidence. Range [0, 1].
# Corresponds to the JSON property `detectionConfidence`
# @return [Float]
attr_accessor :detection_confidence
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `fdBoundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1BoundingPoly]
attr_accessor :fd_bounding_poly
# Headwear likelihood.
# Corresponds to the JSON property `headwearLikelihood`
# @return [String]
attr_accessor :headwear_likelihood
# Joy likelihood.
# Corresponds to the JSON property `joyLikelihood`
# @return [String]
attr_accessor :joy_likelihood
# Face landmarking confidence. Range [0, 1].
# Corresponds to the JSON property `landmarkingConfidence`
# @return [Float]
attr_accessor :landmarking_confidence
# Detected face landmarks.
# Corresponds to the JSON property `landmarks`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1FaceAnnotationLandmark>]
attr_accessor :landmarks
# Yaw angle, which indicates the leftward/rightward angle that the face is
# pointing relative to the vertical plane perpendicular to the image. Range [-
# 180,180].
# Corresponds to the JSON property `panAngle`
# @return [Float]
attr_accessor :pan_angle
# Roll angle, which indicates the amount of clockwise/anti-clockwise rotation of
# the face relative to the image vertical about the axis perpendicular to the
# face. Range [-180,180].
# Corresponds to the JSON property `rollAngle`
# @return [Float]
attr_accessor :roll_angle
# Sorrow likelihood.
# Corresponds to the JSON property `sorrowLikelihood`
# @return [String]
attr_accessor :sorrow_likelihood
# Surprise likelihood.
# Corresponds to the JSON property `surpriseLikelihood`
# @return [String]
attr_accessor :surprise_likelihood
# Pitch angle, which indicates the upwards/downwards angle that the face is
# pointing relative to the image's horizontal plane. Range [-180,180].
# Corresponds to the JSON property `tiltAngle`
# @return [Float]
attr_accessor :tilt_angle
# Under-exposed likelihood.
# Corresponds to the JSON property `underExposedLikelihood`
# @return [String]
attr_accessor :under_exposed_likelihood
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@anger_likelihood = args[:anger_likelihood] if args.key?(:anger_likelihood)
@blurred_likelihood = args[:blurred_likelihood] if args.key?(:blurred_likelihood)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@detection_confidence = args[:detection_confidence] if args.key?(:detection_confidence)
@fd_bounding_poly = args[:fd_bounding_poly] if args.key?(:fd_bounding_poly)
@headwear_likelihood = args[:headwear_likelihood] if args.key?(:headwear_likelihood)
@joy_likelihood = args[:joy_likelihood] if args.key?(:joy_likelihood)
@landmarking_confidence = args[:landmarking_confidence] if args.key?(:landmarking_confidence)
@landmarks = args[:landmarks] if args.key?(:landmarks)
@pan_angle = args[:pan_angle] if args.key?(:pan_angle)
@roll_angle = args[:roll_angle] if args.key?(:roll_angle)
@sorrow_likelihood = args[:sorrow_likelihood] if args.key?(:sorrow_likelihood)
@surprise_likelihood = args[:surprise_likelihood] if args.key?(:surprise_likelihood)
@tilt_angle = args[:tilt_angle] if args.key?(:tilt_angle)
@under_exposed_likelihood = args[:under_exposed_likelihood] if args.key?(:under_exposed_likelihood)
end
end
# A face-specific landmark (for example, a face feature).
class GoogleCloudVisionV1p2beta1FaceAnnotationLandmark
include Google::Apis::Core::Hashable
# A 3D position in the image, used primarily for Face detection landmarks. A
# valid Position must have both x and y coordinates. The position coordinates
# are in the same scale as the original image.
# Corresponds to the JSON property `position`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1Position]
attr_accessor :position
# Face landmark type.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@position = args[:position] if args.key?(:position)
@type = args[:type] if args.key?(:type)
end
end
# The type of Google Cloud Vision API detection to perform, and the maximum
# number of results to return for that type. Multiple `Feature` objects can be
# specified in the `features` list.
class GoogleCloudVisionV1p2beta1Feature
include Google::Apis::Core::Hashable
# Maximum number of results of this type. Does not apply to `TEXT_DETECTION`, `
# DOCUMENT_TEXT_DETECTION`, or `CROP_HINTS`.
# Corresponds to the JSON property `maxResults`
# @return [Fixnum]
attr_accessor :max_results
# Model to use for the feature. Supported values: "builtin/stable" (the default
# if unset) and "builtin/latest".
# Corresponds to the JSON property `model`
# @return [String]
attr_accessor :model
# The feature type.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@max_results = args[:max_results] if args.key?(:max_results)
@model = args[:model] if args.key?(:model)
@type = args[:type] if args.key?(:type)
end
end
# The Google Cloud Storage location where the output will be written to.
class GoogleCloudVisionV1p2beta1GcsDestination
include Google::Apis::Core::Hashable
# Google Cloud Storage URI prefix where the results will be stored. Results will
# be in JSON format and preceded by its corresponding input URI prefix. This
# field can either represent a gcs file prefix or gcs directory. In either case,
# the uri should be unique because in order to get all of the output files, you
# will need to do a wildcard gcs search on the uri prefix you provide. Examples:
# * File Prefix: gs://bucket-name/here/filenameprefix The output files will be
# created in gs://bucket-name/here/ and the names of the output files will begin
# with "filenameprefix". * Directory Prefix: gs://bucket-name/some/location/ The
# output files will be created in gs://bucket-name/some/location/ and the names
# of the output files could be anything because there was no filename prefix
# specified. If multiple outputs, each response is still AnnotateFileResponse,
# each of which contains some subset of the full list of AnnotateImageResponse.
# Multiple outputs can happen if, for example, the output JSON is too large and
# overflows into multiple sharded files.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@uri = args[:uri] if args.key?(:uri)
end
end
# The Google Cloud Storage location where the input will be read from.
class GoogleCloudVisionV1p2beta1GcsSource
include Google::Apis::Core::Hashable
# Google Cloud Storage URI for the input file. This must only be a Google Cloud
# Storage object. Wildcards are not currently supported.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@uri = args[:uri] if args.key?(:uri)
end
end
# Client image to perform Google Cloud Vision API tasks over.
class GoogleCloudVisionV1p2beta1Image
include Google::Apis::Core::Hashable
# Image content, represented as a stream of bytes. Note: As with all `bytes`
# fields, protobuffers use a pure binary representation, whereas JSON
# representations use base64. Currently, this field only works for
# BatchAnnotateImages requests. It does not work for AsyncBatchAnnotateImages
# requests.
# Corresponds to the JSON property `content`
# NOTE: Values are automatically base64 encoded/decoded in the client library.
# @return [String]
attr_accessor :content
# External image source (Google Cloud Storage or web URL image location).
# Corresponds to the JSON property `source`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1ImageSource]
attr_accessor :source
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@content = args[:content] if args.key?(:content)
@source = args[:source] if args.key?(:source)
end
end
# If an image was produced from a file (e.g. a PDF), this message gives
# information about the source of that image.
class GoogleCloudVisionV1p2beta1ImageAnnotationContext
include Google::Apis::Core::Hashable
# If the file was a PDF or TIFF, this field gives the page number within the
# file used to produce the image.
# Corresponds to the JSON property `pageNumber`
# @return [Fixnum]
attr_accessor :page_number
# The URI of the file used to produce the image.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@page_number = args[:page_number] if args.key?(:page_number)
@uri = args[:uri] if args.key?(:uri)
end
end
# Image context and/or feature-specific parameters.
class GoogleCloudVisionV1p2beta1ImageContext
include Google::Apis::Core::Hashable
# Parameters for crop hints annotation request.
# Corresponds to the JSON property `cropHintsParams`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1CropHintsParams]
attr_accessor :crop_hints_params
# List of languages to use for TEXT_DETECTION. In most cases, an empty value
# yields the best results since it enables automatic language detection. For
# languages based on the Latin alphabet, setting `language_hints` is not needed.
# In rare cases, when the language of the text in the image is known, setting a
# hint will help get better results (although it will be a significant hindrance
# if the hint is wrong). Text detection returns an error if one or more of the
# specified languages is not one of the [supported languages](https://cloud.
# google.com/vision/docs/languages).
# Corresponds to the JSON property `languageHints`
# @return [Array<String>]
attr_accessor :language_hints
# Rectangle determined by min and max `LatLng` pairs.
# Corresponds to the JSON property `latLongRect`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1LatLongRect]
attr_accessor :lat_long_rect
# Parameters for a product search request.
# Corresponds to the JSON property `productSearchParams`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1ProductSearchParams]
attr_accessor :product_search_params
# Parameters for text detections. This is used to control TEXT_DETECTION and
# DOCUMENT_TEXT_DETECTION features.
# Corresponds to the JSON property `textDetectionParams`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1TextDetectionParams]
attr_accessor :text_detection_params
# Parameters for web detection request.
# Corresponds to the JSON property `webDetectionParams`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1WebDetectionParams]
attr_accessor :web_detection_params
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@crop_hints_params = args[:crop_hints_params] if args.key?(:crop_hints_params)
@language_hints = args[:language_hints] if args.key?(:language_hints)
@lat_long_rect = args[:lat_long_rect] if args.key?(:lat_long_rect)
@product_search_params = args[:product_search_params] if args.key?(:product_search_params)
@text_detection_params = args[:text_detection_params] if args.key?(:text_detection_params)
@web_detection_params = args[:web_detection_params] if args.key?(:web_detection_params)
end
end
# Stores image properties, such as dominant colors.
class GoogleCloudVisionV1p2beta1ImageProperties
include Google::Apis::Core::Hashable
# Set of dominant colors and their corresponding scores.
# Corresponds to the JSON property `dominantColors`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1DominantColorsAnnotation]
attr_accessor :dominant_colors
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@dominant_colors = args[:dominant_colors] if args.key?(:dominant_colors)
end
end
# External image source (Google Cloud Storage or web URL image location).
class GoogleCloudVisionV1p2beta1ImageSource
include Google::Apis::Core::Hashable
# **Use `image_uri` instead.** The Google Cloud Storage URI of the form `gs://
# bucket_name/object_name`. Object versioning is not supported. See [Google
# Cloud Storage Request URIs](https://cloud.google.com/storage/docs/reference-
# uris) for more info.
# Corresponds to the JSON property `gcsImageUri`
# @return [String]
attr_accessor :gcs_image_uri
# The URI of the source image. Can be either: 1. A Google Cloud Storage URI of
# the form `gs://bucket_name/object_name`. Object versioning is not supported.
# See [Google Cloud Storage Request URIs](https://cloud.google.com/storage/docs/
# reference-uris) for more info. 2. A publicly-accessible image HTTP/HTTPS URL.
# When fetching images from HTTP/HTTPS URLs, Google cannot guarantee that the
# request will be completed. Your request may fail if the specified host denies
# the request (e.g. due to request throttling or DOS prevention), or if Google
# throttles requests to the site for abuse prevention. You should not depend on
# externally-hosted images for production applications. When both `gcs_image_uri`
# and `image_uri` are specified, `image_uri` takes precedence.
# Corresponds to the JSON property `imageUri`
# @return [String]
attr_accessor :image_uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@gcs_image_uri = args[:gcs_image_uri] if args.key?(:gcs_image_uri)
@image_uri = args[:image_uri] if args.key?(:image_uri)
end
end
# The desired input location and metadata.
class GoogleCloudVisionV1p2beta1InputConfig
include Google::Apis::Core::Hashable
# File content, represented as a stream of bytes. Note: As with all `bytes`
# fields, protobuffers use a pure binary representation, whereas JSON
# representations use base64. Currently, this field only works for
# BatchAnnotateFiles requests. It does not work for AsyncBatchAnnotateFiles
# requests.
# Corresponds to the JSON property `content`
# NOTE: Values are automatically base64 encoded/decoded in the client library.
# @return [String]
attr_accessor :content
# The Google Cloud Storage location where the input will be read from.
# Corresponds to the JSON property `gcsSource`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1GcsSource]
attr_accessor :gcs_source
# The type of the file. Currently only "application/pdf", "image/tiff" and "
# image/gif" are supported. Wildcards are not supported.
# Corresponds to the JSON property `mimeType`
# @return [String]
attr_accessor :mime_type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@content = args[:content] if args.key?(:content)
@gcs_source = args[:gcs_source] if args.key?(:gcs_source)
@mime_type = args[:mime_type] if args.key?(:mime_type)
end
end
# Rectangle determined by min and max `LatLng` pairs.
class GoogleCloudVisionV1p2beta1LatLongRect
include Google::Apis::Core::Hashable
# An object that represents a latitude/longitude pair. This is expressed as a
# pair of doubles to represent degrees latitude and degrees longitude. Unless
# specified otherwise, this must conform to the WGS84 standard. Values must be
# within normalized ranges.
# Corresponds to the JSON property `maxLatLng`
# @return [Google::Apis::VisionV1p2beta1::LatLng]
attr_accessor :max_lat_lng
# An object that represents a latitude/longitude pair. This is expressed as a
# pair of doubles to represent degrees latitude and degrees longitude. Unless
# specified otherwise, this must conform to the WGS84 standard. Values must be
# within normalized ranges.
# Corresponds to the JSON property `minLatLng`
# @return [Google::Apis::VisionV1p2beta1::LatLng]
attr_accessor :min_lat_lng
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@max_lat_lng = args[:max_lat_lng] if args.key?(:max_lat_lng)
@min_lat_lng = args[:min_lat_lng] if args.key?(:min_lat_lng)
end
end
# Set of detected objects with bounding boxes.
class GoogleCloudVisionV1p2beta1LocalizedObjectAnnotation
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1BoundingPoly]
attr_accessor :bounding_poly
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more information,
# see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Object ID that should align with EntityAnnotation mid.
# Corresponds to the JSON property `mid`
# @return [String]
attr_accessor :mid
# Object name, expressed in its `language_code` language.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Score of the result. Range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@language_code = args[:language_code] if args.key?(:language_code)
@mid = args[:mid] if args.key?(:mid)
@name = args[:name] if args.key?(:name)
@score = args[:score] if args.key?(:score)
end
end
# Detected entity location information.
class GoogleCloudVisionV1p2beta1LocationInfo
include Google::Apis::Core::Hashable
# An object that represents a latitude/longitude pair. This is expressed as a
# pair of doubles to represent degrees latitude and degrees longitude. Unless
# specified otherwise, this must conform to the WGS84 standard. Values must be
# within normalized ranges.
# Corresponds to the JSON property `latLng`
# @return [Google::Apis::VisionV1p2beta1::LatLng]
attr_accessor :lat_lng
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@lat_lng = args[:lat_lng] if args.key?(:lat_lng)
end
end
# A vertex represents a 2D point in the image. NOTE: the normalized vertex
# coordinates are relative to the original image and range from 0 to 1.
class GoogleCloudVisionV1p2beta1NormalizedVertex
include Google::Apis::Core::Hashable
# X coordinate.
# Corresponds to the JSON property `x`
# @return [Float]
attr_accessor :x
# Y coordinate.
# Corresponds to the JSON property `y`
# @return [Float]
attr_accessor :y
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@x = args[:x] if args.key?(:x)
@y = args[:y] if args.key?(:y)
end
end
# Contains metadata for the BatchAnnotateImages operation.
class GoogleCloudVisionV1p2beta1OperationMetadata
include Google::Apis::Core::Hashable
# The time when the batch request was received.
# Corresponds to the JSON property `createTime`
# @return [String]
attr_accessor :create_time
# Current state of the batch operation.
# Corresponds to the JSON property `state`
# @return [String]
attr_accessor :state
# The time when the operation result was last updated.
# Corresponds to the JSON property `updateTime`
# @return [String]
attr_accessor :update_time
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@create_time = args[:create_time] if args.key?(:create_time)
@state = args[:state] if args.key?(:state)
@update_time = args[:update_time] if args.key?(:update_time)
end
end
# The desired output location and metadata.
class GoogleCloudVisionV1p2beta1OutputConfig
include Google::Apis::Core::Hashable
# The max number of response protos to put into each output JSON file on Google
# Cloud Storage. The valid range is [1, 100]. If not specified, the default
# value is 20. For example, for one pdf file with 100 pages, 100 response protos
# will be generated. If `batch_size` = 20, then 5 json files each containing 20
# response protos will be written under the prefix `gcs_destination`.`uri`.
# Currently, batch_size only applies to GcsDestination, with potential future
# support for other output configurations.
# Corresponds to the JSON property `batchSize`
# @return [Fixnum]
attr_accessor :batch_size
# The Google Cloud Storage location where the output will be written to.
# Corresponds to the JSON property `gcsDestination`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1GcsDestination]
attr_accessor :gcs_destination
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@batch_size = args[:batch_size] if args.key?(:batch_size)
@gcs_destination = args[:gcs_destination] if args.key?(:gcs_destination)
end
end
# Detected page from OCR.
class GoogleCloudVisionV1p2beta1Page
include Google::Apis::Core::Hashable
# List of blocks of text, images etc on this page.
# Corresponds to the JSON property `blocks`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1Block>]
attr_accessor :blocks
# Confidence of the OCR results on the page. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Page height. For PDFs the unit is points. For images (including TIFFs) the
# unit is pixels.
# Corresponds to the JSON property `height`
# @return [Fixnum]
attr_accessor :height
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1TextAnnotationTextProperty]
attr_accessor :property
# Page width. For PDFs the unit is points. For images (including TIFFs) the unit
# is pixels.
# Corresponds to the JSON property `width`
# @return [Fixnum]
attr_accessor :width
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@blocks = args[:blocks] if args.key?(:blocks)
@confidence = args[:confidence] if args.key?(:confidence)
@height = args[:height] if args.key?(:height)
@property = args[:property] if args.key?(:property)
@width = args[:width] if args.key?(:width)
end
end
# Structural unit of text representing a number of words in certain order.
class GoogleCloudVisionV1p2beta1Paragraph
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results for the paragraph. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1TextAnnotationTextProperty]
attr_accessor :property
# List of all words in this paragraph.
# Corresponds to the JSON property `words`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1Word>]
attr_accessor :words
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@property = args[:property] if args.key?(:property)
@words = args[:words] if args.key?(:words)
end
end
# A 3D position in the image, used primarily for Face detection landmarks. A
# valid Position must have both x and y coordinates. The position coordinates
# are in the same scale as the original image.
class GoogleCloudVisionV1p2beta1Position
include Google::Apis::Core::Hashable
# X coordinate.
# Corresponds to the JSON property `x`
# @return [Float]
attr_accessor :x
# Y coordinate.
# Corresponds to the JSON property `y`
# @return [Float]
attr_accessor :y
# Z coordinate (or depth).
# Corresponds to the JSON property `z`
# @return [Float]
attr_accessor :z
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@x = args[:x] if args.key?(:x)
@y = args[:y] if args.key?(:y)
@z = args[:z] if args.key?(:z)
end
end
# A Product contains ReferenceImages.
class GoogleCloudVisionV1p2beta1Product
include Google::Apis::Core::Hashable
# User-provided metadata to be stored with this product. Must be at most 4096
# characters long.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The user-provided name for this Product. Must not be empty. Must be at most
# 4096 characters long.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# The resource name of the product. Format is: `projects/PROJECT_ID/locations/
# LOC_ID/products/PRODUCT_ID`. This field is ignored when creating a product.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Immutable. The category for the product identified by the reference image.
# This should be one of "homegoods-v2", "apparel-v2", "toys-v2", "packagedgoods-
# v1" or "general-v1". The legacy categories "homegoods", "apparel", and "toys"
# are still supported, but these should not be used for new products.
# Corresponds to the JSON property `productCategory`
# @return [String]
attr_accessor :product_category
# Key-value pairs that can be attached to a product. At query time, constraints
# can be specified based on the product_labels. Note that integer values can be
# provided as strings, e.g. "1199". Only strings with integer values can match a
# range-based restriction which is to be supported soon. Multiple values can be
# assigned to the same key. One product may have up to 500 product_labels.
# Notice that the total number of distinct product_labels over all products in
# one ProductSet cannot exceed 1M, otherwise the product search pipeline will
# refuse to work for that ProductSet.
# Corresponds to the JSON property `productLabels`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1ProductKeyValue>]
attr_accessor :product_labels
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@display_name = args[:display_name] if args.key?(:display_name)
@name = args[:name] if args.key?(:name)
@product_category = args[:product_category] if args.key?(:product_category)
@product_labels = args[:product_labels] if args.key?(:product_labels)
end
end
# A product label represented as a key-value pair.
class GoogleCloudVisionV1p2beta1ProductKeyValue
include Google::Apis::Core::Hashable
# The key of the label attached to the product. Cannot be empty and cannot
# exceed 128 bytes.
# Corresponds to the JSON property `key`
# @return [String]
attr_accessor :key
# The value of the label attached to the product. Cannot be empty and cannot
# exceed 128 bytes.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@key = args[:key] if args.key?(:key)
@value = args[:value] if args.key?(:value)
end
end
# Parameters for a product search request.
class GoogleCloudVisionV1p2beta1ProductSearchParams
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1BoundingPoly]
attr_accessor :bounding_poly
# The filtering expression. This can be used to restrict search results based on
# Product labels. We currently support an AND of OR of key-value expressions,
# where each expression within an OR must have the same key. An '=' should be
# used to connect the key and value. For example, "(color = red OR color = blue)
# AND brand = Google" is acceptable, but "(color = red OR brand = Google)" is
# not acceptable. "color: red" is not acceptable because it uses a ':' instead
# of an '='.
# Corresponds to the JSON property `filter`
# @return [String]
attr_accessor :filter
# The list of product categories to search in. Currently, we only consider the
# first category, and either "homegoods-v2", "apparel-v2", "toys-v2", "
# packagedgoods-v1", or "general-v1" should be specified. The legacy categories "
# homegoods", "apparel", and "toys" are still supported but will be deprecated.
# For new products, please use "homegoods-v2", "apparel-v2", or "toys-v2" for
# better product search accuracy. It is recommended to migrate existing products
# to these categories as well.
# Corresponds to the JSON property `productCategories`
# @return [Array<String>]
attr_accessor :product_categories
# The resource name of a ProductSet to be searched for similar images. Format is:
# `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`.
# Corresponds to the JSON property `productSet`
# @return [String]
attr_accessor :product_set
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@filter = args[:filter] if args.key?(:filter)
@product_categories = args[:product_categories] if args.key?(:product_categories)
@product_set = args[:product_set] if args.key?(:product_set)
end
end
# Results for a product search request.
class GoogleCloudVisionV1p2beta1ProductSearchResults
include Google::Apis::Core::Hashable
# Timestamp of the index which provided these results. Products added to the
# product set and products removed from the product set after this time are not
# reflected in the current results.
# Corresponds to the JSON property `indexTime`
# @return [String]
attr_accessor :index_time
# List of results grouped by products detected in the query image. Each entry
# corresponds to one bounding polygon in the query image, and contains the
# matching products specific to that region. There may be duplicate product
# matches in the union of all the per-product results.
# Corresponds to the JSON property `productGroupedResults`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1ProductSearchResultsGroupedResult>]
attr_accessor :product_grouped_results
# List of results, one for each product match.
# Corresponds to the JSON property `results`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1ProductSearchResultsResult>]
attr_accessor :results
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@index_time = args[:index_time] if args.key?(:index_time)
@product_grouped_results = args[:product_grouped_results] if args.key?(:product_grouped_results)
@results = args[:results] if args.key?(:results)
end
end
# Information about the products similar to a single product in a query image.
class GoogleCloudVisionV1p2beta1ProductSearchResultsGroupedResult
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1BoundingPoly]
attr_accessor :bounding_poly
# List of generic predictions for the object in the bounding box.
# Corresponds to the JSON property `objectAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1ProductSearchResultsObjectAnnotation>]
attr_accessor :object_annotations
# List of results, one for each product match.
# Corresponds to the JSON property `results`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1ProductSearchResultsResult>]
attr_accessor :results
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@object_annotations = args[:object_annotations] if args.key?(:object_annotations)
@results = args[:results] if args.key?(:results)
end
end
# Prediction for what the object in the bounding box is.
class GoogleCloudVisionV1p2beta1ProductSearchResultsObjectAnnotation
include Google::Apis::Core::Hashable
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more information,
# see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Object ID that should align with EntityAnnotation mid.
# Corresponds to the JSON property `mid`
# @return [String]
attr_accessor :mid
# Object name, expressed in its `language_code` language.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Score of the result. Range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@language_code = args[:language_code] if args.key?(:language_code)
@mid = args[:mid] if args.key?(:mid)
@name = args[:name] if args.key?(:name)
@score = args[:score] if args.key?(:score)
end
end
# Information about a product.
class GoogleCloudVisionV1p2beta1ProductSearchResultsResult
include Google::Apis::Core::Hashable
# The resource name of the image from the product that is the closest match to
# the query.
# Corresponds to the JSON property `image`
# @return [String]
attr_accessor :image
# A Product contains ReferenceImages.
# Corresponds to the JSON property `product`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1Product]
attr_accessor :product
# A confidence level on the match, ranging from 0 (no confidence) to 1 (full
# confidence).
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@image = args[:image] if args.key?(:image)
@product = args[:product] if args.key?(:product)
@score = args[:score] if args.key?(:score)
end
end
# A `Property` consists of a user-supplied name/value pair.
class GoogleCloudVisionV1p2beta1Property
include Google::Apis::Core::Hashable
# Name of the property.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Value of numeric properties.
# Corresponds to the JSON property `uint64Value`
# @return [Fixnum]
attr_accessor :uint64_value
# Value of the property.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@name = args[:name] if args.key?(:name)
@uint64_value = args[:uint64_value] if args.key?(:uint64_value)
@value = args[:value] if args.key?(:value)
end
end
# Set of features pertaining to the image, computed by computer vision methods
# over safe-search verticals (for example, adult, spoof, medical, violence).
class GoogleCloudVisionV1p2beta1SafeSearchAnnotation
include Google::Apis::Core::Hashable
# Represents the adult content likelihood for the image. Adult content may
# contain elements such as nudity, pornographic images or cartoons, or sexual
# activities.
# Corresponds to the JSON property `adult`
# @return [String]
attr_accessor :adult
# Likelihood that this is a medical image.
# Corresponds to the JSON property `medical`
# @return [String]
attr_accessor :medical
# Likelihood that the request image contains racy content. Racy content may
# include (but is not limited to) skimpy or sheer clothing, strategically
# covered nudity, lewd or provocative poses, or close-ups of sensitive body
# areas.
# Corresponds to the JSON property `racy`
# @return [String]
attr_accessor :racy
# Spoof likelihood. The likelihood that an modification was made to the image's
# canonical version to make it appear funny or offensive.
# Corresponds to the JSON property `spoof`
# @return [String]
attr_accessor :spoof
# Likelihood that this image contains violent content.
# Corresponds to the JSON property `violence`
# @return [String]
attr_accessor :violence
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@adult = args[:adult] if args.key?(:adult)
@medical = args[:medical] if args.key?(:medical)
@racy = args[:racy] if args.key?(:racy)
@spoof = args[:spoof] if args.key?(:spoof)
@violence = args[:violence] if args.key?(:violence)
end
end
# A single symbol representation.
class GoogleCloudVisionV1p2beta1Symbol
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results for the symbol. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1TextAnnotationTextProperty]
attr_accessor :property
# The actual UTF-8 representation of the symbol.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@property = args[:property] if args.key?(:property)
@text = args[:text] if args.key?(:text)
end
end
# TextAnnotation contains a structured representation of OCR extracted text. The
# hierarchy of an OCR extracted text structure is like this: TextAnnotation ->
# Page -> Block -> Paragraph -> Word -> Symbol Each structural component,
# starting from Page, may further have their own properties. Properties describe
# detected languages, breaks etc.. Please refer to the TextAnnotation.
# TextProperty message definition below for more detail.
class GoogleCloudVisionV1p2beta1TextAnnotation
include Google::Apis::Core::Hashable
# List of pages detected by OCR.
# Corresponds to the JSON property `pages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1Page>]
attr_accessor :pages
# UTF-8 text detected on the pages.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@pages = args[:pages] if args.key?(:pages)
@text = args[:text] if args.key?(:text)
end
end
# Detected start or end of a structural component.
class GoogleCloudVisionV1p2beta1TextAnnotationDetectedBreak
include Google::Apis::Core::Hashable
# True if break prepends the element.
# Corresponds to the JSON property `isPrefix`
# @return [Boolean]
attr_accessor :is_prefix
alias_method :is_prefix?, :is_prefix
# Detected break type.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@is_prefix = args[:is_prefix] if args.key?(:is_prefix)
@type = args[:type] if args.key?(:type)
end
end
# Detected language for a structural component.
class GoogleCloudVisionV1p2beta1TextAnnotationDetectedLanguage
include Google::Apis::Core::Hashable
# Confidence of detected language. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more information,
# see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@confidence = args[:confidence] if args.key?(:confidence)
@language_code = args[:language_code] if args.key?(:language_code)
end
end
# Additional information detected on the structural component.
class GoogleCloudVisionV1p2beta1TextAnnotationTextProperty
include Google::Apis::Core::Hashable
# Detected start or end of a structural component.
# Corresponds to the JSON property `detectedBreak`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1TextAnnotationDetectedBreak]
attr_accessor :detected_break
# A list of detected languages together with confidence.
# Corresponds to the JSON property `detectedLanguages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1TextAnnotationDetectedLanguage>]
attr_accessor :detected_languages
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@detected_break = args[:detected_break] if args.key?(:detected_break)
@detected_languages = args[:detected_languages] if args.key?(:detected_languages)
end
end
# Parameters for text detections. This is used to control TEXT_DETECTION and
# DOCUMENT_TEXT_DETECTION features.
class GoogleCloudVisionV1p2beta1TextDetectionParams
include Google::Apis::Core::Hashable
# By default, Cloud Vision API only includes confidence score for
# DOCUMENT_TEXT_DETECTION result. Set the flag to true to include confidence
# score for TEXT_DETECTION as well.
# Corresponds to the JSON property `enableTextDetectionConfidenceScore`
# @return [Boolean]
attr_accessor :enable_text_detection_confidence_score
alias_method :enable_text_detection_confidence_score?, :enable_text_detection_confidence_score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@enable_text_detection_confidence_score = args[:enable_text_detection_confidence_score] if args.key?(:enable_text_detection_confidence_score)
end
end
# A vertex represents a 2D point in the image. NOTE: the vertex coordinates are
# in the same scale as the original image.
class GoogleCloudVisionV1p2beta1Vertex
include Google::Apis::Core::Hashable
# X coordinate.
# Corresponds to the JSON property `x`
# @return [Fixnum]
attr_accessor :x
# Y coordinate.
# Corresponds to the JSON property `y`
# @return [Fixnum]
attr_accessor :y
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@x = args[:x] if args.key?(:x)
@y = args[:y] if args.key?(:y)
end
end
# Relevant information for the image from the Internet.
class GoogleCloudVisionV1p2beta1WebDetection
include Google::Apis::Core::Hashable
# The service's best guess as to the topic of the request image. Inferred from
# similar images on the open web.
# Corresponds to the JSON property `bestGuessLabels`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1WebDetectionWebLabel>]
attr_accessor :best_guess_labels
# Fully matching images from the Internet. Can include resized copies of the
# query image.
# Corresponds to the JSON property `fullMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1WebDetectionWebImage>]
attr_accessor :full_matching_images
# Web pages containing the matching images from the Internet.
# Corresponds to the JSON property `pagesWithMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1WebDetectionWebPage>]
attr_accessor :pages_with_matching_images
# Partial matching images from the Internet. Those images are similar enough to
# share some key-point features. For example an original image will likely have
# partial matching for its crops.
# Corresponds to the JSON property `partialMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1WebDetectionWebImage>]
attr_accessor :partial_matching_images
# The visually similar image results.
# Corresponds to the JSON property `visuallySimilarImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1WebDetectionWebImage>]
attr_accessor :visually_similar_images
# Deduced entities from similar images on the Internet.
# Corresponds to the JSON property `webEntities`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1WebDetectionWebEntity>]
attr_accessor :web_entities
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@best_guess_labels = args[:best_guess_labels] if args.key?(:best_guess_labels)
@full_matching_images = args[:full_matching_images] if args.key?(:full_matching_images)
@pages_with_matching_images = args[:pages_with_matching_images] if args.key?(:pages_with_matching_images)
@partial_matching_images = args[:partial_matching_images] if args.key?(:partial_matching_images)
@visually_similar_images = args[:visually_similar_images] if args.key?(:visually_similar_images)
@web_entities = args[:web_entities] if args.key?(:web_entities)
end
end
# Parameters for web detection request.
class GoogleCloudVisionV1p2beta1WebDetectionParams
include Google::Apis::Core::Hashable
# Whether to include results derived from the geo information in the image.
# Corresponds to the JSON property `includeGeoResults`
# @return [Boolean]
attr_accessor :include_geo_results
alias_method :include_geo_results?, :include_geo_results
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@include_geo_results = args[:include_geo_results] if args.key?(:include_geo_results)
end
end
# Entity deduced from similar images on the Internet.
class GoogleCloudVisionV1p2beta1WebDetectionWebEntity
include Google::Apis::Core::Hashable
# Canonical description of the entity, in English.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# Opaque entity ID.
# Corresponds to the JSON property `entityId`
# @return [String]
attr_accessor :entity_id
# Overall relevancy score for the entity. Not normalized and not comparable
# across different image queries.
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@entity_id = args[:entity_id] if args.key?(:entity_id)
@score = args[:score] if args.key?(:score)
end
end
# Metadata for online images.
class GoogleCloudVisionV1p2beta1WebDetectionWebImage
include Google::Apis::Core::Hashable
# (Deprecated) Overall relevancy score for the image.
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
# The result image URL.
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@score = args[:score] if args.key?(:score)
@url = args[:url] if args.key?(:url)
end
end
# Label to provide extra metadata for the web detection.
class GoogleCloudVisionV1p2beta1WebDetectionWebLabel
include Google::Apis::Core::Hashable
# Label for extra metadata.
# Corresponds to the JSON property `label`
# @return [String]
attr_accessor :label
# The BCP-47 language code for `label`, such as "en-US" or "sr-Latn". For more
# information, see http://www.unicode.org/reports/tr35/#
# Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@label = args[:label] if args.key?(:label)
@language_code = args[:language_code] if args.key?(:language_code)
end
end
# Metadata for web pages.
class GoogleCloudVisionV1p2beta1WebDetectionWebPage
include Google::Apis::Core::Hashable
# Fully matching images on the page. Can include resized copies of the query
# image.
# Corresponds to the JSON property `fullMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1WebDetectionWebImage>]
attr_accessor :full_matching_images
# Title for the web page, may contain HTML markups.
# Corresponds to the JSON property `pageTitle`
# @return [String]
attr_accessor :page_title
# Partial matching images on the page. Those images are similar enough to share
# some key-point features. For example an original image will likely have
# partial matching for its crops.
# Corresponds to the JSON property `partialMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1WebDetectionWebImage>]
attr_accessor :partial_matching_images
# (Deprecated) Overall relevancy score for the web page.
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
# The result web page URL.
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@full_matching_images = args[:full_matching_images] if args.key?(:full_matching_images)
@page_title = args[:page_title] if args.key?(:page_title)
@partial_matching_images = args[:partial_matching_images] if args.key?(:partial_matching_images)
@score = args[:score] if args.key?(:score)
@url = args[:url] if args.key?(:url)
end
end
# A word representation.
class GoogleCloudVisionV1p2beta1Word
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results for the word. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1TextAnnotationTextProperty]
attr_accessor :property
# List of symbols in the word. The order of the symbols follows the natural
# reading order.
# Corresponds to the JSON property `symbols`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p2beta1Symbol>]
attr_accessor :symbols
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@property = args[:property] if args.key?(:property)
@symbols = args[:symbols] if args.key?(:symbols)
end
end
# Response to a single file annotation request. A file may contain one or more
# images, which individually have their own responses.
class GoogleCloudVisionV1p3beta1AnnotateFileResponse
include Google::Apis::Core::Hashable
# The `Status` type defines a logical error model that is suitable for different
# programming environments, including REST APIs and RPC APIs. It is used by [
# gRPC](https://github.com/grpc). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `error`
# @return [Google::Apis::VisionV1p2beta1::Status]
attr_accessor :error
# The desired input location and metadata.
# Corresponds to the JSON property `inputConfig`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1InputConfig]
attr_accessor :input_config
# Individual responses to images found within the file. This field will be empty
# if the `error` field is set.
# Corresponds to the JSON property `responses`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1AnnotateImageResponse>]
attr_accessor :responses
# This field gives the total number of pages in the file.
# Corresponds to the JSON property `totalPages`
# @return [Fixnum]
attr_accessor :total_pages
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@error = args[:error] if args.key?(:error)
@input_config = args[:input_config] if args.key?(:input_config)
@responses = args[:responses] if args.key?(:responses)
@total_pages = args[:total_pages] if args.key?(:total_pages)
end
end
# Response to an image annotation request.
class GoogleCloudVisionV1p3beta1AnnotateImageResponse
include Google::Apis::Core::Hashable
# If an image was produced from a file (e.g. a PDF), this message gives
# information about the source of that image.
# Corresponds to the JSON property `context`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1ImageAnnotationContext]
attr_accessor :context
# Set of crop hints that are used to generate new crops when serving images.
# Corresponds to the JSON property `cropHintsAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1CropHintsAnnotation]
attr_accessor :crop_hints_annotation
# The `Status` type defines a logical error model that is suitable for different
# programming environments, including REST APIs and RPC APIs. It is used by [
# gRPC](https://github.com/grpc). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `error`
# @return [Google::Apis::VisionV1p2beta1::Status]
attr_accessor :error
# If present, face detection has completed successfully.
# Corresponds to the JSON property `faceAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1FaceAnnotation>]
attr_accessor :face_annotations
# TextAnnotation contains a structured representation of OCR extracted text. The
# hierarchy of an OCR extracted text structure is like this: TextAnnotation ->
# Page -> Block -> Paragraph -> Word -> Symbol Each structural component,
# starting from Page, may further have their own properties. Properties describe
# detected languages, breaks etc.. Please refer to the TextAnnotation.
# TextProperty message definition below for more detail.
# Corresponds to the JSON property `fullTextAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1TextAnnotation]
attr_accessor :full_text_annotation
# Stores image properties, such as dominant colors.
# Corresponds to the JSON property `imagePropertiesAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1ImageProperties]
attr_accessor :image_properties_annotation
# If present, label detection has completed successfully.
# Corresponds to the JSON property `labelAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1EntityAnnotation>]
attr_accessor :label_annotations
# If present, landmark detection has completed successfully.
# Corresponds to the JSON property `landmarkAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1EntityAnnotation>]
attr_accessor :landmark_annotations
# If present, localized object detection has completed successfully. This will
# be sorted descending by confidence score.
# Corresponds to the JSON property `localizedObjectAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1LocalizedObjectAnnotation>]
attr_accessor :localized_object_annotations
# If present, logo detection has completed successfully.
# Corresponds to the JSON property `logoAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1EntityAnnotation>]
attr_accessor :logo_annotations
# Results for a product search request.
# Corresponds to the JSON property `productSearchResults`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1ProductSearchResults]
attr_accessor :product_search_results
# Set of features pertaining to the image, computed by computer vision methods
# over safe-search verticals (for example, adult, spoof, medical, violence).
# Corresponds to the JSON property `safeSearchAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1SafeSearchAnnotation]
attr_accessor :safe_search_annotation
# If present, text (OCR) detection has completed successfully.
# Corresponds to the JSON property `textAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1EntityAnnotation>]
attr_accessor :text_annotations
# Relevant information for the image from the Internet.
# Corresponds to the JSON property `webDetection`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1WebDetection]
attr_accessor :web_detection
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@context = args[:context] if args.key?(:context)
@crop_hints_annotation = args[:crop_hints_annotation] if args.key?(:crop_hints_annotation)
@error = args[:error] if args.key?(:error)
@face_annotations = args[:face_annotations] if args.key?(:face_annotations)
@full_text_annotation = args[:full_text_annotation] if args.key?(:full_text_annotation)
@image_properties_annotation = args[:image_properties_annotation] if args.key?(:image_properties_annotation)
@label_annotations = args[:label_annotations] if args.key?(:label_annotations)
@landmark_annotations = args[:landmark_annotations] if args.key?(:landmark_annotations)
@localized_object_annotations = args[:localized_object_annotations] if args.key?(:localized_object_annotations)
@logo_annotations = args[:logo_annotations] if args.key?(:logo_annotations)
@product_search_results = args[:product_search_results] if args.key?(:product_search_results)
@safe_search_annotation = args[:safe_search_annotation] if args.key?(:safe_search_annotation)
@text_annotations = args[:text_annotations] if args.key?(:text_annotations)
@web_detection = args[:web_detection] if args.key?(:web_detection)
end
end
# The response for a single offline file annotation request.
class GoogleCloudVisionV1p3beta1AsyncAnnotateFileResponse
include Google::Apis::Core::Hashable
# The desired output location and metadata.
# Corresponds to the JSON property `outputConfig`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1OutputConfig]
attr_accessor :output_config
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@output_config = args[:output_config] if args.key?(:output_config)
end
end
# Response to an async batch file annotation request.
class GoogleCloudVisionV1p3beta1AsyncBatchAnnotateFilesResponse
include Google::Apis::Core::Hashable
# The list of file annotation responses, one for each request in
# AsyncBatchAnnotateFilesRequest.
# Corresponds to the JSON property `responses`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1AsyncAnnotateFileResponse>]
attr_accessor :responses
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@responses = args[:responses] if args.key?(:responses)
end
end
# Metadata for the batch operations such as the current state. This is included
# in the `metadata` field of the `Operation` returned by the `GetOperation` call
# of the `google::longrunning::Operations` service.
class GoogleCloudVisionV1p3beta1BatchOperationMetadata
include Google::Apis::Core::Hashable
# The time when the batch request is finished and google.longrunning.Operation.
# done is set to true.
# Corresponds to the JSON property `endTime`
# @return [String]
attr_accessor :end_time
# The current state of the batch operation.
# Corresponds to the JSON property `state`
# @return [String]
attr_accessor :state
# The time when the batch request was submitted to the server.
# Corresponds to the JSON property `submitTime`
# @return [String]
attr_accessor :submit_time
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@end_time = args[:end_time] if args.key?(:end_time)
@state = args[:state] if args.key?(:state)
@submit_time = args[:submit_time] if args.key?(:submit_time)
end
end
# Logical element on the page.
class GoogleCloudVisionV1p3beta1Block
include Google::Apis::Core::Hashable
# Detected block type (text, image etc) for this block.
# Corresponds to the JSON property `blockType`
# @return [String]
attr_accessor :block_type
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results on the block. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# List of paragraphs in this block (if this blocks is of type text).
# Corresponds to the JSON property `paragraphs`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1Paragraph>]
attr_accessor :paragraphs
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1TextAnnotationTextProperty]
attr_accessor :property
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@block_type = args[:block_type] if args.key?(:block_type)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@paragraphs = args[:paragraphs] if args.key?(:paragraphs)
@property = args[:property] if args.key?(:property)
end
end
# A bounding polygon for the detected image annotation.
class GoogleCloudVisionV1p3beta1BoundingPoly
include Google::Apis::Core::Hashable
# The bounding polygon normalized vertices.
# Corresponds to the JSON property `normalizedVertices`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1NormalizedVertex>]
attr_accessor :normalized_vertices
# The bounding polygon vertices.
# Corresponds to the JSON property `vertices`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1Vertex>]
attr_accessor :vertices
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@normalized_vertices = args[:normalized_vertices] if args.key?(:normalized_vertices)
@vertices = args[:vertices] if args.key?(:vertices)
end
end
# Color information consists of RGB channels, score, and the fraction of the
# image that the color occupies in the image.
class GoogleCloudVisionV1p3beta1ColorInfo
include Google::Apis::Core::Hashable
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation can
# be trivially provided to the constructor of "java.awt.Color" in Java; it can
# also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into a
# CSS "rgba()" string in JavaScript, as well. Note: this proto does not carry
# information about the absolute color space that should be used to interpret
# the RGB value (e.g. sRGB, Adobe RGB, DCI-P3, BT.2020, etc.). By default,
# applications SHOULD assume the sRGB color space. Note: when color equality
# needs to be decided, implementations, unless documented otherwise, will treat
# two colors to be equal if all their red, green, blue and alpha values each
# differ by at most 1e-5. Example (Java): import com.google.type.Color; // ...
# public static java.awt.Color fromProto(Color protocolor) ` float alpha =
# protocolor.hasAlpha() ? protocolor.getAlpha().getValue() : 1.0; return new
# java.awt.Color( protocolor.getRed(), protocolor.getGreen(), protocolor.getBlue(
# ), alpha); ` public static Color toProto(java.awt.Color color) ` float red = (
# float) color.getRed(); float green = (float) color.getGreen(); float blue = (
# float) color.getBlue(); float denominator = 255.0; Color.Builder resultBuilder
# = Color .newBuilder() .setRed(red / denominator) .setGreen(green / denominator)
# .setBlue(blue / denominator); int alpha = color.getAlpha(); if (alpha != 255)
# ` result.setAlpha( FloatValue .newBuilder() .setValue(((float) alpha) /
# denominator) .build()); ` return resultBuilder.build(); ` // ... Example (iOS /
# Obj-C): // ... static UIColor* fromProto(Color* protocolor) ` float red = [
# protocolor red]; float green = [protocolor green]; float blue = [protocolor
# blue]; FloatValue* alpha_wrapper = [protocolor alpha]; float alpha = 1.0; if (
# alpha_wrapper != nil) ` alpha = [alpha_wrapper value]; ` return [UIColor
# colorWithRed:red green:green blue:blue alpha:alpha]; ` static Color* toProto(
# UIColor* color) ` CGFloat red, green, blue, alpha; if (![color getRed:&red
# green:&green blue:&blue alpha:&alpha]) ` return nil; ` Color* result = [[Color
# alloc] init]; [result setRed:red]; [result setGreen:green]; [result setBlue:
# blue]; if (alpha <= 0.9999) ` [result setAlpha:floatWrapperWithValue(alpha)]; `
# [result autorelease]; return result; ` // ... Example (JavaScript): // ...
# var protoToCssColor = function(rgb_color) ` var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0; var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255); var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255); if (!('alpha' in rgb_color)) ` return
# rgbToCssColor_(red, green, blue); ` var alphaFrac = rgb_color.alpha.value || 0.
# 0; var rgbParams = [red, green, blue].join(','); return ['rgba(', rgbParams, ',
# ', alphaFrac, ')'].join(''); `; var rgbToCssColor_ = function(red, green, blue)
# ` var rgbNumber = new Number((red << 16) | (green << 8) | blue); var
# hexString = rgbNumber.toString(16); var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#']; for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0'); ` resultBuilder.push(hexString); return resultBuilder.
# join(''); `; // ...
# Corresponds to the JSON property `color`
# @return [Google::Apis::VisionV1p2beta1::Color]
attr_accessor :color
# The fraction of pixels the color occupies in the image. Value in range [0, 1].
# Corresponds to the JSON property `pixelFraction`
# @return [Float]
attr_accessor :pixel_fraction
# Image-specific score for this color. Value in range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@color = args[:color] if args.key?(:color)
@pixel_fraction = args[:pixel_fraction] if args.key?(:pixel_fraction)
@score = args[:score] if args.key?(:score)
end
end
# Single crop hint that is used to generate a new crop when serving an image.
class GoogleCloudVisionV1p3beta1CropHint
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1BoundingPoly]
attr_accessor :bounding_poly
# Confidence of this being a salient region. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Fraction of importance of this salient region with respect to the original
# image.
# Corresponds to the JSON property `importanceFraction`
# @return [Float]
attr_accessor :importance_fraction
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@confidence = args[:confidence] if args.key?(:confidence)
@importance_fraction = args[:importance_fraction] if args.key?(:importance_fraction)
end
end
# Set of crop hints that are used to generate new crops when serving images.
class GoogleCloudVisionV1p3beta1CropHintsAnnotation
include Google::Apis::Core::Hashable
# Crop hint results.
# Corresponds to the JSON property `cropHints`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1CropHint>]
attr_accessor :crop_hints
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@crop_hints = args[:crop_hints] if args.key?(:crop_hints)
end
end
# Set of dominant colors and their corresponding scores.
class GoogleCloudVisionV1p3beta1DominantColorsAnnotation
include Google::Apis::Core::Hashable
# RGB color values with their score and pixel fraction.
# Corresponds to the JSON property `colors`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1ColorInfo>]
attr_accessor :colors
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@colors = args[:colors] if args.key?(:colors)
end
end
# Set of detected entity features.
class GoogleCloudVisionV1p3beta1EntityAnnotation
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1BoundingPoly]
attr_accessor :bounding_poly
# **Deprecated. Use `score` instead.** The accuracy of the entity detection in
# an image. For example, for an image in which the "Eiffel Tower" entity is
# detected, this field represents the confidence that there is a tower in the
# query image. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Entity textual description, expressed in its `locale` language.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The language code for the locale in which the entity textual `description` is
# expressed.
# Corresponds to the JSON property `locale`
# @return [String]
attr_accessor :locale
# The location information for the detected entity. Multiple `LocationInfo`
# elements can be present because one location may indicate the location of the
# scene in the image, and another location may indicate the location of the
# place where the image was taken. Location information is usually present for
# landmarks.
# Corresponds to the JSON property `locations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1LocationInfo>]
attr_accessor :locations
# Opaque entity ID. Some IDs may be available in [Google Knowledge Graph Search
# API](https://developers.google.com/knowledge-graph/).
# Corresponds to the JSON property `mid`
# @return [String]
attr_accessor :mid
# Some entities may have optional user-supplied `Property` (name/value) fields,
# such a score or string that qualifies the entity.
# Corresponds to the JSON property `properties`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1Property>]
attr_accessor :properties
# Overall score of the result. Range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
# The relevancy of the ICA (Image Content Annotation) label to the image. For
# example, the relevancy of "tower" is likely higher to an image containing the
# detected "Eiffel Tower" than to an image containing a detected distant
# towering building, even though the confidence that there is a tower in each
# image may be the same. Range [0, 1].
# Corresponds to the JSON property `topicality`
# @return [Float]
attr_accessor :topicality
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@confidence = args[:confidence] if args.key?(:confidence)
@description = args[:description] if args.key?(:description)
@locale = args[:locale] if args.key?(:locale)
@locations = args[:locations] if args.key?(:locations)
@mid = args[:mid] if args.key?(:mid)
@properties = args[:properties] if args.key?(:properties)
@score = args[:score] if args.key?(:score)
@topicality = args[:topicality] if args.key?(:topicality)
end
end
# A face annotation object contains the results of face detection.
class GoogleCloudVisionV1p3beta1FaceAnnotation
include Google::Apis::Core::Hashable
# Anger likelihood.
# Corresponds to the JSON property `angerLikelihood`
# @return [String]
attr_accessor :anger_likelihood
# Blurred likelihood.
# Corresponds to the JSON property `blurredLikelihood`
# @return [String]
attr_accessor :blurred_likelihood
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1BoundingPoly]
attr_accessor :bounding_poly
# Detection confidence. Range [0, 1].
# Corresponds to the JSON property `detectionConfidence`
# @return [Float]
attr_accessor :detection_confidence
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `fdBoundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1BoundingPoly]
attr_accessor :fd_bounding_poly
# Headwear likelihood.
# Corresponds to the JSON property `headwearLikelihood`
# @return [String]
attr_accessor :headwear_likelihood
# Joy likelihood.
# Corresponds to the JSON property `joyLikelihood`
# @return [String]
attr_accessor :joy_likelihood
# Face landmarking confidence. Range [0, 1].
# Corresponds to the JSON property `landmarkingConfidence`
# @return [Float]
attr_accessor :landmarking_confidence
# Detected face landmarks.
# Corresponds to the JSON property `landmarks`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1FaceAnnotationLandmark>]
attr_accessor :landmarks
# Yaw angle, which indicates the leftward/rightward angle that the face is
# pointing relative to the vertical plane perpendicular to the image. Range [-
# 180,180].
# Corresponds to the JSON property `panAngle`
# @return [Float]
attr_accessor :pan_angle
# Roll angle, which indicates the amount of clockwise/anti-clockwise rotation of
# the face relative to the image vertical about the axis perpendicular to the
# face. Range [-180,180].
# Corresponds to the JSON property `rollAngle`
# @return [Float]
attr_accessor :roll_angle
# Sorrow likelihood.
# Corresponds to the JSON property `sorrowLikelihood`
# @return [String]
attr_accessor :sorrow_likelihood
# Surprise likelihood.
# Corresponds to the JSON property `surpriseLikelihood`
# @return [String]
attr_accessor :surprise_likelihood
# Pitch angle, which indicates the upwards/downwards angle that the face is
# pointing relative to the image's horizontal plane. Range [-180,180].
# Corresponds to the JSON property `tiltAngle`
# @return [Float]
attr_accessor :tilt_angle
# Under-exposed likelihood.
# Corresponds to the JSON property `underExposedLikelihood`
# @return [String]
attr_accessor :under_exposed_likelihood
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@anger_likelihood = args[:anger_likelihood] if args.key?(:anger_likelihood)
@blurred_likelihood = args[:blurred_likelihood] if args.key?(:blurred_likelihood)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@detection_confidence = args[:detection_confidence] if args.key?(:detection_confidence)
@fd_bounding_poly = args[:fd_bounding_poly] if args.key?(:fd_bounding_poly)
@headwear_likelihood = args[:headwear_likelihood] if args.key?(:headwear_likelihood)
@joy_likelihood = args[:joy_likelihood] if args.key?(:joy_likelihood)
@landmarking_confidence = args[:landmarking_confidence] if args.key?(:landmarking_confidence)
@landmarks = args[:landmarks] if args.key?(:landmarks)
@pan_angle = args[:pan_angle] if args.key?(:pan_angle)
@roll_angle = args[:roll_angle] if args.key?(:roll_angle)
@sorrow_likelihood = args[:sorrow_likelihood] if args.key?(:sorrow_likelihood)
@surprise_likelihood = args[:surprise_likelihood] if args.key?(:surprise_likelihood)
@tilt_angle = args[:tilt_angle] if args.key?(:tilt_angle)
@under_exposed_likelihood = args[:under_exposed_likelihood] if args.key?(:under_exposed_likelihood)
end
end
# A face-specific landmark (for example, a face feature).
class GoogleCloudVisionV1p3beta1FaceAnnotationLandmark
include Google::Apis::Core::Hashable
# A 3D position in the image, used primarily for Face detection landmarks. A
# valid Position must have both x and y coordinates. The position coordinates
# are in the same scale as the original image.
# Corresponds to the JSON property `position`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1Position]
attr_accessor :position
# Face landmark type.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@position = args[:position] if args.key?(:position)
@type = args[:type] if args.key?(:type)
end
end
# The Google Cloud Storage location where the output will be written to.
class GoogleCloudVisionV1p3beta1GcsDestination
include Google::Apis::Core::Hashable
# Google Cloud Storage URI prefix where the results will be stored. Results will
# be in JSON format and preceded by its corresponding input URI prefix. This
# field can either represent a gcs file prefix or gcs directory. In either case,
# the uri should be unique because in order to get all of the output files, you
# will need to do a wildcard gcs search on the uri prefix you provide. Examples:
# * File Prefix: gs://bucket-name/here/filenameprefix The output files will be
# created in gs://bucket-name/here/ and the names of the output files will begin
# with "filenameprefix". * Directory Prefix: gs://bucket-name/some/location/ The
# output files will be created in gs://bucket-name/some/location/ and the names
# of the output files could be anything because there was no filename prefix
# specified. If multiple outputs, each response is still AnnotateFileResponse,
# each of which contains some subset of the full list of AnnotateImageResponse.
# Multiple outputs can happen if, for example, the output JSON is too large and
# overflows into multiple sharded files.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@uri = args[:uri] if args.key?(:uri)
end
end
# The Google Cloud Storage location where the input will be read from.
class GoogleCloudVisionV1p3beta1GcsSource
include Google::Apis::Core::Hashable
# Google Cloud Storage URI for the input file. This must only be a Google Cloud
# Storage object. Wildcards are not currently supported.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@uri = args[:uri] if args.key?(:uri)
end
end
# If an image was produced from a file (e.g. a PDF), this message gives
# information about the source of that image.
class GoogleCloudVisionV1p3beta1ImageAnnotationContext
include Google::Apis::Core::Hashable
# If the file was a PDF or TIFF, this field gives the page number within the
# file used to produce the image.
# Corresponds to the JSON property `pageNumber`
# @return [Fixnum]
attr_accessor :page_number
# The URI of the file used to produce the image.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@page_number = args[:page_number] if args.key?(:page_number)
@uri = args[:uri] if args.key?(:uri)
end
end
# Stores image properties, such as dominant colors.
class GoogleCloudVisionV1p3beta1ImageProperties
include Google::Apis::Core::Hashable
# Set of dominant colors and their corresponding scores.
# Corresponds to the JSON property `dominantColors`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1DominantColorsAnnotation]
attr_accessor :dominant_colors
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@dominant_colors = args[:dominant_colors] if args.key?(:dominant_colors)
end
end
# Response message for the `ImportProductSets` method. This message is returned
# by the google.longrunning.Operations.GetOperation method in the returned
# google.longrunning.Operation.response field.
class GoogleCloudVisionV1p3beta1ImportProductSetsResponse
include Google::Apis::Core::Hashable
# The list of reference_images that are imported successfully.
# Corresponds to the JSON property `referenceImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1ReferenceImage>]
attr_accessor :reference_images
# The rpc status for each ImportProductSet request, including both successes and
# errors. The number of statuses here matches the number of lines in the csv
# file, and statuses[i] stores the success or failure status of processing the i-
# th line of the csv, starting from line 0.
# Corresponds to the JSON property `statuses`
# @return [Array<Google::Apis::VisionV1p2beta1::Status>]
attr_accessor :statuses
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@reference_images = args[:reference_images] if args.key?(:reference_images)
@statuses = args[:statuses] if args.key?(:statuses)
end
end
# The desired input location and metadata.
class GoogleCloudVisionV1p3beta1InputConfig
include Google::Apis::Core::Hashable
# File content, represented as a stream of bytes. Note: As with all `bytes`
# fields, protobuffers use a pure binary representation, whereas JSON
# representations use base64. Currently, this field only works for
# BatchAnnotateFiles requests. It does not work for AsyncBatchAnnotateFiles
# requests.
# Corresponds to the JSON property `content`
# NOTE: Values are automatically base64 encoded/decoded in the client library.
# @return [String]
attr_accessor :content
# The Google Cloud Storage location where the input will be read from.
# Corresponds to the JSON property `gcsSource`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1GcsSource]
attr_accessor :gcs_source
# The type of the file. Currently only "application/pdf", "image/tiff" and "
# image/gif" are supported. Wildcards are not supported.
# Corresponds to the JSON property `mimeType`
# @return [String]
attr_accessor :mime_type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@content = args[:content] if args.key?(:content)
@gcs_source = args[:gcs_source] if args.key?(:gcs_source)
@mime_type = args[:mime_type] if args.key?(:mime_type)
end
end
# Set of detected objects with bounding boxes.
class GoogleCloudVisionV1p3beta1LocalizedObjectAnnotation
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1BoundingPoly]
attr_accessor :bounding_poly
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more information,
# see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Object ID that should align with EntityAnnotation mid.
# Corresponds to the JSON property `mid`
# @return [String]
attr_accessor :mid
# Object name, expressed in its `language_code` language.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Score of the result. Range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@language_code = args[:language_code] if args.key?(:language_code)
@mid = args[:mid] if args.key?(:mid)
@name = args[:name] if args.key?(:name)
@score = args[:score] if args.key?(:score)
end
end
# Detected entity location information.
class GoogleCloudVisionV1p3beta1LocationInfo
include Google::Apis::Core::Hashable
# An object that represents a latitude/longitude pair. This is expressed as a
# pair of doubles to represent degrees latitude and degrees longitude. Unless
# specified otherwise, this must conform to the WGS84 standard. Values must be
# within normalized ranges.
# Corresponds to the JSON property `latLng`
# @return [Google::Apis::VisionV1p2beta1::LatLng]
attr_accessor :lat_lng
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@lat_lng = args[:lat_lng] if args.key?(:lat_lng)
end
end
# A vertex represents a 2D point in the image. NOTE: the normalized vertex
# coordinates are relative to the original image and range from 0 to 1.
class GoogleCloudVisionV1p3beta1NormalizedVertex
include Google::Apis::Core::Hashable
# X coordinate.
# Corresponds to the JSON property `x`
# @return [Float]
attr_accessor :x
# Y coordinate.
# Corresponds to the JSON property `y`
# @return [Float]
attr_accessor :y
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@x = args[:x] if args.key?(:x)
@y = args[:y] if args.key?(:y)
end
end
# Contains metadata for the BatchAnnotateImages operation.
class GoogleCloudVisionV1p3beta1OperationMetadata
include Google::Apis::Core::Hashable
# The time when the batch request was received.
# Corresponds to the JSON property `createTime`
# @return [String]
attr_accessor :create_time
# Current state of the batch operation.
# Corresponds to the JSON property `state`
# @return [String]
attr_accessor :state
# The time when the operation result was last updated.
# Corresponds to the JSON property `updateTime`
# @return [String]
attr_accessor :update_time
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@create_time = args[:create_time] if args.key?(:create_time)
@state = args[:state] if args.key?(:state)
@update_time = args[:update_time] if args.key?(:update_time)
end
end
# The desired output location and metadata.
class GoogleCloudVisionV1p3beta1OutputConfig
include Google::Apis::Core::Hashable
# The max number of response protos to put into each output JSON file on Google
# Cloud Storage. The valid range is [1, 100]. If not specified, the default
# value is 20. For example, for one pdf file with 100 pages, 100 response protos
# will be generated. If `batch_size` = 20, then 5 json files each containing 20
# response protos will be written under the prefix `gcs_destination`.`uri`.
# Currently, batch_size only applies to GcsDestination, with potential future
# support for other output configurations.
# Corresponds to the JSON property `batchSize`
# @return [Fixnum]
attr_accessor :batch_size
# The Google Cloud Storage location where the output will be written to.
# Corresponds to the JSON property `gcsDestination`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1GcsDestination]
attr_accessor :gcs_destination
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@batch_size = args[:batch_size] if args.key?(:batch_size)
@gcs_destination = args[:gcs_destination] if args.key?(:gcs_destination)
end
end
# Detected page from OCR.
class GoogleCloudVisionV1p3beta1Page
include Google::Apis::Core::Hashable
# List of blocks of text, images etc on this page.
# Corresponds to the JSON property `blocks`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1Block>]
attr_accessor :blocks
# Confidence of the OCR results on the page. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Page height. For PDFs the unit is points. For images (including TIFFs) the
# unit is pixels.
# Corresponds to the JSON property `height`
# @return [Fixnum]
attr_accessor :height
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1TextAnnotationTextProperty]
attr_accessor :property
# Page width. For PDFs the unit is points. For images (including TIFFs) the unit
# is pixels.
# Corresponds to the JSON property `width`
# @return [Fixnum]
attr_accessor :width
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@blocks = args[:blocks] if args.key?(:blocks)
@confidence = args[:confidence] if args.key?(:confidence)
@height = args[:height] if args.key?(:height)
@property = args[:property] if args.key?(:property)
@width = args[:width] if args.key?(:width)
end
end
# Structural unit of text representing a number of words in certain order.
class GoogleCloudVisionV1p3beta1Paragraph
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results for the paragraph. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1TextAnnotationTextProperty]
attr_accessor :property
# List of all words in this paragraph.
# Corresponds to the JSON property `words`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1Word>]
attr_accessor :words
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@property = args[:property] if args.key?(:property)
@words = args[:words] if args.key?(:words)
end
end
# A 3D position in the image, used primarily for Face detection landmarks. A
# valid Position must have both x and y coordinates. The position coordinates
# are in the same scale as the original image.
class GoogleCloudVisionV1p3beta1Position
include Google::Apis::Core::Hashable
# X coordinate.
# Corresponds to the JSON property `x`
# @return [Float]
attr_accessor :x
# Y coordinate.
# Corresponds to the JSON property `y`
# @return [Float]
attr_accessor :y
# Z coordinate (or depth).
# Corresponds to the JSON property `z`
# @return [Float]
attr_accessor :z
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@x = args[:x] if args.key?(:x)
@y = args[:y] if args.key?(:y)
@z = args[:z] if args.key?(:z)
end
end
# A Product contains ReferenceImages.
class GoogleCloudVisionV1p3beta1Product
include Google::Apis::Core::Hashable
# User-provided metadata to be stored with this product. Must be at most 4096
# characters long.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The user-provided name for this Product. Must not be empty. Must be at most
# 4096 characters long.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# The resource name of the product. Format is: `projects/PROJECT_ID/locations/
# LOC_ID/products/PRODUCT_ID`. This field is ignored when creating a product.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Immutable. The category for the product identified by the reference image.
# This should be one of "homegoods-v2", "apparel-v2", "toys-v2", "packagedgoods-
# v1" or "general-v1". The legacy categories "homegoods", "apparel", and "toys"
# are still supported, but these should not be used for new products.
# Corresponds to the JSON property `productCategory`
# @return [String]
attr_accessor :product_category
# Key-value pairs that can be attached to a product. At query time, constraints
# can be specified based on the product_labels. Note that integer values can be
# provided as strings, e.g. "1199". Only strings with integer values can match a
# range-based restriction which is to be supported soon. Multiple values can be
# assigned to the same key. One product may have up to 500 product_labels.
# Notice that the total number of distinct product_labels over all products in
# one ProductSet cannot exceed 1M, otherwise the product search pipeline will
# refuse to work for that ProductSet.
# Corresponds to the JSON property `productLabels`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1ProductKeyValue>]
attr_accessor :product_labels
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@display_name = args[:display_name] if args.key?(:display_name)
@name = args[:name] if args.key?(:name)
@product_category = args[:product_category] if args.key?(:product_category)
@product_labels = args[:product_labels] if args.key?(:product_labels)
end
end
# A product label represented as a key-value pair.
class GoogleCloudVisionV1p3beta1ProductKeyValue
include Google::Apis::Core::Hashable
# The key of the label attached to the product. Cannot be empty and cannot
# exceed 128 bytes.
# Corresponds to the JSON property `key`
# @return [String]
attr_accessor :key
# The value of the label attached to the product. Cannot be empty and cannot
# exceed 128 bytes.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@key = args[:key] if args.key?(:key)
@value = args[:value] if args.key?(:value)
end
end
# Results for a product search request.
class GoogleCloudVisionV1p3beta1ProductSearchResults
include Google::Apis::Core::Hashable
# Timestamp of the index which provided these results. Products added to the
# product set and products removed from the product set after this time are not
# reflected in the current results.
# Corresponds to the JSON property `indexTime`
# @return [String]
attr_accessor :index_time
# List of results grouped by products detected in the query image. Each entry
# corresponds to one bounding polygon in the query image, and contains the
# matching products specific to that region. There may be duplicate product
# matches in the union of all the per-product results.
# Corresponds to the JSON property `productGroupedResults`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1ProductSearchResultsGroupedResult>]
attr_accessor :product_grouped_results
# List of results, one for each product match.
# Corresponds to the JSON property `results`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1ProductSearchResultsResult>]
attr_accessor :results
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@index_time = args[:index_time] if args.key?(:index_time)
@product_grouped_results = args[:product_grouped_results] if args.key?(:product_grouped_results)
@results = args[:results] if args.key?(:results)
end
end
# Information about the products similar to a single product in a query image.
class GoogleCloudVisionV1p3beta1ProductSearchResultsGroupedResult
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1BoundingPoly]
attr_accessor :bounding_poly
# List of generic predictions for the object in the bounding box.
# Corresponds to the JSON property `objectAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1ProductSearchResultsObjectAnnotation>]
attr_accessor :object_annotations
# List of results, one for each product match.
# Corresponds to the JSON property `results`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1ProductSearchResultsResult>]
attr_accessor :results
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@object_annotations = args[:object_annotations] if args.key?(:object_annotations)
@results = args[:results] if args.key?(:results)
end
end
# Prediction for what the object in the bounding box is.
class GoogleCloudVisionV1p3beta1ProductSearchResultsObjectAnnotation
include Google::Apis::Core::Hashable
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more information,
# see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Object ID that should align with EntityAnnotation mid.
# Corresponds to the JSON property `mid`
# @return [String]
attr_accessor :mid
# Object name, expressed in its `language_code` language.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Score of the result. Range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@language_code = args[:language_code] if args.key?(:language_code)
@mid = args[:mid] if args.key?(:mid)
@name = args[:name] if args.key?(:name)
@score = args[:score] if args.key?(:score)
end
end
# Information about a product.
class GoogleCloudVisionV1p3beta1ProductSearchResultsResult
include Google::Apis::Core::Hashable
# The resource name of the image from the product that is the closest match to
# the query.
# Corresponds to the JSON property `image`
# @return [String]
attr_accessor :image
# A Product contains ReferenceImages.
# Corresponds to the JSON property `product`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1Product]
attr_accessor :product
# A confidence level on the match, ranging from 0 (no confidence) to 1 (full
# confidence).
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@image = args[:image] if args.key?(:image)
@product = args[:product] if args.key?(:product)
@score = args[:score] if args.key?(:score)
end
end
# A `Property` consists of a user-supplied name/value pair.
class GoogleCloudVisionV1p3beta1Property
include Google::Apis::Core::Hashable
# Name of the property.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Value of numeric properties.
# Corresponds to the JSON property `uint64Value`
# @return [Fixnum]
attr_accessor :uint64_value
# Value of the property.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@name = args[:name] if args.key?(:name)
@uint64_value = args[:uint64_value] if args.key?(:uint64_value)
@value = args[:value] if args.key?(:value)
end
end
# A `ReferenceImage` represents a product image and its associated metadata,
# such as bounding boxes.
class GoogleCloudVisionV1p3beta1ReferenceImage
include Google::Apis::Core::Hashable
# Optional. Bounding polygons around the areas of interest in the reference
# image. If this field is empty, the system will try to detect regions of
# interest. At most 10 bounding polygons will be used. The provided shape is
# converted into a non-rotated rectangle. Once converted, the small edge of the
# rectangle must be greater than or equal to 300 pixels. The aspect ratio must
# be 1:4 or less (i.e. 1:3 is ok; 1:5 is not).
# Corresponds to the JSON property `boundingPolys`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1BoundingPoly>]
attr_accessor :bounding_polys
# The resource name of the reference image. Format is: `projects/PROJECT_ID/
# locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`. This field is
# ignored when creating a reference image.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Required. The Google Cloud Storage URI of the reference image. The URI must
# start with `gs://`.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_polys = args[:bounding_polys] if args.key?(:bounding_polys)
@name = args[:name] if args.key?(:name)
@uri = args[:uri] if args.key?(:uri)
end
end
# Set of features pertaining to the image, computed by computer vision methods
# over safe-search verticals (for example, adult, spoof, medical, violence).
class GoogleCloudVisionV1p3beta1SafeSearchAnnotation
include Google::Apis::Core::Hashable
# Represents the adult content likelihood for the image. Adult content may
# contain elements such as nudity, pornographic images or cartoons, or sexual
# activities.
# Corresponds to the JSON property `adult`
# @return [String]
attr_accessor :adult
# Likelihood that this is a medical image.
# Corresponds to the JSON property `medical`
# @return [String]
attr_accessor :medical
# Likelihood that the request image contains racy content. Racy content may
# include (but is not limited to) skimpy or sheer clothing, strategically
# covered nudity, lewd or provocative poses, or close-ups of sensitive body
# areas.
# Corresponds to the JSON property `racy`
# @return [String]
attr_accessor :racy
# Spoof likelihood. The likelihood that an modification was made to the image's
# canonical version to make it appear funny or offensive.
# Corresponds to the JSON property `spoof`
# @return [String]
attr_accessor :spoof
# Likelihood that this image contains violent content.
# Corresponds to the JSON property `violence`
# @return [String]
attr_accessor :violence
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@adult = args[:adult] if args.key?(:adult)
@medical = args[:medical] if args.key?(:medical)
@racy = args[:racy] if args.key?(:racy)
@spoof = args[:spoof] if args.key?(:spoof)
@violence = args[:violence] if args.key?(:violence)
end
end
# A single symbol representation.
class GoogleCloudVisionV1p3beta1Symbol
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results for the symbol. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1TextAnnotationTextProperty]
attr_accessor :property
# The actual UTF-8 representation of the symbol.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@property = args[:property] if args.key?(:property)
@text = args[:text] if args.key?(:text)
end
end
# TextAnnotation contains a structured representation of OCR extracted text. The
# hierarchy of an OCR extracted text structure is like this: TextAnnotation ->
# Page -> Block -> Paragraph -> Word -> Symbol Each structural component,
# starting from Page, may further have their own properties. Properties describe
# detected languages, breaks etc.. Please refer to the TextAnnotation.
# TextProperty message definition below for more detail.
class GoogleCloudVisionV1p3beta1TextAnnotation
include Google::Apis::Core::Hashable
# List of pages detected by OCR.
# Corresponds to the JSON property `pages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1Page>]
attr_accessor :pages
# UTF-8 text detected on the pages.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@pages = args[:pages] if args.key?(:pages)
@text = args[:text] if args.key?(:text)
end
end
# Detected start or end of a structural component.
class GoogleCloudVisionV1p3beta1TextAnnotationDetectedBreak
include Google::Apis::Core::Hashable
# True if break prepends the element.
# Corresponds to the JSON property `isPrefix`
# @return [Boolean]
attr_accessor :is_prefix
alias_method :is_prefix?, :is_prefix
# Detected break type.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@is_prefix = args[:is_prefix] if args.key?(:is_prefix)
@type = args[:type] if args.key?(:type)
end
end
# Detected language for a structural component.
class GoogleCloudVisionV1p3beta1TextAnnotationDetectedLanguage
include Google::Apis::Core::Hashable
# Confidence of detected language. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more information,
# see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@confidence = args[:confidence] if args.key?(:confidence)
@language_code = args[:language_code] if args.key?(:language_code)
end
end
# Additional information detected on the structural component.
class GoogleCloudVisionV1p3beta1TextAnnotationTextProperty
include Google::Apis::Core::Hashable
# Detected start or end of a structural component.
# Corresponds to the JSON property `detectedBreak`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1TextAnnotationDetectedBreak]
attr_accessor :detected_break
# A list of detected languages together with confidence.
# Corresponds to the JSON property `detectedLanguages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1TextAnnotationDetectedLanguage>]
attr_accessor :detected_languages
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@detected_break = args[:detected_break] if args.key?(:detected_break)
@detected_languages = args[:detected_languages] if args.key?(:detected_languages)
end
end
# A vertex represents a 2D point in the image. NOTE: the vertex coordinates are
# in the same scale as the original image.
class GoogleCloudVisionV1p3beta1Vertex
include Google::Apis::Core::Hashable
# X coordinate.
# Corresponds to the JSON property `x`
# @return [Fixnum]
attr_accessor :x
# Y coordinate.
# Corresponds to the JSON property `y`
# @return [Fixnum]
attr_accessor :y
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@x = args[:x] if args.key?(:x)
@y = args[:y] if args.key?(:y)
end
end
# Relevant information for the image from the Internet.
class GoogleCloudVisionV1p3beta1WebDetection
include Google::Apis::Core::Hashable
# The service's best guess as to the topic of the request image. Inferred from
# similar images on the open web.
# Corresponds to the JSON property `bestGuessLabels`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1WebDetectionWebLabel>]
attr_accessor :best_guess_labels
# Fully matching images from the Internet. Can include resized copies of the
# query image.
# Corresponds to the JSON property `fullMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1WebDetectionWebImage>]
attr_accessor :full_matching_images
# Web pages containing the matching images from the Internet.
# Corresponds to the JSON property `pagesWithMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1WebDetectionWebPage>]
attr_accessor :pages_with_matching_images
# Partial matching images from the Internet. Those images are similar enough to
# share some key-point features. For example an original image will likely have
# partial matching for its crops.
# Corresponds to the JSON property `partialMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1WebDetectionWebImage>]
attr_accessor :partial_matching_images
# The visually similar image results.
# Corresponds to the JSON property `visuallySimilarImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1WebDetectionWebImage>]
attr_accessor :visually_similar_images
# Deduced entities from similar images on the Internet.
# Corresponds to the JSON property `webEntities`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1WebDetectionWebEntity>]
attr_accessor :web_entities
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@best_guess_labels = args[:best_guess_labels] if args.key?(:best_guess_labels)
@full_matching_images = args[:full_matching_images] if args.key?(:full_matching_images)
@pages_with_matching_images = args[:pages_with_matching_images] if args.key?(:pages_with_matching_images)
@partial_matching_images = args[:partial_matching_images] if args.key?(:partial_matching_images)
@visually_similar_images = args[:visually_similar_images] if args.key?(:visually_similar_images)
@web_entities = args[:web_entities] if args.key?(:web_entities)
end
end
# Entity deduced from similar images on the Internet.
class GoogleCloudVisionV1p3beta1WebDetectionWebEntity
include Google::Apis::Core::Hashable
# Canonical description of the entity, in English.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# Opaque entity ID.
# Corresponds to the JSON property `entityId`
# @return [String]
attr_accessor :entity_id
# Overall relevancy score for the entity. Not normalized and not comparable
# across different image queries.
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@entity_id = args[:entity_id] if args.key?(:entity_id)
@score = args[:score] if args.key?(:score)
end
end
# Metadata for online images.
class GoogleCloudVisionV1p3beta1WebDetectionWebImage
include Google::Apis::Core::Hashable
# (Deprecated) Overall relevancy score for the image.
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
# The result image URL.
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@score = args[:score] if args.key?(:score)
@url = args[:url] if args.key?(:url)
end
end
# Label to provide extra metadata for the web detection.
class GoogleCloudVisionV1p3beta1WebDetectionWebLabel
include Google::Apis::Core::Hashable
# Label for extra metadata.
# Corresponds to the JSON property `label`
# @return [String]
attr_accessor :label
# The BCP-47 language code for `label`, such as "en-US" or "sr-Latn". For more
# information, see http://www.unicode.org/reports/tr35/#
# Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@label = args[:label] if args.key?(:label)
@language_code = args[:language_code] if args.key?(:language_code)
end
end
# Metadata for web pages.
class GoogleCloudVisionV1p3beta1WebDetectionWebPage
include Google::Apis::Core::Hashable
# Fully matching images on the page. Can include resized copies of the query
# image.
# Corresponds to the JSON property `fullMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1WebDetectionWebImage>]
attr_accessor :full_matching_images
# Title for the web page, may contain HTML markups.
# Corresponds to the JSON property `pageTitle`
# @return [String]
attr_accessor :page_title
# Partial matching images on the page. Those images are similar enough to share
# some key-point features. For example an original image will likely have
# partial matching for its crops.
# Corresponds to the JSON property `partialMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1WebDetectionWebImage>]
attr_accessor :partial_matching_images
# (Deprecated) Overall relevancy score for the web page.
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
# The result web page URL.
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@full_matching_images = args[:full_matching_images] if args.key?(:full_matching_images)
@page_title = args[:page_title] if args.key?(:page_title)
@partial_matching_images = args[:partial_matching_images] if args.key?(:partial_matching_images)
@score = args[:score] if args.key?(:score)
@url = args[:url] if args.key?(:url)
end
end
# A word representation.
class GoogleCloudVisionV1p3beta1Word
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results for the word. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1TextAnnotationTextProperty]
attr_accessor :property
# List of symbols in the word. The order of the symbols follows the natural
# reading order.
# Corresponds to the JSON property `symbols`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p3beta1Symbol>]
attr_accessor :symbols
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@property = args[:property] if args.key?(:property)
@symbols = args[:symbols] if args.key?(:symbols)
end
end
# Response to a single file annotation request. A file may contain one or more
# images, which individually have their own responses.
class GoogleCloudVisionV1p4beta1AnnotateFileResponse
include Google::Apis::Core::Hashable
# The `Status` type defines a logical error model that is suitable for different
# programming environments, including REST APIs and RPC APIs. It is used by [
# gRPC](https://github.com/grpc). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `error`
# @return [Google::Apis::VisionV1p2beta1::Status]
attr_accessor :error
# The desired input location and metadata.
# Corresponds to the JSON property `inputConfig`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1InputConfig]
attr_accessor :input_config
# Individual responses to images found within the file. This field will be empty
# if the `error` field is set.
# Corresponds to the JSON property `responses`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1AnnotateImageResponse>]
attr_accessor :responses
# This field gives the total number of pages in the file.
# Corresponds to the JSON property `totalPages`
# @return [Fixnum]
attr_accessor :total_pages
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@error = args[:error] if args.key?(:error)
@input_config = args[:input_config] if args.key?(:input_config)
@responses = args[:responses] if args.key?(:responses)
@total_pages = args[:total_pages] if args.key?(:total_pages)
end
end
# Response to an image annotation request.
class GoogleCloudVisionV1p4beta1AnnotateImageResponse
include Google::Apis::Core::Hashable
# If an image was produced from a file (e.g. a PDF), this message gives
# information about the source of that image.
# Corresponds to the JSON property `context`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1ImageAnnotationContext]
attr_accessor :context
# Set of crop hints that are used to generate new crops when serving images.
# Corresponds to the JSON property `cropHintsAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1CropHintsAnnotation]
attr_accessor :crop_hints_annotation
# The `Status` type defines a logical error model that is suitable for different
# programming environments, including REST APIs and RPC APIs. It is used by [
# gRPC](https://github.com/grpc). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `error`
# @return [Google::Apis::VisionV1p2beta1::Status]
attr_accessor :error
# If present, face detection has completed successfully.
# Corresponds to the JSON property `faceAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1FaceAnnotation>]
attr_accessor :face_annotations
# TextAnnotation contains a structured representation of OCR extracted text. The
# hierarchy of an OCR extracted text structure is like this: TextAnnotation ->
# Page -> Block -> Paragraph -> Word -> Symbol Each structural component,
# starting from Page, may further have their own properties. Properties describe
# detected languages, breaks etc.. Please refer to the TextAnnotation.
# TextProperty message definition below for more detail.
# Corresponds to the JSON property `fullTextAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1TextAnnotation]
attr_accessor :full_text_annotation
# Stores image properties, such as dominant colors.
# Corresponds to the JSON property `imagePropertiesAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1ImageProperties]
attr_accessor :image_properties_annotation
# If present, label detection has completed successfully.
# Corresponds to the JSON property `labelAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1EntityAnnotation>]
attr_accessor :label_annotations
# If present, landmark detection has completed successfully.
# Corresponds to the JSON property `landmarkAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1EntityAnnotation>]
attr_accessor :landmark_annotations
# If present, localized object detection has completed successfully. This will
# be sorted descending by confidence score.
# Corresponds to the JSON property `localizedObjectAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1LocalizedObjectAnnotation>]
attr_accessor :localized_object_annotations
# If present, logo detection has completed successfully.
# Corresponds to the JSON property `logoAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1EntityAnnotation>]
attr_accessor :logo_annotations
# Results for a product search request.
# Corresponds to the JSON property `productSearchResults`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1ProductSearchResults]
attr_accessor :product_search_results
# Set of features pertaining to the image, computed by computer vision methods
# over safe-search verticals (for example, adult, spoof, medical, violence).
# Corresponds to the JSON property `safeSearchAnnotation`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1SafeSearchAnnotation]
attr_accessor :safe_search_annotation
# If present, text (OCR) detection has completed successfully.
# Corresponds to the JSON property `textAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1EntityAnnotation>]
attr_accessor :text_annotations
# Relevant information for the image from the Internet.
# Corresponds to the JSON property `webDetection`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1WebDetection]
attr_accessor :web_detection
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@context = args[:context] if args.key?(:context)
@crop_hints_annotation = args[:crop_hints_annotation] if args.key?(:crop_hints_annotation)
@error = args[:error] if args.key?(:error)
@face_annotations = args[:face_annotations] if args.key?(:face_annotations)
@full_text_annotation = args[:full_text_annotation] if args.key?(:full_text_annotation)
@image_properties_annotation = args[:image_properties_annotation] if args.key?(:image_properties_annotation)
@label_annotations = args[:label_annotations] if args.key?(:label_annotations)
@landmark_annotations = args[:landmark_annotations] if args.key?(:landmark_annotations)
@localized_object_annotations = args[:localized_object_annotations] if args.key?(:localized_object_annotations)
@logo_annotations = args[:logo_annotations] if args.key?(:logo_annotations)
@product_search_results = args[:product_search_results] if args.key?(:product_search_results)
@safe_search_annotation = args[:safe_search_annotation] if args.key?(:safe_search_annotation)
@text_annotations = args[:text_annotations] if args.key?(:text_annotations)
@web_detection = args[:web_detection] if args.key?(:web_detection)
end
end
# The response for a single offline file annotation request.
class GoogleCloudVisionV1p4beta1AsyncAnnotateFileResponse
include Google::Apis::Core::Hashable
# The desired output location and metadata.
# Corresponds to the JSON property `outputConfig`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1OutputConfig]
attr_accessor :output_config
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@output_config = args[:output_config] if args.key?(:output_config)
end
end
# Response to an async batch file annotation request.
class GoogleCloudVisionV1p4beta1AsyncBatchAnnotateFilesResponse
include Google::Apis::Core::Hashable
# The list of file annotation responses, one for each request in
# AsyncBatchAnnotateFilesRequest.
# Corresponds to the JSON property `responses`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1AsyncAnnotateFileResponse>]
attr_accessor :responses
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@responses = args[:responses] if args.key?(:responses)
end
end
# Response to an async batch image annotation request.
class GoogleCloudVisionV1p4beta1AsyncBatchAnnotateImagesResponse
include Google::Apis::Core::Hashable
# The desired output location and metadata.
# Corresponds to the JSON property `outputConfig`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1OutputConfig]
attr_accessor :output_config
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@output_config = args[:output_config] if args.key?(:output_config)
end
end
# A list of file annotation responses.
class GoogleCloudVisionV1p4beta1BatchAnnotateFilesResponse
include Google::Apis::Core::Hashable
# The list of file annotation responses, each response corresponding to each
# AnnotateFileRequest in BatchAnnotateFilesRequest.
# Corresponds to the JSON property `responses`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1AnnotateFileResponse>]
attr_accessor :responses
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@responses = args[:responses] if args.key?(:responses)
end
end
# Metadata for the batch operations such as the current state. This is included
# in the `metadata` field of the `Operation` returned by the `GetOperation` call
# of the `google::longrunning::Operations` service.
class GoogleCloudVisionV1p4beta1BatchOperationMetadata
include Google::Apis::Core::Hashable
# The time when the batch request is finished and google.longrunning.Operation.
# done is set to true.
# Corresponds to the JSON property `endTime`
# @return [String]
attr_accessor :end_time
# The current state of the batch operation.
# Corresponds to the JSON property `state`
# @return [String]
attr_accessor :state
# The time when the batch request was submitted to the server.
# Corresponds to the JSON property `submitTime`
# @return [String]
attr_accessor :submit_time
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@end_time = args[:end_time] if args.key?(:end_time)
@state = args[:state] if args.key?(:state)
@submit_time = args[:submit_time] if args.key?(:submit_time)
end
end
# Logical element on the page.
class GoogleCloudVisionV1p4beta1Block
include Google::Apis::Core::Hashable
# Detected block type (text, image etc) for this block.
# Corresponds to the JSON property `blockType`
# @return [String]
attr_accessor :block_type
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results on the block. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# List of paragraphs in this block (if this blocks is of type text).
# Corresponds to the JSON property `paragraphs`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1Paragraph>]
attr_accessor :paragraphs
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1TextAnnotationTextProperty]
attr_accessor :property
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@block_type = args[:block_type] if args.key?(:block_type)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@paragraphs = args[:paragraphs] if args.key?(:paragraphs)
@property = args[:property] if args.key?(:property)
end
end
# A bounding polygon for the detected image annotation.
class GoogleCloudVisionV1p4beta1BoundingPoly
include Google::Apis::Core::Hashable
# The bounding polygon normalized vertices.
# Corresponds to the JSON property `normalizedVertices`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1NormalizedVertex>]
attr_accessor :normalized_vertices
# The bounding polygon vertices.
# Corresponds to the JSON property `vertices`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1Vertex>]
attr_accessor :vertices
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@normalized_vertices = args[:normalized_vertices] if args.key?(:normalized_vertices)
@vertices = args[:vertices] if args.key?(:vertices)
end
end
# A Celebrity is a group of Faces with an identity.
class GoogleCloudVisionV1p4beta1Celebrity
include Google::Apis::Core::Hashable
# The Celebrity's description.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The Celebrity's display name.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# The resource name of the preloaded Celebrity. Has the format `builtin/`mid``.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@display_name = args[:display_name] if args.key?(:display_name)
@name = args[:name] if args.key?(:name)
end
end
# Color information consists of RGB channels, score, and the fraction of the
# image that the color occupies in the image.
class GoogleCloudVisionV1p4beta1ColorInfo
include Google::Apis::Core::Hashable
# Represents a color in the RGBA color space. This representation is designed
# for simplicity of conversion to/from color representations in various
# languages over compactness; for example, the fields of this representation can
# be trivially provided to the constructor of "java.awt.Color" in Java; it can
# also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
# method in iOS; and, with just a little work, it can be easily formatted into a
# CSS "rgba()" string in JavaScript, as well. Note: this proto does not carry
# information about the absolute color space that should be used to interpret
# the RGB value (e.g. sRGB, Adobe RGB, DCI-P3, BT.2020, etc.). By default,
# applications SHOULD assume the sRGB color space. Note: when color equality
# needs to be decided, implementations, unless documented otherwise, will treat
# two colors to be equal if all their red, green, blue and alpha values each
# differ by at most 1e-5. Example (Java): import com.google.type.Color; // ...
# public static java.awt.Color fromProto(Color protocolor) ` float alpha =
# protocolor.hasAlpha() ? protocolor.getAlpha().getValue() : 1.0; return new
# java.awt.Color( protocolor.getRed(), protocolor.getGreen(), protocolor.getBlue(
# ), alpha); ` public static Color toProto(java.awt.Color color) ` float red = (
# float) color.getRed(); float green = (float) color.getGreen(); float blue = (
# float) color.getBlue(); float denominator = 255.0; Color.Builder resultBuilder
# = Color .newBuilder() .setRed(red / denominator) .setGreen(green / denominator)
# .setBlue(blue / denominator); int alpha = color.getAlpha(); if (alpha != 255)
# ` result.setAlpha( FloatValue .newBuilder() .setValue(((float) alpha) /
# denominator) .build()); ` return resultBuilder.build(); ` // ... Example (iOS /
# Obj-C): // ... static UIColor* fromProto(Color* protocolor) ` float red = [
# protocolor red]; float green = [protocolor green]; float blue = [protocolor
# blue]; FloatValue* alpha_wrapper = [protocolor alpha]; float alpha = 1.0; if (
# alpha_wrapper != nil) ` alpha = [alpha_wrapper value]; ` return [UIColor
# colorWithRed:red green:green blue:blue alpha:alpha]; ` static Color* toProto(
# UIColor* color) ` CGFloat red, green, blue, alpha; if (![color getRed:&red
# green:&green blue:&blue alpha:&alpha]) ` return nil; ` Color* result = [[Color
# alloc] init]; [result setRed:red]; [result setGreen:green]; [result setBlue:
# blue]; if (alpha <= 0.9999) ` [result setAlpha:floatWrapperWithValue(alpha)]; `
# [result autorelease]; return result; ` // ... Example (JavaScript): // ...
# var protoToCssColor = function(rgb_color) ` var redFrac = rgb_color.red || 0.0;
# var greenFrac = rgb_color.green || 0.0; var blueFrac = rgb_color.blue || 0.0;
# var red = Math.floor(redFrac * 255); var green = Math.floor(greenFrac * 255);
# var blue = Math.floor(blueFrac * 255); if (!('alpha' in rgb_color)) ` return
# rgbToCssColor_(red, green, blue); ` var alphaFrac = rgb_color.alpha.value || 0.
# 0; var rgbParams = [red, green, blue].join(','); return ['rgba(', rgbParams, ',
# ', alphaFrac, ')'].join(''); `; var rgbToCssColor_ = function(red, green, blue)
# ` var rgbNumber = new Number((red << 16) | (green << 8) | blue); var
# hexString = rgbNumber.toString(16); var missingZeros = 6 - hexString.length;
# var resultBuilder = ['#']; for (var i = 0; i < missingZeros; i++) `
# resultBuilder.push('0'); ` resultBuilder.push(hexString); return resultBuilder.
# join(''); `; // ...
# Corresponds to the JSON property `color`
# @return [Google::Apis::VisionV1p2beta1::Color]
attr_accessor :color
# The fraction of pixels the color occupies in the image. Value in range [0, 1].
# Corresponds to the JSON property `pixelFraction`
# @return [Float]
attr_accessor :pixel_fraction
# Image-specific score for this color. Value in range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@color = args[:color] if args.key?(:color)
@pixel_fraction = args[:pixel_fraction] if args.key?(:pixel_fraction)
@score = args[:score] if args.key?(:score)
end
end
# Single crop hint that is used to generate a new crop when serving an image.
class GoogleCloudVisionV1p4beta1CropHint
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1BoundingPoly]
attr_accessor :bounding_poly
# Confidence of this being a salient region. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Fraction of importance of this salient region with respect to the original
# image.
# Corresponds to the JSON property `importanceFraction`
# @return [Float]
attr_accessor :importance_fraction
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@confidence = args[:confidence] if args.key?(:confidence)
@importance_fraction = args[:importance_fraction] if args.key?(:importance_fraction)
end
end
# Set of crop hints that are used to generate new crops when serving images.
class GoogleCloudVisionV1p4beta1CropHintsAnnotation
include Google::Apis::Core::Hashable
# Crop hint results.
# Corresponds to the JSON property `cropHints`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1CropHint>]
attr_accessor :crop_hints
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@crop_hints = args[:crop_hints] if args.key?(:crop_hints)
end
end
# Set of dominant colors and their corresponding scores.
class GoogleCloudVisionV1p4beta1DominantColorsAnnotation
include Google::Apis::Core::Hashable
# RGB color values with their score and pixel fraction.
# Corresponds to the JSON property `colors`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1ColorInfo>]
attr_accessor :colors
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@colors = args[:colors] if args.key?(:colors)
end
end
# Set of detected entity features.
class GoogleCloudVisionV1p4beta1EntityAnnotation
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1BoundingPoly]
attr_accessor :bounding_poly
# **Deprecated. Use `score` instead.** The accuracy of the entity detection in
# an image. For example, for an image in which the "Eiffel Tower" entity is
# detected, this field represents the confidence that there is a tower in the
# query image. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Entity textual description, expressed in its `locale` language.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The language code for the locale in which the entity textual `description` is
# expressed.
# Corresponds to the JSON property `locale`
# @return [String]
attr_accessor :locale
# The location information for the detected entity. Multiple `LocationInfo`
# elements can be present because one location may indicate the location of the
# scene in the image, and another location may indicate the location of the
# place where the image was taken. Location information is usually present for
# landmarks.
# Corresponds to the JSON property `locations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1LocationInfo>]
attr_accessor :locations
# Opaque entity ID. Some IDs may be available in [Google Knowledge Graph Search
# API](https://developers.google.com/knowledge-graph/).
# Corresponds to the JSON property `mid`
# @return [String]
attr_accessor :mid
# Some entities may have optional user-supplied `Property` (name/value) fields,
# such a score or string that qualifies the entity.
# Corresponds to the JSON property `properties`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1Property>]
attr_accessor :properties
# Overall score of the result. Range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
# The relevancy of the ICA (Image Content Annotation) label to the image. For
# example, the relevancy of "tower" is likely higher to an image containing the
# detected "Eiffel Tower" than to an image containing a detected distant
# towering building, even though the confidence that there is a tower in each
# image may be the same. Range [0, 1].
# Corresponds to the JSON property `topicality`
# @return [Float]
attr_accessor :topicality
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@confidence = args[:confidence] if args.key?(:confidence)
@description = args[:description] if args.key?(:description)
@locale = args[:locale] if args.key?(:locale)
@locations = args[:locations] if args.key?(:locations)
@mid = args[:mid] if args.key?(:mid)
@properties = args[:properties] if args.key?(:properties)
@score = args[:score] if args.key?(:score)
@topicality = args[:topicality] if args.key?(:topicality)
end
end
# A face annotation object contains the results of face detection.
class GoogleCloudVisionV1p4beta1FaceAnnotation
include Google::Apis::Core::Hashable
# Anger likelihood.
# Corresponds to the JSON property `angerLikelihood`
# @return [String]
attr_accessor :anger_likelihood
# Blurred likelihood.
# Corresponds to the JSON property `blurredLikelihood`
# @return [String]
attr_accessor :blurred_likelihood
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1BoundingPoly]
attr_accessor :bounding_poly
# Detection confidence. Range [0, 1].
# Corresponds to the JSON property `detectionConfidence`
# @return [Float]
attr_accessor :detection_confidence
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `fdBoundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1BoundingPoly]
attr_accessor :fd_bounding_poly
# Headwear likelihood.
# Corresponds to the JSON property `headwearLikelihood`
# @return [String]
attr_accessor :headwear_likelihood
# Joy likelihood.
# Corresponds to the JSON property `joyLikelihood`
# @return [String]
attr_accessor :joy_likelihood
# Face landmarking confidence. Range [0, 1].
# Corresponds to the JSON property `landmarkingConfidence`
# @return [Float]
attr_accessor :landmarking_confidence
# Detected face landmarks.
# Corresponds to the JSON property `landmarks`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1FaceAnnotationLandmark>]
attr_accessor :landmarks
# Yaw angle, which indicates the leftward/rightward angle that the face is
# pointing relative to the vertical plane perpendicular to the image. Range [-
# 180,180].
# Corresponds to the JSON property `panAngle`
# @return [Float]
attr_accessor :pan_angle
# Additional recognition information. Only computed if image_context.
# face_recognition_params is provided, **and** a match is found to a Celebrity
# in the input CelebritySet. This field is sorted in order of decreasing
# confidence values.
# Corresponds to the JSON property `recognitionResult`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1FaceRecognitionResult>]
attr_accessor :recognition_result
# Roll angle, which indicates the amount of clockwise/anti-clockwise rotation of
# the face relative to the image vertical about the axis perpendicular to the
# face. Range [-180,180].
# Corresponds to the JSON property `rollAngle`
# @return [Float]
attr_accessor :roll_angle
# Sorrow likelihood.
# Corresponds to the JSON property `sorrowLikelihood`
# @return [String]
attr_accessor :sorrow_likelihood
# Surprise likelihood.
# Corresponds to the JSON property `surpriseLikelihood`
# @return [String]
attr_accessor :surprise_likelihood
# Pitch angle, which indicates the upwards/downwards angle that the face is
# pointing relative to the image's horizontal plane. Range [-180,180].
# Corresponds to the JSON property `tiltAngle`
# @return [Float]
attr_accessor :tilt_angle
# Under-exposed likelihood.
# Corresponds to the JSON property `underExposedLikelihood`
# @return [String]
attr_accessor :under_exposed_likelihood
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@anger_likelihood = args[:anger_likelihood] if args.key?(:anger_likelihood)
@blurred_likelihood = args[:blurred_likelihood] if args.key?(:blurred_likelihood)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@detection_confidence = args[:detection_confidence] if args.key?(:detection_confidence)
@fd_bounding_poly = args[:fd_bounding_poly] if args.key?(:fd_bounding_poly)
@headwear_likelihood = args[:headwear_likelihood] if args.key?(:headwear_likelihood)
@joy_likelihood = args[:joy_likelihood] if args.key?(:joy_likelihood)
@landmarking_confidence = args[:landmarking_confidence] if args.key?(:landmarking_confidence)
@landmarks = args[:landmarks] if args.key?(:landmarks)
@pan_angle = args[:pan_angle] if args.key?(:pan_angle)
@recognition_result = args[:recognition_result] if args.key?(:recognition_result)
@roll_angle = args[:roll_angle] if args.key?(:roll_angle)
@sorrow_likelihood = args[:sorrow_likelihood] if args.key?(:sorrow_likelihood)
@surprise_likelihood = args[:surprise_likelihood] if args.key?(:surprise_likelihood)
@tilt_angle = args[:tilt_angle] if args.key?(:tilt_angle)
@under_exposed_likelihood = args[:under_exposed_likelihood] if args.key?(:under_exposed_likelihood)
end
end
# A face-specific landmark (for example, a face feature).
class GoogleCloudVisionV1p4beta1FaceAnnotationLandmark
include Google::Apis::Core::Hashable
# A 3D position in the image, used primarily for Face detection landmarks. A
# valid Position must have both x and y coordinates. The position coordinates
# are in the same scale as the original image.
# Corresponds to the JSON property `position`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1Position]
attr_accessor :position
# Face landmark type.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@position = args[:position] if args.key?(:position)
@type = args[:type] if args.key?(:type)
end
end
# Information about a face's identity.
class GoogleCloudVisionV1p4beta1FaceRecognitionResult
include Google::Apis::Core::Hashable
# A Celebrity is a group of Faces with an identity.
# Corresponds to the JSON property `celebrity`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1Celebrity]
attr_accessor :celebrity
# Recognition confidence. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@celebrity = args[:celebrity] if args.key?(:celebrity)
@confidence = args[:confidence] if args.key?(:confidence)
end
end
# The Google Cloud Storage location where the output will be written to.
class GoogleCloudVisionV1p4beta1GcsDestination
include Google::Apis::Core::Hashable
# Google Cloud Storage URI prefix where the results will be stored. Results will
# be in JSON format and preceded by its corresponding input URI prefix. This
# field can either represent a gcs file prefix or gcs directory. In either case,
# the uri should be unique because in order to get all of the output files, you
# will need to do a wildcard gcs search on the uri prefix you provide. Examples:
# * File Prefix: gs://bucket-name/here/filenameprefix The output files will be
# created in gs://bucket-name/here/ and the names of the output files will begin
# with "filenameprefix". * Directory Prefix: gs://bucket-name/some/location/ The
# output files will be created in gs://bucket-name/some/location/ and the names
# of the output files could be anything because there was no filename prefix
# specified. If multiple outputs, each response is still AnnotateFileResponse,
# each of which contains some subset of the full list of AnnotateImageResponse.
# Multiple outputs can happen if, for example, the output JSON is too large and
# overflows into multiple sharded files.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@uri = args[:uri] if args.key?(:uri)
end
end
# The Google Cloud Storage location where the input will be read from.
class GoogleCloudVisionV1p4beta1GcsSource
include Google::Apis::Core::Hashable
# Google Cloud Storage URI for the input file. This must only be a Google Cloud
# Storage object. Wildcards are not currently supported.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@uri = args[:uri] if args.key?(:uri)
end
end
# If an image was produced from a file (e.g. a PDF), this message gives
# information about the source of that image.
class GoogleCloudVisionV1p4beta1ImageAnnotationContext
include Google::Apis::Core::Hashable
# If the file was a PDF or TIFF, this field gives the page number within the
# file used to produce the image.
# Corresponds to the JSON property `pageNumber`
# @return [Fixnum]
attr_accessor :page_number
# The URI of the file used to produce the image.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@page_number = args[:page_number] if args.key?(:page_number)
@uri = args[:uri] if args.key?(:uri)
end
end
# Stores image properties, such as dominant colors.
class GoogleCloudVisionV1p4beta1ImageProperties
include Google::Apis::Core::Hashable
# Set of dominant colors and their corresponding scores.
# Corresponds to the JSON property `dominantColors`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1DominantColorsAnnotation]
attr_accessor :dominant_colors
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@dominant_colors = args[:dominant_colors] if args.key?(:dominant_colors)
end
end
# Response message for the `ImportProductSets` method. This message is returned
# by the google.longrunning.Operations.GetOperation method in the returned
# google.longrunning.Operation.response field.
class GoogleCloudVisionV1p4beta1ImportProductSetsResponse
include Google::Apis::Core::Hashable
# The list of reference_images that are imported successfully.
# Corresponds to the JSON property `referenceImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1ReferenceImage>]
attr_accessor :reference_images
# The rpc status for each ImportProductSet request, including both successes and
# errors. The number of statuses here matches the number of lines in the csv
# file, and statuses[i] stores the success or failure status of processing the i-
# th line of the csv, starting from line 0.
# Corresponds to the JSON property `statuses`
# @return [Array<Google::Apis::VisionV1p2beta1::Status>]
attr_accessor :statuses
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@reference_images = args[:reference_images] if args.key?(:reference_images)
@statuses = args[:statuses] if args.key?(:statuses)
end
end
# The desired input location and metadata.
class GoogleCloudVisionV1p4beta1InputConfig
include Google::Apis::Core::Hashable
# File content, represented as a stream of bytes. Note: As with all `bytes`
# fields, protobuffers use a pure binary representation, whereas JSON
# representations use base64. Currently, this field only works for
# BatchAnnotateFiles requests. It does not work for AsyncBatchAnnotateFiles
# requests.
# Corresponds to the JSON property `content`
# NOTE: Values are automatically base64 encoded/decoded in the client library.
# @return [String]
attr_accessor :content
# The Google Cloud Storage location where the input will be read from.
# Corresponds to the JSON property `gcsSource`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1GcsSource]
attr_accessor :gcs_source
# The type of the file. Currently only "application/pdf", "image/tiff" and "
# image/gif" are supported. Wildcards are not supported.
# Corresponds to the JSON property `mimeType`
# @return [String]
attr_accessor :mime_type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@content = args[:content] if args.key?(:content)
@gcs_source = args[:gcs_source] if args.key?(:gcs_source)
@mime_type = args[:mime_type] if args.key?(:mime_type)
end
end
# Set of detected objects with bounding boxes.
class GoogleCloudVisionV1p4beta1LocalizedObjectAnnotation
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1BoundingPoly]
attr_accessor :bounding_poly
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more information,
# see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Object ID that should align with EntityAnnotation mid.
# Corresponds to the JSON property `mid`
# @return [String]
attr_accessor :mid
# Object name, expressed in its `language_code` language.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Score of the result. Range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@language_code = args[:language_code] if args.key?(:language_code)
@mid = args[:mid] if args.key?(:mid)
@name = args[:name] if args.key?(:name)
@score = args[:score] if args.key?(:score)
end
end
# Detected entity location information.
class GoogleCloudVisionV1p4beta1LocationInfo
include Google::Apis::Core::Hashable
# An object that represents a latitude/longitude pair. This is expressed as a
# pair of doubles to represent degrees latitude and degrees longitude. Unless
# specified otherwise, this must conform to the WGS84 standard. Values must be
# within normalized ranges.
# Corresponds to the JSON property `latLng`
# @return [Google::Apis::VisionV1p2beta1::LatLng]
attr_accessor :lat_lng
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@lat_lng = args[:lat_lng] if args.key?(:lat_lng)
end
end
# A vertex represents a 2D point in the image. NOTE: the normalized vertex
# coordinates are relative to the original image and range from 0 to 1.
class GoogleCloudVisionV1p4beta1NormalizedVertex
include Google::Apis::Core::Hashable
# X coordinate.
# Corresponds to the JSON property `x`
# @return [Float]
attr_accessor :x
# Y coordinate.
# Corresponds to the JSON property `y`
# @return [Float]
attr_accessor :y
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@x = args[:x] if args.key?(:x)
@y = args[:y] if args.key?(:y)
end
end
# Contains metadata for the BatchAnnotateImages operation.
class GoogleCloudVisionV1p4beta1OperationMetadata
include Google::Apis::Core::Hashable
# The time when the batch request was received.
# Corresponds to the JSON property `createTime`
# @return [String]
attr_accessor :create_time
# Current state of the batch operation.
# Corresponds to the JSON property `state`
# @return [String]
attr_accessor :state
# The time when the operation result was last updated.
# Corresponds to the JSON property `updateTime`
# @return [String]
attr_accessor :update_time
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@create_time = args[:create_time] if args.key?(:create_time)
@state = args[:state] if args.key?(:state)
@update_time = args[:update_time] if args.key?(:update_time)
end
end
# The desired output location and metadata.
class GoogleCloudVisionV1p4beta1OutputConfig
include Google::Apis::Core::Hashable
# The max number of response protos to put into each output JSON file on Google
# Cloud Storage. The valid range is [1, 100]. If not specified, the default
# value is 20. For example, for one pdf file with 100 pages, 100 response protos
# will be generated. If `batch_size` = 20, then 5 json files each containing 20
# response protos will be written under the prefix `gcs_destination`.`uri`.
# Currently, batch_size only applies to GcsDestination, with potential future
# support for other output configurations.
# Corresponds to the JSON property `batchSize`
# @return [Fixnum]
attr_accessor :batch_size
# The Google Cloud Storage location where the output will be written to.
# Corresponds to the JSON property `gcsDestination`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1GcsDestination]
attr_accessor :gcs_destination
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@batch_size = args[:batch_size] if args.key?(:batch_size)
@gcs_destination = args[:gcs_destination] if args.key?(:gcs_destination)
end
end
# Detected page from OCR.
class GoogleCloudVisionV1p4beta1Page
include Google::Apis::Core::Hashable
# List of blocks of text, images etc on this page.
# Corresponds to the JSON property `blocks`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1Block>]
attr_accessor :blocks
# Confidence of the OCR results on the page. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Page height. For PDFs the unit is points. For images (including TIFFs) the
# unit is pixels.
# Corresponds to the JSON property `height`
# @return [Fixnum]
attr_accessor :height
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1TextAnnotationTextProperty]
attr_accessor :property
# Page width. For PDFs the unit is points. For images (including TIFFs) the unit
# is pixels.
# Corresponds to the JSON property `width`
# @return [Fixnum]
attr_accessor :width
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@blocks = args[:blocks] if args.key?(:blocks)
@confidence = args[:confidence] if args.key?(:confidence)
@height = args[:height] if args.key?(:height)
@property = args[:property] if args.key?(:property)
@width = args[:width] if args.key?(:width)
end
end
# Structural unit of text representing a number of words in certain order.
class GoogleCloudVisionV1p4beta1Paragraph
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results for the paragraph. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1TextAnnotationTextProperty]
attr_accessor :property
# List of all words in this paragraph.
# Corresponds to the JSON property `words`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1Word>]
attr_accessor :words
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@property = args[:property] if args.key?(:property)
@words = args[:words] if args.key?(:words)
end
end
# A 3D position in the image, used primarily for Face detection landmarks. A
# valid Position must have both x and y coordinates. The position coordinates
# are in the same scale as the original image.
class GoogleCloudVisionV1p4beta1Position
include Google::Apis::Core::Hashable
# X coordinate.
# Corresponds to the JSON property `x`
# @return [Float]
attr_accessor :x
# Y coordinate.
# Corresponds to the JSON property `y`
# @return [Float]
attr_accessor :y
# Z coordinate (or depth).
# Corresponds to the JSON property `z`
# @return [Float]
attr_accessor :z
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@x = args[:x] if args.key?(:x)
@y = args[:y] if args.key?(:y)
@z = args[:z] if args.key?(:z)
end
end
# A Product contains ReferenceImages.
class GoogleCloudVisionV1p4beta1Product
include Google::Apis::Core::Hashable
# User-provided metadata to be stored with this product. Must be at most 4096
# characters long.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The user-provided name for this Product. Must not be empty. Must be at most
# 4096 characters long.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# The resource name of the product. Format is: `projects/PROJECT_ID/locations/
# LOC_ID/products/PRODUCT_ID`. This field is ignored when creating a product.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Immutable. The category for the product identified by the reference image.
# This should be one of "homegoods-v2", "apparel-v2", "toys-v2", "packagedgoods-
# v1" or "general-v1". The legacy categories "homegoods", "apparel", and "toys"
# are still supported, but these should not be used for new products.
# Corresponds to the JSON property `productCategory`
# @return [String]
attr_accessor :product_category
# Key-value pairs that can be attached to a product. At query time, constraints
# can be specified based on the product_labels. Note that integer values can be
# provided as strings, e.g. "1199". Only strings with integer values can match a
# range-based restriction which is to be supported soon. Multiple values can be
# assigned to the same key. One product may have up to 500 product_labels.
# Notice that the total number of distinct product_labels over all products in
# one ProductSet cannot exceed 1M, otherwise the product search pipeline will
# refuse to work for that ProductSet.
# Corresponds to the JSON property `productLabels`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1ProductKeyValue>]
attr_accessor :product_labels
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@display_name = args[:display_name] if args.key?(:display_name)
@name = args[:name] if args.key?(:name)
@product_category = args[:product_category] if args.key?(:product_category)
@product_labels = args[:product_labels] if args.key?(:product_labels)
end
end
# A product label represented as a key-value pair.
class GoogleCloudVisionV1p4beta1ProductKeyValue
include Google::Apis::Core::Hashable
# The key of the label attached to the product. Cannot be empty and cannot
# exceed 128 bytes.
# Corresponds to the JSON property `key`
# @return [String]
attr_accessor :key
# The value of the label attached to the product. Cannot be empty and cannot
# exceed 128 bytes.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@key = args[:key] if args.key?(:key)
@value = args[:value] if args.key?(:value)
end
end
# Results for a product search request.
class GoogleCloudVisionV1p4beta1ProductSearchResults
include Google::Apis::Core::Hashable
# Timestamp of the index which provided these results. Products added to the
# product set and products removed from the product set after this time are not
# reflected in the current results.
# Corresponds to the JSON property `indexTime`
# @return [String]
attr_accessor :index_time
# List of results grouped by products detected in the query image. Each entry
# corresponds to one bounding polygon in the query image, and contains the
# matching products specific to that region. There may be duplicate product
# matches in the union of all the per-product results.
# Corresponds to the JSON property `productGroupedResults`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1ProductSearchResultsGroupedResult>]
attr_accessor :product_grouped_results
# List of results, one for each product match.
# Corresponds to the JSON property `results`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1ProductSearchResultsResult>]
attr_accessor :results
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@index_time = args[:index_time] if args.key?(:index_time)
@product_grouped_results = args[:product_grouped_results] if args.key?(:product_grouped_results)
@results = args[:results] if args.key?(:results)
end
end
# Information about the products similar to a single product in a query image.
class GoogleCloudVisionV1p4beta1ProductSearchResultsGroupedResult
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1BoundingPoly]
attr_accessor :bounding_poly
# List of generic predictions for the object in the bounding box.
# Corresponds to the JSON property `objectAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1ProductSearchResultsObjectAnnotation>]
attr_accessor :object_annotations
# List of results, one for each product match.
# Corresponds to the JSON property `results`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1ProductSearchResultsResult>]
attr_accessor :results
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@object_annotations = args[:object_annotations] if args.key?(:object_annotations)
@results = args[:results] if args.key?(:results)
end
end
# Prediction for what the object in the bounding box is.
class GoogleCloudVisionV1p4beta1ProductSearchResultsObjectAnnotation
include Google::Apis::Core::Hashable
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more information,
# see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Object ID that should align with EntityAnnotation mid.
# Corresponds to the JSON property `mid`
# @return [String]
attr_accessor :mid
# Object name, expressed in its `language_code` language.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Score of the result. Range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@language_code = args[:language_code] if args.key?(:language_code)
@mid = args[:mid] if args.key?(:mid)
@name = args[:name] if args.key?(:name)
@score = args[:score] if args.key?(:score)
end
end
# Information about a product.
class GoogleCloudVisionV1p4beta1ProductSearchResultsResult
include Google::Apis::Core::Hashable
# The resource name of the image from the product that is the closest match to
# the query.
# Corresponds to the JSON property `image`
# @return [String]
attr_accessor :image
# A Product contains ReferenceImages.
# Corresponds to the JSON property `product`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1Product]
attr_accessor :product
# A confidence level on the match, ranging from 0 (no confidence) to 1 (full
# confidence).
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@image = args[:image] if args.key?(:image)
@product = args[:product] if args.key?(:product)
@score = args[:score] if args.key?(:score)
end
end
# A `Property` consists of a user-supplied name/value pair.
class GoogleCloudVisionV1p4beta1Property
include Google::Apis::Core::Hashable
# Name of the property.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Value of numeric properties.
# Corresponds to the JSON property `uint64Value`
# @return [Fixnum]
attr_accessor :uint64_value
# Value of the property.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@name = args[:name] if args.key?(:name)
@uint64_value = args[:uint64_value] if args.key?(:uint64_value)
@value = args[:value] if args.key?(:value)
end
end
# A `ReferenceImage` represents a product image and its associated metadata,
# such as bounding boxes.
class GoogleCloudVisionV1p4beta1ReferenceImage
include Google::Apis::Core::Hashable
# Optional. Bounding polygons around the areas of interest in the reference
# image. If this field is empty, the system will try to detect regions of
# interest. At most 10 bounding polygons will be used. The provided shape is
# converted into a non-rotated rectangle. Once converted, the small edge of the
# rectangle must be greater than or equal to 300 pixels. The aspect ratio must
# be 1:4 or less (i.e. 1:3 is ok; 1:5 is not).
# Corresponds to the JSON property `boundingPolys`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1BoundingPoly>]
attr_accessor :bounding_polys
# The resource name of the reference image. Format is: `projects/PROJECT_ID/
# locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`. This field is
# ignored when creating a reference image.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Required. The Google Cloud Storage URI of the reference image. The URI must
# start with `gs://`.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_polys = args[:bounding_polys] if args.key?(:bounding_polys)
@name = args[:name] if args.key?(:name)
@uri = args[:uri] if args.key?(:uri)
end
end
# Set of features pertaining to the image, computed by computer vision methods
# over safe-search verticals (for example, adult, spoof, medical, violence).
class GoogleCloudVisionV1p4beta1SafeSearchAnnotation
include Google::Apis::Core::Hashable
# Represents the adult content likelihood for the image. Adult content may
# contain elements such as nudity, pornographic images or cartoons, or sexual
# activities.
# Corresponds to the JSON property `adult`
# @return [String]
attr_accessor :adult
# Likelihood that this is a medical image.
# Corresponds to the JSON property `medical`
# @return [String]
attr_accessor :medical
# Likelihood that the request image contains racy content. Racy content may
# include (but is not limited to) skimpy or sheer clothing, strategically
# covered nudity, lewd or provocative poses, or close-ups of sensitive body
# areas.
# Corresponds to the JSON property `racy`
# @return [String]
attr_accessor :racy
# Spoof likelihood. The likelihood that an modification was made to the image's
# canonical version to make it appear funny or offensive.
# Corresponds to the JSON property `spoof`
# @return [String]
attr_accessor :spoof
# Likelihood that this image contains violent content.
# Corresponds to the JSON property `violence`
# @return [String]
attr_accessor :violence
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@adult = args[:adult] if args.key?(:adult)
@medical = args[:medical] if args.key?(:medical)
@racy = args[:racy] if args.key?(:racy)
@spoof = args[:spoof] if args.key?(:spoof)
@violence = args[:violence] if args.key?(:violence)
end
end
# A single symbol representation.
class GoogleCloudVisionV1p4beta1Symbol
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results for the symbol. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1TextAnnotationTextProperty]
attr_accessor :property
# The actual UTF-8 representation of the symbol.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@property = args[:property] if args.key?(:property)
@text = args[:text] if args.key?(:text)
end
end
# TextAnnotation contains a structured representation of OCR extracted text. The
# hierarchy of an OCR extracted text structure is like this: TextAnnotation ->
# Page -> Block -> Paragraph -> Word -> Symbol Each structural component,
# starting from Page, may further have their own properties. Properties describe
# detected languages, breaks etc.. Please refer to the TextAnnotation.
# TextProperty message definition below for more detail.
class GoogleCloudVisionV1p4beta1TextAnnotation
include Google::Apis::Core::Hashable
# List of pages detected by OCR.
# Corresponds to the JSON property `pages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1Page>]
attr_accessor :pages
# UTF-8 text detected on the pages.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@pages = args[:pages] if args.key?(:pages)
@text = args[:text] if args.key?(:text)
end
end
# Detected start or end of a structural component.
class GoogleCloudVisionV1p4beta1TextAnnotationDetectedBreak
include Google::Apis::Core::Hashable
# True if break prepends the element.
# Corresponds to the JSON property `isPrefix`
# @return [Boolean]
attr_accessor :is_prefix
alias_method :is_prefix?, :is_prefix
# Detected break type.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@is_prefix = args[:is_prefix] if args.key?(:is_prefix)
@type = args[:type] if args.key?(:type)
end
end
# Detected language for a structural component.
class GoogleCloudVisionV1p4beta1TextAnnotationDetectedLanguage
include Google::Apis::Core::Hashable
# Confidence of detected language. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more information,
# see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@confidence = args[:confidence] if args.key?(:confidence)
@language_code = args[:language_code] if args.key?(:language_code)
end
end
# Additional information detected on the structural component.
class GoogleCloudVisionV1p4beta1TextAnnotationTextProperty
include Google::Apis::Core::Hashable
# Detected start or end of a structural component.
# Corresponds to the JSON property `detectedBreak`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1TextAnnotationDetectedBreak]
attr_accessor :detected_break
# A list of detected languages together with confidence.
# Corresponds to the JSON property `detectedLanguages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1TextAnnotationDetectedLanguage>]
attr_accessor :detected_languages
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@detected_break = args[:detected_break] if args.key?(:detected_break)
@detected_languages = args[:detected_languages] if args.key?(:detected_languages)
end
end
# A vertex represents a 2D point in the image. NOTE: the vertex coordinates are
# in the same scale as the original image.
class GoogleCloudVisionV1p4beta1Vertex
include Google::Apis::Core::Hashable
# X coordinate.
# Corresponds to the JSON property `x`
# @return [Fixnum]
attr_accessor :x
# Y coordinate.
# Corresponds to the JSON property `y`
# @return [Fixnum]
attr_accessor :y
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@x = args[:x] if args.key?(:x)
@y = args[:y] if args.key?(:y)
end
end
# Relevant information for the image from the Internet.
class GoogleCloudVisionV1p4beta1WebDetection
include Google::Apis::Core::Hashable
# The service's best guess as to the topic of the request image. Inferred from
# similar images on the open web.
# Corresponds to the JSON property `bestGuessLabels`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1WebDetectionWebLabel>]
attr_accessor :best_guess_labels
# Fully matching images from the Internet. Can include resized copies of the
# query image.
# Corresponds to the JSON property `fullMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1WebDetectionWebImage>]
attr_accessor :full_matching_images
# Web pages containing the matching images from the Internet.
# Corresponds to the JSON property `pagesWithMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1WebDetectionWebPage>]
attr_accessor :pages_with_matching_images
# Partial matching images from the Internet. Those images are similar enough to
# share some key-point features. For example an original image will likely have
# partial matching for its crops.
# Corresponds to the JSON property `partialMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1WebDetectionWebImage>]
attr_accessor :partial_matching_images
# The visually similar image results.
# Corresponds to the JSON property `visuallySimilarImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1WebDetectionWebImage>]
attr_accessor :visually_similar_images
# Deduced entities from similar images on the Internet.
# Corresponds to the JSON property `webEntities`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1WebDetectionWebEntity>]
attr_accessor :web_entities
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@best_guess_labels = args[:best_guess_labels] if args.key?(:best_guess_labels)
@full_matching_images = args[:full_matching_images] if args.key?(:full_matching_images)
@pages_with_matching_images = args[:pages_with_matching_images] if args.key?(:pages_with_matching_images)
@partial_matching_images = args[:partial_matching_images] if args.key?(:partial_matching_images)
@visually_similar_images = args[:visually_similar_images] if args.key?(:visually_similar_images)
@web_entities = args[:web_entities] if args.key?(:web_entities)
end
end
# Entity deduced from similar images on the Internet.
class GoogleCloudVisionV1p4beta1WebDetectionWebEntity
include Google::Apis::Core::Hashable
# Canonical description of the entity, in English.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# Opaque entity ID.
# Corresponds to the JSON property `entityId`
# @return [String]
attr_accessor :entity_id
# Overall relevancy score for the entity. Not normalized and not comparable
# across different image queries.
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@entity_id = args[:entity_id] if args.key?(:entity_id)
@score = args[:score] if args.key?(:score)
end
end
# Metadata for online images.
class GoogleCloudVisionV1p4beta1WebDetectionWebImage
include Google::Apis::Core::Hashable
# (Deprecated) Overall relevancy score for the image.
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
# The result image URL.
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@score = args[:score] if args.key?(:score)
@url = args[:url] if args.key?(:url)
end
end
# Label to provide extra metadata for the web detection.
class GoogleCloudVisionV1p4beta1WebDetectionWebLabel
include Google::Apis::Core::Hashable
# Label for extra metadata.
# Corresponds to the JSON property `label`
# @return [String]
attr_accessor :label
# The BCP-47 language code for `label`, such as "en-US" or "sr-Latn". For more
# information, see http://www.unicode.org/reports/tr35/#
# Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@label = args[:label] if args.key?(:label)
@language_code = args[:language_code] if args.key?(:language_code)
end
end
# Metadata for web pages.
class GoogleCloudVisionV1p4beta1WebDetectionWebPage
include Google::Apis::Core::Hashable
# Fully matching images on the page. Can include resized copies of the query
# image.
# Corresponds to the JSON property `fullMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1WebDetectionWebImage>]
attr_accessor :full_matching_images
# Title for the web page, may contain HTML markups.
# Corresponds to the JSON property `pageTitle`
# @return [String]
attr_accessor :page_title
# Partial matching images on the page. Those images are similar enough to share
# some key-point features. For example an original image will likely have
# partial matching for its crops.
# Corresponds to the JSON property `partialMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1WebDetectionWebImage>]
attr_accessor :partial_matching_images
# (Deprecated) Overall relevancy score for the web page.
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
# The result web page URL.
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@full_matching_images = args[:full_matching_images] if args.key?(:full_matching_images)
@page_title = args[:page_title] if args.key?(:page_title)
@partial_matching_images = args[:partial_matching_images] if args.key?(:partial_matching_images)
@score = args[:score] if args.key?(:score)
@url = args[:url] if args.key?(:url)
end
end
# A word representation.
class GoogleCloudVisionV1p4beta1Word
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results for the word. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1TextAnnotationTextProperty]
attr_accessor :property
# List of symbols in the word. The order of the symbols follows the natural
# reading order.
# Corresponds to the JSON property `symbols`
# @return [Array<Google::Apis::VisionV1p2beta1::GoogleCloudVisionV1p4beta1Symbol>]
attr_accessor :symbols
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@property = args[:property] if args.key?(:property)
@symbols = args[:symbols] if args.key?(:symbols)
end
end
# Information about the products similar to a single product in a query image.
class GroupedResult
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::BoundingPoly]
attr_accessor :bounding_poly
# List of generic predictions for the object in the bounding box.
# Corresponds to the JSON property `objectAnnotations`
# @return [Array<Google::Apis::VisionV1p2beta1::ObjectAnnotation>]
attr_accessor :object_annotations
# List of results, one for each product match.
# Corresponds to the JSON property `results`
# @return [Array<Google::Apis::VisionV1p2beta1::Result>]
attr_accessor :results
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@object_annotations = args[:object_annotations] if args.key?(:object_annotations)
@results = args[:results] if args.key?(:results)
end
end
# If an image was produced from a file (e.g. a PDF), this message gives
# information about the source of that image.
class ImageAnnotationContext
include Google::Apis::Core::Hashable
# If the file was a PDF or TIFF, this field gives the page number within the
# file used to produce the image.
# Corresponds to the JSON property `pageNumber`
# @return [Fixnum]
attr_accessor :page_number
# The URI of the file used to produce the image.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@page_number = args[:page_number] if args.key?(:page_number)
@uri = args[:uri] if args.key?(:uri)
end
end
# Stores image properties, such as dominant colors.
class ImageProperties
include Google::Apis::Core::Hashable
# Set of dominant colors and their corresponding scores.
# Corresponds to the JSON property `dominantColors`
# @return [Google::Apis::VisionV1p2beta1::DominantColorsAnnotation]
attr_accessor :dominant_colors
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@dominant_colors = args[:dominant_colors] if args.key?(:dominant_colors)
end
end
# Response message for the `ImportProductSets` method. This message is returned
# by the google.longrunning.Operations.GetOperation method in the returned
# google.longrunning.Operation.response field.
class ImportProductSetsResponse
include Google::Apis::Core::Hashable
# The list of reference_images that are imported successfully.
# Corresponds to the JSON property `referenceImages`
# @return [Array<Google::Apis::VisionV1p2beta1::ReferenceImage>]
attr_accessor :reference_images
# The rpc status for each ImportProductSet request, including both successes and
# errors. The number of statuses here matches the number of lines in the csv
# file, and statuses[i] stores the success or failure status of processing the i-
# th line of the csv, starting from line 0.
# Corresponds to the JSON property `statuses`
# @return [Array<Google::Apis::VisionV1p2beta1::Status>]
attr_accessor :statuses
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@reference_images = args[:reference_images] if args.key?(:reference_images)
@statuses = args[:statuses] if args.key?(:statuses)
end
end
# The desired input location and metadata.
class InputConfig
include Google::Apis::Core::Hashable
# File content, represented as a stream of bytes. Note: As with all `bytes`
# fields, protobuffers use a pure binary representation, whereas JSON
# representations use base64. Currently, this field only works for
# BatchAnnotateFiles requests. It does not work for AsyncBatchAnnotateFiles
# requests.
# Corresponds to the JSON property `content`
# NOTE: Values are automatically base64 encoded/decoded in the client library.
# @return [String]
attr_accessor :content
# The Google Cloud Storage location where the input will be read from.
# Corresponds to the JSON property `gcsSource`
# @return [Google::Apis::VisionV1p2beta1::GcsSource]
attr_accessor :gcs_source
# The type of the file. Currently only "application/pdf", "image/tiff" and "
# image/gif" are supported. Wildcards are not supported.
# Corresponds to the JSON property `mimeType`
# @return [String]
attr_accessor :mime_type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@content = args[:content] if args.key?(:content)
@gcs_source = args[:gcs_source] if args.key?(:gcs_source)
@mime_type = args[:mime_type] if args.key?(:mime_type)
end
end
# A product label represented as a key-value pair.
class KeyValue
include Google::Apis::Core::Hashable
# The key of the label attached to the product. Cannot be empty and cannot
# exceed 128 bytes.
# Corresponds to the JSON property `key`
# @return [String]
attr_accessor :key
# The value of the label attached to the product. Cannot be empty and cannot
# exceed 128 bytes.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@key = args[:key] if args.key?(:key)
@value = args[:value] if args.key?(:value)
end
end
# A face-specific landmark (for example, a face feature).
class Landmark
include Google::Apis::Core::Hashable
# A 3D position in the image, used primarily for Face detection landmarks. A
# valid Position must have both x and y coordinates. The position coordinates
# are in the same scale as the original image.
# Corresponds to the JSON property `position`
# @return [Google::Apis::VisionV1p2beta1::Position]
attr_accessor :position
# Face landmark type.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@position = args[:position] if args.key?(:position)
@type = args[:type] if args.key?(:type)
end
end
# An object that represents a latitude/longitude pair. This is expressed as a
# pair of doubles to represent degrees latitude and degrees longitude. Unless
# specified otherwise, this must conform to the WGS84 standard. Values must be
# within normalized ranges.
class LatLng
include Google::Apis::Core::Hashable
# The latitude in degrees. It must be in the range [-90.0, +90.0].
# Corresponds to the JSON property `latitude`
# @return [Float]
attr_accessor :latitude
# The longitude in degrees. It must be in the range [-180.0, +180.0].
# Corresponds to the JSON property `longitude`
# @return [Float]
attr_accessor :longitude
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@latitude = args[:latitude] if args.key?(:latitude)
@longitude = args[:longitude] if args.key?(:longitude)
end
end
# Set of detected objects with bounding boxes.
class LocalizedObjectAnnotation
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingPoly`
# @return [Google::Apis::VisionV1p2beta1::BoundingPoly]
attr_accessor :bounding_poly
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more information,
# see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Object ID that should align with EntityAnnotation mid.
# Corresponds to the JSON property `mid`
# @return [String]
attr_accessor :mid
# Object name, expressed in its `language_code` language.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Score of the result. Range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_poly = args[:bounding_poly] if args.key?(:bounding_poly)
@language_code = args[:language_code] if args.key?(:language_code)
@mid = args[:mid] if args.key?(:mid)
@name = args[:name] if args.key?(:name)
@score = args[:score] if args.key?(:score)
end
end
# Detected entity location information.
class LocationInfo
include Google::Apis::Core::Hashable
# An object that represents a latitude/longitude pair. This is expressed as a
# pair of doubles to represent degrees latitude and degrees longitude. Unless
# specified otherwise, this must conform to the WGS84 standard. Values must be
# within normalized ranges.
# Corresponds to the JSON property `latLng`
# @return [Google::Apis::VisionV1p2beta1::LatLng]
attr_accessor :lat_lng
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@lat_lng = args[:lat_lng] if args.key?(:lat_lng)
end
end
# A vertex represents a 2D point in the image. NOTE: the normalized vertex
# coordinates are relative to the original image and range from 0 to 1.
class NormalizedVertex
include Google::Apis::Core::Hashable
# X coordinate.
# Corresponds to the JSON property `x`
# @return [Float]
attr_accessor :x
# Y coordinate.
# Corresponds to the JSON property `y`
# @return [Float]
attr_accessor :y
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@x = args[:x] if args.key?(:x)
@y = args[:y] if args.key?(:y)
end
end
# Prediction for what the object in the bounding box is.
class ObjectAnnotation
include Google::Apis::Core::Hashable
# The BCP-47 language code, such as "en-US" or "sr-Latn". For more information,
# see http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
# Object ID that should align with EntityAnnotation mid.
# Corresponds to the JSON property `mid`
# @return [String]
attr_accessor :mid
# Object name, expressed in its `language_code` language.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Score of the result. Range [0, 1].
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@language_code = args[:language_code] if args.key?(:language_code)
@mid = args[:mid] if args.key?(:mid)
@name = args[:name] if args.key?(:name)
@score = args[:score] if args.key?(:score)
end
end
# This resource represents a long-running operation that is the result of a
# network API call.
class Operation
include Google::Apis::Core::Hashable
# If the value is `false`, it means the operation is still in progress. If `true`
# , the operation is completed, and either `error` or `response` is available.
# Corresponds to the JSON property `done`
# @return [Boolean]
attr_accessor :done
alias_method :done?, :done
# The `Status` type defines a logical error model that is suitable for different
# programming environments, including REST APIs and RPC APIs. It is used by [
# gRPC](https://github.com/grpc). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
# Corresponds to the JSON property `error`
# @return [Google::Apis::VisionV1p2beta1::Status]
attr_accessor :error
# Service-specific metadata associated with the operation. It typically contains
# progress information and common metadata such as create time. Some services
# might not provide such metadata. Any method that returns a long-running
# operation should document the metadata type, if any.
# Corresponds to the JSON property `metadata`
# @return [Hash<String,Object>]
attr_accessor :metadata
# The server-assigned name, which is only unique within the same service that
# originally returns it. If you use the default HTTP mapping, the `name` should
# be a resource name ending with `operations/`unique_id``.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# The normal response of the operation in case of success. If the original
# method returns no data on success, such as `Delete`, the response is `google.
# protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`,
# the response should be the resource. For other methods, the response should
# have the type `XxxResponse`, where `Xxx` is the original method name. For
# example, if the original method name is `TakeSnapshot()`, the inferred
# response type is `TakeSnapshotResponse`.
# Corresponds to the JSON property `response`
# @return [Hash<String,Object>]
attr_accessor :response
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@done = args[:done] if args.key?(:done)
@error = args[:error] if args.key?(:error)
@metadata = args[:metadata] if args.key?(:metadata)
@name = args[:name] if args.key?(:name)
@response = args[:response] if args.key?(:response)
end
end
# Contains metadata for the BatchAnnotateImages operation.
class OperationMetadata
include Google::Apis::Core::Hashable
# The time when the batch request was received.
# Corresponds to the JSON property `createTime`
# @return [String]
attr_accessor :create_time
# Current state of the batch operation.
# Corresponds to the JSON property `state`
# @return [String]
attr_accessor :state
# The time when the operation result was last updated.
# Corresponds to the JSON property `updateTime`
# @return [String]
attr_accessor :update_time
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@create_time = args[:create_time] if args.key?(:create_time)
@state = args[:state] if args.key?(:state)
@update_time = args[:update_time] if args.key?(:update_time)
end
end
# The desired output location and metadata.
class OutputConfig
include Google::Apis::Core::Hashable
# The max number of response protos to put into each output JSON file on Google
# Cloud Storage. The valid range is [1, 100]. If not specified, the default
# value is 20. For example, for one pdf file with 100 pages, 100 response protos
# will be generated. If `batch_size` = 20, then 5 json files each containing 20
# response protos will be written under the prefix `gcs_destination`.`uri`.
# Currently, batch_size only applies to GcsDestination, with potential future
# support for other output configurations.
# Corresponds to the JSON property `batchSize`
# @return [Fixnum]
attr_accessor :batch_size
# The Google Cloud Storage location where the output will be written to.
# Corresponds to the JSON property `gcsDestination`
# @return [Google::Apis::VisionV1p2beta1::GcsDestination]
attr_accessor :gcs_destination
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@batch_size = args[:batch_size] if args.key?(:batch_size)
@gcs_destination = args[:gcs_destination] if args.key?(:gcs_destination)
end
end
# Detected page from OCR.
class Page
include Google::Apis::Core::Hashable
# List of blocks of text, images etc on this page.
# Corresponds to the JSON property `blocks`
# @return [Array<Google::Apis::VisionV1p2beta1::Block>]
attr_accessor :blocks
# Confidence of the OCR results on the page. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Page height. For PDFs the unit is points. For images (including TIFFs) the
# unit is pixels.
# Corresponds to the JSON property `height`
# @return [Fixnum]
attr_accessor :height
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::TextProperty]
attr_accessor :property
# Page width. For PDFs the unit is points. For images (including TIFFs) the unit
# is pixels.
# Corresponds to the JSON property `width`
# @return [Fixnum]
attr_accessor :width
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@blocks = args[:blocks] if args.key?(:blocks)
@confidence = args[:confidence] if args.key?(:confidence)
@height = args[:height] if args.key?(:height)
@property = args[:property] if args.key?(:property)
@width = args[:width] if args.key?(:width)
end
end
# Structural unit of text representing a number of words in certain order.
class Paragraph
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results for the paragraph. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::TextProperty]
attr_accessor :property
# List of all words in this paragraph.
# Corresponds to the JSON property `words`
# @return [Array<Google::Apis::VisionV1p2beta1::Word>]
attr_accessor :words
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@property = args[:property] if args.key?(:property)
@words = args[:words] if args.key?(:words)
end
end
# A 3D position in the image, used primarily for Face detection landmarks. A
# valid Position must have both x and y coordinates. The position coordinates
# are in the same scale as the original image.
class Position
include Google::Apis::Core::Hashable
# X coordinate.
# Corresponds to the JSON property `x`
# @return [Float]
attr_accessor :x
# Y coordinate.
# Corresponds to the JSON property `y`
# @return [Float]
attr_accessor :y
# Z coordinate (or depth).
# Corresponds to the JSON property `z`
# @return [Float]
attr_accessor :z
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@x = args[:x] if args.key?(:x)
@y = args[:y] if args.key?(:y)
@z = args[:z] if args.key?(:z)
end
end
# A Product contains ReferenceImages.
class Product
include Google::Apis::Core::Hashable
# User-provided metadata to be stored with this product. Must be at most 4096
# characters long.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# The user-provided name for this Product. Must not be empty. Must be at most
# 4096 characters long.
# Corresponds to the JSON property `displayName`
# @return [String]
attr_accessor :display_name
# The resource name of the product. Format is: `projects/PROJECT_ID/locations/
# LOC_ID/products/PRODUCT_ID`. This field is ignored when creating a product.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Immutable. The category for the product identified by the reference image.
# This should be one of "homegoods-v2", "apparel-v2", "toys-v2", "packagedgoods-
# v1" or "general-v1". The legacy categories "homegoods", "apparel", and "toys"
# are still supported, but these should not be used for new products.
# Corresponds to the JSON property `productCategory`
# @return [String]
attr_accessor :product_category
# Key-value pairs that can be attached to a product. At query time, constraints
# can be specified based on the product_labels. Note that integer values can be
# provided as strings, e.g. "1199". Only strings with integer values can match a
# range-based restriction which is to be supported soon. Multiple values can be
# assigned to the same key. One product may have up to 500 product_labels.
# Notice that the total number of distinct product_labels over all products in
# one ProductSet cannot exceed 1M, otherwise the product search pipeline will
# refuse to work for that ProductSet.
# Corresponds to the JSON property `productLabels`
# @return [Array<Google::Apis::VisionV1p2beta1::KeyValue>]
attr_accessor :product_labels
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@display_name = args[:display_name] if args.key?(:display_name)
@name = args[:name] if args.key?(:name)
@product_category = args[:product_category] if args.key?(:product_category)
@product_labels = args[:product_labels] if args.key?(:product_labels)
end
end
# Results for a product search request.
class ProductSearchResults
include Google::Apis::Core::Hashable
# Timestamp of the index which provided these results. Products added to the
# product set and products removed from the product set after this time are not
# reflected in the current results.
# Corresponds to the JSON property `indexTime`
# @return [String]
attr_accessor :index_time
# List of results grouped by products detected in the query image. Each entry
# corresponds to one bounding polygon in the query image, and contains the
# matching products specific to that region. There may be duplicate product
# matches in the union of all the per-product results.
# Corresponds to the JSON property `productGroupedResults`
# @return [Array<Google::Apis::VisionV1p2beta1::GroupedResult>]
attr_accessor :product_grouped_results
# List of results, one for each product match.
# Corresponds to the JSON property `results`
# @return [Array<Google::Apis::VisionV1p2beta1::Result>]
attr_accessor :results
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@index_time = args[:index_time] if args.key?(:index_time)
@product_grouped_results = args[:product_grouped_results] if args.key?(:product_grouped_results)
@results = args[:results] if args.key?(:results)
end
end
# A `Property` consists of a user-supplied name/value pair.
class Property
include Google::Apis::Core::Hashable
# Name of the property.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Value of numeric properties.
# Corresponds to the JSON property `uint64Value`
# @return [Fixnum]
attr_accessor :uint64_value
# Value of the property.
# Corresponds to the JSON property `value`
# @return [String]
attr_accessor :value
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@name = args[:name] if args.key?(:name)
@uint64_value = args[:uint64_value] if args.key?(:uint64_value)
@value = args[:value] if args.key?(:value)
end
end
# A `ReferenceImage` represents a product image and its associated metadata,
# such as bounding boxes.
class ReferenceImage
include Google::Apis::Core::Hashable
# Optional. Bounding polygons around the areas of interest in the reference
# image. If this field is empty, the system will try to detect regions of
# interest. At most 10 bounding polygons will be used. The provided shape is
# converted into a non-rotated rectangle. Once converted, the small edge of the
# rectangle must be greater than or equal to 300 pixels. The aspect ratio must
# be 1:4 or less (i.e. 1:3 is ok; 1:5 is not).
# Corresponds to the JSON property `boundingPolys`
# @return [Array<Google::Apis::VisionV1p2beta1::BoundingPoly>]
attr_accessor :bounding_polys
# The resource name of the reference image. Format is: `projects/PROJECT_ID/
# locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`. This field is
# ignored when creating a reference image.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Required. The Google Cloud Storage URI of the reference image. The URI must
# start with `gs://`.
# Corresponds to the JSON property `uri`
# @return [String]
attr_accessor :uri
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_polys = args[:bounding_polys] if args.key?(:bounding_polys)
@name = args[:name] if args.key?(:name)
@uri = args[:uri] if args.key?(:uri)
end
end
# Information about a product.
class Result
include Google::Apis::Core::Hashable
# The resource name of the image from the product that is the closest match to
# the query.
# Corresponds to the JSON property `image`
# @return [String]
attr_accessor :image
# A Product contains ReferenceImages.
# Corresponds to the JSON property `product`
# @return [Google::Apis::VisionV1p2beta1::Product]
attr_accessor :product
# A confidence level on the match, ranging from 0 (no confidence) to 1 (full
# confidence).
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@image = args[:image] if args.key?(:image)
@product = args[:product] if args.key?(:product)
@score = args[:score] if args.key?(:score)
end
end
# Set of features pertaining to the image, computed by computer vision methods
# over safe-search verticals (for example, adult, spoof, medical, violence).
class SafeSearchAnnotation
include Google::Apis::Core::Hashable
# Represents the adult content likelihood for the image. Adult content may
# contain elements such as nudity, pornographic images or cartoons, or sexual
# activities.
# Corresponds to the JSON property `adult`
# @return [String]
attr_accessor :adult
# Likelihood that this is a medical image.
# Corresponds to the JSON property `medical`
# @return [String]
attr_accessor :medical
# Likelihood that the request image contains racy content. Racy content may
# include (but is not limited to) skimpy or sheer clothing, strategically
# covered nudity, lewd or provocative poses, or close-ups of sensitive body
# areas.
# Corresponds to the JSON property `racy`
# @return [String]
attr_accessor :racy
# Spoof likelihood. The likelihood that an modification was made to the image's
# canonical version to make it appear funny or offensive.
# Corresponds to the JSON property `spoof`
# @return [String]
attr_accessor :spoof
# Likelihood that this image contains violent content.
# Corresponds to the JSON property `violence`
# @return [String]
attr_accessor :violence
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@adult = args[:adult] if args.key?(:adult)
@medical = args[:medical] if args.key?(:medical)
@racy = args[:racy] if args.key?(:racy)
@spoof = args[:spoof] if args.key?(:spoof)
@violence = args[:violence] if args.key?(:violence)
end
end
# The `Status` type defines a logical error model that is suitable for different
# programming environments, including REST APIs and RPC APIs. It is used by [
# gRPC](https://github.com/grpc). Each `Status` message contains three pieces of
# data: error code, error message, and error details. You can find out more
# about this error model and how to work with it in the [API Design Guide](https:
# //cloud.google.com/apis/design/errors).
class Status
include Google::Apis::Core::Hashable
# The status code, which should be an enum value of google.rpc.Code.
# Corresponds to the JSON property `code`
# @return [Fixnum]
attr_accessor :code
# A list of messages that carry the error details. There is a common set of
# message types for APIs to use.
# Corresponds to the JSON property `details`
# @return [Array<Hash<String,Object>>]
attr_accessor :details
# A developer-facing error message, which should be in English. Any user-facing
# error message should be localized and sent in the google.rpc.Status.details
# field, or localized by the client.
# Corresponds to the JSON property `message`
# @return [String]
attr_accessor :message
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@code = args[:code] if args.key?(:code)
@details = args[:details] if args.key?(:details)
@message = args[:message] if args.key?(:message)
end
end
# A single symbol representation.
class Symbol
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results for the symbol. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::TextProperty]
attr_accessor :property
# The actual UTF-8 representation of the symbol.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@property = args[:property] if args.key?(:property)
@text = args[:text] if args.key?(:text)
end
end
# TextAnnotation contains a structured representation of OCR extracted text. The
# hierarchy of an OCR extracted text structure is like this: TextAnnotation ->
# Page -> Block -> Paragraph -> Word -> Symbol Each structural component,
# starting from Page, may further have their own properties. Properties describe
# detected languages, breaks etc.. Please refer to the TextAnnotation.
# TextProperty message definition below for more detail.
class TextAnnotation
include Google::Apis::Core::Hashable
# List of pages detected by OCR.
# Corresponds to the JSON property `pages`
# @return [Array<Google::Apis::VisionV1p2beta1::Page>]
attr_accessor :pages
# UTF-8 text detected on the pages.
# Corresponds to the JSON property `text`
# @return [String]
attr_accessor :text
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@pages = args[:pages] if args.key?(:pages)
@text = args[:text] if args.key?(:text)
end
end
# Additional information detected on the structural component.
class TextProperty
include Google::Apis::Core::Hashable
# Detected start or end of a structural component.
# Corresponds to the JSON property `detectedBreak`
# @return [Google::Apis::VisionV1p2beta1::DetectedBreak]
attr_accessor :detected_break
# A list of detected languages together with confidence.
# Corresponds to the JSON property `detectedLanguages`
# @return [Array<Google::Apis::VisionV1p2beta1::DetectedLanguage>]
attr_accessor :detected_languages
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@detected_break = args[:detected_break] if args.key?(:detected_break)
@detected_languages = args[:detected_languages] if args.key?(:detected_languages)
end
end
# A vertex represents a 2D point in the image. NOTE: the vertex coordinates are
# in the same scale as the original image.
class Vertex
include Google::Apis::Core::Hashable
# X coordinate.
# Corresponds to the JSON property `x`
# @return [Fixnum]
attr_accessor :x
# Y coordinate.
# Corresponds to the JSON property `y`
# @return [Fixnum]
attr_accessor :y
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@x = args[:x] if args.key?(:x)
@y = args[:y] if args.key?(:y)
end
end
# Relevant information for the image from the Internet.
class WebDetection
include Google::Apis::Core::Hashable
# The service's best guess as to the topic of the request image. Inferred from
# similar images on the open web.
# Corresponds to the JSON property `bestGuessLabels`
# @return [Array<Google::Apis::VisionV1p2beta1::WebLabel>]
attr_accessor :best_guess_labels
# Fully matching images from the Internet. Can include resized copies of the
# query image.
# Corresponds to the JSON property `fullMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::WebImage>]
attr_accessor :full_matching_images
# Web pages containing the matching images from the Internet.
# Corresponds to the JSON property `pagesWithMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::WebPage>]
attr_accessor :pages_with_matching_images
# Partial matching images from the Internet. Those images are similar enough to
# share some key-point features. For example an original image will likely have
# partial matching for its crops.
# Corresponds to the JSON property `partialMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::WebImage>]
attr_accessor :partial_matching_images
# The visually similar image results.
# Corresponds to the JSON property `visuallySimilarImages`
# @return [Array<Google::Apis::VisionV1p2beta1::WebImage>]
attr_accessor :visually_similar_images
# Deduced entities from similar images on the Internet.
# Corresponds to the JSON property `webEntities`
# @return [Array<Google::Apis::VisionV1p2beta1::WebEntity>]
attr_accessor :web_entities
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@best_guess_labels = args[:best_guess_labels] if args.key?(:best_guess_labels)
@full_matching_images = args[:full_matching_images] if args.key?(:full_matching_images)
@pages_with_matching_images = args[:pages_with_matching_images] if args.key?(:pages_with_matching_images)
@partial_matching_images = args[:partial_matching_images] if args.key?(:partial_matching_images)
@visually_similar_images = args[:visually_similar_images] if args.key?(:visually_similar_images)
@web_entities = args[:web_entities] if args.key?(:web_entities)
end
end
# Entity deduced from similar images on the Internet.
class WebEntity
include Google::Apis::Core::Hashable
# Canonical description of the entity, in English.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# Opaque entity ID.
# Corresponds to the JSON property `entityId`
# @return [String]
attr_accessor :entity_id
# Overall relevancy score for the entity. Not normalized and not comparable
# across different image queries.
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@description = args[:description] if args.key?(:description)
@entity_id = args[:entity_id] if args.key?(:entity_id)
@score = args[:score] if args.key?(:score)
end
end
# Metadata for online images.
class WebImage
include Google::Apis::Core::Hashable
# (Deprecated) Overall relevancy score for the image.
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
# The result image URL.
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@score = args[:score] if args.key?(:score)
@url = args[:url] if args.key?(:url)
end
end
# Label to provide extra metadata for the web detection.
class WebLabel
include Google::Apis::Core::Hashable
# Label for extra metadata.
# Corresponds to the JSON property `label`
# @return [String]
attr_accessor :label
# The BCP-47 language code for `label`, such as "en-US" or "sr-Latn". For more
# information, see http://www.unicode.org/reports/tr35/#
# Unicode_locale_identifier.
# Corresponds to the JSON property `languageCode`
# @return [String]
attr_accessor :language_code
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@label = args[:label] if args.key?(:label)
@language_code = args[:language_code] if args.key?(:language_code)
end
end
# Metadata for web pages.
class WebPage
include Google::Apis::Core::Hashable
# Fully matching images on the page. Can include resized copies of the query
# image.
# Corresponds to the JSON property `fullMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::WebImage>]
attr_accessor :full_matching_images
# Title for the web page, may contain HTML markups.
# Corresponds to the JSON property `pageTitle`
# @return [String]
attr_accessor :page_title
# Partial matching images on the page. Those images are similar enough to share
# some key-point features. For example an original image will likely have
# partial matching for its crops.
# Corresponds to the JSON property `partialMatchingImages`
# @return [Array<Google::Apis::VisionV1p2beta1::WebImage>]
attr_accessor :partial_matching_images
# (Deprecated) Overall relevancy score for the web page.
# Corresponds to the JSON property `score`
# @return [Float]
attr_accessor :score
# The result web page URL.
# Corresponds to the JSON property `url`
# @return [String]
attr_accessor :url
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@full_matching_images = args[:full_matching_images] if args.key?(:full_matching_images)
@page_title = args[:page_title] if args.key?(:page_title)
@partial_matching_images = args[:partial_matching_images] if args.key?(:partial_matching_images)
@score = args[:score] if args.key?(:score)
@url = args[:url] if args.key?(:url)
end
end
# A word representation.
class Word
include Google::Apis::Core::Hashable
# A bounding polygon for the detected image annotation.
# Corresponds to the JSON property `boundingBox`
# @return [Google::Apis::VisionV1p2beta1::BoundingPoly]
attr_accessor :bounding_box
# Confidence of the OCR results for the word. Range [0, 1].
# Corresponds to the JSON property `confidence`
# @return [Float]
attr_accessor :confidence
# Additional information detected on the structural component.
# Corresponds to the JSON property `property`
# @return [Google::Apis::VisionV1p2beta1::TextProperty]
attr_accessor :property
# List of symbols in the word. The order of the symbols follows the natural
# reading order.
# Corresponds to the JSON property `symbols`
# @return [Array<Google::Apis::VisionV1p2beta1::Symbol>]
attr_accessor :symbols
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@bounding_box = args[:bounding_box] if args.key?(:bounding_box)
@confidence = args[:confidence] if args.key?(:confidence)
@property = args[:property] if args.key?(:property)
@symbols = args[:symbols] if args.key?(:symbols)
end
end
end
end
end
| 42.848988 | 151 | 0.635591 |
b91b2d7d36917443ab883c0f4866758305564216 | 586 | module Braspag
# Merchant identification on Braspag
#
# @attr [String] merchant_id the merchant identification number
# @attr [String] merchant_key the merchant identification key
class Merchant
attr_accessor :merchant_id,
:merchant_key
# @param merchant_id [String] the merchant identification number
# @param merchant_key [String] the merchant identification key
def initialize(merchant_id, merchant_key)
@merchant_id = merchant_id
@merchant_key = merchant_key
end
end
end
| 32.555556 | 72 | 0.665529 |
33aab1f20de812ca23ad3cec01bda49216c8fa58 | 1,894 | # gitlab.rb
#external_url 'http://swarm.local/gitlab'
external_url 'http://swarm.local'
# Disable e-mail
gitlab_rails['gitlab_email_enabled'] = false
# Reduce the amount of logs
logging['svlogd_size'] = 2 * 1024 * 1024 # rotate after 2 MB of log data
logging['svlogd_num'] = 3 # keep 3 rotated log files
logging['logrotate_rotate'] = 3 # keep 3 rotated logs
# Disable bundle services
postgresql['enable'] = false
redis['enable'] = false
prometheus['enable'] = false
postgres_exporter['enable'] = false
redis_exporter['enable'] = false
grafana['enable'] = false
# Postgres settings
gitlab_rails['db_adapter'] = 'postgresql'
gitlab_rails['db_encoding'] = 'utf8'
# database service will be named "postgres" in the stack
gitlab_rails['db_host'] = 'pgpool'
gitlab_rails['db_database'] = 'gitlab'
gitlab_rails['db_username'] = 'postgres'
gitlab_rails['db_password'] = 'adminpassword'
# Enable or disable automatic database migrations
# gitlab_rails['auto_migrate'] = false
# Redis settings
# redis service will be named "redis" in the stack
#gitlab_rails['redis_host'] = 'redis'
redis['master_name'] = 'gitlab-redis'
redis['master_password'] = 'str0ng_passw0rd'
gitlab_rails['redis_sentinels'] = [
{'host' => 'redis-sentinel-0', 'port' => 26379},
{'host' => 'redis-sentinel-1', 'port' => 26379},
{'host' => 'redis-sentinel-2', 'port' => 26379}
]
# Prometheus exporters
node_exporter['listen_address'] = '0.0.0.0:9100'
gitlab_exporter['listen_address'] = '0.0.0.0'
gitaly['prometheus_listen_addr'] = "0.0.0.0:9236"
gitlab_workhorse['prometheus_listen_addr'] = "0.0.0.0:9229"
sidekiq['listen_address'] = '0.0.0.0'
gitlab_exporter['listen_port'] = '9168'
#node_exporter['listen_address'] = '0.0.0.0:9100'
#gitlab_monitor['listen_address'] = '0.0.0.0'
#gitaly['prometheus_listen_addr'] = "0.0.0.0:9236"
#gitlab_workhorse['prometheus_listen_addr'] = "0.0.0.0:9229" | 32.655172 | 72 | 0.710665 |
3879bf6cedbc3e98ab14826c2f8daabda21143d1 | 293 | # frozen_string_literal: true
if RUBY_VERSION >= '2.5.0'
require 'simplecov'
SimpleCov.start do
add_filter '/test/'
enable_coverage :branch
end
end
$LOAD_PATH.unshift File.expand_path('../lib', __dir__)
require 'u-struct'
require 'minitest/pride'
require 'minitest/autorun'
| 16.277778 | 54 | 0.723549 |
6a6d53533eca9fff65a90e3cf5462c5a63562d99 | 372 | class SitemapController < ApplicationController
self.view_paths = Mephisto::Plugin.view_paths[:sitemap]
session :off
helper :sitemap
layout nil
def index
headers['Content-Type'] = 'text/xml; charset=utf-8'
@plugin = Mephisto::Plugin[:sitemap]
@sections = site.sections(true)
@last_article = Article.find_by_date(:limit => 1).first
end
end
| 26.571429 | 59 | 0.706989 |
e93b747b0f204473e8a31964db6a7b3940c8c177 | 5,036 | require 'spec_helper'
require 'time'
require 'elasticsearch-transport'
require 'faraday'
require 'ddtrace'
RSpec.describe 'Elasticsearch::Transport::Client tracing' do
before(:each) do
WebMock.enable!
WebMock.disable_net_connect!
end
after(:each) do
WebMock.allow_net_connect!
WebMock.reset!
WebMock.disable!
end
let(:host) { ENV.fetch('TEST_ELASTICSEARCH_HOST', '127.0.0.1') }
let(:port) { ENV.fetch('TEST_ELASTICSEARCH_PORT', '1234').to_i }
let(:server) { "http://#{host}:#{port}" }
let(:client) { Elasticsearch::Client.new(url: server) }
let(:tracer) { get_test_tracer }
let(:spans) { tracer.writer.spans }
let(:span) { spans.first }
before(:each) do
Datadog.configure do |c|
c.use :elasticsearch, tracer: tracer
end
end
context 'when configured with middleware' do
let(:client) do
Elasticsearch::Client.new url: server do |c|
c.use middleware
end
end
let(:middleware) do
stub_const('MyFaradayMiddleware', Class.new(Faraday::Middleware) do
def initialize(app)
super(app)
end
def call(env)
@app.call(env)
end
end)
end
describe 'the handlers' do
subject(:handlers) { client.transport.connections.first.connection.builder.handlers }
it { is_expected.to include(middleware) }
end
end
describe '#perform_request' do
context 'with a' do
context 'GET request' do
subject(:response) { client.perform_request(method, path) }
let(:method) { 'GET' }
let(:path) { '_cluster/health' }
before(:each) do
stub_request(:get, "#{server}/#{path}").to_return(status: 200)
expect(response.status).to eq(200)
end
it 'produces a well-formed trace' do
expect(WebMock).to have_requested(:get, "#{server}/#{path}")
expect(spans).to have(1).items
expect(span.name).to eq('elasticsearch.query')
expect(span.service).to eq('elasticsearch')
expect(span.resource).to eq('GET _cluster/health')
expect(span.get_tag('elasticsearch.url')).to eq('_cluster/health')
expect(span.get_tag('elasticsearch.method')).to eq('GET')
expect(span.get_tag('http.status_code')).to eq('200')
expect(span.get_tag('elasticsearch.params')).to be nil
expect(span.get_tag('elasticsearch.body')).to be nil
expect(span.get_tag('out.host')).to eq(host)
expect(span.get_tag('out.port')).to eq(port.to_s)
end
end
context 'PUT request' do
subject(:response) { client.perform_request(method, path, params, body) }
let(:method) { 'PUT' }
let(:path) { 'my/thing/1' }
let(:params) { { refresh: true } }
before(:each) do
stub_request(:put, "#{server}/#{path}?refresh=true").with(body: body).to_return(status: 201)
expect(response.status).to eq(201)
end
shared_examples_for 'a PUT request trace' do
it do
expect(WebMock).to have_requested(:put, "#{server}/#{path}?refresh=true")
expect(spans).to have(1).items
expect(span.name).to eq('elasticsearch.query')
expect(span.service).to eq('elasticsearch')
expect(span.resource).to eq('PUT my/thing/?')
expect(span.get_tag('elasticsearch.url')).to eq(path)
expect(span.get_tag('elasticsearch.method')).to eq('PUT')
expect(span.get_tag('http.status_code')).to eq('201')
expect(span.get_tag('elasticsearch.params')).to eq(params.to_json)
expect(span.get_tag('elasticsearch.body')).to eq('{"data1":"?","data2":"?"}')
expect(span.get_tag('out.host')).to eq(host)
expect(span.get_tag('out.port')).to eq(port.to_s)
end
end
context 'with Hash params' do
let(:body) { '{"data1":"D1","data2":"D2"}' }
it_behaves_like 'a PUT request trace'
end
context 'with encoded body' do
let(:body) { { data1: 'D1', data2: 'D2' } }
it_behaves_like 'a PUT request trace'
end
end
end
end
describe 'client Datadog::Pin' do
context 'when #service is overridden' do
before(:each) { Datadog::Pin.get_from(client).service = service_name }
let(:service_name) { 'bar' }
describe 'then a GET request' do
subject(:response) { client.perform_request(method, path) }
let(:method) { 'GET' }
let(:path) { '_cluster/health' }
before(:each) do
stub_request(:get, "#{server}/#{path}").to_return(status: 200)
expect(response.status).to eq(200)
end
it 'produces a well-formed trace' do
expect(WebMock).to have_requested(:get, "#{server}/#{path}")
expect(spans).to have(1).items
expect(span.name).to eq('elasticsearch.query')
expect(span.service).to eq(service_name)
end
end
end
end
end
| 31.873418 | 102 | 0.599484 |
79a7ec744a16ed70cf85ce02cc2c52ec5bfeea30 | 491 | cask "twine" do
version "2.3.9"
sha256 "b6afb15ff3f496f88a42e2f268d11875df4d206376cc851f3911bd41ddc58ec5"
# github.com/klembot/twinejs/ was verified as official when first introduced to the cask
url "https://github.com/klembot/twinejs/releases/download/#{version}/twine_#{version}_macos.dmg"
appcast "https://github.com/klembot/twinejs/releases.atom"
name "Twine"
desc "Tool for telling interactive, nonlinear stories"
homepage "https://twinery.org/"
app "Twine.app"
end
| 35.071429 | 98 | 0.767821 |
f8a3c36bf541e916885c1342a12bef62330504da | 998 | cask :v1 => 'switchresx' do
version '4.5.1'
sha256 'b4995cb72046cc2d0ef47d81ec885ca8bc32e52fe80f5bd50f561cb00c06b212'
url "http://www.madrau.com/data/switchresx/SwitchResX#{version.to_i}.zip"
name 'SwitchResX'
homepage 'http://www.madrau.com'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
prefpane 'SwitchResX.prefPane'
uninstall :quit => [
'fr.madrau.switchresx.app',
'fr.madrau.switchresx.daemon', # note, daemon does not :quit cleanly
],
:signal => [
[ 'INT', 'fr.madrau.switchresx.daemon' ],
[ 'KILL', 'fr.madrau.switchresx.daemon' ],
],
:delete => [
'/Library/ScriptingAdditions/SwitchResX Extensions.osax',
'/Library/ScriptingAdditions/SwitchResX Menu.osax',
]
end
| 39.92 | 115 | 0.556112 |
62f5b33e8c230624fcb84aa50dd3296c7b4cb6d8 | 188 | # frozen_string_literal: true
Rails.application.routes.draw do
resources :posts
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
| 31.333333 | 101 | 0.792553 |
b91043b7c4b30dfd0c2b0ca6fdabe49e475f02c9 | 2,017 | # Author:: Xabier de Zuazo (<[email protected]>)
# Copyright:: Copyright 2013-2016, Onddo Labs, SL.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "spec_helper"
require "chef/version/platform"
describe Chef::Version::Platform do
it "is a subclass of Chef::Version" do
v = Chef::Version::Platform.new("1.1")
expect(v).to be_an_instance_of(Chef::Version::Platform)
expect(v).to be_a_kind_of(Chef::Version)
end
it "should transform 1 to 1.0.0" do
expect(Chef::Version::Platform.new("1").to_s).to eq("1.0.0")
end
describe "when creating valid Versions" do
good_versions = %w{1 1.2 1.2.3 1000.80.50000 0.300.25 001.02.00003 1.2-STABLE 10.0-BETA3 9.1-RELEASE-p3}
good_versions.each do |v|
it "should accept '#{v}'" do
Chef::Version::Platform.new v
end
end
end
describe "when given bogus input" do
bad_versions = ["1.2.3.4", "1.2.a4", "a", "1.2 3", "1.2 a",
"1 2 3", "1-2-3", "1_2_3", "1.2_3", "1.2-3"]
the_error = Chef::Exceptions::InvalidPlatformVersion
bad_versions.each do |v|
it "should raise #{the_error} when given '#{v}'" do
expect { Chef::Version::Platform.new v }.to raise_error(the_error)
end
end
end
describe "<=>" do
it "should equate versions 1 and 1.0.0" do
expect(Chef::Version::Platform.new("1")).to eq(Chef::Version::Platform.new("1.0.0"))
end
end
end
| 33.065574 | 109 | 0.647992 |
e8a6ebcd126a64cf2a177238bc7f48ecb8e8d03f | 15,205 | # frozen_string_literal: true
require 'spec_helper'
describe Bitcoin::Builder do
let(:keys) { Array.new(5) { Bitcoin::Key.generate } }
let(:target) { '00'.ljust(64, 'f') }
let(:genesis_block) { create_block('00' * 32, false) }
let(:block) { create_block(genesis_block.hash, false, [], keys[0]) }
before { Bitcoin.network = :spec }
it 'should build blocks' do
result = build_block(target) do |b|
b.prev_block block.hash
b.tx do |t|
t.input { |i| i.coinbase 'foobar' }
t.output do |o|
o.value 5_000_000_000
o.script do |s|
s.type :address
s.recipient keys[0].addr
end
end
end
end
expect(result.hash[0..1]).to eq('00')
expect(result.ver).to eq(1)
expect(result.prev_block).to eq(block.binary_hash.reverse)
expect(result.tx.size).to eq(1)
tx = result.tx[0]
expect(tx.in.size).to eq(1)
expect(tx.out.size).to eq(1)
expect(tx.in[0].script_sig).to eq(['foobar'].pack('H*'))
expect(tx.out[0].value).to eq(5_000_000_000)
end
it 'should build transactions with input and output signatures' do
tx = build_tx do |t|
t.input do |i|
i.prev_out block.tx[0]
i.prev_out_index 0
i.signature_key keys[0]
end
t.output do |o|
o.value 123
o.script do |s|
s.type :address
s.recipient keys[1].addr
end
end
end
expect(tx.in[0].prev_out.reverse_hth).to eq(block.tx[0].hash)
expect(tx.in[0].prev_out_index).to eq(0)
expect(
Bitcoin::Script.new(tx.in[0].script_sig).chunks[1].unpack('H*')[0]
).to eq(keys[0].pub)
expect(tx.out[0].value).to eq(123)
script = Bitcoin::Script.new(tx.out[0].pk_script)
expect(script.type).to eq(:hash160)
expect(script.get_address).to eq(keys[1].addr)
expect(tx.verify_input_signature(0, block.tx[0])).to be true
# check shortcuts also work
tx2 = build_tx do |t|
t.input do |i|
i.prev_out block.tx[0], 0
i.signature_key keys[0]
end
t.output do |o|
o.value 123
o.script { |s| s.recipient keys[1].addr }
end
t.output do |o|
o.to keys[1].addr
o.value 321
end
t.output { |o| o.to 'deadbeef', :op_return }
end
expect(tx2.in[0].prev_out).to eq(tx.in[0].prev_out)
expect(tx2.in[0].prev_out_index).to eq(tx.in[0].prev_out_index)
expect(tx2.out[0].value).to eq(tx.out[0].value)
expect(tx2.out[0].pk_script).to eq(tx.out[0].pk_script)
expect(
Bitcoin::Script.new(tx2.out[0].pk_script).to_string
).to eq(
"OP_DUP OP_HASH160 #{keys[1].hash160} OP_EQUALVERIFY OP_CHECKSIG"
)
expect(
Bitcoin::Script.new(tx2.out[0].pk_script).to_string
).to eq(
"OP_DUP OP_HASH160 #{keys[1].hash160} OP_EQUALVERIFY OP_CHECKSIG"
)
expect(tx2.out[2].value).to eq(0)
end
it 'should build transactions with p2wpkh signatures' do
key = Bitcoin::Key.new('619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9')
script_pubkey = '00141d0f172a0ecb48aee1be1f2687d2963ae33f71a1'.htb
tx = build_tx do |t|
t.input do |i|
i.prev_out(
'8ac60eb9575db5b2d987e29f301b5b819ea83a5c6579d282d189cc04b8e151ef',
1,
script_pubkey,
600_000_000
)
i.signature_key key
end
end
expect(tx.in[0].script_sig).to eq('')
end
it 'should failure to build tx with p2wpkh signatures due to inconsistency of key' do
key = Bitcoin::Key.new('619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9')
script_pubkey = '0014deadbeafdeadbeafdeadbeafdeadbeafdeadbeaf'.htb
expect do
build_tx do |t|
t.input do |i|
i.prev_out(
'8ac60eb9575db5b2d987e29f301b5b819ea83a5c6579d282d189cc04b8e151ef',
1,
script_pubkey,
600_000_000
)
i.signature_key key
end
end
end.to raise_error(RuntimeError, 'Signature error')
end
it 'should build p2sh transaction with p2wpkh signatures' do
key = Bitcoin::Key.new('619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9')
witness_prog = '00141d0f172a0ecb48aee1be1f2687d2963ae33f71a1'.htb
script_pubkey = Bitcoin::Script.to_p2sh_script('bdbb096c26dd64dca06d0fbe8bb5e990ac3cdb42')
tx = build_tx do |t|
t.input do |i|
i.prev_out(SecureRandom.hex(32), 0, script_pubkey, 600_000_000)
i.redeem_script witness_prog
i.signature_key key
end
end
expect(tx.in[0].script_sig).to eq(Bitcoin::Script.pack_pushdata(witness_prog))
end
it 'should allow txin.prev_out as tx or hash' do
prev_tx = block.tx[0]
tx1 = build_tx do |t|
t.input { |i| i.prev_out prev_tx, 0 }
end
tx2 = build_tx do |t|
t.input { |i| i.prev_out prev_tx.hash, 0, prev_tx.out[0].pk_script }
end
expect(tx1.in[0]).to eq(tx2.in[0])
end
it 'should provide tx#output shortcut' do
tx1 = build_tx { |t| t.output(123, keys[1].addr) }
expect(tx1).to eq(
build_tx do |t|
t.output do |o|
o.value 123
o.to keys[1].addr
end
end
)
tx2 = build_tx { |t| t.output(123, keys[1].pub, :pubkey) }
expect(tx2).to eq(
build_tx do |t|
t.output do |o|
o.value 123
o.to keys[1].pub, :pubkey
end
end
)
end
it 'should provide txout#to shortcut' do
tx1 = build_tx do |t|
t.output do |o|
o.value 123
o.to keys[1].addr
end
end
tx2 = build_tx do |t|
t.output do |o|
o.value 123
o.script { |s| s.recipient keys[1].addr }
end
end
expect(tx1.out[0]).to eq(tx2.out[0])
end
it 'should build unsigned transactions and add the signature hash' do
tx = build_tx do |t|
t.input do |i|
i.prev_out block.tx[0]
i.prev_out_index 0
# no signature key
end
t.output do |o|
o.value 123
o.script { |s| s.recipient keys[1].addr }
end
end
expect(tx).to be_a(Bitcoin::P::Tx)
expect(tx.in[0].sig_hash).not_to be_nil
end
it 'should build unsigned multisig transactions and add the signature hash' do
tx1 = build_tx do |t|
t.input do |i|
i.prev_out(block.tx[0], 0)
i.signature_key(keys[0])
end
t.output do |o|
o.value 123
o.to [2, *keys[0..2].map(&:pub)], :multisig
end
end
tx2 = build_tx do |t|
t.input do |i|
i.prev_out tx1, 0
i.signature_key keys[0]
end
t.output do |o|
o.value 123
o.to keys[0].addr
end
end
expect(tx2).to be_a(Bitcoin::P::Tx)
expect(tx2.in[0].sig_hash).not_to be_nil
end
it 'should build unsigned p2sh multisig transactions and add the signature hash' do
tx1 = build_tx do |t|
t.input do |i|
i.prev_out(block.tx[0], 0)
i.signature_key(keys[0])
end
t.output do |o|
o.value 123
o.to [2, *keys[0..2].map(&:pub)], :p2sh_multisig
end
end
tx2 = build_tx do |t|
t.input do |i|
i.prev_out tx1, 0
i.signature_key keys[0]
i.redeem_script tx1.out[0].redeem_script
end
t.output do |o|
o.value 123
o.to keys[0].addr
end
end
expect(tx2).to be_a(Bitcoin::P::Tx)
expect(tx2.in[0].sig_hash).not_to be_nil
end
it 'should add change output' do
change_address = Bitcoin::Key.generate.addr
input_value = block.tx[0].out.map(&:value).inject(:+)
tx = build_tx(input_value: input_value, change_address: change_address) do |t|
t.input do |i|
i.prev_out block.tx[0]
i.prev_out_index 0
i.signature_key keys[0]
end
t.output do |o|
o.value 12_345
o.script { |s| s.recipient keys[1].addr }
end
end
expect(tx.out.count).to be(2)
expect(tx.out.last.value).to eq(50e8 - 12_345)
expect(
Bitcoin::Script.new(tx.out.last.pk_script).get_address
).to eq(change_address)
end
it 'should add change output and leave fee' do
change_address = Bitcoin::Key.generate.addr
input_value = block.tx[0].out.map(&:value).inject(:+)
tx = build_tx(input_value: input_value,
change_address: change_address, leave_fee: true) do |t|
t.input do |i|
i.prev_out block.tx[0]
i.prev_out_index 0
i.signature_key keys[0]
end
t.output do |o|
o.value 12_345
o.script { |s| s.recipient keys[1].addr }
end
end
expect(tx.out.count).to eq(2)
expect(tx.out.last.value)
.to eq(50e8 - 12_345 - Bitcoin.network[:min_tx_fee])
expect(
Bitcoin::Script.new(tx.out.last.pk_script).get_address
).to eq(change_address)
input_value = block.tx[0].out.map(&:value).inject(:+)
tx = build_tx(input_value: input_value,
change_address: change_address, leave_fee: true) do |t|
t.input do |i|
i.prev_out block.tx[0]
i.prev_out_index 0
i.signature_key keys[0]
end
49.times do
t.output do |o|
o.value 1e8
o.script { |s| s.recipient keys[1].addr }
end
end
t.output do |o|
o.value(1e8 - 10_000)
o.script { |s| s.recipient keys[1].addr }
end
end
expect(tx.out.size).to eq(50)
expect(tx.out.map(&:value).inject(:+)).to eq(50e8 - 10_000)
end
it 'randomize_outputs should not modify output values or fees' do
change_address = Bitcoin::Key.generate.addr
input_value = block.tx[0].out.map(&:value).inject(:+)
tx = build_tx(input_value: input_value,
change_address: change_address, leave_fee: true) do |t|
t.input do |i|
i.prev_out block.tx[0]
i.prev_out_index 0
i.signature_key keys[0]
end
t.output do |o|
o.value 12_345
o.script { |s| s.recipient keys[1].addr }
end
t.randomize_outputs
end
expect(tx.out.count).to eq(2)
expect(tx.out.last.value).to eq(50e8 - 12_345 - Bitcoin.network[:min_tx_fee])
expect(
Bitcoin::Script.new(tx.out.last.pk_script).get_address
).to eq(change_address)
input_value = block.tx[0].out.map(&:value).inject(:+)
tx = build_tx(input_value: input_value,
change_address: change_address, leave_fee: true) do |t|
t.input do |i|
i.prev_out block.tx[0]
i.prev_out_index 0
i.signature_key keys[0]
end
49.times do
t.output do |o|
o.value 1e8
o.script { |s| s.recipient keys[1].addr }
end
end
t.output do |o|
o.value(1e8 - 10_000)
o.script { |s| s.recipient keys[1].addr }
end
t.randomize_outputs
end
expect(tx.out.size).to eq(50)
expect(tx.out.map(&:value).inject(:+)).to eq(50e8 - 10_000)
end
it 'should build op_return output' do
builder = Bitcoin::Builder::TxOutBuilder.new
builder.to 'deadbeef', :op_return
expect(builder.txout.parsed_script.to_string).to eq('OP_RETURN deadbeef')
end
it 'should build op_return script' do
result = script do |s|
s.type :op_return
s.recipient 'deadbeef'
end
expect(Bitcoin::Script.new(result).to_string).to eq('OP_RETURN deadbeef')
end
it 'should build address script' do
key = Bitcoin::Key.generate
result = script do |s|
s.type :address
s.recipient key.addr
end
expect(Bitcoin::Script.new(result).to_string)
.to eq("OP_DUP OP_HASH160 #{Bitcoin.hash160_from_address(key.addr)} " \
'OP_EQUALVERIFY OP_CHECKSIG')
end
it 'should build pubkey script' do
key = Bitcoin::Key.generate
result = script do |s|
s.type :pubkey
s.recipient key.pub
end
expect(Bitcoin::Script.new(result).to_string)
.to eq("#{key.pub} OP_CHECKSIG")
end
it 'should build multisig script' do
keys = Array.new(3) { Bitcoin::Key.generate }
result = script do |s|
s.type :multisig
s.recipient 1, keys[0].pub, keys[1].pub
end
expect(Bitcoin::Script.new(result).to_string)
.to eq("1 #{keys[0].pub} #{keys[1].pub} 2 OP_CHECKMULTISIG")
end
it 'should build and spend multisig output' do
tx1 = build_tx do |t|
t.input do |i|
i.prev_out(block.tx[0], 0)
i.signature_key(keys[0])
end
t.output do |o|
o.value 123
o.to [2, *keys[0..2].map(&:pub)], :multisig
end
end
expect(
Bitcoin::Script.new(tx1.out[0].pk_script).to_string
).to eq("2 #{keys[0..2].map(&:pub).join(' ')} 3 OP_CHECKMULTISIG")
tx2 = build_tx do |t|
t.input do |i|
i.prev_out tx1, 0
i.signature_key keys[0..1]
end
t.output do |o|
o.value 123
o.to keys[0].addr
end
end
expect(tx2.verify_input_signature(0, tx1)).to be true
end
it 'should build and spend p2sh multisig output' do
tx1 = build_tx do |t|
t.input do |i|
i.prev_out(block.tx[0], 0)
i.signature_key(keys[0])
end
t.output do |o|
o.value 123
o.to [2, *keys[0..2].map(&:pub)], :p2sh_multisig
end
end
expect(Bitcoin::Script.new(tx1.out[0].pk_script).to_string)
.to eq("OP_HASH160 #{Bitcoin.hash160(tx1.out[0].redeem_script.hth)} OP_EQUAL")
tx2 = build_tx do |t|
t.input do |i|
i.prev_out tx1, 0
# provide 2 required keys for signing
i.signature_key keys[0..1]
# provide the redeem script from the previous output
i.redeem_script tx1.out[0].redeem_script
end
t.output do |o|
o.value 123
o.to keys[0].addr
end
end
script = Bitcoin::Script.new(tx2.in[0].script_sig, tx1.out[0].pk_script)
# check script execution is valid
expect(script.run { true }).to be true
# check signatures are valid
expect(tx2.verify_input_signature(0, tx1)).to be true
end
it 'should build and sign bcash transaction' do
tx = build_tx do |t|
t.input do |i|
prev_tx = block.tx[0]
utxo = prev_tx.out[0]
i.prev_out prev_tx.hash, 0, utxo.script, utxo.amount, 0
i.signature_key keys[0]
end
t.output do |o|
o.value 4_999_900_000
o.script do |s|
s.type :address
s.recipient keys[1].addr
end
end
end
expect(tx.in[0].prev_out.reverse_hth).to eq(block.tx[0].hash)
expect(tx.in[0].prev_out_index).to eq(0)
expect(
Bitcoin::Script.new(tx.in[0].script_sig).chunks[1].unpack('H*')[0]
).to eq(keys[0].pub)
expect(tx.out[0].value).to eq(4_999_900_000)
script = Bitcoin::Script.new(tx.out[0].pk_script)
expect(script.type).to eq(:hash160)
expect(script.get_address).to eq(keys[1].addr)
expect(
tx.verify_input_signature(0, block.tx[0], Time.now.to_i, fork_id: 0)
).to be true
expect(Bitcoin::Script.new(tx.out[0].pk_script).to_string)
.to eq("OP_DUP OP_HASH160 #{keys[1].hash160} OP_EQUALVERIFY OP_CHECKSIG")
end
end
| 27.54529 | 94 | 0.601381 |
e2f3970e4d6b202b12c6f596bc2a81af121df702 | 33,023 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Google
module Cloud
module Language
module V1
# ================================================================ #
#
# Represents the input to API methods.
# @!attribute [rw] type
# @return [Google::Cloud::Language::V1::Document::Type]
# Required. If the type is not set or is +TYPE_UNSPECIFIED+,
# returns an +INVALID_ARGUMENT+ error.
# @!attribute [rw] content
# @return [String]
# The content of the input in string format.
# @!attribute [rw] gcs_content_uri
# @return [String]
# The Google Cloud Storage URI where the file content is located.
# This URI must be of the form: gs://bucket_name/object_name. For more
# details, see https://cloud.google.com/storage/docs/reference-uris.
# NOTE: Cloud Storage object versioning is not supported.
# @!attribute [rw] language
# @return [String]
# The language of the document (if not specified, the language is
# automatically detected). Both ISO and BCP-47 language codes are
# accepted.<br>
# [Language Support](https://cloud.google.com/natural-language/docs/languages)
# lists currently supported languages for each API method.
# If the language (either specified by the caller or automatically detected)
# is not supported by the called API method, an +INVALID_ARGUMENT+ error
# is returned.
class Document
# The document types enum.
module Type
# The content type is not specified.
TYPE_UNSPECIFIED = 0
# Plain text
PLAIN_TEXT = 1
# HTML
HTML = 2
end
end
# Represents a sentence in the input document.
# @!attribute [rw] text
# @return [Google::Cloud::Language::V1::TextSpan]
# The sentence text.
# @!attribute [rw] sentiment
# @return [Google::Cloud::Language::V1::Sentiment]
# For calls to {AnalyzeSentiment} or if
# {Google::Cloud::Language::V1::AnnotateTextRequest::Features#extract_document_sentiment AnnotateTextRequest::Features#extract_document_sentiment} is set to
# true, this field will contain the sentiment for the sentence.
class Sentence; end
# Represents a phrase in the text that is a known entity, such as
# a person, an organization, or location. The API associates information, such
# as salience and mentions, with entities.
# @!attribute [rw] name
# @return [String]
# The representative name for the entity.
# @!attribute [rw] type
# @return [Google::Cloud::Language::V1::Entity::Type]
# The entity type.
# @!attribute [rw] metadata
# @return [Hash{String => String}]
# Metadata associated with the entity.
#
# Currently, Wikipedia URLs and Knowledge Graph MIDs are provided, if
# available. The associated keys are "wikipedia_url" and "mid", respectively.
# @!attribute [rw] salience
# @return [Float]
# The salience score associated with the entity in the [0, 1.0] range.
#
# The salience score for an entity provides information about the
# importance or centrality of that entity to the entire document text.
# Scores closer to 0 are less salient, while scores closer to 1.0 are highly
# salient.
# @!attribute [rw] mentions
# @return [Array<Google::Cloud::Language::V1::EntityMention>]
# The mentions of this entity in the input document. The API currently
# supports proper noun mentions.
# @!attribute [rw] sentiment
# @return [Google::Cloud::Language::V1::Sentiment]
# For calls to {AnalyzeEntitySentiment} or if
# {Google::Cloud::Language::V1::AnnotateTextRequest::Features#extract_entity_sentiment AnnotateTextRequest::Features#extract_entity_sentiment} is set to
# true, this field will contain the aggregate sentiment expressed for this
# entity in the provided document.
class Entity
# The type of the entity.
module Type
# Unknown
UNKNOWN = 0
# Person
PERSON = 1
# Location
LOCATION = 2
# Organization
ORGANIZATION = 3
# Event
EVENT = 4
# Work of art
WORK_OF_ART = 5
# Consumer goods
CONSUMER_GOOD = 6
# Other types
OTHER = 7
end
end
# Represents the smallest syntactic building block of the text.
# @!attribute [rw] text
# @return [Google::Cloud::Language::V1::TextSpan]
# The token text.
# @!attribute [rw] part_of_speech
# @return [Google::Cloud::Language::V1::PartOfSpeech]
# Parts of speech tag for this token.
# @!attribute [rw] dependency_edge
# @return [Google::Cloud::Language::V1::DependencyEdge]
# Dependency tree parse for this token.
# @!attribute [rw] lemma
# @return [String]
# [Lemma](https://en.wikipedia.org/wiki/Lemma_%28morphology%29) of the token.
class Token; end
# Represents the feeling associated with the entire text or entities in
# the text.
# @!attribute [rw] magnitude
# @return [Float]
# A non-negative number in the [0, +inf) range, which represents
# the absolute magnitude of sentiment regardless of score (positive or
# negative).
# @!attribute [rw] score
# @return [Float]
# Sentiment score between -1.0 (negative sentiment) and 1.0
# (positive sentiment).
class Sentiment; end
# Represents part of speech information for a token. Parts of speech
# are as defined in
# http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf
# @!attribute [rw] tag
# @return [Google::Cloud::Language::V1::PartOfSpeech::Tag]
# The part of speech tag.
# @!attribute [rw] aspect
# @return [Google::Cloud::Language::V1::PartOfSpeech::Aspect]
# The grammatical aspect.
# @!attribute [rw] case
# @return [Google::Cloud::Language::V1::PartOfSpeech::Case]
# The grammatical case.
# @!attribute [rw] form
# @return [Google::Cloud::Language::V1::PartOfSpeech::Form]
# The grammatical form.
# @!attribute [rw] gender
# @return [Google::Cloud::Language::V1::PartOfSpeech::Gender]
# The grammatical gender.
# @!attribute [rw] mood
# @return [Google::Cloud::Language::V1::PartOfSpeech::Mood]
# The grammatical mood.
# @!attribute [rw] number
# @return [Google::Cloud::Language::V1::PartOfSpeech::Number]
# The grammatical number.
# @!attribute [rw] person
# @return [Google::Cloud::Language::V1::PartOfSpeech::Person]
# The grammatical person.
# @!attribute [rw] proper
# @return [Google::Cloud::Language::V1::PartOfSpeech::Proper]
# The grammatical properness.
# @!attribute [rw] reciprocity
# @return [Google::Cloud::Language::V1::PartOfSpeech::Reciprocity]
# The grammatical reciprocity.
# @!attribute [rw] tense
# @return [Google::Cloud::Language::V1::PartOfSpeech::Tense]
# The grammatical tense.
# @!attribute [rw] voice
# @return [Google::Cloud::Language::V1::PartOfSpeech::Voice]
# The grammatical voice.
class PartOfSpeech
# The part of speech tags enum.
module Tag
# Unknown
UNKNOWN = 0
# Adjective
ADJ = 1
# Adposition (preposition and postposition)
ADP = 2
# Adverb
ADV = 3
# Conjunction
CONJ = 4
# Determiner
DET = 5
# Noun (common and proper)
NOUN = 6
# Cardinal number
NUM = 7
# Pronoun
PRON = 8
# Particle or other function word
PRT = 9
# Punctuation
PUNCT = 10
# Verb (all tenses and modes)
VERB = 11
# Other: foreign words, typos, abbreviations
X = 12
# Affix
AFFIX = 13
end
# The characteristic of a verb that expresses time flow during an event.
module Aspect
# Aspect is not applicable in the analyzed language or is not predicted.
ASPECT_UNKNOWN = 0
# Perfective
PERFECTIVE = 1
# Imperfective
IMPERFECTIVE = 2
# Progressive
PROGRESSIVE = 3
end
# The grammatical function performed by a noun or pronoun in a phrase,
# clause, or sentence. In some languages, other parts of speech, such as
# adjective and determiner, take case inflection in agreement with the noun.
module Case
# Case is not applicable in the analyzed language or is not predicted.
CASE_UNKNOWN = 0
# Accusative
ACCUSATIVE = 1
# Adverbial
ADVERBIAL = 2
# Complementive
COMPLEMENTIVE = 3
# Dative
DATIVE = 4
# Genitive
GENITIVE = 5
# Instrumental
INSTRUMENTAL = 6
# Locative
LOCATIVE = 7
# Nominative
NOMINATIVE = 8
# Oblique
OBLIQUE = 9
# Partitive
PARTITIVE = 10
# Prepositional
PREPOSITIONAL = 11
# Reflexive
REFLEXIVE_CASE = 12
# Relative
RELATIVE_CASE = 13
# Vocative
VOCATIVE = 14
end
# Depending on the language, Form can be categorizing different forms of
# verbs, adjectives, adverbs, etc. For example, categorizing inflected
# endings of verbs and adjectives or distinguishing between short and long
# forms of adjectives and participles
module Form
# Form is not applicable in the analyzed language or is not predicted.
FORM_UNKNOWN = 0
# Adnomial
ADNOMIAL = 1
# Auxiliary
AUXILIARY = 2
# Complementizer
COMPLEMENTIZER = 3
# Final ending
FINAL_ENDING = 4
# Gerund
GERUND = 5
# Realis
REALIS = 6
# Irrealis
IRREALIS = 7
# Short form
SHORT = 8
# Long form
LONG = 9
# Order form
ORDER = 10
# Specific form
SPECIFIC = 11
end
# Gender classes of nouns reflected in the behaviour of associated words.
module Gender
# Gender is not applicable in the analyzed language or is not predicted.
GENDER_UNKNOWN = 0
# Feminine
FEMININE = 1
# Masculine
MASCULINE = 2
# Neuter
NEUTER = 3
end
# The grammatical feature of verbs, used for showing modality and attitude.
module Mood
# Mood is not applicable in the analyzed language or is not predicted.
MOOD_UNKNOWN = 0
# Conditional
CONDITIONAL_MOOD = 1
# Imperative
IMPERATIVE = 2
# Indicative
INDICATIVE = 3
# Interrogative
INTERROGATIVE = 4
# Jussive
JUSSIVE = 5
# Subjunctive
SUBJUNCTIVE = 6
end
# Count distinctions.
module Number
# Number is not applicable in the analyzed language or is not predicted.
NUMBER_UNKNOWN = 0
# Singular
SINGULAR = 1
# Plural
PLURAL = 2
# Dual
DUAL = 3
end
# The distinction between the speaker, second person, third person, etc.
module Person
# Person is not applicable in the analyzed language or is not predicted.
PERSON_UNKNOWN = 0
# First
FIRST = 1
# Second
SECOND = 2
# Third
THIRD = 3
# Reflexive
REFLEXIVE_PERSON = 4
end
# This category shows if the token is part of a proper name.
module Proper
# Proper is not applicable in the analyzed language or is not predicted.
PROPER_UNKNOWN = 0
# Proper
PROPER = 1
# Not proper
NOT_PROPER = 2
end
# Reciprocal features of a pronoun.
module Reciprocity
# Reciprocity is not applicable in the analyzed language or is not
# predicted.
RECIPROCITY_UNKNOWN = 0
# Reciprocal
RECIPROCAL = 1
# Non-reciprocal
NON_RECIPROCAL = 2
end
# Time reference.
module Tense
# Tense is not applicable in the analyzed language or is not predicted.
TENSE_UNKNOWN = 0
# Conditional
CONDITIONAL_TENSE = 1
# Future
FUTURE = 2
# Past
PAST = 3
# Present
PRESENT = 4
# Imperfect
IMPERFECT = 5
# Pluperfect
PLUPERFECT = 6
end
# The relationship between the action that a verb expresses and the
# participants identified by its arguments.
module Voice
# Voice is not applicable in the analyzed language or is not predicted.
VOICE_UNKNOWN = 0
# Active
ACTIVE = 1
# Causative
CAUSATIVE = 2
# Passive
PASSIVE = 3
end
end
# Represents dependency parse tree information for a token. (For more
# information on dependency labels, see
# http://www.aclweb.org/anthology/P13-2017
# @!attribute [rw] head_token_index
# @return [Integer]
# Represents the head of this token in the dependency tree.
# This is the index of the token which has an arc going to this token.
# The index is the position of the token in the array of tokens returned
# by the API method. If this token is a root token, then the
# +head_token_index+ is its own index.
# @!attribute [rw] label
# @return [Google::Cloud::Language::V1::DependencyEdge::Label]
# The parse label for the token.
class DependencyEdge
# The parse label enum for the token.
module Label
# Unknown
UNKNOWN = 0
# Abbreviation modifier
ABBREV = 1
# Adjectival complement
ACOMP = 2
# Adverbial clause modifier
ADVCL = 3
# Adverbial modifier
ADVMOD = 4
# Adjectival modifier of an NP
AMOD = 5
# Appositional modifier of an NP
APPOS = 6
# Attribute dependent of a copular verb
ATTR = 7
# Auxiliary (non-main) verb
AUX = 8
# Passive auxiliary
AUXPASS = 9
# Coordinating conjunction
CC = 10
# Clausal complement of a verb or adjective
CCOMP = 11
# Conjunct
CONJ = 12
# Clausal subject
CSUBJ = 13
# Clausal passive subject
CSUBJPASS = 14
# Dependency (unable to determine)
DEP = 15
# Determiner
DET = 16
# Discourse
DISCOURSE = 17
# Direct object
DOBJ = 18
# Expletive
EXPL = 19
# Goes with (part of a word in a text not well edited)
GOESWITH = 20
# Indirect object
IOBJ = 21
# Marker (word introducing a subordinate clause)
MARK = 22
# Multi-word expression
MWE = 23
# Multi-word verbal expression
MWV = 24
# Negation modifier
NEG = 25
# Noun compound modifier
NN = 26
# Noun phrase used as an adverbial modifier
NPADVMOD = 27
# Nominal subject
NSUBJ = 28
# Passive nominal subject
NSUBJPASS = 29
# Numeric modifier of a noun
NUM = 30
# Element of compound number
NUMBER = 31
# Punctuation mark
P = 32
# Parataxis relation
PARATAXIS = 33
# Participial modifier
PARTMOD = 34
# The complement of a preposition is a clause
PCOMP = 35
# Object of a preposition
POBJ = 36
# Possession modifier
POSS = 37
# Postverbal negative particle
POSTNEG = 38
# Predicate complement
PRECOMP = 39
# Preconjunt
PRECONJ = 40
# Predeterminer
PREDET = 41
# Prefix
PREF = 42
# Prepositional modifier
PREP = 43
# The relationship between a verb and verbal morpheme
PRONL = 44
# Particle
PRT = 45
# Associative or possessive marker
PS = 46
# Quantifier phrase modifier
QUANTMOD = 47
# Relative clause modifier
RCMOD = 48
# Complementizer in relative clause
RCMODREL = 49
# Ellipsis without a preceding predicate
RDROP = 50
# Referent
REF = 51
# Remnant
REMNANT = 52
# Reparandum
REPARANDUM = 53
# Root
ROOT = 54
# Suffix specifying a unit of number
SNUM = 55
# Suffix
SUFF = 56
# Temporal modifier
TMOD = 57
# Topic marker
TOPIC = 58
# Clause headed by an infinite form of the verb that modifies a noun
VMOD = 59
# Vocative
VOCATIVE = 60
# Open clausal complement
XCOMP = 61
# Name suffix
SUFFIX = 62
# Name title
TITLE = 63
# Adverbial phrase modifier
ADVPHMOD = 64
# Causative auxiliary
AUXCAUS = 65
# Helper auxiliary
AUXVV = 66
# Rentaishi (Prenominal modifier)
DTMOD = 67
# Foreign words
FOREIGN = 68
# Keyword
KW = 69
# List for chains of comparable items
LIST = 70
# Nominalized clause
NOMC = 71
# Nominalized clausal subject
NOMCSUBJ = 72
# Nominalized clausal passive
NOMCSUBJPASS = 73
# Compound of numeric modifier
NUMC = 74
# Copula
COP = 75
# Dislocated relation (for fronted/topicalized elements)
DISLOCATED = 76
# Aspect marker
ASP = 77
# Genitive modifier
GMOD = 78
# Genitive object
GOBJ = 79
# Infinitival modifier
INFMOD = 80
# Measure
MES = 81
# Nominal complement of a noun
NCOMP = 82
end
end
# Represents a mention for an entity in the text. Currently, proper noun
# mentions are supported.
# @!attribute [rw] text
# @return [Google::Cloud::Language::V1::TextSpan]
# The mention text.
# @!attribute [rw] type
# @return [Google::Cloud::Language::V1::EntityMention::Type]
# The type of the entity mention.
# @!attribute [rw] sentiment
# @return [Google::Cloud::Language::V1::Sentiment]
# For calls to {AnalyzeEntitySentiment} or if
# {Google::Cloud::Language::V1::AnnotateTextRequest::Features#extract_entity_sentiment AnnotateTextRequest::Features#extract_entity_sentiment} is set to
# true, this field will contain the sentiment expressed for this mention of
# the entity in the provided document.
class EntityMention
# The supported types of mentions.
module Type
# Unknown
TYPE_UNKNOWN = 0
# Proper name
PROPER = 1
# Common noun (or noun compound)
COMMON = 2
end
end
# Represents an output piece of text.
# @!attribute [rw] content
# @return [String]
# The content of the output text.
# @!attribute [rw] begin_offset
# @return [Integer]
# The API calculates the beginning offset of the content in the original
# document according to the {Google::Cloud::Language::V1::EncodingType EncodingType} specified in the API request.
class TextSpan; end
# Represents a category returned from the text classifier.
# @!attribute [rw] name
# @return [String]
# The name of the category representing the document.
# @!attribute [rw] confidence
# @return [Float]
# The classifier's confidence of the category. Number represents how certain
# the classifier is that this category represents the given text.
class ClassificationCategory; end
# The sentiment analysis request message.
# @!attribute [rw] document
# @return [Google::Cloud::Language::V1::Document]
# Input document.
# @!attribute [rw] encoding_type
# @return [Google::Cloud::Language::V1::EncodingType]
# The encoding type used by the API to calculate sentence offsets.
class AnalyzeSentimentRequest; end
# The sentiment analysis response message.
# @!attribute [rw] document_sentiment
# @return [Google::Cloud::Language::V1::Sentiment]
# The overall sentiment of the input document.
# @!attribute [rw] language
# @return [String]
# The language of the text, which will be the same as the language specified
# in the request or, if not specified, the automatically-detected language.
# See {Google::Cloud::Language::V1::Document#language Document#language} field for more details.
# @!attribute [rw] sentences
# @return [Array<Google::Cloud::Language::V1::Sentence>]
# The sentiment for all the sentences in the document.
class AnalyzeSentimentResponse; end
# The entity-level sentiment analysis request message.
# @!attribute [rw] document
# @return [Google::Cloud::Language::V1::Document]
# Input document.
# @!attribute [rw] encoding_type
# @return [Google::Cloud::Language::V1::EncodingType]
# The encoding type used by the API to calculate offsets.
class AnalyzeEntitySentimentRequest; end
# The entity-level sentiment analysis response message.
# @!attribute [rw] entities
# @return [Array<Google::Cloud::Language::V1::Entity>]
# The recognized entities in the input document with associated sentiments.
# @!attribute [rw] language
# @return [String]
# The language of the text, which will be the same as the language specified
# in the request or, if not specified, the automatically-detected language.
# See {Google::Cloud::Language::V1::Document#language Document#language} field for more details.
class AnalyzeEntitySentimentResponse; end
# The entity analysis request message.
# @!attribute [rw] document
# @return [Google::Cloud::Language::V1::Document]
# Input document.
# @!attribute [rw] encoding_type
# @return [Google::Cloud::Language::V1::EncodingType]
# The encoding type used by the API to calculate offsets.
class AnalyzeEntitiesRequest; end
# The entity analysis response message.
# @!attribute [rw] entities
# @return [Array<Google::Cloud::Language::V1::Entity>]
# The recognized entities in the input document.
# @!attribute [rw] language
# @return [String]
# The language of the text, which will be the same as the language specified
# in the request or, if not specified, the automatically-detected language.
# See {Google::Cloud::Language::V1::Document#language Document#language} field for more details.
class AnalyzeEntitiesResponse; end
# The syntax analysis request message.
# @!attribute [rw] document
# @return [Google::Cloud::Language::V1::Document]
# Input document.
# @!attribute [rw] encoding_type
# @return [Google::Cloud::Language::V1::EncodingType]
# The encoding type used by the API to calculate offsets.
class AnalyzeSyntaxRequest; end
# The syntax analysis response message.
# @!attribute [rw] sentences
# @return [Array<Google::Cloud::Language::V1::Sentence>]
# Sentences in the input document.
# @!attribute [rw] tokens
# @return [Array<Google::Cloud::Language::V1::Token>]
# Tokens, along with their syntactic information, in the input document.
# @!attribute [rw] language
# @return [String]
# The language of the text, which will be the same as the language specified
# in the request or, if not specified, the automatically-detected language.
# See {Google::Cloud::Language::V1::Document#language Document#language} field for more details.
class AnalyzeSyntaxResponse; end
# The document classification request message.
# @!attribute [rw] document
# @return [Google::Cloud::Language::V1::Document]
# Input document.
class ClassifyTextRequest; end
# The document classification response message.
# @!attribute [rw] categories
# @return [Array<Google::Cloud::Language::V1::ClassificationCategory>]
# Categories representing the input document.
class ClassifyTextResponse; end
# The request message for the text annotation API, which can perform multiple
# analysis types (sentiment, entities, and syntax) in one call.
# @!attribute [rw] document
# @return [Google::Cloud::Language::V1::Document]
# Input document.
# @!attribute [rw] features
# @return [Google::Cloud::Language::V1::AnnotateTextRequest::Features]
# The enabled features.
# @!attribute [rw] encoding_type
# @return [Google::Cloud::Language::V1::EncodingType]
# The encoding type used by the API to calculate offsets.
class AnnotateTextRequest
# All available features for sentiment, syntax, and semantic analysis.
# Setting each one to true will enable that specific analysis for the input.
# @!attribute [rw] extract_syntax
# @return [true, false]
# Extract syntax information.
# @!attribute [rw] extract_entities
# @return [true, false]
# Extract entities.
# @!attribute [rw] extract_document_sentiment
# @return [true, false]
# Extract document-level sentiment.
# @!attribute [rw] extract_entity_sentiment
# @return [true, false]
# Extract entities and their associated sentiment.
# @!attribute [rw] classify_text
# @return [true, false]
# Classify the full document into categories.
class Features; end
end
# The text annotations response message.
# @!attribute [rw] sentences
# @return [Array<Google::Cloud::Language::V1::Sentence>]
# Sentences in the input document. Populated if the user enables
# {Google::Cloud::Language::V1::AnnotateTextRequest::Features#extract_syntax AnnotateTextRequest::Features#extract_syntax}.
# @!attribute [rw] tokens
# @return [Array<Google::Cloud::Language::V1::Token>]
# Tokens, along with their syntactic information, in the input document.
# Populated if the user enables
# {Google::Cloud::Language::V1::AnnotateTextRequest::Features#extract_syntax AnnotateTextRequest::Features#extract_syntax}.
# @!attribute [rw] entities
# @return [Array<Google::Cloud::Language::V1::Entity>]
# Entities, along with their semantic information, in the input document.
# Populated if the user enables
# {Google::Cloud::Language::V1::AnnotateTextRequest::Features#extract_entities AnnotateTextRequest::Features#extract_entities}.
# @!attribute [rw] document_sentiment
# @return [Google::Cloud::Language::V1::Sentiment]
# The overall sentiment for the document. Populated if the user enables
# {Google::Cloud::Language::V1::AnnotateTextRequest::Features#extract_document_sentiment AnnotateTextRequest::Features#extract_document_sentiment}.
# @!attribute [rw] language
# @return [String]
# The language of the text, which will be the same as the language specified
# in the request or, if not specified, the automatically-detected language.
# See {Google::Cloud::Language::V1::Document#language Document#language} field for more details.
# @!attribute [rw] categories
# @return [Array<Google::Cloud::Language::V1::ClassificationCategory>]
# Categories identified in the input document.
class AnnotateTextResponse; end
# Represents the text encoding that the caller uses to process the output.
# Providing an +EncodingType+ is recommended because the API provides the
# beginning offsets for various outputs, such as tokens and mentions, and
# languages that natively use different text encodings may access offsets
# differently.
module EncodingType
# If +EncodingType+ is not specified, encoding-dependent information (such as
# +begin_offset+) will be set at +-1+.
NONE = 0
# Encoding-dependent information (such as +begin_offset+) is calculated based
# on the UTF-8 encoding of the input. C++ and Go are examples of languages
# that use this encoding natively.
UTF8 = 1
# Encoding-dependent information (such as +begin_offset+) is calculated based
# on the UTF-16 encoding of the input. Java and Javascript are examples of
# languages that use this encoding natively.
UTF16 = 2
# Encoding-dependent information (such as +begin_offset+) is calculated based
# on the UTF-32 encoding of the input. Python is an example of a language
# that uses this encoding natively.
UTF32 = 3
end
end
end
end
end | 33.255791 | 168 | 0.557399 |
aba17c7ca30134b777821d931ccfc92acbba5e23 | 657 | cask 'syncovery' do
version '8.18e'
sha256 '20211e88ebd073186939f8b04eb426fd41ad8687a57809b89394de96f265f9a8'
url "https://www.syncovery.com/release/SyncoveryMac#{version}.dmg"
name 'Syncovery'
homepage 'https://www.syncovery.com/'
pkg 'SyncoveryMac (double-click to install).pkg'
uninstall pkgutil: 'com.company.Syncovery*'
zap trash: '~/Library/Preferences/Syncovery.ini',
rmdir: [
'~/Library/Application Support/Syncovery',
'~/Saved Application State/com.company.Syncovery.savedState',
'~/Library/Preferences/Syncovery',
'~/Library/Logs/Syncovery',
]
end
| 31.285714 | 76 | 0.668189 |
6251f0b399eadf766bd6168707bfe4ea647ea626 | 920 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership. The
# ASF licenses this file to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class CIMI::Model::SystemCredential < CIMI::Model::Base
href :credential
array :operations do
scalar :rel, :href
end
end
| 36.8 | 75 | 0.76087 |
ff3f714b00f2147adce280e1385b793d206b75e3 | 164 | # frozen_string_literal: true
class AddParentIdToUsers < ActiveRecord::Migration[4.2]
def change
add_column :users, :parent_id, :integer, limit: 8
end
end
| 20.5 | 55 | 0.75 |
1885b293fb42e8db11e950c9dbf6ba891db261ae | 621 | require 'quickeebooks/online/service/service_base'
require 'quickeebooks/online/model/payment'
require 'quickeebooks/online/model/payment_header'
require 'quickeebooks/online/model/payment_line_item'
require 'quickeebooks/online/model/payment_detail'
require 'quickeebooks/online/model/credit_card'
require 'quickeebooks/online/model/credit_charge_info'
require 'quickeebooks/online/model/credit_charge_response'
require 'quickeebooks/common/service_crud'
require 'nokogiri'
module Quickeebooks
module Online
module Service
class Payment < ServiceBase
include ServiceCRUD
end
end
end
end
| 29.571429 | 58 | 0.813205 |
8754853ac855a665d73f4e2f8d217b3f39e70776 | 211 | # frozen_string_literal: true
class ResultsFileNotifierPreview < ActionMailer::Preview
def file_uploaded
file = StoredFile.sample_result.last
ResultsFileNotifierMailer.file_uploaded(file)
end
end
| 19.181818 | 56 | 0.805687 |
d52b946a3e090e9f853fdcd0653f4eae06056b88 | 223 | Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
namespace :api do
namespace :v1 do
resources :videos
end
end
end
| 22.3 | 102 | 0.713004 |
6273fa94da8608396bd1d6b70441988a1b702a0b | 1,651 | require 'rails_helper'
module Toker
RSpec.describe Token, type: :model do
let(:expires_at) { 1.year.from_now }
let(:user) { FactoryGirl.create(:user) }
subject { FactoryGirl.create(:token, user: user, expires_at: expires_at) }
describe 'payload' do
it 'includes token_id and exp' do
expect(subject.payload[:token_id]).to eq subject.id
expect(subject.payload[:exp]).to eq expires_at.to_i
end
end
describe 'generate_key!' do
it 'generates a json web token' do
expect(subject.key).to be_blank
subject.generate_key!
expect(subject.key).to match /\A.*\..*\..*\z/
end
end
describe 'decode' do
context 'given a valid JWT token' do
before(:each) do
subject.generate_key!
subject.save
end
it 'can decode a JWT token' do
token, error = Token.decode(subject.key)
expect(token.user.id).to eq user.id
expect(token.expires_at).to eq expires_at
expect(token.key).to eq subject.key
end
end
context 'given an expired token' do
before do
subject.expires_at = 1.minute.ago
subject.generate_key!
end
it 'returns an error message' do
token, error = Token.decode(subject.key)
expect(error[:Unauthorized]).to eq 'Token expired'
end
end
context 'given an invalid token' do
it 'returns an error message' do
token, error = Token.decode(subject.key)
expect(error[:Unauthorized]).to eq 'Token invalid'
end
end
end
end
end
| 23.927536 | 78 | 0.59782 |
3992c0f8f43903345da76cfc25ac429a0fc2cf9a | 1,293 | require 'spec_helper'
describe Spree::Preferences::Store do
before :each do
@store = Spree::Preferences::StoreInstance.new
end
it "sets and gets a key" do
@store.set :test, 1
@store.exist?(:test).should be true
@store.get(:test).should eq 1
end
it "can set and get false values when cache return nil" do
@store.set :test, false
@store.get(:test).should be false
end
it "will return db value when cache is emtpy and cache the db value" do
preference = Spree::Preference.where(:key => 'test').first_or_initialize
preference.value = '123'
preference.save
Rails.cache.clear
@store.get(:test).should eq '123'
Rails.cache.read(:test).should eq '123'
end
it "should return and cache fallback value when supplied" do
Rails.cache.clear
@store.get(:test){ false }.should be false
Rails.cache.read(:test).should be false
end
it "should return but not cache fallback value when persistence is disabled" do
Rails.cache.clear
@store.stub(:should_persist? => false)
@store.get(:test){ true }.should be true
Rails.cache.exist?(:test).should be false
end
it "should return nil when key can't be found and fallback value is not supplied" do
@store.get(:random_key){ nil }.should be_nil
end
end
| 27.510638 | 86 | 0.688322 |
4a060f15fba824fbd29facafd16a2df2b06836c2 | 2,935 | class SnipsInjection < Formula
desc "Snips Words Injection"
homepage "https://snips.ai"
url "ssh://[email protected]/snipsco/snips-platform.git",
:using => :git, :tag => "0.64.0", :revision => "6df6a46d5ccfb312163c60a0ce2b3b90d8136b54"
head "ssh://[email protected]/snipsco/snips-platform.git",
:using => :git, :branch => "develop"
bottle do
root_url "https://homebrew.snips.ai/bottles"
cellar :any_skip_relocation
sha256 "f431962c233324ccb74c274cfea252b503e0fdae5758f4cd692b8b706f188817" => :el_capitan
end
option "with-debug", "Build with debug support"
option "without-completion", "bash, zsh and fish completion will not be installed"
depends_on "autoconf" => :build # needed by snips-fst-rs
depends_on "automake" => :build # needed by snips-fst-rs
depends_on "pkg-config" => :build # needed by snips-kaldi
depends_on "rust" => :build
depends_on "snips-platform-common"
def install
target_dir = build.with?("debug") ? "target/debug" : "target/release"
args = %W[--root=#{prefix}]
args << "--path=snips-injection/snips-injection"
args << "--debug" if build.with? "debug"
# Needed to build openfst (cstdint issue)
ENV["MACOSX_DEPLOYMENT_TARGET"] = "10.11"
system "cargo", "install", *args
bin.install "#{target_dir}/snips-injection"
mkdir_p "homebrew/snips"
cp_r "snips-asr/snips-g2p-resources", "homebrew/snips/g2p-models"
share.install "homebrew/snips"
if build.with? "completion"
bash_completion.install "#{target_dir}/completion/snips-injection.bash"
fish_completion.install "#{target_dir}/completion/snips-injection.fish"
zsh_completion.install "#{target_dir}/completion/_snips-injection"
end
end
plist_options :manual => "snips-injection -c #{HOMEBREW_PREFIX}/etc/snips.toml"
def plist; <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key>
<false/>
</dict>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_bin}/snips-injection</string>
<string>-c</string>
<string>#{etc}/snips.toml</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>WorkingDirectory</key>
<string>#{var}</string>
<key>StandardErrorPath</key>
<string>#{var}/log/snips/snips-injection.log</string>
<key>StandardOutPath</key>
<string>#{var}/log/snips/snips-injection.log</string>
<key>ProcessType</key>
<string>Interactive</string>
</dict>
</plist>
EOS
end
test do
assert_equal "snips-injection #{version}\n", shell_output("#{bin}/snips-injection --version")
end
end
| 32.611111 | 106 | 0.646337 |
7aa714f18e07b5770fde26b1f230621f062b4af9 | 303 | require 'rails_helper'
RSpec.describe Incident::StudentDuty, type: :model do
# Validations
it { should validate_presence_of :item }
# Columns
it { should have_db_column :id }
it { should have_db_column :item }
# === Relations ===
it { should have_and_belong_to_many(:incidents) }
end
| 21.642857 | 53 | 0.706271 |
919dd48b527fb373209e7af68e194b032f886dcd | 2,690 | class Minio < Formula
desc "Amazon S3 compatible object storage server"
homepage "https://github.com/minio/minio"
url "https://github.com/minio/minio.git",
:tag => "RELEASE.2019-10-02T21-19-38Z",
:revision => "90bfa6260a8ac83199d522ed4c8fe1097dbd5153"
version "20191002211938"
bottle do
cellar :any_skip_relocation
sha256 "a3c06aa40a0338f8313294e99738201a7eb3ba35ea0c7e256a7fff5a62802a9e" => :catalina
sha256 "5ac5fff839ad066e7957f519b4a016f288cb382dc9890a24d58aabf428c0cf78" => :mojave
sha256 "3a2b1d0f5aa0e937bdf025d3941366acf0182ba14b3f18a438061478bdd1e0b3" => :high_sierra
end
depends_on "go" => :build
def install
ENV["GOPATH"] = buildpath
src = buildpath/"src/github.com/minio/minio"
src.install buildpath.children
src.cd do
if build.head?
system "go", "build", "-o", buildpath/"minio"
else
release = `git tag --points-at HEAD`.chomp
version = release.gsub(/RELEASE\./, "").chomp.gsub(/T(\d+)\-(\d+)\-(\d+)Z/, 'T\1:\2:\3Z')
commit = `git rev-parse HEAD`.chomp
proj = "github.com/minio/minio"
system "go", "build", "-o", buildpath/"minio", "-ldflags", <<~EOS
-X #{proj}/cmd.Version=#{version}
-X #{proj}/cmd.ReleaseTag=#{release}
-X #{proj}/cmd.CommitID=#{commit}
EOS
end
end
bin.install buildpath/"minio"
prefix.install_metafiles
end
def post_install
(var/"minio").mkpath
(etc/"minio").mkpath
end
plist_options :manual => "minio server"
def plist
<<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_bin}/minio</string>
<string>server</string>
<string>--config-dir=#{etc}/minio</string>
<string>--address=:9000</string>
<string>#{var}/minio</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>WorkingDirectory</key>
<string>#{HOMEBREW_PREFIX}</string>
<key>StandardErrorPath</key>
<string>#{var}/log/minio.log</string>
<key>StandardOutPath</key>
<string>#{var}/log/minio.log</string>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
EOS
end
test do
system "#{bin}/minio", "version"
end
end
| 30.224719 | 108 | 0.586989 |
035cfe2336c4fd94c1970596e2587017f26cc035 | 1,191 | # frozen_string_literal: true
require "logger"
require "sw/logger/version"
require "sw/log_formatter/simple_formatter"
require "sw/log_formatter/json_formatter"
require "sw/log_formatter/default_formatter"
module Sw
def self.logger(*args)
Sw::Logger.new(*args)
end
def self.json_logger(*args)
Sw::Logger.new(*args).tap do |logger|
logger.formatter = Sw::LogFormatter::JsonFormatter.new
end
end
def self.simple_logger(*args)
Sw::Logger.new(*args).tap do |logger|
logger.formatter = Sw::LogFormatter::SimpleFormatter.new
end
end
class Logger < ::Logger
def initialize(*)
super
self.formatter ||= Sw::LogFormatter::DefaultFormatter.new
end
def with_context(context = {})
return dup.tap { |it| it.formatter.context = context } unless block_given?
formatter.with_context(context.to_h) { yield self }
end
def tagged(*tags)
tags = Array(tags).flatten
return dup.tap { |it| it.formatter.tags = tags } unless block_given?
formatter.with_tags(tags) { yield self }
end
private
def initialize_copy(original)
self.formatter = original.formatter.dup
end
end
end
| 22.903846 | 80 | 0.685139 |
e22d6a8f9df04a7f81d15b795c8c6476b7d49f57 | 855 | # frozen_string_literal: true
lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require_relative 'lib/himekuri_rs/version'
Gem::Specification.new do |spec|
spec.name = 'himekuri_rs'
spec.version = HimekuriRs::VERSION
spec.authors = ['Takayuki Kamiyama']
spec.email = ['[email protected]']
spec.summary = '日めくり、Rust版'
spec.description = '日めくりをRustで作りました。'
spec.homepage = 'https://github.com/takkii/himekuri_rs'
spec.license = 'MIT'
spec.executables = %w[himekuri_rs]
spec.metadata = { 'github_repo' => 'ssh://github.com/takkii/himekuri_rs' }
spec.require_paths = ['lib']
spec.files = Dir.chdir(File.expand_path(__dir__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
end
| 34.2 | 85 | 0.65848 |
03f01974725ed3c0660285a3ad8f182616318fd4 | 326 | # frozen_string_literal: true
describe Grape::Exceptions::InvalidFormatter do
describe '#message' do
let(:error) do
described_class.new(String, 'xml')
end
it 'contains the problem in the message' do
expect(error.message).to include(
'cannot convert String to xml'
)
end
end
end
| 20.375 | 47 | 0.665644 |
e927f9109fd9f99ab6074124d8f1c4df97cb8d5f | 4,817 | require_relative '../puppet/application'
require_relative '../puppet/error'
require_relative '../puppet/util/at_fork'
require 'timeout'
# A general class for triggering a run of another
# class.
class Puppet::Agent
require_relative 'agent/locker'
include Puppet::Agent::Locker
require_relative 'agent/disabler'
include Puppet::Agent::Disabler
require_relative '../puppet/util/splayer'
include Puppet::Util::Splayer
# Special exception class used to signal an agent run has timed out.
class RunTimeoutError < Exception
end
attr_reader :client_class, :client, :should_fork
def initialize(client_class, should_fork=true)
@should_fork = can_fork? && should_fork
@client_class = client_class
end
def can_fork?
Puppet.features.posix? && RUBY_PLATFORM != 'java'
end
def needing_restart?
Puppet::Application.restart_requested?
end
# Perform a run with our client.
def run(client_options = {})
if disabled?
Puppet.notice _("Skipping run of %{client_class}; administratively disabled (Reason: '%{disable_message}');\nUse 'puppet agent --enable' to re-enable.") % { client_class: client_class, disable_message: disable_message }
return
end
result = nil
wait_for_lock_deadline = nil
block_run = Puppet::Application.controlled_run do
splay client_options.fetch :splay, Puppet[:splay]
result = run_in_fork(should_fork) do
with_client(client_options[:transaction_uuid], client_options[:job_id]) do |client|
client_args = client_options.merge(:pluginsync => Puppet::Configurer.should_pluginsync?)
begin
lock do
# NOTE: Timeout is pretty heinous as the location in which it
# throws an error is entirely unpredictable, which means that
# it can interrupt code blocks that perform cleanup or enforce
# sanity. The only thing a Puppet agent should do after this
# error is thrown is die with as much dignity as possible.
Timeout.timeout(Puppet[:runtimeout], RunTimeoutError) do
client.run(client_args)
end
end
rescue Puppet::LockError
now = Time.now.to_i
wait_for_lock_deadline ||= now + Puppet[:maxwaitforlock]
if Puppet[:waitforlock] < 1
Puppet.notice _("Run of %{client_class} already in progress; skipping (%{lockfile_path} exists)") % { client_class: client_class, lockfile_path: lockfile_path }
nil
elsif now >= wait_for_lock_deadline
Puppet.notice _("Exiting now because the maxwaitforlock timeout has been exceeded.")
nil
else
Puppet.info _("Another puppet instance is already running; --waitforlock flag used, waiting for running instance to finish.")
Puppet.info _("Will try again in %{time} seconds.") % {time: Puppet[:waitforlock]}
sleep Puppet[:waitforlock]
retry
end
rescue RunTimeoutError => detail
Puppet.log_exception(detail, _("Execution of %{client_class} did not complete within %{runtimeout} seconds and was terminated.") %
{client_class: client_class,
runtimeout: Puppet[:runtimeout]})
nil
rescue StandardError => detail
Puppet.log_exception(detail, _("Could not run %{client_class}: %{detail}") % { client_class: client_class, detail: detail })
nil
end
end
end
true
end
Puppet.notice _("Shutdown/restart in progress (%{status}); skipping run") % { status: Puppet::Application.run_status.inspect } unless block_run
result
end
def stopping?
Puppet::Application.stop_requested?
end
def run_in_fork(forking = true)
return yield unless forking or Puppet.features.windows?
atForkHandler = Puppet::Util::AtFork.get_handler
atForkHandler.prepare
begin
child_pid = Kernel.fork do
atForkHandler.child
$0 = _("puppet agent: applying configuration")
begin
exit(yield || 1)
rescue NoMemoryError
exit(254)
end
end
ensure
atForkHandler.parent
end
exit_code = Process.waitpid2(child_pid)
exit_code[1].exitstatus
end
private
# Create and yield a client instance, keeping a reference
# to it during the yield.
def with_client(transaction_uuid, job_id = nil)
begin
@client = client_class.new(transaction_uuid, job_id)
rescue StandardError => detail
Puppet.log_exception(detail, _("Could not create instance of %{client_class}: %{detail}") % { client_class: client_class, detail: detail })
return
end
yield @client
ensure
@client = nil
end
end
| 34.163121 | 225 | 0.658501 |
e8b39aebf381e26cf028fb4efb68f6721aba492f | 1,176 | # desc "Explaining what the task does"
namespace :herd do
task reset: :environment do
Herd::Asset.destroy_all
Herd::Transform.destroy_all
FileUtils.rm_rf File.join(Rails.root, 'public', 'uploads', Rails.env)
end
desc "Remove public/assets folder"
task :cleanup do
FileUtils.rm_rf File.join(Rails.root, 'public', 'uploads', Rails.env)
end
task watch: :environment do
Herd::Config.new.watch
end
namespace :config do
task import: :environment do |t,args|
args.with_defaults(:async => false)
Herd::TransformImportWorker.new.perform Rails.root.join('config/herd.yml'), args.async
end
task export: :environment do |t,args|
Herd::TransformExportWorker.new.perform Rails.root.join 'config/herd.yml'
end
end
task :generate, [:async] => [:environment] do |t,args|
args.with_defaults(:async => false)
Herd::Asset.master.where.not(assetable:nil).map do |a|
a.assetable.transforms.each do |t|
t.async = args.async
a.child_with_transform t
end if a.assetable
end
end
end
Rake::Task["db:reset"].enhance ['herd:cleanup']
Rake::Task["db:drop"].enhance ['herd:cleanup']
| 26.727273 | 92 | 0.680272 |
87f80e0f55ca23065dc23170dfcf0aa87125019a | 4,856 | # Copyright © 2011-2020 MUSC Foundation for Research Development~
# All rights reserved.~
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:~
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.~
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following~
# disclaimer in the documentation and/or other materials provided with the distribution.~
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products~
# derived from this software without specific prior written permission.~
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,~
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT~
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL~
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS~
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR~
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.~
require 'rails_helper'
RSpec.describe ProtocolImporterJob, type: :job do
describe '#enqueue' do
it 'should create a Active::Job' do
callback_url = "http://#{ENV['SPARC_API_HOST']}/api/v1/sub_service_requests/6213.json"
ProtocolImporterJob.perform_later(6213, callback_url, 'create')
expect(ProtocolImporterJob).to have_been_enqueued
end
end
describe '#perform', sparc_api: :get_sub_service_request_1, enqueue: false do
#TODO this needs to be updated to match the current method of import
# before do
# service = create(:service)
# @identity = create(:identity, email: "[email protected]")
# allow(Service).to receive(:find).and_return(service)
# allow(Identity).to receive(:find).and_return(@identity)
#
# callback_url = "http://#{ENV['SPARC_API_HOST']}/api/v1/sub_service_requests/6213.json"
# protocol_job = ProtocolImporterJob.perform_later(6213, callback_url, 'update')
# end
#
# it 'should make requests to the objects callback_url' do
# # SPARC sub_service_request
# expect(a_request(:get, /\/v1\/sub_service_requests\/6213.json/)).to have_been_made.once
#
# # SPARC service_request
# expect(a_request(:get, /\/v1\/service_requests\/201780.json/)).to have_been_made.once
#
# # SPARC protocol_request
# expect(a_request(:get, /\/v1\/protocols\/7564.json/)).to have_been_made.once
# end
#
# it 'should import the full Protocol' do
# protocol = Protocol.find_by(sparc_id: 7564)
#
# # Protocol
# expect(Protocol.where('sparc_id IS NULL').any?).to_not be
# expect(protocol.study_cost).to eq(1320300)
# expect(protocol.status).to eq('Complete')
#
# # Arms
# expect(Arm.where('sparc_id IS NULL').any?).to_not be
# expect(Arm.where('protocol_id IS NULL').any?).to_not be
# expect(protocol.arms.any?).to be
# expect(protocol.arms.first.visit_groups.any?).to be
# expect(protocol.arms.first.visit_groups.first.visits.any?).to be
#
# # VisitGroups
# expect(VisitGroup.any?).to be
# expect(VisitGroup.where('sparc_id IS NULL').any?).to_not be
# expect(VisitGroup.where('arm_id IS NULL').any?).to_not be
#
# # LineItems
# expect(LineItem.any?).to be
# expect(LineItem.where('arm_id IS NULL').any?).to_not be
#
# # Visits
# expect(Visit.any?).to be
# expect(Visit.where('sparc_id IS NULL').any?).to_not be
# expect(Visit.where('visit_group_id IS NULL').any?).to_not be
# expect(Visit.where('line_item_id IS NULL').any?).to_not be
# end
#
# it "should POST once to the Faye server on the 'protocols' channel", enqueue: false do
# expect(a_request(:post, /#{ENV['CWF_FAYE_HOST']}/).with{ |request| request.body.match(/protocols/) }).to have_been_made.once
# end
#
# it "should POST once to the Faye server on the 'protocol_id' channel", enqueue: false do
# protocol = Protocol.find_by(sparc_id: 7564)
#
# expect(a_request(:post, /#{ENV['CWF_FAYE_HOST']}/).with { |request| request.body.match(/protocol_#{protocol.id}/) }).to have_been_made.once
# end
#
# it "should NOT utilize PaperTrail on import", enqueue: false do
# protocol = Protocol.find_by(sparc_id: 7564)
#
# expect(protocol.versions.count).to eq(0)
# end
end
end
| 44.962963 | 146 | 0.713344 |
26daeced0287b359cdab0b222efcc7fb9a9ce786 | 338 | require 'ruby_xml_nfe/icms00'
module RubyXmlNfe
class Icms
attr_reader :xml, :icms00_params
def initialize(xml, params)
@xml = xml
@icms00_params = params[:ICMS00]
end
def build
xml.ICMS do
icms00 = RubyXmlNfe::Icms00.new(xml, icms00_params)
icms00.build
end
end
end
end
| 16.9 | 59 | 0.633136 |
9154c0a3e70834e967d4d6edfd6319d78e229b68 | 5,743 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::ServiceFabric::V7_0_0_42
module Models
#
# A record of the times when the repair task entered each state.
#
# This type supports the Service Fabric platform; it is not meant to be
# used directly from your code.
#
class RepairTaskHistory
include MsRestAzure
# @return [DateTime] The time when the repair task entered the Created
# state.
attr_accessor :created_utc_timestamp
# @return [DateTime] The time when the repair task entered the Claimed
# state.
attr_accessor :claimed_utc_timestamp
# @return [DateTime] The time when the repair task entered the Preparing
# state.
attr_accessor :preparing_utc_timestamp
# @return [DateTime] The time when the repair task entered the Approved
# state
attr_accessor :approved_utc_timestamp
# @return [DateTime] The time when the repair task entered the Executing
# state
attr_accessor :executing_utc_timestamp
# @return [DateTime] The time when the repair task entered the Restoring
# state
attr_accessor :restoring_utc_timestamp
# @return [DateTime] The time when the repair task entered the Completed
# state
attr_accessor :completed_utc_timestamp
# @return [DateTime] The time when the repair task started the health
# check in the Preparing state.
attr_accessor :preparing_health_check_start_utc_timestamp
# @return [DateTime] The time when the repair task completed the health
# check in the Preparing state.
attr_accessor :preparing_health_check_end_utc_timestamp
# @return [DateTime] The time when the repair task started the health
# check in the Restoring state.
attr_accessor :restoring_health_check_start_utc_timestamp
# @return [DateTime] The time when the repair task completed the health
# check in the Restoring state.
attr_accessor :restoring_health_check_end_utc_timestamp
#
# Mapper for RepairTaskHistory class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'RepairTaskHistory',
type: {
name: 'Composite',
class_name: 'RepairTaskHistory',
model_properties: {
created_utc_timestamp: {
client_side_validation: true,
required: false,
serialized_name: 'CreatedUtcTimestamp',
type: {
name: 'DateTime'
}
},
claimed_utc_timestamp: {
client_side_validation: true,
required: false,
serialized_name: 'ClaimedUtcTimestamp',
type: {
name: 'DateTime'
}
},
preparing_utc_timestamp: {
client_side_validation: true,
required: false,
serialized_name: 'PreparingUtcTimestamp',
type: {
name: 'DateTime'
}
},
approved_utc_timestamp: {
client_side_validation: true,
required: false,
serialized_name: 'ApprovedUtcTimestamp',
type: {
name: 'DateTime'
}
},
executing_utc_timestamp: {
client_side_validation: true,
required: false,
serialized_name: 'ExecutingUtcTimestamp',
type: {
name: 'DateTime'
}
},
restoring_utc_timestamp: {
client_side_validation: true,
required: false,
serialized_name: 'RestoringUtcTimestamp',
type: {
name: 'DateTime'
}
},
completed_utc_timestamp: {
client_side_validation: true,
required: false,
serialized_name: 'CompletedUtcTimestamp',
type: {
name: 'DateTime'
}
},
preparing_health_check_start_utc_timestamp: {
client_side_validation: true,
required: false,
serialized_name: 'PreparingHealthCheckStartUtcTimestamp',
type: {
name: 'DateTime'
}
},
preparing_health_check_end_utc_timestamp: {
client_side_validation: true,
required: false,
serialized_name: 'PreparingHealthCheckEndUtcTimestamp',
type: {
name: 'DateTime'
}
},
restoring_health_check_start_utc_timestamp: {
client_side_validation: true,
required: false,
serialized_name: 'RestoringHealthCheckStartUtcTimestamp',
type: {
name: 'DateTime'
}
},
restoring_health_check_end_utc_timestamp: {
client_side_validation: true,
required: false,
serialized_name: 'RestoringHealthCheckEndUtcTimestamp',
type: {
name: 'DateTime'
}
}
}
}
}
end
end
end
end
| 33.584795 | 78 | 0.55128 |
1a4369d5971f94907bc99695f7ecba5a1e4d4dd3 | 416 | require 'ransack/adapters/active_record/base'
ActiveRecord::Base.extend Ransack::Adapters::ActiveRecord::Base
case ActiveRecord::VERSION::STRING
when /^3\.0\./
require 'ransack/adapters/active_record/3.0/context'
when /^3\.1\./
require 'ransack/adapters/active_record/3.1/context'
when /^3\.2\./
require 'ransack/adapters/active_record/3.2/context'
else
require 'ransack/adapters/active_record/context'
end
| 29.714286 | 63 | 0.769231 |
79742b0560d061fb73bf12cbfdd423fedcd2f697 | 2,333 | require 'spec_helper'
describe 'Puppet::Type::Group::Provider::Aix' do
let(:provider_class) { Puppet::Type.type(:group).provider(:aix) }
let(:resource) do
Puppet::Type.type(:group).new(
:name => 'test_aix_user',
:ensure => :present
)
end
let(:provider) do
provider_class.new(resource)
end
describe '.find' do
let(:groups) do
objects = [
{ :name => 'group1', :id => '1' },
{ :name => 'group2', :id => '2' }
]
objects
end
let(:ia_module_args) { [ '-R', 'module' ] }
let(:expected_group) do
{
:name => 'group1',
:gid => 1
}
end
before(:each) do
provider_class.stubs(:list_all).with(ia_module_args).returns(groups)
end
it 'raises an ArgumentError if the group does not exist' do
expect do
provider_class.find('non_existent_group', ia_module_args)
end.to raise_error do |error|
expect(error).to be_a(ArgumentError)
expect(error.message).to match('non_existent_group')
end
end
it 'can find the group when passed-in a group name' do
expect(provider_class.find('group1', ia_module_args)).to eql(expected_group)
end
it 'can find the group when passed-in the gid' do
expect(provider_class.find(1, ia_module_args)).to eql(expected_group)
end
end
describe '.users_to_members' do
it 'converts the users attribute to the members property' do
expect(provider_class.users_to_members('foo,bar'))
.to eql(['foo', 'bar'])
end
end
describe '.members_to_users' do
context 'when auth_membership == true' do
before(:each) do
resource[:auth_membership] = true
end
it 'returns only the passed-in members' do
expect(provider_class.members_to_users(provider, ['user1', 'user2']))
.to eql('user1,user2')
end
end
context 'when auth_membership == false' do
before(:each) do
resource[:auth_membership] = false
provider.stubs(:members).returns(['user3', 'user1'])
end
it 'adds the passed-in members to the current list of members, filtering out any duplicates' do
expect(provider_class.members_to_users(provider, ['user1', 'user2']))
.to eql('user1,user2,user3')
end
end
end
end
| 25.637363 | 101 | 0.618517 |
6a4a35bb20e3bf141373f3d9b36c66ad991d1feb | 8,751 | require 'fastlane_core'
require 'credentials_manager'
module Sigh
class Options
def self.available_options
user = CredentialsManager::AppfileConfig.try_fetch_value(:apple_dev_portal_id)
user ||= CredentialsManager::AppfileConfig.try_fetch_value(:apple_id)
[
FastlaneCore::ConfigItem.new(key: :adhoc,
env_name: "SIGH_AD_HOC",
description: "Setting this flag will generate AdHoc profiles instead of App Store Profiles",
is_string: false,
default_value: false,
conflicting_options: [:development],
conflict_block: proc do |value|
UI.user_error!("You can't enable both :development and :adhoc")
end),
FastlaneCore::ConfigItem.new(key: :development,
env_name: "SIGH_DEVELOPMENT",
description: "Renew the development certificate instead of the production one",
is_string: false,
default_value: false,
conflicting_options: [:adhoc],
conflict_block: proc do |value|
UI.user_error!("You can't enable both :development and :adhoc")
end),
FastlaneCore::ConfigItem.new(key: :skip_install,
env_name: "SIGH_SKIP_INSTALL",
description: "By default, the certificate will be added on your local machine. Setting this flag will skip this action",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :force,
env_name: "SIGH_FORCE",
description: "Renew provisioning profiles regardless of its state - to automatically add all devices for ad hoc profiles",
is_string: false,
short_option: "-f",
default_value: false),
FastlaneCore::ConfigItem.new(key: :app_identifier,
short_option: "-a",
env_name: "SIGH_APP_IDENTIFIER",
description: "The bundle identifier of your app",
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier)),
FastlaneCore::ConfigItem.new(key: :username,
short_option: "-u",
env_name: "SIGH_USERNAME",
description: "Your Apple ID Username",
default_value: user),
FastlaneCore::ConfigItem.new(key: :team_id,
short_option: "-b",
env_name: "SIGH_TEAM_ID",
description: "The ID of your Developer Portal team if you're in multiple teams",
optional: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_id),
verify_block: proc do |value|
ENV["FASTLANE_TEAM_ID"] = value.to_s
end),
FastlaneCore::ConfigItem.new(key: :team_name,
short_option: "-l",
env_name: "SIGH_TEAM_NAME",
description: "The name of your Developer Portal team if you're in multiple teams",
optional: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_name),
verify_block: proc do |value|
ENV["FASTLANE_TEAM_NAME"] = value.to_s
end),
FastlaneCore::ConfigItem.new(key: :provisioning_name,
short_option: "-n",
env_name: "SIGH_PROVISIONING_PROFILE_NAME",
description: "The name of the profile that is used on the Apple Developer Portal",
optional: true),
FastlaneCore::ConfigItem.new(key: :ignore_profiles_with_different_name,
env_name: "SIGH_IGNORE_PROFILES_WITH_DIFFERENT_NAME",
description: "Use in combination with :provisioning_name - when true only profiles matching this exact name will be downloaded",
optional: true,
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :output_path,
short_option: "-o",
env_name: "SIGH_OUTPUT_PATH",
description: "Directory in which the profile should be stored",
default_value: "."),
FastlaneCore::ConfigItem.new(key: :cert_id,
short_option: "-i",
env_name: "SIGH_CERTIFICATE_ID",
description: "The ID of the code signing certificate to use (e.g. 78ADL6LVAA) ",
optional: true),
FastlaneCore::ConfigItem.new(key: :cert_owner_name,
short_option: "-c",
env_name: "SIGH_CERTIFICATE",
description: "The certificate name to use for new profiles, or to renew with. (e.g. \"Felix Krause\")",
optional: true),
FastlaneCore::ConfigItem.new(key: :filename,
short_option: "-q",
env_name: "SIGH_PROFILE_FILE_NAME",
optional: true,
description: "Filename to use for the generated provisioning profile (must include .mobileprovision)",
verify_block: proc do |value|
UI.user_error!("The output name must end with .mobileprovision") unless value.end_with?(".mobileprovision")
end),
FastlaneCore::ConfigItem.new(key: :skip_fetch_profiles,
env_name: "SIGH_SKIP_FETCH_PROFILES",
description: "Skips the verification of existing profiles which is useful if you have thousands of profiles",
is_string: false,
default_value: false,
short_option: "-w"),
FastlaneCore::ConfigItem.new(key: :skip_certificate_verification,
short_option: '-z',
env_name: "SIGH_SKIP_CERTIFICATE_VERIFICATION",
description: "Skips the verification of the certificates for every existing profiles. This will make sure the provisioning profile can be used on the local machine",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :platform,
short_option: '-p',
env_name: "SIGH_PLATFORM",
description: "Set the provisioning profile's platform (i.e. ios, tvos)",
is_string: false,
default_value: "ios",
verify_block: proc do |value|
value = value.to_s
pt = %w(macos tvos ios)
UI.user_error!("Unsupported platform, must be: #{pt}") unless pt.include?(value)
end)
]
end
end
end
| 67.837209 | 202 | 0.44852 |
e83ea73f766a11faeb0b4d4b820d522c03007127 | 631 | require 'formula'
class Jetty76 < Formula
homepage 'http://www.eclipse.org/jetty/'
url 'http://download.eclipse.org/jetty/stable-7/dist/jetty-distribution-7.6.9.v20130131.tar.gz'
version '7.6.9'
sha1 '2aaad044f9fd049cf3795268f209297911c64e53'
def install
rm_rf Dir['bin/*.{cmd,bat]}']
libexec.install Dir['*']
(libexec+'logs').mkpath
bin.mkpath
Dir["#{libexec}/bin/*.sh"].each do |f|
scriptname = File.basename(f, '.sh')
(bin+scriptname).write <<-EOS.undent
#!/bin/bash
JETTY_HOME=#{libexec}
#{f} $@
EOS
chmod 0755, bin+scriptname
end
end
end
| 23.37037 | 97 | 0.62599 |
61832bb960d6810ce24820b86b80d4d979ce2f50 | 3,764 | require 'spec_helper'
describe ApnClient::Connection do
describe "#initialize" do
it "opens an SSL connection given host, port, certificate, and certificate_passphrase" do
if certificate_exists?
connection = ApnClient::Connection.new(valid_config)
connection.config.should == valid_config_with_defaults
connection.tcp_socket.is_a?(TCPSocket).should be_true
connection.ssl_socket.is_a?(OpenSSL::SSL::SSLSocket).should be_true
end
end
it "raises an exception if a required argument is missing" do
if certificate_exists?
TCPSocket.expects(:new).never
lambda {
connection = ApnClient::Connection.new(valid_config.reject { |key| key == :host })
}.should raise_error(/host/)
end
end
it "can take a select_timeout argument" do
if certificate_exists?
config = valid_config.merge(:select_timeout => 0.5)
connection = ApnClient::Connection.new(config)
connection.config.should == config
connection.tcp_socket.is_a?(TCPSocket).should be_true
connection.ssl_socket.is_a?(OpenSSL::SSL::SSLSocket).should be_true
end
end
it "does not accept invalid arguments" do
invalid_config = valid_config.merge({:foobar => 1})
TCPSocket.expects(:new).never
lambda {
ApnClient::Connection.new(invalid_config)
}.should raise_error(/foobar/)
end
end
describe "#close" do
it "closes ssl and tcp sockets and sets them to nil" do
if certificate_exists?
connection = ApnClient::Connection.new(valid_config)
connection.close
connection.tcp_socket.should be_nil
connection.ssl_socket.should be_nil
end
end
end
describe "#write" do
it "invokes write on the ssl socket" do
ApnClient::Connection.any_instance.expects(:connect_to_socket)
connection = ApnClient::Connection.new(valid_config)
ssl_socket = mock('ssl_socket')
ssl_socket.expects(:write).with('foo')
connection.expects(:ssl_socket).returns(ssl_socket)
connection.write(:foo)
end
end
describe "#read" do
it "invokes read on the ssl socket" do
ApnClient::Connection.any_instance.expects(:connect_to_socket)
connection = ApnClient::Connection.new(valid_config)
ssl_socket = mock('ssl_socket')
ssl_socket.expects(:read).with("foo", "bar")
connection.expects(:ssl_socket).returns(ssl_socket)
connection.read("foo", "bar")
end
end
describe "#select" do
it "does an IO.select on the ssl socket with a timeout" do
ApnClient::Connection.any_instance.expects(:connect_to_socket)
connection = ApnClient::Connection.new(valid_config.merge(:select_timeout => 0.9))
ssl_socket = mock('ssl_socket')
connection.expects(:ssl_socket).returns(ssl_socket)
IO.expects(:select).with([ssl_socket], nil, nil, 0.9)
connection.select
end
end
describe ".open" do
it "opens a connection, yields it to a block, then closes it" do
ApnClient::Connection.any_instance.expects(:connect_to_socket)
ApnClient::Connection.any_instance.expects(:close)
ApnClient::Connection.open(valid_config) do |connection|
connection.config.should == valid_config_with_defaults
end
end
end
def certificate_path
File.join(File.dirname(__FILE__), "certificate.pem")
end
def certificate_exists?
File.exists?(certificate_path)
end
def valid_config
{
:host => 'gateway.push.apple.com',
:port => 2195,
:certificate => IO.read(certificate_path),
:certificate_passphrase => ''
}
end
def valid_config_with_defaults
valid_config.merge(:select_timeout => 0.1)
end
end
| 32.17094 | 93 | 0.684378 |
6179e2903b618a89f1ac937d80aec544ed075c0c | 2,089 | module Intrigue
module Issue
class VulnApacheStrutsJakartaParser20175638 < BaseIssue
def self.generate(instance_details={})
{
name: "apache_struts_jakarta_parser",
pretty_name: "Vulnerable Apache Struts Jakarta Parser (CVE-2017-5638)",
identifiers: [
{ type: "CVE", name: "CVE-2017-5638" }
],
severity: 1,
status: "confirmed",
category: "vulnerability",
description: "A remote code execution vulnerability (CVE-2017-5638) in the Jakarta Multipart Parser in affected versions of the Apache Struts framework can enable a remote attacker to run arbitrary commands on the web server. Since its initial disclosure, this vulnerability has received significant attention, and has been exploited in the wild. Public exploits are also available for this vulnerability.",
remediation: "Customers are advised to immediately patch their servers to the latest versions of Apache Struts or implement recommended workarounds. See https://cwiki.apache.org/confluence/display/WW/S2-045 for more details.",
affected_software: [
{ :vendor => "Apache", :product => "Struts", :version_from => "2.3.5", :version_to => "2.3.31" },
{ :vendor => "Apache", :product => "Struts", :version_from => "2.5.0", :version_to => "2.5.10" }
],
references: [ # types: description, remediation, detection_rule, exploit, threat_intel
{ type: "description", uri: "https://nvd.nist.gov/vuln/detail/CVE-2017-5638" },
{ type: "remediation", uri: "https://cwiki.apache.org/confluence/display/WW/S2-045" },
{ type: "detection_rule", uri: "https://exchange.xforce.ibmcloud.com/collection/Apache-Struts-Jakarta-Multipart-parser-code-execution-c7cfb0c86407ba72f6b5cb9fdbc98112" },
{ type: "exploit", uri: "https://packetstormsecurity.com/files/141494" },
{ type: "threat_intel", uri: "https://blog.rapid7.com/2017/03/09/apache-jakarta-vulnerability-attacks-in-the-wild/" }
],
check: "vuln/apache_struts_jakarta_parser"
}.merge!(instance_details)
end
end
end
end
| 56.459459 | 414 | 0.696984 |
62ed68d708a088a29b8aa44546bffa5a83739834 | 1,130 | RSpec.describe Section, type: :model do
it { is_expected.to belong_to(:journey) }
describe "validations" do
it { is_expected.to validate_presence_of(:title) }
it { is_expected.to validate_presence_of(:contentful_id) }
end
describe "default_order" do
it "orders by order ASC" do
oldest_section = create(:section, order: 0)
middle_aged_section = create(:section, order: 1)
youngest_section = create(:section, order: 2)
result = described_class.all
expect(result.first).to eq(oldest_section)
expect(result.second).to eq(middle_aged_section)
expect(result.third).to eq(youngest_section)
end
end
describe "#incomplete?" do
it "returns true if all steps in the section are not complete" do
task = create(:task)
question = create(:step, :radio, task: task)
statement = create(:step, :statement, task: task)
section = create(:section, tasks: [task])
expect(section.incomplete?).to be true
create(:radio_answer, step: question)
statement.acknowledge!
expect(section.incomplete?).to be false
end
end
end
| 28.974359 | 69 | 0.680531 |
914d7011aa3b1e09cdd5b7e3a634c19a7fd68832 | 826 | require_relative 'rule_definition'
class RuleRegistry
attr_reader :rules
def initialize
@rules = []
end
def definition(id:,
type:,
message:)
rule_definition = RuleDefinition.new(id: id,
type: type,
message: message)
existing_def = by_id id
if existing_def.nil?
add_rule rule_definition
else
existing_def
end
end
def by_id(id)
@rules.find { |rule| rule.id == id }
end
def warnings
@rules.select { |rule| rule.type == RuleDefinition::WARNING }
end
def failings
@rules.select { |rule| rule.type == RuleDefinition::FAILING_VIOLATION }
end
private
def add_rule(violation_def)
@rules << violation_def
violation_def
end
end
| 18.772727 | 75 | 0.578692 |
916c22a2f5269a831298bcc7d587c2feca47aaf7 | 25 | get '/', to: 'site#main'
| 12.5 | 24 | 0.52 |
bf4da029e73aa0152d2be864f961833add2ead78 | 493 | module BetfairNg
# Declares the module for API interactions
#
module API
# Declares the module for Data types
#
module DataTypes
# Declares TimeRange
#
# TimeRange
#
# == Fields
# - from
# - to
#
class TimeRange < Base
# from, format: ISO 8601)
# @!attribute [w]
#
field :from, type: Time, required: false
# to, format: ISO 8601
# @!attribute [w]
#
field :to, type: Time, required: false
end
end
end
end
| 13.694444 | 44 | 0.56998 |
08308486681606a6fa3bb68801b615d56a84f95d | 351 | Gem::Specification.new do |s|
s.name = 'dynamic_form'
s.version = '1.0.0'
s.author = 'David Heinemeier Hansson'
s.email = '[email protected]'
s.summary = 'Deprecated dynamic form helpers: input, form, error_messages_for, error_messages_on'
s.add_dependency('rails', '6.1.3')
s.files = Dir['lib/**/*']
s.require_path = 'lib'
end
| 27 | 99 | 0.680912 |
62ed67f385eb9b48e1cccacf4560ad63a88a13da | 1,132 | module Bsl
class Mapper
def initialize(booking_request)
@booking_request = booking_request
end
def call # rubocop:disable MethodLength, AbcSize
{
first_name: booking_request.first_name,
last_name: booking_request.last_name,
email: booking_request.email,
phone: booking_request.phone,
memorable_word: booking_request.memorable_word,
date_of_birth: booking_request.date_of_birth,
defined_contribution_pot_confirmed: booking_request.defined_contribution_pot_confirmed,
accessibility_needs: booking_request.accessibility_needs,
additional_info: booking_request.additional_info,
where_you_heard: booking_request.where_you_heard,
gdpr_consent: booking_request.gdpr_consent.to_s,
support: booking_request.supported,
support_name: booking_request.support_name,
support_relationship: booking_request.support_relationship,
support_email: booking_request.support_email,
support_phone: booking_request.support_phone
}
end
private
attr_reader :booking_request
end
end
| 34.30303 | 95 | 0.742933 |
5d3fe38ab6ec3b9cb175cb8863a5112f5200fb6d | 462 | describe Line::Message::Base do
describe '.subclasses' do
it 'returns an array of the subclasses' do
arr = [
Line::Message::Audio,
Line::Message::Contact,
Line::Message::Image,
Line::Message::Location,
Line::Message::RichMessage,
Line::Message::Sticker,
Line::Message::Text,
Line::Message::Video
]
expect(Line::Message::Base.subclasses).to match_array arr
end
end
end
| 25.666667 | 63 | 0.599567 |
1812d0b0700cd54756123e3aa90517cb791670b7 | 1,074 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::IotHub::Mgmt::V2018_04_01
module Models
#
# Input values.
#
class OperationInputs
include MsRestAzure
# @return [String] The name of the IoT hub to check.
attr_accessor :name
#
# Mapper for OperationInputs class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'OperationInputs',
type: {
name: 'Composite',
class_name: 'OperationInputs',
model_properties: {
name: {
client_side_validation: true,
required: true,
serialized_name: 'name',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 23.347826 | 70 | 0.531657 |
26daaa07088c77707512f4bfe49c10a734d058c6 | 13,636 | # Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
# Devise will use the `secret_key_base` as its `secret_key`
# by default. You can change it below and use your own secret key.
# config.secret_key = '3a293c4ebec1119a8510b071a50d46680dd04b5ae9fc092694211e4844e20f16eea23f9421b479d4161cd94da9380ae057012d573946475d84e5dc990c7b103d'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = '[email protected]'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# Configure the parent class responsible to send e-mails.
# config.parent_mailer = 'ActionMailer::Base'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/mongoid'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [:email]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [:email]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [:email]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If 401 status code should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# When false, Devise will not attempt to reload routes on eager load.
# This can reduce the time taken to boot the app but if your application
# requires the Devise mappings to be loaded during boot time the application
# won't boot properly.
# config.reload_routes = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 11. If
# using other algorithms, it sets how many times you want the password to be hashed.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# algorithm), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 11
# Set up a pepper to generate the hashed password.
# config.pepper = '4062d0b0025a5d7f5301edaed292e0c6d26691489f4cf7c09a61e938b799e8ddb9f02846ff05b07a3b9b4b928d50b6dd610e32835cd4ec7d00ca608933f1ad1c'
# Send a notification to the original email when the user's email is changed.
# config.send_email_changed_notification = false
# Send a notification email when the user's password is changed.
# config.send_password_change_notification = false
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [:email]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = true
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 6..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [:email]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = true
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [:email]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# When set to false, does not sign a user in automatically after their password is
# reset. Defaults to true, so a user is signed in automatically after a reset.
# config.sign_in_after_reset_password = true
# ==> Configuration for :encryptable
# Allow you to use another hashing or encryption algorithm besides bcrypt (default).
# You can use :sha1, :sha512 or algorithms from others authentication tools as
# :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
# for default behavior) and :restful_authentication_sha1 (then you should set
# stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using OmniAuth, Devise cannot automatically set OmniAuth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
end
| 49.05036 | 154 | 0.751247 |
ed6e26b9f67a9982538d08f619aa110463f9c367 | 2,726 | # IMPORTANT: This file is generated by cucumber-rails - edit at your own peril.
# It is recommended to regenerate this file in the future when you upgrade to a
# newer version of cucumber-rails. Consider adding your own code to a new file
# instead of editing this one. Cucumber will automatically load all features/**/*.rb
# files.
require "simplecov"
SimpleCov.start "rails"
require "cucumber/rails"
# Capybara defaults to CSS3 selectors rather than XPath.
# If you'd prefer to use XPath, just uncomment this line and adjust any
# selectors in your step definitions to use the XPath syntax.
# Capybara.default_selector = :xpath
# By default, any exception happening in your Rails application will bubble up
# to Cucumber so that your scenario will fail. This is a different from how
# your application behaves in the production environment, where an error page will
# be rendered instead.
#
# Sometimes we want to override this default behaviour and allow Rails to rescue
# exceptions and display an error page (just like when the app is running in production).
# Typical scenarios where you want to do this is when you test your error pages.
# There are two ways to allow Rails to rescue exceptions:
#
# 1) Tag your scenario (or feature) with @allow-rescue
#
# 2) Set the value below to true. Beware that doing this globally is not
# recommended as it will mask a lot of errors for you!
#
ActionController::Base.allow_rescue = false
# Remove/comment out the lines below if your app doesn't have a database.
# For some databases (like MongoDB and CouchDB) you may need to use :truncation instead.
begin
DatabaseCleaner.allow_remote_database_url = true
DatabaseCleaner.strategy = :transaction
rescue NameError
raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it."
end
# You may also want to configure DatabaseCleaner to use different strategies for certain features and scenarios.
# See the DatabaseCleaner documentation for details. Example:
#
# Before('@no-txn,@selenium,@culerity,@celerity,@javascript') do
# # { :except => [:widgets] } may not do what you expect here
# # as Cucumber::Rails::Database.javascript_strategy overrides
# # this setting.
# DatabaseCleaner.strategy = :truncation
# end
#
# Before('~@no-txn', '~@selenium', '~@culerity', '~@celerity', '~@javascript') do
# DatabaseCleaner.strategy = :transaction
# end
#
# Possible values are :truncation and :transaction
# The :transaction strategy is faster, but might give you threading problems.
# See https://github.com/cucumber/cucumber-rails/blob/master/features/choose_javascript_database_strategy.feature
Cucumber::Rails::Database.javascript_strategy = :truncation
| 43.967742 | 113 | 0.76339 |
abf42625c696dc707f99073b26996d9348ce7967 | 22,636 | # == Schema Information
#
# Table name: people
#
# id :integer not null, primary key
# first_name :string(255)
# last_name :string(255)
# display_name :string(255)
# email :string(255) not null
# created_at :datetime not null
# updated_at :datetime not null
# buyer_id :string(255)
# password_digest :string(255)
# account_completed :boolean default(FALSE)
# paypal_email :string(255)
# last_seen_at :datetime
# last_bulk_mailed_at :datetime
# admin :boolean default(FALSE)
# bio :text
# location :string(255)
# url :string(255)
# company :string(255)
# public_email :string(255)
# accepted_terms_at :datetime
# cloudinary_id :string(255)
# deleted :boolean default(FALSE), not null
# profile_completed :boolean default(FALSE), not null
# shopping_cart_id :integer
# stripe_customer_id :string(255)
# suspended_at :datetime
# bounty_hunter :boolean
#
# Indexes
#
# index_people_on_email (email) UNIQUE
# index_people_on_shopping_cart_id (shopping_cart_id)
#
class Person < ActiveRecord::Base
attr_accessible :first_name, :last_name, :display_name, :email, :password, :password_confirmation, :github_account,
:paypal_email, :paypal_email_confirmation, :account, :last_seen_at,
:bio, :location, :public_email, :url, :company,
:accepted_terms_at, :terms, :profile_completed, :shopping_cart_id, :suspended_at, :bounty_hunter
# temporarily holds a raw access token... useful in controllers-and-views
attr_accessor :current_access_token
has_cloudinary_image
has_paper_trail :only => [:first_name, :last_name, :display_name, :email, :password, :bio, :location, :public_email, :url, :company]
has_account class_name: Account::Personal
has_many :orders, -> { where('type LIKE ?', 'Transaction::Order%') }, class_name: 'Transaction'
has_many :bounty_claims
has_many :bounty_claim_responses
has_many :bounty_claim_events
has_many :access_tokens
has_many :saved_search_tabs
# there is no longer a Github::Commit model -- CAB
# has_many :commits, class_name: Github::Commit
has_many :fundraisers
has_many :searches
has_many :person_relations, class_name: PersonRelation::Base
has_many :friends,
class_name: Person,
through: :person_relations,
source: :target_person
# linked accounts
has_many :linked_accounts, class_name: LinkedAccount::Base
has_one :github_account, class_name: LinkedAccount::Github::User
has_one :facebook_account, class_name: LinkedAccount::Facebook
has_one :twitter_account, class_name: LinkedAccount::Twitter
has_one :gittip_account, class_name: LinkedAccount::Gittip
has_many :tracker_plugins
has_many :tracker_relations, through: :linked_accounts
has_many :tag_votes
has_many :follow_relations
has_many :team_member_relations
has_many :teams, through: :team_member_relations
has_many :pledges
has_many :bounties
has_many :team_payins
has_many :solutions
has_many :solution_events, through: :solutions
has_many :language_relations, class_name: LanguagePersonRelation
has_many :developer_goals
has_many :activity_logs
has_many :ranked_issues, through: :issue_rank_caches, source: :issue
has_many :issue_rank_caches, class_name: IssueRankCache
has_many :tracker_rank_caches, class_name: TrackerRankCache
has_many :shopping_carts
has_many :tracker_person_relations
has_many :addresses
has_many :cash_outs
has_many :proposals
has_many :thumbs
has_many :recommendation_events
has_many :payment_methods
has_many :support_levels
has_many :team_bounty_hunters
has_many :issue_suggestions
has_many :comments, through: :linked_accounts
EMAIL_REGEX = /\A.+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+\z/
# all Person objects must have an email address
validates :email,
uniqueness: true,
format: { with: EMAIL_REGEX }
# if a new password was set, validate it. if there isn't an encrypted password, require one
validates :password,
length: { minimum: 8 },
format: { with: /[a-z].*[0-9]|[0-9].*[a-z]/i, message: 'must contain a letter and a number' },
if: 'password_digest.blank? || !password.blank?'
# NOTE: this only validates if accept is defined (aka: nil is valid)
validates_acceptance_of :terms, :accept => true
before_create do
self.accepted_terms_at = Time.now if self.terms
end
has_secure_password
#validates :paypal_email,
# confirmation: true,
# format: { with: EMAIL_REGEX },
# unless: "paypal_email.nil?"
scope :distinct_backers, lambda { select('distinct people.*').joins(:bounties) }
scope :celebrity, lambda { |min_followers=50|
joins(:linked_accounts)
.where("linked_accounts.person_id is not null and linked_accounts.followers > :min", min: min_followers)
.group("people.id")
.order("sum(linked_accounts.followers) desc")
.select("people.*, sum(linked_accounts.followers) as total_followers")
.includes(:twitter_account, :github_account)
}
scope :active, lambda { where.not(deleted: true).where(suspended_at: nil) }
scope :bounty_hunters, lambda { |options={}|
retval = active.where(bounty_hunter: true)
if options[:team]
retval = retval.where(id: options[:team].team_bounty_hunters.active.pluck(:person_id))
end
if options[:team]
retval = retval.select("people.*, coalesce((select sum(amount) from bounty_claims where person_id=people.id and paid_out=true and issue_id in (select issue_id from bounties where owner_type='Team' and owner_id=#{options[:team].id})),0) as bounty_claim_total")
elsif options[:since]
retval = retval.select("people.*, coalesce((select sum(amount) from bounty_claims where person_id=people.id and paid_out=true and created_at > #{ActiveRecord::Base.connection.quote(options[:since])}),0) as bounty_claim_total")
else
retval = retval.select("people.*, coalesce((select sum(amount) from bounty_claims where person_id=people.id and paid_out=true),0) as bounty_claim_total")
end
retval = retval.order('bounty_claim_total desc')
retval
}
def self.admin_search(query)
results = where(%(lower(people.first_name) LIKE :q OR lower(people.last_name) LIKE :q OR lower(people.display_name) LIKE :q or lower(people.email) LIKE :q or lower(people.public_email) LIKE :q or people.id=:id), q: "%#{query}%".downcase, id: query.to_i)
results.uniq
end
after_save do
self.send_email(:account_created) if changes["email"] && changes["email"].first.nil?
end
# NOTE: opting into a team implies becoming global bounty hunter
def is_bounty_hunter!(options={})
update_attribute(:bounty_hunter, true)
teams = []
if options[:team]
teams << options[:team]
elsif options[:issue]
teams += Team.where(id: options[:issue].bounties.where(owner_type: 'Team').pluck(:owner_id))
end
teams.each do |team|
tbh = team_bounty_hunters.where(team: team).first_or_create!
tbh.update_attributes!(opted_out_at: nil) if tbh.opted_out_at
end
end
# NOTE: opting out of team does not opt-out globally
def is_not_bounty_hunter!(options={})
if options[:team]
tbh = team_bounty_hunters.where(team: options[:team]).first_or_create!
tbh.update_attributes!(opted_out_at: Time.now) unless tbh.opted_out_at
else
update_attribute(:bounty_hunter, false)
end
end
def active_bounties
bounties.visible
end
def populate_friends
PersonRelation::Github.find_or_create_friends self if github_account
PersonRelation::Facebook.find_or_create_friends self if facebook_account
PersonRelation::Twitter.find_or_create_friends self if twitter_account
end
def to_param
display_name ? "#{id}-#{display_name.parameterize}" : "#{id}"
rescue ActionView::Template::Error => e
logger.error "ERROR: person##{id} #{e}"
"#{id}"
end
def frontend_path
"/users/#{to_param}"
end
def frontend_url
File.join(Api::Application.config.www_url, frontend_path)
end
def self.authenticate(email, password)
self.active.find_by_email(email).try(:authenticate, password)
end
# support sha1 and mysql style passwords with auto-updating
def authenticate_with_legacy_passwords(password)
return false if password.blank?
case password_digest
when /^[0-9a-f]{40}$/ # sha1
if Digest::SHA1.hexdigest(password) == password_digest
update_attribute(:password, password) #intentionally skip validations via update_attribute
send_email(:account_created)
return self
else
return false
end
else
authenticate_without_legacy_passwords(password)
end
end
alias_method_chain :authenticate, :legacy_passwords
def self.distinct_backers_count
self.joins(:bounties).count(distinct: true) # distinct_backers.count does NOT work
end
# similar to access_token but used for referring to a person, not authentication (i.e. passing through paypal IPN params)
def create_perma_reference
time = Time.now.to_i
"#{self.id}.#{time}.#{self.class.hash_access_token(self, time).first(16)}"
end
def self.find_by_perma_reference(access_token)
person_id, time, hash = (access_token||'').split('.')
return nil if person_id.blank? || time.blank? || hash.blank?
return nil unless (person = Person.find_by_id(person_id))
return nil unless hash == self.hash_access_token(person, time).first(16)
person
end
def create_access_token(request=nil)
self.current_access_token = access_tokens.create!(!request ? {} : {
remote_ip: request.remote_ip,
user_agent: request.user_agent
}).token
end
def self.find_by_access_token(token)
# sometimes acces_tokens will have 4 param for admin. if so, ignore.
token = token.split('.')[0..2].join('.') unless token.blank?
access_token = AccessToken.where(token: token).first
if access_token.try(:still_valid?)
person = access_token.person
person.current_access_token = token
return person
else
return nil
end
end
def send_email(which, options={})
Rails.env.test? ? deliver_email(which, options) : delay.deliver_email(which, options)
end
def deliver_email(which, options={})
message = Mailer.send(which, { person: self }.merge(options)).deliver
if message
# Log sent email
SentEmail.create!(
person: self,
template: which,
options: options
)
# log mixpanel event
MixpanelEvent.track(
person_id: self.id,
event: 'Sent Email',
template: which
)
end
return message
end
# A backer is defined as anyone that's put a bounty on an issue
def backer?
bounties.count > 0
end
# check to see if all profile information is provided
#def account_completed?
# self.account_completed = (first_name? and last_name? and email?)
# save if account_completed_changed?
# self.account_completed
#end
# emailed to the person, so that they can reset their password.
def reset_password_code
Digest::SHA1.hexdigest("#{self.id}:#{self.email}:#{self.password_digest}").first(16)
end
def display_name
return attributes['display_name'] unless attributes['display_name'].blank?
return "#{attributes['first_name']} #{attributes['last_name']}" unless attributes['first_name'].blank? && attributes['last_name'].blank?
return '(unknown)'
end
def first_name
return attributes['first_name'] unless attributes['first_name'].blank?
return attributes['display_name'].split(' ',2)[0] unless attributes['display_name'].blank?
return '(unknown)'
end
def last_name
return attributes['last_name'] unless attributes['last_name'].blank?
return attributes['display_name'].split(' ',2)[1] if attributes['display_name'] =~ / /
return '(unknown)'
end
def full_name
"#{first_name} #{last_name}"
end
# only update if it's been over an hour... this saves updating the DB for *every* request
def was_seen!
update_attribute(:last_seen_at, Time.now) if valid? && (last_seen_at.nil? || last_seen_at < 1.hour.ago)
end
def can_view?(model)
return true if admin?
return false unless model.is_a? ActiveRecord::Base
# special cases
case model
when Pledge
# you created the pledge, or are the fundraiser creator
(self == model.person) or (self == model.fundraiser.person)
else
self == model.person
end
end
# projects that the person is a committer/owner of
def projects
Tracker.includes(:tracker_relations => [:linked_account]).where('trackers.id in (:ids)', ids: tracker_relations.pluck(:tracker_id))
end
def followed_trackers
Tracker.joins(:follow_relations).where('follow_relations.person_id = ? AND follow_relations.active = ?', id, true)
end
# mask this model instance so that display name reads
# 'An anonymous user'
def self.anon
new(display_name: 'An anonymous user')
end
def start_work!(issue_id)
DeveloperBidEvent::StartedWork.create(issue_id: issue_id, person_id: self.id)
end
def continue_work!(issue_id)
DeveloperBidEvent::ContinuedWork.create(issue_id: issue_id, person_id: self.id)
end
def stop_work!(issue_id)
DeveloperBidEvent::StoppedWork.create(issue_id: issue_id, person_id: self.id)
end
def idle!(issue_id)
DeveloperBidEvent::Idle.create(issue_id: issue_id, person_id: self.id)
end
def complete_work!(issue_id)
DeveloperBidEvent::CompletedWork.create(issue_id: issue_id, person_id: self.id)
end
def get_work_status(issue_id)
DeveloperBidEvent.status(issue_id: issue_id, person_id: self.id)
end
# Sync languages from projects
def sync_languages
projects.find_each do |tracker|
tracker.languages.find_each do |language|
language_relations.find_or_create_by(language: language)
end
end
end
def self.top_backers
bounty_posters = Person.joins(:bounties).where("bounties.owner_type IS NULL OR bounties.owner_type LIKE 'Person%'").merge(Bounty.visible).group("people.id, bounties.id").select("people.*, sum(bounties.amount) as total_backed").to_a
pledge_givers = Person.joins(:pledges).where("pledges.owner_type IS NULL OR pledges.owner_type LIKE 'Person%'").merge(Pledge.active).group("people.id, pledges.id").select("people.*, sum(pledges.amount) as total_pledged").to_a
top_backers_map = Hash.new(0)
bounty_posters.each do |person|
top_backers_map[person] += person.total_backed.to_i
end
pledge_givers.each do |person|
top_backers_map[person] += person.total_pledged.to_i
end
return top_backers_map
end
def self.top_earners
claim_creators = Person.joins(:bounty_claims => [:issue]).select("people.*, issues.bounty_total as total_collected")
fundraiser_creators = Person.joins(:fundraisers).where("fundraisers.total_pledged > 0").group("people.id").select("people.*, sum(fundraisers.total_pledged) as total_received")
top_earners_map = Hash.new(0)
claim_creators.find_each do |person|
top_earners_map[person] += person.total_collected.to_i
end
fundraiser_creators.find_each do |person|
top_earners_map[person] += person.total_received.to_i
end
top_earners_map
end
# Autocreate ShoppingCart
def shopping_cart
cart = shopping_carts.find_by(id: shopping_cart_id) || shopping_carts.create!
self.shopping_cart_id = cart.id
save! if self.shopping_cart_id_changed?
cart
end
#bunch of JSON rendering logic.. doesn't really belong in Person model.
def get_ranked_issues
issues = ranked_issues.joins(:issue_rank_caches).includes(:tracker).where("issue_rank_caches.rank > ?", 2).order("issue_rank_caches.rank DESC").limit(10)
end
def issues_from_ranked_trackers
tracker_ids = tracker_rank_caches.order("rank DESC").limit(10).pluck(:tracker_id)
trackers = Tracker.where(id: tracker_ids)
trackers.map {|tracker| tracker.issues.includes(:tracker).top_issues_by_rank(5)}.flatten
end
def self.fill_out_issues(remaining = nil)
#portion out remaining issue-spaces based on ranking
issues = Tracker.proportional_issues_for_top_trackers({tracker_count: 5, issue_count: remaining})
end
def personalized_issues
#limit queries. gather ID's and try to do one query.
issues = []
#grab personally relevant issues base on issue/tracker cached activity
issues += get_ranked_issues
issues += issues_from_ranked_trackers unless issues.count >= 100
issues = issues.uniq {|issue| issue.id}
#fill remaining space with popular issues from highly ranked trackers (based on global rank)
issues += Person.fill_out_issues(150 - issues.count) unless issues.count >= 100
issues.uniq { |i| i.id }.first(100)
end
# Null out personal information, but keep all models around.
# Yeah, I know I am using destroy instead of delete_all. I want validations to run.
def safe_destroy
ActiveRecord::Base.transaction do
# Person attributes stripped away
self.first_name = '[deleted]'
self.last_name = '[deleted]'
self.email = "null-#{id}@bountysource.com"
self.display_name = '[deleted]'
self.paypal_email = nil
self.image_url = nil
self.bio = nil
self.location = nil
self.public_email = nil
self.url = nil
self.company = nil
self.save!
# Clear image_url
ActiveRecord::Base.connection.execute("update people set cloudinary_id = NULL where id = #{id}")
# Delete unpublished Fundraisers
fundraisers.where(published: false).find_each(&:destroy)
# Delete published fundraisers with no Pledges
fundraisers.where(published: true).find_each { |fundraiser| fundraiser.delete if fundraiser.pledges.empty? }
# Make Pledges and Bounties anonymous
bounties.find_each { |bounty| bounty.owner_id = nil ; bounty.owner_type = nil ; bounty.save! }
pledges.find_each { |pledge| pledge.owner_id = nil ; pledge.owner_type = nil ; pledge.save! }
ActiveRecord::Base.connection.execute("update bounties set anonymous = 't' where person_id = #{id}")
ActiveRecord::Base.connection.execute("update pledges set anonymous = 't' where person_id = #{id}")
# Can safely delete BountyClaims that were never accepted
bounty_claims.where(collected: false).each(&:destroy)
# Null out person on logged searches
searches.find_each { |search| search.update_attribute(:person, nil) }
# Delete all of the things that we can
solutions.find_each(&:destroy)
developer_goals.find_each(&:destroy)
team_member_relations.find_each(&:destroy)
shopping_cart.destroy
access_tokens.find_each(&:destroy)
saved_search_tabs.find_each(&:destroy)
addresses.find_each(&:destroy)
person_relations.find_each(&:destroy)
tracker_relations.find_each(&:destroy)
tag_votes.find_each(&:destroy)
follow_relations.find_each(&:destroy)
team_member_relations.find_each(&:destroy)
language_relations.find_each(&:destroy)
activity_logs.find_each(&:destroy)
issue_rank_caches.find_each(&:destroy)
tracker_rank_caches.find_each(&:destroy)
tracker_person_relations.find_each(&:destroy)
# Unclaim some linked accounts
if github_account
github_account.oauth_token = nil
github_account.permissions = nil
github_account.person_id = nil
github_account.save!
end
linked_accounts.where.not(type: 'LinkedAccount::Github::User').find_each(&:destroy)
update_attribute(:deleted, true)
end
end
def languages
Language.where(id: language_relations.where(active: true).pluck(:language_id))
end
# Set languages.
def set_languages(*language_ids)
ActiveRecord::Base.transaction do
language_relations.update_all(active: false)
language_ids.each do |language_id|
relation = language_relations.where(language_id: language_id).first
if relation
relation.update_attribute(:active, true) unless relation.active?
else
language_relations.create(language: Language.find(language_id))
end
end
end
languages
end
def followed_trackers
Tracker.where(
id: follow_relations.select('item_id').
where(active: true).
where(
'item_type LIKE ? OR item_type LIKE ?',
'%Repository', '%Tracker'
)
)
end
def yearly_cash_out_totals
self.cash_outs.completed.inject({}) { |hash, cash_out| hash[cash_out.sent_at.year] = (hash[cash_out.sent_at.year] || 0.0) + cash_out.final_payment_amount; hash }
end
def suspend!
update_attributes(suspended_at: Time.now)
end
def admin_team_ids
team_member_relations.where(admin: true).pluck(:team_id)
end
def workflow_issues
issue_ids = []
# bountied
issue_ids += self.bounties.not_refunded.pluck(:issue_id)
# thumbed
issue_ids += self.thumbs.up_votes.where(item_type: 'Issue').pluck(:item_id)
# issue suggestions
issue_ids += self.issue_suggestions.pluck(:issue_id)
# started work on
issue_ids += self.solutions.pluck(:issue_id)
# submitted claims for
issue_ids += self.bounty_claims.pluck(:issue_id)
# set goals
issue_ids += self.developer_goals.pluck(:issue_id)
# created via linked github account
linked_account_ids = self.linked_accounts.pluck(:id)
unless linked_account_ids.empty?
query = Issue.where(author_linked_account_id: linked_account_ids).active
query = query.where("created_at > ?", 3.months.ago) if query.count > 50
issue_ids += query.pluck(:id)
end
# collection
# NOTE: it sucks we don't track "closed_at"... so this is a half ass way to figure it out
Issue.not_deleted.where(id: issue_ids.uniq).where("can_add_bounty=? or updated_at>?", true, 1.month.ago)
end
def suggested_issues
issue_ids = []
# issues i've commented on via github
issue_ids += current_user.comments.pluck(:issue_id)
end
protected
def self.hash_access_token(person, time)
Digest::SHA1.hexdigest("#{person.id}.#{time}.#{Api::Application.config.person_hash_secret}")
end
end
| 33.937031 | 265 | 0.700477 |
336d32ebfd2398ac25931dfb5f40389bd5a18b40 | 3,067 | # frozen_string_literal: true
module Homebrew
module Livecheck
module Strategy
# The `Sourceforge` strategy identifies versions of software at
# sourceforge.net by checking a project's RSS feed.
#
# SourceForge URLs take a few different formats:
# * https://downloads.sourceforge.net/project/example/example-1.2.3.tar.gz
# * https://svn.code.sf.net/p/example/code/trunk
# * :pserver:anonymous:@example.cvs.sourceforge.net:/cvsroot/example
#
# The RSS feed for a project contains the most recent release archives
# and this is fine for most projects but this approach has some
# shortcomings. Some project releases involve so many files that the one
# we're interested in isn't present in the feed content. Some projects
# contain additional software and the archive we're interested in is
# pushed out of the feed (especially if it hasn't been updated recently).
#
# Usually we address this situation by adding a `livecheck` block to
# the formula that checks the page for the relevant directory in the
# project instead. In this situation, it's necessary to use
# `strategy :page_match` to prevent the `Sourceforge` stratgy from
# being used.
#
# The default regex matches within `url` attributes in the RSS feed
# and identifies versions within directory names or filenames.
#
# @api public
class Sourceforge
NICE_NAME = "SourceForge"
# The `Regexp` used to determine if the strategy applies to the URL.
URL_MATCH_REGEX = /(?:sourceforge|sf)\.net/i.freeze
# Whether the strategy can be applied to the provided URL.
# @param url [String] the URL to match against
# @return [Boolean]
def self.match?(url)
URL_MATCH_REGEX.match?(url)
end
# Generates a URL and regex (if one isn't provided) and passes them
# to the `PageMatch#find_versions` method to identify versions in the
# content.
# @param url [String] the URL of the content to check
# @param regex [Regexp] a regex used for matching versions in content
# @return [Hash]
def self.find_versions(url, regex = nil)
if url.include?("/project")
%r{/projects?/(?<project_name>[^/]+)/}i =~ url
elsif url.include?(".net/p/")
%r{\.net/p/(?<project_name>[^/]+)/}i =~ url
else
%r{\.net(?::/cvsroot)?/(?<project_name>[^/]+)}i =~ url
end
page_url = "https://sourceforge.net/projects/#{project_name}/rss"
# It may be possible to improve the default regex but there's quite a
# bit of variation between projects and it can be challenging to
# create something that works for most URLs.
regex ||= %r{url=.*?/#{Regexp.escape(project_name)}/files/.*?[-_/](\d+(?:[-.]\d+)+)[-_/%.]}i
Homebrew::Livecheck::Strategy::PageMatch.find_versions(page_url, regex)
end
end
end
end
end
| 42.597222 | 102 | 0.633192 |
5d463625bbb2b3cd24489cda9efa84c37695225a | 130 | class AddFieldToContracts < ActiveRecord::Migration[4.2]
def change
add_reference :contracts, :agent, index: true
end
end
| 21.666667 | 56 | 0.753846 |
b9ce2a37160fe0137f94ea734626b3055cfd673e | 632 | require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe '#chart' do
before { init_lastfm }
it 'should return an instance of Lastfm::Chart' do
@lastfm.chart.should be_an_instance_of(Lastfm::MethodCategory::Chart)
end
describe '#get_hyped_artists' do
it 'should get hyped artists' do
@lastfm.should_receive(:request).with('chart.getHypedArtists', {
:limit => 10,
:page => 3
}).and_return(make_response('chart_get_hyped_artists'))
hyped_artists = @lastfm.chart.get_hyped_artists(:limit => 10, :page => 3)
hyped_artists.size.should > 1
end
end
end
| 28.727273 | 79 | 0.683544 |
e277c13bd50a601f4dfccdb6808546a5246c97c5 | 5,329 | %w'bigdecimal bigdecimal/util date enumerator thread time uri yaml'.each do |f|
require f
end
%w"core_ext sql core_sql connection_pool exceptions pretty_table
dataset migration schema database object_graph".each do |f|
require "sequel_core/#{f}"
end
# Top level module for Sequel
#
# There are some class methods that are added via metaprogramming, one for
# each supported adapter. For example:
#
# DB = Sequel.sqlite # Memory database
# DB = Sequel.sqlite('blog.db')
# DB = Sequel.postgres('database_name', :user=>'user',
# :password=>'password', :host=>'host', :port=>5432,
# :max_connections=>10)
#
# If a block is given to these methods, it is passed the opened Database
# object, which is closed (disconnected) when the block exits. For example:
#
# Sequel.sqlite('blog.db'){|db| puts db.users.count}
#
# Sequel can use either Time or DateTime for times returned from the
# database. It defaults to Time. To change it to DateTime, use:
#
# Sequel.datetime_class = DateTime
#
# Sequel converts the column type tinyint to a boolean by default,
# you can override the conversion to use tinyint as an integer:
#
# Sequel.convert_tinyint_to_bool = false
module Sequel
@datetime_class = Time
@convert_tinyint_to_bool = true
metaattr_accessor :datetime_class
metaattr_accessor :convert_tinyint_to_bool
# Creates a new database object based on the supplied connection string
# and optional arguments. The specified scheme determines the database
# class used, and the rest of the string specifies the connection options.
# For example:
#
# DB = Sequel.connect('sqlite:/') # Memory database
# DB = Sequel.connect('sqlite://blog.db') # ./blog.db
# DB = Sequel.connect('sqlite:///blog.db') # /blog.db
# DB = Sequel.connect('postgres://user:password@host:port/database_name')
# DB = Sequel.connect('sqlite:///blog.db', :max_connections=>10)
#
# If a block is given, it is passed the opened Database object, which is
# closed when the block exits. For example:
#
# Sequel.connect('sqlite://blog.db'){|db| puts db.users.count}
#
# This is also aliased as Sequel.open.
def self.connect(*args, &block)
Database.connect(*args, &block)
end
metaalias :open, :connect
# Set whether to quote identifiers for all databases by default. By default,
# Sequel quotes identifiers in all SQL strings, so to turn that off:
#
# Sequel.quote_identifiers = false
def self.quote_identifiers=(value)
Database.quote_identifiers = value
end
# Set whether to set the single threaded mode for all databases by default. By default,
# Sequel uses a threadsafe connection pool, which isn't as fast as the
# single threaded connection pool. If your program will only have one thread,
# and speed is a priority, you may want to set this to true:
#
# Sequel.single_threaded = true
#
# Note that some database adapters (e.g. MySQL) have issues with single threaded mode if
# you try to perform more than one query simultaneously. For example, the
# following code will not work well in single threaded mode on MySQL:
#
# DB[:items].each{|i| DB[:nodes].filter(:item_id=>i[:id]).each{|n| puts "#{i} #{n}"}}
#
# Basically, you can't issue another query inside a call to Dataset#each in single
# threaded mode. There is a fairly easy fix, just use Dataset#all inside
# Dataset#each for the outer query:
#
# DB[:items].all{|i| DB[:nodes].filter(:item_id=>i[:id]).each{|n| puts "#{i} #{n}"}}
#
# Dataset#all gets all of the returned objects before calling the block, so the query
# isn't left open. Some of the adapters do this internally, and thus don't have a
# problem issuing queries inside of Dataset#each.
def self.single_threaded=(value)
Database.single_threaded = value
end
# Always returns false, since ParseTree support has been removed.
def self.use_parse_tree
false
end
# Raises an error if attempting to turn ParseTree support on (since it no longer exists).
# Otherwise, is a no-op.
def self.use_parse_tree=(val)
raise(Error, 'ParseTree support has been removed from Sequel') if val
end
### Private Class Methods ###
# Helper method that the database adapter class methods that are added to Sequel via
# metaprogramming use to parse arguments.
def self.adapter_method(adapter, *args, &block) # :nodoc:
raise(::Sequel::Error, "Wrong number of arguments, 0-2 arguments valid") if args.length > 2
opts = {:adapter=>adapter.to_sym}
opts[:database] = args.shift if args.length >= 1 && !(args[0].is_a?(Hash))
if Hash === (arg = args[0])
opts.merge!(arg)
elsif !arg.nil?
raise ::Sequel::Error, "Wrong format of arguments, either use (), (String), (Hash), or (String, Hash)"
end
connect(opts, &block)
end
# Method that adds a database adapter class method to Sequel that calls
# Sequel.adapter_method.
def self.def_adapter_method(*adapters) # :nodoc:
adapters.each do |adapter|
instance_eval("def #{adapter}(*args, &block); adapter_method('#{adapter}', *args, &block) end")
end
end
private_class_method :adapter_method, :def_adapter_method
# Add the database adapter class methods to Sequel via metaprogramming
def_adapter_method(*Database::ADAPTERS)
end
| 38.89781 | 108 | 0.704635 |
acb5d9f39d7ac0a725990d5c69ae7f98b1f4bc92 | 3,961 | class ProteinSequenceAnnotationStanza < TogoStanza::Stanza::Base
property :sequence_annotations do |tax_id, gene_id|
annotations = query("http://sparql-app.togogenome.org/sparql", <<-SPARQL.strip_heredoc)
DEFINE sql:select-option "order"
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX up: <http://purl.uniprot.org/core/>
PREFIX faldo: <http://biohackathon.org/resource/faldo#>
SELECT DISTINCT ?parent_label ?label ?begin_location ?end_location ?seq_length ?comment (GROUP_CONCAT(?substitution; SEPARATOR = ", ") AS ?substitutions) ?seq ?feature_identifier
FROM <http://togogenome.org/graph/uniprot>
FROM <http://togogenome.org/graph/tgup>
WHERE {
{
SELECT DISTINCT ?parent_label ?label ?begin_location ?end_location ?annotation ?isoform
{
{
SELECT ?protein
{
<http://togogenome.org/gene/#{tax_id}:#{gene_id}> skos:exactMatch ?gene ;
rdfs:seeAlso ?id_upid .
?id_upid rdfs:seeAlso ?protein .
?protein a up:Protein ;
up:reviewed ?reviewed .
} ORDER BY DESC(?reviewed) LIMIT 1
}
?protein up:annotation ?annotation .
?annotation rdf:type ?type .
?type rdfs:label ?label .
# sequence annotation 直下のtype のラベルを取得(Region, Site, Molecule Processing, Experimental Information)
?type rdfs:subClassOf* ?parent_type .
?parent_type rdfs:subClassOf up:Sequence_Annotation ;
rdfs:label ?parent_label .
?annotation up:range ?range .
?range faldo:begin/faldo:position ?begin_location ;
faldo:end/faldo:position ?end_location .
# sequence annotationが紐づいているisoformとそのsequenceを取得する
?range faldo:begin/faldo:reference ?isoform .
?isoform rdf:value ?value .
}
}
OPTIONAL { ?annotation rdfs:comment ?comment . }
# description の一部が取得できるが、内容の表示に必要があるのか
OPTIONAL {
?annotation up:substitution ?substitution .
?isoform rdf:value ?seq .
}
# sequence の長さ取得
OPTIONAL {
?isoform rdf:value ?seq_txt .
BIND (STRLEN(?seq_txt) AS ?seq_length) .
}
OPTIONAL {
?annotation rdf:type ?type . # Virtuoso 対応
BIND (STR(?annotation) AS ?feature_identifier) .
FILTER REGEX(STR(?annotation), 'http://purl.uniprot.org/annotation')
}
}
GROUP BY ?parent_label ?label ?begin_location ?end_location ?seq_length ?comment ?seq ?feature_identifier
ORDER BY ?parent_label ?label ?begin_location ?end_location
SPARQL
annotations.uniq.map.with_index {|hash, i|
begin_location, end_location, substitutions, seq = hash.values_at(:begin_location, :end_location, :substitutions, :seq)
hash.merge(
location_length: length(begin_location, end_location),
position: position(begin_location, end_location),
substitution_sequence: substitution_sequence(begin_location, end_location, substitutions, seq),
row_id: "row#{i}" #graphical view 描画用に各行の要素IDを設定
)
}.group_by {|hash|
hash[:parent_label]
}.values
end
private
def position(begin_location, end_location)
(begin_location == end_location) ? begin_location : "#{begin_location}-#{end_location}"
end
def length(begin_location, end_location)
end_location.to_i - begin_location.to_i + 1
end
def substitution_sequence(begin_location, end_location, substitutions, seq)
return nil unless seq
original = seq.slice(begin_location.to_i.pred..end_location.to_i.pred)
"#{original} → #{substitutions}: "
end
end
| 38.456311 | 184 | 0.630144 |
21c47b53a0712f503cb92b98b56c1dc1e426451c | 1,556 | class Pnpm < Formula
require "language/node"
desc "📦🚀 Fast, disk space efficient package manager"
homepage "https://pnpm.io/"
url "https://registry.npmjs.org/pnpm/-/pnpm-6.32.2.tgz"
sha256 "db76fda0fc0bae5a22652504129a0356edd8aa6e0bebb67a33d941de87bf1684"
license "MIT"
livecheck do
url "https://registry.npmjs.org/pnpm/latest"
regex(/["']version["']:\s*?["']([^"']+)["']/i)
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "d790c1b827cd9ee7b88a6fd36fba8d4b115ad9d449d632a58a03baecb0e998d3"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "d790c1b827cd9ee7b88a6fd36fba8d4b115ad9d449d632a58a03baecb0e998d3"
sha256 cellar: :any_skip_relocation, monterey: "88e429a5908ca432a2ff1e8030c7904f3160bb4a7fcc943b5837422a3daa916b"
sha256 cellar: :any_skip_relocation, big_sur: "e547bae308b54b64c580e1e5d9e27cba6071b7645fe5c44dfd728f3132d5115e"
sha256 cellar: :any_skip_relocation, catalina: "e547bae308b54b64c580e1e5d9e27cba6071b7645fe5c44dfd728f3132d5115e"
sha256 cellar: :any_skip_relocation, x86_64_linux: "d790c1b827cd9ee7b88a6fd36fba8d4b115ad9d449d632a58a03baecb0e998d3"
end
depends_on "node"
conflicts_with "corepack", because: "both installs `pnpm` and `pnpx` binaries"
def install
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
system "#{bin}/pnpm", "init", "-y"
assert_predicate testpath/"package.json", :exist?, "package.json must exist"
end
end
| 40.947368 | 123 | 0.758997 |
4a66bb45283e8b97d7c2a438c6c3fc8f4e3bf554 | 13,129 | # Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
# Devise will use the `secret_key_base` on Rails 4+ applications as its `secret_key`
# by default. You can change it below and use your own secret key.
# config.secret_key = 'b6ff97960fd5157a09d5d60e4881dba43756c90a5a3e8b116c024ad2cbd558e6d9b1461c385945c6ecfb03fd2d620a093b3272b00ae8818c37415eaa19de3c6b'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = '[email protected]'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [:email]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [:email]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [:email]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If 401 status code should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# encryptor), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = '16dbc24df209ab3d234d96b30b5c572a304f84dcdf3f845621deef7d6df60ca557e9e442feb6bd3f7271339b17025e4a295aabf78fe2a831f1589c697e02d8d3'
# Send a notification email when the user's password is changed
# config.send_password_change_notification = false
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [:email]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = true
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 8..72
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^@]+@[^@]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [:email]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = true
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [:email]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# When set to false, does not sign a user in automatically after their password is
# reset. Defaults to true, so a user is signed in automatically after a reset.
# config.sign_in_after_reset_password = true
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using OmniAuth, Devise cannot automatically set OmniAuth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
end
| 49.357143 | 154 | 0.75139 |
62058ded418890219f36bb959c63bcba56a31d23 | 179 | Rails.application.routes.draw do
root 'cards#index'
resources :cards
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
| 29.833333 | 102 | 0.776536 |
18d4a7074d567952fbc502e7307b9e9e53042fc8 | 15,339 | require 'yaml'
require 'restclient'
require 'fileutils'
require 'rake'
require 'mspec'
# push type: Rhoconnect Push Service (rhoconnect_push) | Google Cloud Messaging (gcm)
# push_type = MSpec.retrieve(:push_type)
# push_type = ((ARGV[1].nil?) ? "rhoconnect_push" : ARGV[1]) #unless push_type
push_type = ENV['PUSH_TYPE'] ? ENV['PUSH_TYPE'] : "rhoconnect_push"
unless push_type == 'rhoconnect_push' || push_type == 'gcm'
puts "Invalid param: 'rhoconnect_push' or 'gcm' expected"
exit
end
puts "Running Ruby Push specs for #{(push_type == "rhoconnect_push") ? 'Rhoconnect Push' : 'Google Cloud Messaging'} Service"
TEST_PKGS = %w[ com.rhomobile.push_client_rb ]
TEST_PKGS << 'com.motsolutions.cto.services.ans' if push_type == "rhoconnect_push"
$rho_root = nil
cfgfilename = File.join(File.dirname(__FILE__),'config.yml')
if File.file?(cfgfilename)
config = YAML::load_file(cfgfilename)
$rho_root = config["rhodes"]
$rhoconnect_root = config["rhoconnect"]
$rho_root = File.expand_path($rho_root) if $rho_root
$rhoconnect_root = File.expand_path($rhoconnect_root) if $rhoconnect_root
$rhoelements_root = config["rhoelements"]
$rhoelements_root = File.expand_path($rhoelements_root) if $rhoelements_root
end
$rho_root = `get-rhodes-info --rhodes-path`.chomp unless $rho_root
# puts "$rho_root: #{$rho_root}"
require File.join($rho_root, 'lib', 'build', 'jake.rb')
require_relative './rhoconnect_helper'
$spec_path = FileUtils.pwd
$platform = 'android'
appname = "push_client_rb"
$app_path = File.expand_path(File.join(File.dirname(__FILE__), appname))
RhoconnectHelper.set_enable_redis(false)
RhoconnectHelper.set_enable_resque(false)
RhoconnectHelper.set_enable_push(false) if push_type == "gcm"
$server = nil
$requests = []
$signal = ConditionVariable.new
$mutex = Mutex.new
# Patch rhodes 'rhoconfig.txt' file
cfgfile = File.join($app_path, 'rhoconfig.txt')
cfg = File.read(cfgfile)
cfg.gsub!(/(syncserver.*)/, "syncserver = 'http://#{RhoconnectHelper.host}:#{RhoconnectHelper.port}'")
cfg.gsub!(/(Push.rhoconnect.pushServer.*)/, "Push.rhoconnect.pushServer = 'http://#{RhoconnectHelper.push_host}:#{RhoconnectHelper.push_port}'")
File.open(cfgfile, 'w') { |f| f.write cfg }
# Select proper build file for rhodes app
# puts ENV['JENKINS_HOME']
build_dir = ENV['JENKINS_HOME'] ? File.join($app_path, 'jenkins') : $app_path
if push_type == "rhoconnect_push"
FileUtils.cp(File.join(build_dir, 'build.yml.rps'), File.join($app_path, 'build.yml'))
else # "gcm"
FileUtils.cp(File.join(build_dir, 'build.yml.gcm'), File.join($app_path, 'build.yml'))
end
###############################
# puts "-- Starting local server"
# $server, addr, port = Jake.run_local_server(8081)
log_file = File.open(File.join($app_path, 'webrick.log'), 'w')
$server, addr, port = Jake.run_local_server_with_logger(8081, log_file)
$server.mount_proc('/', nil) do |req, res|
query = req.query
# puts "Local server:"
# puts " Headers: #{req.header.inspect}"
# puts " Query: #{query.inspect}"
res.status = 200
$mutex.synchronize do
$requests << req
$signal.signal
end
end
def expect_request(name, timeout=30)
val = nil
$mutex.synchronize do
$signal.wait($mutex, timeout) # wait timeout 30 secs.
$requests.count.should == 1
val = $requests.first.query[name]
$requests.clear
end
val
end
def expect_params(timeout=30)
params = nil
$mutex.synchronize do
$signal.wait($mutex, timeout) # wait timeout
params = $requests.first.query if $requests.count != 0
$requests.clear
end
params
end
###############################
# Store local server settings
File.open(File.join($spec_path, appname, 'app', 'local_server.rb'), 'w') do |f|
f.puts "SPEC_LOCAL_SERVER_HOST = '#{addr}'"
f.puts "SPEC_LOCAL_SERVER_PORT = #{port}"
end
FileUtils.chdir File.join($spec_path, appname)
puts "\nBuilding rhodes app ..."
puts "rake device:#{$platform}:debug"
raise "Failed to build rhodes app" unless system("rake device:#{$platform}:debug")
FileUtils.chdir $spec_path
$deviceId = nil
$deviceOpts = '-e'
out = `adb get-state`
unless out =~ /device/
puts "Restart adb server ..."
out = `adb kill-server; adb start-server`
puts out
end
out = `adb devices`
puts out
device_list = out.split("\n")
device_list.shift # skip "List of devices attached "
device_list << '' if device_list.empty?
device_list.each do |dev|
if dev == ''
puts "Running push specs on android emulator"
else
$deviceId = dev.split("\t")[0]
$deviceOpts = "-s #{$deviceId}"
puts "Running push specs on device #{$deviceId}"
end
describe 'Push specs' do
before(:all) do
RhoconnectHelper.stop_rhoconnect_stack
$tmp_path = File.join(File.dirname(__FILE__),'tmp')
FileUtils.mkdir_p File.expand_path($tmp_path) unless File.exists?($tmp_path)
$server_path = File.expand_path(File.join($tmp_path,'testapp'))
FileUtils.rm_r $server_path if File.exists?($server_path)
RhoconnectHelper.set_rhoconnect_bin $rhoconnect_root
puts "Generating rhoconnect app ..."
test_appname = "testapp"
res = RhoconnectHelper.generate_app($tmp_path, test_appname)
# puts "bundle install"
# Kernel.system("bundle", "install", :chdir => $server_path)
# Copy setting.yml file with :gcm_api_key to 'testapp/settings' directory
FileUtils.cp('settings.yml', File.join($server_path, 'settings')) if push_type == "gcm"
RhoconnectHelper.set_rc_push_out File.open( File.join($app_path, "rhoconnect_push.log" ), "w") if push_type == "rhoconnect_push"
RhoconnectHelper.set_rc_out(File.open( File.join($app_path, "rhoconnect.log" ), "w"),
File.open( File.join($app_path, "rhoconnect_err.log" ), "w"))
RhoconnectHelper.start_rhoconnect_stack($server_path, true)
@api_token = RhoconnectHelper.api_post('system/login', { :login => 'rhoadmin', :password => '' })
FileUtils.chdir File.join($spec_path, appname)
if $deviceId
TEST_PKGS.each do |pkg|
out = `adb #{$deviceOpts} shell pm list packages #{pkg}`
unless out.empty?
puts "Uninstalling package #{pkg} ..."
system "adb #{$deviceOpts} uninstall #{pkg}"
end
end
if push_type == "rhoconnect_push"
puts "Install rhoconnect push service ..."
push_service_apk = File.join($rhoelements_root,'libs','rhoconnect-push-service','rhoconnect-push-service.apk')
system("adb #{$deviceOpts} install -r #{push_service_apk}")
end
puts "\nInstalling rhodes app on device ..."
system("adb #{$deviceOpts} install -r #{Dir.pwd}/bin/target/android/push_client_rb-debug.apk")
puts "\nStarting rhodes app on device ..."
system(
"adb #{$deviceOpts} shell am start -a android.intent.action.MAIN -n com.rhomobile.push_client_rb/com.rhomobile.rhodes.RhodesActivity",
:out=>"/dev/null")
rhodes_log = File.join($spec_path, appname, 'rholog.txt')
File.unlink(rhodes_log) if File.exists?(rhodes_log)
$logcat_pid = Kernel.spawn("adb #{$deviceOpts} logcat", :out => File.open(rhodes_log, "w"))
# puts "Starting logcat process with pid: #{$logcat_pid}"
else # Using emulator
load File.join($rho_root,'Rakefile')
load File.join($rho_root,'platform','android','build','android.rake')
puts "Configure android emulator ..."
Rake::Task["config:android:emulator"].invoke
AndroidTools.run_emulator(:wipe => true, :hidden => true)
TEST_PKGS.each do |pkg|
out = `adb -e shell pm list packages #{pkg}`
unless out.empty?
puts "Uninstalling package #{pkg} ..."
system "adb -e uninstall #{pkg}"
end
end
if push_type == "rhoconnect_push"
puts "Install rhoconnect push service"
push_service_apk = File.join($rhoelements_root,'libs','rhoconnect-push-service','rhoconnect-push-service.apk')
AndroidTools.load_app_and_run("-e", push_service_apk, "")
end
puts 'Building and starting rhodes application ...'
system("rake run:#{$platform}").should == true
end
FileUtils.chdir $spec_path
end
after(:all) do
puts
RhoconnectHelper.stop_rhoconnect_stack
FileUtils.rm_r $server_path if File.exists? $server_path
TEST_PKGS.each do |pkg|
puts "Uninstalling package #{pkg} ..."
system "adb #{$deviceOpts} uninstall #{pkg}"
end
# puts "Stopping local server"
$server.shutdown
`adb emu kill` if $deviceOpts == '-e' # running emulator
system "kill -9 #{$logcat_pid}" if $logcat_pid
end
# 1
it 'should login' do
puts 'should login'
expect_request('error').should == "0"
end
# 2
it 'should register' do
puts 'should register'
device_id = expect_request('device_id')
device_id.should_not be_nil
device_id.should_not == ''
res = ''
client_id = nil
20.times do |i|
res = RhoconnectHelper.api_get('users/pushclient/clients', @api_token)
client_id = JSON.parse(res.body)[0]
break if client_id
sleep 3
end
res.code.should == 200
client_id.should_not be_nil
device_push_type = ''
20.times do |i|
res = RhoconnectHelper.api_get("clients/#{client_id}", @api_token)
body = JSON.parse(res.body)
device_push_type = body[2]['value']
body.each { |h| device_push_type = h['value'] if h['name'] == 'device_push_type' }
break if device_push_type
sleep 3
end
res.code.should == 200
device_push_type.should == push_type
end
# 3
it 'should process push message at foreground' do
puts 'should process push message at foreground'
message = 'hello_world'
params = { :user_id=>['pushclient'], :message => message }
RhoconnectHelper.api_post('users/ping', params, @api_token)
expect_request('alert', 60).should == message
end
# 4
it 'should return push properties' do
puts 'should return push properties'
message = 'properties'
params = { :user_id=>['pushclient'], :message => message }
# Get properties by call like Rho::Push.type ...
3.times do
RhoconnectHelper.api_post('users/ping', params, @api_token)
sleep 3
@properties = expect_params
break if @properties
end
if push_type == "rhoconnect_push"
@properties['pushAppName'].should == 'someappname'
@properties['pushServer'].should == "http://#{RhoconnectHelper.push_host}:#{RhoconnectHelper.push_port}"
@properties['type'].should == "rhoconnect-push"
else # gcm
@properties['pushAppName'].should == ''
@properties['pushServer'].should == ''
@properties['type'].should == "native-push"
end
@properties['userNotifyMode'].should == "" # expected 'backgroundNotifications'
end
# 5
it "should return push properties by property name" do
puts "should return push properties by property name"
if push_type == "rhoconnect_push"
@properties['pushAppName1'].should == 'someappname'
@properties['pushServer1'].should == "http://#{RhoconnectHelper.push_host}:#{RhoconnectHelper.push_port}"
@properties['type1'].should == "rhoconnect-push"
else # gcm
@properties['pushAppName1'].should == ''
@properties['pushServer1'].should == ''
@properties['type1'].should == "native-push"
end
@properties['userNotifyMode1'].should == "" # expected 'backgroundNotifications'
end
# 6
it "should set userNotifyMode on Android" do
puts "should set userNotifyMode on Android"
@properties['userNotifyMode2'].should == 'backgroundNotifications'
end
# 7
it 'should process sequence of push messages' do
puts 'should process sequence of push messages'
COUNT = 3
# puts "Sending #{COUNT} push messages ..."
alerts = {}
COUNT.times do |i|
message = "magic#{i}"
alerts[message] = true
params = { :user_id=>['pushclient'], :message => message}
RhoconnectHelper.api_post('users/ping',params,@api_token)
sleep 3
end
# puts 'Waiting messages with push content...'
COUNT.times do |i|
$mutex.synchronize do
break if $requests.count == COUNT
$signal.wait($mutex, 30)
end
# puts "Message count: #{$requests.count}"
end
$requests.count.should == COUNT
$mutex.synchronize do
# puts alerts.inspect
COUNT.times do |i|
message = $requests[i].query['alert']
message.should_not be_nil
# puts "message: #{message}"
alerts[message].should be_true
alerts[message] = false
end
$requests.clear
end
end
# 8
it 'should process push message with exit command' do
puts 'should process push message with exit command'
message = 'exit'
params = { :user_id=>['pushclient'], :message=>message }
RhoconnectHelper.api_post('users/ping',params,@api_token)
# puts 'Waiting message with push content...'
expect_request('alert').should == message
sleep 5
args = $deviceId ? ['-s', $deviceId, 'shell', 'ps'] : ['-e', 'shell', 'ps']
output = Jake.run2('adb', args, {:hide_output => true})
(output =~ /push_client_rb/).should be_nil
end
# 9
it 'should start stopped app and process pending push message' do
puts 'should start stopped app and process pending push message'
args = $deviceId ? ['-s', $deviceId, 'shell', 'ps'] : ['-e', 'shell', 'ps']
output = Jake.run2('adb', args, {:hide_output => true})
(output =~ /push_client_rb/).should be_nil
# puts 'Sending push message with greeting ...'
message = 'Hello'
params = { :user_id=>['pushclient'], :message => message}
RhoconnectHelper.api_post('users/ping',params,@api_token)
# puts 'Waiting ping message with push content ...'
expect_request('alert', 60).should == message
args = $deviceId ? ['-s', $deviceId, 'shell', 'ps'] : ['-e', 'shell', 'ps']
output = Jake.run2('adb', args, {:hide_output => true})
(output =~ /push_client_rb/).should_not be_nil
end
# 10
it 'should logout and login back and process ping message' do
puts 'should logout and login back and process ping message'
message = 'logout'
params = { :user_id=>['pushclient'], :message=>message }
RhoconnectHelper.api_post('users/ping',params,@api_token)
expect_request('alert').should == message
system("adb #{$deviceOpts} shell am start -a android.intent.action.MAIN -n com.rhomobile.push_client_rb/com.rhomobile.rhodes.RhodesActivity", :out=>"/dev/null").should == true
expect_request('error').should == "0"
device_id = expect_request('device_id')
device_id.should_not be_nil
device_id.should_not == ''
message = 'welcome'
params = { :user_id=>['pushclient'], :message => message}
RhoconnectHelper.api_post('users/ping',params,@api_token)
expect_request('alert').should == message
end
end
end
| 35.672093 | 181 | 0.646587 |
38eaf0326e1a23d31fb99fe96631bb4761672ea5 | 1,931 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::CognitiveServices::Customvisionprediction::V2_0
module Models
#
# Model object.
#
#
class BoundingBox
include MsRestAzure
# @return [Float]
attr_accessor :left
# @return [Float]
attr_accessor :top
# @return [Float]
attr_accessor :width
# @return [Float]
attr_accessor :height
#
# Mapper for BoundingBox class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'BoundingBox',
type: {
name: 'Composite',
class_name: 'BoundingBox',
model_properties: {
left: {
client_side_validation: true,
required: false,
serialized_name: 'left',
type: {
name: 'Double'
}
},
top: {
client_side_validation: true,
required: false,
serialized_name: 'top',
type: {
name: 'Double'
}
},
width: {
client_side_validation: true,
required: false,
serialized_name: 'width',
type: {
name: 'Double'
}
},
height: {
client_side_validation: true,
required: false,
serialized_name: 'height',
type: {
name: 'Double'
}
}
}
}
}
end
end
end
end
| 23.839506 | 70 | 0.456758 |
bbaa461419f5607c04166aff65c788fae7f74c64 | 1,473 | module OpenIDTokenProxy
class Token
module Authentication
extend ActiveSupport::Concern
included do
rescue_from OpenIDTokenProxy::Error, with: :require_authorization
helper_method :current_token, :raw_token
end
module ClassMethods
def require_valid_token(*args)
before_action :require_valid_token, *args
after_action :expose_token_expiry_time
end
end
def set_authentication_url!
uri = OpenIDTokenProxy.client.authorization_uri
response.headers['X-Authentication-URL'] = uri
end
def require_authorization(exception)
set_authentication_url!
render json: exception.to_json, status: :unauthorized
end
def require_valid_token
config = OpenIDTokenProxy.config
current_token.validate! audiences: config.allowed_audiences
end
def expose_token_expiry_time
response.headers['X-Token-Expiry-Time'] = current_token.expiry_time.iso8601
end
def current_token
@current_token ||= OpenIDTokenProxy::Token.decode!(raw_token)
end
def raw_token
token = params[:token]
return token if token
authorization = request.headers['Authorization']
if authorization
token = authorization[/Bearer (.+)/, 1]
return token if token
end
request.headers['X-Token'] || cookies[:token]
end
end
end
end
| 25.842105 | 83 | 0.65852 |
7a6ac5af6cb399527309d6173e9a30df0e618ace | 617 | class Flyway < Formula
desc "Database version control to control migrations"
homepage "https://flywaydb.org/"
url "https://search.maven.org/remotecontent?filepath=org/flywaydb/flyway-commandline/6.3.2/flyway-commandline-6.3.2.tar.gz"
sha256 "d81c8d428109e5327d110ba0f4f34d5dcb019f037035f26388fac26bffc161ab"
bottle :unneeded
depends_on "openjdk"
def install
rm Dir["*.cmd"]
libexec.install Dir["*"]
(bin/"flyway").write_env_script libexec/"flyway", :JAVA_HOME => Formula["openjdk"].opt_prefix
end
test do
system "#{bin}/flyway", "-url=jdbc:h2:mem:flywaydb", "validate"
end
end
| 29.380952 | 125 | 0.730956 |
bbeab2de9e45b29c49781a0c38fc722b93ad1436 | 853 | require 'time'
module Serverspec::Type
class X509PrivateKey < Base
def valid?
runner_res = @runner.run_command("echo | openssl rsa -in #{name} -check -noout -passin #{@options[:passin] || "stdin"}")
( runner_res.exit_status == 0 && runner_res.stdout.chomp == 'RSA key ok' ) && ([email protected]_key?(:passin) || encrypted?)
end
def encrypted?
@runner.run_command("grep -Ewq \"^(Proc-Type.*ENCRYPTED|-----BEGIN ENCRYPTED PRIVATE KEY-----)$\" #{name}").exit_status == 0
end
def has_matching_certificate?(cert_file)
h1 = @runner.run_command("openssl x509 -noout -modulus -in #{cert_file}")
h2 = @runner.run_command("echo | openssl rsa -noout -modulus -in #{name} -passin #{@options[:passin] || "stdin"}")
(h1.stdout == h2.stdout) && (h1.exit_status == 0) && (h2.exit_status == 0)
end
end
end
| 40.619048 | 130 | 0.631887 |
79eaa6112ca2425ce7d69148c4eeb6431c67274e | 224 | Rails.application.routes.draw do
resources :stocks do
collection { post :import }
end
devise_for :users
root to: 'stocks#index'
get 'analytics', to: 'pages#analytics'
get 'settings', to: 'pages#settings'
end
| 22.4 | 40 | 0.700893 |
873fa9dac3cc73a26fba04822f7a0cc10950ef03 | 221 | require 'rails_helper'
RSpec.describe "Pages", type: :request do
describe "GET /home" do
it "returns http success" do
get "/pages/home"
expect(response).to have_http_status(:success)
end
end
end
| 18.416667 | 52 | 0.674208 |
e2062d393cae957f33af98b00071afae311f8acd | 1,511 | # frozen_string_literal: true
require 'capybara/rails'
require 'capybara/rspec'
require 'webdrivers'
# default capybara/selenium configuration
# https://github.com/itmammoth/capybara-bootstrap/blob/master/scrape.rb
# https://thoughtbot.com/blog/headless-feature-specs-with-chrome
# run as headless mode with set window size
Capybara.register_driver :headless_chrome do |app|
options = Selenium::WebDriver::Chrome::Options.new(
# Additional stuff is disabled to reduce the amount of memory required to execute the tests
# no-sandbox is required to get it to run in docker
args: %w[headless disable-extensions disable-gpu disable-infobars disable-translate no-sandbox window-size=1280,800]
)
Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end
Capybara.javascript_driver = :headless_chrome
Capybara.configure do |config|
config.default_max_wait_time = 5 # seconds
config.default_driver = :headless_chrome
end
# used for Integration Testing
# https://gitlab.com/gitlab-org/gitlab-ce/blob/master/spec/support/capybara.rb
RSpec.configure do |config|
# capybara/rspec already calls Capybara.reset_sessions! in an `after` hook,
# but `block_and_wait_for_requests_complete` is called before it so by
# calling it explicitly here, we prevent any new requests from being fired
config.after(:each, :js) do
# Clear sessions to remove logged in user from Capybara webdriver session
Capybara.reset_sessions!
block_and_wait_for_requests_complete
end
end
| 39.763158 | 120 | 0.783587 |
21449af1dcc80ac9b4a685072544446b1c8bf1e9 | 1,138 | #
# Copyright 2012 Wade Alcorn [email protected]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# DNS Enumeration
class Dns_enumeration < BeEF::Core::Command
def self.options
return [
{'name' => 'dns_list', 'ui_label' => 'DNS (comma separated)', 'value' => '%default%'},
{'name' => 'timeout', 'ui_label' => 'Timeout (ms)', 'value' => '4000'}
]
end
def post_execute
content = {}
content['result'] =@datastore['result'] if not @datastore['result'].nil?
if content.empty?
content['fail'] = 'No DNS hosts have been discovered.'
end
save content
end
end
| 30.756757 | 94 | 0.66696 |
188da471d2b27f0d5362bb375b123c4ed544db71 | 252 | module Connect
class AuthorizationRequestObject < ActiveRecord::Base
belongs_to :authorization
belongs_to :request_object
include Join
validates :authorization, presence: true
validates :request_object, presence: true
end
end | 22.909091 | 55 | 0.765873 |
39e46d612dfcf5e1452ab9ec8ed1c13831fc9ba1 | 460 | def fix_dup_balances(u)
u.account_lists.each(&method(:fix_dup_balance))
end
def fix_dup_balance(a)
balance_to_account = {}
a.designation_accounts.order("CASE WHEN name LIKE '% and %' THEN 0 ELSE 1 END")
.order(created_at: :desc).each do |da|
next unless da.balance.present?
if balance_to_account[da.balance].present?
da.update!(active: false)
else
balance_to_account[da.balance] = da
end
end
a.async(:import_data)
end
| 25.555556 | 81 | 0.704348 |
7945e5b71eeee5ebaee4b28a1f6dab312d509daf | 7,837 |
# line 1 "coordinate.rl"
# coordinate.rl
module Mvnizer
class CoordinateLexer
# line 33 "coordinate.rl"
def initialize
@group_found = false
# line 18 "coordinate.rb"
class << self
attr_accessor :_coordinate_lexer_actions
private :_coordinate_lexer_actions, :_coordinate_lexer_actions=
end
self._coordinate_lexer_actions = [
0, 1, 2, 1, 5, 1, 6, 1,
7, 1, 8, 2, 0, 1, 2, 3,
4
]
class << self
attr_accessor :_coordinate_lexer_key_offsets
private :_coordinate_lexer_key_offsets, :_coordinate_lexer_key_offsets=
end
self._coordinate_lexer_key_offsets = [
0, 0, 1, 2, 3, 11, 20, 26,
35
]
class << self
attr_accessor :_coordinate_lexer_trans_keys
private :_coordinate_lexer_trans_keys, :_coordinate_lexer_trans_keys=
end
self._coordinate_lexer_trans_keys = [
106, 97, 114, 45, 46, 48, 57, 65,
90, 97, 122, 97, 45, 46, 48, 57,
65, 90, 98, 122, 58, 106, 65, 90,
97, 122, 58, 45, 46, 48, 57, 65,
90, 97, 122, 58, 114, 45, 46, 48,
57, 65, 90, 97, 122, 0
]
class << self
attr_accessor :_coordinate_lexer_single_lengths
private :_coordinate_lexer_single_lengths, :_coordinate_lexer_single_lengths=
end
self._coordinate_lexer_single_lengths = [
0, 1, 1, 1, 0, 1, 2, 1,
2
]
class << self
attr_accessor :_coordinate_lexer_range_lengths
private :_coordinate_lexer_range_lengths, :_coordinate_lexer_range_lengths=
end
self._coordinate_lexer_range_lengths = [
0, 0, 0, 0, 4, 4, 2, 4,
4
]
class << self
attr_accessor :_coordinate_lexer_index_offsets
private :_coordinate_lexer_index_offsets, :_coordinate_lexer_index_offsets=
end
self._coordinate_lexer_index_offsets = [
0, 0, 2, 4, 6, 11, 17, 22,
28
]
class << self
attr_accessor :_coordinate_lexer_indicies
private :_coordinate_lexer_indicies, :_coordinate_lexer_indicies=
end
self._coordinate_lexer_indicies = [
0, 1, 2, 1, 3, 1, 5, 5,
5, 5, 4, 6, 5, 5, 5, 5,
1, 7, 9, 8, 8, 1, 11, 5,
5, 5, 5, 10, 11, 8, 5, 5,
5, 5, 10, 0
]
class << self
attr_accessor :_coordinate_lexer_trans_targs
private :_coordinate_lexer_trans_targs, :_coordinate_lexer_trans_targs=
end
self._coordinate_lexer_trans_targs = [
2, 0, 3, 6, 6, 7, 8, 1,
4, 5, 6, 6
]
class << self
attr_accessor :_coordinate_lexer_trans_actions
private :_coordinate_lexer_trans_actions, :_coordinate_lexer_trans_actions=
end
self._coordinate_lexer_trans_actions = [
0, 0, 0, 5, 9, 0, 14, 0,
0, 0, 7, 3
]
class << self
attr_accessor :_coordinate_lexer_to_state_actions
private :_coordinate_lexer_to_state_actions, :_coordinate_lexer_to_state_actions=
end
self._coordinate_lexer_to_state_actions = [
0, 0, 0, 0, 0, 0, 11, 0,
0
]
class << self
attr_accessor :_coordinate_lexer_from_state_actions
private :_coordinate_lexer_from_state_actions, :_coordinate_lexer_from_state_actions=
end
self._coordinate_lexer_from_state_actions = [
0, 0, 0, 0, 0, 0, 1, 0,
0
]
class << self
attr_accessor :_coordinate_lexer_eof_trans
private :_coordinate_lexer_eof_trans, :_coordinate_lexer_eof_trans=
end
self._coordinate_lexer_eof_trans = [
0, 0, 0, 0, 5, 0, 0, 11,
11
]
class << self
attr_accessor :coordinate_lexer_start
end
self.coordinate_lexer_start = 6;
class << self
attr_accessor :coordinate_lexer_first_final
end
self.coordinate_lexer_first_final = 6;
class << self
attr_accessor :coordinate_lexer_error
end
self.coordinate_lexer_error = 0;
class << self
attr_accessor :coordinate_lexer_en_main
end
self.coordinate_lexer_en_main = 6;
# line 39 "coordinate.rl"
end
def scan(data)
# convert string into an array of 8-bit signed integers.
data = data.unpack("c*") if(data.is_a?(String))
eof = pe = data.length
ts = te = 0
# line 164 "coordinate.rb"
begin
p ||= 0
pe ||= data.length
cs = coordinate_lexer_start
ts = nil
te = nil
act = 0
end
# line 48 "coordinate.rl"
# line 176 "coordinate.rb"
begin
_klen, _trans, _keys, _acts, _nacts = nil
_goto_level = 0
_resume = 10
_eof_trans = 15
_again = 20
_test_eof = 30
_out = 40
while true
_trigger_goto = false
if _goto_level <= 0
if p == pe
_goto_level = _test_eof
next
end
if cs == 0
_goto_level = _out
next
end
end
if _goto_level <= _resume
_acts = _coordinate_lexer_from_state_actions[cs]
_nacts = _coordinate_lexer_actions[_acts]
_acts += 1
while _nacts > 0
_nacts -= 1
_acts += 1
case _coordinate_lexer_actions[_acts - 1]
when 2 then
# line 1 "NONE"
begin
ts = p
end
# line 210 "coordinate.rb"
end # from state action switch
end
if _trigger_goto
next
end
_keys = _coordinate_lexer_key_offsets[cs]
_trans = _coordinate_lexer_index_offsets[cs]
_klen = _coordinate_lexer_single_lengths[cs]
_break_match = false
begin
if _klen > 0
_lower = _keys
_upper = _keys + _klen - 1
loop do
break if _upper < _lower
_mid = _lower + ( (_upper - _lower) >> 1 )
if data[p].ord < _coordinate_lexer_trans_keys[_mid]
_upper = _mid - 1
elsif data[p].ord > _coordinate_lexer_trans_keys[_mid]
_lower = _mid + 1
else
_trans += (_mid - _keys)
_break_match = true
break
end
end # loop
break if _break_match
_keys += _klen
_trans += _klen
end
_klen = _coordinate_lexer_range_lengths[cs]
if _klen > 0
_lower = _keys
_upper = _keys + (_klen << 1) - 2
loop do
break if _upper < _lower
_mid = _lower + (((_upper-_lower) >> 1) & ~1)
if data[p].ord < _coordinate_lexer_trans_keys[_mid]
_upper = _mid - 2
elsif data[p].ord > _coordinate_lexer_trans_keys[_mid+1]
_lower = _mid + 2
else
_trans += ((_mid - _keys) >> 1)
_break_match = true
break
end
end # loop
break if _break_match
_trans += _klen
end
end while false
_trans = _coordinate_lexer_indicies[_trans]
end
if _goto_level <= _eof_trans
cs = _coordinate_lexer_trans_targs[_trans]
if _coordinate_lexer_trans_actions[_trans] != 0
_acts = _coordinate_lexer_trans_actions[_trans]
_nacts = _coordinate_lexer_actions[_acts]
_acts += 1
while _nacts > 0
_nacts -= 1
_acts += 1
case _coordinate_lexer_actions[_acts - 1]
when 3 then
# line 1 "NONE"
begin
te = p+1
end
when 4 then
# line 26 "coordinate.rl"
begin
act = 2; end
when 5 then
# line 25 "coordinate.rl"
begin
te = p+1
begin puts "#{ts} => #{te} #{data[ts...te].pack("c*")} " end
end
when 6 then
# line 27 "coordinate.rl"
begin
te = p+1
begin puts "Doh" end
end
when 7 then
# line 26 "coordinate.rl"
begin
te = p
p = p - 1; begin puts "Blah" end
end
when 8 then
# line 1 "NONE"
begin
case act
when 0 then
begin begin
cs = 0
_trigger_goto = true
_goto_level = _again
break
end
end
when 2 then
begin begin p = ((te))-1; end
puts "Blah" end
end
end
# line 321 "coordinate.rb"
end # action switch
end
end
if _trigger_goto
next
end
end
if _goto_level <= _again
_acts = _coordinate_lexer_to_state_actions[cs]
_nacts = _coordinate_lexer_actions[_acts]
_acts += 1
while _nacts > 0
_nacts -= 1
_acts += 1
case _coordinate_lexer_actions[_acts - 1]
when 0 then
# line 1 "NONE"
begin
ts = nil; end
when 1 then
# line 1 "NONE"
begin
act = 0
end
# line 346 "coordinate.rb"
end # to state action switch
end
if _trigger_goto
next
end
if cs == 0
_goto_level = _out
next
end
p += 1
if p != pe
_goto_level = _resume
next
end
end
if _goto_level <= _test_eof
if p == eof
if _coordinate_lexer_eof_trans[cs] > 0
_trans = _coordinate_lexer_eof_trans[cs] - 1;
_goto_level = _eof_trans
next;
end
end
end
if _goto_level <= _out
break
end
end
end
# line 49 "coordinate.rl"
end
private
def get_string(data, p)
data[@start_string...p].pack("c*")
end
end
end | 20.355844 | 86 | 0.681894 |
6138036b0af59f3e650620ca6caa5442ad9533a8 | 68,630 | # frozen_string_literal: true
require 'spec_helper'
describe API::Runner, :clean_gitlab_redis_shared_state do
include StubGitlabCalls
include RedisHelpers
include WorkhorseHelpers
let(:registration_token) { 'abcdefg123456' }
before do
stub_feature_flags(ci_enable_live_trace: true)
stub_gitlab_calls
stub_application_setting(runners_registration_token: registration_token)
allow_any_instance_of(Ci::Runner).to receive(:cache_attributes)
end
describe '/api/v4/runners' do
describe 'POST /api/v4/runners' do
context 'when no token is provided' do
it 'returns 400 error' do
post api('/runners')
expect(response).to have_gitlab_http_status 400
end
end
context 'when invalid token is provided' do
it 'returns 403 error' do
post api('/runners'), params: { token: 'invalid' }
expect(response).to have_gitlab_http_status 403
end
end
context 'when valid token is provided' do
it 'creates runner with default values' do
post api('/runners'), params: { token: registration_token }
runner = Ci::Runner.first
expect(response).to have_gitlab_http_status 201
expect(json_response['id']).to eq(runner.id)
expect(json_response['token']).to eq(runner.token)
expect(runner.run_untagged).to be true
expect(runner.active).to be true
expect(runner.token).not_to eq(registration_token)
expect(runner).to be_instance_type
end
context 'when project token is used' do
let(:project) { create(:project) }
it 'creates project runner' do
post api('/runners'), params: { token: project.runners_token }
expect(response).to have_gitlab_http_status 201
expect(project.runners.size).to eq(1)
runner = Ci::Runner.first
expect(runner.token).not_to eq(registration_token)
expect(runner.token).not_to eq(project.runners_token)
expect(runner).to be_project_type
end
end
context 'when group token is used' do
let(:group) { create(:group) }
it 'creates a group runner' do
post api('/runners'), params: { token: group.runners_token }
expect(response).to have_http_status 201
expect(group.runners.reload.size).to eq(1)
runner = Ci::Runner.first
expect(runner.token).not_to eq(registration_token)
expect(runner.token).not_to eq(group.runners_token)
expect(runner).to be_group_type
end
end
end
context 'when runner description is provided' do
it 'creates runner' do
post api('/runners'), params: {
token: registration_token,
description: 'server.hostname'
}
expect(response).to have_gitlab_http_status 201
expect(Ci::Runner.first.description).to eq('server.hostname')
end
end
context 'when runner tags are provided' do
it 'creates runner' do
post api('/runners'), params: {
token: registration_token,
tag_list: 'tag1, tag2'
}
expect(response).to have_gitlab_http_status 201
expect(Ci::Runner.first.tag_list.sort).to eq(%w(tag1 tag2))
end
end
context 'when option for running untagged jobs is provided' do
context 'when tags are provided' do
it 'creates runner' do
post api('/runners'), params: {
token: registration_token,
run_untagged: false,
tag_list: ['tag']
}
expect(response).to have_gitlab_http_status 201
expect(Ci::Runner.first.run_untagged).to be false
expect(Ci::Runner.first.tag_list.sort).to eq(['tag'])
end
end
context 'when tags are not provided' do
it 'returns 400 error' do
post api('/runners'), params: {
token: registration_token,
run_untagged: false
}
expect(response).to have_gitlab_http_status 400
expect(json_response['message']).to include(
'tags_list' => ['can not be empty when runner is not allowed to pick untagged jobs'])
end
end
end
context 'when option for locking Runner is provided' do
it 'creates runner' do
post api('/runners'), params: {
token: registration_token,
locked: true
}
expect(response).to have_gitlab_http_status 201
expect(Ci::Runner.first.locked).to be true
end
end
context 'when option for activating a Runner is provided' do
context 'when active is set to true' do
it 'creates runner' do
post api('/runners'), params: {
token: registration_token,
active: true
}
expect(response).to have_gitlab_http_status 201
expect(Ci::Runner.first.active).to be true
end
end
context 'when active is set to false' do
it 'creates runner' do
post api('/runners'), params: {
token: registration_token,
active: false
}
expect(response).to have_gitlab_http_status 201
expect(Ci::Runner.first.active).to be false
end
end
end
context 'when access_level is provided for Runner' do
context 'when access_level is set to ref_protected' do
it 'creates runner' do
post api('/runners'), params: {
token: registration_token,
access_level: 'ref_protected'
}
expect(response).to have_gitlab_http_status 201
expect(Ci::Runner.first.ref_protected?).to be true
end
end
context 'when access_level is set to not_protected' do
it 'creates runner' do
post api('/runners'), params: {
token: registration_token,
access_level: 'not_protected'
}
expect(response).to have_gitlab_http_status 201
expect(Ci::Runner.first.ref_protected?).to be false
end
end
end
context 'when maximum job timeout is specified' do
it 'creates runner' do
post api('/runners'), params: {
token: registration_token,
maximum_timeout: 9000
}
expect(response).to have_gitlab_http_status 201
expect(Ci::Runner.first.maximum_timeout).to eq(9000)
end
context 'when maximum job timeout is empty' do
it 'creates runner' do
post api('/runners'), params: {
token: registration_token,
maximum_timeout: ''
}
expect(response).to have_gitlab_http_status 201
expect(Ci::Runner.first.maximum_timeout).to be_nil
end
end
end
%w(name version revision platform architecture).each do |param|
context "when info parameter '#{param}' info is present" do
let(:value) { "#{param}_value" }
it "updates provided Runner's parameter" do
post api('/runners'), params: {
token: registration_token,
info: { param => value }
}
expect(response).to have_gitlab_http_status 201
expect(Ci::Runner.first.read_attribute(param.to_sym)).to eq(value)
end
end
end
it "sets the runner's ip_address" do
post api('/runners'),
params: { token: registration_token },
headers: { 'X-Forwarded-For' => '123.111.123.111' }
expect(response).to have_gitlab_http_status 201
expect(Ci::Runner.first.ip_address).to eq('123.111.123.111')
end
end
describe 'DELETE /api/v4/runners' do
context 'when no token is provided' do
it 'returns 400 error' do
delete api('/runners')
expect(response).to have_gitlab_http_status 400
end
end
context 'when invalid token is provided' do
it 'returns 403 error' do
delete api('/runners'), params: { token: 'invalid' }
expect(response).to have_gitlab_http_status 403
end
end
context 'when valid token is provided' do
let(:runner) { create(:ci_runner) }
it 'deletes Runner' do
delete api('/runners'), params: { token: runner.token }
expect(response).to have_gitlab_http_status 204
expect(Ci::Runner.count).to eq(0)
end
it_behaves_like '412 response' do
let(:request) { api('/runners') }
let(:params) { { token: runner.token } }
end
end
end
describe 'POST /api/v4/runners/verify' do
let(:runner) { create(:ci_runner) }
context 'when no token is provided' do
it 'returns 400 error' do
post api('/runners/verify')
expect(response).to have_gitlab_http_status :bad_request
end
end
context 'when invalid token is provided' do
it 'returns 403 error' do
post api('/runners/verify'), params: { token: 'invalid-token' }
expect(response).to have_gitlab_http_status 403
end
end
context 'when valid token is provided' do
it 'verifies Runner credentials' do
post api('/runners/verify'), params: { token: runner.token }
expect(response).to have_gitlab_http_status 200
end
end
end
end
describe '/api/v4/jobs' do
let(:root_namespace) { create(:namespace) }
let(:namespace) { create(:namespace, parent: root_namespace) }
let(:project) { create(:project, namespace: namespace, shared_runners_enabled: false) }
let(:pipeline) { create(:ci_pipeline, project: project, ref: 'master') }
let(:runner) { create(:ci_runner, :project, projects: [project]) }
let(:job) do
create(:ci_build, :artifacts, :extended_options,
pipeline: pipeline, name: 'spinach', stage: 'test', stage_idx: 0)
end
describe 'POST /api/v4/jobs/request' do
let!(:last_update) {}
let!(:new_update) { }
let(:user_agent) { 'gitlab-runner 9.0.0 (9-0-stable; go1.7.4; linux/amd64)' }
before do
job
stub_container_registry_config(enabled: false)
end
shared_examples 'no jobs available' do
before do
request_job
end
context 'when runner sends version in User-Agent' do
context 'for stable version' do
it 'gives 204 and set X-GitLab-Last-Update' do
expect(response).to have_gitlab_http_status(204)
expect(response.header).to have_key('X-GitLab-Last-Update')
end
end
context 'when last_update is up-to-date' do
let(:last_update) { runner.ensure_runner_queue_value }
it 'gives 204 and set the same X-GitLab-Last-Update' do
expect(response).to have_gitlab_http_status(204)
expect(response.header['X-GitLab-Last-Update']).to eq(last_update)
end
end
context 'when last_update is outdated' do
let(:last_update) { runner.ensure_runner_queue_value }
let(:new_update) { runner.tick_runner_queue }
it 'gives 204 and set a new X-GitLab-Last-Update' do
expect(response).to have_gitlab_http_status(204)
expect(response.header['X-GitLab-Last-Update']).to eq(new_update)
end
end
context 'when beta version is sent' do
let(:user_agent) { 'gitlab-runner 9.0.0~beta.167.g2b2bacc (master; go1.7.4; linux/amd64)' }
it { expect(response).to have_gitlab_http_status(204) }
end
context 'when pre-9-0 version is sent' do
let(:user_agent) { 'gitlab-ci-multi-runner 1.6.0 (1-6-stable; go1.6.3; linux/amd64)' }
it { expect(response).to have_gitlab_http_status(204) }
end
context 'when pre-9-0 beta version is sent' do
let(:user_agent) { 'gitlab-ci-multi-runner 1.6.0~beta.167.g2b2bacc (master; go1.6.3; linux/amd64)' }
it { expect(response).to have_gitlab_http_status(204) }
end
end
end
context 'when no token is provided' do
it 'returns 400 error' do
post api('/jobs/request')
expect(response).to have_gitlab_http_status 400
end
end
context 'when invalid token is provided' do
it 'returns 403 error' do
post api('/jobs/request'), params: { token: 'invalid' }
expect(response).to have_gitlab_http_status 403
end
end
context 'when valid token is provided' do
context 'when Runner is not active' do
let(:runner) { create(:ci_runner, :inactive) }
let(:update_value) { runner.ensure_runner_queue_value }
it 'returns 204 error' do
request_job
expect(response).to have_gitlab_http_status(204)
expect(response.header['X-GitLab-Last-Update']).to eq(update_value)
end
end
context 'when jobs are finished' do
before do
job.success
end
it_behaves_like 'no jobs available'
end
context 'when other projects have pending jobs' do
before do
job.success
create(:ci_build, :pending)
end
it_behaves_like 'no jobs available'
end
context 'when shared runner requests job for project without shared_runners_enabled' do
let(:runner) { create(:ci_runner, :instance) }
it_behaves_like 'no jobs available'
end
context 'when there is a pending job' do
let(:expected_job_info) do
{ 'name' => job.name,
'stage' => job.stage,
'project_id' => job.project.id,
'project_name' => job.project.name }
end
let(:expected_git_info) do
{ 'repo_url' => job.repo_url,
'ref' => job.ref,
'sha' => job.sha,
'before_sha' => job.before_sha,
'ref_type' => 'branch',
'refspecs' => ["+refs/heads/#{job.ref}:refs/remotes/origin/#{job.ref}"],
'depth' => project.ci_default_git_depth }
end
let(:expected_steps) do
[{ 'name' => 'script',
'script' => %w(echo),
'timeout' => job.metadata_timeout,
'when' => 'on_success',
'allow_failure' => false },
{ 'name' => 'after_script',
'script' => %w(ls date),
'timeout' => job.metadata_timeout,
'when' => 'always',
'allow_failure' => true }]
end
let(:expected_variables) do
[{ 'key' => 'CI_JOB_NAME', 'value' => 'spinach', 'public' => true, 'masked' => false },
{ 'key' => 'CI_JOB_STAGE', 'value' => 'test', 'public' => true, 'masked' => false },
{ 'key' => 'DB_NAME', 'value' => 'postgres', 'public' => true, 'masked' => false }]
end
let(:expected_artifacts) do
[{ 'name' => 'artifacts_file',
'untracked' => false,
'paths' => %w(out/),
'when' => 'always',
'expire_in' => '7d',
"artifact_type" => "archive",
"artifact_format" => "zip" }]
end
let(:expected_cache) do
[{ 'key' => 'cache_key',
'untracked' => false,
'paths' => ['vendor/*'],
'policy' => 'pull-push' }]
end
let(:expected_features) { { 'trace_sections' => true } }
it 'picks a job' do
request_job info: { platform: :darwin }
expect(response).to have_gitlab_http_status(201)
expect(response.headers).not_to have_key('X-GitLab-Last-Update')
expect(runner.reload.platform).to eq('darwin')
expect(json_response['id']).to eq(job.id)
expect(json_response['token']).to eq(job.token)
expect(json_response['job_info']).to eq(expected_job_info)
expect(json_response['git_info']).to eq(expected_git_info)
expect(json_response['image']).to eq({ 'name' => 'ruby:2.1', 'entrypoint' => '/bin/sh', 'ports' => [] })
expect(json_response['services']).to eq([{ 'name' => 'postgres', 'entrypoint' => nil,
'alias' => nil, 'command' => nil, 'ports' => [] },
{ 'name' => 'docker:stable-dind', 'entrypoint' => '/bin/sh',
'alias' => 'docker', 'command' => 'sleep 30', 'ports' => [] }])
expect(json_response['steps']).to eq(expected_steps)
expect(json_response['artifacts']).to eq(expected_artifacts)
expect(json_response['cache']).to eq(expected_cache)
expect(json_response['variables']).to include(*expected_variables)
expect(json_response['features']).to eq(expected_features)
end
context 'when job is made for tag' do
let!(:job) { create(:ci_build, :tag, pipeline: pipeline, name: 'spinach', stage: 'test', stage_idx: 0) }
it 'sets branch as ref_type' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['git_info']['ref_type']).to eq('tag')
end
context 'when GIT_DEPTH is specified' do
before do
create(:ci_pipeline_variable, key: 'GIT_DEPTH', value: 1, pipeline: pipeline)
end
it 'specifies refspecs' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['git_info']['refspecs']).to include("+refs/tags/#{job.ref}:refs/tags/#{job.ref}")
end
end
context 'when GIT_DEPTH is not specified and there is no default git depth for the project' do
before do
project.update!(ci_default_git_depth: nil)
end
it 'specifies refspecs' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['git_info']['refspecs'])
.to contain_exactly('+refs/tags/*:refs/tags/*', '+refs/heads/*:refs/remotes/origin/*')
end
end
end
context 'when job filtered by job_age' do
let!(:job) { create(:ci_build, :tag, pipeline: pipeline, name: 'spinach', stage: 'test', stage_idx: 0, queued_at: 60.seconds.ago) }
context 'job is queued less than job_age parameter' do
let(:job_age) { 120 }
it 'gives 204' do
request_job(job_age: job_age)
expect(response).to have_gitlab_http_status(204)
end
end
context 'job is queued more than job_age parameter' do
let(:job_age) { 30 }
it 'picks a job' do
request_job(job_age: job_age)
expect(response).to have_gitlab_http_status(201)
end
end
end
context 'when job is made for branch' do
it 'sets tag as ref_type' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['git_info']['ref_type']).to eq('branch')
end
context 'when GIT_DEPTH is specified' do
before do
create(:ci_pipeline_variable, key: 'GIT_DEPTH', value: 1, pipeline: pipeline)
end
it 'specifies refspecs' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['git_info']['refspecs']).to include("+refs/heads/#{job.ref}:refs/remotes/origin/#{job.ref}")
end
end
context 'when GIT_DEPTH is not specified and there is no default git depth for the project' do
before do
project.update!(ci_default_git_depth: nil)
end
it 'specifies refspecs' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['git_info']['refspecs'])
.to contain_exactly('+refs/tags/*:refs/tags/*', '+refs/heads/*:refs/remotes/origin/*')
end
end
end
context 'when job is made for merge request' do
let(:pipeline) { create(:ci_pipeline, source: :merge_request_event, project: project, ref: 'feature', merge_request: merge_request) }
let!(:job) { create(:ci_build, pipeline: pipeline, name: 'spinach', ref: 'feature', stage: 'test', stage_idx: 0) }
let(:merge_request) { create(:merge_request) }
it 'sets branch as ref_type' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['git_info']['ref_type']).to eq('branch')
end
context 'when GIT_DEPTH is specified' do
before do
create(:ci_pipeline_variable, key: 'GIT_DEPTH', value: 1, pipeline: pipeline)
end
it 'returns the overwritten git depth for merge request refspecs' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['git_info']['depth']).to eq(1)
end
end
end
it 'updates runner info' do
expect { request_job }.to change { runner.reload.contacted_at }
end
%w(version revision platform architecture).each do |param|
context "when info parameter '#{param}' is present" do
let(:value) { "#{param}_value" }
it "updates provided Runner's parameter" do
request_job info: { param => value }
expect(response).to have_gitlab_http_status(201)
expect(runner.reload.read_attribute(param.to_sym)).to eq(value)
end
end
end
it "sets the runner's ip_address" do
post api('/jobs/request'),
params: { token: runner.token },
headers: { 'User-Agent' => user_agent, 'X-Forwarded-For' => '123.222.123.222' }
expect(response).to have_gitlab_http_status 201
expect(runner.reload.ip_address).to eq('123.222.123.222')
end
it "handles multiple X-Forwarded-For addresses" do
post api('/jobs/request'),
params: { token: runner.token },
headers: { 'User-Agent' => user_agent, 'X-Forwarded-For' => '123.222.123.222, 127.0.0.1' }
expect(response).to have_gitlab_http_status 201
expect(runner.reload.ip_address).to eq('123.222.123.222')
end
context 'when concurrently updating a job' do
before do
expect_any_instance_of(Ci::Build).to receive(:run!)
.and_raise(ActiveRecord::StaleObjectError.new(nil, nil))
end
it 'returns a conflict' do
request_job
expect(response).to have_gitlab_http_status(409)
expect(response.headers).not_to have_key('X-GitLab-Last-Update')
end
end
context 'when project and pipeline have multiple jobs' do
let!(:job) { create(:ci_build, :tag, pipeline: pipeline, name: 'spinach', stage: 'test', stage_idx: 0) }
let!(:job2) { create(:ci_build, :tag, pipeline: pipeline, name: 'rubocop', stage: 'test', stage_idx: 0) }
let!(:test_job) { create(:ci_build, pipeline: pipeline, name: 'deploy', stage: 'deploy', stage_idx: 1) }
before do
job.success
job2.success
end
it 'returns dependent jobs' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['id']).to eq(test_job.id)
expect(json_response['dependencies'].count).to eq(2)
expect(json_response['dependencies']).to include(
{ 'id' => job.id, 'name' => job.name, 'token' => job.token },
{ 'id' => job2.id, 'name' => job2.name, 'token' => job2.token })
end
end
context 'when pipeline have jobs with artifacts' do
let!(:job) { create(:ci_build, :tag, :artifacts, pipeline: pipeline, name: 'spinach', stage: 'test', stage_idx: 0) }
let!(:test_job) { create(:ci_build, pipeline: pipeline, name: 'deploy', stage: 'deploy', stage_idx: 1) }
before do
job.success
end
it 'returns dependent jobs' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['id']).to eq(test_job.id)
expect(json_response['dependencies'].count).to eq(1)
expect(json_response['dependencies']).to include(
{ 'id' => job.id, 'name' => job.name, 'token' => job.token,
'artifacts_file' => { 'filename' => 'ci_build_artifacts.zip', 'size' => 106365 } })
end
end
context 'when explicit dependencies are defined' do
let!(:job) { create(:ci_build, :tag, pipeline: pipeline, name: 'spinach', stage: 'test', stage_idx: 0) }
let!(:job2) { create(:ci_build, :tag, pipeline: pipeline, name: 'rubocop', stage: 'test', stage_idx: 0) }
let!(:test_job) do
create(:ci_build, pipeline: pipeline, token: 'test-job-token', name: 'deploy',
stage: 'deploy', stage_idx: 1,
options: { script: ['bash'], dependencies: [job2.name] })
end
before do
job.success
job2.success
end
it 'returns dependent jobs' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['id']).to eq(test_job.id)
expect(json_response['dependencies'].count).to eq(1)
expect(json_response['dependencies'][0]).to include('id' => job2.id, 'name' => job2.name, 'token' => job2.token)
end
end
context 'when dependencies is an empty array' do
let!(:job) { create(:ci_build, :tag, pipeline: pipeline, name: 'spinach', stage: 'test', stage_idx: 0) }
let!(:job2) { create(:ci_build, :tag, pipeline: pipeline, name: 'rubocop', stage: 'test', stage_idx: 0) }
let!(:empty_dependencies_job) do
create(:ci_build, pipeline: pipeline, token: 'test-job-token', name: 'empty_dependencies_job',
stage: 'deploy', stage_idx: 1,
options: { script: ['bash'], dependencies: [] })
end
before do
job.success
job2.success
end
it 'returns an empty array' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['id']).to eq(empty_dependencies_job.id)
expect(json_response['dependencies'].count).to eq(0)
end
end
context 'when job has no tags' do
before do
job.update(tags: [])
end
context 'when runner is allowed to pick untagged jobs' do
before do
runner.update_column(:run_untagged, true)
end
it 'picks job' do
request_job
expect(response).to have_gitlab_http_status 201
end
end
context 'when runner is not allowed to pick untagged jobs' do
before do
runner.update_column(:run_untagged, false)
end
it_behaves_like 'no jobs available'
end
end
context 'when triggered job is available' do
let(:expected_variables) do
[{ 'key' => 'CI_JOB_NAME', 'value' => 'spinach', 'public' => true, 'masked' => false },
{ 'key' => 'CI_JOB_STAGE', 'value' => 'test', 'public' => true, 'masked' => false },
{ 'key' => 'CI_PIPELINE_TRIGGERED', 'value' => 'true', 'public' => true, 'masked' => false },
{ 'key' => 'DB_NAME', 'value' => 'postgres', 'public' => true, 'masked' => false },
{ 'key' => 'SECRET_KEY', 'value' => 'secret_value', 'public' => false, 'masked' => false },
{ 'key' => 'TRIGGER_KEY_1', 'value' => 'TRIGGER_VALUE_1', 'public' => false, 'masked' => false }]
end
let(:trigger) { create(:ci_trigger, project: project) }
let!(:trigger_request) { create(:ci_trigger_request, pipeline: pipeline, builds: [job], trigger: trigger) }
before do
project.variables << Ci::Variable.new(key: 'SECRET_KEY', value: 'secret_value')
end
shared_examples 'expected variables behavior' do
it 'returns variables for triggers' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['variables']).to include(*expected_variables)
end
end
context 'when variables are stored in trigger_request' do
before do
trigger_request.update_attribute(:variables, { TRIGGER_KEY_1: 'TRIGGER_VALUE_1' } )
end
it_behaves_like 'expected variables behavior'
end
context 'when variables are stored in pipeline_variables' do
before do
create(:ci_pipeline_variable, pipeline: pipeline, key: :TRIGGER_KEY_1, value: 'TRIGGER_VALUE_1')
end
it_behaves_like 'expected variables behavior'
end
end
describe 'registry credentials support' do
let(:registry_url) { 'registry.example.com:5005' }
let(:registry_credentials) do
{ 'type' => 'registry',
'url' => registry_url,
'username' => 'gitlab-ci-token',
'password' => job.token }
end
context 'when registry is enabled' do
before do
stub_container_registry_config(enabled: true, host_port: registry_url)
end
it 'sends registry credentials key' do
request_job
expect(json_response).to have_key('credentials')
expect(json_response['credentials']).to include(registry_credentials)
end
end
context 'when registry is disabled' do
before do
stub_container_registry_config(enabled: false, host_port: registry_url)
end
it 'does not send registry credentials' do
request_job
expect(json_response).to have_key('credentials')
expect(json_response['credentials']).not_to include(registry_credentials)
end
end
end
describe 'timeout support' do
context 'when project specifies job timeout' do
let(:project) { create(:project, shared_runners_enabled: false, build_timeout: 1234) }
it 'contains info about timeout taken from project' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['runner_info']).to include({ 'timeout' => 1234 })
end
context 'when runner specifies lower timeout' do
let(:runner) { create(:ci_runner, :project, maximum_timeout: 1000, projects: [project]) }
it 'contains info about timeout overridden by runner' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['runner_info']).to include({ 'timeout' => 1000 })
end
end
context 'when runner specifies bigger timeout' do
let(:runner) { create(:ci_runner, :project, maximum_timeout: 2000, projects: [project]) }
it 'contains info about timeout not overridden by runner' do
request_job
expect(response).to have_gitlab_http_status(201)
expect(json_response['runner_info']).to include({ 'timeout' => 1234 })
end
end
end
end
end
describe 'port support' do
let(:job) { create(:ci_build, pipeline: pipeline, options: options) }
context 'when job image has ports' do
let(:options) do
{
image: {
name: 'ruby',
ports: [80]
},
services: ['mysql']
}
end
it 'returns the image ports' do
request_job
expect(response).to have_http_status(:created)
expect(json_response).to include(
'id' => job.id,
'image' => a_hash_including('name' => 'ruby', 'ports' => [{ 'number' => 80, 'protocol' => 'http', 'name' => 'default_port' }]),
'services' => all(a_hash_including('name' => 'mysql')))
end
end
context 'when job services settings has ports' do
let(:options) do
{
image: 'ruby',
services: [
{
name: 'tomcat',
ports: [{ number: 8081, protocol: 'http', name: 'custom_port' }]
}
]
}
end
it 'returns the service ports' do
request_job
expect(response).to have_http_status(:created)
expect(json_response).to include(
'id' => job.id,
'image' => a_hash_including('name' => 'ruby'),
'services' => all(a_hash_including('name' => 'tomcat', 'ports' => [{ 'number' => 8081, 'protocol' => 'http', 'name' => 'custom_port' }])))
end
end
end
def request_job(token = runner.token, **params)
new_params = params.merge(token: token, last_update: last_update)
post api('/jobs/request'), params: new_params, headers: { 'User-Agent' => user_agent }
end
end
end
describe 'PUT /api/v4/jobs/:id' do
let(:job) { create(:ci_build, :pending, :trace_live, pipeline: pipeline, runner_id: runner.id) }
before do
job.run!
end
context 'when status is given' do
it 'mark job as succeeded' do
update_job(state: 'success')
job.reload
expect(job).to be_success
end
it 'mark job as failed' do
update_job(state: 'failed')
job.reload
expect(job).to be_failed
expect(job).to be_unknown_failure
end
context 'when failure_reason is script_failure' do
before do
update_job(state: 'failed', failure_reason: 'script_failure')
job.reload
end
it { expect(job).to be_script_failure }
end
context 'when failure_reason is runner_system_failure' do
before do
update_job(state: 'failed', failure_reason: 'runner_system_failure')
job.reload
end
it { expect(job).to be_runner_system_failure }
end
context 'when failure_reason is unrecognized value' do
before do
update_job(state: 'failed', failure_reason: 'what_is_this')
job.reload
end
it { expect(job).to be_unknown_failure }
end
context 'when failure_reason is job_execution_timeout' do
before do
update_job(state: 'failed', failure_reason: 'job_execution_timeout')
job.reload
end
it { expect(job).to be_job_execution_timeout }
end
context 'when failure_reason is unmet_prerequisites' do
before do
update_job(state: 'failed', failure_reason: 'unmet_prerequisites')
job.reload
end
it { expect(job).to be_unmet_prerequisites }
end
end
context 'when trace is given' do
it 'creates a trace artifact' do
allow(BuildFinishedWorker).to receive(:perform_async).with(job.id) do
ArchiveTraceWorker.new.perform(job.id)
end
update_job(state: 'success', trace: 'BUILD TRACE UPDATED')
job.reload
expect(response).to have_gitlab_http_status(200)
expect(job.trace.raw).to eq 'BUILD TRACE UPDATED'
expect(job.job_artifacts_trace.open.read).to eq 'BUILD TRACE UPDATED'
end
context 'when concurrent update of trace is happening' do
before do
job.trace.write('wb') do
update_job(state: 'success', trace: 'BUILD TRACE UPDATED')
end
end
it 'returns that operation conflicts' do
expect(response.status).to eq(409)
end
end
end
context 'when no trace is given' do
it 'does not override trace information' do
update_job
expect(job.reload.trace.raw).to eq 'BUILD TRACE'
end
context 'when running state is sent' do
it 'updates update_at value' do
expect { update_job_after_time }.to change { job.reload.updated_at }
end
end
context 'when other state is sent' do
it "doesn't update update_at value" do
expect { update_job_after_time(20.minutes, state: 'success') }.not_to change { job.reload.updated_at }
end
end
end
context 'when job has been erased' do
let(:job) { create(:ci_build, runner_id: runner.id, erased_at: Time.now) }
it 'responds with forbidden' do
update_job
expect(response).to have_gitlab_http_status(403)
end
end
context 'when job has already been finished' do
before do
job.trace.set('Job failed')
job.drop!(:script_failure)
end
it 'does not update job status and job trace' do
update_job(state: 'success', trace: 'BUILD TRACE UPDATED')
job.reload
expect(response).to have_gitlab_http_status(403)
expect(response.header['Job-Status']).to eq 'failed'
expect(job.trace.raw).to eq 'Job failed'
expect(job).to be_failed
end
end
def update_job(token = job.token, **params)
new_params = params.merge(token: token)
put api("/jobs/#{job.id}"), params: new_params
end
def update_job_after_time(update_interval = 20.minutes, state = 'running')
Timecop.travel(job.updated_at + update_interval) do
update_job(job.token, state: state)
end
end
end
describe 'PATCH /api/v4/jobs/:id/trace' do
let(:job) { create(:ci_build, :running, :trace_live, runner_id: runner.id, pipeline: pipeline) }
let(:headers) { { API::Helpers::Runner::JOB_TOKEN_HEADER => job.token, 'Content-Type' => 'text/plain' } }
let(:headers_with_range) { headers.merge({ 'Content-Range' => '11-20' }) }
let(:update_interval) { 10.seconds.to_i }
before do
initial_patch_the_trace
end
context 'when request is valid' do
it 'gets correct response' do
expect(response.status).to eq 202
expect(job.reload.trace.raw).to eq 'BUILD TRACE appended'
expect(response.header).to have_key 'Range'
expect(response.header).to have_key 'Job-Status'
end
context 'when job has been updated recently' do
it { expect { patch_the_trace }.not_to change { job.updated_at }}
it "changes the job's trace" do
patch_the_trace
expect(job.reload.trace.raw).to eq 'BUILD TRACE appended appended'
end
context 'when Runner makes a force-patch' do
it { expect { force_patch_the_trace }.not_to change { job.updated_at }}
it "doesn't change the build.trace" do
force_patch_the_trace
expect(job.reload.trace.raw).to eq 'BUILD TRACE appended'
end
end
end
context 'when job was not updated recently' do
let(:update_interval) { 15.minutes.to_i }
it { expect { patch_the_trace }.to change { job.updated_at } }
it 'changes the job.trace' do
patch_the_trace
expect(job.reload.trace.raw).to eq 'BUILD TRACE appended appended'
end
context 'when Runner makes a force-patch' do
it { expect { force_patch_the_trace }.to change { job.updated_at } }
it "doesn't change the job.trace" do
force_patch_the_trace
expect(job.reload.trace.raw).to eq 'BUILD TRACE appended'
end
end
end
context 'when project for the build has been deleted' do
let(:job) do
create(:ci_build, :running, :trace_live, runner_id: runner.id, pipeline: pipeline) do |job|
job.project.update(pending_delete: true)
end
end
it 'responds with forbidden' do
expect(response.status).to eq(403)
end
end
context 'when trace is patched' do
before do
patch_the_trace
end
it 'has valid trace' do
expect(response.status).to eq(202)
expect(job.reload.trace.raw).to eq 'BUILD TRACE appended appended'
end
context 'when job is cancelled' do
before do
job.cancel
end
context 'when trace is patched' do
before do
patch_the_trace
end
it 'returns Forbidden ' do
expect(response.status).to eq(403)
end
end
end
context 'when redis data are flushed' do
before do
redis_shared_state_cleanup!
end
it 'has empty trace' do
expect(job.reload.trace.raw).to eq ''
end
context 'when we perform partial patch' do
before do
patch_the_trace('hello', headers.merge({ 'Content-Range' => "28-32/5" }))
end
it 'returns an error' do
expect(response.status).to eq(416)
expect(response.header['Range']).to eq('0-0')
end
end
context 'when we resend full trace' do
before do
patch_the_trace('BUILD TRACE appended appended hello', headers.merge({ 'Content-Range' => "0-34/35" }))
end
it 'succeeds with updating trace' do
expect(response.status).to eq(202)
expect(job.reload.trace.raw).to eq 'BUILD TRACE appended appended hello'
end
end
end
end
context 'when concurrent update of trace is happening' do
before do
job.trace.write('wb') do
patch_the_trace
end
end
it 'returns that operation conflicts' do
expect(response.status).to eq(409)
end
end
context 'when the job is canceled' do
before do
job.cancel
patch_the_trace
end
it 'receives status in header' do
expect(response.header['Job-Status']).to eq 'canceled'
end
end
end
context 'when Runner makes a force-patch' do
before do
force_patch_the_trace
end
it 'gets correct response' do
expect(response.status).to eq 202
expect(job.reload.trace.raw).to eq 'BUILD TRACE appended'
expect(response.header).to have_key 'Range'
expect(response.header).to have_key 'Job-Status'
end
end
context 'when content-range start is too big' do
let(:headers_with_range) { headers.merge({ 'Content-Range' => '15-20/6' }) }
it 'gets 416 error response with range headers' do
expect(response.status).to eq 416
expect(response.header).to have_key 'Range'
expect(response.header['Range']).to eq '0-11'
end
end
context 'when content-range start is too small' do
let(:headers_with_range) { headers.merge({ 'Content-Range' => '8-20/13' }) }
it 'gets 416 error response with range headers' do
expect(response.status).to eq 416
expect(response.header).to have_key 'Range'
expect(response.header['Range']).to eq '0-11'
end
end
context 'when Content-Range header is missing' do
let(:headers_with_range) { headers }
it { expect(response.status).to eq 400 }
end
context 'when job has been errased' do
let(:job) { create(:ci_build, runner_id: runner.id, erased_at: Time.now) }
it { expect(response.status).to eq 403 }
end
def patch_the_trace(content = ' appended', request_headers = nil)
unless request_headers
job.trace.read do |stream|
offset = stream.size
limit = offset + content.length - 1
request_headers = headers.merge({ 'Content-Range' => "#{offset}-#{limit}" })
end
end
Timecop.travel(job.updated_at + update_interval) do
patch api("/jobs/#{job.id}/trace"), params: content, headers: request_headers
job.reload
end
end
def initial_patch_the_trace
patch_the_trace(' appended', headers_with_range)
end
def force_patch_the_trace
2.times { patch_the_trace('') }
end
end
describe 'artifacts' do
let(:job) { create(:ci_build, :pending, pipeline: pipeline, runner_id: runner.id) }
let(:jwt_token) { JWT.encode({ 'iss' => 'gitlab-workhorse' }, Gitlab::Workhorse.secret, 'HS256') }
let(:headers) { { 'GitLab-Workhorse' => '1.0', Gitlab::Workhorse::INTERNAL_API_REQUEST_HEADER => jwt_token } }
let(:headers_with_token) { headers.merge(API::Helpers::Runner::JOB_TOKEN_HEADER => job.token) }
let(:file_upload) { fixture_file_upload('spec/fixtures/banana_sample.gif', 'image/gif') }
let(:file_upload2) { fixture_file_upload('spec/fixtures/dk.png', 'image/gif') }
before do
stub_artifacts_object_storage
job.run!
end
describe 'POST /api/v4/jobs/:id/artifacts/authorize' do
context 'when using token as parameter' do
context 'posting artifacts to running job' do
subject do
authorize_artifacts_with_token_in_params
end
shared_examples 'authorizes local file' do
it 'succeeds' do
subject
expect(response).to have_gitlab_http_status(200)
expect(response.content_type.to_s).to eq(Gitlab::Workhorse::INTERNAL_API_CONTENT_TYPE)
expect(json_response['TempPath']).to eq(JobArtifactUploader.workhorse_local_upload_path)
expect(json_response['RemoteObject']).to be_nil
end
end
context 'when using local storage' do
it_behaves_like 'authorizes local file'
end
context 'when using remote storage' do
context 'when direct upload is enabled' do
before do
stub_artifacts_object_storage(enabled: true, direct_upload: true)
end
it 'succeeds' do
subject
expect(response).to have_gitlab_http_status(200)
expect(response.content_type.to_s).to eq(Gitlab::Workhorse::INTERNAL_API_CONTENT_TYPE)
expect(json_response).not_to have_key('TempPath')
expect(json_response['RemoteObject']).to have_key('ID')
expect(json_response['RemoteObject']).to have_key('GetURL')
expect(json_response['RemoteObject']).to have_key('StoreURL')
expect(json_response['RemoteObject']).to have_key('DeleteURL')
expect(json_response['RemoteObject']).to have_key('MultipartUpload')
end
end
context 'when direct upload is disabled' do
before do
stub_artifacts_object_storage(enabled: true, direct_upload: false)
end
it_behaves_like 'authorizes local file'
end
end
end
context 'when artifact is too large' do
let(:sample_max_size) { 100 }
shared_examples_for 'rejecting too large artifacts' do
it 'fails to post' do
authorize_artifacts_with_token_in_params(filesize: sample_max_size.megabytes.to_i)
expect(response).to have_gitlab_http_status(413)
end
end
context 'based on application setting' do
before do
stub_application_setting(max_artifacts_size: sample_max_size)
end
it_behaves_like 'rejecting too large artifacts'
end
context 'based on root namespace setting' do
before do
stub_application_setting(max_artifacts_size: 200)
root_namespace.update!(max_artifacts_size: sample_max_size)
end
it_behaves_like 'rejecting too large artifacts'
end
context 'based on child namespace setting' do
before do
stub_application_setting(max_artifacts_size: 200)
root_namespace.update!(max_artifacts_size: 200)
namespace.update!(max_artifacts_size: sample_max_size)
end
it_behaves_like 'rejecting too large artifacts'
end
context 'based on project setting' do
before do
stub_application_setting(max_artifacts_size: 200)
root_namespace.update!(max_artifacts_size: 200)
namespace.update!(max_artifacts_size: 200)
project.update!(max_artifacts_size: sample_max_size)
end
it_behaves_like 'rejecting too large artifacts'
end
end
end
context 'when using token as header' do
it 'authorizes posting artifacts to running job' do
authorize_artifacts_with_token_in_headers
expect(response).to have_gitlab_http_status(200)
expect(response.content_type.to_s).to eq(Gitlab::Workhorse::INTERNAL_API_CONTENT_TYPE)
expect(json_response['TempPath']).not_to be_nil
end
it 'fails to post too large artifact' do
stub_application_setting(max_artifacts_size: 0)
authorize_artifacts_with_token_in_headers(filesize: 100)
expect(response).to have_gitlab_http_status(413)
end
end
context 'when using runners token' do
it 'fails to authorize artifacts posting' do
authorize_artifacts(token: job.project.runners_token)
expect(response).to have_gitlab_http_status(403)
end
end
it 'reject requests that did not go through gitlab-workhorse' do
headers.delete(Gitlab::Workhorse::INTERNAL_API_REQUEST_HEADER)
authorize_artifacts
expect(response).to have_gitlab_http_status(500)
end
context 'authorization token is invalid' do
it 'responds with forbidden' do
authorize_artifacts(token: 'invalid', filesize: 100 )
expect(response).to have_gitlab_http_status(403)
end
end
def authorize_artifacts(params = {}, request_headers = headers)
post api("/jobs/#{job.id}/artifacts/authorize"), params: params, headers: request_headers
end
def authorize_artifacts_with_token_in_params(params = {}, request_headers = headers)
params = params.merge(token: job.token)
authorize_artifacts(params, request_headers)
end
def authorize_artifacts_with_token_in_headers(params = {}, request_headers = headers_with_token)
authorize_artifacts(params, request_headers)
end
end
describe 'POST /api/v4/jobs/:id/artifacts' do
context 'when artifacts are being stored inside of tmp path' do
before do
# by configuring this path we allow to pass temp file from any path
allow(JobArtifactUploader).to receive(:workhorse_upload_path).and_return('/')
end
context 'when job has been erased' do
let(:job) { create(:ci_build, erased_at: Time.now) }
before do
upload_artifacts(file_upload, headers_with_token)
end
it 'responds with forbidden' do
upload_artifacts(file_upload, headers_with_token)
expect(response).to have_gitlab_http_status(403)
end
end
context 'when job is running' do
shared_examples 'successful artifacts upload' do
it 'updates successfully' do
expect(response).to have_gitlab_http_status(201)
end
end
context 'when uses accelerated file post' do
context 'for file stored locally' do
before do
upload_artifacts(file_upload, headers_with_token)
end
it_behaves_like 'successful artifacts upload'
end
context 'for file stored remotelly' do
let!(:fog_connection) do
stub_artifacts_object_storage(direct_upload: true)
end
let(:object) do
fog_connection.directories.new(key: 'artifacts').files.create(
key: 'tmp/uploads/12312300',
body: 'content'
)
end
let(:file_upload) { fog_to_uploaded_file(object) }
before do
upload_artifacts(file_upload, headers_with_token, 'file.remote_id' => remote_id)
end
context 'when valid remote_id is used' do
let(:remote_id) { '12312300' }
it_behaves_like 'successful artifacts upload'
end
context 'when invalid remote_id is used' do
let(:remote_id) { 'invalid id' }
it 'responds with bad request' do
expect(response).to have_gitlab_http_status(500)
expect(json_response['message']).to eq("Missing file")
end
end
end
end
context 'when using runners token' do
it 'responds with forbidden' do
upload_artifacts(file_upload, headers.merge(API::Helpers::Runner::JOB_TOKEN_HEADER => job.project.runners_token))
expect(response).to have_gitlab_http_status(403)
end
end
end
context 'when artifacts file is too large' do
it 'fails to post too large artifact' do
stub_application_setting(max_artifacts_size: 0)
upload_artifacts(file_upload, headers_with_token)
expect(response).to have_gitlab_http_status(413)
end
end
context 'when artifacts post request does not contain file' do
it 'fails to post artifacts without file' do
post api("/jobs/#{job.id}/artifacts"), params: {}, headers: headers_with_token
expect(response).to have_gitlab_http_status(400)
end
end
context 'GitLab Workhorse is not configured' do
it 'fails to post artifacts without GitLab-Workhorse' do
post api("/jobs/#{job.id}/artifacts"), params: { token: job.token }, headers: {}
expect(response).to have_gitlab_http_status(403)
end
end
context 'when setting an expire date' do
let(:default_artifacts_expire_in) {}
let(:post_data) do
{ 'file.path' => file_upload.path,
'file.name' => file_upload.original_filename,
'expire_in' => expire_in }
end
before do
stub_application_setting(default_artifacts_expire_in: default_artifacts_expire_in)
post(api("/jobs/#{job.id}/artifacts"), params: post_data, headers: headers_with_token)
end
context 'when an expire_in is given' do
let(:expire_in) { '7 days' }
it 'updates when specified' do
expect(response).to have_gitlab_http_status(201)
expect(job.reload.artifacts_expire_at).to be_within(5.minutes).of(7.days.from_now)
end
end
context 'when no expire_in is given' do
let(:expire_in) { nil }
it 'ignores if not specified' do
expect(response).to have_gitlab_http_status(201)
expect(job.reload.artifacts_expire_at).to be_nil
end
context 'with application default' do
context 'when default is 5 days' do
let(:default_artifacts_expire_in) { '5 days' }
it 'sets to application default' do
expect(response).to have_gitlab_http_status(201)
expect(job.reload.artifacts_expire_at).to be_within(5.minutes).of(5.days.from_now)
end
end
context 'when default is 0' do
let(:default_artifacts_expire_in) { '0' }
it 'does not set expire_in' do
expect(response).to have_gitlab_http_status(201)
expect(job.reload.artifacts_expire_at).to be_nil
end
end
end
end
end
context 'posts artifacts file and metadata file' do
let!(:artifacts) { file_upload }
let!(:artifacts_sha256) { Digest::SHA256.file(artifacts.path).hexdigest }
let!(:metadata) { file_upload2 }
let!(:metadata_sha256) { Digest::SHA256.file(metadata.path).hexdigest }
let(:stored_artifacts_file) { job.reload.artifacts_file }
let(:stored_metadata_file) { job.reload.artifacts_metadata }
let(:stored_artifacts_size) { job.reload.artifacts_size }
let(:stored_artifacts_sha256) { job.reload.job_artifacts_archive.file_sha256 }
let(:stored_metadata_sha256) { job.reload.job_artifacts_metadata.file_sha256 }
before do
post(api("/jobs/#{job.id}/artifacts"), params: post_data, headers: headers_with_token)
end
context 'when posts data accelerated by workhorse is correct' do
let(:post_data) do
{ 'file.path' => artifacts.path,
'file.name' => artifacts.original_filename,
'file.sha256' => artifacts_sha256,
'metadata.path' => metadata.path,
'metadata.name' => metadata.original_filename,
'metadata.sha256' => metadata_sha256 }
end
it 'stores artifacts and artifacts metadata' do
expect(response).to have_gitlab_http_status(201)
expect(stored_artifacts_file.filename).to eq(artifacts.original_filename)
expect(stored_metadata_file.filename).to eq(metadata.original_filename)
expect(stored_artifacts_size).to eq(artifacts.size)
expect(stored_artifacts_sha256).to eq(artifacts_sha256)
expect(stored_metadata_sha256).to eq(metadata_sha256)
end
end
context 'when there is no artifacts file in post data' do
let(:post_data) do
{ 'metadata' => metadata }
end
it 'is expected to respond with bad request' do
expect(response).to have_gitlab_http_status(400)
end
it 'does not store metadata' do
expect(stored_metadata_file).to be_nil
end
end
end
context 'when artifact_type is archive' do
context 'when artifact_format is zip' do
let(:params) { { artifact_type: :archive, artifact_format: :zip } }
it 'stores junit test report' do
upload_artifacts(file_upload, headers_with_token, params)
expect(response).to have_gitlab_http_status(201)
expect(job.reload.job_artifacts_archive).not_to be_nil
end
end
context 'when artifact_format is gzip' do
let(:params) { { artifact_type: :archive, artifact_format: :gzip } }
it 'returns an error' do
upload_artifacts(file_upload, headers_with_token, params)
expect(response).to have_gitlab_http_status(400)
expect(job.reload.job_artifacts_archive).to be_nil
end
end
end
context 'when artifact_type is junit' do
context 'when artifact_format is gzip' do
let(:file_upload) { fixture_file_upload('spec/fixtures/junit/junit.xml.gz') }
let(:params) { { artifact_type: :junit, artifact_format: :gzip } }
it 'stores junit test report' do
upload_artifacts(file_upload, headers_with_token, params)
expect(response).to have_gitlab_http_status(201)
expect(job.reload.job_artifacts_junit).not_to be_nil
end
end
context 'when artifact_format is raw' do
let(:file_upload) { fixture_file_upload('spec/fixtures/junit/junit.xml.gz') }
let(:params) { { artifact_type: :junit, artifact_format: :raw } }
it 'returns an error' do
upload_artifacts(file_upload, headers_with_token, params)
expect(response).to have_gitlab_http_status(400)
expect(job.reload.job_artifacts_junit).to be_nil
end
end
end
end
context 'when artifacts are being stored outside of tmp path' do
let(:new_tmpdir) { Dir.mktmpdir }
before do
# init before overwriting tmp dir
file_upload
# by configuring this path we allow to pass file from @tmpdir only
# but all temporary files are stored in system tmp directory
allow(Dir).to receive(:tmpdir).and_return(new_tmpdir)
end
after do
FileUtils.remove_entry(new_tmpdir)
end
it' "fails to post artifacts for outside of tmp path"' do
upload_artifacts(file_upload, headers_with_token)
expect(response).to have_gitlab_http_status(400)
end
end
def upload_artifacts(file, headers = {}, params = {})
workhorse_finalize(
api("/jobs/#{job.id}/artifacts"),
method: :post,
file_key: :file,
params: params.merge(file: file),
headers: headers
)
end
end
describe 'GET /api/v4/jobs/:id/artifacts' do
let(:token) { job.token }
context 'when job has artifacts' do
let(:job) { create(:ci_build) }
let(:store) { JobArtifactUploader::Store::LOCAL }
before do
create(:ci_job_artifact, :archive, file_store: store, job: job)
end
context 'when using job token' do
context 'when artifacts are stored locally' do
let(:download_headers) do
{ 'Content-Transfer-Encoding' => 'binary',
'Content-Disposition' => %q(attachment; filename="ci_build_artifacts.zip"; filename*=UTF-8''ci_build_artifacts.zip) }
end
before do
download_artifact
end
it 'download artifacts' do
expect(response).to have_gitlab_http_status(200)
expect(response.headers.to_h).to include download_headers
end
end
context 'when artifacts are stored remotely' do
let(:store) { JobArtifactUploader::Store::REMOTE }
let!(:job) { create(:ci_build) }
context 'when proxy download is being used' do
before do
download_artifact(direct_download: false)
end
it 'uses workhorse send-url' do
expect(response).to have_gitlab_http_status(200)
expect(response.headers.to_h).to include(
'Gitlab-Workhorse-Send-Data' => /send-url:/)
end
end
context 'when direct download is being used' do
before do
download_artifact(direct_download: true)
end
it 'receive redirect for downloading artifacts' do
expect(response).to have_gitlab_http_status(302)
expect(response.headers).to include('Location')
end
end
end
end
context 'when using runnners token' do
let(:token) { job.project.runners_token }
before do
download_artifact
end
it 'responds with forbidden' do
expect(response).to have_gitlab_http_status(403)
end
end
end
context 'when job does not has artifacts' do
it 'responds with not found' do
download_artifact
expect(response).to have_gitlab_http_status(404)
end
end
def download_artifact(params = {}, request_headers = headers)
params = params.merge(token: token)
job.reload
get api("/jobs/#{job.id}/artifacts"), params: params, headers: request_headers
end
end
end
end
end
| 35.95076 | 154 | 0.555311 |
bb9874d64d9c7b03ff1dc03a6862b610f9f89fd3 | 2,168 | require "spec_helper"
require "cc/engine/analyzers/file_thread_pool"
RSpec.describe CC::Engine::Analyzers::FileThreadPool do
describe "#run" do
let(:thread) { Thread.new {} }
it "uses default count of threads when concurrency is not specified" do
allow(Thread).to receive(:new).and_return(thread)
pool = CC::Engine::Analyzers::FileThreadPool.new([])
pool.run {}
expect(Thread).to have_received(:new).exactly(
CC::Engine::Analyzers::FileThreadPool::DEFAULT_CONCURRENCY,
).times
end
it "uses default concurrency when concurrency is over max" do
allow(Thread).to receive(:new).and_return(thread)
run_pool_with_concurrency(
CC::Engine::Analyzers::FileThreadPool::DEFAULT_CONCURRENCY + 2,
)
expect(Thread).to have_received(:new).exactly(
CC::Engine::Analyzers::FileThreadPool::DEFAULT_CONCURRENCY,
).times
end
it "uses default concucurrency when concucurrency is under 1" do
allow(Thread).to receive(:new).and_return(thread)
run_pool_with_concurrency(-2)
expect(Thread).to have_received(:new).exactly(
CC::Engine::Analyzers::FileThreadPool::DEFAULT_CONCURRENCY,
).times
end
it "uses supplied concurrency when valid" do
allow(Thread).to receive(:new).and_return(thread)
run_pool_with_concurrency(1)
expect(Thread).to have_received(:new).exactly(1).times
end
it "calls block for each file" do
pool = CC::Engine::Analyzers::FileThreadPool.new(["abc", "123", "xyz"])
results = []
pool.run do |f|
results.push f.reverse
end
pool.join
expect(results).to include("cba")
expect(results).to include("321")
expect(results).to include("zyx")
end
it "aborts on a thread exception" do
allow(Thread).to receive(:new).and_return(thread)
run_pool_with_concurrency(1)
expect(thread.abort_on_exception).to eq(true)
end
end
def run_pool_with_concurrency(concurrency)
pool = CC::Engine::Analyzers::FileThreadPool.new(
[],
concurrency: concurrency,
)
pool.run {}
end
end
| 27.443038 | 77 | 0.663284 |
38111ad7068c0020a3ee3ea56f5d38db6287b067 | 2,849 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2021_09_13_115814) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "comments", force: :cascade do |t|
t.integer "user_id"
t.integer "post_id"
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["post_id"], name: "index_comments_on_post_id"
t.index ["user_id"], name: "index_comments_on_user_id"
end
create_table "friendships", force: :cascade do |t|
t.bigint "invitation_sender_id", null: false
t.bigint "invitation_receiver_id", null: false
t.boolean "status", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["invitation_receiver_id"], name: "index_friendships_on_invitation_receiver_id"
t.index ["invitation_sender_id"], name: "index_friendships_on_invitation_sender_id"
end
create_table "likes", force: :cascade do |t|
t.integer "post_id"
t.integer "user_id"
t.index ["post_id"], name: "index_likes_on_post_id"
t.index ["user_id"], name: "index_likes_on_user_id"
end
create_table "posts", force: :cascade do |t|
t.integer "user_id"
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_posts_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name"
t.string "gravatar_url"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "friendships", "users", column: "invitation_receiver_id"
add_foreign_key "friendships", "users", column: "invitation_sender_id"
end
| 40.7 | 95 | 0.732538 |
ffcec183825afd0c4dd974e04de01752bc77062b | 1,178 | # -*- encoding : utf-8 -*-
# Public: This is a simple matcher for matching text in the handler of a delayed job,
# this is good enough in most cases to detect if a particuluar job was queued
#
# expected_job_text - Name of method or custom job handled asyncronously
#
# Examples
#
# expect { subscription.cancel! }.to create_delayed_job_with(:MyJob)
#
# Returns true or error message on failure
RSpec::Matchers.define(:create_delayed_job_with) do |expected_job_symbol|
supports_block_expectations
match do |actual_block|
actual_block.call
Delayed::Job.any? {|job| job.handler =~ /#{expected_job_symbol.to_s}/}
end
failure_message do |actual|
"Expected the given action to create a delayed job with content: '#{expected_job_symbol.to_s}' but got: \n\n#{organize_array_output(Delayed::Job.all)}"
end
failure_message_when_negated do |actual|
"Expected the given action to not create a delayed job with content: '#{expected_job_symbol.to_s}' but got: \n\n#{organize_array_output(Delayed::Job.all)}"
end
def organize_array_output(arr)
arr.map {|i| i.inspect}.join("\n\n")
end
def supports_block_expectations?
true
end
end
| 32.722222 | 159 | 0.734295 |
91e9da207b7239605460e076114ea0b2af2c7cda | 2,264 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2015 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See doc/COPYRIGHT.rdoc for more details.
#++
FactoryGirl.define do
factory :type do
sequence(:position) { |p| p }
name { |a| "Type No. #{a.position}" }
created_at { Time.now }
updated_at { Time.now }
factory :type_with_workflow, class: Type do
callback(:after_build) do |t|
t.workflows = [FactoryGirl.build(:workflow_with_default_status)]
end
end
end
factory :type_standard, class: Type do
name 'None'
is_standard true
is_default true
created_at { Time.now }
updated_at { Time.now }
end
factory :type_bug, class: Type do
name 'Bug'
position 1
created_at { Time.now }
updated_at { Time.now }
# reuse existing type with the given name
# this prevents a validation error (name has to be unique)
initialize_with { Type.find_or_create_by_name(name) }
factory :type_feature do
name 'Feature'
position 2
is_default true
end
factory :type_support do
name 'Support'
position 3
end
factory :type_task do
name 'Task'
position 4
end
end
end
| 29.025641 | 91 | 0.70318 |
1ca18c42c86db705e2908448d539581ba16095ec | 1,240 | Dir[File.join(__dir__, '../../app/validators', '*.rb')].sort.each { |file| require file }
Apipie.configure do |config|
config.app_name = 'LegalFrameworkApi'
config.api_base_url = '/'
config.doc_base_url = '/apidocs'
# where is your API defined?
config.api_controllers_matcher = Rails.root.join('app/controllers/**/*.rb')
config.translate = false
config.validate = true
config.app_info = <<~END_OF_TEXT
== Legal Framework API
#{' '}
= Overview
This API is used by Apply to be the single source of truth for all things concerning the#{' '}
legal framework, i.e. Matter types, Proceeding types, Scope limitations, merits tasks.
#{' '}
Currently, only one endpoint has been implemented: /merits_tasks (see below)
#{' '}
== Usage
#{' '}
#{' '}
POST /merits_task
#{' '}
The payload to this endpoint includes an array of ccms_codes for the proceeding types in
an application. The response details all the merits tasks that are required at an application level,
and for each proceeding type.
#{' '}
END_OF_TEXT
end
| 40 | 113 | 0.594355 |
f833316aff2a24d5058172c31bfdcb609d124852 | 2,150 | #############################################################################################
# #
# Copyright 2010-2013 Ning, Inc. #
# Copyright 2014 Groupon, Inc. #
# Copyright 2014 The Billing Project, LLC #
# #
# The Billing Project licenses this file to you under the Apache License, version 2.0 #
# (the "License"); you may not use this file except in compliance with the #
# License. You may obtain a copy of the License at: #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT #
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the #
# License for the specific language governing permissions and limitations #
# under the License. #
# #
#############################################################################################
#
# DO NOT EDIT!!!
# File automatically generated by killbill-java-parser ([email protected]:killbill/killbill-java-parser.git)
#
module KillBillClient
module Model
class SubscriptionUsageRecordAttributes < Resource
attribute :subscription_id
attribute :tracking_id
attribute :unit_usage_records
end
end
end
| 58.108108 | 108 | 0.362326 |
1d91e5b0480f8fbfb56d575f8b2d4a6820793e06 | 808 | # frozen_string_literal: true
require 'rbnacl'
class Threema
module E2e
module PublicKey
class << self
def encrypt(data:, private_key:, public_key:, nonce:)
box(public_key, private_key).encrypt(nonce, data)
end
def decrypt(data:, private_key:, public_key:, nonce:)
box(public_key, private_key).decrypt(nonce, data)
end
private
def box(public_key, private_key)
public_key_instance = RbNaCl::Boxes::Curve25519XSalsa20Poly1305::PublicKey.new(Threema::Util.unhexify(public_key))
private_key_instance = RbNaCl::Boxes::Curve25519XSalsa20Poly1305::PrivateKey.new(Threema::Util.unhexify(private_key))
RbNaCl::Box.new(public_key_instance, private_key_instance)
end
end
end
end
end
| 28.857143 | 127 | 0.675743 |
3847c094b816c29100231120f21be53aea4e1b4b | 897 | require 'rails_helper'
module Chaskiq
RSpec.describe LinkRenamer, type: :model do
let(:html) { "<p><a href='http://google.com'></p>"}
let(:renamer){ Chaskiq::LinkRenamer }
it "will rename links" do
data = renamer.convert(html, "AAA")
expect(data).to include("AAA")
end
it "test_initialize_no_escape_attributes_option" do
html = "<html> <body>
<a id='google' href='http://google.com'>Google</a>
<a id='noescape' href='{{link_url}}'>Link</a>
</body> </html>"
[:nokogiri].each do |adapter|
pm = Premailer.new(html, :with_html_string => true, :adapter => adapter, :escape_url_attributes => false)
pm.to_inline_css
doc = pm.processed_doc
expect( doc.at('#google')['href']).to be == 'http://google.com'
expect(doc.at('#noescape')['href']).to be == '{{link_url}}'
end
end
end
end
| 28.03125 | 113 | 0.597547 |
18a63d9b6e61506c29d318a799532c20411479c0 | 1,159 | #
# Cookbook Name:: dokku
# Recipe:: install
#
# Copyright (c) 2015 Nick Charlton, MIT licensed.
include_recipe "dokku::_nginx"
include_recipe "openssl"
package "apt-transport-https"
docker_service "default" do
action %i[create start]
end
packagecloud_repo "dokku/dokku" do
type "deb"
end
execute "install-dokku-plugin-core-dependencies" do
command "dokku plugin:install-dependencies --core"
action :nothing
end
%w(herokuish sshcommand plugn dokku).each do |pkg|
execute "hold-dependency-#{pkg}" do
command "apt-mark hold #{pkg}"
action :nothing
end
execute "unhold-dependency-#{pkg}" do
command "apt-mark unhold #{pkg}"
action :nothing
end
package pkg do
version node["dokku"]["package"][pkg]["version"]
notifies :run, "execute[unhold-dependency-#{pkg}]", :immediately
if pkg == "dokku"
notifies :run,
"execute[install-dokku-plugin-core-dependencies]",
:immediately
end
notifies :run, "execute[hold-dependency-#{pkg}]", :immediately
end
end
file "/home/dokku/VHOST" do
content node["dokku"]["domain"] || node["fqdn"]
end
dokku_nginx_template "global"
| 20.696429 | 68 | 0.680759 |
4a1a0282ec77a88a6cc455975e7e4296de959f4d | 707 | module Projects
class CreateRepository < Base
unloadable
def call
create_project_repository
end
private
def create_project_repository
# Create new repository
repository = Repository.factory('Xitolite')
repository.is_default = true
repository.extra_info = {}
repository.extra_info['extra_report_last_commit'] = '1'
# Save it to database
project.repositories << repository
# Create it in Gitolite
Repositories::Create.call(repository, creation_options)
end
def creation_options
{ create_readme_file: RedmineGitHosting::Config.init_repositories_on_create? }
end
end
end
| 20.794118 | 86 | 0.66761 |
03d540892a7934797281bcdaca41c0697c5268c9 | 448 | require 'rails_helper'
# Specs in this file have access to a helper object that includes
# the StudentMcqsHelper. For example:
#
# describe StudentMcqsHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# expect(helper.concat_strings("this","that")).to eq("this that")
# end
# end
# end
RSpec.describe StudentMcqsHelper, type: :helper do
pending "add some examples to (or delete) #{__FILE__}"
end
| 28 | 71 | 0.716518 |
61e090a25527f081956917f2095ff299a1667879 | 326 | class CreateMembershipTransactionDetails < ActiveRecord::Migration
def change
create_table :membership_transaction_details do |t|
t.integer :club_membership_detail_id
t.integer :end_user_id
t.integer :payment_status, default: 0
t.string :payu_id
t.timestamps null: false
end
end
end
| 25.076923 | 66 | 0.733129 |
035ce9bb01971cf9947c6c421fd24a98a8eaa88e | 2,936 | # Copyright (c) 2011, salesforce.com, inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided
# that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this list of conditions and the
# following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
# the following disclaimer in the documentation and/or other materials provided with the distribution.
#
# Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
# promote products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
CanvasRuby::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Configure static asset server for tests with Cache-Control for performance
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
# Log error messages when you accidentally call methods on nil
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
end
| 49.762712 | 108 | 0.78406 |
21abbe58fd3771934dc504c03cda517c0509f774 | 206 | module Lib
module Objects
class Base < GraphQL::Schema::Object
edge_type_class(Lib::BaseEdge)
connection_type_class(Lib::BaseConnection)
field_class Lib::BaseField
end
end
end
| 20.6 | 48 | 0.708738 |
7a8fa16b7bc77cc10a285828f003b02fd27023dc | 961 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_06_26_163206) do
create_table "pets", force: :cascade do |t|
t.string "name"
t.string "tag"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| 41.782609 | 86 | 0.766909 |
1d78587041afa9e31e7e5926e00da97af7d9ed92 | 381 | require_relative 'weather'
require_relative 'forecast'
require 'optparse'
options = {}
parser = OptionParser.new do|opts|
opts.on('-c', '--city city', 'City') do |city|
options[:city] = city;
end
end
parser.parse!
forecasts = Weather.for("Kathmandu")
forecasts.each do |forecast|
puts "#{forecast.datetime} -- #{forecast.temp} Celsius: #{forecast.description}"
end | 20.052632 | 84 | 0.695538 |
bf82b58f0a42978e00bf815ec237f3b0cbbe6e8b | 4,393 | module Spree
module Admin
class CompaniesController < ResourceController
def index
@search = Spree::Company.ransack(params[:q])
@companies = @search.result.order('name ASC').page(params[:page])
respond_with(:admin, @companies)
end
def new
@company = Spree::Company.new
@bill_address = Spree::Address.new(addr_type: 'billing')
end
def show
redirect_to edit_admin_company_path(@company)
end
def new
@company = Spree::Company.new
render :new
end
def create
@company = Spree::Company.new
@company.attributes = company_params
@bill_address = @company.build_bill_address(addr_type: 'billing')
if @company.save
flash.now[:success] = flash_message_for(@company, :successfully_created)
redirect_to edit_admin_company_path(@company)
else
render :new
end
end
def reset_email_templates
@company = Spree::Company.find(params[:company_id])
overwrite = false
if @company.setup_email_templates(overwrite)
flash.now[:success] = "Email templates reset"
else
flash.now[:error] = "Something went wrong"
end
render :edit
end
def setup_email_templates
@company = Spree::Company.find(params[:company_id])
overwrite = true
if @company.setup_email_templates(overwrite)
flash.now[:success] = "Email templates set up"
else
flash.now[:error] = "Something went wrong"
end
render :edit
end
def update
if @company.update(company_params)
flash[:success] = Spree.t(:account_updated)
redirect_to edit_admin_company_path(@company)
else
flash.now[:errors] = @company.errors.full_messages
render :edit
end
end
def load_default_data
@company = Spree::Company.friendly.find(params[:id])
params[:sample_data_options] ||= {}
@company.load_default_data(params[:sample_data_options])
flash[:success] = 'Sample data will be loaded shortly.'
redirect_to :back
end
def load_sample_data
@company = Spree::Company.friendly.find(params[:id])
params[:sample_data_options] ||= {}
@company.load_sample_data(params[:sample_data_options])
flash[:success] = 'Sample data will be loaded shortly.'
redirect_to :back
end
def customer_accounts
@company = Spree::Company.friendly.find(params[:id])
@accounts = @company.customer_accounts
.includes(:customer)
.order(:fully_qualified_name)
@account_type = 'customer'
render :accounts
end
def vendor_accounts
@company = Spree::Company.friendly.find(params[:id])
@accounts = @company.vendor_accounts
.includes(:vendor)
.order(:fully_qualified_name)
@account_type = 'vendor'
render :accounts
end
def users
@company = Spree::Company.friendly.find(params[:id])
@users = @company.users
end
def reset_inventory
@company = Spree::Company.friendly.find(params[:id])
@company.reset_inventory!
flash[:success] = 'Inventory has been reset.'
redirect_to :back
end
protected
private
def company_params
params.require(:company).permit(
:name,
:email,
:order_cutoff_time,
:currency,
:slug,
:time_zone,
:allow_variants,
:member,
:subscription,
:custom_domain,
:hide_empty_orders,
:use_price_lists,
:only_price_list_pricing,
:set_visibility_by_price_list,
:use_variant_text_options,
bill_address_attributes:
[ :id, :firstname, :lastname, :company, :phone,
:address1, :address2, :city, :country_id, :state_name, :zipcode, :state_id
],
ship_address_attributes:
[ :id, :firstname, :lastname, :company, :phone,
:address1, :address2, :city, :country_id, :state_name, :zipcode, :state_id
]
)
end
end
end
end
| 28.525974 | 88 | 0.583201 |
79375a4fc5442082ccbe621b0bdb2da344a32464 | 1,493 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_01_23_215302) do
create_table "events", force: :cascade do |t|
t.datetime "event_date"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "creator_id"
t.string "desc"
end
create_table "user_events", force: :cascade do |t|
t.integer "user_id"
t.integer "event_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["event_id"], name: "index_user_events_on_event_id"
t.index ["user_id"], name: "index_user_events_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| 37.325 | 86 | 0.736772 |
334bf4876c116e81b54811d40a0147b77453b1f9 | 362 | class CreateTracks < ActiveRecord::Migration
def self.up
create_table :tracks do |t|
t.string :persistent_id
t.string :name
t.string :artist
t.string :album
t.float :duration
t.integer :rating
t.boolean :enabled, :default => true
t.timestamps
end
end
def self.down
drop_table :tracks
end
end
| 18.1 | 44 | 0.629834 |
1d05d968b0cd3473394da6daa3fdd8303fea8b9c | 708 | require 'date'
class Person
attr_reader :first_name, :last_name, :gender, :date_of_birth, :favorite_color
def initialize(args={})
@last_name = args.fetch(:last_name)
@first_name = args.fetch(:first_name)
@gender = standardize_gender(args.fetch(:gender))
@date_of_birth = date_to_datetime(args.fetch(:date_of_birth))
@favorite_color = args.fetch(:favorite_color)
end
def formatted_birthdate
@date_of_birth.strftime("%-m/%-d/%Y")
end
private
def standardize_gender(gender)
gender[0].downcase == "m" ? "Male" : "Female"
end
def date_to_datetime(date)
dates = date.gsub(/[-]/, "/").split("/")
DateTime.parse("#{dates[2]}/#{dates[0]}/#{dates[1]}")
end
end
| 22.83871 | 79 | 0.675141 |
7a3f7992fc19097d994804426aeb6ea95f9a82f2 | 8,614 | #
# Copyright:: Copyright (c) Chef Software Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require_relative "../resource"
require_relative "../dist"
require_relative "helpers/cron_validations"
require "digest/md5"
class Chef
class Resource
class ChefClientCron < Chef::Resource
unified_mode true
provides :chef_client_cron
description "Use the **chef_client_cron** resource to setup the #{Chef::Dist::PRODUCT} to run as a cron job. This resource will also create the specified log directory if it doesn't already exist."
introduced "16.0"
examples <<~DOC
**Setup #{Chef::Dist::PRODUCT} to run using the default 30 minute cadence**:
```ruby
chef_client_cron "Run #{Chef::Dist::PRODUCT} as a cron job"
```
**Run #{Chef::Dist::PRODUCT} twice a day**:
```ruby
chef_client_cron "Run #{Chef::Dist::PRODUCT} every 12 hours" do
minute 0
hour "0,12"
end
```
**Run #{Chef::Dist::PRODUCT} with extra options passed to the client**:
```ruby
chef_client_cron "Run an override recipe" do
daemon_options ["--override-runlist mycorp_base::default"]
end
```
DOC
extend Chef::ResourceHelpers::CronValidations
property :job_name, String,
default: Chef::Dist::CLIENT,
description: "The name of the cron job to create."
property :comment, String,
description: "A comment to place in the cron.d file."
property :user, String,
description: "The name of the user that #{Chef::Dist::PRODUCT} runs as.",
default: "root"
property :minute, [Integer, String],
description: "The minute at which #{Chef::Dist::PRODUCT} is to run (0 - 59) or a cron pattern such as '0,30'.",
default: "0,30", callbacks: {
"should be a valid minute spec" => method(:validate_minute),
}
property :hour, [Integer, String],
description: "The hour at which #{Chef::Dist::PRODUCT} is to run (0 - 23) or a cron pattern such as '0,12'.",
default: "*", callbacks: {
"should be a valid hour spec" => method(:validate_hour),
}
property :day, [Integer, String],
description: "The day of month at which #{Chef::Dist::PRODUCT} is to run (1 - 31) or a cron pattern such as '1,7,14,21,28'.",
default: "*", callbacks: {
"should be a valid day spec" => method(:validate_day),
}
property :month, [Integer, String],
description: "The month in the year on which #{Chef::Dist::PRODUCT} is to run (1 - 12, jan-dec, or *).",
default: "*", callbacks: {
"should be a valid month spec" => method(:validate_month),
}
property :weekday, [Integer, String],
description: "The day of the week on which #{Chef::Dist::PRODUCT} is to run (0-7, mon-sun, or *), where Sunday is both 0 and 7.",
default: "*", callbacks: {
"should be a valid weekday spec" => method(:validate_dow),
}
property :splay, [Integer, String],
default: 300,
coerce: proc { |x| Integer(x) },
callbacks: { "should be a positive number" => proc { |v| v > 0 } },
description: "A random number of seconds between 0 and X to add to interval so that all #{Chef::Dist::CLIENT} commands don't execute at the same time."
property :mailto, String,
description: "The e-mail address to e-mail any cron task failures to."
property :accept_chef_license, [true, false],
description: "Accept the Chef Online Master License and Services Agreement. See <https://www.chef.io/online-master-agreement/>",
default: false
property :config_directory, String,
default: Chef::Dist::CONF_DIR,
description: "The path of the config directory."
property :log_directory, String,
default: lazy { platform?("mac_os_x") ? "/Library/Logs/#{Chef::Dist::DIR_SUFFIX.capitalize}" : "/var/log/#{Chef::Dist::DIR_SUFFIX}" },
default_description: "/Library/Logs/#{Chef::Dist::DIR_SUFFIX.capitalize} on macOS and /var/log/#{Chef::Dist::DIR_SUFFIX} otherwise",
description: "The path of the directory to create the log file in."
property :log_file_name, String,
default: "client.log",
description: "The name of the log file to use."
property :append_log_file, [true, false],
default: true,
description: "Append to the log file instead of overwriting the log file on each run."
property :chef_binary_path, String,
default: "/opt/#{Chef::Dist::DIR_SUFFIX}/bin/#{Chef::Dist::CLIENT}",
description: "The path to the #{Chef::Dist::CLIENT} binary."
property :daemon_options, Array,
default: lazy { [] },
description: "An array of options to pass to the #{Chef::Dist::CLIENT} command."
property :environment, Hash,
default: lazy { {} },
description: "A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`."
action :add do
# TODO: Replace this with a :create_if_missing action on directory when that exists
unless ::Dir.exist?(new_resource.log_directory)
directory new_resource.log_directory do
owner new_resource.user
mode "0750"
recursive true
end
end
declare_resource(cron_resource_type, new_resource.job_name) do
minute new_resource.minute
hour new_resource.hour
day new_resource.day
weekday new_resource.weekday
month new_resource.month
environment new_resource.environment
mailto new_resource.mailto if new_resource.mailto
user new_resource.user
comment new_resource.comment if new_resource.comment
command cron_command
end
end
action :remove do
declare_resource(cron_resource_type, new_resource.job_name) do
action :delete
end
end
action_class do
#
# Generate a uniformly distributed unique number to sleep from 0 to the splay time
#
# @param [Integer] splay The number of seconds to splay
#
# @return [Integer]
#
def splay_sleep_time(splay)
seed = node["shard_seed"] || Digest::MD5.hexdigest(node.name).to_s.hex
random = Random.new(seed.to_i)
random.rand(splay)
end
#
# The complete cron command to run
#
# @return [String]
#
def cron_command
cmd = ""
cmd << "/bin/sleep #{splay_sleep_time(new_resource.splay)}; "
cmd << "#{new_resource.chef_binary_path} "
cmd << "#{new_resource.daemon_options.join(" ")} " unless new_resource.daemon_options.empty?
cmd << "-c #{::File.join(new_resource.config_directory, "client.rb")} "
cmd << "--chef-license accept " if new_resource.accept_chef_license
cmd << log_command
cmd << " || echo \"#{Chef::Dist::PRODUCT} execution failed\"" if new_resource.mailto
cmd
end
#
# The portion of the overall cron job that handles logging based on the append_log_file property
#
# @return [String]
#
def log_command
if new_resource.append_log_file
"-L #{::File.join(new_resource.log_directory, new_resource.log_file_name)}"
else
"> #{::File.join(new_resource.log_directory, new_resource.log_file_name)} 2>&1"
end
end
#
# The type of cron resource to run. Linux systems all support the /etc/cron.d directory
# and can use the cron_d resource, but Solaris / AIX / FreeBSD need to use the crontab
# via the legacy cron resource.
#
# @return [Symbol]
#
def cron_resource_type
linux? ? :cron_d : :cron
end
end
end
end
end
| 37.615721 | 203 | 0.618992 |
21196d85431e0f8763ceb57f8dd8ef48d84ba275 | 1,489 | cask "eloston-chromium" do
arch = Hardware::CPU.intel? ? "x86-64" : "arm64"
if Hardware::CPU.intel?
version "100.0.4896.88-1.1,1649847004"
sha256 "dc2ae76674b276d29325275b4481d2d4aad06085b61db0f58431c0037df581fe"
else
version "100.0.4896.88-1.1,1649890918"
sha256 "8feeafaaf33b18424fbf6f6723b290bbdeba2edc437d70e8ab6fb0a161260e8c"
end
url "https://github.com/kramred/ungoogled-chromium-macos/releases/download/#{version.csv.first}_#{arch}__#{version.csv.second}/ungoogled-chromium_#{version.csv.first}_#{arch}-macos.dmg",
verified: "github.com/kramred/ungoogled-chromium-macos/"
name "Ungoogled Chromium"
desc "Google Chromium, sans integration with Google"
homepage "https://ungoogled-software.github.io/ungoogled-chromium-binaries/"
livecheck do
url "https://github.com/kramred/ungoogled-chromium-macos/releases/"
strategy :page_match do |page|
match = page.match(%r{
releases/download/(\d+(?:[.-]\d+)+)[._-]#{arch}[._-]{2}(\d+)/
ungoogled[._-]chromium[._-](\d+(?:[.-]\d+)+)[._-]#{arch}[._-]macos\.dmg
}xi)
next if match.blank?
"#{match[1]},#{match[2]}"
end
end
conflicts_with cask: [
"chromium",
"freesmug-chromium",
]
app "Chromium.app"
zap trash: [
"~/Library/Application Support/Chromium",
"~/Library/Caches/Chromium",
"~/Library/Preferences/org.chromium.Chromium.plist",
"~/Library/Saved Application State/org.chromium.Chromium.savedState",
]
end
| 33.088889 | 188 | 0.680994 |
1d6fd856be1b41485b08071b33b6b03d549c54e5 | 1,408 | require_relative "../wrapper"
require_relative "../physical_volume_segment"
module LVM
module Wrapper
# segment output is very different in that its multi line, easier to treat as own command
class PVSSEG
include Reporting
attr_reader :attributes
attr_reader :command
def initialize(options)
@attributes = Attributes.load(options[:version], ATTRIBUTES_FILE)
@command = "#{options[:command]} #{Reporting.build_command(attributes, BASE_COMMAND, options[:additional_arguments])}"
end
BASE_COMMAND = "pvs #{Reporting::BASE_ARGUMENTS}"
ATTRIBUTES_FILE = "pvsseg.yaml"
def list
output = External.cmd(@command)
data = parse(output)
if block_given?
return data.each { |obj| yield obj }
else
return data
end
end
private
# Parses the output of self.command
def parse(output)
volumes = []
output.split("\n").each do |line|
args = process_line(attributes, line)
args[:finish] = args[:start] + args[:size]
# finally build our object
volume = PhysicalVolumeSegment.new(args)
if block_given?
yield volume
else
volumes << volume
end
end
volumes
end # parse
end # class PVSSEG
end # module Wrapper
end # module LVM
| 24.701754 | 126 | 0.603693 |
01000c9d6d92ec2a47ffbfb608adb3c7af3ce935 | 1,423 | # frozen_string_literal: true
module Gitlab
module ImportExport
module Project
class TreeSaver
attr_reader :full_path
def initialize(project:, current_user:, shared:, params: {})
@params = params
@project = project
@current_user = current_user
@shared = shared
@full_path = File.join(@shared.export_path, ImportExport.project_filename)
end
def save
json_writer = ImportExport::JSON::LegacyWriter.new(@full_path)
serializer = ImportExport::JSON::StreamingSerializer.new(exportable, reader.project_tree, json_writer)
serializer.execute
true
rescue => e
@shared.error(e)
false
ensure
json_writer&.close
end
private
def reader
@reader ||= Gitlab::ImportExport::Reader.new(shared: @shared)
end
def exportable
@project.present(exportable_params)
end
def exportable_params
params = {
presenter_class: presenter_class,
current_user: @current_user
}
params[:override_description] = @params[:description] if @params[:description].present?
params
end
def presenter_class
Projects::ImportExport::ProjectExportPresenter
end
end
end
end
end
| 24.964912 | 112 | 0.58468 |
39b5b4bf339777651ffb9486f76d6375931dcf12 | 1,300 | require 'beaker-rspec'
require 'beaker_spec_helper'
include BeakerSpecHelper
hosts.each do |host|
if host['platform'] =~ /^ubuntu-(15.04|15.10)-/
on host, "wget -O /tmp/puppet.deb http://apt.puppetlabs.com/puppetlabs-release-pc1-trusty.deb"
on host, "dpkg -i --force-all /tmp/puppet.deb"
on host, "apt-get update"
host.install_package('puppet-agent')
else
install_puppet_agent_on host, {}
end
# Install git so that we can install modules from github
if host['platform'] =~ /^el-5-/
# git is only available on EPEL for el-5
install_package host, 'epel-release'
end
install_package host, 'git'
on host, "puppet cert generate $(facter fqdn)"
end
RSpec.configure do |c|
# Project root
proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))
# Readable test descriptions
c.formatter = :documentation
# Configure all nodes in nodeset
c.before :suite do
# Install module and dependencies
puppet_module_install(:source => proj_root, :module_name => 'metasploit')
hosts.each do |host|
# dependencies
on host, puppet('module', 'install', 'puppetlabs-stdlib'), { :acceptable_exit_codes => [0,1] }
on host, puppet('module', 'install', 'eyp-eyplib'), { :acceptable_exit_codes => [0,1] }
end
end
end
| 28.888889 | 100 | 0.681538 |
bbf79d1fd9c368f770531d1a622cefd3c32f583d | 2,804 | class Pygitup < Formula
include Language::Python::Virtualenv
desc "Nicer 'git pull'"
homepage "https://github.com/msiemens/PyGitUp"
url "https://files.pythonhosted.org/packages/6a/e5/640afbc106bb4e836228977d9593227148b1f7ba365172bd160c4d315c66/git-up-2.0.2.tar.gz"
sha256 "ce1bc2285393145d0c287de271ecea9f5302b6103be92263077e4c4a1fcd58cb"
license "MIT"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "7e4a7970074265fa7855716aa4c4313ddcf91bf6a0dc76969dcac37e3b8e54af"
sha256 cellar: :any_skip_relocation, big_sur: "241451119588df0aedbcf3bfb4084a930a22644629ec2544554f17723cb40110"
sha256 cellar: :any_skip_relocation, catalina: "24d563dbed328cc4a3267b547e0f7d29d198a6ee17f246c7d5d3b5d0ac7378a3"
sha256 cellar: :any_skip_relocation, mojave: "99ea13e47193752b83c7ac7751d1ab44cc1c2b549c2b4662ce54cf9ac6fe4255"
sha256 cellar: :any_skip_relocation, x86_64_linux: "73f588950c094ae92b1bbc209f06a17ecdc85fc619494aceccded0dd5ed9f0e5" # linuxbrew-core
end
depends_on "[email protected]"
resource "click" do
url "https://files.pythonhosted.org/packages/27/6f/be940c8b1f1d69daceeb0032fee6c34d7bd70e3e649ccac0951500b4720e/click-7.1.2.tar.gz"
sha256 "d2b5255c7c6349bc1bd1e59e08cd12acbbd63ce649f2588755783aa94dfb6b1a"
end
resource "colorama" do
url "https://files.pythonhosted.org/packages/1f/bb/5d3246097ab77fa083a61bd8d3d527b7ae063c7d8e8671b1cf8c4ec10cbe/colorama-0.4.4.tar.gz"
sha256 "5941b2b48a20143d2267e95b1c2a7603ce057ee39fd88e7329b0c292aa16869b"
end
resource "gitdb" do
url "https://files.pythonhosted.org/packages/d1/05/eaf2ac564344030d8b3ce870b116d7bb559020163e80d9aa4a3d75f3e820/gitdb-4.0.5.tar.gz"
sha256 "c9e1f2d0db7ddb9a704c2a0217be31214e91a4fe1dea1efad19ae42ba0c285c9"
end
resource "GitPython" do
url "https://files.pythonhosted.org/packages/85/3d/ee9aa9c77a3c0e9074461d2d8da86c3564ed96abd28fa099dc3e05338a72/GitPython-3.1.11.tar.gz"
sha256 "befa4d101f91bad1b632df4308ec64555db684c360bd7d2130b4807d49ce86b8"
end
resource "smmap" do
url "https://files.pythonhosted.org/packages/75/fb/2f594e5364f9c986b2c89eb662fc6067292cb3df2b88ae31c939b9138bb9/smmap-3.0.4.tar.gz"
sha256 "9c98bbd1f9786d22f14b3d4126894d56befb835ec90cef151af566c7e19b5d24"
end
resource "termcolor" do
url "https://files.pythonhosted.org/packages/8a/48/a76be51647d0eb9f10e2a4511bf3ffb8cc1e6b14e9e4fab46173aa79f981/termcolor-1.1.0.tar.gz"
sha256 "1d6d69ce66211143803fbc56652b41d73b4a400a2891d7bf7a1cdf4c02de613b"
end
def install
virtualenv_install_with_resources
end
test do
ENV["LC_ALL"] = "en_US.UTF-8"
system "git", "clone", "https://github.com/Homebrew/install.git"
cd "install" do
assert_match "Fetching origin", shell_output("#{bin}/git-up")
end
end
end
| 45.225806 | 140 | 0.809558 |
ffb3211063354a16acc5447b87568d0d41d88256 | 31,842 | # encoding: UTF-8
require 'library_stdnums'
require 'lightly'
require 'uri'
require_relative 'cache_adapter'
require_relative 'cache_manager'
require_relative 'cache_map'
require_relative 'composite_cache_map'
require_relative 'electronic_access_link'
require_relative 'electronic_access_link_factory'
require_relative 'iiif_manifest_url_builder'
require_relative 'orangelight_url_builder'
module MARC
class Record
# Taken from pul-store marc.rb lib extension
# Shamelessly lifted from SolrMARC, with a few changes; no doubt there will
# be more.
@@THREE_OR_FOUR_DIGITS = /^(20|19|18|17|16|15|14|13|12|11|10|9|8|7|6|5|4|3|2|1)(\d{2})\.?$/
@@FOUR_DIGIT_PATTERN_BRACES = /^\[([12]\d{3})\??\]\.?$/
@@FOUR_DIGIT_PATTERN_ONE_BRACE = /^\[(20|19|18|17|16|15|14|13|12|11|10)(\d{2})/
@@FOUR_DIGIT_PATTERN_OTHER_1 = /^l(\d{3})/
@@FOUR_DIGIT_PATTERN_OTHER_2 = /^\[(20|19|18|17|16|15|14|13|12|11|10)\](\d{2})/
@@FOUR_DIGIT_PATTERN_OTHER_3 = /^\[?(20|19|18|17|16|15|14|13|12|11|10)(\d)[^\d]\]?/
@@FOUR_DIGIT_PATTERN_OTHER_4 = /i\.e\.\,? (20|19|18|17|16|15|14|13|12|11|10)(\d{2})/
@@FOUR_DIGIT_PATTERN_OTHER_5 = /^\[?(\d{2})\-\-\??\]?/
@@BC_DATE_PATTERN = /[0-9]+ [Bb]\.?[Cc]\.?/
def best_date
date = nil
if self['260']
if self['260']['c']
field_260c = self['260']['c']
case field_260c
when @@THREE_OR_FOUR_DIGITS
date = "#{$1}#{$2}"
when @@FOUR_DIGIT_PATTERN_BRACES
date = $1
when @@FOUR_DIGIT_PATTERN_ONE_BRACE
date = $1
when @@FOUR_DIGIT_PATTERN_OTHER_1
date = "1#{$1}"
when @@FOUR_DIGIT_PATTERN_OTHER_2
date = "#{$1}#{$2}"
when @@FOUR_DIGIT_PATTERN_OTHER_3
date = "#{$1}#{$2}0"
when @@FOUR_DIGIT_PATTERN_OTHER_4
date = "#{$1}#{$2}"
when @@FOUR_DIGIT_PATTERN_OTHER_5
date = "#{$1}00"
when @@BC_DATE_PATTERN
date = nil
end
end
end
date ||= self.date_from_008
end
def date_from_008
if self['008']
d = self['008'].value[7, 4]
d = d.gsub 'u', '0' unless d == 'uuuu'
d = d.gsub ' ', '0' unless d == ' '
d if d =~ /^[0-9]{4}$/
end
end
def end_date_from_008
if self['008']
d = self['008'].value[11, 4]
d = d.gsub 'u', '9' unless d == 'uuuu'
d = d.gsub ' ', '9' unless d == ' '
d if d =~ /^[0-9]{4}$/
end
end
def date_display
date = nil
if self['260']
date = self['260']['c'] if self['260']['c']
end
date ||= self.date_from_008
end
end
end
FALLBACK_STANDARD_NO = 'Other standard number'
def map_024_indicators_to_labels i
case i
when '0' then 'International Standard Recording Code'
when '1' then 'Universal Product Code'
when '2' then 'International Standard Music Number'
when '3' then 'International Article Number'
when '4' then 'Serial Item and Contribution Identifier'
when '7' then '$2'
else FALLBACK_STANDARD_NO
end
end
def indicator_label_246 i
case i
when '0' then 'Portion of title'
when '1' then 'Parallel title'
when '2' then 'Distinctive title'
when '3' then 'Other title'
when '4' then 'Cover title'
when '5' then 'Added title page title'
when '6' then 'Caption title'
when '7' then 'Running title'
when '8' then 'Spine title'
end
end
def subfield_specified_hash_key subfield_value, fallback
key = subfield_value.capitalize.gsub(/[[:punct:]]?$/, '')
key.empty? ? fallback : key
end
def standard_no_hash record
standard_no = {}
Traject::MarcExtractor.cached('024').collect_matching_lines(record) do |field, _spec, _extractor|
standard_label = map_024_indicators_to_labels(field.indicator1)
standard_number = nil
field.subfields.each do |s_field|
standard_number = s_field.value if s_field.code == 'a'
standard_label = subfield_specified_hash_key(s_field.value, FALLBACK_STANDARD_NO) if (s_field.code == '2') && (standard_label == '$2')
end
standard_label = FALLBACK_STANDARD_NO if standard_label == '$2'
standard_no[standard_label] ? standard_no[standard_label] << standard_number : standard_no[standard_label] = [standard_number] unless standard_number.nil?
end
standard_no
end
# Handles ISBNs, ISSNs, and OCLCs
# ISBN: 020a, 020z, 776z
# ISSN: 022a, 022l, 022y, 022z, 776x
# OCLC: 035a, 776w, 787w
# BIB: 776w, 787w (adds BIB prefix so Blacklight can detect whether to search id field)
def other_versions record
linked_nums = []
Traject::MarcExtractor.cached('020az:022alyz:035a:776wxz:787w').collect_matching_lines(record) do |field, _spec, _extractor|
field.subfields.each do |s_field|
linked_nums << StdNum::ISBN.normalize(s_field.value) if (field.tag == "020") || ((field.tag == "776") && (s_field.code == 'z'))
linked_nums << StdNum::ISSN.normalize(s_field.value) if (field.tag == "022") || ((field.tag == "776") && (s_field.code == 'x'))
linked_nums << oclc_normalize(s_field.value, prefix: true) if s_field.value.start_with?('(OCoLC)') && (field.tag == "035")
if ((field.tag == "776") && (s_field.code == 'w')) || ((field.tag == "787") && (s_field.code == 'w'))
linked_nums << oclc_normalize(s_field.value, prefix: true) if s_field.value.include?('(OCoLC)')
linked_nums << "BIB" + strip_non_numeric(s_field.value) unless s_field.value.include?('(')
logger.error "#{record['001']} - linked field formatting: #{s_field.value}" if s_field.value.include?('(') && !s_field.value.start_with?('(')
end
end
end
linked_nums.compact.uniq
end
# only includes values before $t
def process_names record
names = []
Traject::MarcExtractor.cached('100aqbcdk:110abcdfgkln:111abcdfgklnpq:700aqbcdk:710abcdfgkln:711abcdfgklnpq').collect_matching_lines(record) do |field, spec, extractor|
name = extractor.collect_subfields(field, spec).first
unless name.nil?
remove = ''
after_t = false
field.subfields.each do |s_field|
remove << " #{s_field.value}" if after_t && spec.includes_subfield_code?(s_field.code)
after_t = true if s_field.code == 't'
end
name = name.chomp(remove)
names << Traject::Macros::Marc21.trim_punctuation(name)
end
end
names.uniq
end
# only includes values before $t
def process_alt_script_names record
names = []
Traject::MarcExtractor.cached('100aqbcdk:110abcdfgkln:111abcdfgklnpq:700aqbcdk:710abcdfgkln:711abcdfgklnpq').collect_matching_lines(record) do |field, spec, extractor|
next unless field.tag == '880'
name = extractor.collect_subfields(field, spec).first
unless name.nil?
remove = ''
after_t = false
field.subfields.each do |s_field|
remove << " #{s_field.value}" if after_t && spec.includes_subfield_code?(s_field.code)
after_t = true if s_field.code == 't'
end
name = name.chomp(remove)
names << Traject::Macros::Marc21.trim_punctuation(name)
end
end
names.uniq
end
##
# Get hash of authors grouped by role
# @param [MARC::Record]
# @return [Hash]
def process_author_roles record
author_roles = {
'TRL' => 'translators',
'EDT' => 'editors',
'COM' => 'compilers',
'TRANSLATOR' => 'translators',
'EDITOR' => 'editors',
'COMPILER' => 'compilers'
}
names = {}
names['secondary_authors'] = []
names['translators'] = []
names['editors'] = []
names['compilers'] = []
Traject::MarcExtractor.cached('100a:110a:111a:700a:710a:711a').collect_matching_lines(record) do |field, spec, extractor|
name = extractor.collect_subfields(field, spec).first
unless name.nil?
name = Traject::Macros::Marc21.trim_punctuation(name)
# If name is from 1xx field, it is the primary author.
if /1../.match?(field.tag)
names['primary_author'] = name
else
relator = ""
field.subfields.each do |s_field|
# relator code (subfield 4)
if s_field.code == '4'
relator = s_field.value.upcase.gsub(/[[:punct:]]?$/, '')
# relator term (subfield e)
elsif s_field.code == 'e'
relator = s_field.value.upcase.gsub(/[[:punct:]]?$/, '')
end
end
# Set role from relator value.
role = author_roles[relator] || 'secondary_authors'
names[role] << name
end
end
end
names
end
##
# Process publication information for citations.
# @param [MARC::Record]
# @return [Array] pub info strings from fields 260 and 264.
def set_pub_citation(record)
pub_citation = []
Traject::MarcExtractor.cached('260:264').collect_matching_lines(record) do |field, _spec, _extractor|
a_pub_info = nil
b_pub_info = nil
pub_info = ""
field.subfields.each do |s_field|
a_pub_info = Traject::Macros::Marc21.trim_punctuation(s_field.value).strip if s_field.code == 'a'
b_pub_info = Traject::Macros::Marc21.trim_punctuation(s_field.value).strip if s_field.code == 'b'
end
# Build publication info string and add to citation array.
pub_info += a_pub_info unless a_pub_info.nil?
pub_info += ": " if !a_pub_info.nil? && !b_pub_info.nil?
pub_info += b_pub_info unless b_pub_info.nil?
pub_citation << pub_info if !pub_info.empty?
end
pub_citation
end
SEPARATOR = '—'
# for the hierarchical subject/genre display
# split with em dash along t,v,x,y,z
# optional vocabulary argument for allowing certain subfield $2 vocabularies
def process_hierarchy(record, fields, vocabulary = [])
headings = []
split_on_subfield = ['t', 'v', 'x', 'y', 'z']
Traject::MarcExtractor.cached(fields).collect_matching_lines(record) do |field, spec, extractor|
heading = extractor.collect_subfields(field, spec).first
include_heading = vocabulary.empty? # always include the heading if a vocabulary is not specified
unless heading.nil?
field.subfields.each do |s_field|
# when specified, only include heading if it is part of the vocabulary
include_heading = vocabulary.include?(s_field.value) if s_field.code == '2' && !vocabulary.empty?
heading = heading.gsub(" #{s_field.value}", "#{SEPARATOR}#{s_field.value}") if split_on_subfield.include?(s_field.code)
end
heading = heading.split(SEPARATOR)
heading = heading.map { |s| Traject::Macros::Marc21.trim_punctuation(s) }.join(SEPARATOR)
headings << heading if include_heading
end
end
headings
end
# for the split subject facet
# split with em dash along x,z
def process_subject_topic_facet record
subjects = []
Traject::MarcExtractor.cached('600|*0|abcdfklmnopqrtxz:610|*0|abfklmnoprstxz:611|*0|abcdefgklnpqstxz:630|*0|adfgklmnoprstxz:650|*0|abcxz:651|*0|axz').collect_matching_lines(record) do |field, spec, extractor|
subject = extractor.collect_subfields(field, spec).first
unless subject.nil?
field.subfields.each do |s_field|
subject = subject.gsub(" #{s_field.value}", "#{SEPARATOR}#{s_field.value}") if (s_field.code == 'x' || s_field.code == 'z')
end
subject = subject.split(SEPARATOR)
subjects << subject.map { |s| Traject::Macros::Marc21.trim_punctuation(s) }
end
end
Traject::MarcExtractor.cached('650|*7|abcxz').collect_matching_lines(record) do |field, spec, extractor|
subject = extractor.collect_subfields(field, spec).first
should_include = false
unless subject.nil?
field.subfields.each do |s_field|
should_include = s_field.value == 'sk' if s_field.code == '2'
subject = subject.gsub(" #{s_field.value}", "#{SEPARATOR}#{s_field.value}") if (s_field.code == 'x' || s_field.code == 'z')
end
subject = subject.split(SEPARATOR)
subjects << subject.map { |s| Traject::Macros::Marc21.trim_punctuation(s) } if should_include
end
end
subjects.flatten
end
def strip_non_numeric num_str
num_str.gsub(/\D/, '').to_i.to_s
end
def oclc_normalize oclc, opts = { prefix: false }
oclc_num = strip_non_numeric(oclc)
if opts[:prefix] == true
case oclc_num.length
when 1..8
"ocm" + "%08d" % oclc_num
when 9
"ocn" + oclc_num
else
"on" + oclc_num
end
else
oclc_num
end
end
# Construct (or retrieve) the cache manager service
# @return [CacheManager] the cache manager service
def build_cache_manager(figgy_dir_path:)
return @cache_manager unless @cache_manager.nil?
figgy_lightly = Lightly.new(dir: figgy_dir_path, life: 0, hash: false)
figgy_cache_adapter = CacheAdapter.new(service: figgy_lightly)
CacheManager.initialize(figgy_cache: figgy_cache_adapter, logger: logger)
@cache_manager = CacheManager.current
end
# returns hash of links ($u) (key),
# anchor text ($y, $3, hostname), and additional labels ($z) (array value)
# @param [MARC::Record] the MARC record being parsed
# @return [Hash] the values used to construct the links
def electronic_access_links(record, figgy_dir_path)
solr_field_values = {}
holding_856s = {}
iiif_manifest_paths = {}
output = []
iiif_manifest_links = []
fragment_index = 0
Traject::MarcExtractor.cached('856').collect_matching_lines(record) do |field, _spec, _extractor|
anchor_text = false
z_label = false
url_key = false
holding_id = nil
bib_id = record['001']
electronic_access_link = ElectronicAccessLinkFactory.build bib_id: bib_id, marc_field: field
# If the electronic access link is an ARK...
if electronic_access_link.ark
# ...and attempt to build an Orangelight URL from the (cached) mappings exposed by the repositories
cache_manager = build_cache_manager(figgy_dir_path: figgy_dir_path)
# Orangelight links
catalog_url_builder = OrangelightUrlBuilder.new(ark_cache: cache_manager.ark_cache, fragment: fragment_value(fragment_index))
orangelight_url = catalog_url_builder.build(url: electronic_access_link.ark)
if orangelight_url
# Index this by the domain for Orangelight
anchor_text = electronic_access_link.anchor_text
anchor_text = 'Digital content' if electronic_access_link.url&.host == electronic_access_link.anchor_text
orangelight_link = electronic_access_link.clone url_key: orangelight_url.to_s, anchor_text: anchor_text
# Only add the link to the current page if it resolves to a resource with a IIIF Manifest
output << orangelight_link
else
# Otherwise, always add the link to the resource
output << electronic_access_link
end
# Figgy URL's
figgy_url_builder = IIIFManifestUrlBuilder.new(ark_cache: cache_manager.figgy_ark_cache, service_host: 'figgy.princeton.edu')
figgy_iiif_manifest = figgy_url_builder.build(url: electronic_access_link.ark)
if figgy_iiif_manifest
figgy_iiif_manifest_link = electronic_access_link.clone url_key: figgy_iiif_manifest.to_s
iiif_manifest_paths[electronic_access_link.url_key] = figgy_iiif_manifest_link.url.to_s
end
else
# Always add links to the resource if it isn't an ARK
output << electronic_access_link
end
output.each do |link|
if link.holding_id
holding_856s[link.holding_id] = { link.url_key => link.url_labels }
elsif link.url_key && link.url_labels
solr_field_values[link.url_key] = link.url_labels
end
end
fragment_index += 1
end
solr_field_values['holding_record_856s'] = holding_856s unless holding_856s == {}
solr_field_values['iiif_manifest_paths'] = iiif_manifest_paths unless iiif_manifest_paths.empty?
solr_field_values
end
def fragment_value(fragment_index)
if fragment_index == 0
'view'
else
"view_#{fragment_index}"
end
end
def remove_parens_035 standard_no
standard_no.gsub(/^\(.*?\)/, '')
end
GENRES = [
'Bibliography',
'Biography',
'Catalogs',
'Catalogues raisonnes',
'Commentaries',
'Congresses',
'Diaries',
'Dictionaries',
'Drama',
'Encyclopedias',
'Exhibitions',
'Fiction',
'Guidebooks',
'In art',
'Indexes',
'Librettos',
'Manuscripts',
'Newspapers',
'Periodicals',
'Pictorial works',
'Poetry',
'Portraits',
'Scores',
'Songs and music',
'Sources',
'Statistics',
'Texts',
'Translations'
]
GENRE_STARTS_WITH = [
'Census',
'Maps',
'Methods',
'Parts',
'Personal narratives',
'Scores and parts',
'Study and teaching',
'Translations into '
]
SUBJECT_GENRE_VOCABULARIES = ['sk', 'aat', 'lcgft', 'rbbin', 'rbgenr', 'rbmscv',
'rbpap', 'rbpri', 'rbprov', 'rbpub', 'rbtyp']
# 600/610/650/651 $v, $x filtered
# 655 $a, $v, $x filtered
def process_genre_facet record
genres = []
Traject::MarcExtractor.cached('600|*0|x:610|*0|x:611|*0|x:630|*0|x:650|*0|x:651|*0|x:655|*0|x').collect_matching_lines(record) do |field, spec, extractor|
genre = extractor.collect_subfields(field, spec).first
unless genre.nil?
genre = Traject::Macros::Marc21.trim_punctuation(genre)
genres << genre if GENRES.include?(genre) || GENRE_STARTS_WITH.any? { |g| genre[g] }
end
end
Traject::MarcExtractor.cached('650|*7|v:655|*7|a:655|*7|v').collect_matching_lines(record) do |field, spec, extractor|
should_include = false
field.subfields.each do |s_field|
# only include heading if it is part of the vocabulary
should_include = SUBJECT_GENRE_VOCABULARIES.include?(s_field.value) if s_field.code == '2'
end
genre = extractor.collect_subfields(field, spec).first
unless genre.nil?
genre = Traject::Macros::Marc21.trim_punctuation(genre)
if genre.match?(/^\s+$/)
logger.error "#{record['001']} - Blank genre field"
elsif should_include
genres << genre
end
end
end
Traject::MarcExtractor.cached('600|*0|v:610|*0|v:611|*0|v:630|*0|v:650|*0|v:651|*0|v:655|*0|a:655|*0|v').collect_matching_lines(record) do |field, spec, extractor|
genre = extractor.collect_subfields(field, spec).first
unless genre.nil?
genre = Traject::Macros::Marc21.trim_punctuation(genre)
if genre.match?(/^\s+$/)
logger.error "#{record['001']} - Blank genre field"
else
genres << genre
end
end
end
genres.uniq
end
def everything_after_t record, fields
values = []
Traject::MarcExtractor.cached(fields).collect_matching_lines(record) do |field, _spec, _extractor|
after_t = false
title = []
field.subfields.each do |s_field|
title << s_field.value if after_t
if s_field.code == 't'
title << s_field.value
after_t = true
end
end
values << Traject::Macros::Marc21.trim_punctuation(title.join(' ')) unless title.empty?
end
values
end
def everything_after_t_alt_script record, fields
values = []
Traject::MarcExtractor.cached(fields).collect_matching_lines(record) do |field, _spec, _extractor|
next unless field.tag == '880'
after_t = false
title = []
field.subfields.each do |s_field|
title << s_field.value if after_t
if s_field.code == 't'
title << s_field.value
after_t = true
end
end
values << Traject::Macros::Marc21.trim_punctuation(title.join(' ')) unless title.empty?
end
values
end
def everything_through_t record, fields
values = []
Traject::MarcExtractor.cached(fields).collect_matching_lines(record) do |field, _spec, _extractor|
non_t = true
title = []
field.subfields.each do |s_field|
title << s_field.value
if s_field.code == 't'
non_t = false
break
end
end
values << Traject::Macros::Marc21.trim_punctuation(title.join(' ')) unless (title.empty? || non_t)
end
values
end
##
# @param record [MARC::Record]
# @param fields [String] MARC fields of interest
# @return [Array] of name-titles each in an [Array], each element [String] split by hierarchy,
# both name ($a) and title ($t) are required
def prep_name_title record, fields
values = []
Traject::MarcExtractor.cached(fields).collect_matching_lines(record) do |field, spec, _extractor|
name_title = []
author = []
non_a = true
non_t = true
field.subfields.each do |s_field|
next if (!spec.subfields.nil? && !spec.subfields.include?(s_field.code))
non_a = false if s_field.code == 'a'
non_t = false if s_field.code == 't'
if non_t
author << s_field.value
else
name_title << s_field.value
end
end
unless (non_a || non_t)
name_title.unshift(author.join(' '))
values << name_title unless name_title.empty?
end
end
values
end
# @param fields [Array] with portions of hierarchy from name-titles
# @return [Array] name-title portions of hierarchy including previous elements, author
def join_hierarchy_without_author fields
fields.collect { |h| h.collect.with_index { |_v, i| Traject::Macros::Marc21.trim_punctuation(h[0..i].join(' ')) } }
end
# @param fields [Array] with portions of hierarchy from name-titles
# @return [Array] name-title portions of hierarchy including previous elements
def join_hierarchy fields
join_hierarchy_without_author(fields).map { |a| a[1..-1] }
end
# Removes empty call_number fields from holdings_1display
def remove_empty_call_number_fields(holding)
holding.tap { |h| ["call_number", "call_number_browse"].map { |k| h.delete(k) if h.fetch(k, []).empty? } }
end
# Collects only non empty khi
def call_number_khi(field)
field.subfields.reject { |s| s.value.empty? }.collect { |s| s if ["k", "h", "i"].include?(s.code) }.compact
end
# Alma Princeton item
def alma_code_start_22?(code)
code.to_s.start_with?("22") && code.to_s.end_with?("06421")
end
def alma_code_start_53?(code)
code.to_s.start_with?("53") && code.to_s.end_with?("06421")
end
def alma_852(record)
record.fields('852').select { |f| alma_code_start_22?(f['8']) }
end
def alma_876(record)
record.fields('876').select { |f| alma_code_start_22?(f['0']) }
end
def alma_951_active(record)
alma_951 = record.fields('951').select { |f| alma_code_start_53?(f['8']) }
alma_951&.select { |f| f['a'] == "Available" }
end
def alma_953(record)
record.fields('953').select { |f| alma_code_start_53?(f['a']) }
end
def alma_954(record)
record.fields('954').select { |f| alma_code_start_53?(f['a']) }
end
def alma_950(record)
field_950_a = record.fields('950').select { |f| ["true", "false"].include?(f['a']) }
field_950_a.map { |f| f['b'] }.first if field_950_a.present?
end
# SCSB item
# Keep this check with the alma_code? check
# until we make sure that the records in alma are updated
def scsb_doc?(record_id)
/^SCSB-\d+/.match?(record_id)
end
# holding block json hash keyed on mfhd id including location, library, call number, shelving title,
# location note, location has, location has (current), indexes, and supplements
# pulls from mfhd 852, 866, 867, and 868
# assumes exactly 1 852 is present per mfhd (it saves the last 852 it finds)
def process_holdings record # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
all_holdings = {}
Traject::MarcExtractor.cached('852').collect_matching_lines(record) do |field, _spec, _extractor|
holding = {}
holding_id = nil
is_alma = alma_code_start_22?(field['8'])
is_scsb = scsb_doc?(record['001'].value) && field['0']
next unless is_alma || is_scsb
field.subfields.each do |s_field|
# Index holdings from Princeton records
if s_field.code == '8' && is_alma
holding_id = s_field.value
# Index holdings from SCSB.
elsif s_field.code == '0' && is_scsb
holding_id = s_field.value
elsif s_field.code == 'b'
holding['location_code'] ||= s_field.value
# Append 852c to location code 852b if it's an Alma item
# Do not append the 852c if it is a SCSB - we save the SCSB locations as scsbnypl and scsbcul
holding['location_code'] += "$#{field['c']}" if field['c'] && is_alma
holding['location'] ||= Traject::TranslationMap.new("locations", default: "__passthrough__")[holding['location_code']]
holding['library'] ||= Traject::TranslationMap.new("location_display", default: "__passthrough__")[holding['location_code']]
elsif /[khij]/.match?(s_field.code)
holding['call_number'] ||= []
holding['call_number'] << s_field.value
holding['call_number_browse'] ||= []
holding['call_number_browse'] << s_field.value
elsif s_field.code == 'l'
holding['shelving_title'] ||= []
holding['shelving_title'] << s_field.value
elsif s_field.code == 'z'
holding['location_note'] ||= []
holding['location_note'] << s_field.value
end
end
holding['call_number'] = holding['call_number'].join(' ').strip if holding['call_number'].present?
holding['call_number_browse'] = holding['call_number_browse'].join(' ').strip if holding['call_number_browse'].present?
all_holdings[holding_id] = remove_empty_call_number_fields(holding) unless holding_id.nil? || invalid_location?(holding['location_code'])
end
Traject::MarcExtractor.cached('866az').collect_matching_lines(record) do |field, _spec, _extractor|
value = []
holding_id = nil
is_alma = alma_code_start_22?(field['8'])
is_scsb = scsb_doc?(record['001'].value) && field['0']
next unless is_alma || is_scsb
field.subfields.each do |s_field|
# Index holding from Princeton records
if s_field.code == '8' && is_alma
holding_id = s_field.value
# Index holding from SCSB
elsif s_field.code == '0' && is_scsb
holding_id = s_field.value
# location_has for SCSB or Princeton
elsif s_field.code == 'a'
value << s_field.value
# location_has for SCSB or Princeton
elsif s_field.code == 'z'
value << s_field.value
end
end
if (all_holdings[holding_id] && !value.empty?)
all_holdings[holding_id]['location_has'] ||= []
all_holdings[holding_id]['location_has'] << value.join(' ')
end
end
Traject::MarcExtractor.cached('867az').collect_matching_lines(record) do |field, _spec, _extractor|
value = []
holding_id = nil
is_alma = alma_code_start_22?(field['8'])
is_scsb = scsb_doc?(record['001'].value) && field['0']
next unless is_alma || is_scsb
field.subfields.each do |s_field|
# Index holding from Princeton records
if s_field.code == '8' && is_alma
holding_id = s_field.value
# Index holding from SCSB
elsif s_field.code == '0' && is_scsb
holding_id = s_field.value
# supplements for SCSB or Princeton
elsif s_field.code == 'a'
value << s_field.value
# supplements for SCSB or Princeton
elsif s_field.code == 'z'
value << s_field.value
end
end
if (all_holdings[holding_id] && !value.empty?)
all_holdings[holding_id]['supplements'] ||= []
all_holdings[holding_id]['supplements'] << value.join(' ')
end
end
Traject::MarcExtractor.cached('868az').collect_matching_lines(record) do |field, _spec, _extractor|
value = []
holding_id = nil
is_alma = alma_code_start_22?(field['8'])
is_scsb = scsb_doc?(record['001'].value) && field['0']
next unless is_alma || is_scsb
field.subfields.each do |s_field|
# Index holding from Princeton records
if s_field.code == '8' && is_alma
holding_id = s_field.value
# Index holding from SCSB
elsif s_field.code == '0' && is_scsb
holding_id = s_field.value
# indexes for SCSB or Princeton
elsif s_field.code == 'a'
value << s_field.value
# indexes for SCSB or Princeton
elsif s_field.code == 'z'
value << s_field.value
end
end
if (all_holdings[holding_id] && !value.empty?)
all_holdings[holding_id]['indexes'] ||= []
all_holdings[holding_id]['indexes'] << value.join(' ')
end
end
### Added for SCSB - scsbnypl, scsbcul
Traject::MarcExtractor.cached('87603ahljptxz').collect_matching_lines(record) do |field, _spec, _extractor|
is_alma = alma_code_start_22?(field['0'])
is_scsb = scsb_doc?(record['001'].value) && field['0']
next unless is_scsb || is_alma
item = {}
field.subfields.each do |s_field|
if s_field.code == '0'
item[:holding_id] = s_field.value
elsif s_field.code == '3'
item[:enumeration] = s_field.value
elsif s_field.code == 'a'
item[:id] = s_field.value
elsif s_field.code == 'h' && is_scsb
item[:use_statement] = s_field.value
elsif s_field.code == 'j'
item[:status_at_load] = s_field.value
elsif s_field.code == 'l' && is_scsb
item[:storage_location] = s_field.value
elsif s_field.code == 'p'
item[:barcode] = s_field.value
elsif s_field.code == 't'
item[:copy_number] = s_field.value
elsif s_field.code == 'x' && is_scsb
item[:cgc] = s_field.value
elsif s_field.code == 'z' && is_scsb
item[:collection_code] = s_field.value
end
end
if all_holdings[item[:holding_id]].present?
if all_holdings[item[:holding_id]]["items"].nil?
all_holdings[item[:holding_id]]["items"] = [item]
else
all_holdings[item[:holding_id]]["items"] << item
end
end
end
all_holdings
end
def invalid_location?(code)
Traject::TranslationMap.new("locations")[code].nil?
end
def process_recap_notes record
item_notes = []
partner_lib = nil
Traject::MarcExtractor.cached('852').collect_matching_lines(record) do |field, _spec, _extractor|
is_scsb = scsb_doc?(record['001'].value) && field['0']
next unless is_scsb
field.subfields.each do |s_field|
if s_field.code == 'b'
partner_lib = s_field.value # ||= Traject::TranslationMap.new("locations", :default => "__passthrough__")[s_field.value]
end
end
end
Traject::MarcExtractor.cached('87603ahjptxz').collect_matching_lines(record) do |field, _spec, _extractor|
is_scsb = scsb_doc?(record['001'].value) && field['0']
next unless is_scsb
col_group = ''
field.subfields.each do |s_field|
if s_field.code == 'x'
if s_field.value == 'Shared'
col_group = 'S'
elsif s_field.value == 'Private'
col_group = 'P'
elsif s_field.value == 'Committed'
col_group = 'C'
elsif s_field.value == 'Uncommittable'
col_group = 'U'
else
col_group = 'O'
end
end
end
if partner_lib == 'scsbnypl'
partner_display_string = 'N'
elsif partner_lib == 'scsbcul'
partner_display_string = 'C'
elsif partner_lib == "scsbhl"
partner_display_string = "H"
end
item_notes << "#{partner_display_string} - #{col_group}"
end
item_notes
end
def find_hathi_by_oclc(oclc)
return if ENV["RUN_HATHI_COMPARE"].blank?
output_dir = ENV['HATHI_OUTPUT_DIR']
if output_dir.blank?
puts "The output directory must be set for Hathi comparison to work!!! ENV['HATHI_OUTPUT_DIR']"
return ""
end
overlap_file = Dir.glob("#{output_dir}/overlap*final.tsv").sort_by { |filename| filename.to_date.strftime }.last
if overlap_file.blank?
puts "The overlap file is missing from #{output_dir}!!"
return ""
end
oclc_hathi = `grep "^#{oclc}\t" #{overlap_file}`
end
# "980\t1590302\tmono\tdeny\tic\tmdp.39015002162876\n980\t1590302\tmono\tdeny\tic\tmdp.39015010651894\n980\t1590302\tmono\tdeny\tic\tmdp.39015066013585\n"
def parse_locations_from_hathi_line(line)
return [] if line.blank?
access = line.split("\t")[3]
locs = ["hathi"]
locs << "hathi_temp" if access == "deny"
locs
end
def parse_hathi_identifer_from_hathi_line(line)
return "" if line.blank?
[line.split("\n").first.split("\t")[5]]
end
| 35.145695 | 210 | 0.664468 |
f721ad0c62e910dd1afd32c8d292aabdb43c219b | 175 | assert 'Module#name' do
module A
class B
end
end
assert_nil A::B.singleton_class.name
assert_equal 'Fixnum', Fixnum.name
assert_equal 'A::B', A::B.name
end
| 15.909091 | 38 | 0.68 |
87dd9695c39102bbc65653ec7a7637683ffb937b | 4,299 | # -*- encoding: utf-8 -*-
# stub: capybara 3.0.2 ruby lib
Gem::Specification.new do |s|
s.name = "capybara".freeze
s.version = "3.0.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Thomas Walpole".freeze, "Jonas Nicklas".freeze]
s.cert_chain = ["gem-public_cert.pem".freeze]
s.date = "2018-04-13"
s.description = "Capybara is an integration testing tool for rack based web applications. It simulates how a user would interact with a website".freeze
s.email = ["[email protected]".freeze, "[email protected]".freeze]
s.homepage = "https://github.com/teamcapybara/capybara".freeze
s.licenses = ["MIT".freeze]
s.required_ruby_version = Gem::Requirement.new(">= 2.2.2".freeze)
s.rubygems_version = "2.7.6".freeze
s.summary = "Capybara aims to simplify the process of integration testing Rack applications, such as Rails, Sinatra or Merb".freeze
s.installed_by_version = "2.7.6" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<addressable>.freeze, [">= 0"])
s.add_runtime_dependency(%q<mini_mime>.freeze, [">= 0.1.3"])
s.add_runtime_dependency(%q<nokogiri>.freeze, ["~> 1.8"])
s.add_runtime_dependency(%q<rack>.freeze, [">= 1.6.0"])
s.add_runtime_dependency(%q<rack-test>.freeze, [">= 0.6.3"])
s.add_runtime_dependency(%q<xpath>.freeze, ["~> 3.0"])
s.add_development_dependency(%q<cucumber>.freeze, [">= 2.3.0"])
s.add_development_dependency(%q<erubi>.freeze, [">= 0"])
s.add_development_dependency(%q<fuubar>.freeze, [">= 1.0.0"])
s.add_development_dependency(%q<launchy>.freeze, [">= 2.0.4"])
s.add_development_dependency(%q<minitest>.freeze, [">= 0"])
s.add_development_dependency(%q<puma>.freeze, [">= 0"])
s.add_development_dependency(%q<rake>.freeze, [">= 0"])
s.add_development_dependency(%q<rspec>.freeze, [">= 3.4.0"])
s.add_development_dependency(%q<selenium-webdriver>.freeze, ["!= 3.4.1", "< 4.0", ">= 3.0"])
s.add_development_dependency(%q<sinatra>.freeze, [">= 1.4.0"])
s.add_development_dependency(%q<yard>.freeze, [">= 0.9.0"])
else
s.add_dependency(%q<addressable>.freeze, [">= 0"])
s.add_dependency(%q<mini_mime>.freeze, [">= 0.1.3"])
s.add_dependency(%q<nokogiri>.freeze, ["~> 1.8"])
s.add_dependency(%q<rack>.freeze, [">= 1.6.0"])
s.add_dependency(%q<rack-test>.freeze, [">= 0.6.3"])
s.add_dependency(%q<xpath>.freeze, ["~> 3.0"])
s.add_dependency(%q<cucumber>.freeze, [">= 2.3.0"])
s.add_dependency(%q<erubi>.freeze, [">= 0"])
s.add_dependency(%q<fuubar>.freeze, [">= 1.0.0"])
s.add_dependency(%q<launchy>.freeze, [">= 2.0.4"])
s.add_dependency(%q<minitest>.freeze, [">= 0"])
s.add_dependency(%q<puma>.freeze, [">= 0"])
s.add_dependency(%q<rake>.freeze, [">= 0"])
s.add_dependency(%q<rspec>.freeze, [">= 3.4.0"])
s.add_dependency(%q<selenium-webdriver>.freeze, ["!= 3.4.1", "< 4.0", ">= 3.0"])
s.add_dependency(%q<sinatra>.freeze, [">= 1.4.0"])
s.add_dependency(%q<yard>.freeze, [">= 0.9.0"])
end
else
s.add_dependency(%q<addressable>.freeze, [">= 0"])
s.add_dependency(%q<mini_mime>.freeze, [">= 0.1.3"])
s.add_dependency(%q<nokogiri>.freeze, ["~> 1.8"])
s.add_dependency(%q<rack>.freeze, [">= 1.6.0"])
s.add_dependency(%q<rack-test>.freeze, [">= 0.6.3"])
s.add_dependency(%q<xpath>.freeze, ["~> 3.0"])
s.add_dependency(%q<cucumber>.freeze, [">= 2.3.0"])
s.add_dependency(%q<erubi>.freeze, [">= 0"])
s.add_dependency(%q<fuubar>.freeze, [">= 1.0.0"])
s.add_dependency(%q<launchy>.freeze, [">= 2.0.4"])
s.add_dependency(%q<minitest>.freeze, [">= 0"])
s.add_dependency(%q<puma>.freeze, [">= 0"])
s.add_dependency(%q<rake>.freeze, [">= 0"])
s.add_dependency(%q<rspec>.freeze, [">= 3.4.0"])
s.add_dependency(%q<selenium-webdriver>.freeze, ["!= 3.4.1", "< 4.0", ">= 3.0"])
s.add_dependency(%q<sinatra>.freeze, [">= 1.4.0"])
s.add_dependency(%q<yard>.freeze, [">= 0.9.0"])
end
end
| 51.795181 | 153 | 0.624331 |
873c99e499cc205dd61b7967c47d77ece43815d2 | 788 | Gem::Specification.new do |s|
s.authors = ['Eli Foster']
s.name = 'weatheruby'
s.summary = 'A Ruby gem for accessing the Weather Underground API.'
s.version = '1.0.0'
s.license = 'MIT'
s.description = 'Accessing the Weather Underground API through HTTPClient.'
s.email = '[email protected]'
s.homepage = 'https://github.com/elifoster/weatheruby'
s.metadata = {
'issue_tracker' => 'https://github.com/elifoster/weatheruby/issues'
}
s.files = [
'CHANGELOG.md',
'LICENSE.md',
'lib/weatheruby.rb',
'lib/weather/actions.rb',
'lib/weather/planner.rb'
]
s.executables = 'weatheruby'
s.add_runtime_dependency('httpclient', '~> 2.8')
s.add_runtime_dependency('rainbow', '~> 2.1')
s.add_runtime_dependency('string-utility', '~> 3.0')
end
| 31.52 | 77 | 0.668782 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.