repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
StuartApp/h3_ruby | lib/h3/regions.rb | H3.Regions.max_polyfill_size | def max_polyfill_size(geo_polygon, resolution)
geo_polygon = geo_json_to_coordinates(geo_polygon) if geo_polygon.is_a?(String)
Bindings::Private.max_polyfill_size(build_polygon(geo_polygon), resolution)
end | ruby | def max_polyfill_size(geo_polygon, resolution)
geo_polygon = geo_json_to_coordinates(geo_polygon) if geo_polygon.is_a?(String)
Bindings::Private.max_polyfill_size(build_polygon(geo_polygon), resolution)
end | [
"def",
"max_polyfill_size",
"(",
"geo_polygon",
",",
"resolution",
")",
"geo_polygon",
"=",
"geo_json_to_coordinates",
"(",
"geo_polygon",
")",
"if",
"geo_polygon",
".",
"is_a?",
"(",
"String",
")",
"Bindings",
"::",
"Private",
".",
"max_polyfill_size",
"(",
"build_polygon",
"(",
"geo_polygon",
")",
",",
"resolution",
")",
"end"
] | Derive the maximum number of H3 indexes that could be returned from the input.
@param [String, Array<Array<Array<Float>>>] geo_polygon Either a GeoJSON string
or a coordinates nested array.
@param [Integer] resolution Resolution.
@example Derive maximum number of hexagons for given GeoJSON document.
geo_json = "{\"type\":\"Polygon\",\"coordinates\":[[[-1.735839843749998,52.24630137198303],
[-1.8923950195312498,52.05249047600099],[-1.56829833984375,51.891749018068246],
[-1.27716064453125,51.91208502557545],[-1.19476318359375,52.032218104145294],
[-1.24420166015625,52.19413974159753],[-1.5902709960937498,52.24125614966341],
[-1.7358398437499998,52.24630137198303]],[[-1.58203125,52.12590076522272],
[-1.476287841796875,52.12590076522272],[-1.46392822265625,52.075285904832334],
[-1.58203125,52.06937709602395],[-1.58203125,52.12590076522272]],
[[-1.4556884765625,52.01531743663362],[-1.483154296875,51.97642166216334],
[-1.3677978515625,51.96626938051444],[-1.3568115234375,52.0102459910103],
[-1.4556884765625,52.01531743663362]]]}"
H3.max_polyfill_size(geo_json, 9)
33391
@example Derive maximum number of hexagons for a nested array of coordinates.
coordinates = [
[
[52.24630137198303, -1.7358398437499998], [52.05249047600099, -1.8923950195312498],
[51.891749018068246, -1.56829833984375], [51.91208502557545, -1.27716064453125],
[52.032218104145294, -1.19476318359375], [52.19413974159753, -1.24420166015625],
[52.24125614966341, -1.5902709960937498], [52.24630137198303, -1.7358398437499998]
],
[
[52.12590076522272, -1.58203125], [52.12590076522272, -1.476287841796875],
[52.075285904832334, -1.46392822265625], [52.06937709602395, -1.58203125],
[52.12590076522272, -1.58203125]
],
[
[52.01531743663362, -1.4556884765625], [51.97642166216334, -1.483154296875],
[51.96626938051444, -1.3677978515625], [52.0102459910103, -1.3568115234375],
[52.01531743663362, -1.4556884765625]
]
]
H3.max_polyfill_size(coordinates, 9)
33391
@return [Integer] Maximum number of hexagons needed to polyfill given area. | [
"Derive",
"the",
"maximum",
"number",
"of",
"H3",
"indexes",
"that",
"could",
"be",
"returned",
"from",
"the",
"input",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/regions.rb#L51-L54 | train |
StuartApp/h3_ruby | lib/h3/regions.rb | H3.Regions.polyfill | def polyfill(geo_polygon, resolution)
geo_polygon = geo_json_to_coordinates(geo_polygon) if geo_polygon.is_a?(String)
max_size = max_polyfill_size(geo_polygon, resolution)
out = H3Indexes.of_size(max_size)
Bindings::Private.polyfill(build_polygon(geo_polygon), resolution, out)
out.read
end | ruby | def polyfill(geo_polygon, resolution)
geo_polygon = geo_json_to_coordinates(geo_polygon) if geo_polygon.is_a?(String)
max_size = max_polyfill_size(geo_polygon, resolution)
out = H3Indexes.of_size(max_size)
Bindings::Private.polyfill(build_polygon(geo_polygon), resolution, out)
out.read
end | [
"def",
"polyfill",
"(",
"geo_polygon",
",",
"resolution",
")",
"geo_polygon",
"=",
"geo_json_to_coordinates",
"(",
"geo_polygon",
")",
"if",
"geo_polygon",
".",
"is_a?",
"(",
"String",
")",
"max_size",
"=",
"max_polyfill_size",
"(",
"geo_polygon",
",",
"resolution",
")",
"out",
"=",
"H3Indexes",
".",
"of_size",
"(",
"max_size",
")",
"Bindings",
"::",
"Private",
".",
"polyfill",
"(",
"build_polygon",
"(",
"geo_polygon",
")",
",",
"resolution",
",",
"out",
")",
"out",
".",
"read",
"end"
] | Derive a list of H3 indexes that fall within a given geo polygon structure.
@param [String, Array<Array<Array<Float>>>] geo_polygon Either a GeoJSON string or a
coordinates nested array.
@param [Integer] resolution Resolution.
@example Derive hexagons for given GeoJSON document.
geo_json = "{\"type\":\"Polygon\",\"coordinates\":[[[-1.735839843799998,52.24630137198303],
[-1.8923950195312498,52.05249047600099],[-1.56829833984375,51.891749018068246],
[-1.27716064453125,51.91208502557545],[-1.19476318359375,52.032218104145294],
[-1.24420166015625,52.19413974159753],[-1.5902709960937498,52.24125614966341],
[-1.7358398437499998,52.24630137198303]],[[-1.58203125,52.12590076522272],
[-1.476287841796875,52.12590076522272],[-1.46392822265625,52.075285904832334],
[-1.58203125,52.06937709602395],[-1.58203125,52.12590076522272]],
[[-1.4556884765625,52.01531743663362],[-1.483154296875,51.97642166216334],
[-1.3677978515625,51.96626938051444],[-1.3568115234375,52.0102459910103],
[-1.4556884765625,52.01531743663362]]]}"
H3.polyfill(geo_json, 5)
[
599424968551301119, 599424888020664319, 599424970698784767, 599424964256333823,
599424969625042943, 599425001837297663, 599425000763555839
]
@example Derive hexagons for a nested array of coordinates.
coordinates = [
[
[52.24630137198303, -1.7358398437499998], [52.05249047600099, -1.8923950195312498],
[51.891749018068246, -1.56829833984375], [51.91208502557545, -1.27716064453125],
[52.032218104145294, -1.19476318359375], [52.19413974159753, -1.24420166015625],
[52.24125614966341, -1.5902709960937498], [52.24630137198303, -1.7358398437499998]
],
[
[52.12590076522272, -1.58203125], [52.12590076522272, -1.476287841796875],
[52.075285904832334, -1.46392822265625], [52.06937709602395, -1.58203125],
[52.12590076522272, -1.58203125]
],
[
[52.01531743663362, -1.4556884765625], [51.97642166216334, -1.483154296875],
[51.96626938051444, -1.3677978515625], [52.0102459910103, -1.3568115234375],
[52.01531743663362, -1.4556884765625]
]
]
H3.polyfill(coordinates, 5)
[
599424968551301119, 599424888020664319, 599424970698784767, 599424964256333823,
599424969625042943, 599425001837297663, 599425000763555839
]
@return [Array<Integer>] Hexagons needed to polyfill given area. | [
"Derive",
"a",
"list",
"of",
"H3",
"indexes",
"that",
"fall",
"within",
"a",
"given",
"geo",
"polygon",
"structure",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/regions.rb#L105-L111 | train |
StuartApp/h3_ruby | lib/h3/regions.rb | H3.Regions.h3_set_to_linked_geo | def h3_set_to_linked_geo(h3_indexes)
h3_set = H3Indexes.with_contents(h3_indexes)
linked_geo_polygon = LinkedGeoPolygon.new
Bindings::Private.h3_set_to_linked_geo(h3_set, h3_indexes.size, linked_geo_polygon)
extract_linked_geo_polygon(linked_geo_polygon).first
ensure
Bindings::Private.destroy_linked_polygon(linked_geo_polygon)
end | ruby | def h3_set_to_linked_geo(h3_indexes)
h3_set = H3Indexes.with_contents(h3_indexes)
linked_geo_polygon = LinkedGeoPolygon.new
Bindings::Private.h3_set_to_linked_geo(h3_set, h3_indexes.size, linked_geo_polygon)
extract_linked_geo_polygon(linked_geo_polygon).first
ensure
Bindings::Private.destroy_linked_polygon(linked_geo_polygon)
end | [
"def",
"h3_set_to_linked_geo",
"(",
"h3_indexes",
")",
"h3_set",
"=",
"H3Indexes",
".",
"with_contents",
"(",
"h3_indexes",
")",
"linked_geo_polygon",
"=",
"LinkedGeoPolygon",
".",
"new",
"Bindings",
"::",
"Private",
".",
"h3_set_to_linked_geo",
"(",
"h3_set",
",",
"h3_indexes",
".",
"size",
",",
"linked_geo_polygon",
")",
"extract_linked_geo_polygon",
"(",
"linked_geo_polygon",
")",
".",
"first",
"ensure",
"Bindings",
"::",
"Private",
".",
"destroy_linked_polygon",
"(",
"linked_geo_polygon",
")",
"end"
] | Derive a nested array of coordinates from a list of H3 indexes.
@param [Array<Integer>] h3_indexes A list of H3 indexes.
@example Get a set of coordinates from a given list of H3 indexes.
h3_indexes = [
599424968551301119, 599424888020664319, 599424970698784767,
599424964256333823, 599424969625042943, 599425001837297663,
599425000763555839
]
H3.h3_set_to_linked_geo(h3_indexes)
[
[
[52.24425364171531, -1.6470570189756442], [52.19515282473624, -1.7508281227260887],
[52.10973325363767, -1.7265910686763437], [52.06042870859474, -1.8301115887419024],
[51.97490199314513, -1.8057974545517919], [51.9387204737266, -1.6783497689296265],
[51.853128001893175, -1.654344796003053], [51.81682604752331, -1.5274195136674955],
[51.866019925789956, -1.424329996292339], [51.829502535462176, -1.2977583914075301],
[51.87843896218677, -1.1946402363628545], [51.96394676922824, -1.21787542551618],
[52.01267958543637, -1.1145114691876956], [52.09808058649905, -1.1376655003242908],
[52.134791926560325, -1.26456988729442], [52.22012854584846, -1.2880298658365215],
[52.25672060485973, -1.4154623025177386], [52.20787927927604, -1.5192658757247421]
]
]
@return [Array<Array<Array<Float>>>] Nested array of coordinates. | [
"Derive",
"a",
"nested",
"array",
"of",
"coordinates",
"from",
"a",
"list",
"of",
"H3",
"indexes",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/regions.rb#L139-L147 | train |
StuartApp/h3_ruby | lib/h3/indexing.rb | H3.Indexing.geo_to_h3 | def geo_to_h3(coords, resolution)
raise ArgumentError unless coords.is_a?(Array) && coords.count == 2
lat, lon = coords
if lat > 90 || lat < -90 || lon > 180 || lon < -180
raise(ArgumentError, "Invalid coordinates")
end
coords = GeoCoord.new
coords[:lat] = degs_to_rads(lat)
coords[:lon] = degs_to_rads(lon)
Bindings::Private.geo_to_h3(coords, resolution)
end | ruby | def geo_to_h3(coords, resolution)
raise ArgumentError unless coords.is_a?(Array) && coords.count == 2
lat, lon = coords
if lat > 90 || lat < -90 || lon > 180 || lon < -180
raise(ArgumentError, "Invalid coordinates")
end
coords = GeoCoord.new
coords[:lat] = degs_to_rads(lat)
coords[:lon] = degs_to_rads(lon)
Bindings::Private.geo_to_h3(coords, resolution)
end | [
"def",
"geo_to_h3",
"(",
"coords",
",",
"resolution",
")",
"raise",
"ArgumentError",
"unless",
"coords",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"coords",
".",
"count",
"==",
"2",
"lat",
",",
"lon",
"=",
"coords",
"if",
"lat",
">",
"90",
"||",
"lat",
"<",
"-",
"90",
"||",
"lon",
">",
"180",
"||",
"lon",
"<",
"-",
"180",
"raise",
"(",
"ArgumentError",
",",
"\"Invalid coordinates\"",
")",
"end",
"coords",
"=",
"GeoCoord",
".",
"new",
"coords",
"[",
":lat",
"]",
"=",
"degs_to_rads",
"(",
"lat",
")",
"coords",
"[",
":lon",
"]",
"=",
"degs_to_rads",
"(",
"lon",
")",
"Bindings",
"::",
"Private",
".",
"geo_to_h3",
"(",
"coords",
",",
"resolution",
")",
"end"
] | Derive H3 index for the given set of coordinates.
@param [Array<Integer>] coords A coordinate pair.
@param [Integer] resolution The desired resolution of the H3 index.
@example Derive the H3 index for the given coordinates.
H3.geo_to_h3([52.24630137198303, -1.7358398437499998], 9)
617439284584775679
@raise [ArgumentError] If coordinates are invalid.
@return [Integer] H3 index. | [
"Derive",
"H3",
"index",
"for",
"the",
"given",
"set",
"of",
"coordinates",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/indexing.rb#L23-L36 | train |
StuartApp/h3_ruby | lib/h3/indexing.rb | H3.Indexing.h3_to_geo | def h3_to_geo(h3_index)
coords = GeoCoord.new
Bindings::Private.h3_to_geo(h3_index, coords)
[rads_to_degs(coords[:lat]), rads_to_degs(coords[:lon])]
end | ruby | def h3_to_geo(h3_index)
coords = GeoCoord.new
Bindings::Private.h3_to_geo(h3_index, coords)
[rads_to_degs(coords[:lat]), rads_to_degs(coords[:lon])]
end | [
"def",
"h3_to_geo",
"(",
"h3_index",
")",
"coords",
"=",
"GeoCoord",
".",
"new",
"Bindings",
"::",
"Private",
".",
"h3_to_geo",
"(",
"h3_index",
",",
"coords",
")",
"[",
"rads_to_degs",
"(",
"coords",
"[",
":lat",
"]",
")",
",",
"rads_to_degs",
"(",
"coords",
"[",
":lon",
"]",
")",
"]",
"end"
] | Derive coordinates for a given H3 index.
The coordinates map to the centre of the hexagon at the given index.
@param [Integer] h3_index A valid H3 index.
@example Derive the central coordinates for the given H3 index.
H3.h3_to_geo(617439284584775679)
[52.245519061399506, -1.7363137757391423]
@return [Array<Integer>] A coordinate pair. | [
"Derive",
"coordinates",
"for",
"a",
"given",
"H3",
"index",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/indexing.rb#L49-L53 | train |
StuartApp/h3_ruby | lib/h3/indexing.rb | H3.Indexing.h3_to_geo_boundary | def h3_to_geo_boundary(h3_index)
geo_boundary = GeoBoundary.new
Bindings::Private.h3_to_geo_boundary(h3_index, geo_boundary)
geo_boundary[:verts].take(geo_boundary[:num_verts]).map do |d|
[rads_to_degs(d[:lat]), rads_to_degs(d[:lon])]
end
end | ruby | def h3_to_geo_boundary(h3_index)
geo_boundary = GeoBoundary.new
Bindings::Private.h3_to_geo_boundary(h3_index, geo_boundary)
geo_boundary[:verts].take(geo_boundary[:num_verts]).map do |d|
[rads_to_degs(d[:lat]), rads_to_degs(d[:lon])]
end
end | [
"def",
"h3_to_geo_boundary",
"(",
"h3_index",
")",
"geo_boundary",
"=",
"GeoBoundary",
".",
"new",
"Bindings",
"::",
"Private",
".",
"h3_to_geo_boundary",
"(",
"h3_index",
",",
"geo_boundary",
")",
"geo_boundary",
"[",
":verts",
"]",
".",
"take",
"(",
"geo_boundary",
"[",
":num_verts",
"]",
")",
".",
"map",
"do",
"|",
"d",
"|",
"[",
"rads_to_degs",
"(",
"d",
"[",
":lat",
"]",
")",
",",
"rads_to_degs",
"(",
"d",
"[",
":lon",
"]",
")",
"]",
"end",
"end"
] | Derive the geographical boundary as coordinates for a given H3 index.
This will be a set of 6 coordinate pairs matching the vertexes of the
hexagon represented by the given H3 index.
If the H3 index is a pentagon, there will be only 5 coordinate pairs returned.
@param [Integer] h3_index A valid H3 index.
@example Derive the geographical boundary for the given H3 index.
H3.h3_to_geo_boundary(617439284584775679)
[
[52.247260929171055, -1.736809158397472], [52.24625850761068, -1.7389279144996015],
[52.244516619273476, -1.7384324668792375], [52.243777169245725, -1.7358184256304658],
[52.24477956752282, -1.7336997597088104], [52.246521439109415, -1.7341950448552204]
]
@return [Array<Array<Integer>>] An array of six coordinate pairs. | [
"Derive",
"the",
"geographical",
"boundary",
"as",
"coordinates",
"for",
"a",
"given",
"H3",
"index",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/indexing.rb#L73-L79 | train |
StuartApp/h3_ruby | lib/h3/unidirectional_edges.rb | H3.UnidirectionalEdges.h3_indexes_from_unidirectional_edge | def h3_indexes_from_unidirectional_edge(edge)
max_hexagons = 2
out = H3Indexes.of_size(max_hexagons)
Bindings::Private.h3_indexes_from_unidirectional_edge(edge, out)
out.read
end | ruby | def h3_indexes_from_unidirectional_edge(edge)
max_hexagons = 2
out = H3Indexes.of_size(max_hexagons)
Bindings::Private.h3_indexes_from_unidirectional_edge(edge, out)
out.read
end | [
"def",
"h3_indexes_from_unidirectional_edge",
"(",
"edge",
")",
"max_hexagons",
"=",
"2",
"out",
"=",
"H3Indexes",
".",
"of_size",
"(",
"max_hexagons",
")",
"Bindings",
"::",
"Private",
".",
"h3_indexes_from_unidirectional_edge",
"(",
"edge",
",",
"out",
")",
"out",
".",
"read",
"end"
] | Derive origin and destination H3 indexes from edge.
Returned in the form
[origin, destination]
@param [Integer] edge H3 edge index
@example Get origin and destination indexes from edge
H3.h3_indexes_from_unidirectional_edge(1266218516299644927)
[617700169958293503, 617700169961177087]
@return [Array<Integer>] H3 index array. | [
"Derive",
"origin",
"and",
"destination",
"H3",
"indexes",
"from",
"edge",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/unidirectional_edges.rb#L100-L105 | train |
StuartApp/h3_ruby | lib/h3/unidirectional_edges.rb | H3.UnidirectionalEdges.h3_unidirectional_edges_from_hexagon | def h3_unidirectional_edges_from_hexagon(origin)
max_edges = 6
out = H3Indexes.of_size(max_edges)
Bindings::Private.h3_unidirectional_edges_from_hexagon(origin, out)
out.read
end | ruby | def h3_unidirectional_edges_from_hexagon(origin)
max_edges = 6
out = H3Indexes.of_size(max_edges)
Bindings::Private.h3_unidirectional_edges_from_hexagon(origin, out)
out.read
end | [
"def",
"h3_unidirectional_edges_from_hexagon",
"(",
"origin",
")",
"max_edges",
"=",
"6",
"out",
"=",
"H3Indexes",
".",
"of_size",
"(",
"max_edges",
")",
"Bindings",
"::",
"Private",
".",
"h3_unidirectional_edges_from_hexagon",
"(",
"origin",
",",
"out",
")",
"out",
".",
"read",
"end"
] | Derive unidirectional edges for a H3 index.
@param [Integer] origin H3 index
@example Get unidirectional indexes from hexagon
H3.h3_unidirectional_edges_from_hexagon(612933930963697663)
[
1261452277305049087, 1333509871342977023, 1405567465380904959,
1477625059418832895, 1549682653456760831, 1621740247494688767
]
@return [Array<Integer>] H3 index array. | [
"Derive",
"unidirectional",
"edges",
"for",
"a",
"H3",
"index",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/unidirectional_edges.rb#L119-L124 | train |
StuartApp/h3_ruby | lib/h3/unidirectional_edges.rb | H3.UnidirectionalEdges.h3_unidirectional_edge_boundary | def h3_unidirectional_edge_boundary(edge)
geo_boundary = GeoBoundary.new
Bindings::Private.h3_unidirectional_edge_boundary(edge, geo_boundary)
geo_boundary[:verts].take(geo_boundary[:num_verts]).map do |d|
[rads_to_degs(d[:lat]), rads_to_degs(d[:lon])]
end
end | ruby | def h3_unidirectional_edge_boundary(edge)
geo_boundary = GeoBoundary.new
Bindings::Private.h3_unidirectional_edge_boundary(edge, geo_boundary)
geo_boundary[:verts].take(geo_boundary[:num_verts]).map do |d|
[rads_to_degs(d[:lat]), rads_to_degs(d[:lon])]
end
end | [
"def",
"h3_unidirectional_edge_boundary",
"(",
"edge",
")",
"geo_boundary",
"=",
"GeoBoundary",
".",
"new",
"Bindings",
"::",
"Private",
".",
"h3_unidirectional_edge_boundary",
"(",
"edge",
",",
"geo_boundary",
")",
"geo_boundary",
"[",
":verts",
"]",
".",
"take",
"(",
"geo_boundary",
"[",
":num_verts",
"]",
")",
".",
"map",
"do",
"|",
"d",
"|",
"[",
"rads_to_degs",
"(",
"d",
"[",
":lat",
"]",
")",
",",
"rads_to_degs",
"(",
"d",
"[",
":lon",
"]",
")",
"]",
"end",
"end"
] | Derive coordinates for edge boundary.
@param [Integer] edge H3 edge index
@example
H3.h3_unidirectional_edge_boundary(612933930963697663)
[
[68.92995788193981, 31.831280499087402], [69.39359648991828, 62.345344956509784],
[76.163042830191, 94.14309010184775], [87.36469532319619, 145.5581976913368],
[81.27137179020497, -34.75841798028461], [73.31022368544393, 0.32561035194326043]
]
@return [Array<Array<Float>>] Edge boundary coordinates for a hexagon | [
"Derive",
"coordinates",
"for",
"edge",
"boundary",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/unidirectional_edges.rb#L139-L145 | train |
StuartApp/h3_ruby | lib/h3/traversal.rb | H3.Traversal.hex_ring | def hex_ring(origin, k)
max_hexagons = max_hex_ring_size(k)
out = H3Indexes.of_size(max_hexagons)
pentagonal_distortion = Bindings::Private.hex_ring(origin, k, out)
raise(ArgumentError, "The hex ring contains a pentagon") if pentagonal_distortion
out.read
end | ruby | def hex_ring(origin, k)
max_hexagons = max_hex_ring_size(k)
out = H3Indexes.of_size(max_hexagons)
pentagonal_distortion = Bindings::Private.hex_ring(origin, k, out)
raise(ArgumentError, "The hex ring contains a pentagon") if pentagonal_distortion
out.read
end | [
"def",
"hex_ring",
"(",
"origin",
",",
"k",
")",
"max_hexagons",
"=",
"max_hex_ring_size",
"(",
"k",
")",
"out",
"=",
"H3Indexes",
".",
"of_size",
"(",
"max_hexagons",
")",
"pentagonal_distortion",
"=",
"Bindings",
"::",
"Private",
".",
"hex_ring",
"(",
"origin",
",",
"k",
",",
"out",
")",
"raise",
"(",
"ArgumentError",
",",
"\"The hex ring contains a pentagon\"",
")",
"if",
"pentagonal_distortion",
"out",
".",
"read",
"end"
] | Derives the hollow hexagonal ring centered at origin with sides of length k.
An error is raised when one of the indexes returned is a pentagon or is
in the pentagon distortion area.
@param [Integer] origin Origin H3 index.
@param [Integer] k K distance.
@example Derive the hex ring for the H3 index at k = 1
H3.hex_ring(617700169983721471, 1)
[
617700170044014591, 617700170047946751, 617700169984245759,
617700169982672895, 617700169983983615, 617700170044276735
]
@raise [ArgumentError] Raised if the hex ring contains a pentagon.
@return [Array<Integer>] Array of H3 indexes within the hex ring. | [
"Derives",
"the",
"hollow",
"hexagonal",
"ring",
"centered",
"at",
"origin",
"with",
"sides",
"of",
"length",
"k",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/traversal.rb#L136-L142 | train |
StuartApp/h3_ruby | lib/h3/traversal.rb | H3.Traversal.hex_ranges | def hex_ranges(h3_set, k, grouped: true)
h3_range_indexes = hex_ranges_ungrouped(h3_set, k)
return h3_range_indexes unless grouped
h3_range_indexes.each_slice(max_kring_size(k)).each_with_object({}) do |indexes, out|
h3_index = indexes.first
out[h3_index] = k_rings_for_hex_range(indexes, k)
end
end | ruby | def hex_ranges(h3_set, k, grouped: true)
h3_range_indexes = hex_ranges_ungrouped(h3_set, k)
return h3_range_indexes unless grouped
h3_range_indexes.each_slice(max_kring_size(k)).each_with_object({}) do |indexes, out|
h3_index = indexes.first
out[h3_index] = k_rings_for_hex_range(indexes, k)
end
end | [
"def",
"hex_ranges",
"(",
"h3_set",
",",
"k",
",",
"grouped",
":",
"true",
")",
"h3_range_indexes",
"=",
"hex_ranges_ungrouped",
"(",
"h3_set",
",",
"k",
")",
"return",
"h3_range_indexes",
"unless",
"grouped",
"h3_range_indexes",
".",
"each_slice",
"(",
"max_kring_size",
"(",
"k",
")",
")",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"indexes",
",",
"out",
"|",
"h3_index",
"=",
"indexes",
".",
"first",
"out",
"[",
"h3_index",
"]",
"=",
"k_rings_for_hex_range",
"(",
"indexes",
",",
"k",
")",
"end",
"end"
] | Derives H3 indexes within k distance for each H3 index in the set.
@param [Array<Integer>] h3_set Set of H3 indexes
@param [Integer] k K distance.
@param [Boolean] grouped Whether to group the output. Default true.
@example Derive the hex ranges for a given H3 set with k of 0.
H3.hex_ranges([617700169983721471, 617700169982672895], 1)
{
617700169983721471 => [
[617700169983721471],
[
617700170047946751, 617700169984245759, 617700169982672895,
617700169983983615, 617700170044276735, 617700170044014591
]
],
617700169982672895 = > [
[617700169982672895],
[
617700169984245759, 617700169983197183, 617700169983459327,
617700169982935039, 617700169983983615, 617700169983721471
]
]
}
@example Derive the hex ranges for a given H3 set with k of 0 ungrouped.
H3.hex_ranges([617700169983721471, 617700169982672895], 1, grouped: false)
[
617700169983721471, 617700170047946751, 617700169984245759,
617700169982672895, 617700169983983615, 617700170044276735,
617700170044014591, 617700169982672895, 617700169984245759,
617700169983197183, 617700169983459327, 617700169982935039,
617700169983983615, 617700169983721471
]
@raise [ArgumentError] Raised if any of the ranges contains a pentagon.
@see #hex_range
@return [Hash] Hash of H3 index keys, with array values grouped by k-ring. | [
"Derives",
"H3",
"indexes",
"within",
"k",
"distance",
"for",
"each",
"H3",
"index",
"in",
"the",
"set",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/traversal.rb#L199-L207 | train |
StuartApp/h3_ruby | lib/h3/traversal.rb | H3.Traversal.k_ring_distances | def k_ring_distances(origin, k)
max_out_size = max_kring_size(k)
out = H3Indexes.of_size(max_out_size)
distances = FFI::MemoryPointer.new(:int, max_out_size)
Bindings::Private.k_ring_distances(origin, k, out, distances)
hexagons = out.read
distances = distances.read_array_of_int(max_out_size)
Hash[
distances.zip(hexagons).group_by(&:first).map { |d, hs| [d, hs.map(&:last)] }
]
end | ruby | def k_ring_distances(origin, k)
max_out_size = max_kring_size(k)
out = H3Indexes.of_size(max_out_size)
distances = FFI::MemoryPointer.new(:int, max_out_size)
Bindings::Private.k_ring_distances(origin, k, out, distances)
hexagons = out.read
distances = distances.read_array_of_int(max_out_size)
Hash[
distances.zip(hexagons).group_by(&:first).map { |d, hs| [d, hs.map(&:last)] }
]
end | [
"def",
"k_ring_distances",
"(",
"origin",
",",
"k",
")",
"max_out_size",
"=",
"max_kring_size",
"(",
"k",
")",
"out",
"=",
"H3Indexes",
".",
"of_size",
"(",
"max_out_size",
")",
"distances",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":int",
",",
"max_out_size",
")",
"Bindings",
"::",
"Private",
".",
"k_ring_distances",
"(",
"origin",
",",
"k",
",",
"out",
",",
"distances",
")",
"hexagons",
"=",
"out",
".",
"read",
"distances",
"=",
"distances",
".",
"read_array_of_int",
"(",
"max_out_size",
")",
"Hash",
"[",
"distances",
".",
"zip",
"(",
"hexagons",
")",
".",
"group_by",
"(",
":first",
")",
".",
"map",
"{",
"|",
"d",
",",
"hs",
"|",
"[",
"d",
",",
"hs",
".",
"map",
"(",
":last",
")",
"]",
"}",
"]",
"end"
] | Derives the k-ring for the given origin at k distance, sub-grouped by distance.
@param [Integer] origin Origin H3 index.
@param [Integer] k K distance.
@example Derive k-ring at distance 2
H3.k_ring_distances(617700169983721471, 2)
{
0 => [617700169983721471],
1 = >[
617700170047946751, 617700169984245759, 617700169982672895,
617700169983983615, 617700170044276735, 617700170044014591
],
2 => [
617700170048995327, 617700170047684607, 617700170048471039,
617700169988177919, 617700169983197183, 617700169983459327,
617700169982935039, 617700175096053759, 617700175097102335,
617700170043752447, 617700170043490303, 617700170045063167
]
}
@return [Hash] Hash of k-ring distances grouped by distance. | [
"Derives",
"the",
"k",
"-",
"ring",
"for",
"the",
"given",
"origin",
"at",
"k",
"distance",
"sub",
"-",
"grouped",
"by",
"distance",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/traversal.rb#L270-L282 | train |
StuartApp/h3_ruby | lib/h3/inspection.rb | H3.Inspection.h3_to_string | def h3_to_string(h3_index)
h3_str = FFI::MemoryPointer.new(:char, H3_TO_STR_BUF_SIZE)
Bindings::Private.h3_to_string(h3_index, h3_str, H3_TO_STR_BUF_SIZE)
h3_str.read_string
end | ruby | def h3_to_string(h3_index)
h3_str = FFI::MemoryPointer.new(:char, H3_TO_STR_BUF_SIZE)
Bindings::Private.h3_to_string(h3_index, h3_str, H3_TO_STR_BUF_SIZE)
h3_str.read_string
end | [
"def",
"h3_to_string",
"(",
"h3_index",
")",
"h3_str",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":char",
",",
"H3_TO_STR_BUF_SIZE",
")",
"Bindings",
"::",
"Private",
".",
"h3_to_string",
"(",
"h3_index",
",",
"h3_str",
",",
"H3_TO_STR_BUF_SIZE",
")",
"h3_str",
".",
"read_string",
"end"
] | Derives the hexadecimal string representation for a given H3 index.
@param [Integer] h3_index A valid H3 index.
@example Derive the given hexadecimal form for the H3 index
H3.h3_to_string(617700169958293503)
"89283470dcbffff"
@return [String] H3 index in hexadecimal form. | [
"Derives",
"the",
"hexadecimal",
"string",
"representation",
"for",
"a",
"given",
"H3",
"index",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/inspection.rb#L99-L103 | train |
StuartApp/h3_ruby | lib/h3/geo_json.rb | H3.GeoJSON.geo_json_to_coordinates | def geo_json_to_coordinates(input)
geom = RGeo::GeoJSON.decode(input)
coordinates = fetch_coordinates(geom)
swap_lat_lon(coordinates) || failed_to_parse!
rescue JSON::ParserError
failed_to_parse!
end | ruby | def geo_json_to_coordinates(input)
geom = RGeo::GeoJSON.decode(input)
coordinates = fetch_coordinates(geom)
swap_lat_lon(coordinates) || failed_to_parse!
rescue JSON::ParserError
failed_to_parse!
end | [
"def",
"geo_json_to_coordinates",
"(",
"input",
")",
"geom",
"=",
"RGeo",
"::",
"GeoJSON",
".",
"decode",
"(",
"input",
")",
"coordinates",
"=",
"fetch_coordinates",
"(",
"geom",
")",
"swap_lat_lon",
"(",
"coordinates",
")",
"||",
"failed_to_parse!",
"rescue",
"JSON",
"::",
"ParserError",
"failed_to_parse!",
"end"
] | Convert a GeoJSON document to a nested array of coordinates.
@param [String] input The GeoJSON document. This can be a feature collection, feature,
or polygon. If a feature collection is provided, the first feature is used.
@example Convert a GeoJSON document of Banbury to a set of nested coordinates.
document = "{\"type\":\"Polygon\",\"coordinates\":[
[
[-1.7358398437499998,52.24630137198303], [-1.8923950195312498,52.05249047600099],
[-1.56829833984375,51.891749018068246], [-1.27716064453125,51.91208502557545],
[-1.19476318359375,52.032218104145294], [-1.24420166015625,52.19413974159753],
[-1.5902709960937498,52.24125614966341], [-1.7358398437499998,52.24630137198303]
],
[
[-1.58203125,52.12590076522272], [-1.476287841796875,52.12590076522272],
[-1.46392822265625,52.075285904832334], [-1.58203125,52.06937709602395],
[-1.58203125,52.12590076522272]
],
[
[-1.4556884765625,52.01531743663362], [-1.483154296875,51.97642166216334],
[-1.3677978515625,51.96626938051444], [-1.3568115234375,52.0102459910103],
[-1.4556884765625,52.01531743663362]
]
]}"
H3.geo_json_to_coordinates(document)
[
[
[52.24630137198303, -1.7358398437499998], [52.05249047600099, -1.8923950195312498],
[51.891749018068246, -1.56829833984375], [51.91208502557545, -1.27716064453125],
[52.032218104145294, -1.19476318359375], [52.19413974159753, -1.24420166015625],
[52.24125614966341, -1.5902709960937498], [52.24630137198303, -1.7358398437499998]
],
[
[52.12590076522272, -1.58203125], [52.12590076522272, -1.476287841796875],
[52.075285904832334, -1.46392822265625], [52.06937709602395, -1.58203125],
[52.12590076522272, -1.58203125]
],
[
[52.01531743663362, -1.4556884765625], [51.97642166216334, -1.483154296875],
[51.96626938051444, -1.3677978515625], [52.0102459910103, -1.3568115234375],
[52.01531743663362, -1.4556884765625]
]
]
@raise [ArgumentError] Failed to parse the GeoJSON document.
@return [Array<Array<Array>>] Nested array of coordinates. | [
"Convert",
"a",
"GeoJSON",
"document",
"to",
"a",
"nested",
"array",
"of",
"coordinates",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/geo_json.rb#L78-L84 | train |
StuartApp/h3_ruby | lib/h3/geo_json.rb | H3.GeoJSON.coordinates_to_geo_json | def coordinates_to_geo_json(coordinates)
coordinates = swap_lat_lon(coordinates)
outer_coords, *inner_coords = coordinates
factory = RGeo::Cartesian.simple_factory
exterior = factory.linear_ring(outer_coords.map { |lon, lat| factory.point(lon, lat) })
interior_rings = inner_coords.map do |polygon|
factory.linear_ring(polygon.map { |lon, lat| factory.point(lon, lat) })
end
polygon = factory.polygon(exterior, interior_rings)
RGeo::GeoJSON.encode(polygon).to_json
rescue RGeo::Error::InvalidGeometry, NoMethodError
invalid_coordinates!
end | ruby | def coordinates_to_geo_json(coordinates)
coordinates = swap_lat_lon(coordinates)
outer_coords, *inner_coords = coordinates
factory = RGeo::Cartesian.simple_factory
exterior = factory.linear_ring(outer_coords.map { |lon, lat| factory.point(lon, lat) })
interior_rings = inner_coords.map do |polygon|
factory.linear_ring(polygon.map { |lon, lat| factory.point(lon, lat) })
end
polygon = factory.polygon(exterior, interior_rings)
RGeo::GeoJSON.encode(polygon).to_json
rescue RGeo::Error::InvalidGeometry, NoMethodError
invalid_coordinates!
end | [
"def",
"coordinates_to_geo_json",
"(",
"coordinates",
")",
"coordinates",
"=",
"swap_lat_lon",
"(",
"coordinates",
")",
"outer_coords",
",",
"*",
"inner_coords",
"=",
"coordinates",
"factory",
"=",
"RGeo",
"::",
"Cartesian",
".",
"simple_factory",
"exterior",
"=",
"factory",
".",
"linear_ring",
"(",
"outer_coords",
".",
"map",
"{",
"|",
"lon",
",",
"lat",
"|",
"factory",
".",
"point",
"(",
"lon",
",",
"lat",
")",
"}",
")",
"interior_rings",
"=",
"inner_coords",
".",
"map",
"do",
"|",
"polygon",
"|",
"factory",
".",
"linear_ring",
"(",
"polygon",
".",
"map",
"{",
"|",
"lon",
",",
"lat",
"|",
"factory",
".",
"point",
"(",
"lon",
",",
"lat",
")",
"}",
")",
"end",
"polygon",
"=",
"factory",
".",
"polygon",
"(",
"exterior",
",",
"interior_rings",
")",
"RGeo",
"::",
"GeoJSON",
".",
"encode",
"(",
"polygon",
")",
".",
"to_json",
"rescue",
"RGeo",
"::",
"Error",
"::",
"InvalidGeometry",
",",
"NoMethodError",
"invalid_coordinates!",
"end"
] | Convert a nested array of coordinates to a GeoJSON document
@param [Array<Array<Array>>] coordinates Nested array of coordinates.
@example Convert a set of nested coordinates of Banbury to a GeoJSON document.
coordinates = [
[
[52.24630137198303, -1.7358398437499998], [52.05249047600099, -1.8923950195312498],
[51.891749018068246, -1.56829833984375], [51.91208502557545, -1.27716064453125],
[52.032218104145294, -1.19476318359375], [52.19413974159753, -1.24420166015625],
[52.24125614966341, -1.5902709960937498], [52.24630137198303, -1.7358398437499998]
],
[
[52.12590076522272, -1.58203125], [52.12590076522272, -1.476287841796875],
[52.075285904832334, -1.46392822265625], [52.06937709602395, -1.58203125],
[52.12590076522272, -1.58203125]
],
[
[52.01531743663362, -1.4556884765625], [51.97642166216334, -1.483154296875],
[51.96626938051444, -1.3677978515625], [52.0102459910103, -1.3568115234375],
[52.01531743663362, -1.4556884765625]
]
]
H3.coordinates_to_geo_json(coordinates)
"{\"type\":\"Polygon\",\"coordinates\":[
[
[-1.7358398437499998,52.24630137198303], [-1.8923950195312498,52.05249047600099],
[-1.56829833984375,51.891749018068246], [-1.27716064453125,51.91208502557545],
[-1.19476318359375,52.032218104145294], [-1.24420166015625,52.19413974159753],
[-1.5902709960937498,52.24125614966341], [-1.7358398437499998,52.24630137198303]
],
[
[-1.58203125,52.12590076522272], [-1.476287841796875,52.12590076522272],
[-1.46392822265625,52.075285904832334], [-1.58203125,52.06937709602395],
[-1.58203125,52.12590076522272]
],
[
[-1.4556884765625,52.01531743663362], [-1.483154296875,51.97642166216334],
[-1.3677978515625,51.96626938051444], [-1.3568115234375,52.0102459910103],
[-1.4556884765625,52.01531743663362]
]
]}"
@raise [ArgumentError] Failed to parse the given coordinates.
@return [String] GeoJSON document. | [
"Convert",
"a",
"nested",
"array",
"of",
"coordinates",
"to",
"a",
"GeoJSON",
"document"
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/geo_json.rb#L132-L144 | train |
StuartApp/h3_ruby | lib/h3/hierarchy.rb | H3.Hierarchy.h3_to_children | def h3_to_children(h3_index, child_resolution)
max_children = max_h3_to_children_size(h3_index, child_resolution)
out = H3Indexes.of_size(max_children)
Bindings::Private.h3_to_children(h3_index, child_resolution, out)
out.read
end | ruby | def h3_to_children(h3_index, child_resolution)
max_children = max_h3_to_children_size(h3_index, child_resolution)
out = H3Indexes.of_size(max_children)
Bindings::Private.h3_to_children(h3_index, child_resolution, out)
out.read
end | [
"def",
"h3_to_children",
"(",
"h3_index",
",",
"child_resolution",
")",
"max_children",
"=",
"max_h3_to_children_size",
"(",
"h3_index",
",",
"child_resolution",
")",
"out",
"=",
"H3Indexes",
".",
"of_size",
"(",
"max_children",
")",
"Bindings",
"::",
"Private",
".",
"h3_to_children",
"(",
"h3_index",
",",
"child_resolution",
",",
"out",
")",
"out",
".",
"read",
"end"
] | Derive child hexagons contained within the hexagon at the given H3 index.
@param [Integer] h3_index A valid H3 index.
@param [Integer] child_resolution The desired resolution of hexagons returned.
@example Find the child hexagons for a H3 index.
H3.h3_to_children(613196570357137407, 9)
[
617700169982672895, 617700169982935039, 617700169983197183, 617700169983459327,
617700169983721471, 617700169983983615, 617700169984245759
]
@return [Array<Integer>] H3 indexes of child hexagons. | [
"Derive",
"child",
"hexagons",
"contained",
"within",
"the",
"hexagon",
"at",
"the",
"given",
"H3",
"index",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/hierarchy.rb#L49-L54 | train |
StuartApp/h3_ruby | lib/h3/hierarchy.rb | H3.Hierarchy.max_uncompact_size | def max_uncompact_size(compacted_set, resolution)
h3_set = H3Indexes.with_contents(compacted_set)
size = Bindings::Private.max_uncompact_size(h3_set, compacted_set.size, resolution)
raise(ArgumentError, "Couldn't estimate size. Invalid resolution?") if size.negative?
size
end | ruby | def max_uncompact_size(compacted_set, resolution)
h3_set = H3Indexes.with_contents(compacted_set)
size = Bindings::Private.max_uncompact_size(h3_set, compacted_set.size, resolution)
raise(ArgumentError, "Couldn't estimate size. Invalid resolution?") if size.negative?
size
end | [
"def",
"max_uncompact_size",
"(",
"compacted_set",
",",
"resolution",
")",
"h3_set",
"=",
"H3Indexes",
".",
"with_contents",
"(",
"compacted_set",
")",
"size",
"=",
"Bindings",
"::",
"Private",
".",
"max_uncompact_size",
"(",
"h3_set",
",",
"compacted_set",
".",
"size",
",",
"resolution",
")",
"raise",
"(",
"ArgumentError",
",",
"\"Couldn't estimate size. Invalid resolution?\"",
")",
"if",
"size",
".",
"negative?",
"size",
"end"
] | Find the maximum uncompacted size of the given set of H3 indexes.
@param [Array<Integer>] compacted_set An array of valid H3 indexes.
@param [Integer] resolution The desired resolution to uncompact to.
@example Find the maximum uncompacted size of the given set.
h3_set = [
617700440093229055, 617700440092704767, 617700440100569087, 617700440013012991,
617700440013275135, 617700440092180479, 617700440091656191, 617700440092966911,
617700440100831231, 617700440100044799, 617700440101617663, 617700440081956863,
613196840447246335
]
H3.max_uncompact_size(h3_set, 10)
133
@raise [ArgumentError] Given resolution is invalid for h3_set.
@return [Integer] Maximum size of uncompacted set. | [
"Find",
"the",
"maximum",
"uncompacted",
"size",
"of",
"the",
"given",
"set",
"of",
"H3",
"indexes",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/hierarchy.rb#L74-L79 | train |
StuartApp/h3_ruby | lib/h3/hierarchy.rb | H3.Hierarchy.compact | def compact(h3_set)
h3_set = H3Indexes.with_contents(h3_set)
out = H3Indexes.of_size(h3_set.size)
failure = Bindings::Private.compact(h3_set, out, out.size)
raise "Couldn't compact given indexes" if failure
out.read
end | ruby | def compact(h3_set)
h3_set = H3Indexes.with_contents(h3_set)
out = H3Indexes.of_size(h3_set.size)
failure = Bindings::Private.compact(h3_set, out, out.size)
raise "Couldn't compact given indexes" if failure
out.read
end | [
"def",
"compact",
"(",
"h3_set",
")",
"h3_set",
"=",
"H3Indexes",
".",
"with_contents",
"(",
"h3_set",
")",
"out",
"=",
"H3Indexes",
".",
"of_size",
"(",
"h3_set",
".",
"size",
")",
"failure",
"=",
"Bindings",
"::",
"Private",
".",
"compact",
"(",
"h3_set",
",",
"out",
",",
"out",
".",
"size",
")",
"raise",
"\"Couldn't compact given indexes\"",
"if",
"failure",
"out",
".",
"read",
"end"
] | Compact a set of H3 indexes as best as possible.
In the case where the set cannot be compacted, the set is returned unchanged.
@param [Array<Integer>] h3_set An array of valid H3 indexes.
@example Compact the given set.
h3_set = [
617700440073043967, 617700440072781823, 617700440073568255, 617700440093229055,
617700440092704767, 617700440100569087, 617700440074092543, 617700440073830399,
617700440074354687, 617700440073306111, 617700440013012991, 617700440013275135,
617700440092180479, 617700440091656191, 617700440092966911, 617700440100831231,
617700440100044799, 617700440101617663, 617700440081956863
]
H3.compact(h3_set)
[
617700440093229055, 617700440092704767, 617700440100569087, 617700440013012991,
617700440013275135, 617700440092180479, 617700440091656191, 617700440092966911,
617700440100831231, 617700440100044799, 617700440101617663, 617700440081956863,
613196840447246335
]
@raise [RuntimeError] Couldn't attempt to compact given H3 indexes.
@return [Array<Integer>] Compacted set of H3 indexes. | [
"Compact",
"a",
"set",
"of",
"H3",
"indexes",
"as",
"best",
"as",
"possible",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/hierarchy.rb#L106-L113 | train |
StuartApp/h3_ruby | lib/h3/hierarchy.rb | H3.Hierarchy.uncompact | def uncompact(compacted_set, resolution)
max_size = max_uncompact_size(compacted_set, resolution)
out = H3Indexes.of_size(max_size)
h3_set = H3Indexes.with_contents(compacted_set)
failure = Bindings::Private.uncompact(h3_set, compacted_set.size, out, max_size, resolution)
raise "Couldn't uncompact given indexes" if failure
out.read
end | ruby | def uncompact(compacted_set, resolution)
max_size = max_uncompact_size(compacted_set, resolution)
out = H3Indexes.of_size(max_size)
h3_set = H3Indexes.with_contents(compacted_set)
failure = Bindings::Private.uncompact(h3_set, compacted_set.size, out, max_size, resolution)
raise "Couldn't uncompact given indexes" if failure
out.read
end | [
"def",
"uncompact",
"(",
"compacted_set",
",",
"resolution",
")",
"max_size",
"=",
"max_uncompact_size",
"(",
"compacted_set",
",",
"resolution",
")",
"out",
"=",
"H3Indexes",
".",
"of_size",
"(",
"max_size",
")",
"h3_set",
"=",
"H3Indexes",
".",
"with_contents",
"(",
"compacted_set",
")",
"failure",
"=",
"Bindings",
"::",
"Private",
".",
"uncompact",
"(",
"h3_set",
",",
"compacted_set",
".",
"size",
",",
"out",
",",
"max_size",
",",
"resolution",
")",
"raise",
"\"Couldn't uncompact given indexes\"",
"if",
"failure",
"out",
".",
"read",
"end"
] | Uncompact a set of H3 indexes to the given resolution.
@param [Array<Integer>] compacted_set An array of valid H3 indexes.
@param [Integer] resolution The desired resolution to uncompact to.
@example Compact the given set.
h3_set = [
617700440093229055, 617700440092704767, 617700440100569087, 617700440013012991,
617700440013275135, 617700440092180479, 617700440091656191, 617700440092966911,
617700440100831231, 617700440100044799, 617700440101617663, 617700440081956863,
613196840447246335
]
H3.uncompact(h3_set)
[
617700440093229055, 617700440092704767, 617700440100569087, 617700440013012991,
617700440013275135, 617700440092180479, 617700440091656191, 617700440092966911,
617700440100831231, 617700440100044799, 617700440101617663, 617700440081956863,
617700440072781823, 617700440073043967, 617700440073306111, 617700440073568255,
617700440073830399, 617700440074092543, 617700440074354687
]
@raise [RuntimeError] Couldn't attempt to umcompact H3 indexes.
@return [Array<Integer>] Uncompacted set of H3 indexes. | [
"Uncompact",
"a",
"set",
"of",
"H3",
"indexes",
"to",
"the",
"given",
"resolution",
"."
] | f32e91fe1d4d1b1428e940941cb51f0ea260c46d | https://github.com/StuartApp/h3_ruby/blob/f32e91fe1d4d1b1428e940941cb51f0ea260c46d/lib/h3/hierarchy.rb#L139-L148 | train |
piotrmurach/necromancer | lib/necromancer/conversion_target.rb | Necromancer.ConversionTarget.to | def to(target, options = {})
conversion = conversions[source || detect(object, false), detect(target)]
conversion.call(object, options)
end | ruby | def to(target, options = {})
conversion = conversions[source || detect(object, false), detect(target)]
conversion.call(object, options)
end | [
"def",
"to",
"(",
"target",
",",
"options",
"=",
"{",
"}",
")",
"conversion",
"=",
"conversions",
"[",
"source",
"||",
"detect",
"(",
"object",
",",
"false",
")",
",",
"detect",
"(",
"target",
")",
"]",
"conversion",
".",
"call",
"(",
"object",
",",
"options",
")",
"end"
] | Runs a given conversion
@example
converter.convert('1').to(:numeric) # => 1
@example
converter.convert('1') >> Integer # => 1
@return [Object]
the converted target type
@api public | [
"Runs",
"a",
"given",
"conversion"
] | 8d18fbfc4b9b3ed569aeda74c4b76eaaa6f88e8e | https://github.com/piotrmurach/necromancer/blob/8d18fbfc4b9b3ed569aeda74c4b76eaaa6f88e8e/lib/necromancer/conversion_target.rb#L59-L62 | train |
piotrmurach/necromancer | lib/necromancer/conversion_target.rb | Necromancer.ConversionTarget.detect | def detect(object, symbol_as_object = true)
case object
when TrueClass, FalseClass then :boolean
when Integer then :integer
when Class then object.name.downcase
else
if object.is_a?(Symbol) && symbol_as_object
object
else
object.class.name.downcase
end
end
end | ruby | def detect(object, symbol_as_object = true)
case object
when TrueClass, FalseClass then :boolean
when Integer then :integer
when Class then object.name.downcase
else
if object.is_a?(Symbol) && symbol_as_object
object
else
object.class.name.downcase
end
end
end | [
"def",
"detect",
"(",
"object",
",",
"symbol_as_object",
"=",
"true",
")",
"case",
"object",
"when",
"TrueClass",
",",
"FalseClass",
"then",
":boolean",
"when",
"Integer",
"then",
":integer",
"when",
"Class",
"then",
"object",
".",
"name",
".",
"downcase",
"else",
"if",
"object",
".",
"is_a?",
"(",
"Symbol",
")",
"&&",
"symbol_as_object",
"object",
"else",
"object",
".",
"class",
".",
"name",
".",
"downcase",
"end",
"end",
"end"
] | Detect object type and coerce into known key type
@param [Object] object
@api private | [
"Detect",
"object",
"type",
"and",
"coerce",
"into",
"known",
"key",
"type"
] | 8d18fbfc4b9b3ed569aeda74c4b76eaaa6f88e8e | https://github.com/piotrmurach/necromancer/blob/8d18fbfc4b9b3ed569aeda74c4b76eaaa6f88e8e/lib/necromancer/conversion_target.rb#L79-L91 | train |
piotrmurach/necromancer | lib/necromancer/conversions.rb | Necromancer.Conversions.load | def load
ArrayConverters.load(self)
BooleanConverters.load(self)
DateTimeConverters.load(self)
NumericConverters.load(self)
RangeConverters.load(self)
end | ruby | def load
ArrayConverters.load(self)
BooleanConverters.load(self)
DateTimeConverters.load(self)
NumericConverters.load(self)
RangeConverters.load(self)
end | [
"def",
"load",
"ArrayConverters",
".",
"load",
"(",
"self",
")",
"BooleanConverters",
".",
"load",
"(",
"self",
")",
"DateTimeConverters",
".",
"load",
"(",
"self",
")",
"NumericConverters",
".",
"load",
"(",
"self",
")",
"RangeConverters",
".",
"load",
"(",
"self",
")",
"end"
] | Creates a new conversions map
@example
conversion = Necromancer::Conversions.new
@api public
Load converters
@api private | [
"Creates",
"a",
"new",
"conversions",
"map"
] | 8d18fbfc4b9b3ed569aeda74c4b76eaaa6f88e8e | https://github.com/piotrmurach/necromancer/blob/8d18fbfc4b9b3ed569aeda74c4b76eaaa6f88e8e/lib/necromancer/conversions.rb#L33-L39 | train |
piotrmurach/necromancer | lib/necromancer/conversions.rb | Necromancer.Conversions.register | def register(converter = nil, &block)
converter ||= Converter.create(&block)
key = generate_key(converter)
converter = add_config(converter, @configuration)
return false if converter_map.key?(key)
converter_map[key] = converter
true
end | ruby | def register(converter = nil, &block)
converter ||= Converter.create(&block)
key = generate_key(converter)
converter = add_config(converter, @configuration)
return false if converter_map.key?(key)
converter_map[key] = converter
true
end | [
"def",
"register",
"(",
"converter",
"=",
"nil",
",",
"&",
"block",
")",
"converter",
"||=",
"Converter",
".",
"create",
"(",
"block",
")",
"key",
"=",
"generate_key",
"(",
"converter",
")",
"converter",
"=",
"add_config",
"(",
"converter",
",",
"@configuration",
")",
"return",
"false",
"if",
"converter_map",
".",
"key?",
"(",
"key",
")",
"converter_map",
"[",
"key",
"]",
"=",
"converter",
"true",
"end"
] | Register a converter
@example with simple object
conversions.register NullConverter.new(:array, :array)
@example with block
conversions.register do |c|
c.source = :array
c.target = :array
c.convert = -> { |val, options| val }
end
@api public | [
"Register",
"a",
"converter"
] | 8d18fbfc4b9b3ed569aeda74c4b76eaaa6f88e8e | https://github.com/piotrmurach/necromancer/blob/8d18fbfc4b9b3ed569aeda74c4b76eaaa6f88e8e/lib/necromancer/conversions.rb#L74-L81 | train |
piotrmurach/necromancer | lib/necromancer/conversions.rb | Necromancer.Conversions.add_config | def add_config(converter, config)
converter.instance_exec(:"@config") do |var|
instance_variable_set(var, config)
end
converter
end | ruby | def add_config(converter, config)
converter.instance_exec(:"@config") do |var|
instance_variable_set(var, config)
end
converter
end | [
"def",
"add_config",
"(",
"converter",
",",
"config",
")",
"converter",
".",
"instance_exec",
"(",
":\"",
"\"",
")",
"do",
"|",
"var",
"|",
"instance_variable_set",
"(",
"var",
",",
"config",
")",
"end",
"converter",
"end"
] | Inject config into converter
@api private | [
"Inject",
"config",
"into",
"converter"
] | 8d18fbfc4b9b3ed569aeda74c4b76eaaa6f88e8e | https://github.com/piotrmurach/necromancer/blob/8d18fbfc4b9b3ed569aeda74c4b76eaaa6f88e8e/lib/necromancer/conversions.rb#L112-L117 | train |
molybdenum-99/tlaw | lib/tlaw/data_table.rb | TLAW.DataTable.[] | def [](index_or_column)
case index_or_column
when Integer
super
when String, Symbol
map { |h| h[index_or_column.to_s] }
else
fail ArgumentError,
'Expected integer or string/symbol index' \
", got #{index_or_column.class}"
end
end | ruby | def [](index_or_column)
case index_or_column
when Integer
super
when String, Symbol
map { |h| h[index_or_column.to_s] }
else
fail ArgumentError,
'Expected integer or string/symbol index' \
", got #{index_or_column.class}"
end
end | [
"def",
"[]",
"(",
"index_or_column",
")",
"case",
"index_or_column",
"when",
"Integer",
"super",
"when",
"String",
",",
"Symbol",
"map",
"{",
"|",
"h",
"|",
"h",
"[",
"index_or_column",
".",
"to_s",
"]",
"}",
"else",
"fail",
"ArgumentError",
",",
"'Expected integer or string/symbol index'",
"\", got #{index_or_column.class}\"",
"end",
"end"
] | Allows access to one column or row.
@overload [](index)
Returns one row from a DataTable.
@param index [Integer] Row number
@return [Hash] Row as a hash
@overload [](column_name)
Returns one column from a DataTable.
@param column_name [String] Name of column
@return [Array] Column as an array of all values in it | [
"Allows",
"access",
"to",
"one",
"column",
"or",
"row",
"."
] | 922ecb7994b91aafda56582d7a69e230d14a19db | https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/data_table.rb#L74-L85 | train |
molybdenum-99/tlaw | lib/tlaw/data_table.rb | TLAW.DataTable.columns | def columns(*names)
names.map!(&:to_s)
DataTable.new(map { |h| names.map { |n| [n, h[n]] }.to_h })
end | ruby | def columns(*names)
names.map!(&:to_s)
DataTable.new(map { |h| names.map { |n| [n, h[n]] }.to_h })
end | [
"def",
"columns",
"(",
"*",
"names",
")",
"names",
".",
"map!",
"(",
":to_s",
")",
"DataTable",
".",
"new",
"(",
"map",
"{",
"|",
"h",
"|",
"names",
".",
"map",
"{",
"|",
"n",
"|",
"[",
"n",
",",
"h",
"[",
"n",
"]",
"]",
"}",
".",
"to_h",
"}",
")",
"end"
] | Slice of a DataTable with only specified columns left.
@param names [Array<String>] What columns to leave in a DataTable
@return [DataTable] | [
"Slice",
"of",
"a",
"DataTable",
"with",
"only",
"specified",
"columns",
"left",
"."
] | 922ecb7994b91aafda56582d7a69e230d14a19db | https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/data_table.rb#L91-L94 | train |
molybdenum-99/tlaw | lib/tlaw/data_table.rb | TLAW.DataTable.to_h | def to_h
keys.map { |k| [k, map { |h| h[k] }] }.to_h
end | ruby | def to_h
keys.map { |k| [k, map { |h| h[k] }] }.to_h
end | [
"def",
"to_h",
"keys",
".",
"map",
"{",
"|",
"k",
"|",
"[",
"k",
",",
"map",
"{",
"|",
"h",
"|",
"h",
"[",
"k",
"]",
"}",
"]",
"}",
".",
"to_h",
"end"
] | Represents DataTable as a `column name => all values in columns`
hash.
@return [Hash{String => Array}] | [
"Represents",
"DataTable",
"as",
"a",
"column",
"name",
"=",
">",
"all",
"values",
"in",
"columns",
"hash",
"."
] | 922ecb7994b91aafda56582d7a69e230d14a19db | https://github.com/molybdenum-99/tlaw/blob/922ecb7994b91aafda56582d7a69e230d14a19db/lib/tlaw/data_table.rb#L100-L102 | train |
gdotdesign/elm-github-install | lib/elm_install/directory_source.rb | ElmInstall.DirectorySource.copy_to | def copy_to(_, directory)
# Delete the directory to make sure no pervious version remains
FileUtils.rm_rf(directory) if directory.exist?
# Create parent directory
FileUtils.mkdir_p(directory.parent)
# Create symlink
FileUtils.ln_s(@dir.expand_path, directory)
nil
end | ruby | def copy_to(_, directory)
# Delete the directory to make sure no pervious version remains
FileUtils.rm_rf(directory) if directory.exist?
# Create parent directory
FileUtils.mkdir_p(directory.parent)
# Create symlink
FileUtils.ln_s(@dir.expand_path, directory)
nil
end | [
"def",
"copy_to",
"(",
"_",
",",
"directory",
")",
"# Delete the directory to make sure no pervious version remains",
"FileUtils",
".",
"rm_rf",
"(",
"directory",
")",
"if",
"directory",
".",
"exist?",
"# Create parent directory",
"FileUtils",
".",
"mkdir_p",
"(",
"directory",
".",
"parent",
")",
"# Create symlink",
"FileUtils",
".",
"ln_s",
"(",
"@dir",
".",
"expand_path",
",",
"directory",
")",
"nil",
"end"
] | Copies the directory to the given other directory
@param _ [Semverse::Version] The version
@param directory [Pathname] The pathname
@return nil | [
"Copies",
"the",
"directory",
"to",
"the",
"given",
"other",
"directory"
] | 153b1b4c2bfa1a24175fe1d686b40b139674b5b3 | https://github.com/gdotdesign/elm-github-install/blob/153b1b4c2bfa1a24175fe1d686b40b139674b5b3/lib/elm_install/directory_source.rb#L35-L46 | train |
gdotdesign/elm-github-install | lib/elm_install/identifier.rb | ElmInstall.Identifier.identify | def identify(directory)
raw = json(directory)
dependencies = raw['dependencies'].to_h
dependency_sources =
raw['dependency-sources']
.to_h
.merge(@dependency_sources)
dependencies.map do |package, constraint|
constraints = Utils.transform_constraint constraint
type =
if dependency_sources.key?(package)
source = dependency_sources[package]
case source
when Hash
uri_type source['url'], Branch::Just(source['ref'])
when String
if File.exist?(source)
Type::Directory(Pathname.new(source))
else
uri_type source, Branch::Just('master')
end
end
else
Type::Git(Uri::Github(package), Branch::Nothing())
end
type.source.identifier = self
type.source.options = @options
Dependency.new(package, type.source, constraints)
end
end | ruby | def identify(directory)
raw = json(directory)
dependencies = raw['dependencies'].to_h
dependency_sources =
raw['dependency-sources']
.to_h
.merge(@dependency_sources)
dependencies.map do |package, constraint|
constraints = Utils.transform_constraint constraint
type =
if dependency_sources.key?(package)
source = dependency_sources[package]
case source
when Hash
uri_type source['url'], Branch::Just(source['ref'])
when String
if File.exist?(source)
Type::Directory(Pathname.new(source))
else
uri_type source, Branch::Just('master')
end
end
else
Type::Git(Uri::Github(package), Branch::Nothing())
end
type.source.identifier = self
type.source.options = @options
Dependency.new(package, type.source, constraints)
end
end | [
"def",
"identify",
"(",
"directory",
")",
"raw",
"=",
"json",
"(",
"directory",
")",
"dependencies",
"=",
"raw",
"[",
"'dependencies'",
"]",
".",
"to_h",
"dependency_sources",
"=",
"raw",
"[",
"'dependency-sources'",
"]",
".",
"to_h",
".",
"merge",
"(",
"@dependency_sources",
")",
"dependencies",
".",
"map",
"do",
"|",
"package",
",",
"constraint",
"|",
"constraints",
"=",
"Utils",
".",
"transform_constraint",
"constraint",
"type",
"=",
"if",
"dependency_sources",
".",
"key?",
"(",
"package",
")",
"source",
"=",
"dependency_sources",
"[",
"package",
"]",
"case",
"source",
"when",
"Hash",
"uri_type",
"source",
"[",
"'url'",
"]",
",",
"Branch",
"::",
"Just",
"(",
"source",
"[",
"'ref'",
"]",
")",
"when",
"String",
"if",
"File",
".",
"exist?",
"(",
"source",
")",
"Type",
"::",
"Directory",
"(",
"Pathname",
".",
"new",
"(",
"source",
")",
")",
"else",
"uri_type",
"source",
",",
"Branch",
"::",
"Just",
"(",
"'master'",
")",
"end",
"end",
"else",
"Type",
"::",
"Git",
"(",
"Uri",
"::",
"Github",
"(",
"package",
")",
",",
"Branch",
"::",
"Nothing",
"(",
")",
")",
"end",
"type",
".",
"source",
".",
"identifier",
"=",
"self",
"type",
".",
"source",
".",
"options",
"=",
"@options",
"Dependency",
".",
"new",
"(",
"package",
",",
"type",
".",
"source",
",",
"constraints",
")",
"end",
"end"
] | Identifies dependencies from a directory
@param directory [Dir] The directory
@return [Array] The dependencies | [
"Identifies",
"dependencies",
"from",
"a",
"directory"
] | 153b1b4c2bfa1a24175fe1d686b40b139674b5b3 | https://github.com/gdotdesign/elm-github-install/blob/153b1b4c2bfa1a24175fe1d686b40b139674b5b3/lib/elm_install/identifier.rb#L72-L107 | train |
gdotdesign/elm-github-install | lib/elm_install/identifier.rb | ElmInstall.Identifier.uri_type | def uri_type(url, branch)
uri = GitCloneUrl.parse(url)
case uri
when URI::SshGit::Generic
Type::Git(Uri::Ssh(uri), branch)
when URI::HTTP
Type::Git(Uri::Http(uri), branch)
end
end | ruby | def uri_type(url, branch)
uri = GitCloneUrl.parse(url)
case uri
when URI::SshGit::Generic
Type::Git(Uri::Ssh(uri), branch)
when URI::HTTP
Type::Git(Uri::Http(uri), branch)
end
end | [
"def",
"uri_type",
"(",
"url",
",",
"branch",
")",
"uri",
"=",
"GitCloneUrl",
".",
"parse",
"(",
"url",
")",
"case",
"uri",
"when",
"URI",
"::",
"SshGit",
"::",
"Generic",
"Type",
"::",
"Git",
"(",
"Uri",
"::",
"Ssh",
"(",
"uri",
")",
",",
"branch",
")",
"when",
"URI",
"::",
"HTTP",
"Type",
"::",
"Git",
"(",
"Uri",
"::",
"Http",
"(",
"uri",
")",
",",
"branch",
")",
"end",
"end"
] | Returns the type from the given arguments.
@param url [String] The base url
@param branch [Branch] The branch
@return [Type] The type | [
"Returns",
"the",
"type",
"from",
"the",
"given",
"arguments",
"."
] | 153b1b4c2bfa1a24175fe1d686b40b139674b5b3 | https://github.com/gdotdesign/elm-github-install/blob/153b1b4c2bfa1a24175fe1d686b40b139674b5b3/lib/elm_install/identifier.rb#L116-L124 | train |
gdotdesign/elm-github-install | lib/elm_install/identifier.rb | ElmInstall.Identifier.json | def json(directory)
path = File.join(directory, 'elm-package.json')
JSON.parse(File.read(path))
rescue JSON::ParserError
warn "Invalid JSON in file: #{path.bold}"
rescue Errno::ENOENT
warn "Could not find file: #{path.bold}"
end | ruby | def json(directory)
path = File.join(directory, 'elm-package.json')
JSON.parse(File.read(path))
rescue JSON::ParserError
warn "Invalid JSON in file: #{path.bold}"
rescue Errno::ENOENT
warn "Could not find file: #{path.bold}"
end | [
"def",
"json",
"(",
"directory",
")",
"path",
"=",
"File",
".",
"join",
"(",
"directory",
",",
"'elm-package.json'",
")",
"JSON",
".",
"parse",
"(",
"File",
".",
"read",
"(",
"path",
")",
")",
"rescue",
"JSON",
"::",
"ParserError",
"warn",
"\"Invalid JSON in file: #{path.bold}\"",
"rescue",
"Errno",
"::",
"ENOENT",
"warn",
"\"Could not find file: #{path.bold}\"",
"end"
] | Returns the contents of the 'elm-package.json' for the given directory.
@param directory [Dir] The directory
@return [Hash] The contents | [
"Returns",
"the",
"contents",
"of",
"the",
"elm",
"-",
"package",
".",
"json",
"for",
"the",
"given",
"directory",
"."
] | 153b1b4c2bfa1a24175fe1d686b40b139674b5b3 | https://github.com/gdotdesign/elm-github-install/blob/153b1b4c2bfa1a24175fe1d686b40b139674b5b3/lib/elm_install/identifier.rb#L132-L139 | train |
gdotdesign/elm-github-install | lib/elm_install/utils.rb | ElmInstall.Utils.transform_constraint | def transform_constraint(elm_constraint)
elm_constraint.gsub!(/\s/, '')
CONVERTERS
.map { |regexp, prefix| [elm_constraint.match(regexp), prefix] }
.select { |(match)| match }
.map { |(match, prefix)| "#{prefix} #{match[1]}" }
.map { |constraint| Solve::Constraint.new constraint }
end | ruby | def transform_constraint(elm_constraint)
elm_constraint.gsub!(/\s/, '')
CONVERTERS
.map { |regexp, prefix| [elm_constraint.match(regexp), prefix] }
.select { |(match)| match }
.map { |(match, prefix)| "#{prefix} #{match[1]}" }
.map { |constraint| Solve::Constraint.new constraint }
end | [
"def",
"transform_constraint",
"(",
"elm_constraint",
")",
"elm_constraint",
".",
"gsub!",
"(",
"/",
"\\s",
"/",
",",
"''",
")",
"CONVERTERS",
".",
"map",
"{",
"|",
"regexp",
",",
"prefix",
"|",
"[",
"elm_constraint",
".",
"match",
"(",
"regexp",
")",
",",
"prefix",
"]",
"}",
".",
"select",
"{",
"|",
"(",
"match",
")",
"|",
"match",
"}",
".",
"map",
"{",
"|",
"(",
"match",
",",
"prefix",
")",
"|",
"\"#{prefix} #{match[1]}\"",
"}",
".",
"map",
"{",
"|",
"constraint",
"|",
"Solve",
"::",
"Constraint",
".",
"new",
"constraint",
"}",
"end"
] | Transform an 'elm' constraint into a proper one.
@param elm_constraint [String] The elm constraint
@return [Array] The transform constraints | [
"Transform",
"an",
"elm",
"constraint",
"into",
"a",
"proper",
"one",
"."
] | 153b1b4c2bfa1a24175fe1d686b40b139674b5b3 | https://github.com/gdotdesign/elm-github-install/blob/153b1b4c2bfa1a24175fe1d686b40b139674b5b3/lib/elm_install/utils.rb#L23-L31 | train |
gdotdesign/elm-github-install | lib/elm_install/installer.rb | ElmInstall.Installer.results | def results
Solve
.it!(@graph, initial_solve_constraints)
.map do |name, version|
dep = @resolver.dependencies[name]
dep.version = Semverse::Version.new(version)
dep
end
end | ruby | def results
Solve
.it!(@graph, initial_solve_constraints)
.map do |name, version|
dep = @resolver.dependencies[name]
dep.version = Semverse::Version.new(version)
dep
end
end | [
"def",
"results",
"Solve",
".",
"it!",
"(",
"@graph",
",",
"initial_solve_constraints",
")",
".",
"map",
"do",
"|",
"name",
",",
"version",
"|",
"dep",
"=",
"@resolver",
".",
"dependencies",
"[",
"name",
"]",
"dep",
".",
"version",
"=",
"Semverse",
"::",
"Version",
".",
"new",
"(",
"version",
")",
"dep",
"end",
"end"
] | Returns the results of solving
@return [Array] Array of dependencies | [
"Returns",
"the",
"results",
"of",
"solving"
] | 153b1b4c2bfa1a24175fe1d686b40b139674b5b3 | https://github.com/gdotdesign/elm-github-install/blob/153b1b4c2bfa1a24175fe1d686b40b139674b5b3/lib/elm_install/installer.rb#L41-L49 | train |
gdotdesign/elm-github-install | lib/elm_install/installer.rb | ElmInstall.Installer.initial_solve_constraints | def initial_solve_constraints
@identifier.initial_dependencies.flat_map do |dependency|
dependency.constraints.map do |constraint|
[dependency.name, constraint]
end
end
end | ruby | def initial_solve_constraints
@identifier.initial_dependencies.flat_map do |dependency|
dependency.constraints.map do |constraint|
[dependency.name, constraint]
end
end
end | [
"def",
"initial_solve_constraints",
"@identifier",
".",
"initial_dependencies",
".",
"flat_map",
"do",
"|",
"dependency",
"|",
"dependency",
".",
"constraints",
".",
"map",
"do",
"|",
"constraint",
"|",
"[",
"dependency",
".",
"name",
",",
"constraint",
"]",
"end",
"end",
"end"
] | Returns the inital constraints
@return [Array] Array of dependency names and constraints | [
"Returns",
"the",
"inital",
"constraints"
] | 153b1b4c2bfa1a24175fe1d686b40b139674b5b3 | https://github.com/gdotdesign/elm-github-install/blob/153b1b4c2bfa1a24175fe1d686b40b139674b5b3/lib/elm_install/installer.rb#L55-L61 | train |
gdotdesign/elm-github-install | lib/elm_install/resolver.rb | ElmInstall.Resolver.resolve_dependency | def resolve_dependency(dependency)
@dependencies[dependency.name] ||= dependency
dependency
.source
.versions(
dependency.constraints,
@identifier.initial_elm_version,
!@options[:skip_update],
@options[:only_update]
)
.each do |version|
next if @graph.artifact?(dependency.name, version)
resolve_dependencies(dependency, version)
end
nil
end | ruby | def resolve_dependency(dependency)
@dependencies[dependency.name] ||= dependency
dependency
.source
.versions(
dependency.constraints,
@identifier.initial_elm_version,
!@options[:skip_update],
@options[:only_update]
)
.each do |version|
next if @graph.artifact?(dependency.name, version)
resolve_dependencies(dependency, version)
end
nil
end | [
"def",
"resolve_dependency",
"(",
"dependency",
")",
"@dependencies",
"[",
"dependency",
".",
"name",
"]",
"||=",
"dependency",
"dependency",
".",
"source",
".",
"versions",
"(",
"dependency",
".",
"constraints",
",",
"@identifier",
".",
"initial_elm_version",
",",
"!",
"@options",
"[",
":skip_update",
"]",
",",
"@options",
"[",
":only_update",
"]",
")",
".",
"each",
"do",
"|",
"version",
"|",
"next",
"if",
"@graph",
".",
"artifact?",
"(",
"dependency",
".",
"name",
",",
"version",
")",
"resolve_dependencies",
"(",
"dependency",
",",
"version",
")",
"end",
"nil",
"end"
] | Resolves the dependencies of a dependency
@param dependency [Dependency] The dependency
@return nil | [
"Resolves",
"the",
"dependencies",
"of",
"a",
"dependency"
] | 153b1b4c2bfa1a24175fe1d686b40b139674b5b3 | https://github.com/gdotdesign/elm-github-install/blob/153b1b4c2bfa1a24175fe1d686b40b139674b5b3/lib/elm_install/resolver.rb#L40-L57 | train |
gdotdesign/elm-github-install | lib/elm_install/resolver.rb | ElmInstall.Resolver.resolve_dependencies | def resolve_dependencies(main, version)
dependencies = @identifier.identify(main.source.fetch(version))
artifact = @graph.artifact main.name, version
dependencies.each do |dependency|
dependency.constraints.each do |constraint|
artifact.depends dependency.name, constraint
end
resolve_dependency dependency
end
nil
end | ruby | def resolve_dependencies(main, version)
dependencies = @identifier.identify(main.source.fetch(version))
artifact = @graph.artifact main.name, version
dependencies.each do |dependency|
dependency.constraints.each do |constraint|
artifact.depends dependency.name, constraint
end
resolve_dependency dependency
end
nil
end | [
"def",
"resolve_dependencies",
"(",
"main",
",",
"version",
")",
"dependencies",
"=",
"@identifier",
".",
"identify",
"(",
"main",
".",
"source",
".",
"fetch",
"(",
"version",
")",
")",
"artifact",
"=",
"@graph",
".",
"artifact",
"main",
".",
"name",
",",
"version",
"dependencies",
".",
"each",
"do",
"|",
"dependency",
"|",
"dependency",
".",
"constraints",
".",
"each",
"do",
"|",
"constraint",
"|",
"artifact",
".",
"depends",
"dependency",
".",
"name",
",",
"constraint",
"end",
"resolve_dependency",
"dependency",
"end",
"nil",
"end"
] | Resolves the dependencies of a dependency and version
@param main [Dependency] The dependency
@param version [Semverse::Version] The version
@return nil | [
"Resolves",
"the",
"dependencies",
"of",
"a",
"dependency",
"and",
"version"
] | 153b1b4c2bfa1a24175fe1d686b40b139674b5b3 | https://github.com/gdotdesign/elm-github-install/blob/153b1b4c2bfa1a24175fe1d686b40b139674b5b3/lib/elm_install/resolver.rb#L66-L79 | train |
gdotdesign/elm-github-install | lib/elm_install/git_source.rb | ElmInstall.GitSource.fetch | def fetch(version)
# Get the reference from the branch
ref =
case @branch
when Branch::Just
@branch.ref
when Branch::Nothing
case version
when String
version
else
version.to_simple
end
end
repository.checkout ref
end | ruby | def fetch(version)
# Get the reference from the branch
ref =
case @branch
when Branch::Just
@branch.ref
when Branch::Nothing
case version
when String
version
else
version.to_simple
end
end
repository.checkout ref
end | [
"def",
"fetch",
"(",
"version",
")",
"# Get the reference from the branch",
"ref",
"=",
"case",
"@branch",
"when",
"Branch",
"::",
"Just",
"@branch",
".",
"ref",
"when",
"Branch",
"::",
"Nothing",
"case",
"version",
"when",
"String",
"version",
"else",
"version",
".",
"to_simple",
"end",
"end",
"repository",
".",
"checkout",
"ref",
"end"
] | Downloads the version into a temporary directory
@param version [Semverse::Version] The version to fetch
@return [Dir] The directory for the source of the version | [
"Downloads",
"the",
"version",
"into",
"a",
"temporary",
"directory"
] | 153b1b4c2bfa1a24175fe1d686b40b139674b5b3 | https://github.com/gdotdesign/elm-github-install/blob/153b1b4c2bfa1a24175fe1d686b40b139674b5b3/lib/elm_install/git_source.rb#L29-L45 | train |
gdotdesign/elm-github-install | lib/elm_install/git_source.rb | ElmInstall.GitSource.copy_to | def copy_to(version, directory)
# Delete the directory to make sure no pervious version remains if
# we are using a branch or symlink if using Dir.
FileUtils.rm_rf(directory) if directory.exist?
# Create directory if not exists
FileUtils.mkdir_p directory
# Copy hole repository
FileUtils.cp_r("#{fetch(version).path}/.", directory)
# Remove .git directory
FileUtils.rm_rf(File.join(directory, '.git'))
nil
end | ruby | def copy_to(version, directory)
# Delete the directory to make sure no pervious version remains if
# we are using a branch or symlink if using Dir.
FileUtils.rm_rf(directory) if directory.exist?
# Create directory if not exists
FileUtils.mkdir_p directory
# Copy hole repository
FileUtils.cp_r("#{fetch(version).path}/.", directory)
# Remove .git directory
FileUtils.rm_rf(File.join(directory, '.git'))
nil
end | [
"def",
"copy_to",
"(",
"version",
",",
"directory",
")",
"# Delete the directory to make sure no pervious version remains if",
"# we are using a branch or symlink if using Dir.",
"FileUtils",
".",
"rm_rf",
"(",
"directory",
")",
"if",
"directory",
".",
"exist?",
"# Create directory if not exists",
"FileUtils",
".",
"mkdir_p",
"directory",
"# Copy hole repository",
"FileUtils",
".",
"cp_r",
"(",
"\"#{fetch(version).path}/.\"",
",",
"directory",
")",
"# Remove .git directory",
"FileUtils",
".",
"rm_rf",
"(",
"File",
".",
"join",
"(",
"directory",
",",
"'.git'",
")",
")",
"nil",
"end"
] | Copies the version into the given directory
@param version [Semverse::Version] The version
@param directory [Pathname] The pathname
@return nil | [
"Copies",
"the",
"version",
"into",
"the",
"given",
"directory"
] | 153b1b4c2bfa1a24175fe1d686b40b139674b5b3 | https://github.com/gdotdesign/elm-github-install/blob/153b1b4c2bfa1a24175fe1d686b40b139674b5b3/lib/elm_install/git_source.rb#L54-L69 | train |
gdotdesign/elm-github-install | lib/elm_install/git_source.rb | ElmInstall.GitSource.versions | def versions(constraints, elm_version, should_update, only_update)
if repository.cloned? &&
!repository.fetched &&
should_update &&
(!only_update || only_update == package_name)
# Get updates from upstream
Logger.arrow "Getting updates for: #{package_name.bold}"
repository.fetch
end
case @branch
when Branch::Just
[identifier.version(fetch(@branch.ref))]
when Branch::Nothing
matching_versions constraints, elm_version
end
end | ruby | def versions(constraints, elm_version, should_update, only_update)
if repository.cloned? &&
!repository.fetched &&
should_update &&
(!only_update || only_update == package_name)
# Get updates from upstream
Logger.arrow "Getting updates for: #{package_name.bold}"
repository.fetch
end
case @branch
when Branch::Just
[identifier.version(fetch(@branch.ref))]
when Branch::Nothing
matching_versions constraints, elm_version
end
end | [
"def",
"versions",
"(",
"constraints",
",",
"elm_version",
",",
"should_update",
",",
"only_update",
")",
"if",
"repository",
".",
"cloned?",
"&&",
"!",
"repository",
".",
"fetched",
"&&",
"should_update",
"&&",
"(",
"!",
"only_update",
"||",
"only_update",
"==",
"package_name",
")",
"# Get updates from upstream",
"Logger",
".",
"arrow",
"\"Getting updates for: #{package_name.bold}\"",
"repository",
".",
"fetch",
"end",
"case",
"@branch",
"when",
"Branch",
"::",
"Just",
"[",
"identifier",
".",
"version",
"(",
"fetch",
"(",
"@branch",
".",
"ref",
")",
")",
"]",
"when",
"Branch",
"::",
"Nothing",
"matching_versions",
"constraints",
",",
"elm_version",
"end",
"end"
] | Returns the available versions for a repository
@param constraints [Array] The constraints
@param elm_version [String] The Elm version to match against
@return [Array] The versions | [
"Returns",
"the",
"available",
"versions",
"for",
"a",
"repository"
] | 153b1b4c2bfa1a24175fe1d686b40b139674b5b3 | https://github.com/gdotdesign/elm-github-install/blob/153b1b4c2bfa1a24175fe1d686b40b139674b5b3/lib/elm_install/git_source.rb#L93-L109 | train |
gdotdesign/elm-github-install | lib/elm_install/git_source.rb | ElmInstall.GitSource.matching_versions | def matching_versions(constraints, elm_version)
repository
.versions
.select do |version|
elm_version_of(version.to_s) == elm_version &&
constraints.all? { |constraint| constraint.satisfies?(version) }
end
.sort
.reverse
end | ruby | def matching_versions(constraints, elm_version)
repository
.versions
.select do |version|
elm_version_of(version.to_s) == elm_version &&
constraints.all? { |constraint| constraint.satisfies?(version) }
end
.sort
.reverse
end | [
"def",
"matching_versions",
"(",
"constraints",
",",
"elm_version",
")",
"repository",
".",
"versions",
".",
"select",
"do",
"|",
"version",
"|",
"elm_version_of",
"(",
"version",
".",
"to_s",
")",
"==",
"elm_version",
"&&",
"constraints",
".",
"all?",
"{",
"|",
"constraint",
"|",
"constraint",
".",
"satisfies?",
"(",
"version",
")",
"}",
"end",
".",
"sort",
".",
"reverse",
"end"
] | Returns the matchign versions for a repository for the given constraints
@param constraints [Array] The constraints
@param elm_version [String] The Elm version to match against
@return [Array] The versions | [
"Returns",
"the",
"matchign",
"versions",
"for",
"a",
"repository",
"for",
"the",
"given",
"constraints"
] | 153b1b4c2bfa1a24175fe1d686b40b139674b5b3 | https://github.com/gdotdesign/elm-github-install/blob/153b1b4c2bfa1a24175fe1d686b40b139674b5b3/lib/elm_install/git_source.rb#L118-L127 | train |
gdotdesign/elm-github-install | lib/elm_install/populator.rb | ElmInstall.Populator.log_dependency | def log_dependency(dependency)
log = "#{dependency.name} - "
log += dependency.source.to_log.to_s
log += " (#{dependency.version.to_simple})"
Logger.dot log
nil
end | ruby | def log_dependency(dependency)
log = "#{dependency.name} - "
log += dependency.source.to_log.to_s
log += " (#{dependency.version.to_simple})"
Logger.dot log
nil
end | [
"def",
"log_dependency",
"(",
"dependency",
")",
"log",
"=",
"\"#{dependency.name} - \"",
"log",
"+=",
"dependency",
".",
"source",
".",
"to_log",
".",
"to_s",
"log",
"+=",
"\" (#{dependency.version.to_simple})\"",
"Logger",
".",
"dot",
"log",
"nil",
"end"
] | Logs the dependency with a dot
@param dependency [Dependency] The dependency
@return nil | [
"Logs",
"the",
"dependency",
"with",
"a",
"dot"
] | 153b1b4c2bfa1a24175fe1d686b40b139674b5b3 | https://github.com/gdotdesign/elm-github-install/blob/153b1b4c2bfa1a24175fe1d686b40b139674b5b3/lib/elm_install/populator.rb#L70-L77 | train |
gdotdesign/elm-github-install | lib/elm_install/repository.rb | ElmInstall.Repository.versions | def versions
@versions ||=
repo
.tags
.map(&:name)
.select { |tag| tag =~ /(.*\..*\..*)/ }
.map { |tag| Semverse::Version.try_new tag }
.compact
end | ruby | def versions
@versions ||=
repo
.tags
.map(&:name)
.select { |tag| tag =~ /(.*\..*\..*)/ }
.map { |tag| Semverse::Version.try_new tag }
.compact
end | [
"def",
"versions",
"@versions",
"||=",
"repo",
".",
"tags",
".",
"map",
"(",
":name",
")",
".",
"select",
"{",
"|",
"tag",
"|",
"tag",
"=~",
"/",
"\\.",
"\\.",
"/",
"}",
".",
"map",
"{",
"|",
"tag",
"|",
"Semverse",
"::",
"Version",
".",
"try_new",
"tag",
"}",
".",
"compact",
"end"
] | Returns the versions of the repository
@return [Array<Semverse::Version>] The versions | [
"Returns",
"the",
"versions",
"of",
"the",
"repository"
] | 153b1b4c2bfa1a24175fe1d686b40b139674b5b3 | https://github.com/gdotdesign/elm-github-install/blob/153b1b4c2bfa1a24175fe1d686b40b139674b5b3/lib/elm_install/repository.rb#L68-L76 | train |
lwe/simple_enum | lib/simple_enum/view_helpers.rb | SimpleEnum.ViewHelpers.enum_option_pairs | def enum_option_pairs(record, enum, encode_as_value = false)
reader = enum.to_s.pluralize
record = record.class unless record.respond_to?(reader)
record.send(reader).map { |key, value|
name = record.human_enum_name(enum, key) if record.respond_to?(:human_enum_name)
name ||= translate_enum_key(enum, key)
[name, encode_as_value ? value : key]
}
end | ruby | def enum_option_pairs(record, enum, encode_as_value = false)
reader = enum.to_s.pluralize
record = record.class unless record.respond_to?(reader)
record.send(reader).map { |key, value|
name = record.human_enum_name(enum, key) if record.respond_to?(:human_enum_name)
name ||= translate_enum_key(enum, key)
[name, encode_as_value ? value : key]
}
end | [
"def",
"enum_option_pairs",
"(",
"record",
",",
"enum",
",",
"encode_as_value",
"=",
"false",
")",
"reader",
"=",
"enum",
".",
"to_s",
".",
"pluralize",
"record",
"=",
"record",
".",
"class",
"unless",
"record",
".",
"respond_to?",
"(",
"reader",
")",
"record",
".",
"send",
"(",
"reader",
")",
".",
"map",
"{",
"|",
"key",
",",
"value",
"|",
"name",
"=",
"record",
".",
"human_enum_name",
"(",
"enum",
",",
"key",
")",
"if",
"record",
".",
"respond_to?",
"(",
":human_enum_name",
")",
"name",
"||=",
"translate_enum_key",
"(",
"enum",
",",
"key",
")",
"[",
"name",
",",
"encode_as_value",
"?",
"value",
":",
"key",
"]",
"}",
"end"
] | A helper to build forms with Rails' form builder, built to be used with
f.select helper.
f.select :gender, enum_option_pairs(User, :gender), ...
record - The model or Class with the enum
enum - The Symbol with the name of the enum to create the options for
encode_as_value - The Boolean which defines if either the key or the value
should be used as value attribute for the option,
defaults to using the key (i.e. false)
FIXME: check if the name `enum_option_pairs` is actually good and clear
enough...
Returns an Array of pairs, like e.g. `[["Translated key", "key"], ...]` | [
"A",
"helper",
"to",
"build",
"forms",
"with",
"Rails",
"form",
"builder",
"built",
"to",
"be",
"used",
"with",
"f",
".",
"select",
"helper",
"."
] | 325de98b8505f2ecda8c9375e6dfb63cee294123 | https://github.com/lwe/simple_enum/blob/325de98b8505f2ecda8c9375e6dfb63cee294123/lib/simple_enum/view_helpers.rb#L21-L30 | train |
wurmlab/genevalidator | lib/genevalidator/validation_alignment.rb | GeneValidator.AlignmentValidation.array_to_ranges | def array_to_ranges(ar)
prev = ar[0]
ranges = ar.slice_before do |e|
prev2 = prev
prev = e
prev2 + 1 != e
end.map { |a| a[0]..a[-1] }
ranges
end | ruby | def array_to_ranges(ar)
prev = ar[0]
ranges = ar.slice_before do |e|
prev2 = prev
prev = e
prev2 + 1 != e
end.map { |a| a[0]..a[-1] }
ranges
end | [
"def",
"array_to_ranges",
"(",
"ar",
")",
"prev",
"=",
"ar",
"[",
"0",
"]",
"ranges",
"=",
"ar",
".",
"slice_before",
"do",
"|",
"e",
"|",
"prev2",
"=",
"prev",
"prev",
"=",
"e",
"prev2",
"+",
"1",
"!=",
"e",
"end",
".",
"map",
"{",
"|",
"a",
"|",
"a",
"[",
"0",
"]",
"..",
"a",
"[",
"-",
"1",
"]",
"}",
"ranges",
"end"
] | converts an array of integers into array of ranges | [
"converts",
"an",
"array",
"of",
"integers",
"into",
"array",
"of",
"ranges"
] | b44a4a7e72eb8314c73d0cd7062d37a1c4c58299 | https://github.com/wurmlab/genevalidator/blob/b44a4a7e72eb8314c73d0cd7062d37a1c4c58299/lib/genevalidator/validation_alignment.rb#L379-L389 | train |
wurmlab/genevalidator | lib/genevalidator/validation_duplication.rb | GeneValidator.DuplicationValidation.find_local_alignment | def find_local_alignment(hit, prediction, hsp)
# indexing in blast starts from 1
hit_local = hit.raw_sequence[hsp.hit_from - 1..hsp.hit_to - 1]
query_local = prediction.raw_sequence[hsp.match_query_from -
1..hsp.match_query_to - 1]
# in case of nucleotide prediction sequence translate into protein
# use translate with reading frame 1 because
# to/from coordinates of the hsp already correspond to the
# reading frame in which the prediction was read to match this hsp
if @type == :nucleotide
s = Bio::Sequence::NA.new(query_local)
query_local = s.translate
end
opt = ['--maxiterate', '1000', '--localpair', '--anysymbol', '--quiet',
'--thread', @num_threads.to_s]
mafft = Bio::MAFFT.new('mafft', opt)
# local alignment for hit and query
seqs = [hit_local, query_local]
report = mafft.query_align(seqs)
report.alignment.map(&:to_s)
rescue StandardError
raise NoMafftInstallationError
end | ruby | def find_local_alignment(hit, prediction, hsp)
# indexing in blast starts from 1
hit_local = hit.raw_sequence[hsp.hit_from - 1..hsp.hit_to - 1]
query_local = prediction.raw_sequence[hsp.match_query_from -
1..hsp.match_query_to - 1]
# in case of nucleotide prediction sequence translate into protein
# use translate with reading frame 1 because
# to/from coordinates of the hsp already correspond to the
# reading frame in which the prediction was read to match this hsp
if @type == :nucleotide
s = Bio::Sequence::NA.new(query_local)
query_local = s.translate
end
opt = ['--maxiterate', '1000', '--localpair', '--anysymbol', '--quiet',
'--thread', @num_threads.to_s]
mafft = Bio::MAFFT.new('mafft', opt)
# local alignment for hit and query
seqs = [hit_local, query_local]
report = mafft.query_align(seqs)
report.alignment.map(&:to_s)
rescue StandardError
raise NoMafftInstallationError
end | [
"def",
"find_local_alignment",
"(",
"hit",
",",
"prediction",
",",
"hsp",
")",
"# indexing in blast starts from 1",
"hit_local",
"=",
"hit",
".",
"raw_sequence",
"[",
"hsp",
".",
"hit_from",
"-",
"1",
"..",
"hsp",
".",
"hit_to",
"-",
"1",
"]",
"query_local",
"=",
"prediction",
".",
"raw_sequence",
"[",
"hsp",
".",
"match_query_from",
"-",
"1",
"..",
"hsp",
".",
"match_query_to",
"-",
"1",
"]",
"# in case of nucleotide prediction sequence translate into protein",
"# use translate with reading frame 1 because",
"# to/from coordinates of the hsp already correspond to the",
"# reading frame in which the prediction was read to match this hsp",
"if",
"@type",
"==",
":nucleotide",
"s",
"=",
"Bio",
"::",
"Sequence",
"::",
"NA",
".",
"new",
"(",
"query_local",
")",
"query_local",
"=",
"s",
".",
"translate",
"end",
"opt",
"=",
"[",
"'--maxiterate'",
",",
"'1000'",
",",
"'--localpair'",
",",
"'--anysymbol'",
",",
"'--quiet'",
",",
"'--thread'",
",",
"@num_threads",
".",
"to_s",
"]",
"mafft",
"=",
"Bio",
"::",
"MAFFT",
".",
"new",
"(",
"'mafft'",
",",
"opt",
")",
"# local alignment for hit and query",
"seqs",
"=",
"[",
"hit_local",
",",
"query_local",
"]",
"report",
"=",
"mafft",
".",
"query_align",
"(",
"seqs",
")",
"report",
".",
"alignment",
".",
"map",
"(",
":to_s",
")",
"rescue",
"StandardError",
"raise",
"NoMafftInstallationError",
"end"
] | Only run if the BLAST output does not contain hit alignmment | [
"Only",
"run",
"if",
"the",
"BLAST",
"output",
"does",
"not",
"contain",
"hit",
"alignmment"
] | b44a4a7e72eb8314c73d0cd7062d37a1c4c58299 | https://github.com/wurmlab/genevalidator/blob/b44a4a7e72eb8314c73d0cd7062d37a1c4c58299/lib/genevalidator/validation_duplication.rb#L199-L224 | train |
wurmlab/genevalidator | lib/genevalidator/clusterization.rb | GeneValidator.Cluster.print | def print
warn "Cluster: mean = #{mean}, density = #{density}"
lengths.sort { |a, b| a <=> b }.each do |elem|
warn "#{elem[0]}, #{elem[1]}"
end
warn '--------------------------'
end | ruby | def print
warn "Cluster: mean = #{mean}, density = #{density}"
lengths.sort { |a, b| a <=> b }.each do |elem|
warn "#{elem[0]}, #{elem[1]}"
end
warn '--------------------------'
end | [
"def",
"print",
"warn",
"\"Cluster: mean = #{mean}, density = #{density}\"",
"lengths",
".",
"sort",
"{",
"|",
"a",
",",
"b",
"|",
"a",
"<=>",
"b",
"}",
".",
"each",
"do",
"|",
"elem",
"|",
"warn",
"\"#{elem[0]}, #{elem[1]}\"",
"end",
"warn",
"'--------------------------'",
"end"
] | Prints the current cluster | [
"Prints",
"the",
"current",
"cluster"
] | b44a4a7e72eb8314c73d0cd7062d37a1c4c58299 | https://github.com/wurmlab/genevalidator/blob/b44a4a7e72eb8314c73d0cd7062d37a1c4c58299/lib/genevalidator/clusterization.rb#L275-L281 | train |
wurmlab/genevalidator | lib/genevalidator/validation.rb | GeneValidator.Validations.get_info_on_query_sequence | def get_info_on_query_sequence(seq_type = @config[:type],
index = @config[:idx])
query = GeneValidator.extract_input_fasta_sequence(index)
parse_query = query.scan(/^>([^\n]*)\n([A-Za-z\n]*)/)[0]
prediction = Query.new
prediction.definition = parse_query[0].delete("\n")
prediction.identifier = prediction.definition.gsub(/ .*/, '')
prediction.type = seq_type
prediction.raw_sequence = parse_query[1].delete("\n")
prediction.length_protein = prediction.raw_sequence.length
prediction.length_protein /= 3 if seq_type == :nucleotide
prediction
end | ruby | def get_info_on_query_sequence(seq_type = @config[:type],
index = @config[:idx])
query = GeneValidator.extract_input_fasta_sequence(index)
parse_query = query.scan(/^>([^\n]*)\n([A-Za-z\n]*)/)[0]
prediction = Query.new
prediction.definition = parse_query[0].delete("\n")
prediction.identifier = prediction.definition.gsub(/ .*/, '')
prediction.type = seq_type
prediction.raw_sequence = parse_query[1].delete("\n")
prediction.length_protein = prediction.raw_sequence.length
prediction.length_protein /= 3 if seq_type == :nucleotide
prediction
end | [
"def",
"get_info_on_query_sequence",
"(",
"seq_type",
"=",
"@config",
"[",
":type",
"]",
",",
"index",
"=",
"@config",
"[",
":idx",
"]",
")",
"query",
"=",
"GeneValidator",
".",
"extract_input_fasta_sequence",
"(",
"index",
")",
"parse_query",
"=",
"query",
".",
"scan",
"(",
"/",
"\\n",
"\\n",
"\\n",
"/",
")",
"[",
"0",
"]",
"prediction",
"=",
"Query",
".",
"new",
"prediction",
".",
"definition",
"=",
"parse_query",
"[",
"0",
"]",
".",
"delete",
"(",
"\"\\n\"",
")",
"prediction",
".",
"identifier",
"=",
"prediction",
".",
"definition",
".",
"gsub",
"(",
"/",
"/",
",",
"''",
")",
"prediction",
".",
"type",
"=",
"seq_type",
"prediction",
".",
"raw_sequence",
"=",
"parse_query",
"[",
"1",
"]",
".",
"delete",
"(",
"\"\\n\"",
")",
"prediction",
".",
"length_protein",
"=",
"prediction",
".",
"raw_sequence",
".",
"length",
"prediction",
".",
"length_protein",
"/=",
"3",
"if",
"seq_type",
"==",
":nucleotide",
"prediction",
"end"
] | get info about the query | [
"get",
"info",
"about",
"the",
"query"
] | b44a4a7e72eb8314c73d0cd7062d37a1c4c58299 | https://github.com/wurmlab/genevalidator/blob/b44a4a7e72eb8314c73d0cd7062d37a1c4c58299/lib/genevalidator/validation.rb#L69-L82 | train |
wurmlab/genevalidator | lib/genevalidator/validation.rb | GeneValidator.Validate.length_validation_scores | def length_validation_scores(validations, scores)
lcv = validations.select { |v| v.class == LengthClusterValidationOutput }
lrv = validations.select { |v| v.class == LengthRankValidationOutput }
if lcv.length == 1 && lrv.length == 1
score_lcv = (lcv[0].result == lcv[0].expected)
score_lrv = (lrv[0].result == lrv[0].expected)
if score_lcv == true && score_lrv == true
scores[:successes] -= 1 # if both are true: counted as 1 success
elsif score_lcv == false && score_lrv == false
scores[:fails] -= 1 # if both are false: counted as 1 fail
else
scores[:successes] -= 0.5
scores[:fails] -= 0.5
end
end
scores
end | ruby | def length_validation_scores(validations, scores)
lcv = validations.select { |v| v.class == LengthClusterValidationOutput }
lrv = validations.select { |v| v.class == LengthRankValidationOutput }
if lcv.length == 1 && lrv.length == 1
score_lcv = (lcv[0].result == lcv[0].expected)
score_lrv = (lrv[0].result == lrv[0].expected)
if score_lcv == true && score_lrv == true
scores[:successes] -= 1 # if both are true: counted as 1 success
elsif score_lcv == false && score_lrv == false
scores[:fails] -= 1 # if both are false: counted as 1 fail
else
scores[:successes] -= 0.5
scores[:fails] -= 0.5
end
end
scores
end | [
"def",
"length_validation_scores",
"(",
"validations",
",",
"scores",
")",
"lcv",
"=",
"validations",
".",
"select",
"{",
"|",
"v",
"|",
"v",
".",
"class",
"==",
"LengthClusterValidationOutput",
"}",
"lrv",
"=",
"validations",
".",
"select",
"{",
"|",
"v",
"|",
"v",
".",
"class",
"==",
"LengthRankValidationOutput",
"}",
"if",
"lcv",
".",
"length",
"==",
"1",
"&&",
"lrv",
".",
"length",
"==",
"1",
"score_lcv",
"=",
"(",
"lcv",
"[",
"0",
"]",
".",
"result",
"==",
"lcv",
"[",
"0",
"]",
".",
"expected",
")",
"score_lrv",
"=",
"(",
"lrv",
"[",
"0",
"]",
".",
"result",
"==",
"lrv",
"[",
"0",
"]",
".",
"expected",
")",
"if",
"score_lcv",
"==",
"true",
"&&",
"score_lrv",
"==",
"true",
"scores",
"[",
":successes",
"]",
"-=",
"1",
"# if both are true: counted as 1 success",
"elsif",
"score_lcv",
"==",
"false",
"&&",
"score_lrv",
"==",
"false",
"scores",
"[",
":fails",
"]",
"-=",
"1",
"# if both are false: counted as 1 fail",
"else",
"scores",
"[",
":successes",
"]",
"-=",
"0.5",
"scores",
"[",
":fails",
"]",
"-=",
"0.5",
"end",
"end",
"scores",
"end"
] | Since there are two length validations, it is necessary to adjust the
scores accordingly | [
"Since",
"there",
"are",
"two",
"length",
"validations",
"it",
"is",
"necessary",
"to",
"adjust",
"the",
"scores",
"accordingly"
] | b44a4a7e72eb8314c73d0cd7062d37a1c4c58299 | https://github.com/wurmlab/genevalidator/blob/b44a4a7e72eb8314c73d0cd7062d37a1c4c58299/lib/genevalidator/validation.rb#L243-L259 | train |
wurmlab/genevalidator | lib/genevalidator/output_files.rb | GeneValidator.OutputFiles.turn_off_automated_sorting | def turn_off_automated_sorting
js_file = File.join(@dirs[:output_dir], 'html_files/js/gv.compiled.min.js')
original_content = File.read(js_file)
# removes the automatic sort on page load
updated_content = original_content.gsub(',sortList:[[0,0]]', '')
File.open("#{script_file}.tmp", 'w') { |f| f.puts updated_content }
FileUtils.mv("#{script_file}.tmp", script_file)
end | ruby | def turn_off_automated_sorting
js_file = File.join(@dirs[:output_dir], 'html_files/js/gv.compiled.min.js')
original_content = File.read(js_file)
# removes the automatic sort on page load
updated_content = original_content.gsub(',sortList:[[0,0]]', '')
File.open("#{script_file}.tmp", 'w') { |f| f.puts updated_content }
FileUtils.mv("#{script_file}.tmp", script_file)
end | [
"def",
"turn_off_automated_sorting",
"js_file",
"=",
"File",
".",
"join",
"(",
"@dirs",
"[",
":output_dir",
"]",
",",
"'html_files/js/gv.compiled.min.js'",
")",
"original_content",
"=",
"File",
".",
"read",
"(",
"js_file",
")",
"# removes the automatic sort on page load",
"updated_content",
"=",
"original_content",
".",
"gsub",
"(",
"',sortList:[[0,0]]'",
",",
"''",
")",
"File",
".",
"open",
"(",
"\"#{script_file}.tmp\"",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"puts",
"updated_content",
"}",
"FileUtils",
".",
"mv",
"(",
"\"#{script_file}.tmp\"",
",",
"script_file",
")",
"end"
] | By default, on page load, the results are automatically sorted by the
index. However since the whole idea is that users would sort by JSON,
this is not wanted here. | [
"By",
"default",
"on",
"page",
"load",
"the",
"results",
"are",
"automatically",
"sorted",
"by",
"the",
"index",
".",
"However",
"since",
"the",
"whole",
"idea",
"is",
"that",
"users",
"would",
"sort",
"by",
"JSON",
"this",
"is",
"not",
"wanted",
"here",
"."
] | b44a4a7e72eb8314c73d0cd7062d37a1c4c58299 | https://github.com/wurmlab/genevalidator/blob/b44a4a7e72eb8314c73d0cd7062d37a1c4c58299/lib/genevalidator/output_files.rb#L87-L94 | train |
wurmlab/genevalidator | lib/genevalidator/output_files.rb | GeneValidator.OutputFiles.overview_html_hash | def overview_html_hash(evaluation, less)
data = [@overview[:scores].group_by { |a| a }.map do |k, vs|
{ 'key': k, 'value': vs.length, 'main': false }
end]
{ data: data, type: :simplebars, aux1: 10, aux2: '',
title: 'Overall GeneValidator Score Evaluation', footer: '',
xtitle: 'Validation Score', ytitle: 'Number of Queries',
less: less, evaluation: evaluation }
end | ruby | def overview_html_hash(evaluation, less)
data = [@overview[:scores].group_by { |a| a }.map do |k, vs|
{ 'key': k, 'value': vs.length, 'main': false }
end]
{ data: data, type: :simplebars, aux1: 10, aux2: '',
title: 'Overall GeneValidator Score Evaluation', footer: '',
xtitle: 'Validation Score', ytitle: 'Number of Queries',
less: less, evaluation: evaluation }
end | [
"def",
"overview_html_hash",
"(",
"evaluation",
",",
"less",
")",
"data",
"=",
"[",
"@overview",
"[",
":scores",
"]",
".",
"group_by",
"{",
"|",
"a",
"|",
"a",
"}",
".",
"map",
"do",
"|",
"k",
",",
"vs",
"|",
"{",
"'key'",
":",
"k",
",",
"'value'",
":",
"vs",
".",
"length",
",",
"'main'",
":",
"false",
"}",
"end",
"]",
"{",
"data",
":",
"data",
",",
"type",
":",
":simplebars",
",",
"aux1",
":",
"10",
",",
"aux2",
":",
"''",
",",
"title",
":",
"'Overall GeneValidator Score Evaluation'",
",",
"footer",
":",
"''",
",",
"xtitle",
":",
"'Validation Score'",
",",
"ytitle",
":",
"'Number of Queries'",
",",
"less",
":",
"less",
",",
"evaluation",
":",
"evaluation",
"}",
"end"
] | make the historgram with the resulted scores | [
"make",
"the",
"historgram",
"with",
"the",
"resulted",
"scores"
] | b44a4a7e72eb8314c73d0cd7062d37a1c4c58299 | https://github.com/wurmlab/genevalidator/blob/b44a4a7e72eb8314c73d0cd7062d37a1c4c58299/lib/genevalidator/output_files.rb#L105-L113 | train |
calonso/rails-push-notifications | lib/rails-push-notifications/apps/base_app.rb | RailsPushNotifications.BaseApp.push_notifications | def push_notifications
pending = find_pending
to_send = pending.map do |notification|
notification_type.new notification.destinations, notification.data
end
pusher = build_pusher
pusher.push to_send
pending.each_with_index do |p, i|
p.update_attributes! results: to_send[i].results
end
end | ruby | def push_notifications
pending = find_pending
to_send = pending.map do |notification|
notification_type.new notification.destinations, notification.data
end
pusher = build_pusher
pusher.push to_send
pending.each_with_index do |p, i|
p.update_attributes! results: to_send[i].results
end
end | [
"def",
"push_notifications",
"pending",
"=",
"find_pending",
"to_send",
"=",
"pending",
".",
"map",
"do",
"|",
"notification",
"|",
"notification_type",
".",
"new",
"notification",
".",
"destinations",
",",
"notification",
".",
"data",
"end",
"pusher",
"=",
"build_pusher",
"pusher",
".",
"push",
"to_send",
"pending",
".",
"each_with_index",
"do",
"|",
"p",
",",
"i",
"|",
"p",
".",
"update_attributes!",
"results",
":",
"to_send",
"[",
"i",
"]",
".",
"results",
"end",
"end"
] | This method will find all notifications owned by this app and
push them. | [
"This",
"method",
"will",
"find",
"all",
"notifications",
"owned",
"by",
"this",
"app",
"and",
"push",
"them",
"."
] | 820a5bc4a32384624d6ced8f06f2da478497b001 | https://github.com/calonso/rails-push-notifications/blob/820a5bc4a32384624d6ced8f06f2da478497b001/lib/rails-push-notifications/apps/base_app.rb#L18-L28 | train |
joker1007/activemodel-associations | lib/active_record/associations/has_many_for_active_model_association.rb | ActiveRecord::Associations.HasManyForActiveModelAssociation.replace | def replace(other_array)
original_target = load_target.dup
other_array.each { |val| raise_on_type_mismatch!(val) }
target_ids = reflection.options[:target_ids]
owner[target_ids] = other_array.map(&:id)
old_records = original_target - other_array
old_records.each do |record|
@target.delete(record)
end
other_array.each do |record|
if index = @target.index(record)
@target[index] = record
else
@target << record
end
end
end | ruby | def replace(other_array)
original_target = load_target.dup
other_array.each { |val| raise_on_type_mismatch!(val) }
target_ids = reflection.options[:target_ids]
owner[target_ids] = other_array.map(&:id)
old_records = original_target - other_array
old_records.each do |record|
@target.delete(record)
end
other_array.each do |record|
if index = @target.index(record)
@target[index] = record
else
@target << record
end
end
end | [
"def",
"replace",
"(",
"other_array",
")",
"original_target",
"=",
"load_target",
".",
"dup",
"other_array",
".",
"each",
"{",
"|",
"val",
"|",
"raise_on_type_mismatch!",
"(",
"val",
")",
"}",
"target_ids",
"=",
"reflection",
".",
"options",
"[",
":target_ids",
"]",
"owner",
"[",
"target_ids",
"]",
"=",
"other_array",
".",
"map",
"(",
":id",
")",
"old_records",
"=",
"original_target",
"-",
"other_array",
"old_records",
".",
"each",
"do",
"|",
"record",
"|",
"@target",
".",
"delete",
"(",
"record",
")",
"end",
"other_array",
".",
"each",
"do",
"|",
"record",
"|",
"if",
"index",
"=",
"@target",
".",
"index",
"(",
"record",
")",
"@target",
"[",
"index",
"]",
"=",
"record",
"else",
"@target",
"<<",
"record",
"end",
"end",
"end"
] | full replace simplely | [
"full",
"replace",
"simplely"
] | 8bbea47e774c73f77ccaad8839c111b71e380ce8 | https://github.com/joker1007/activemodel-associations/blob/8bbea47e774c73f77ccaad8839c111b71e380ce8/lib/active_record/associations/has_many_for_active_model_association.rb#L23-L41 | train |
joker1007/activemodel-associations | lib/active_record/associations/has_many_for_active_model_association.rb | ActiveRecord::Associations.HasManyForActiveModelAssociation.concat | def concat(*records)
load_target
flatten_records = records.flatten
flatten_records.each { |val| raise_on_type_mismatch!(val) }
target_ids = reflection.options[:target_ids]
owner[target_ids] ||= []
owner[target_ids].concat(flatten_records.map(&:id))
flatten_records.each do |record|
if index = @target.index(record)
@target[index] = record
else
@target << record
end
end
target
end | ruby | def concat(*records)
load_target
flatten_records = records.flatten
flatten_records.each { |val| raise_on_type_mismatch!(val) }
target_ids = reflection.options[:target_ids]
owner[target_ids] ||= []
owner[target_ids].concat(flatten_records.map(&:id))
flatten_records.each do |record|
if index = @target.index(record)
@target[index] = record
else
@target << record
end
end
target
end | [
"def",
"concat",
"(",
"*",
"records",
")",
"load_target",
"flatten_records",
"=",
"records",
".",
"flatten",
"flatten_records",
".",
"each",
"{",
"|",
"val",
"|",
"raise_on_type_mismatch!",
"(",
"val",
")",
"}",
"target_ids",
"=",
"reflection",
".",
"options",
"[",
":target_ids",
"]",
"owner",
"[",
"target_ids",
"]",
"||=",
"[",
"]",
"owner",
"[",
"target_ids",
"]",
".",
"concat",
"(",
"flatten_records",
".",
"map",
"(",
":id",
")",
")",
"flatten_records",
".",
"each",
"do",
"|",
"record",
"|",
"if",
"index",
"=",
"@target",
".",
"index",
"(",
"record",
")",
"@target",
"[",
"index",
"]",
"=",
"record",
"else",
"@target",
"<<",
"record",
"end",
"end",
"target",
"end"
] | no need transaction | [
"no",
"need",
"transaction"
] | 8bbea47e774c73f77ccaad8839c111b71e380ce8 | https://github.com/joker1007/activemodel-associations/blob/8bbea47e774c73f77ccaad8839c111b71e380ce8/lib/active_record/associations/has_many_for_active_model_association.rb#L44-L61 | train |
joker1007/activemodel-associations | lib/active_model/associations/override_methods.rb | ActiveModel::Associations.OverrideMethods.association | def association(name) #:nodoc:
association = association_instance_get(name)
if association.nil?
reflection = self.class.reflect_on_association(name)
if reflection.options[:active_model]
association = ActiveRecord::Associations::HasManyForActiveModelAssociation.new(self, reflection)
else
association = reflection.association_class.new(self, reflection)
end
association_instance_set(name, association)
end
association
end | ruby | def association(name) #:nodoc:
association = association_instance_get(name)
if association.nil?
reflection = self.class.reflect_on_association(name)
if reflection.options[:active_model]
association = ActiveRecord::Associations::HasManyForActiveModelAssociation.new(self, reflection)
else
association = reflection.association_class.new(self, reflection)
end
association_instance_set(name, association)
end
association
end | [
"def",
"association",
"(",
"name",
")",
"#:nodoc:",
"association",
"=",
"association_instance_get",
"(",
"name",
")",
"if",
"association",
".",
"nil?",
"reflection",
"=",
"self",
".",
"class",
".",
"reflect_on_association",
"(",
"name",
")",
"if",
"reflection",
".",
"options",
"[",
":active_model",
"]",
"association",
"=",
"ActiveRecord",
"::",
"Associations",
"::",
"HasManyForActiveModelAssociation",
".",
"new",
"(",
"self",
",",
"reflection",
")",
"else",
"association",
"=",
"reflection",
".",
"association_class",
".",
"new",
"(",
"self",
",",
"reflection",
")",
"end",
"association_instance_set",
"(",
"name",
",",
"association",
")",
"end",
"association",
"end"
] | use by association accessor | [
"use",
"by",
"association",
"accessor"
] | 8bbea47e774c73f77ccaad8839c111b71e380ce8 | https://github.com/joker1007/activemodel-associations/blob/8bbea47e774c73f77ccaad8839c111b71e380ce8/lib/active_model/associations/override_methods.rb#L64-L78 | train |
frenesim/schema_to_scaffold | lib/schema_to_scaffold/path.rb | SchemaToScaffold.Path.choose | def choose
validate_path
search_paths_list = search_paths
if search_paths_list.empty?
puts "\nThere is no /schema[^\/]*.rb$/ in the directory #{@path}"
exit
end
search_paths_list.each_with_index {|path,indx| puts "#{indx}. #{path}" }
begin
print "\nSelect a path to the target schema: "
end while search_paths_list[(id = STDIN.gets.to_i)].nil?
search_paths_list[id]
end | ruby | def choose
validate_path
search_paths_list = search_paths
if search_paths_list.empty?
puts "\nThere is no /schema[^\/]*.rb$/ in the directory #{@path}"
exit
end
search_paths_list.each_with_index {|path,indx| puts "#{indx}. #{path}" }
begin
print "\nSelect a path to the target schema: "
end while search_paths_list[(id = STDIN.gets.to_i)].nil?
search_paths_list[id]
end | [
"def",
"choose",
"validate_path",
"search_paths_list",
"=",
"search_paths",
"if",
"search_paths_list",
".",
"empty?",
"puts",
"\"\\nThere is no /schema[^\\/]*.rb$/ in the directory #{@path}\"",
"exit",
"end",
"search_paths_list",
".",
"each_with_index",
"{",
"|",
"path",
",",
"indx",
"|",
"puts",
"\"#{indx}. #{path}\"",
"}",
"begin",
"print",
"\"\\nSelect a path to the target schema: \"",
"end",
"while",
"search_paths_list",
"[",
"(",
"id",
"=",
"STDIN",
".",
"gets",
".",
"to_i",
")",
"]",
".",
"nil?",
"search_paths_list",
"[",
"id",
"]",
"end"
] | Return the chosen path | [
"Return",
"the",
"chosen",
"path"
] | 957770cc9f245ab6dc2ab7947c0b791d5341ae0e | https://github.com/frenesim/schema_to_scaffold/blob/957770cc9f245ab6dc2ab7947c0b791d5341ae0e/lib/schema_to_scaffold/path.rb#L14-L29 | train |
simplymadeapps/simple_scheduler | lib/simple_scheduler/scheduler_job.rb | SimpleScheduler.SchedulerJob.load_config | def load_config
@config = YAML.safe_load(ERB.new(File.read(config_path)).result)
@queue_ahead = @config["queue_ahead"] || Task::DEFAULT_QUEUE_AHEAD_MINUTES
@queue_name = @config["queue_name"] || "default"
@time_zone = @config["tz"] || Time.zone.tzinfo.name
@config.delete("queue_ahead")
@config.delete("queue_name")
@config.delete("tz")
end | ruby | def load_config
@config = YAML.safe_load(ERB.new(File.read(config_path)).result)
@queue_ahead = @config["queue_ahead"] || Task::DEFAULT_QUEUE_AHEAD_MINUTES
@queue_name = @config["queue_name"] || "default"
@time_zone = @config["tz"] || Time.zone.tzinfo.name
@config.delete("queue_ahead")
@config.delete("queue_name")
@config.delete("tz")
end | [
"def",
"load_config",
"@config",
"=",
"YAML",
".",
"safe_load",
"(",
"ERB",
".",
"new",
"(",
"File",
".",
"read",
"(",
"config_path",
")",
")",
".",
"result",
")",
"@queue_ahead",
"=",
"@config",
"[",
"\"queue_ahead\"",
"]",
"||",
"Task",
"::",
"DEFAULT_QUEUE_AHEAD_MINUTES",
"@queue_name",
"=",
"@config",
"[",
"\"queue_name\"",
"]",
"||",
"\"default\"",
"@time_zone",
"=",
"@config",
"[",
"\"tz\"",
"]",
"||",
"Time",
".",
"zone",
".",
"tzinfo",
".",
"name",
"@config",
".",
"delete",
"(",
"\"queue_ahead\"",
")",
"@config",
".",
"delete",
"(",
"\"queue_name\"",
")",
"@config",
".",
"delete",
"(",
"\"tz\"",
")",
"end"
] | Load the global scheduler config from the YAML file. | [
"Load",
"the",
"global",
"scheduler",
"config",
"from",
"the",
"YAML",
"file",
"."
] | 4d186042507c1397ee79a5e8fe929cc14008c026 | https://github.com/simplymadeapps/simple_scheduler/blob/4d186042507c1397ee79a5e8fe929cc14008c026/lib/simple_scheduler/scheduler_job.rb#L18-L26 | train |
simplymadeapps/simple_scheduler | lib/simple_scheduler/scheduler_job.rb | SimpleScheduler.SchedulerJob.queue_future_jobs | def queue_future_jobs
tasks.each do |task|
# Schedule the new run times using the future job wrapper.
new_run_times = task.future_run_times - task.existing_run_times
new_run_times.each do |time|
SimpleScheduler::FutureJob.set(queue: @queue_name, wait_until: time)
.perform_later(task.params, time.to_i)
end
end
end | ruby | def queue_future_jobs
tasks.each do |task|
# Schedule the new run times using the future job wrapper.
new_run_times = task.future_run_times - task.existing_run_times
new_run_times.each do |time|
SimpleScheduler::FutureJob.set(queue: @queue_name, wait_until: time)
.perform_later(task.params, time.to_i)
end
end
end | [
"def",
"queue_future_jobs",
"tasks",
".",
"each",
"do",
"|",
"task",
"|",
"# Schedule the new run times using the future job wrapper.",
"new_run_times",
"=",
"task",
".",
"future_run_times",
"-",
"task",
".",
"existing_run_times",
"new_run_times",
".",
"each",
"do",
"|",
"time",
"|",
"SimpleScheduler",
"::",
"FutureJob",
".",
"set",
"(",
"queue",
":",
"@queue_name",
",",
"wait_until",
":",
"time",
")",
".",
"perform_later",
"(",
"task",
".",
"params",
",",
"time",
".",
"to_i",
")",
"end",
"end",
"end"
] | Queue each of the future jobs into Sidekiq from the defined tasks. | [
"Queue",
"each",
"of",
"the",
"future",
"jobs",
"into",
"Sidekiq",
"from",
"the",
"defined",
"tasks",
"."
] | 4d186042507c1397ee79a5e8fe929cc14008c026 | https://github.com/simplymadeapps/simple_scheduler/blob/4d186042507c1397ee79a5e8fe929cc14008c026/lib/simple_scheduler/scheduler_job.rb#L29-L38 | train |
simplymadeapps/simple_scheduler | lib/simple_scheduler/scheduler_job.rb | SimpleScheduler.SchedulerJob.tasks | def tasks
@config.map do |task_name, options|
task_params = options.symbolize_keys
task_params[:queue_ahead] ||= @queue_ahead
task_params[:name] = task_name
task_params[:tz] ||= @time_zone
Task.new(task_params)
end
end | ruby | def tasks
@config.map do |task_name, options|
task_params = options.symbolize_keys
task_params[:queue_ahead] ||= @queue_ahead
task_params[:name] = task_name
task_params[:tz] ||= @time_zone
Task.new(task_params)
end
end | [
"def",
"tasks",
"@config",
".",
"map",
"do",
"|",
"task_name",
",",
"options",
"|",
"task_params",
"=",
"options",
".",
"symbolize_keys",
"task_params",
"[",
":queue_ahead",
"]",
"||=",
"@queue_ahead",
"task_params",
"[",
":name",
"]",
"=",
"task_name",
"task_params",
"[",
":tz",
"]",
"||=",
"@time_zone",
"Task",
".",
"new",
"(",
"task_params",
")",
"end",
"end"
] | The array of tasks loaded from the config YAML.
@return [Array<SimpleScheduler::Task] | [
"The",
"array",
"of",
"tasks",
"loaded",
"from",
"the",
"config",
"YAML",
"."
] | 4d186042507c1397ee79a5e8fe929cc14008c026 | https://github.com/simplymadeapps/simple_scheduler/blob/4d186042507c1397ee79a5e8fe929cc14008c026/lib/simple_scheduler/scheduler_job.rb#L42-L50 | train |
simplymadeapps/simple_scheduler | lib/simple_scheduler/task.rb | SimpleScheduler.Task.existing_jobs | def existing_jobs
@existing_jobs ||= SimpleScheduler::Task.scheduled_set.select do |job|
next unless job.display_class == "SimpleScheduler::FutureJob"
task_params = job.display_args[0].symbolize_keys
task_params[:class] == job_class_name && task_params[:name] == name
end.to_a
end | ruby | def existing_jobs
@existing_jobs ||= SimpleScheduler::Task.scheduled_set.select do |job|
next unless job.display_class == "SimpleScheduler::FutureJob"
task_params = job.display_args[0].symbolize_keys
task_params[:class] == job_class_name && task_params[:name] == name
end.to_a
end | [
"def",
"existing_jobs",
"@existing_jobs",
"||=",
"SimpleScheduler",
"::",
"Task",
".",
"scheduled_set",
".",
"select",
"do",
"|",
"job",
"|",
"next",
"unless",
"job",
".",
"display_class",
"==",
"\"SimpleScheduler::FutureJob\"",
"task_params",
"=",
"job",
".",
"display_args",
"[",
"0",
"]",
".",
"symbolize_keys",
"task_params",
"[",
":class",
"]",
"==",
"job_class_name",
"&&",
"task_params",
"[",
":name",
"]",
"==",
"name",
"end",
".",
"to_a",
"end"
] | Returns an array of existing jobs matching the job class of the task.
@return [Array<Sidekiq::SortedEntry>] | [
"Returns",
"an",
"array",
"of",
"existing",
"jobs",
"matching",
"the",
"job",
"class",
"of",
"the",
"task",
"."
] | 4d186042507c1397ee79a5e8fe929cc14008c026 | https://github.com/simplymadeapps/simple_scheduler/blob/4d186042507c1397ee79a5e8fe929cc14008c026/lib/simple_scheduler/task.rb#L42-L49 | train |
simplymadeapps/simple_scheduler | lib/simple_scheduler/task.rb | SimpleScheduler.Task.future_run_times | def future_run_times
future_run_times = existing_run_times.dup
last_run_time = future_run_times.last || at - frequency
last_run_time = last_run_time.in_time_zone(time_zone)
# Ensure there are at least two future jobs scheduled and that the queue ahead time is filled
while future_run_times.length < 2 || minutes_queued_ahead(last_run_time) < queue_ahead
last_run_time = frequency.from_now(last_run_time)
# The hour may not match because of a shift caused by DST in previous run times,
# so we need to ensure that the hour matches the specified hour if given.
last_run_time = last_run_time.change(hour: at.hour, min: at.min) if at.hour?
future_run_times << last_run_time
end
future_run_times
end | ruby | def future_run_times
future_run_times = existing_run_times.dup
last_run_time = future_run_times.last || at - frequency
last_run_time = last_run_time.in_time_zone(time_zone)
# Ensure there are at least two future jobs scheduled and that the queue ahead time is filled
while future_run_times.length < 2 || minutes_queued_ahead(last_run_time) < queue_ahead
last_run_time = frequency.from_now(last_run_time)
# The hour may not match because of a shift caused by DST in previous run times,
# so we need to ensure that the hour matches the specified hour if given.
last_run_time = last_run_time.change(hour: at.hour, min: at.min) if at.hour?
future_run_times << last_run_time
end
future_run_times
end | [
"def",
"future_run_times",
"future_run_times",
"=",
"existing_run_times",
".",
"dup",
"last_run_time",
"=",
"future_run_times",
".",
"last",
"||",
"at",
"-",
"frequency",
"last_run_time",
"=",
"last_run_time",
".",
"in_time_zone",
"(",
"time_zone",
")",
"# Ensure there are at least two future jobs scheduled and that the queue ahead time is filled",
"while",
"future_run_times",
".",
"length",
"<",
"2",
"||",
"minutes_queued_ahead",
"(",
"last_run_time",
")",
"<",
"queue_ahead",
"last_run_time",
"=",
"frequency",
".",
"from_now",
"(",
"last_run_time",
")",
"# The hour may not match because of a shift caused by DST in previous run times,",
"# so we need to ensure that the hour matches the specified hour if given.",
"last_run_time",
"=",
"last_run_time",
".",
"change",
"(",
"hour",
":",
"at",
".",
"hour",
",",
"min",
":",
"at",
".",
"min",
")",
"if",
"at",
".",
"hour?",
"future_run_times",
"<<",
"last_run_time",
"end",
"future_run_times",
"end"
] | Returns an array Time objects for future run times based on
the current time and the given minutes to look ahead.
@return [Array<Time>]
rubocop:disable Metrics/AbcSize | [
"Returns",
"an",
"array",
"Time",
"objects",
"for",
"future",
"run",
"times",
"based",
"on",
"the",
"current",
"time",
"and",
"the",
"given",
"minutes",
"to",
"look",
"ahead",
"."
] | 4d186042507c1397ee79a5e8fe929cc14008c026 | https://github.com/simplymadeapps/simple_scheduler/blob/4d186042507c1397ee79a5e8fe929cc14008c026/lib/simple_scheduler/task.rb#L67-L82 | train |
simplymadeapps/simple_scheduler | lib/simple_scheduler/future_job.rb | SimpleScheduler.FutureJob.perform | def perform(task_params, scheduled_time)
@task = Task.new(task_params)
@scheduled_time = Time.at(scheduled_time).in_time_zone(@task.time_zone)
raise Expired if expired?
queue_task
end | ruby | def perform(task_params, scheduled_time)
@task = Task.new(task_params)
@scheduled_time = Time.at(scheduled_time).in_time_zone(@task.time_zone)
raise Expired if expired?
queue_task
end | [
"def",
"perform",
"(",
"task_params",
",",
"scheduled_time",
")",
"@task",
"=",
"Task",
".",
"new",
"(",
"task_params",
")",
"@scheduled_time",
"=",
"Time",
".",
"at",
"(",
"scheduled_time",
")",
".",
"in_time_zone",
"(",
"@task",
".",
"time_zone",
")",
"raise",
"Expired",
"if",
"expired?",
"queue_task",
"end"
] | Perform the future job as defined by the task.
@param task_params [Hash] The params from the scheduled task
@param scheduled_time [Integer] The epoch time for when the job was scheduled to be run | [
"Perform",
"the",
"future",
"job",
"as",
"defined",
"by",
"the",
"task",
"."
] | 4d186042507c1397ee79a5e8fe929cc14008c026 | https://github.com/simplymadeapps/simple_scheduler/blob/4d186042507c1397ee79a5e8fe929cc14008c026/lib/simple_scheduler/future_job.rb#L22-L28 | train |
simplymadeapps/simple_scheduler | lib/simple_scheduler/future_job.rb | SimpleScheduler.FutureJob.expire_duration | def expire_duration
split_duration = @task.expires_after.split(".")
duration = split_duration[0].to_i
duration_units = split_duration[1]
duration.send(duration_units)
end | ruby | def expire_duration
split_duration = @task.expires_after.split(".")
duration = split_duration[0].to_i
duration_units = split_duration[1]
duration.send(duration_units)
end | [
"def",
"expire_duration",
"split_duration",
"=",
"@task",
".",
"expires_after",
".",
"split",
"(",
"\".\"",
")",
"duration",
"=",
"split_duration",
"[",
"0",
"]",
".",
"to_i",
"duration_units",
"=",
"split_duration",
"[",
"1",
"]",
"duration",
".",
"send",
"(",
"duration_units",
")",
"end"
] | The duration between the scheduled run time and actual run time that
will cause the job to expire. Expired jobs will not be executed.
@return [ActiveSupport::Duration] | [
"The",
"duration",
"between",
"the",
"scheduled",
"run",
"time",
"and",
"actual",
"run",
"time",
"that",
"will",
"cause",
"the",
"job",
"to",
"expire",
".",
"Expired",
"jobs",
"will",
"not",
"be",
"executed",
"."
] | 4d186042507c1397ee79a5e8fe929cc14008c026 | https://github.com/simplymadeapps/simple_scheduler/blob/4d186042507c1397ee79a5e8fe929cc14008c026/lib/simple_scheduler/future_job.rb#L42-L47 | train |
simplymadeapps/simple_scheduler | lib/simple_scheduler/future_job.rb | SimpleScheduler.FutureJob.expired? | def expired?
return false if @task.expires_after.blank?
expire_duration.from_now(@scheduled_time) < Time.now.in_time_zone(@task.time_zone)
end | ruby | def expired?
return false if @task.expires_after.blank?
expire_duration.from_now(@scheduled_time) < Time.now.in_time_zone(@task.time_zone)
end | [
"def",
"expired?",
"return",
"false",
"if",
"@task",
".",
"expires_after",
".",
"blank?",
"expire_duration",
".",
"from_now",
"(",
"@scheduled_time",
")",
"<",
"Time",
".",
"now",
".",
"in_time_zone",
"(",
"@task",
".",
"time_zone",
")",
"end"
] | Returns whether or not the job has expired based on the time
between the scheduled run time and the current time.
@return [Boolean] | [
"Returns",
"whether",
"or",
"not",
"the",
"job",
"has",
"expired",
"based",
"on",
"the",
"time",
"between",
"the",
"scheduled",
"run",
"time",
"and",
"the",
"current",
"time",
"."
] | 4d186042507c1397ee79a5e8fe929cc14008c026 | https://github.com/simplymadeapps/simple_scheduler/blob/4d186042507c1397ee79a5e8fe929cc14008c026/lib/simple_scheduler/future_job.rb#L52-L56 | train |
simplymadeapps/simple_scheduler | lib/simple_scheduler/future_job.rb | SimpleScheduler.FutureJob.handle_expired_task | def handle_expired_task(exception)
exception.run_time = Time.now.in_time_zone(@task.time_zone)
exception.scheduled_time = @scheduled_time
exception.task = @task
SimpleScheduler.expired_task_blocks.each do |block|
block.call(exception)
end
end | ruby | def handle_expired_task(exception)
exception.run_time = Time.now.in_time_zone(@task.time_zone)
exception.scheduled_time = @scheduled_time
exception.task = @task
SimpleScheduler.expired_task_blocks.each do |block|
block.call(exception)
end
end | [
"def",
"handle_expired_task",
"(",
"exception",
")",
"exception",
".",
"run_time",
"=",
"Time",
".",
"now",
".",
"in_time_zone",
"(",
"@task",
".",
"time_zone",
")",
"exception",
".",
"scheduled_time",
"=",
"@scheduled_time",
"exception",
".",
"task",
"=",
"@task",
"SimpleScheduler",
".",
"expired_task_blocks",
".",
"each",
"do",
"|",
"block",
"|",
"block",
".",
"call",
"(",
"exception",
")",
"end",
"end"
] | Handle the expired task by passing the task and run time information
to a block that can be creating in a Rails initializer file. | [
"Handle",
"the",
"expired",
"task",
"by",
"passing",
"the",
"task",
"and",
"run",
"time",
"information",
"to",
"a",
"block",
"that",
"can",
"be",
"creating",
"in",
"a",
"Rails",
"initializer",
"file",
"."
] | 4d186042507c1397ee79a5e8fe929cc14008c026 | https://github.com/simplymadeapps/simple_scheduler/blob/4d186042507c1397ee79a5e8fe929cc14008c026/lib/simple_scheduler/future_job.rb#L60-L68 | train |
simplymadeapps/simple_scheduler | lib/simple_scheduler/future_job.rb | SimpleScheduler.FutureJob.queue_task | def queue_task
if @task.job_class.instance_method(:perform).arity.zero?
@task.job_class.send(perform_method)
else
@task.job_class.send(perform_method, @scheduled_time.to_i)
end
end | ruby | def queue_task
if @task.job_class.instance_method(:perform).arity.zero?
@task.job_class.send(perform_method)
else
@task.job_class.send(perform_method, @scheduled_time.to_i)
end
end | [
"def",
"queue_task",
"if",
"@task",
".",
"job_class",
".",
"instance_method",
"(",
":perform",
")",
".",
"arity",
".",
"zero?",
"@task",
".",
"job_class",
".",
"send",
"(",
"perform_method",
")",
"else",
"@task",
".",
"job_class",
".",
"send",
"(",
"perform_method",
",",
"@scheduled_time",
".",
"to_i",
")",
"end",
"end"
] | Queue the task with the scheduled time if the job allows. | [
"Queue",
"the",
"task",
"with",
"the",
"scheduled",
"time",
"if",
"the",
"job",
"allows",
"."
] | 4d186042507c1397ee79a5e8fe929cc14008c026 | https://github.com/simplymadeapps/simple_scheduler/blob/4d186042507c1397ee79a5e8fe929cc14008c026/lib/simple_scheduler/future_job.rb#L81-L87 | train |
simplymadeapps/simple_scheduler | lib/simple_scheduler/at.rb | SimpleScheduler.At.parsed_time | def parsed_time
return @parsed_time if @parsed_time
@parsed_time = parsed_day
change_hour = next_hour
# There is no hour 24, so we need to move to the next day
if change_hour == 24
@parsed_time = 1.day.from_now(@parsed_time)
change_hour = 0
end
@parsed_time = @parsed_time.change(hour: change_hour, min: at_min)
# If the parsed time is still before the current time, add an additional day if
# the week day wasn't specified or add an additional week to get the correct time.
@parsed_time += at_wday? ? 1.week : 1.day if now > @parsed_time
@parsed_time
end | ruby | def parsed_time
return @parsed_time if @parsed_time
@parsed_time = parsed_day
change_hour = next_hour
# There is no hour 24, so we need to move to the next day
if change_hour == 24
@parsed_time = 1.day.from_now(@parsed_time)
change_hour = 0
end
@parsed_time = @parsed_time.change(hour: change_hour, min: at_min)
# If the parsed time is still before the current time, add an additional day if
# the week day wasn't specified or add an additional week to get the correct time.
@parsed_time += at_wday? ? 1.week : 1.day if now > @parsed_time
@parsed_time
end | [
"def",
"parsed_time",
"return",
"@parsed_time",
"if",
"@parsed_time",
"@parsed_time",
"=",
"parsed_day",
"change_hour",
"=",
"next_hour",
"# There is no hour 24, so we need to move to the next day",
"if",
"change_hour",
"==",
"24",
"@parsed_time",
"=",
"1",
".",
"day",
".",
"from_now",
"(",
"@parsed_time",
")",
"change_hour",
"=",
"0",
"end",
"@parsed_time",
"=",
"@parsed_time",
".",
"change",
"(",
"hour",
":",
"change_hour",
",",
"min",
":",
"at_min",
")",
"# If the parsed time is still before the current time, add an additional day if",
"# the week day wasn't specified or add an additional week to get the correct time.",
"@parsed_time",
"+=",
"at_wday?",
"?",
"1",
".",
"week",
":",
"1",
".",
"day",
"if",
"now",
">",
"@parsed_time",
"@parsed_time",
"end"
] | Returns the very first time a job should be run for the scheduled task.
@return [Time] | [
"Returns",
"the",
"very",
"first",
"time",
"a",
"job",
"should",
"be",
"run",
"for",
"the",
"scheduled",
"task",
"."
] | 4d186042507c1397ee79a5e8fe929cc14008c026 | https://github.com/simplymadeapps/simple_scheduler/blob/4d186042507c1397ee79a5e8fe929cc14008c026/lib/simple_scheduler/at.rb#L109-L127 | train |
mxenabled/action_subscriber | lib/action_subscriber/dsl.rb | ActionSubscriber.DSL.exchange_names | def exchange_names(*names)
@_exchange_names ||= []
@_exchange_names += names.flatten.map(&:to_s)
if @_exchange_names.empty?
return [ ::ActionSubscriber.config.default_exchange ]
else
return @_exchange_names.compact.uniq
end
end | ruby | def exchange_names(*names)
@_exchange_names ||= []
@_exchange_names += names.flatten.map(&:to_s)
if @_exchange_names.empty?
return [ ::ActionSubscriber.config.default_exchange ]
else
return @_exchange_names.compact.uniq
end
end | [
"def",
"exchange_names",
"(",
"*",
"names",
")",
"@_exchange_names",
"||=",
"[",
"]",
"@_exchange_names",
"+=",
"names",
".",
"flatten",
".",
"map",
"(",
":to_s",
")",
"if",
"@_exchange_names",
".",
"empty?",
"return",
"[",
"::",
"ActionSubscriber",
".",
"config",
".",
"default_exchange",
"]",
"else",
"return",
"@_exchange_names",
".",
"compact",
".",
"uniq",
"end",
"end"
] | Explicitly set the name of the exchange | [
"Explicitly",
"set",
"the",
"name",
"of",
"the",
"exchange"
] | 4bfd11b09b649d06bc5c8734ceb9e8f99211fa0c | https://github.com/mxenabled/action_subscriber/blob/4bfd11b09b649d06bc5c8734ceb9e8f99211fa0c/lib/action_subscriber/dsl.rb#L36-L45 | train |
mxenabled/action_subscriber | lib/action_subscriber/subscribable.rb | ActionSubscriber.Subscribable.queue_name_for_method | def queue_name_for_method(method_name)
return queue_names[method_name] if queue_names[method_name]
queue_name = generate_queue_name(method_name)
queue_for(method_name, queue_name)
return queue_name
end | ruby | def queue_name_for_method(method_name)
return queue_names[method_name] if queue_names[method_name]
queue_name = generate_queue_name(method_name)
queue_for(method_name, queue_name)
return queue_name
end | [
"def",
"queue_name_for_method",
"(",
"method_name",
")",
"return",
"queue_names",
"[",
"method_name",
"]",
"if",
"queue_names",
"[",
"method_name",
"]",
"queue_name",
"=",
"generate_queue_name",
"(",
"method_name",
")",
"queue_for",
"(",
"method_name",
",",
"queue_name",
")",
"return",
"queue_name",
"end"
] | Build the `queue` for a given method.
If the queue name is not set, the queue name is
"local.remote.resoure.action"
Example
"bob.alice.user.created" | [
"Build",
"the",
"queue",
"for",
"a",
"given",
"method",
"."
] | 4bfd11b09b649d06bc5c8734ceb9e8f99211fa0c | https://github.com/mxenabled/action_subscriber/blob/4bfd11b09b649d06bc5c8734ceb9e8f99211fa0c/lib/action_subscriber/subscribable.rb#L57-L63 | train |
mxenabled/action_subscriber | lib/action_subscriber/subscribable.rb | ActionSubscriber.Subscribable.routing_key_name_for_method | def routing_key_name_for_method(method_name)
return routing_key_names[method_name] if routing_key_names[method_name]
routing_key_name = generate_routing_key_name(method_name)
routing_key_for(method_name, routing_key_name)
return routing_key_name
end | ruby | def routing_key_name_for_method(method_name)
return routing_key_names[method_name] if routing_key_names[method_name]
routing_key_name = generate_routing_key_name(method_name)
routing_key_for(method_name, routing_key_name)
return routing_key_name
end | [
"def",
"routing_key_name_for_method",
"(",
"method_name",
")",
"return",
"routing_key_names",
"[",
"method_name",
"]",
"if",
"routing_key_names",
"[",
"method_name",
"]",
"routing_key_name",
"=",
"generate_routing_key_name",
"(",
"method_name",
")",
"routing_key_for",
"(",
"method_name",
",",
"routing_key_name",
")",
"return",
"routing_key_name",
"end"
] | Build the `routing_key` for a given method.
If the routing_key name is not set, the routing_key name is
"remote.resoure.action"
Example
"amigo.user.created" | [
"Build",
"the",
"routing_key",
"for",
"a",
"given",
"method",
"."
] | 4bfd11b09b649d06bc5c8734ceb9e8f99211fa0c | https://github.com/mxenabled/action_subscriber/blob/4bfd11b09b649d06bc5c8734ceb9e8f99211fa0c/lib/action_subscriber/subscribable.rb#L80-L86 | train |
DavidEGrayson/ruby_ecdsa | lib/ecdsa/point.rb | ECDSA.Point.double | def double
return self if infinity?
gamma = field.mod((3 * x * x + @group.param_a) * field.inverse(2 * y))
new_x = field.mod(gamma * gamma - 2 * x)
new_y = field.mod(gamma * (x - new_x) - y)
self.class.new(group, new_x, new_y)
end | ruby | def double
return self if infinity?
gamma = field.mod((3 * x * x + @group.param_a) * field.inverse(2 * y))
new_x = field.mod(gamma * gamma - 2 * x)
new_y = field.mod(gamma * (x - new_x) - y)
self.class.new(group, new_x, new_y)
end | [
"def",
"double",
"return",
"self",
"if",
"infinity?",
"gamma",
"=",
"field",
".",
"mod",
"(",
"(",
"3",
"*",
"x",
"*",
"x",
"+",
"@group",
".",
"param_a",
")",
"*",
"field",
".",
"inverse",
"(",
"2",
"*",
"y",
")",
")",
"new_x",
"=",
"field",
".",
"mod",
"(",
"gamma",
"*",
"gamma",
"-",
"2",
"*",
"x",
")",
"new_y",
"=",
"field",
".",
"mod",
"(",
"gamma",
"*",
"(",
"x",
"-",
"new_x",
")",
"-",
"y",
")",
"self",
".",
"class",
".",
"new",
"(",
"group",
",",
"new_x",
",",
"new_y",
")",
"end"
] | Returns the point added to itself.
This algorithm is defined in
[SEC1](http://www.secg.org/collateral/sec1_final.pdf), Section 2.2.1,
Rule 5.
@return (Point) | [
"Returns",
"the",
"point",
"added",
"to",
"itself",
"."
] | 2216043b38170b9603c05bf1d4e43e184fc6181e | https://github.com/DavidEGrayson/ruby_ecdsa/blob/2216043b38170b9603c05bf1d4e43e184fc6181e/lib/ecdsa/point.rb#L104-L110 | train |
DavidEGrayson/ruby_ecdsa | lib/ecdsa/point.rb | ECDSA.Point.multiply_by_scalar | def multiply_by_scalar(i)
raise ArgumentError, 'Scalar is not an integer.' if !i.is_a?(Integer)
raise ArgumentError, 'Scalar is negative.' if i < 0
result = group.infinity
v = self
while i > 0
result = result.add_to_point(v) if i.odd?
v = v.double
i >>= 1
end
result
end | ruby | def multiply_by_scalar(i)
raise ArgumentError, 'Scalar is not an integer.' if !i.is_a?(Integer)
raise ArgumentError, 'Scalar is negative.' if i < 0
result = group.infinity
v = self
while i > 0
result = result.add_to_point(v) if i.odd?
v = v.double
i >>= 1
end
result
end | [
"def",
"multiply_by_scalar",
"(",
"i",
")",
"raise",
"ArgumentError",
",",
"'Scalar is not an integer.'",
"if",
"!",
"i",
".",
"is_a?",
"(",
"Integer",
")",
"raise",
"ArgumentError",
",",
"'Scalar is negative.'",
"if",
"i",
"<",
"0",
"result",
"=",
"group",
".",
"infinity",
"v",
"=",
"self",
"while",
"i",
">",
"0",
"result",
"=",
"result",
".",
"add_to_point",
"(",
"v",
")",
"if",
"i",
".",
"odd?",
"v",
"=",
"v",
".",
"double",
"i",
">>=",
"1",
"end",
"result",
"end"
] | Returns the point multiplied by a non-negative integer.
@param i (Integer)
@return (Point) | [
"Returns",
"the",
"point",
"multiplied",
"by",
"a",
"non",
"-",
"negative",
"integer",
"."
] | 2216043b38170b9603c05bf1d4e43e184fc6181e | https://github.com/DavidEGrayson/ruby_ecdsa/blob/2216043b38170b9603c05bf1d4e43e184fc6181e/lib/ecdsa/point.rb#L116-L127 | train |
DavidEGrayson/ruby_ecdsa | lib/ecdsa/prime_field.rb | ECDSA.PrimeField.square_roots | def square_roots(n)
raise ArgumentError, "Not a member of the field: #{n}." if !include?(n)
case
when prime == 2 then [n]
when (prime % 4) == 3 then square_roots_for_p_3_mod_4(n)
when (prime % 8) == 5 then square_roots_for_p_5_mod_8(n)
else square_roots_default(n)
end
end | ruby | def square_roots(n)
raise ArgumentError, "Not a member of the field: #{n}." if !include?(n)
case
when prime == 2 then [n]
when (prime % 4) == 3 then square_roots_for_p_3_mod_4(n)
when (prime % 8) == 5 then square_roots_for_p_5_mod_8(n)
else square_roots_default(n)
end
end | [
"def",
"square_roots",
"(",
"n",
")",
"raise",
"ArgumentError",
",",
"\"Not a member of the field: #{n}.\"",
"if",
"!",
"include?",
"(",
"n",
")",
"case",
"when",
"prime",
"==",
"2",
"then",
"[",
"n",
"]",
"when",
"(",
"prime",
"%",
"4",
")",
"==",
"3",
"then",
"square_roots_for_p_3_mod_4",
"(",
"n",
")",
"when",
"(",
"prime",
"%",
"8",
")",
"==",
"5",
"then",
"square_roots_for_p_5_mod_8",
"(",
"n",
")",
"else",
"square_roots_default",
"(",
"n",
")",
"end",
"end"
] | Finds all possible square roots of the given field element.
@param n (Integer)
@return (Array) A sorted array of numbers whose square is equal to `n`. | [
"Finds",
"all",
"possible",
"square",
"roots",
"of",
"the",
"given",
"field",
"element",
"."
] | 2216043b38170b9603c05bf1d4e43e184fc6181e | https://github.com/DavidEGrayson/ruby_ecdsa/blob/2216043b38170b9603c05bf1d4e43e184fc6181e/lib/ecdsa/prime_field.rb#L94-L102 | train |
jstrait/wavefile | lib/wavefile/writer.rb | WaveFile.Writer.write_header | def write_header(sample_frame_count)
extensible = @format.channels > 2 ||
(@format.sample_format == :pcm && @format.bits_per_sample != 8 && @format.bits_per_sample != 16) ||
(@format.channels == 1 && @format.speaker_mapping != [:front_center]) ||
(@format.channels == 2 && @format.speaker_mapping != [:front_left, :front_right])
format_code = extensible ? :extensible : @format.sample_format
requires_fact_chunk = (format_code != :pcm)
sample_data_byte_count = sample_frame_count * @format.block_align
riff_chunk_size = CANONICAL_HEADER_BYTE_LENGTH[format_code] + sample_data_byte_count
if sample_data_byte_count.odd?
riff_chunk_size += 1
end
# Write the header for the RIFF chunk
header = CHUNK_IDS[:riff]
header += [riff_chunk_size].pack(UNSIGNED_INT_32)
header += WAVEFILE_FORMAT_CODE
# Write the format chunk
header += CHUNK_IDS[:format]
header += [FORMAT_CHUNK_BYTE_LENGTH[format_code]].pack(UNSIGNED_INT_32)
header += [FORMAT_CODES[format_code]].pack(UNSIGNED_INT_16)
header += [@format.channels].pack(UNSIGNED_INT_16)
header += [@format.sample_rate].pack(UNSIGNED_INT_32)
header += [@format.byte_rate].pack(UNSIGNED_INT_32)
header += [@format.block_align].pack(UNSIGNED_INT_16)
header += [@format.bits_per_sample].pack(UNSIGNED_INT_16)
if format_code == :float
header += [0].pack(UNSIGNED_INT_16)
end
if extensible
header += [22].pack(UNSIGNED_INT_16)
header += [@format.bits_per_sample].pack(UNSIGNED_INT_16)
header += [pack_speaker_mapping(@format.speaker_mapping)].pack(UNSIGNED_INT_32)
if @format.sample_format == :pcm
format_guid = WaveFile::SUB_FORMAT_GUID_PCM
elsif @format.sample_format == :float
format_guid = WaveFile::SUB_FORMAT_GUID_FLOAT
end
header += format_guid
end
# Write the FACT chunk, if necessary
if requires_fact_chunk
header += CHUNK_IDS[:fact]
header += [4].pack(UNSIGNED_INT_32)
header += [sample_frame_count].pack(UNSIGNED_INT_32)
end
# Write the header for the data chunk
header += CHUNK_IDS[:data]
header += [sample_data_byte_count].pack(UNSIGNED_INT_32)
@io.write(header)
end | ruby | def write_header(sample_frame_count)
extensible = @format.channels > 2 ||
(@format.sample_format == :pcm && @format.bits_per_sample != 8 && @format.bits_per_sample != 16) ||
(@format.channels == 1 && @format.speaker_mapping != [:front_center]) ||
(@format.channels == 2 && @format.speaker_mapping != [:front_left, :front_right])
format_code = extensible ? :extensible : @format.sample_format
requires_fact_chunk = (format_code != :pcm)
sample_data_byte_count = sample_frame_count * @format.block_align
riff_chunk_size = CANONICAL_HEADER_BYTE_LENGTH[format_code] + sample_data_byte_count
if sample_data_byte_count.odd?
riff_chunk_size += 1
end
# Write the header for the RIFF chunk
header = CHUNK_IDS[:riff]
header += [riff_chunk_size].pack(UNSIGNED_INT_32)
header += WAVEFILE_FORMAT_CODE
# Write the format chunk
header += CHUNK_IDS[:format]
header += [FORMAT_CHUNK_BYTE_LENGTH[format_code]].pack(UNSIGNED_INT_32)
header += [FORMAT_CODES[format_code]].pack(UNSIGNED_INT_16)
header += [@format.channels].pack(UNSIGNED_INT_16)
header += [@format.sample_rate].pack(UNSIGNED_INT_32)
header += [@format.byte_rate].pack(UNSIGNED_INT_32)
header += [@format.block_align].pack(UNSIGNED_INT_16)
header += [@format.bits_per_sample].pack(UNSIGNED_INT_16)
if format_code == :float
header += [0].pack(UNSIGNED_INT_16)
end
if extensible
header += [22].pack(UNSIGNED_INT_16)
header += [@format.bits_per_sample].pack(UNSIGNED_INT_16)
header += [pack_speaker_mapping(@format.speaker_mapping)].pack(UNSIGNED_INT_32)
if @format.sample_format == :pcm
format_guid = WaveFile::SUB_FORMAT_GUID_PCM
elsif @format.sample_format == :float
format_guid = WaveFile::SUB_FORMAT_GUID_FLOAT
end
header += format_guid
end
# Write the FACT chunk, if necessary
if requires_fact_chunk
header += CHUNK_IDS[:fact]
header += [4].pack(UNSIGNED_INT_32)
header += [sample_frame_count].pack(UNSIGNED_INT_32)
end
# Write the header for the data chunk
header += CHUNK_IDS[:data]
header += [sample_data_byte_count].pack(UNSIGNED_INT_32)
@io.write(header)
end | [
"def",
"write_header",
"(",
"sample_frame_count",
")",
"extensible",
"=",
"@format",
".",
"channels",
">",
"2",
"||",
"(",
"@format",
".",
"sample_format",
"==",
":pcm",
"&&",
"@format",
".",
"bits_per_sample",
"!=",
"8",
"&&",
"@format",
".",
"bits_per_sample",
"!=",
"16",
")",
"||",
"(",
"@format",
".",
"channels",
"==",
"1",
"&&",
"@format",
".",
"speaker_mapping",
"!=",
"[",
":front_center",
"]",
")",
"||",
"(",
"@format",
".",
"channels",
"==",
"2",
"&&",
"@format",
".",
"speaker_mapping",
"!=",
"[",
":front_left",
",",
":front_right",
"]",
")",
"format_code",
"=",
"extensible",
"?",
":extensible",
":",
"@format",
".",
"sample_format",
"requires_fact_chunk",
"=",
"(",
"format_code",
"!=",
":pcm",
")",
"sample_data_byte_count",
"=",
"sample_frame_count",
"*",
"@format",
".",
"block_align",
"riff_chunk_size",
"=",
"CANONICAL_HEADER_BYTE_LENGTH",
"[",
"format_code",
"]",
"+",
"sample_data_byte_count",
"if",
"sample_data_byte_count",
".",
"odd?",
"riff_chunk_size",
"+=",
"1",
"end",
"# Write the header for the RIFF chunk",
"header",
"=",
"CHUNK_IDS",
"[",
":riff",
"]",
"header",
"+=",
"[",
"riff_chunk_size",
"]",
".",
"pack",
"(",
"UNSIGNED_INT_32",
")",
"header",
"+=",
"WAVEFILE_FORMAT_CODE",
"# Write the format chunk",
"header",
"+=",
"CHUNK_IDS",
"[",
":format",
"]",
"header",
"+=",
"[",
"FORMAT_CHUNK_BYTE_LENGTH",
"[",
"format_code",
"]",
"]",
".",
"pack",
"(",
"UNSIGNED_INT_32",
")",
"header",
"+=",
"[",
"FORMAT_CODES",
"[",
"format_code",
"]",
"]",
".",
"pack",
"(",
"UNSIGNED_INT_16",
")",
"header",
"+=",
"[",
"@format",
".",
"channels",
"]",
".",
"pack",
"(",
"UNSIGNED_INT_16",
")",
"header",
"+=",
"[",
"@format",
".",
"sample_rate",
"]",
".",
"pack",
"(",
"UNSIGNED_INT_32",
")",
"header",
"+=",
"[",
"@format",
".",
"byte_rate",
"]",
".",
"pack",
"(",
"UNSIGNED_INT_32",
")",
"header",
"+=",
"[",
"@format",
".",
"block_align",
"]",
".",
"pack",
"(",
"UNSIGNED_INT_16",
")",
"header",
"+=",
"[",
"@format",
".",
"bits_per_sample",
"]",
".",
"pack",
"(",
"UNSIGNED_INT_16",
")",
"if",
"format_code",
"==",
":float",
"header",
"+=",
"[",
"0",
"]",
".",
"pack",
"(",
"UNSIGNED_INT_16",
")",
"end",
"if",
"extensible",
"header",
"+=",
"[",
"22",
"]",
".",
"pack",
"(",
"UNSIGNED_INT_16",
")",
"header",
"+=",
"[",
"@format",
".",
"bits_per_sample",
"]",
".",
"pack",
"(",
"UNSIGNED_INT_16",
")",
"header",
"+=",
"[",
"pack_speaker_mapping",
"(",
"@format",
".",
"speaker_mapping",
")",
"]",
".",
"pack",
"(",
"UNSIGNED_INT_32",
")",
"if",
"@format",
".",
"sample_format",
"==",
":pcm",
"format_guid",
"=",
"WaveFile",
"::",
"SUB_FORMAT_GUID_PCM",
"elsif",
"@format",
".",
"sample_format",
"==",
":float",
"format_guid",
"=",
"WaveFile",
"::",
"SUB_FORMAT_GUID_FLOAT",
"end",
"header",
"+=",
"format_guid",
"end",
"# Write the FACT chunk, if necessary",
"if",
"requires_fact_chunk",
"header",
"+=",
"CHUNK_IDS",
"[",
":fact",
"]",
"header",
"+=",
"[",
"4",
"]",
".",
"pack",
"(",
"UNSIGNED_INT_32",
")",
"header",
"+=",
"[",
"sample_frame_count",
"]",
".",
"pack",
"(",
"UNSIGNED_INT_32",
")",
"end",
"# Write the header for the data chunk",
"header",
"+=",
"CHUNK_IDS",
"[",
":data",
"]",
"header",
"+=",
"[",
"sample_data_byte_count",
"]",
".",
"pack",
"(",
"UNSIGNED_INT_32",
")",
"@io",
".",
"write",
"(",
"header",
")",
"end"
] | Internal
Writes the RIFF chunk header, format chunk, and the header for the data chunk. After this
method is called the file will be "queued up" and ready for writing actual sample data. | [
"Internal",
"Writes",
"the",
"RIFF",
"chunk",
"header",
"format",
"chunk",
"and",
"the",
"header",
"for",
"the",
"data",
"chunk",
".",
"After",
"this",
"method",
"is",
"called",
"the",
"file",
"will",
"be",
"queued",
"up",
"and",
"ready",
"for",
"writing",
"actual",
"sample",
"data",
"."
] | 3efe8099ee996dfcf9d3b2e656aa9ec4fa983222 | https://github.com/jstrait/wavefile/blob/3efe8099ee996dfcf9d3b2e656aa9ec4fa983222/lib/wavefile/writer.rb#L283-L341 | train |
namick/obfuscate_id | lib/obfuscate_id.rb | ObfuscateId.ClassMethods.obfuscate_id_default_spin | def obfuscate_id_default_spin
alphabet = Array("a".."z")
number = name.split("").collect do |char|
alphabet.index(char)
end
number.shift(12).join.to_i
end | ruby | def obfuscate_id_default_spin
alphabet = Array("a".."z")
number = name.split("").collect do |char|
alphabet.index(char)
end
number.shift(12).join.to_i
end | [
"def",
"obfuscate_id_default_spin",
"alphabet",
"=",
"Array",
"(",
"\"a\"",
"..",
"\"z\"",
")",
"number",
"=",
"name",
".",
"split",
"(",
"\"\"",
")",
".",
"collect",
"do",
"|",
"char",
"|",
"alphabet",
".",
"index",
"(",
"char",
")",
"end",
"number",
".",
"shift",
"(",
"12",
")",
".",
"join",
".",
"to_i",
"end"
] | Generate a default spin from the Model name
This makes it easy to drop obfuscate_id onto any model
and produce different obfuscated ids for different models | [
"Generate",
"a",
"default",
"spin",
"from",
"the",
"Model",
"name",
"This",
"makes",
"it",
"easy",
"to",
"drop",
"obfuscate_id",
"onto",
"any",
"model",
"and",
"produce",
"different",
"obfuscated",
"ids",
"for",
"different",
"models"
] | bd3ee63bbe3bf2de93023947478831f4ee01a1bf | https://github.com/namick/obfuscate_id/blob/bd3ee63bbe3bf2de93023947478831f4ee01a1bf/lib/obfuscate_id.rb#L44-L51 | train |
praxis/praxis | lib/praxis/validation_handler.rb | Praxis.ValidationHandler.handle! | def handle!(summary:, request:, stage:, errors: nil, exception: nil, **opts)
documentation = Docs::LinkBuilder.instance.for_request request
Responses::ValidationError.new(summary: summary, errors: errors, exception: exception, documentation: documentation, **opts)
end | ruby | def handle!(summary:, request:, stage:, errors: nil, exception: nil, **opts)
documentation = Docs::LinkBuilder.instance.for_request request
Responses::ValidationError.new(summary: summary, errors: errors, exception: exception, documentation: documentation, **opts)
end | [
"def",
"handle!",
"(",
"summary",
":",
",",
"request",
":",
",",
"stage",
":",
",",
"errors",
":",
"nil",
",",
"exception",
":",
"nil",
",",
"**",
"opts",
")",
"documentation",
"=",
"Docs",
"::",
"LinkBuilder",
".",
"instance",
".",
"for_request",
"request",
"Responses",
"::",
"ValidationError",
".",
"new",
"(",
"summary",
":",
"summary",
",",
"errors",
":",
"errors",
",",
"exception",
":",
"exception",
",",
"documentation",
":",
"documentation",
",",
"**",
"opts",
")",
"end"
] | Should return the Response to send back | [
"Should",
"return",
"the",
"Response",
"to",
"send",
"back"
] | 37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635 | https://github.com/praxis/praxis/blob/37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635/lib/praxis/validation_handler.rb#L5-L8 | train |
praxis/praxis | lib/praxis/response.rb | Praxis.Response.validate | def validate(action, validate_body: false)
return if response_name == :validation_error
unless (response_definition = action.responses[response_name])
raise Exceptions::Validation, "Attempting to return a response with name #{response_name} " \
"but no response definition with that name can be found"
end
response_definition.validate(self, validate_body: validate_body)
end | ruby | def validate(action, validate_body: false)
return if response_name == :validation_error
unless (response_definition = action.responses[response_name])
raise Exceptions::Validation, "Attempting to return a response with name #{response_name} " \
"but no response definition with that name can be found"
end
response_definition.validate(self, validate_body: validate_body)
end | [
"def",
"validate",
"(",
"action",
",",
"validate_body",
":",
"false",
")",
"return",
"if",
"response_name",
"==",
":validation_error",
"unless",
"(",
"response_definition",
"=",
"action",
".",
"responses",
"[",
"response_name",
"]",
")",
"raise",
"Exceptions",
"::",
"Validation",
",",
"\"Attempting to return a response with name #{response_name} \"",
"\"but no response definition with that name can be found\"",
"end",
"response_definition",
".",
"validate",
"(",
"self",
",",
"validate_body",
":",
"validate_body",
")",
"end"
] | Validates the response
@param [Object] action | [
"Validates",
"the",
"response"
] | 37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635 | https://github.com/praxis/praxis/blob/37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635/lib/praxis/response.rb#L116-L125 | train |
praxis/praxis | lib/praxis/config.rb | Praxis.Config.define | def define(key=nil, type=Attributor::Struct, **opts, &block)
if key.nil? && type != Attributor::Struct
raise Exceptions::InvalidConfiguration.new(
"You cannot define the top level configuration with a non-Struct type. Got: #{type.inspect}"
)
end
case key
when String, Symbol, NilClass
top = key.nil? ? @attribute : @attribute.attributes[key]
if top #key defined...redefine
unless type == Attributor::Struct && top.type < Attributor::Struct
raise Exceptions::InvalidConfiguration.new(
"Incompatible type received for extending configuration key [#{key}]. Got type #{type.name}"
)
end
top.options.merge!(opts)
top.type.attributes(opts, &block)
else
@attribute.attributes[key] = Attributor::Attribute.new(type, opts, &block)
end
else
raise Exceptions::InvalidConfiguration.new(
"Defining a configuration key requires a String or a Symbol key. Got: #{key.inspect}"
)
end
end | ruby | def define(key=nil, type=Attributor::Struct, **opts, &block)
if key.nil? && type != Attributor::Struct
raise Exceptions::InvalidConfiguration.new(
"You cannot define the top level configuration with a non-Struct type. Got: #{type.inspect}"
)
end
case key
when String, Symbol, NilClass
top = key.nil? ? @attribute : @attribute.attributes[key]
if top #key defined...redefine
unless type == Attributor::Struct && top.type < Attributor::Struct
raise Exceptions::InvalidConfiguration.new(
"Incompatible type received for extending configuration key [#{key}]. Got type #{type.name}"
)
end
top.options.merge!(opts)
top.type.attributes(opts, &block)
else
@attribute.attributes[key] = Attributor::Attribute.new(type, opts, &block)
end
else
raise Exceptions::InvalidConfiguration.new(
"Defining a configuration key requires a String or a Symbol key. Got: #{key.inspect}"
)
end
end | [
"def",
"define",
"(",
"key",
"=",
"nil",
",",
"type",
"=",
"Attributor",
"::",
"Struct",
",",
"**",
"opts",
",",
"&",
"block",
")",
"if",
"key",
".",
"nil?",
"&&",
"type",
"!=",
"Attributor",
"::",
"Struct",
"raise",
"Exceptions",
"::",
"InvalidConfiguration",
".",
"new",
"(",
"\"You cannot define the top level configuration with a non-Struct type. Got: #{type.inspect}\"",
")",
"end",
"case",
"key",
"when",
"String",
",",
"Symbol",
",",
"NilClass",
"top",
"=",
"key",
".",
"nil?",
"?",
"@attribute",
":",
"@attribute",
".",
"attributes",
"[",
"key",
"]",
"if",
"top",
"#key defined...redefine",
"unless",
"type",
"==",
"Attributor",
"::",
"Struct",
"&&",
"top",
".",
"type",
"<",
"Attributor",
"::",
"Struct",
"raise",
"Exceptions",
"::",
"InvalidConfiguration",
".",
"new",
"(",
"\"Incompatible type received for extending configuration key [#{key}]. Got type #{type.name}\"",
")",
"end",
"top",
".",
"options",
".",
"merge!",
"(",
"opts",
")",
"top",
".",
"type",
".",
"attributes",
"(",
"opts",
",",
"block",
")",
"else",
"@attribute",
".",
"attributes",
"[",
"key",
"]",
"=",
"Attributor",
"::",
"Attribute",
".",
"new",
"(",
"type",
",",
"opts",
",",
"block",
")",
"end",
"else",
"raise",
"Exceptions",
"::",
"InvalidConfiguration",
".",
"new",
"(",
"\"Defining a configuration key requires a String or a Symbol key. Got: #{key.inspect}\"",
")",
"end",
"end"
] | You can define the configuration in different ways
Add a key to the top struct
define do
attribute :added_to_top, String
end
Add a key to the top struct (that is a struct itself)
define do
attribute :app do
attribute :one String
end
end
Which you could expand too in this way
define do
attribute :app do
attribute :two String
end
end
...or using this way too (equivalent)
define(:app) do
attribute :two, String
end
You can also define a key to be a non-Struct type
define :app, Attributor::Hash | [
"You",
"can",
"define",
"the",
"configuration",
"in",
"different",
"ways"
] | 37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635 | https://github.com/praxis/praxis/blob/37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635/lib/praxis/config.rb#L39-L67 | train |
praxis/praxis | lib/praxis/multipart/part.rb | Praxis.MultipartPart.derive_content_type | def derive_content_type(handler_name)
possible_values = if self.content_type.match 'text/plain'
_, content_type_attribute = self.headers_attribute && self.headers_attribute.attributes.find { |k,v| k.to_s =~ /^content[-_]{1}type$/i }
if content_type_attribute && content_type_attribute.options.key?(:values)
content_type_attribute.options[:values]
else
[]
end
else
[self.content_type]
end
# generic default encoding is the best we can do
if possible_values.empty?
return MediaTypeIdentifier.load("application/#{handler_name}")
end
# if any defined value match the preferred handler_name, return it
possible_values.each do |ct|
mti = MediaTypeIdentifier.load(ct)
return mti if mti.handler_name == handler_name
end
# otherwise, pick the first
pick = MediaTypeIdentifier.load(possible_values.first)
# and return that one if it already corresponds to a registered handler
# otherwise, add the encoding
if Praxis::Application.instance.handlers.include?(pick.handler_name)
return pick
else
return pick + handler_name
end
end | ruby | def derive_content_type(handler_name)
possible_values = if self.content_type.match 'text/plain'
_, content_type_attribute = self.headers_attribute && self.headers_attribute.attributes.find { |k,v| k.to_s =~ /^content[-_]{1}type$/i }
if content_type_attribute && content_type_attribute.options.key?(:values)
content_type_attribute.options[:values]
else
[]
end
else
[self.content_type]
end
# generic default encoding is the best we can do
if possible_values.empty?
return MediaTypeIdentifier.load("application/#{handler_name}")
end
# if any defined value match the preferred handler_name, return it
possible_values.each do |ct|
mti = MediaTypeIdentifier.load(ct)
return mti if mti.handler_name == handler_name
end
# otherwise, pick the first
pick = MediaTypeIdentifier.load(possible_values.first)
# and return that one if it already corresponds to a registered handler
# otherwise, add the encoding
if Praxis::Application.instance.handlers.include?(pick.handler_name)
return pick
else
return pick + handler_name
end
end | [
"def",
"derive_content_type",
"(",
"handler_name",
")",
"possible_values",
"=",
"if",
"self",
".",
"content_type",
".",
"match",
"'text/plain'",
"_",
",",
"content_type_attribute",
"=",
"self",
".",
"headers_attribute",
"&&",
"self",
".",
"headers_attribute",
".",
"attributes",
".",
"find",
"{",
"|",
"k",
",",
"v",
"|",
"k",
".",
"to_s",
"=~",
"/",
"/i",
"}",
"if",
"content_type_attribute",
"&&",
"content_type_attribute",
".",
"options",
".",
"key?",
"(",
":values",
")",
"content_type_attribute",
".",
"options",
"[",
":values",
"]",
"else",
"[",
"]",
"end",
"else",
"[",
"self",
".",
"content_type",
"]",
"end",
"# generic default encoding is the best we can do",
"if",
"possible_values",
".",
"empty?",
"return",
"MediaTypeIdentifier",
".",
"load",
"(",
"\"application/#{handler_name}\"",
")",
"end",
"# if any defined value match the preferred handler_name, return it",
"possible_values",
".",
"each",
"do",
"|",
"ct",
"|",
"mti",
"=",
"MediaTypeIdentifier",
".",
"load",
"(",
"ct",
")",
"return",
"mti",
"if",
"mti",
".",
"handler_name",
"==",
"handler_name",
"end",
"# otherwise, pick the first",
"pick",
"=",
"MediaTypeIdentifier",
".",
"load",
"(",
"possible_values",
".",
"first",
")",
"# and return that one if it already corresponds to a registered handler",
"# otherwise, add the encoding",
"if",
"Praxis",
"::",
"Application",
".",
"instance",
".",
"handlers",
".",
"include?",
"(",
"pick",
".",
"handler_name",
")",
"return",
"pick",
"else",
"return",
"pick",
"+",
"handler_name",
"end",
"end"
] | Determine an appropriate default content_type for this part given
the preferred handler_name, if possible.
Considers any pre-defined set of values on the content_type attributge
of the headers. | [
"Determine",
"an",
"appropriate",
"default",
"content_type",
"for",
"this",
"part",
"given",
"the",
"preferred",
"handler_name",
"if",
"possible",
"."
] | 37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635 | https://github.com/praxis/praxis/blob/37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635/lib/praxis/multipart/part.rb#L224-L258 | train |
praxis/praxis | lib/praxis/action_definition.rb | Praxis.ActionDefinition.precomputed_header_keys_for_rack | def precomputed_header_keys_for_rack
@precomputed_header_keys_for_rack ||= begin
@headers.attributes.keys.each_with_object(Hash.new) do |key,hash|
name = key.to_s
name = "HTTP_#{name.gsub('-','_').upcase}" unless ( name == "CONTENT_TYPE" || name == "CONTENT_LENGTH" )
hash[name] = key
end
end
end | ruby | def precomputed_header_keys_for_rack
@precomputed_header_keys_for_rack ||= begin
@headers.attributes.keys.each_with_object(Hash.new) do |key,hash|
name = key.to_s
name = "HTTP_#{name.gsub('-','_').upcase}" unless ( name == "CONTENT_TYPE" || name == "CONTENT_LENGTH" )
hash[name] = key
end
end
end | [
"def",
"precomputed_header_keys_for_rack",
"@precomputed_header_keys_for_rack",
"||=",
"begin",
"@headers",
".",
"attributes",
".",
"keys",
".",
"each_with_object",
"(",
"Hash",
".",
"new",
")",
"do",
"|",
"key",
",",
"hash",
"|",
"name",
"=",
"key",
".",
"to_s",
"name",
"=",
"\"HTTP_#{name.gsub('-','_').upcase}\"",
"unless",
"(",
"name",
"==",
"\"CONTENT_TYPE\"",
"||",
"name",
"==",
"\"CONTENT_LENGTH\"",
")",
"hash",
"[",
"name",
"]",
"=",
"key",
"end",
"end",
"end"
] | Good optimization to avoid creating lots of strings and comparisons
on a per-request basis.
However, this is hacky, as it is rack-specific, and does not really belong here | [
"Good",
"optimization",
"to",
"avoid",
"creating",
"lots",
"of",
"strings",
"and",
"comparisons",
"on",
"a",
"per",
"-",
"request",
"basis",
".",
"However",
"this",
"is",
"hacky",
"as",
"it",
"is",
"rack",
"-",
"specific",
"and",
"does",
"not",
"really",
"belong",
"here"
] | 37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635 | https://github.com/praxis/praxis/blob/37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635/lib/praxis/action_definition.rb#L168-L176 | train |
praxis/praxis | lib/praxis/action_definition.rb | Praxis.ActionDefinition.derive_content_type | def derive_content_type(example, handler_name)
# MultipartArrays *must* use the provided content_type
if example.kind_of? Praxis::Types::MultipartArray
return MediaTypeIdentifier.load(example.content_type)
end
_, content_type_attribute = self.headers && self.headers.attributes.find { |k,v| k.to_s =~ /^content[-_]{1}type$/i }
if content_type_attribute && content_type_attribute.options.key?(:values)
# if any defined value match the preferred handler_name, return it
content_type_attribute.options[:values].each do |ct|
mti = MediaTypeIdentifier.load(ct)
return mti if mti.handler_name == handler_name
end
# otherwise, pick the first
pick = MediaTypeIdentifier.load(content_type_attribute.options[:values].first)
# and return that one if it already corresponds to a registered handler
# otherwise, add the encoding
if Praxis::Application.instance.handlers.include?(pick.handler_name)
return pick
else
return pick + handler_name
end
end
# generic default encoding
MediaTypeIdentifier.load("application/#{handler_name}")
end | ruby | def derive_content_type(example, handler_name)
# MultipartArrays *must* use the provided content_type
if example.kind_of? Praxis::Types::MultipartArray
return MediaTypeIdentifier.load(example.content_type)
end
_, content_type_attribute = self.headers && self.headers.attributes.find { |k,v| k.to_s =~ /^content[-_]{1}type$/i }
if content_type_attribute && content_type_attribute.options.key?(:values)
# if any defined value match the preferred handler_name, return it
content_type_attribute.options[:values].each do |ct|
mti = MediaTypeIdentifier.load(ct)
return mti if mti.handler_name == handler_name
end
# otherwise, pick the first
pick = MediaTypeIdentifier.load(content_type_attribute.options[:values].first)
# and return that one if it already corresponds to a registered handler
# otherwise, add the encoding
if Praxis::Application.instance.handlers.include?(pick.handler_name)
return pick
else
return pick + handler_name
end
end
# generic default encoding
MediaTypeIdentifier.load("application/#{handler_name}")
end | [
"def",
"derive_content_type",
"(",
"example",
",",
"handler_name",
")",
"# MultipartArrays *must* use the provided content_type",
"if",
"example",
".",
"kind_of?",
"Praxis",
"::",
"Types",
"::",
"MultipartArray",
"return",
"MediaTypeIdentifier",
".",
"load",
"(",
"example",
".",
"content_type",
")",
"end",
"_",
",",
"content_type_attribute",
"=",
"self",
".",
"headers",
"&&",
"self",
".",
"headers",
".",
"attributes",
".",
"find",
"{",
"|",
"k",
",",
"v",
"|",
"k",
".",
"to_s",
"=~",
"/",
"/i",
"}",
"if",
"content_type_attribute",
"&&",
"content_type_attribute",
".",
"options",
".",
"key?",
"(",
":values",
")",
"# if any defined value match the preferred handler_name, return it",
"content_type_attribute",
".",
"options",
"[",
":values",
"]",
".",
"each",
"do",
"|",
"ct",
"|",
"mti",
"=",
"MediaTypeIdentifier",
".",
"load",
"(",
"ct",
")",
"return",
"mti",
"if",
"mti",
".",
"handler_name",
"==",
"handler_name",
"end",
"# otherwise, pick the first",
"pick",
"=",
"MediaTypeIdentifier",
".",
"load",
"(",
"content_type_attribute",
".",
"options",
"[",
":values",
"]",
".",
"first",
")",
"# and return that one if it already corresponds to a registered handler",
"# otherwise, add the encoding",
"if",
"Praxis",
"::",
"Application",
".",
"instance",
".",
"handlers",
".",
"include?",
"(",
"pick",
".",
"handler_name",
")",
"return",
"pick",
"else",
"return",
"pick",
"+",
"handler_name",
"end",
"end",
"# generic default encoding",
"MediaTypeIdentifier",
".",
"load",
"(",
"\"application/#{handler_name}\"",
")",
"end"
] | Determine the content_type to report for a given example,
using handler_name if possible.
Considers any pre-defined set of values on the content_type attributge
of the headers. | [
"Determine",
"the",
"content_type",
"to",
"report",
"for",
"a",
"given",
"example",
"using",
"handler_name",
"if",
"possible",
"."
] | 37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635 | https://github.com/praxis/praxis/blob/37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635/lib/praxis/action_definition.rb#L286-L315 | train |
praxis/praxis | lib/praxis/media_type_identifier.rb | Praxis.MediaTypeIdentifier.without_parameters | def without_parameters
if self.parameters.empty?
self
else
MediaTypeIdentifier.load(type: self.type, subtype: self.subtype, suffix: self.suffix)
end
end | ruby | def without_parameters
if self.parameters.empty?
self
else
MediaTypeIdentifier.load(type: self.type, subtype: self.subtype, suffix: self.suffix)
end
end | [
"def",
"without_parameters",
"if",
"self",
".",
"parameters",
".",
"empty?",
"self",
"else",
"MediaTypeIdentifier",
".",
"load",
"(",
"type",
":",
"self",
".",
"type",
",",
"subtype",
":",
"self",
".",
"subtype",
",",
"suffix",
":",
"self",
".",
"suffix",
")",
"end",
"end"
] | If parameters are empty, return self; otherwise return a new object consisting of this type
minus parameters.
@return [MediaTypeIdentifier] | [
"If",
"parameters",
"are",
"empty",
"return",
"self",
";",
"otherwise",
"return",
"a",
"new",
"object",
"consisting",
"of",
"this",
"type",
"minus",
"parameters",
"."
] | 37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635 | https://github.com/praxis/praxis/blob/37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635/lib/praxis/media_type_identifier.rb#L145-L151 | train |
praxis/praxis | lib/praxis/response_definition.rb | Praxis.ResponseDefinition.validate_status! | def validate_status!(response)
return unless status
# Validate status code if defined in the spec
if response.status != status
raise Exceptions::Validation.new(
"Invalid response code detected. Response %s dictates status of %s but this response is returning %s." %
[name, status.inspect, response.status.inspect]
)
end
end | ruby | def validate_status!(response)
return unless status
# Validate status code if defined in the spec
if response.status != status
raise Exceptions::Validation.new(
"Invalid response code detected. Response %s dictates status of %s but this response is returning %s." %
[name, status.inspect, response.status.inspect]
)
end
end | [
"def",
"validate_status!",
"(",
"response",
")",
"return",
"unless",
"status",
"# Validate status code if defined in the spec",
"if",
"response",
".",
"status",
"!=",
"status",
"raise",
"Exceptions",
"::",
"Validation",
".",
"new",
"(",
"\"Invalid response code detected. Response %s dictates status of %s but this response is returning %s.\"",
"%",
"[",
"name",
",",
"status",
".",
"inspect",
",",
"response",
".",
"status",
".",
"inspect",
"]",
")",
"end",
"end"
] | Validates Status code
@raise [Exceptions::Validation] When response returns an unexpected status. | [
"Validates",
"Status",
"code"
] | 37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635 | https://github.com/praxis/praxis/blob/37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635/lib/praxis/response_definition.rb#L214-L223 | train |
praxis/praxis | lib/praxis/response_definition.rb | Praxis.ResponseDefinition.validate_location! | def validate_location!(response)
return if location.nil? || location === response.headers['Location']
raise Exceptions::Validation.new("LOCATION does not match #{location.inspect}")
end | ruby | def validate_location!(response)
return if location.nil? || location === response.headers['Location']
raise Exceptions::Validation.new("LOCATION does not match #{location.inspect}")
end | [
"def",
"validate_location!",
"(",
"response",
")",
"return",
"if",
"location",
".",
"nil?",
"||",
"location",
"===",
"response",
".",
"headers",
"[",
"'Location'",
"]",
"raise",
"Exceptions",
"::",
"Validation",
".",
"new",
"(",
"\"LOCATION does not match #{location.inspect}\"",
")",
"end"
] | Validates 'Location' header
@raise [Exceptions::Validation] When location header does not match to the defined one. | [
"Validates",
"Location",
"header"
] | 37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635 | https://github.com/praxis/praxis/blob/37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635/lib/praxis/response_definition.rb#L230-L233 | train |
praxis/praxis | lib/praxis/response_definition.rb | Praxis.ResponseDefinition.validate_content_type! | def validate_content_type!(response)
return unless media_type
response_content_type = response.content_type
expected_content_type = Praxis::MediaTypeIdentifier.load(media_type.identifier)
unless expected_content_type.match(response_content_type)
raise Exceptions::Validation.new(
"Bad Content-Type header. #{response_content_type}" +
" is incompatible with #{expected_content_type} as described in response: #{self.name}"
)
end
end | ruby | def validate_content_type!(response)
return unless media_type
response_content_type = response.content_type
expected_content_type = Praxis::MediaTypeIdentifier.load(media_type.identifier)
unless expected_content_type.match(response_content_type)
raise Exceptions::Validation.new(
"Bad Content-Type header. #{response_content_type}" +
" is incompatible with #{expected_content_type} as described in response: #{self.name}"
)
end
end | [
"def",
"validate_content_type!",
"(",
"response",
")",
"return",
"unless",
"media_type",
"response_content_type",
"=",
"response",
".",
"content_type",
"expected_content_type",
"=",
"Praxis",
"::",
"MediaTypeIdentifier",
".",
"load",
"(",
"media_type",
".",
"identifier",
")",
"unless",
"expected_content_type",
".",
"match",
"(",
"response_content_type",
")",
"raise",
"Exceptions",
"::",
"Validation",
".",
"new",
"(",
"\"Bad Content-Type header. #{response_content_type}\"",
"+",
"\" is incompatible with #{expected_content_type} as described in response: #{self.name}\"",
")",
"end",
"end"
] | Validates Content-Type header and response media type
@param [Object] response
@raise [Exceptions::Validation] When there is a missing required header | [
"Validates",
"Content",
"-",
"Type",
"header",
"and",
"response",
"media",
"type"
] | 37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635 | https://github.com/praxis/praxis/blob/37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635/lib/praxis/response_definition.rb#L279-L291 | train |
praxis/praxis | lib/praxis/response_definition.rb | Praxis.ResponseDefinition.validate_body! | def validate_body!(response)
return unless media_type
return if media_type.kind_of? SimpleMediaType
errors = self.media_type.validate(self.media_type.load(response.body))
if errors.any?
message = "Invalid response body for #{media_type.identifier}." +
"Errors: #{errors.inspect}"
raise Exceptions::Validation.new(message, errors: errors)
end
end | ruby | def validate_body!(response)
return unless media_type
return if media_type.kind_of? SimpleMediaType
errors = self.media_type.validate(self.media_type.load(response.body))
if errors.any?
message = "Invalid response body for #{media_type.identifier}." +
"Errors: #{errors.inspect}"
raise Exceptions::Validation.new(message, errors: errors)
end
end | [
"def",
"validate_body!",
"(",
"response",
")",
"return",
"unless",
"media_type",
"return",
"if",
"media_type",
".",
"kind_of?",
"SimpleMediaType",
"errors",
"=",
"self",
".",
"media_type",
".",
"validate",
"(",
"self",
".",
"media_type",
".",
"load",
"(",
"response",
".",
"body",
")",
")",
"if",
"errors",
".",
"any?",
"message",
"=",
"\"Invalid response body for #{media_type.identifier}.\"",
"+",
"\"Errors: #{errors.inspect}\"",
"raise",
"Exceptions",
"::",
"Validation",
".",
"new",
"(",
"message",
",",
"errors",
":",
"errors",
")",
"end",
"end"
] | Validates response body
@param [Object] response
@raise [Exceptions::Validation] When there is a missing required header.. | [
"Validates",
"response",
"body"
] | 37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635 | https://github.com/praxis/praxis/blob/37b97f2d72116cd3ae7c2e90f03dfe37fa3b5635/lib/praxis/response_definition.rb#L298-L309 | train |
mynyml/harmony | lib/harmony/page.rb | Harmony.Page.load | def load(*paths)
paths.flatten.each do |path|
window.load(path.to_s)
end
self
end | ruby | def load(*paths)
paths.flatten.each do |path|
window.load(path.to_s)
end
self
end | [
"def",
"load",
"(",
"*",
"paths",
")",
"paths",
".",
"flatten",
".",
"each",
"do",
"|",
"path",
"|",
"window",
".",
"load",
"(",
"path",
".",
"to_s",
")",
"end",
"self",
"end"
] | Create new page containing given document.
@param [String] document
HTML document. Defaults to an "about:blank" window, with the basic
structure: `<html><head><title></title></head><body></body></html>`
Load one or more javascript files in page's context
@param [#to_s, #to_s, ...] paths
paths to js file
@return [Page] self | [
"Create",
"new",
"page",
"containing",
"given",
"document",
"."
] | dc80bd2b686d1dcfb04dec0ef22355fea5c2acbb | https://github.com/mynyml/harmony/blob/dc80bd2b686d1dcfb04dec0ef22355fea5c2acbb/lib/harmony/page.rb#L74-L79 | train |
fredjean/middleman-s3_sync | lib/middleman-s3_sync/extension.rb | Middleman.S3SyncExtension.read_config | def read_config(io = nil)
unless io
root_path = ::Middleman::Application.root
config_file_path = File.join(root_path, ".s3_sync")
# skip if config file does not exist
return unless File.exists?(config_file_path)
io = File.open(config_file_path, "r")
end
config = (YAML.load(io) || {}).symbolize_keys
config.each do |key, value|
options[key.to_sym] = value
end
end | ruby | def read_config(io = nil)
unless io
root_path = ::Middleman::Application.root
config_file_path = File.join(root_path, ".s3_sync")
# skip if config file does not exist
return unless File.exists?(config_file_path)
io = File.open(config_file_path, "r")
end
config = (YAML.load(io) || {}).symbolize_keys
config.each do |key, value|
options[key.to_sym] = value
end
end | [
"def",
"read_config",
"(",
"io",
"=",
"nil",
")",
"unless",
"io",
"root_path",
"=",
"::",
"Middleman",
"::",
"Application",
".",
"root",
"config_file_path",
"=",
"File",
".",
"join",
"(",
"root_path",
",",
"\".s3_sync\"",
")",
"# skip if config file does not exist",
"return",
"unless",
"File",
".",
"exists?",
"(",
"config_file_path",
")",
"io",
"=",
"File",
".",
"open",
"(",
"config_file_path",
",",
"\"r\"",
")",
"end",
"config",
"=",
"(",
"YAML",
".",
"load",
"(",
"io",
")",
"||",
"{",
"}",
")",
".",
"symbolize_keys",
"config",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"options",
"[",
"key",
".",
"to_sym",
"]",
"=",
"value",
"end",
"end"
] | Read config options from an IO stream and set them on `self`. Defaults
to reading from the `.s3_sync` file in the MM project root if it exists.
@param io [IO] an IO stream to read from
@return [void] | [
"Read",
"config",
"options",
"from",
"an",
"IO",
"stream",
"and",
"set",
"them",
"on",
"self",
".",
"Defaults",
"to",
"reading",
"from",
"the",
".",
"s3_sync",
"file",
"in",
"the",
"MM",
"project",
"root",
"if",
"it",
"exists",
"."
] | 32f98ac1acf613ba3ac5a203c095f74ebe4d304d | https://github.com/fredjean/middleman-s3_sync/blob/32f98ac1acf613ba3ac5a203c095f74ebe4d304d/lib/middleman-s3_sync/extension.rb#L74-L90 | train |
zverok/geo_coord | lib/geo/coord.rb | Geo.Coord.strfcoord | def strfcoord(formatstr)
h = full_hash
DIRECTIVES.reduce(formatstr) do |memo, (from, to)|
memo.gsub(from) do
to = to.call(Regexp.last_match) if to.is_a?(Proc)
res = to % h
res, carrymin = guard_seconds(to, res)
h[carrymin] += 1 if carrymin
res
end
end
end | ruby | def strfcoord(formatstr)
h = full_hash
DIRECTIVES.reduce(formatstr) do |memo, (from, to)|
memo.gsub(from) do
to = to.call(Regexp.last_match) if to.is_a?(Proc)
res = to % h
res, carrymin = guard_seconds(to, res)
h[carrymin] += 1 if carrymin
res
end
end
end | [
"def",
"strfcoord",
"(",
"formatstr",
")",
"h",
"=",
"full_hash",
"DIRECTIVES",
".",
"reduce",
"(",
"formatstr",
")",
"do",
"|",
"memo",
",",
"(",
"from",
",",
"to",
")",
"|",
"memo",
".",
"gsub",
"(",
"from",
")",
"do",
"to",
"=",
"to",
".",
"call",
"(",
"Regexp",
".",
"last_match",
")",
"if",
"to",
".",
"is_a?",
"(",
"Proc",
")",
"res",
"=",
"to",
"%",
"h",
"res",
",",
"carrymin",
"=",
"guard_seconds",
"(",
"to",
",",
"res",
")",
"h",
"[",
"carrymin",
"]",
"+=",
"1",
"if",
"carrymin",
"res",
"end",
"end",
"end"
] | Formats coordinates according to directives in +formatstr+.
Each directive starts with +%+ and can contain some modifiers before
its name.
Acceptable modifiers:
- unsigned integers: none;
- signed integers: <tt>+</tt> for mandatory sign printing;
- floats: same as integers and number of digits modifier, like
<tt>.03</tt>.
List of directives:
%lat :: Full latitude, floating point, signed
%latds :: Latitude degrees, integer, signed
%latd :: Latitude degrees, integer, unsigned
%latm :: Latitude minutes, integer, unsigned
%lats :: Latitude seconds, floating point, unsigned
%lath :: Latitude hemisphere, "N" or "S"
%lng :: Full longitude, floating point, signed
%lngds :: Longitude degrees, integer, signed
%lngd :: Longitude degrees, integer, unsigned
%lngm :: Longitude minutes, integer, unsigned
%lngs :: Longitude seconds, floating point, unsigned
%lngh :: Longitude hemisphere, "E" or "W"
Examples:
g = Geo::Coord.new(50.004444, 36.231389)
g.strfcoord('%+lat, %+lng')
# => "+50.004444, +36.231389"
g.strfcoord("%latd°%latm'%lath -- %lngd°%lngm'%lngh")
# => "50°0'N -- 36°13'E"
+strfcoord+ handles seconds rounding implicitly:
pos = Geo::Coord.new(0.033333, 91.333333)
pos.lats # => 0.599988e2
pos.strfcoord('%latd %latm %.05lats') # => "0 1 59.99880"
pos.strfcoord('%latd %latm %lats') # => "0 2 0" | [
"Formats",
"coordinates",
"according",
"to",
"directives",
"in",
"+",
"formatstr",
"+",
"."
] | 08b6595cc679eac7beadda2efc2cf13a5344ad4c | https://github.com/zverok/geo_coord/blob/08b6595cc679eac7beadda2efc2cf13a5344ad4c/lib/geo/coord.rb#L555-L567 | train |
adhearsion/ruby_speech | lib/ruby_speech/generic_element.rb | RubySpeech.GenericElement.read_attr | def read_attr(attr_name, to_call = nil)
val = self[attr_name]
val && to_call ? val.__send__(to_call) : val
end | ruby | def read_attr(attr_name, to_call = nil)
val = self[attr_name]
val && to_call ? val.__send__(to_call) : val
end | [
"def",
"read_attr",
"(",
"attr_name",
",",
"to_call",
"=",
"nil",
")",
"val",
"=",
"self",
"[",
"attr_name",
"]",
"val",
"&&",
"to_call",
"?",
"val",
".",
"__send__",
"(",
"to_call",
")",
":",
"val",
"end"
] | Helper method to read an attribute
@param [#to_sym] attr_name the name of the attribute
@param [String, Symbol, nil] to_call the name of the method to call on
the returned value
@return nil or the value | [
"Helper",
"method",
"to",
"read",
"an",
"attribute"
] | 57562548608ddee2a09b8b63ba13e51ad25eb982 | https://github.com/adhearsion/ruby_speech/blob/57562548608ddee2a09b8b63ba13e51ad25eb982/lib/ruby_speech/generic_element.rb#L193-L196 | train |
adhearsion/ruby_speech | lib/ruby_speech/generic_element.rb | RubySpeech.GenericElement.write_attr | def write_attr(attr_name, value, to_call = nil)
self[attr_name] = value && to_call ? value.__send__(to_call) : value
end | ruby | def write_attr(attr_name, value, to_call = nil)
self[attr_name] = value && to_call ? value.__send__(to_call) : value
end | [
"def",
"write_attr",
"(",
"attr_name",
",",
"value",
",",
"to_call",
"=",
"nil",
")",
"self",
"[",
"attr_name",
"]",
"=",
"value",
"&&",
"to_call",
"?",
"value",
".",
"__send__",
"(",
"to_call",
")",
":",
"value",
"end"
] | Helper method to write a value to an attribute
@param [#to_sym] attr_name the name of the attribute
@param [#to_s] value the value to set the attribute to | [
"Helper",
"method",
"to",
"write",
"a",
"value",
"to",
"an",
"attribute"
] | 57562548608ddee2a09b8b63ba13e51ad25eb982 | https://github.com/adhearsion/ruby_speech/blob/57562548608ddee2a09b8b63ba13e51ad25eb982/lib/ruby_speech/generic_element.rb#L202-L204 | train |
adhearsion/ruby_speech | lib/ruby_speech/generic_element.rb | RubySpeech.GenericElement.namespace= | def namespace=(namespaces)
case namespaces
when Nokogiri::XML::Namespace
super namespaces
when String
ns = self.add_namespace nil, namespaces
super ns
end
end | ruby | def namespace=(namespaces)
case namespaces
when Nokogiri::XML::Namespace
super namespaces
when String
ns = self.add_namespace nil, namespaces
super ns
end
end | [
"def",
"namespace",
"=",
"(",
"namespaces",
")",
"case",
"namespaces",
"when",
"Nokogiri",
"::",
"XML",
"::",
"Namespace",
"super",
"namespaces",
"when",
"String",
"ns",
"=",
"self",
".",
"add_namespace",
"nil",
",",
"namespaces",
"super",
"ns",
"end",
"end"
] | Attach a namespace to the node
@overload namespace=(ns)
Attach an already created XML::Namespace
@param [XML::Namespace] ns the namespace object
@overload namespace=(ns)
Create a new namespace and attach it
@param [String] ns the namespace uri | [
"Attach",
"a",
"namespace",
"to",
"the",
"node"
] | 57562548608ddee2a09b8b63ba13e51ad25eb982 | https://github.com/adhearsion/ruby_speech/blob/57562548608ddee2a09b8b63ba13e51ad25eb982/lib/ruby_speech/generic_element.rb#L214-L222 | train |
Agrimatics/activemodel-datastore | lib/active_model/datastore/property_values.rb | ActiveModel::Datastore.PropertyValues.default_property_value | def default_property_value(attr, value)
if value.is_a?(TrueClass) || value.is_a?(FalseClass)
send("#{attr.to_sym}=", value) if send(attr.to_sym).nil?
else
send("#{attr.to_sym}=", send(attr.to_sym).presence || value)
end
end | ruby | def default_property_value(attr, value)
if value.is_a?(TrueClass) || value.is_a?(FalseClass)
send("#{attr.to_sym}=", value) if send(attr.to_sym).nil?
else
send("#{attr.to_sym}=", send(attr.to_sym).presence || value)
end
end | [
"def",
"default_property_value",
"(",
"attr",
",",
"value",
")",
"if",
"value",
".",
"is_a?",
"(",
"TrueClass",
")",
"||",
"value",
".",
"is_a?",
"(",
"FalseClass",
")",
"send",
"(",
"\"#{attr.to_sym}=\"",
",",
"value",
")",
"if",
"send",
"(",
"attr",
".",
"to_sym",
")",
".",
"nil?",
"else",
"send",
"(",
"\"#{attr.to_sym}=\"",
",",
"send",
"(",
"attr",
".",
"to_sym",
")",
".",
"presence",
"||",
"value",
")",
"end",
"end"
] | Sets a default value for the property if not currently set.
Example:
default_property_value :state, 0
is equivalent to:
self.state = state.presence || 0
Example:
default_property_value :enabled, false
is equivalent to:
self.enabled = false if enabled.nil? | [
"Sets",
"a",
"default",
"value",
"for",
"the",
"property",
"if",
"not",
"currently",
"set",
"."
] | ac66520ca57f3bedf03461a4d2f3679f5e5f1d56 | https://github.com/Agrimatics/activemodel-datastore/blob/ac66520ca57f3bedf03461a4d2f3679f5e5f1d56/lib/active_model/datastore/property_values.rb#L22-L28 | train |
Agrimatics/activemodel-datastore | lib/active_model/datastore/property_values.rb | ActiveModel::Datastore.PropertyValues.format_property_value | def format_property_value(attr, type)
return unless send(attr.to_sym).present?
case type.to_sym
when :integer
send("#{attr.to_sym}=", send(attr.to_sym).to_i)
when :float
send("#{attr.to_sym}=", send(attr.to_sym).to_f)
when :boolean
send("#{attr.to_sym}=", ActiveModel::Type::Boolean.new.cast(send(attr.to_sym)))
else
raise ArgumentError, 'Supported types are :boolean, :integer, :float'
end
end | ruby | def format_property_value(attr, type)
return unless send(attr.to_sym).present?
case type.to_sym
when :integer
send("#{attr.to_sym}=", send(attr.to_sym).to_i)
when :float
send("#{attr.to_sym}=", send(attr.to_sym).to_f)
when :boolean
send("#{attr.to_sym}=", ActiveModel::Type::Boolean.new.cast(send(attr.to_sym)))
else
raise ArgumentError, 'Supported types are :boolean, :integer, :float'
end
end | [
"def",
"format_property_value",
"(",
"attr",
",",
"type",
")",
"return",
"unless",
"send",
"(",
"attr",
".",
"to_sym",
")",
".",
"present?",
"case",
"type",
".",
"to_sym",
"when",
":integer",
"send",
"(",
"\"#{attr.to_sym}=\"",
",",
"send",
"(",
"attr",
".",
"to_sym",
")",
".",
"to_i",
")",
"when",
":float",
"send",
"(",
"\"#{attr.to_sym}=\"",
",",
"send",
"(",
"attr",
".",
"to_sym",
")",
".",
"to_f",
")",
"when",
":boolean",
"send",
"(",
"\"#{attr.to_sym}=\"",
",",
"ActiveModel",
"::",
"Type",
"::",
"Boolean",
".",
"new",
".",
"cast",
"(",
"send",
"(",
"attr",
".",
"to_sym",
")",
")",
")",
"else",
"raise",
"ArgumentError",
",",
"'Supported types are :boolean, :integer, :float'",
"end",
"end"
] | Converts the type of the property.
Example:
format_property_value :weight, :float
is equivalent to:
self.weight = weight.to_f if weight.present? | [
"Converts",
"the",
"type",
"of",
"the",
"property",
"."
] | ac66520ca57f3bedf03461a4d2f3679f5e5f1d56 | https://github.com/Agrimatics/activemodel-datastore/blob/ac66520ca57f3bedf03461a4d2f3679f5e5f1d56/lib/active_model/datastore/property_values.rb#L39-L52 | train |
Agrimatics/activemodel-datastore | lib/active_model/datastore/nested_attr.rb | ActiveModel::Datastore.NestedAttr.nested_models | def nested_models
model_entities = []
nested_attributes.each { |attr| model_entities << send(attr.to_sym) } if nested_attributes?
model_entities.flatten
end | ruby | def nested_models
model_entities = []
nested_attributes.each { |attr| model_entities << send(attr.to_sym) } if nested_attributes?
model_entities.flatten
end | [
"def",
"nested_models",
"model_entities",
"=",
"[",
"]",
"nested_attributes",
".",
"each",
"{",
"|",
"attr",
"|",
"model_entities",
"<<",
"send",
"(",
"attr",
".",
"to_sym",
")",
"}",
"if",
"nested_attributes?",
"model_entities",
".",
"flatten",
"end"
] | For each attribute name in nested_attributes extract and return the nested model objects. | [
"For",
"each",
"attribute",
"name",
"in",
"nested_attributes",
"extract",
"and",
"return",
"the",
"nested",
"model",
"objects",
"."
] | ac66520ca57f3bedf03461a4d2f3679f5e5f1d56 | https://github.com/Agrimatics/activemodel-datastore/blob/ac66520ca57f3bedf03461a4d2f3679f5e5f1d56/lib/active_model/datastore/nested_attr.rb#L100-L104 | train |
Agrimatics/activemodel-datastore | lib/active_model/datastore/nested_attr.rb | ActiveModel::Datastore.NestedAttr.assign_nested_attributes | def assign_nested_attributes(association_name, attributes, options = {})
attributes = validate_attributes(attributes)
association_name = association_name.to_sym
send("#{association_name}=", []) if send(association_name).nil?
attributes.each_value do |params|
if params['id'].blank?
unless reject_new_record?(params, options)
new = association_name.to_c.new(params.except(*UNASSIGNABLE_KEYS))
send(association_name).push(new)
end
else
existing = send(association_name).detect { |record| record.id.to_s == params['id'].to_s }
assign_to_or_mark_for_destruction(existing, params)
end
end
(self.nested_attributes ||= []).push(association_name)
end | ruby | def assign_nested_attributes(association_name, attributes, options = {})
attributes = validate_attributes(attributes)
association_name = association_name.to_sym
send("#{association_name}=", []) if send(association_name).nil?
attributes.each_value do |params|
if params['id'].blank?
unless reject_new_record?(params, options)
new = association_name.to_c.new(params.except(*UNASSIGNABLE_KEYS))
send(association_name).push(new)
end
else
existing = send(association_name).detect { |record| record.id.to_s == params['id'].to_s }
assign_to_or_mark_for_destruction(existing, params)
end
end
(self.nested_attributes ||= []).push(association_name)
end | [
"def",
"assign_nested_attributes",
"(",
"association_name",
",",
"attributes",
",",
"options",
"=",
"{",
"}",
")",
"attributes",
"=",
"validate_attributes",
"(",
"attributes",
")",
"association_name",
"=",
"association_name",
".",
"to_sym",
"send",
"(",
"\"#{association_name}=\"",
",",
"[",
"]",
")",
"if",
"send",
"(",
"association_name",
")",
".",
"nil?",
"attributes",
".",
"each_value",
"do",
"|",
"params",
"|",
"if",
"params",
"[",
"'id'",
"]",
".",
"blank?",
"unless",
"reject_new_record?",
"(",
"params",
",",
"options",
")",
"new",
"=",
"association_name",
".",
"to_c",
".",
"new",
"(",
"params",
".",
"except",
"(",
"UNASSIGNABLE_KEYS",
")",
")",
"send",
"(",
"association_name",
")",
".",
"push",
"(",
"new",
")",
"end",
"else",
"existing",
"=",
"send",
"(",
"association_name",
")",
".",
"detect",
"{",
"|",
"record",
"|",
"record",
".",
"id",
".",
"to_s",
"==",
"params",
"[",
"'id'",
"]",
".",
"to_s",
"}",
"assign_to_or_mark_for_destruction",
"(",
"existing",
",",
"params",
")",
"end",
"end",
"(",
"self",
".",
"nested_attributes",
"||=",
"[",
"]",
")",
".",
"push",
"(",
"association_name",
")",
"end"
] | Assigns the given nested child attributes.
Attribute hashes with an +:id+ value matching an existing associated object will update
that object. Hashes without an +:id+ value will build a new object for the association.
Hashes with a matching +:id+ value and a +:_destroy+ key set to a truthy value will mark
the matched object for destruction.
Pushes a key of the association name onto the parent object's +nested_attributes+ attribute.
The +nested_attributes+ can be used for determining when the parent has associated children.
@param [Symbol] association_name The attribute name of the associated children.
@param [ActiveSupport::HashWithIndifferentAccess, ActionController::Parameters] attributes
The attributes provided by Rails ActionView. Typically new objects will arrive as
ActiveSupport::HashWithIndifferentAccess and updates as ActionController::Parameters.
@param [Hash] options The options to control how nested attributes are applied.
@option options [Proc, Symbol] :reject_if Allows you to specify a Proc or a Symbol pointing
to a method that checks whether a record should be built for a certain attribute
hash. The hash is passed to the supplied Proc or the method and it should return either
+true+ or +false+. Passing +:all_blank+ instead of a Proc will create a proc
that will reject a record where all the attributes are blank.
The following example will update the amount of the ingredient with ID 1, build a new
associated ingredient with the amount of 45, and mark the associated ingredient
with ID 2 for destruction.
assign_nested_attributes(:ingredients, {
'0' => { id: '1', amount: '123' },
'1' => { amount: '45' },
'2' => { id: '2', _destroy: true }
}) | [
"Assigns",
"the",
"given",
"nested",
"child",
"attributes",
"."
] | ac66520ca57f3bedf03461a4d2f3679f5e5f1d56 | https://github.com/Agrimatics/activemodel-datastore/blob/ac66520ca57f3bedf03461a4d2f3679f5e5f1d56/lib/active_model/datastore/nested_attr.rb#L155-L172 | train |
Agrimatics/activemodel-datastore | lib/active_model/datastore/nested_attr.rb | ActiveModel::Datastore.NestedAttr.assign_to_or_mark_for_destruction | def assign_to_or_mark_for_destruction(record, attributes)
record.assign_attributes(attributes.except(*UNASSIGNABLE_KEYS))
record.mark_for_destruction if destroy_flag?(attributes)
end | ruby | def assign_to_or_mark_for_destruction(record, attributes)
record.assign_attributes(attributes.except(*UNASSIGNABLE_KEYS))
record.mark_for_destruction if destroy_flag?(attributes)
end | [
"def",
"assign_to_or_mark_for_destruction",
"(",
"record",
",",
"attributes",
")",
"record",
".",
"assign_attributes",
"(",
"attributes",
".",
"except",
"(",
"UNASSIGNABLE_KEYS",
")",
")",
"record",
".",
"mark_for_destruction",
"if",
"destroy_flag?",
"(",
"attributes",
")",
"end"
] | Updates an object with attributes or marks it for destruction if has_destroy_flag?. | [
"Updates",
"an",
"object",
"with",
"attributes",
"or",
"marks",
"it",
"for",
"destruction",
"if",
"has_destroy_flag?",
"."
] | ac66520ca57f3bedf03461a4d2f3679f5e5f1d56 | https://github.com/Agrimatics/activemodel-datastore/blob/ac66520ca57f3bedf03461a4d2f3679f5e5f1d56/lib/active_model/datastore/nested_attr.rb#L190-L193 | train |
Agrimatics/activemodel-datastore | lib/active_model/datastore.rb | ActiveModel::Datastore.ClassMethods.find_entity | def find_entity(id_or_name, parent = nil)
key = CloudDatastore.dataset.key name, id_or_name
key.parent = parent if parent.present?
retry_on_exception { CloudDatastore.dataset.find key }
end | ruby | def find_entity(id_or_name, parent = nil)
key = CloudDatastore.dataset.key name, id_or_name
key.parent = parent if parent.present?
retry_on_exception { CloudDatastore.dataset.find key }
end | [
"def",
"find_entity",
"(",
"id_or_name",
",",
"parent",
"=",
"nil",
")",
"key",
"=",
"CloudDatastore",
".",
"dataset",
".",
"key",
"name",
",",
"id_or_name",
"key",
".",
"parent",
"=",
"parent",
"if",
"parent",
".",
"present?",
"retry_on_exception",
"{",
"CloudDatastore",
".",
"dataset",
".",
"find",
"key",
"}",
"end"
] | Retrieves an entity by id or name and by an optional parent.
@param [Integer or String] id_or_name The id or name value of the entity Key.
@param [Google::Cloud::Datastore::Key] parent The parent Key of the entity.
@return [Entity, nil] a Google::Cloud::Datastore::Entity object or nil. | [
"Retrieves",
"an",
"entity",
"by",
"id",
"or",
"name",
"and",
"by",
"an",
"optional",
"parent",
"."
] | ac66520ca57f3bedf03461a4d2f3679f5e5f1d56 | https://github.com/Agrimatics/activemodel-datastore/blob/ac66520ca57f3bedf03461a4d2f3679f5e5f1d56/lib/active_model/datastore.rb#L229-L233 | train |
Agrimatics/activemodel-datastore | lib/active_model/datastore.rb | ActiveModel::Datastore.ClassMethods.all | def all(options = {})
next_cursor = nil
query = build_query(options)
query_results = retry_on_exception { CloudDatastore.dataset.run query }
if options[:limit]
next_cursor = query_results.cursor if query_results.size == options[:limit]
return from_entities(query_results.all), next_cursor
end
from_entities(query_results.all)
end | ruby | def all(options = {})
next_cursor = nil
query = build_query(options)
query_results = retry_on_exception { CloudDatastore.dataset.run query }
if options[:limit]
next_cursor = query_results.cursor if query_results.size == options[:limit]
return from_entities(query_results.all), next_cursor
end
from_entities(query_results.all)
end | [
"def",
"all",
"(",
"options",
"=",
"{",
"}",
")",
"next_cursor",
"=",
"nil",
"query",
"=",
"build_query",
"(",
"options",
")",
"query_results",
"=",
"retry_on_exception",
"{",
"CloudDatastore",
".",
"dataset",
".",
"run",
"query",
"}",
"if",
"options",
"[",
":limit",
"]",
"next_cursor",
"=",
"query_results",
".",
"cursor",
"if",
"query_results",
".",
"size",
"==",
"options",
"[",
":limit",
"]",
"return",
"from_entities",
"(",
"query_results",
".",
"all",
")",
",",
"next_cursor",
"end",
"from_entities",
"(",
"query_results",
".",
"all",
")",
"end"
] | Queries entities from Cloud Datastore by named kind and using the provided options.
When a limit option is provided queries up to the limit and returns results with a cursor.
This method may make several API calls until all query results are retrieved. The `run`
method returns a QueryResults object, which is a special case Array with additional values.
QueryResults are returned in batches, and the batch size is determined by the Datastore API.
Batch size is not guaranteed. It will be affected by the size of the data being returned,
and by other forces such as how distributed and/or consistent the data in Datastore is.
Calling `all` on the QueryResults retrieves all results by repeatedly loading #next until
#next? returns false. The `all` method returns an enumerator which from_entities iterates on.
Be sure to use as narrow a search criteria as possible. Please use with caution.
@param [Hash] options The options to construct the query with.
@option options [Google::Cloud::Datastore::Key] :ancestor Filter for inherited results.
@option options [String] :cursor Sets the cursor to start the results at.
@option options [Integer] :limit Sets a limit to the number of results to be returned.
@option options [String] :order Sort the results by property name.
@option options [String] :desc_order Sort the results by descending property name.
@option options [Array] :select Retrieve only select properties from the matched entities.
@option options [Array] :distinct_on Group results by a list of properties.
@option options [Array] :where Adds a property filter of arrays in the format
[name, operator, value].
@return [Array<Model>, String] An array of ActiveModel results
or if options[:limit] was provided:
@return [Array<Model>, String] An array of ActiveModel results and a cursor that
can be used to query for additional results. | [
"Queries",
"entities",
"from",
"Cloud",
"Datastore",
"by",
"named",
"kind",
"and",
"using",
"the",
"provided",
"options",
".",
"When",
"a",
"limit",
"option",
"is",
"provided",
"queries",
"up",
"to",
"the",
"limit",
"and",
"returns",
"results",
"with",
"a",
"cursor",
"."
] | ac66520ca57f3bedf03461a4d2f3679f5e5f1d56 | https://github.com/Agrimatics/activemodel-datastore/blob/ac66520ca57f3bedf03461a4d2f3679f5e5f1d56/lib/active_model/datastore.rb#L290-L299 | train |
Agrimatics/activemodel-datastore | lib/active_model/datastore.rb | ActiveModel::Datastore.ClassMethods.find_by | def find_by(args)
query = CloudDatastore.dataset.query name
query.ancestor(args[:ancestor]) if args[:ancestor]
query.limit(1)
query.where(args.keys[0].to_s, '=', args.values[0])
query_results = retry_on_exception { CloudDatastore.dataset.run query }
from_entity(query_results.first)
end | ruby | def find_by(args)
query = CloudDatastore.dataset.query name
query.ancestor(args[:ancestor]) if args[:ancestor]
query.limit(1)
query.where(args.keys[0].to_s, '=', args.values[0])
query_results = retry_on_exception { CloudDatastore.dataset.run query }
from_entity(query_results.first)
end | [
"def",
"find_by",
"(",
"args",
")",
"query",
"=",
"CloudDatastore",
".",
"dataset",
".",
"query",
"name",
"query",
".",
"ancestor",
"(",
"args",
"[",
":ancestor",
"]",
")",
"if",
"args",
"[",
":ancestor",
"]",
"query",
".",
"limit",
"(",
"1",
")",
"query",
".",
"where",
"(",
"args",
".",
"keys",
"[",
"0",
"]",
".",
"to_s",
",",
"'='",
",",
"args",
".",
"values",
"[",
"0",
"]",
")",
"query_results",
"=",
"retry_on_exception",
"{",
"CloudDatastore",
".",
"dataset",
".",
"run",
"query",
"}",
"from_entity",
"(",
"query_results",
".",
"first",
")",
"end"
] | Finds the first entity matching the specified condition.
@param [Hash] args In which the key is the property and the value is the value to look for.
@option args [Google::Cloud::Datastore::Key] :ancestor filter for inherited results
@return [Model, nil] An ActiveModel object or nil.
@example
User.find_by(name: 'Joe')
User.find_by(name: 'Bryce', ancestor: parent_key) | [
"Finds",
"the",
"first",
"entity",
"matching",
"the",
"specified",
"condition",
"."
] | ac66520ca57f3bedf03461a4d2f3679f5e5f1d56 | https://github.com/Agrimatics/activemodel-datastore/blob/ac66520ca57f3bedf03461a4d2f3679f5e5f1d56/lib/active_model/datastore.rb#L340-L347 | train |
Agrimatics/activemodel-datastore | lib/active_model/datastore.rb | ActiveModel::Datastore.ClassMethods.query_sort | def query_sort(query, options)
query.order(options[:order]) if options[:order]
query.order(options[:desc_order], :desc) if options[:desc_order]
query
end | ruby | def query_sort(query, options)
query.order(options[:order]) if options[:order]
query.order(options[:desc_order], :desc) if options[:desc_order]
query
end | [
"def",
"query_sort",
"(",
"query",
",",
"options",
")",
"query",
".",
"order",
"(",
"options",
"[",
":order",
"]",
")",
"if",
"options",
"[",
":order",
"]",
"query",
".",
"order",
"(",
"options",
"[",
":desc_order",
"]",
",",
":desc",
")",
"if",
"options",
"[",
":desc_order",
"]",
"query",
"end"
] | Adds sorting to the results by a property name if included in the options. | [
"Adds",
"sorting",
"to",
"the",
"results",
"by",
"a",
"property",
"name",
"if",
"included",
"in",
"the",
"options",
"."
] | ac66520ca57f3bedf03461a4d2f3679f5e5f1d56 | https://github.com/Agrimatics/activemodel-datastore/blob/ac66520ca57f3bedf03461a4d2f3679f5e5f1d56/lib/active_model/datastore.rb#L459-L463 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.