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
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
dicom/rtkit | lib/rtkit/structure_set.rb | RTKIT.StructureSet.add_plan | def add_plan(plan)
raise ArgumentError, "Invalid argument 'plan'. Expected Plan, got #{plan.class}." unless plan.is_a?(Plan)
@plans << plan unless @associated_plans[plan.uid]
@associated_plans[plan.uid] = plan
end | ruby | def add_plan(plan)
raise ArgumentError, "Invalid argument 'plan'. Expected Plan, got #{plan.class}." unless plan.is_a?(Plan)
@plans << plan unless @associated_plans[plan.uid]
@associated_plans[plan.uid] = plan
end | [
"def",
"add_plan",
"(",
"plan",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'plan'. Expected Plan, got #{plan.class}.\"",
"unless",
"plan",
".",
"is_a?",
"(",
"Plan",
")",
"@plans",
"<<",
"plan",
"unless",
"@associated_plans",
"[",
"plan",
".",
"uid",
"]",
"@associated_plans",
"[",
"plan",
".",
"uid",
"]",
"=",
"plan",
"end"
]
| Adds a Plan Series to this StructureSet.
@param [Plan] plan a plan instance to be associated with this structure set | [
"Adds",
"a",
"Plan",
"Series",
"to",
"this",
"StructureSet",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/structure_set.rb#L152-L156 | train |
dicom/rtkit | lib/rtkit/structure_set.rb | RTKIT.StructureSet.add_poi | def add_poi(poi)
raise ArgumentError, "Invalid argument 'poi'. Expected POI, got #{poi.class}." unless poi.is_a?(POI)
@structures << poi unless @structures.include?(poi)
end | ruby | def add_poi(poi)
raise ArgumentError, "Invalid argument 'poi'. Expected POI, got #{poi.class}." unless poi.is_a?(POI)
@structures << poi unless @structures.include?(poi)
end | [
"def",
"add_poi",
"(",
"poi",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'poi'. Expected POI, got #{poi.class}.\"",
"unless",
"poi",
".",
"is_a?",
"(",
"POI",
")",
"@structures",
"<<",
"poi",
"unless",
"@structures",
".",
"include?",
"(",
"poi",
")",
"end"
]
| Adds a POI instance to this StructureSet.
@param [POI] poi a poi instance to be associated with this structure set | [
"Adds",
"a",
"POI",
"instance",
"to",
"this",
"StructureSet",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/structure_set.rb#L162-L165 | train |
dicom/rtkit | lib/rtkit/structure_set.rb | RTKIT.StructureSet.add_structure | def add_structure(structure)
raise ArgumentError, "Invalid argument 'structure'. Expected ROI/POI, got #{structure.class}." unless structure.respond_to?(:to_roi) or structure.respond_to?(:to_poi)
@structures << structure unless @structures.include?(structure)
end | ruby | def add_structure(structure)
raise ArgumentError, "Invalid argument 'structure'. Expected ROI/POI, got #{structure.class}." unless structure.respond_to?(:to_roi) or structure.respond_to?(:to_poi)
@structures << structure unless @structures.include?(structure)
end | [
"def",
"add_structure",
"(",
"structure",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'structure'. Expected ROI/POI, got #{structure.class}.\"",
"unless",
"structure",
".",
"respond_to?",
"(",
":to_roi",
")",
"or",
"structure",
".",
"respond_to?",
"(",
":to_poi",
")",
"@structures",
"<<",
"structure",
"unless",
"@structures",
".",
"include?",
"(",
"structure",
")",
"end"
]
| Adds a Structure instance to this StructureSet.
@param [ROI, POI] structure a Structure to be associated with this StructureSet | [
"Adds",
"a",
"Structure",
"instance",
"to",
"this",
"StructureSet",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/structure_set.rb#L171-L174 | train |
dicom/rtkit | lib/rtkit/structure_set.rb | RTKIT.StructureSet.add_roi | def add_roi(roi)
raise ArgumentError, "Invalid argument 'roi'. Expected ROI, got #{roi.class}." unless roi.is_a?(ROI)
@structures << roi unless @structures.include?(roi)
end | ruby | def add_roi(roi)
raise ArgumentError, "Invalid argument 'roi'. Expected ROI, got #{roi.class}." unless roi.is_a?(ROI)
@structures << roi unless @structures.include?(roi)
end | [
"def",
"add_roi",
"(",
"roi",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'roi'. Expected ROI, got #{roi.class}.\"",
"unless",
"roi",
".",
"is_a?",
"(",
"ROI",
")",
"@structures",
"<<",
"roi",
"unless",
"@structures",
".",
"include?",
"(",
"roi",
")",
"end"
]
| Adds a ROI instance to this StructureSet.
@param [ROI] roi a roi instance to be associated with this structure set | [
"Adds",
"a",
"ROI",
"instance",
"to",
"this",
"StructureSet",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/structure_set.rb#L180-L183 | train |
dicom/rtkit | lib/rtkit/structure_set.rb | RTKIT.StructureSet.create_roi | def create_roi(frame, options={})
raise ArgumentError, "Expected Frame, got #{frame.class}." unless frame.is_a?(Frame)
# Set values:
algorithm = options[:algorithm] || 'Automatic'
name = options[:name] || 'RTKIT-VOLUME'
interpreter = options[:interpreter] || 'RTKIT'
type = options[:type] || 'CONTROL'
if options[:number]
raise ArgumentError, "Expected Integer, got #{options[:number].class} for the option :number." unless options[:number].is_a?(Integer)
raise ArgumentError, "The specified ROI Number (#{options[:roi_number]}) is already used by one of the existing ROIs (#{roi_numbers})." if structure_numbers.include?(options[:number])
number = options[:number]
else
number = (structure_numbers.max ? structure_numbers.max + 1 : 1)
end
# Create ROI:
roi = ROI.new(name, number, frame, self, :algorithm => algorithm, :name => name, :number => number, :interpreter => interpreter, :type => type)
return roi
end | ruby | def create_roi(frame, options={})
raise ArgumentError, "Expected Frame, got #{frame.class}." unless frame.is_a?(Frame)
# Set values:
algorithm = options[:algorithm] || 'Automatic'
name = options[:name] || 'RTKIT-VOLUME'
interpreter = options[:interpreter] || 'RTKIT'
type = options[:type] || 'CONTROL'
if options[:number]
raise ArgumentError, "Expected Integer, got #{options[:number].class} for the option :number." unless options[:number].is_a?(Integer)
raise ArgumentError, "The specified ROI Number (#{options[:roi_number]}) is already used by one of the existing ROIs (#{roi_numbers})." if structure_numbers.include?(options[:number])
number = options[:number]
else
number = (structure_numbers.max ? structure_numbers.max + 1 : 1)
end
# Create ROI:
roi = ROI.new(name, number, frame, self, :algorithm => algorithm, :name => name, :number => number, :interpreter => interpreter, :type => type)
return roi
end | [
"def",
"create_roi",
"(",
"frame",
",",
"options",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"\"Expected Frame, got #{frame.class}.\"",
"unless",
"frame",
".",
"is_a?",
"(",
"Frame",
")",
"algorithm",
"=",
"options",
"[",
":algorithm",
"]",
"||",
"'Automatic'",
"name",
"=",
"options",
"[",
":name",
"]",
"||",
"'RTKIT-VOLUME'",
"interpreter",
"=",
"options",
"[",
":interpreter",
"]",
"||",
"'RTKIT'",
"type",
"=",
"options",
"[",
":type",
"]",
"||",
"'CONTROL'",
"if",
"options",
"[",
":number",
"]",
"raise",
"ArgumentError",
",",
"\"Expected Integer, got #{options[:number].class} for the option :number.\"",
"unless",
"options",
"[",
":number",
"]",
".",
"is_a?",
"(",
"Integer",
")",
"raise",
"ArgumentError",
",",
"\"The specified ROI Number (#{options[:roi_number]}) is already used by one of the existing ROIs (#{roi_numbers}).\"",
"if",
"structure_numbers",
".",
"include?",
"(",
"options",
"[",
":number",
"]",
")",
"number",
"=",
"options",
"[",
":number",
"]",
"else",
"number",
"=",
"(",
"structure_numbers",
".",
"max",
"?",
"structure_numbers",
".",
"max",
"+",
"1",
":",
"1",
")",
"end",
"roi",
"=",
"ROI",
".",
"new",
"(",
"name",
",",
"number",
",",
"frame",
",",
"self",
",",
":algorithm",
"=>",
"algorithm",
",",
":name",
"=>",
"name",
",",
":number",
"=>",
"number",
",",
":interpreter",
"=>",
"interpreter",
",",
":type",
"=>",
"type",
")",
"return",
"roi",
"end"
]
| Creates a ROI belonging to this StructureSet.
@note The ROI is created without any Slice instances (these must be added
after the ROI creation).
@param [Frame] frame the Frame which the ROI is to be associated with
@param [Hash] options the options to use for creating the ROI
@option options [String] :algorithm the ROI generation algorithm (defaults to 'Automatic')
@option options [String] :interpreter the ROI interpreter (defaults to 'RTKIT')
@option options [String] :name the ROI name (defaults to 'RTKIT-VOLUME')
@option options [String] :number the ROI number (defaults to the first available ROI number in the structure set)
@option options [String] :type the ROI interpreted type (defaults to 'CONTROL') | [
"Creates",
"a",
"ROI",
"belonging",
"to",
"this",
"StructureSet",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/structure_set.rb#L198-L215 | train |
dicom/rtkit | lib/rtkit/structure_set.rb | RTKIT.StructureSet.remove_structure | def remove_structure(instance_or_number)
raise ArgumentError, "Invalid argument 'instance_or_number'. Expected a ROI Instance or an Integer (ROI Number). Got #{instance_or_number.class}." unless [ROI, Integer].include?(instance_or_number.class)
s_instance = instance_or_number
if instance_or_number.is_a?(Integer)
s_instance = structure(instance_or_number)
end
index = @structures.index(s_instance)
if index
@structures.delete_at(index)
s_instance.remove_references
end
end | ruby | def remove_structure(instance_or_number)
raise ArgumentError, "Invalid argument 'instance_or_number'. Expected a ROI Instance or an Integer (ROI Number). Got #{instance_or_number.class}." unless [ROI, Integer].include?(instance_or_number.class)
s_instance = instance_or_number
if instance_or_number.is_a?(Integer)
s_instance = structure(instance_or_number)
end
index = @structures.index(s_instance)
if index
@structures.delete_at(index)
s_instance.remove_references
end
end | [
"def",
"remove_structure",
"(",
"instance_or_number",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'instance_or_number'. Expected a ROI Instance or an Integer (ROI Number). Got #{instance_or_number.class}.\"",
"unless",
"[",
"ROI",
",",
"Integer",
"]",
".",
"include?",
"(",
"instance_or_number",
".",
"class",
")",
"s_instance",
"=",
"instance_or_number",
"if",
"instance_or_number",
".",
"is_a?",
"(",
"Integer",
")",
"s_instance",
"=",
"structure",
"(",
"instance_or_number",
")",
"end",
"index",
"=",
"@structures",
".",
"index",
"(",
"s_instance",
")",
"if",
"index",
"@structures",
".",
"delete_at",
"(",
"index",
")",
"s_instance",
".",
"remove_references",
"end",
"end"
]
| Removes a ROI or POI from the structure set.
@param [ROI, POI, Integer] instance_or_number the ROI/POI instance or its identifying number | [
"Removes",
"a",
"ROI",
"or",
"POI",
"from",
"the",
"structure",
"set",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/structure_set.rb#L268-L279 | train |
dicom/rtkit | lib/rtkit/structure_set.rb | RTKIT.StructureSet.structure_names | def structure_names
names = Array.new
@structures.each do |s|
names << s.name
end
return names
end | ruby | def structure_names
names = Array.new
@structures.each do |s|
names << s.name
end
return names
end | [
"def",
"structure_names",
"names",
"=",
"Array",
".",
"new",
"@structures",
".",
"each",
"do",
"|",
"s",
"|",
"names",
"<<",
"s",
".",
"name",
"end",
"return",
"names",
"end"
]
| Gives the names of the structure set's associated structures.
@return [Array<String>] the names of the associated structures | [
"Gives",
"the",
"names",
"of",
"the",
"structure",
"set",
"s",
"associated",
"structures",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/structure_set.rb#L321-L327 | train |
dicom/rtkit | lib/rtkit/structure_set.rb | RTKIT.StructureSet.structure_numbers | def structure_numbers
numbers = Array.new
@structures.each do |s|
numbers << s.number
end
return numbers
end | ruby | def structure_numbers
numbers = Array.new
@structures.each do |s|
numbers << s.number
end
return numbers
end | [
"def",
"structure_numbers",
"numbers",
"=",
"Array",
".",
"new",
"@structures",
".",
"each",
"do",
"|",
"s",
"|",
"numbers",
"<<",
"s",
".",
"number",
"end",
"return",
"numbers",
"end"
]
| Gives the numbers of the structure set's associated structures.
@return [Array<Integer>] the numbers of the associated structures | [
"Gives",
"the",
"numbers",
"of",
"the",
"structure",
"set",
"s",
"associated",
"structures",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/structure_set.rb#L333-L339 | train |
dicom/rtkit | lib/rtkit/structure_set.rb | RTKIT.StructureSet.to_dcm | def to_dcm
# Use the original DICOM object as a starting point (keeping all non-sequence elements):
#@dcm[REF_FRAME_OF_REF_SQ].delete_children
@dcm[STRUCTURE_SET_ROI_SQ].delete_children
@dcm[ROI_CONTOUR_SQ].delete_children
@dcm[RT_ROI_OBS_SQ].delete_children
# Create DICOM
@rois.each do |roi|
@dcm[STRUCTURE_SET_ROI_SQ].add_item(roi.ss_item)
@dcm[ROI_CONTOUR_SQ].add_item(roi.contour_item)
@dcm[RT_ROI_OBS_SQ].add_item(roi.obs_item)
end
return @dcm
end | ruby | def to_dcm
# Use the original DICOM object as a starting point (keeping all non-sequence elements):
#@dcm[REF_FRAME_OF_REF_SQ].delete_children
@dcm[STRUCTURE_SET_ROI_SQ].delete_children
@dcm[ROI_CONTOUR_SQ].delete_children
@dcm[RT_ROI_OBS_SQ].delete_children
# Create DICOM
@rois.each do |roi|
@dcm[STRUCTURE_SET_ROI_SQ].add_item(roi.ss_item)
@dcm[ROI_CONTOUR_SQ].add_item(roi.contour_item)
@dcm[RT_ROI_OBS_SQ].add_item(roi.obs_item)
end
return @dcm
end | [
"def",
"to_dcm",
"@dcm",
"[",
"STRUCTURE_SET_ROI_SQ",
"]",
".",
"delete_children",
"@dcm",
"[",
"ROI_CONTOUR_SQ",
"]",
".",
"delete_children",
"@dcm",
"[",
"RT_ROI_OBS_SQ",
"]",
".",
"delete_children",
"@rois",
".",
"each",
"do",
"|",
"roi",
"|",
"@dcm",
"[",
"STRUCTURE_SET_ROI_SQ",
"]",
".",
"add_item",
"(",
"roi",
".",
"ss_item",
")",
"@dcm",
"[",
"ROI_CONTOUR_SQ",
"]",
".",
"add_item",
"(",
"roi",
".",
"contour_item",
")",
"@dcm",
"[",
"RT_ROI_OBS_SQ",
"]",
".",
"add_item",
"(",
"roi",
".",
"obs_item",
")",
"end",
"return",
"@dcm",
"end"
]
| Converts the structure set instance to a DICOM object.
@note This method uses the original DICOM object of the structure set,
and updates it with attributes from the structure set instance.
@return [DICOM::DObject] the processed DICOM object | [
"Converts",
"the",
"structure",
"set",
"instance",
"to",
"a",
"DICOM",
"object",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/structure_set.rb#L390-L403 | train |
dicom/rtkit | lib/rtkit/structure_set.rb | RTKIT.StructureSet.load_structures | def load_structures
if @dcm[STRUCTURE_SET_ROI_SQ] && @dcm[ROI_CONTOUR_SQ] && @dcm[RT_ROI_OBS_SQ]
# Load the information in a nested hash:
item_group = Hash.new
@dcm[STRUCTURE_SET_ROI_SQ].each do |roi_item|
item_group[roi_item.value(ROI_NUMBER)] = {:roi => roi_item}
end
@dcm[ROI_CONTOUR_SQ].each do |contour_item|
item_group[contour_item.value(REF_ROI_NUMBER)][:contour] = contour_item
end
@dcm[RT_ROI_OBS_SQ].each do |rt_item|
item_group[rt_item.value(REF_ROI_NUMBER)][:rt] = rt_item
end
# Create a ROI instance for each set of items:
item_group.each_value do |roi_items|
Structure.create_from_items(roi_items[:roi], roi_items[:contour], roi_items[:rt], self)
end
else
RTKIT.logger.warn "The structure set contained one or more empty ROI sequences. No ROIs extracted."
end
end | ruby | def load_structures
if @dcm[STRUCTURE_SET_ROI_SQ] && @dcm[ROI_CONTOUR_SQ] && @dcm[RT_ROI_OBS_SQ]
# Load the information in a nested hash:
item_group = Hash.new
@dcm[STRUCTURE_SET_ROI_SQ].each do |roi_item|
item_group[roi_item.value(ROI_NUMBER)] = {:roi => roi_item}
end
@dcm[ROI_CONTOUR_SQ].each do |contour_item|
item_group[contour_item.value(REF_ROI_NUMBER)][:contour] = contour_item
end
@dcm[RT_ROI_OBS_SQ].each do |rt_item|
item_group[rt_item.value(REF_ROI_NUMBER)][:rt] = rt_item
end
# Create a ROI instance for each set of items:
item_group.each_value do |roi_items|
Structure.create_from_items(roi_items[:roi], roi_items[:contour], roi_items[:rt], self)
end
else
RTKIT.logger.warn "The structure set contained one or more empty ROI sequences. No ROIs extracted."
end
end | [
"def",
"load_structures",
"if",
"@dcm",
"[",
"STRUCTURE_SET_ROI_SQ",
"]",
"&&",
"@dcm",
"[",
"ROI_CONTOUR_SQ",
"]",
"&&",
"@dcm",
"[",
"RT_ROI_OBS_SQ",
"]",
"item_group",
"=",
"Hash",
".",
"new",
"@dcm",
"[",
"STRUCTURE_SET_ROI_SQ",
"]",
".",
"each",
"do",
"|",
"roi_item",
"|",
"item_group",
"[",
"roi_item",
".",
"value",
"(",
"ROI_NUMBER",
")",
"]",
"=",
"{",
":roi",
"=>",
"roi_item",
"}",
"end",
"@dcm",
"[",
"ROI_CONTOUR_SQ",
"]",
".",
"each",
"do",
"|",
"contour_item",
"|",
"item_group",
"[",
"contour_item",
".",
"value",
"(",
"REF_ROI_NUMBER",
")",
"]",
"[",
":contour",
"]",
"=",
"contour_item",
"end",
"@dcm",
"[",
"RT_ROI_OBS_SQ",
"]",
".",
"each",
"do",
"|",
"rt_item",
"|",
"item_group",
"[",
"rt_item",
".",
"value",
"(",
"REF_ROI_NUMBER",
")",
"]",
"[",
":rt",
"]",
"=",
"rt_item",
"end",
"item_group",
".",
"each_value",
"do",
"|",
"roi_items",
"|",
"Structure",
".",
"create_from_items",
"(",
"roi_items",
"[",
":roi",
"]",
",",
"roi_items",
"[",
":contour",
"]",
",",
"roi_items",
"[",
":rt",
"]",
",",
"self",
")",
"end",
"else",
"RTKIT",
".",
"logger",
".",
"warn",
"\"The structure set contained one or more empty ROI sequences. No ROIs extracted.\"",
"end",
"end"
]
| Loads the ROI Items contained in the structure set and creates ROI
and POI instances, which are referenced to this structure set. | [
"Loads",
"the",
"ROI",
"Items",
"contained",
"in",
"the",
"structure",
"set",
"and",
"creates",
"ROI",
"and",
"POI",
"instances",
"which",
"are",
"referenced",
"to",
"this",
"structure",
"set",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/structure_set.rb#L475-L495 | train |
dicom/rtkit | lib/rtkit/frame.rb | RTKIT.Frame.add_image | def add_image(image)
raise ArgumentError, "Invalid argument 'image'. Expected Image, got #{image.class}." unless image.is_a?(Image)
@associated_instance_uids[image.uid] = image
# If the ImageSeries of an added Image is not connected to this Frame yet, do so:
add_series(image.series) unless series(image.series.uid)
end | ruby | def add_image(image)
raise ArgumentError, "Invalid argument 'image'. Expected Image, got #{image.class}." unless image.is_a?(Image)
@associated_instance_uids[image.uid] = image
# If the ImageSeries of an added Image is not connected to this Frame yet, do so:
add_series(image.series) unless series(image.series.uid)
end | [
"def",
"add_image",
"(",
"image",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'image'. Expected Image, got #{image.class}.\"",
"unless",
"image",
".",
"is_a?",
"(",
"Image",
")",
"@associated_instance_uids",
"[",
"image",
".",
"uid",
"]",
"=",
"image",
"add_series",
"(",
"image",
".",
"series",
")",
"unless",
"series",
"(",
"image",
".",
"series",
".",
"uid",
")",
"end"
]
| Adds an Image to this Frame.
@param [Image] image an image instance to be associated with this frame | [
"Adds",
"an",
"Image",
"to",
"this",
"Frame",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/frame.rb#L67-L72 | train |
dicom/rtkit | lib/rtkit/frame.rb | RTKIT.Frame.add_series | def add_series(series)
raise ArgumentError, "Invalid argument 'series' Expected ImageSeries or DoseVolume, got #{series.class}." unless [ImageSeries, DoseVolume].include?(series.class)
@image_series << series
@associated_series[series.uid] = series
end | ruby | def add_series(series)
raise ArgumentError, "Invalid argument 'series' Expected ImageSeries or DoseVolume, got #{series.class}." unless [ImageSeries, DoseVolume].include?(series.class)
@image_series << series
@associated_series[series.uid] = series
end | [
"def",
"add_series",
"(",
"series",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'series' Expected ImageSeries or DoseVolume, got #{series.class}.\"",
"unless",
"[",
"ImageSeries",
",",
"DoseVolume",
"]",
".",
"include?",
"(",
"series",
".",
"class",
")",
"@image_series",
"<<",
"series",
"@associated_series",
"[",
"series",
".",
"uid",
"]",
"=",
"series",
"end"
]
| Adds an ImageSeries to this Frame.
@param [ImageSeries, DoseVolume] series an image series instance to be associated with this frame | [
"Adds",
"an",
"ImageSeries",
"to",
"this",
"Frame",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/frame.rb#L87-L91 | train |
dicom/rtkit | lib/rtkit/contour.rb | RTKIT.Contour.add_coordinate | def add_coordinate(coordinate)
raise ArgumentError, "Invalid argument 'coordinate'. Expected Coordinate, got #{coordinate.class}." unless coordinate.is_a?(Coordinate)
@coordinates << coordinate unless @coordinates.include?(coordinate)
end | ruby | def add_coordinate(coordinate)
raise ArgumentError, "Invalid argument 'coordinate'. Expected Coordinate, got #{coordinate.class}." unless coordinate.is_a?(Coordinate)
@coordinates << coordinate unless @coordinates.include?(coordinate)
end | [
"def",
"add_coordinate",
"(",
"coordinate",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'coordinate'. Expected Coordinate, got #{coordinate.class}.\"",
"unless",
"coordinate",
".",
"is_a?",
"(",
"Coordinate",
")",
"@coordinates",
"<<",
"coordinate",
"unless",
"@coordinates",
".",
"include?",
"(",
"coordinate",
")",
"end"
]
| Adds a Coordinate instance to this Contour.
@param [Coordinate] coordinate a coordinate instance to be associated with this contour | [
"Adds",
"a",
"Coordinate",
"instance",
"to",
"this",
"Contour",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/contour.rb#L114-L117 | train |
dicom/rtkit | lib/rtkit/contour.rb | RTKIT.Contour.coords | def coords
x, y, z = Array.new, Array.new, Array.new
@coordinates.each do |coord|
x << coord.x
y << coord.y
z << coord.z
end
return x, y, z
end | ruby | def coords
x, y, z = Array.new, Array.new, Array.new
@coordinates.each do |coord|
x << coord.x
y << coord.y
z << coord.z
end
return x, y, z
end | [
"def",
"coords",
"x",
",",
"y",
",",
"z",
"=",
"Array",
".",
"new",
",",
"Array",
".",
"new",
",",
"Array",
".",
"new",
"@coordinates",
".",
"each",
"do",
"|",
"coord",
"|",
"x",
"<<",
"coord",
".",
"x",
"y",
"<<",
"coord",
".",
"y",
"z",
"<<",
"coord",
".",
"z",
"end",
"return",
"x",
",",
"y",
",",
"z",
"end"
]
| Extracts and transposes all coordinates of this contour, such that the
coordinates are given in arrays of x, y and z coordinates.
@return [Array] the coordinates of this contour, converted to x, y and z arrays | [
"Extracts",
"and",
"transposes",
"all",
"coordinates",
"of",
"this",
"contour",
"such",
"that",
"the",
"coordinates",
"are",
"given",
"in",
"arrays",
"of",
"x",
"y",
"and",
"z",
"coordinates",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/contour.rb#L134-L142 | train |
dicom/rtkit | lib/rtkit/contour.rb | RTKIT.Contour.create_coordinates | def create_coordinates(contour_data)
raise ArgumentError, "Invalid argument 'contour_data'. Expected String (or nil), got #{contour_data.class}." unless [String, NilClass].include?(contour_data.class)
if contour_data && contour_data != ""
# Split the number strings, sperated by a '\', into an array:
string_values = contour_data.split("\\")
size = string_values.length/3
# Extract every third value of the string array as x, y, and z, respectively, and collect them as floats instead of strings:
x = string_values.values_at(*(Array.new(size){|i| i*3 })).collect{|val| val.to_f}
y = string_values.values_at(*(Array.new(size){|i| i*3+1})).collect{|val| val.to_f}
z = string_values.values_at(*(Array.new(size){|i| i*3+2})).collect{|val| val.to_f}
x.each_index do |i|
Coordinate.new(x[i], y[i], z[i], self)
end
end
end | ruby | def create_coordinates(contour_data)
raise ArgumentError, "Invalid argument 'contour_data'. Expected String (or nil), got #{contour_data.class}." unless [String, NilClass].include?(contour_data.class)
if contour_data && contour_data != ""
# Split the number strings, sperated by a '\', into an array:
string_values = contour_data.split("\\")
size = string_values.length/3
# Extract every third value of the string array as x, y, and z, respectively, and collect them as floats instead of strings:
x = string_values.values_at(*(Array.new(size){|i| i*3 })).collect{|val| val.to_f}
y = string_values.values_at(*(Array.new(size){|i| i*3+1})).collect{|val| val.to_f}
z = string_values.values_at(*(Array.new(size){|i| i*3+2})).collect{|val| val.to_f}
x.each_index do |i|
Coordinate.new(x[i], y[i], z[i], self)
end
end
end | [
"def",
"create_coordinates",
"(",
"contour_data",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'contour_data'. Expected String (or nil), got #{contour_data.class}.\"",
"unless",
"[",
"String",
",",
"NilClass",
"]",
".",
"include?",
"(",
"contour_data",
".",
"class",
")",
"if",
"contour_data",
"&&",
"contour_data",
"!=",
"\"\"",
"string_values",
"=",
"contour_data",
".",
"split",
"(",
"\"\\\\\"",
")",
"size",
"=",
"string_values",
".",
"length",
"/",
"3",
"x",
"=",
"string_values",
".",
"values_at",
"(",
"*",
"(",
"Array",
".",
"new",
"(",
"size",
")",
"{",
"|",
"i",
"|",
"i",
"*",
"3",
"}",
")",
")",
".",
"collect",
"{",
"|",
"val",
"|",
"val",
".",
"to_f",
"}",
"y",
"=",
"string_values",
".",
"values_at",
"(",
"*",
"(",
"Array",
".",
"new",
"(",
"size",
")",
"{",
"|",
"i",
"|",
"i",
"*",
"3",
"+",
"1",
"}",
")",
")",
".",
"collect",
"{",
"|",
"val",
"|",
"val",
".",
"to_f",
"}",
"z",
"=",
"string_values",
".",
"values_at",
"(",
"*",
"(",
"Array",
".",
"new",
"(",
"size",
")",
"{",
"|",
"i",
"|",
"i",
"*",
"3",
"+",
"2",
"}",
")",
")",
".",
"collect",
"{",
"|",
"val",
"|",
"val",
".",
"to_f",
"}",
"x",
".",
"each_index",
"do",
"|",
"i",
"|",
"Coordinate",
".",
"new",
"(",
"x",
"[",
"i",
"]",
",",
"y",
"[",
"i",
"]",
",",
"z",
"[",
"i",
"]",
",",
"self",
")",
"end",
"end",
"end"
]
| Creates and connects Coordinate instances with this Contour instance
by processing the value of the Contour Data element value.
@param [String, NilClass] contour_data a string containing x,y,z coordinate triplets separated by '\' | [
"Creates",
"and",
"connects",
"Coordinate",
"instances",
"with",
"this",
"Contour",
"instance",
"by",
"processing",
"the",
"value",
"of",
"the",
"Contour",
"Data",
"element",
"value",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/contour.rb#L149-L163 | train |
dicom/rtkit | lib/rtkit/contour.rb | RTKIT.Contour.to_item | def to_item
# FIXME: We need to decide on how to principally handle the situation when an image series has not been
# loaded, and how to set up the ROI slices. A possible solution is to create Image instances if they hasn't been loaded.
item = DICOM::Item.new
item.add(DICOM::Sequence.new(CONTOUR_IMAGE_SQ))
item[CONTOUR_IMAGE_SQ].add_item
item[CONTOUR_IMAGE_SQ][0].add(DICOM::Element.new(REF_SOP_CLASS_UID, @slice.image ? @slice.image.series.class_uid : '1.2.840.10008.5.1.4.1.1.2')) # Deafult to CT if image ref. doesn't exist.
item[CONTOUR_IMAGE_SQ][0].add(DICOM::Element.new(REF_SOP_UID, @slice.uid))
item.add(DICOM::Element.new(CONTOUR_GEO_TYPE, @type))
item.add(DICOM::Element.new(NR_CONTOUR_POINTS, @coordinates.length.to_s))
item.add(DICOM::Element.new(CONTOUR_NUMBER, @number.to_s))
item.add(DICOM::Element.new(CONTOUR_DATA, contour_data))
return item
end | ruby | def to_item
# FIXME: We need to decide on how to principally handle the situation when an image series has not been
# loaded, and how to set up the ROI slices. A possible solution is to create Image instances if they hasn't been loaded.
item = DICOM::Item.new
item.add(DICOM::Sequence.new(CONTOUR_IMAGE_SQ))
item[CONTOUR_IMAGE_SQ].add_item
item[CONTOUR_IMAGE_SQ][0].add(DICOM::Element.new(REF_SOP_CLASS_UID, @slice.image ? @slice.image.series.class_uid : '1.2.840.10008.5.1.4.1.1.2')) # Deafult to CT if image ref. doesn't exist.
item[CONTOUR_IMAGE_SQ][0].add(DICOM::Element.new(REF_SOP_UID, @slice.uid))
item.add(DICOM::Element.new(CONTOUR_GEO_TYPE, @type))
item.add(DICOM::Element.new(NR_CONTOUR_POINTS, @coordinates.length.to_s))
item.add(DICOM::Element.new(CONTOUR_NUMBER, @number.to_s))
item.add(DICOM::Element.new(CONTOUR_DATA, contour_data))
return item
end | [
"def",
"to_item",
"item",
"=",
"DICOM",
"::",
"Item",
".",
"new",
"item",
".",
"add",
"(",
"DICOM",
"::",
"Sequence",
".",
"new",
"(",
"CONTOUR_IMAGE_SQ",
")",
")",
"item",
"[",
"CONTOUR_IMAGE_SQ",
"]",
".",
"add_item",
"item",
"[",
"CONTOUR_IMAGE_SQ",
"]",
"[",
"0",
"]",
".",
"add",
"(",
"DICOM",
"::",
"Element",
".",
"new",
"(",
"REF_SOP_CLASS_UID",
",",
"@slice",
".",
"image",
"?",
"@slice",
".",
"image",
".",
"series",
".",
"class_uid",
":",
"'1.2.840.10008.5.1.4.1.1.2'",
")",
")",
"item",
"[",
"CONTOUR_IMAGE_SQ",
"]",
"[",
"0",
"]",
".",
"add",
"(",
"DICOM",
"::",
"Element",
".",
"new",
"(",
"REF_SOP_UID",
",",
"@slice",
".",
"uid",
")",
")",
"item",
".",
"add",
"(",
"DICOM",
"::",
"Element",
".",
"new",
"(",
"CONTOUR_GEO_TYPE",
",",
"@type",
")",
")",
"item",
".",
"add",
"(",
"DICOM",
"::",
"Element",
".",
"new",
"(",
"NR_CONTOUR_POINTS",
",",
"@coordinates",
".",
"length",
".",
"to_s",
")",
")",
"item",
".",
"add",
"(",
"DICOM",
"::",
"Element",
".",
"new",
"(",
"CONTOUR_NUMBER",
",",
"@number",
".",
"to_s",
")",
")",
"item",
".",
"add",
"(",
"DICOM",
"::",
"Element",
".",
"new",
"(",
"CONTOUR_DATA",
",",
"contour_data",
")",
")",
"return",
"item",
"end"
]
| Creates a Contour Sequence Item from the attributes of the Contour.
@return [DICOM::Item] the created DICOM item | [
"Creates",
"a",
"Contour",
"Sequence",
"Item",
"from",
"the",
"attributes",
"of",
"the",
"Contour",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/contour.rb#L187-L200 | train |
dicom/rtkit | lib/rtkit/contour.rb | RTKIT.Contour.translate | def translate(x, y, z)
@coordinates.each do |c|
c.translate(x, y, z)
end
end | ruby | def translate(x, y, z)
@coordinates.each do |c|
c.translate(x, y, z)
end
end | [
"def",
"translate",
"(",
"x",
",",
"y",
",",
"z",
")",
"@coordinates",
".",
"each",
"do",
"|",
"c",
"|",
"c",
".",
"translate",
"(",
"x",
",",
"y",
",",
"z",
")",
"end",
"end"
]
| Moves the coordinates of this contour according to the given offset
vector.
@param [Float] x the offset along the x axis (in units of mm)
@param [Float] y the offset along the y axis (in units of mm)
@param [Float] z the offset along the z axis (in units of mm) | [
"Moves",
"the",
"coordinates",
"of",
"this",
"contour",
"according",
"to",
"the",
"given",
"offset",
"vector",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/contour.rb#L209-L213 | train |
celluloid/dcell | lib/dcell/server.rb | DCell.MessageHandler.handle_message | def handle_message(message)
begin
message = decode_message message
rescue InvalidMessageError => ex
Logger.crash("couldn't decode message", ex)
return
end
begin
message.dispatch
rescue => ex
Logger.crash("message dispatch failed", ex)
end
end | ruby | def handle_message(message)
begin
message = decode_message message
rescue InvalidMessageError => ex
Logger.crash("couldn't decode message", ex)
return
end
begin
message.dispatch
rescue => ex
Logger.crash("message dispatch failed", ex)
end
end | [
"def",
"handle_message",
"(",
"message",
")",
"begin",
"message",
"=",
"decode_message",
"message",
"rescue",
"InvalidMessageError",
"=>",
"ex",
"Logger",
".",
"crash",
"(",
"\"couldn't decode message\"",
",",
"ex",
")",
"return",
"end",
"begin",
"message",
".",
"dispatch",
"rescue",
"=>",
"ex",
"Logger",
".",
"crash",
"(",
"\"message dispatch failed\"",
",",
"ex",
")",
"end",
"end"
]
| Handle incoming messages | [
"Handle",
"incoming",
"messages"
]
| a8fecfae220cb2c20d3761bc27880e4133aba498 | https://github.com/celluloid/dcell/blob/a8fecfae220cb2c20d3761bc27880e4133aba498/lib/dcell/server.rb#L8-L21 | train |
celluloid/dcell | lib/dcell/server.rb | DCell.MessageHandler.decode_message | def decode_message(message)
begin
msg = MessagePack.unpack(message, symbolize_keys: true)
rescue => ex
raise InvalidMessageError, "couldn't unpack message: #{ex}"
end
begin
klass = Utils.full_const_get msg[:type]
o = klass.new(*msg[:args])
o.id = msg[:id] if o.respond_to?(:id=) && msg[:id]
o
rescue => ex
raise InvalidMessageError, "invalid message: #{ex}"
end
end | ruby | def decode_message(message)
begin
msg = MessagePack.unpack(message, symbolize_keys: true)
rescue => ex
raise InvalidMessageError, "couldn't unpack message: #{ex}"
end
begin
klass = Utils.full_const_get msg[:type]
o = klass.new(*msg[:args])
o.id = msg[:id] if o.respond_to?(:id=) && msg[:id]
o
rescue => ex
raise InvalidMessageError, "invalid message: #{ex}"
end
end | [
"def",
"decode_message",
"(",
"message",
")",
"begin",
"msg",
"=",
"MessagePack",
".",
"unpack",
"(",
"message",
",",
"symbolize_keys",
":",
"true",
")",
"rescue",
"=>",
"ex",
"raise",
"InvalidMessageError",
",",
"\"couldn't unpack message: #{ex}\"",
"end",
"begin",
"klass",
"=",
"Utils",
".",
"full_const_get",
"msg",
"[",
":type",
"]",
"o",
"=",
"klass",
".",
"new",
"(",
"*",
"msg",
"[",
":args",
"]",
")",
"o",
".",
"id",
"=",
"msg",
"[",
":id",
"]",
"if",
"o",
".",
"respond_to?",
"(",
":id=",
")",
"&&",
"msg",
"[",
":id",
"]",
"o",
"rescue",
"=>",
"ex",
"raise",
"InvalidMessageError",
",",
"\"invalid message: #{ex}\"",
"end",
"end"
]
| Decode incoming messages | [
"Decode",
"incoming",
"messages"
]
| a8fecfae220cb2c20d3761bc27880e4133aba498 | https://github.com/celluloid/dcell/blob/a8fecfae220cb2c20d3761bc27880e4133aba498/lib/dcell/server.rb#L24-L38 | train |
celluloid/dcell | lib/dcell/server.rb | DCell.Server.run | def run
while true
message = @socket.read_multipart
if @socket.is_a? Celluloid::ZMQ::RouterSocket
message = message[1]
else
message = message[0]
end
handle_message message
end
end | ruby | def run
while true
message = @socket.read_multipart
if @socket.is_a? Celluloid::ZMQ::RouterSocket
message = message[1]
else
message = message[0]
end
handle_message message
end
end | [
"def",
"run",
"while",
"true",
"message",
"=",
"@socket",
".",
"read_multipart",
"if",
"@socket",
".",
"is_a?",
"Celluloid",
"::",
"ZMQ",
"::",
"RouterSocket",
"message",
"=",
"message",
"[",
"1",
"]",
"else",
"message",
"=",
"message",
"[",
"0",
"]",
"end",
"handle_message",
"message",
"end",
"end"
]
| Wait for incoming 0MQ messages | [
"Wait",
"for",
"incoming",
"0MQ",
"messages"
]
| a8fecfae220cb2c20d3761bc27880e4133aba498 | https://github.com/celluloid/dcell/blob/a8fecfae220cb2c20d3761bc27880e4133aba498/lib/dcell/server.rb#L80-L90 | train |
jlong/radius | lib/radius/parser/scanner.rb | Radius.Scanner.operate | def operate(prefix, data)
data = Radius::OrdString.new data
@nodes = ['']
re = scanner_regex(prefix)
if md = re.match(data)
remainder = ''
while md
start_tag, attributes, self_enclosed, end_tag = $1, $2, $3, $4
flavor = self_enclosed == '/' ? :self : (start_tag ? :open : :close)
# save the part before the current match as a string node
@nodes << md.pre_match
# save the tag that was found as a tag hash node
@nodes << {:prefix=>prefix, :name=>(start_tag || end_tag), :flavor => flavor, :attrs => parse_attributes(attributes)}
# remember the part after the current match
remainder = md.post_match
# see if we find another tag in the remaining string
md = re.match(md.post_match)
end
# add the last remaining string after the last tag that was found as a string node
@nodes << remainder
else
@nodes << data
end
return @nodes
end | ruby | def operate(prefix, data)
data = Radius::OrdString.new data
@nodes = ['']
re = scanner_regex(prefix)
if md = re.match(data)
remainder = ''
while md
start_tag, attributes, self_enclosed, end_tag = $1, $2, $3, $4
flavor = self_enclosed == '/' ? :self : (start_tag ? :open : :close)
# save the part before the current match as a string node
@nodes << md.pre_match
# save the tag that was found as a tag hash node
@nodes << {:prefix=>prefix, :name=>(start_tag || end_tag), :flavor => flavor, :attrs => parse_attributes(attributes)}
# remember the part after the current match
remainder = md.post_match
# see if we find another tag in the remaining string
md = re.match(md.post_match)
end
# add the last remaining string after the last tag that was found as a string node
@nodes << remainder
else
@nodes << data
end
return @nodes
end | [
"def",
"operate",
"(",
"prefix",
",",
"data",
")",
"data",
"=",
"Radius",
"::",
"OrdString",
".",
"new",
"data",
"@nodes",
"=",
"[",
"''",
"]",
"re",
"=",
"scanner_regex",
"(",
"prefix",
")",
"if",
"md",
"=",
"re",
".",
"match",
"(",
"data",
")",
"remainder",
"=",
"''",
"while",
"md",
"start_tag",
",",
"attributes",
",",
"self_enclosed",
",",
"end_tag",
"=",
"$1",
",",
"$2",
",",
"$3",
",",
"$4",
"flavor",
"=",
"self_enclosed",
"==",
"'/'",
"?",
":self",
":",
"(",
"start_tag",
"?",
":open",
":",
":close",
")",
"@nodes",
"<<",
"md",
".",
"pre_match",
"@nodes",
"<<",
"{",
":prefix",
"=>",
"prefix",
",",
":name",
"=>",
"(",
"start_tag",
"||",
"end_tag",
")",
",",
":flavor",
"=>",
"flavor",
",",
":attrs",
"=>",
"parse_attributes",
"(",
"attributes",
")",
"}",
"remainder",
"=",
"md",
".",
"post_match",
"md",
"=",
"re",
".",
"match",
"(",
"md",
".",
"post_match",
")",
"end",
"@nodes",
"<<",
"remainder",
"else",
"@nodes",
"<<",
"data",
"end",
"return",
"@nodes",
"end"
]
| Parses a given string and returns an array of nodes.
The nodes consist of strings and hashes that describe a Radius tag that was found. | [
"Parses",
"a",
"given",
"string",
"and",
"returns",
"an",
"array",
"of",
"nodes",
".",
"The",
"nodes",
"consist",
"of",
"strings",
"and",
"hashes",
"that",
"describe",
"a",
"Radius",
"tag",
"that",
"was",
"found",
"."
]
| e7b4eab374c6a15e105524ccd663767b8bc91e5b | https://github.com/jlong/radius/blob/e7b4eab374c6a15e105524ccd663767b8bc91e5b/lib/radius/parser/scanner.rb#L12-L44 | train |
slagyr/limelight | ruby/lib/limelight/theater.rb | Limelight.Theater.add_stage | def add_stage(name, options = {})
stage = build_stage(name, options).proxy
@peer.add(stage.peer)
return stage
end | ruby | def add_stage(name, options = {})
stage = build_stage(name, options).proxy
@peer.add(stage.peer)
return stage
end | [
"def",
"add_stage",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"stage",
"=",
"build_stage",
"(",
"name",
",",
"options",
")",
".",
"proxy",
"@peer",
".",
"add",
"(",
"stage",
".",
"peer",
")",
"return",
"stage",
"end"
]
| Adds a Stage to the Theater. Raises an exception is the name of the Stage is duplicated. | [
"Adds",
"a",
"Stage",
"to",
"the",
"Theater",
".",
"Raises",
"an",
"exception",
"is",
"the",
"name",
"of",
"the",
"Stage",
"is",
"duplicated",
"."
]
| 2e8db684771587422d55a9329e895481e9b56a26 | https://github.com/slagyr/limelight/blob/2e8db684771587422d55a9329e895481e9b56a26/ruby/lib/limelight/theater.rb#L52-L56 | train |
dicom/rtkit | lib/rtkit/bin_matcher.rb | RTKIT.BinMatcher.fill_blanks | def fill_blanks
if @volumes.length > 0
# Register all unique images referenced by the various volumes:
images = Set.new
# Include the master volume (if it is present):
[@volumes, @master].flatten.compact.each do |volume|
volume.bin_images.each do |bin_image|
images << bin_image.image unless images.include?(bin_image.image)
end
end
# Check if any of the volumes have images missing, and if so, create empty images:
images.each do |image|
[@volumes, @master].flatten.compact.each do |volume|
match = false
volume.bin_images.each do |bin_image|
match = true if bin_image.image == image
end
unless match
# Create BinImage:
bin_img = BinImage.new(NArray.byte(image.columns, image.rows), image)
volume.add(bin_img)
end
end
end
end
end | ruby | def fill_blanks
if @volumes.length > 0
# Register all unique images referenced by the various volumes:
images = Set.new
# Include the master volume (if it is present):
[@volumes, @master].flatten.compact.each do |volume|
volume.bin_images.each do |bin_image|
images << bin_image.image unless images.include?(bin_image.image)
end
end
# Check if any of the volumes have images missing, and if so, create empty images:
images.each do |image|
[@volumes, @master].flatten.compact.each do |volume|
match = false
volume.bin_images.each do |bin_image|
match = true if bin_image.image == image
end
unless match
# Create BinImage:
bin_img = BinImage.new(NArray.byte(image.columns, image.rows), image)
volume.add(bin_img)
end
end
end
end
end | [
"def",
"fill_blanks",
"if",
"@volumes",
".",
"length",
">",
"0",
"images",
"=",
"Set",
".",
"new",
"[",
"@volumes",
",",
"@master",
"]",
".",
"flatten",
".",
"compact",
".",
"each",
"do",
"|",
"volume",
"|",
"volume",
".",
"bin_images",
".",
"each",
"do",
"|",
"bin_image",
"|",
"images",
"<<",
"bin_image",
".",
"image",
"unless",
"images",
".",
"include?",
"(",
"bin_image",
".",
"image",
")",
"end",
"end",
"images",
".",
"each",
"do",
"|",
"image",
"|",
"[",
"@volumes",
",",
"@master",
"]",
".",
"flatten",
".",
"compact",
".",
"each",
"do",
"|",
"volume",
"|",
"match",
"=",
"false",
"volume",
".",
"bin_images",
".",
"each",
"do",
"|",
"bin_image",
"|",
"match",
"=",
"true",
"if",
"bin_image",
".",
"image",
"==",
"image",
"end",
"unless",
"match",
"bin_img",
"=",
"BinImage",
".",
"new",
"(",
"NArray",
".",
"byte",
"(",
"image",
".",
"columns",
",",
"image",
".",
"rows",
")",
",",
"image",
")",
"volume",
".",
"add",
"(",
"bin_img",
")",
"end",
"end",
"end",
"end",
"end"
]
| Ensures that a valid comparison between volumes can be done, by making
sure that every volume has a BinImage for any image that is referenced
among the BinVolumes. If some BinVolumes are missing one or more
BinImages, empty BinImages will be created for these BinVolumes.
@note The master volume (if present) is also processed by this method. | [
"Ensures",
"that",
"a",
"valid",
"comparison",
"between",
"volumes",
"can",
"be",
"done",
"by",
"making",
"sure",
"that",
"every",
"volume",
"has",
"a",
"BinImage",
"for",
"any",
"image",
"that",
"is",
"referenced",
"among",
"the",
"BinVolumes",
".",
"If",
"some",
"BinVolumes",
"are",
"missing",
"one",
"or",
"more",
"BinImages",
"empty",
"BinImages",
"will",
"be",
"created",
"for",
"these",
"BinVolumes",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/bin_matcher.rb#L79-L104 | train |
dicom/rtkit | lib/rtkit/dose_volume.rb | RTKIT.DoseVolume.add_image | def add_image(image)
raise ArgumentError, "Invalid argument 'image'. Expected Image, got #{image.class}." unless image.is_a?(Image)
@images << image unless @associated_images[image.uid]
@associated_images[image.uid] = image
@image_positions[image.pos_slice.round(2)] = image
end | ruby | def add_image(image)
raise ArgumentError, "Invalid argument 'image'. Expected Image, got #{image.class}." unless image.is_a?(Image)
@images << image unless @associated_images[image.uid]
@associated_images[image.uid] = image
@image_positions[image.pos_slice.round(2)] = image
end | [
"def",
"add_image",
"(",
"image",
")",
"raise",
"ArgumentError",
",",
"\"Invalid argument 'image'. Expected Image, got #{image.class}.\"",
"unless",
"image",
".",
"is_a?",
"(",
"Image",
")",
"@images",
"<<",
"image",
"unless",
"@associated_images",
"[",
"image",
".",
"uid",
"]",
"@associated_images",
"[",
"image",
".",
"uid",
"]",
"=",
"image",
"@image_positions",
"[",
"image",
".",
"pos_slice",
".",
"round",
"(",
"2",
")",
"]",
"=",
"image",
"end"
]
| Adds an Image to this Volume.
@param [Image] image an image instance to be associated with this dose volume | [
"Adds",
"an",
"Image",
"to",
"this",
"Volume",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/dose_volume.rb#L138-L143 | train |
dicom/rtkit | lib/rtkit/dose_volume.rb | RTKIT.DoseVolume.image_by_slice_pos | def image_by_slice_pos(pos)
# Step 1: Try for an (exact) match:
image = @image_positions[pos.round(2)]
# Step 2: If no match, try to search for a close match:
# (A close match is defined as the given slice position being within 1/3 of the
# slice distance from an existing image instance in the series)
if !image && @images.length > 1
proximity = @images.collect{|img| (img.pos_slice - pos).abs}
if proximity.min < slice_spacing / 3.0
index = proximity.index(proximity.min)
image = @images[index]
end
end
return image
end | ruby | def image_by_slice_pos(pos)
# Step 1: Try for an (exact) match:
image = @image_positions[pos.round(2)]
# Step 2: If no match, try to search for a close match:
# (A close match is defined as the given slice position being within 1/3 of the
# slice distance from an existing image instance in the series)
if !image && @images.length > 1
proximity = @images.collect{|img| (img.pos_slice - pos).abs}
if proximity.min < slice_spacing / 3.0
index = proximity.index(proximity.min)
image = @images[index]
end
end
return image
end | [
"def",
"image_by_slice_pos",
"(",
"pos",
")",
"image",
"=",
"@image_positions",
"[",
"pos",
".",
"round",
"(",
"2",
")",
"]",
"if",
"!",
"image",
"&&",
"@images",
".",
"length",
">",
"1",
"proximity",
"=",
"@images",
".",
"collect",
"{",
"|",
"img",
"|",
"(",
"img",
".",
"pos_slice",
"-",
"pos",
")",
".",
"abs",
"}",
"if",
"proximity",
".",
"min",
"<",
"slice_spacing",
"/",
"3.0",
"index",
"=",
"proximity",
".",
"index",
"(",
"proximity",
".",
"min",
")",
"image",
"=",
"@images",
"[",
"index",
"]",
"end",
"end",
"return",
"image",
"end"
]
| Returns an image instance matched by the given slice position.
@param [Float] pos image slice position
@return [Image, NilClass] the matched image (or nil if no image is matched) | [
"Returns",
"an",
"image",
"instance",
"matched",
"by",
"the",
"given",
"slice",
"position",
"."
]
| 08248bf294769ae5b45ed4a9671f0620d5740252 | https://github.com/dicom/rtkit/blob/08248bf294769ae5b45ed4a9671f0620d5740252/lib/rtkit/dose_volume.rb#L288-L302 | train |
dradis/dradis-plugins | lib/dradis/plugins/settings.rb | Dradis::Plugins.Settings.dirty_or_db_setting_or_default | def dirty_or_db_setting_or_default(key)
if @dirty_options.key?(key)
@dirty_options[key]
elsif Configuration.exists?(name: namespaced_key(key))
db_setting(key)
else
@default_options[key]
end
end | ruby | def dirty_or_db_setting_or_default(key)
if @dirty_options.key?(key)
@dirty_options[key]
elsif Configuration.exists?(name: namespaced_key(key))
db_setting(key)
else
@default_options[key]
end
end | [
"def",
"dirty_or_db_setting_or_default",
"(",
"key",
")",
"if",
"@dirty_options",
".",
"key?",
"(",
"key",
")",
"@dirty_options",
"[",
"key",
"]",
"elsif",
"Configuration",
".",
"exists?",
"(",
"name",
":",
"namespaced_key",
"(",
"key",
")",
")",
"db_setting",
"(",
"key",
")",
"else",
"@default_options",
"[",
"key",
"]",
"end",
"end"
]
| This method looks up in the configuration repository DB to see if the
user has provided a value for the given setting. If not, the default
value is returned. | [
"This",
"method",
"looks",
"up",
"in",
"the",
"configuration",
"repository",
"DB",
"to",
"see",
"if",
"the",
"user",
"has",
"provided",
"a",
"value",
"for",
"the",
"given",
"setting",
".",
"If",
"not",
"the",
"default",
"value",
"is",
"returned",
"."
]
| 570367ba16e42dae3f3065a6b72c544dd780ca36 | https://github.com/dradis/dradis-plugins/blob/570367ba16e42dae3f3065a6b72c544dd780ca36/lib/dradis/plugins/settings.rb#L76-L84 | train |
dradis/dradis-plugins | lib/dradis/plugins/content_service/issues.rb | Dradis::Plugins::ContentService.Issues.issue_cache | def issue_cache
@issue_cache ||= begin
issues_map = all_issues.map do |issue|
cache_key = [
issue.fields['plugin'],
issue.fields['plugin_id']
].join('-')
[cache_key, issue]
end
Hash[issues_map]
end
end | ruby | def issue_cache
@issue_cache ||= begin
issues_map = all_issues.map do |issue|
cache_key = [
issue.fields['plugin'],
issue.fields['plugin_id']
].join('-')
[cache_key, issue]
end
Hash[issues_map]
end
end | [
"def",
"issue_cache",
"@issue_cache",
"||=",
"begin",
"issues_map",
"=",
"all_issues",
".",
"map",
"do",
"|",
"issue",
"|",
"cache_key",
"=",
"[",
"issue",
".",
"fields",
"[",
"'plugin'",
"]",
",",
"issue",
".",
"fields",
"[",
"'plugin_id'",
"]",
"]",
".",
"join",
"(",
"'-'",
")",
"[",
"cache_key",
",",
"issue",
"]",
"end",
"Hash",
"[",
"issues_map",
"]",
"end",
"end"
]
| Create a hash with all issues where the keys correspond to the field passed
as an argument.
This is use by the plugins to check whether a given issue is already in
the project.
def all_issues_by_field(field)
# we don't memoize it because we want it to reflect recently added Issues
klass = class_for(:issue)
issues_map = klass.where(category_id: default_issue_category.id).map do |issue|
[issue.fields[field], issue]
end
Hash[issues_map]
end
Accesing the library by primary sorting key. Raise an exception unless
the issue library cache has been initialized. | [
"Create",
"a",
"hash",
"with",
"all",
"issues",
"where",
"the",
"keys",
"correspond",
"to",
"the",
"field",
"passed",
"as",
"an",
"argument",
"."
]
| 570367ba16e42dae3f3065a6b72c544dd780ca36 | https://github.com/dradis/dradis-plugins/blob/570367ba16e42dae3f3065a6b72c544dd780ca36/lib/dradis/plugins/content_service/issues.rb#L65-L77 | train |
bunto/bunto | lib/bunto/renderer.rb | Bunto.Renderer.render_liquid | def render_liquid(content, payload, info, path = nil)
template = site.liquid_renderer.file(path).parse(content)
template.warnings.each do |e|
Bunto.logger.warn "Liquid Warning:",
LiquidRenderer.format_error(e, path || document.relative_path)
end
template.render!(payload, info)
# rubocop: disable RescueException
rescue Exception => e
Bunto.logger.error "Liquid Exception:",
LiquidRenderer.format_error(e, path || document.relative_path)
raise e
end | ruby | def render_liquid(content, payload, info, path = nil)
template = site.liquid_renderer.file(path).parse(content)
template.warnings.each do |e|
Bunto.logger.warn "Liquid Warning:",
LiquidRenderer.format_error(e, path || document.relative_path)
end
template.render!(payload, info)
# rubocop: disable RescueException
rescue Exception => e
Bunto.logger.error "Liquid Exception:",
LiquidRenderer.format_error(e, path || document.relative_path)
raise e
end | [
"def",
"render_liquid",
"(",
"content",
",",
"payload",
",",
"info",
",",
"path",
"=",
"nil",
")",
"template",
"=",
"site",
".",
"liquid_renderer",
".",
"file",
"(",
"path",
")",
".",
"parse",
"(",
"content",
")",
"template",
".",
"warnings",
".",
"each",
"do",
"|",
"e",
"|",
"Bunto",
".",
"logger",
".",
"warn",
"\"Liquid Warning:\"",
",",
"LiquidRenderer",
".",
"format_error",
"(",
"e",
",",
"path",
"||",
"document",
".",
"relative_path",
")",
"end",
"template",
".",
"render!",
"(",
"payload",
",",
"info",
")",
"rescue",
"Exception",
"=>",
"e",
"Bunto",
".",
"logger",
".",
"error",
"\"Liquid Exception:\"",
",",
"LiquidRenderer",
".",
"format_error",
"(",
"e",
",",
"path",
"||",
"document",
".",
"relative_path",
")",
"raise",
"e",
"end"
]
| Render the given content with the payload and info
content -
payload -
info -
path - (optional) the path to the file, for use in ex
Returns the content, rendered by Liquid. | [
"Render",
"the",
"given",
"content",
"with",
"the",
"payload",
"and",
"info"
]
| 45d993fb22329b12c277e15195af3415c9922a28 | https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/renderer.rb#L128-L140 | train |
bunto/bunto | lib/bunto/renderer.rb | Bunto.Renderer.place_in_layouts | def place_in_layouts(content, payload, info)
output = content.dup
layout = layouts[document.data["layout"]]
Bunto.logger.warn(
"Build Warning:",
"Layout '#{document.data["layout"]}' requested in "\
"#{document.relative_path} does not exist."
) if invalid_layout? layout
used = Set.new([layout])
# Reset the payload layout data to ensure it starts fresh for each page.
payload["layout"] = nil
while layout
payload["content"] = output
payload["layout"] = Utils.deep_merge_hashes(layout.data, payload["layout"] || {})
output = render_liquid(
layout.content,
payload,
info,
layout.relative_path
)
# Add layout to dependency tree
site.regenerator.add_dependency(
site.in_source_dir(document.path),
site.in_source_dir(layout.path)
) if document.write?
if (layout = layouts[layout.data["layout"]])
break if used.include?(layout)
used << layout
end
end
output
end | ruby | def place_in_layouts(content, payload, info)
output = content.dup
layout = layouts[document.data["layout"]]
Bunto.logger.warn(
"Build Warning:",
"Layout '#{document.data["layout"]}' requested in "\
"#{document.relative_path} does not exist."
) if invalid_layout? layout
used = Set.new([layout])
# Reset the payload layout data to ensure it starts fresh for each page.
payload["layout"] = nil
while layout
payload["content"] = output
payload["layout"] = Utils.deep_merge_hashes(layout.data, payload["layout"] || {})
output = render_liquid(
layout.content,
payload,
info,
layout.relative_path
)
# Add layout to dependency tree
site.regenerator.add_dependency(
site.in_source_dir(document.path),
site.in_source_dir(layout.path)
) if document.write?
if (layout = layouts[layout.data["layout"]])
break if used.include?(layout)
used << layout
end
end
output
end | [
"def",
"place_in_layouts",
"(",
"content",
",",
"payload",
",",
"info",
")",
"output",
"=",
"content",
".",
"dup",
"layout",
"=",
"layouts",
"[",
"document",
".",
"data",
"[",
"\"layout\"",
"]",
"]",
"Bunto",
".",
"logger",
".",
"warn",
"(",
"\"Build Warning:\"",
",",
"\"Layout '#{document.data[\"layout\"]}' requested in \"",
"\"#{document.relative_path} does not exist.\"",
")",
"if",
"invalid_layout?",
"layout",
"used",
"=",
"Set",
".",
"new",
"(",
"[",
"layout",
"]",
")",
"payload",
"[",
"\"layout\"",
"]",
"=",
"nil",
"while",
"layout",
"payload",
"[",
"\"content\"",
"]",
"=",
"output",
"payload",
"[",
"\"layout\"",
"]",
"=",
"Utils",
".",
"deep_merge_hashes",
"(",
"layout",
".",
"data",
",",
"payload",
"[",
"\"layout\"",
"]",
"||",
"{",
"}",
")",
"output",
"=",
"render_liquid",
"(",
"layout",
".",
"content",
",",
"payload",
",",
"info",
",",
"layout",
".",
"relative_path",
")",
"site",
".",
"regenerator",
".",
"add_dependency",
"(",
"site",
".",
"in_source_dir",
"(",
"document",
".",
"path",
")",
",",
"site",
".",
"in_source_dir",
"(",
"layout",
".",
"path",
")",
")",
"if",
"document",
".",
"write?",
"if",
"(",
"layout",
"=",
"layouts",
"[",
"layout",
".",
"data",
"[",
"\"layout\"",
"]",
"]",
")",
"break",
"if",
"used",
".",
"include?",
"(",
"layout",
")",
"used",
"<<",
"layout",
"end",
"end",
"output",
"end"
]
| Render layouts and place given content inside.
content - the content to be placed in the layout
Returns the content placed in the Liquid-rendered layouts | [
"Render",
"layouts",
"and",
"place",
"given",
"content",
"inside",
"."
]
| 45d993fb22329b12c277e15195af3415c9922a28 | https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/renderer.rb#L158-L197 | train |
bunto/bunto | lib/bunto/site.rb | Bunto.Site.reset | def reset
if config["time"]
self.time = Utils.parse_date(config["time"].to_s, "Invalid time in _config.yml.")
else
self.time = Time.now
end
self.layouts = {}
self.pages = []
self.static_files = []
self.data = {}
@collections = nil
@regenerator.clear_cache
@liquid_renderer.reset
if limit_posts < 0
raise ArgumentError, "limit_posts must be a non-negative number"
end
Bunto::Hooks.trigger :site, :after_reset, self
end | ruby | def reset
if config["time"]
self.time = Utils.parse_date(config["time"].to_s, "Invalid time in _config.yml.")
else
self.time = Time.now
end
self.layouts = {}
self.pages = []
self.static_files = []
self.data = {}
@collections = nil
@regenerator.clear_cache
@liquid_renderer.reset
if limit_posts < 0
raise ArgumentError, "limit_posts must be a non-negative number"
end
Bunto::Hooks.trigger :site, :after_reset, self
end | [
"def",
"reset",
"if",
"config",
"[",
"\"time\"",
"]",
"self",
".",
"time",
"=",
"Utils",
".",
"parse_date",
"(",
"config",
"[",
"\"time\"",
"]",
".",
"to_s",
",",
"\"Invalid time in _config.yml.\"",
")",
"else",
"self",
".",
"time",
"=",
"Time",
".",
"now",
"end",
"self",
".",
"layouts",
"=",
"{",
"}",
"self",
".",
"pages",
"=",
"[",
"]",
"self",
".",
"static_files",
"=",
"[",
"]",
"self",
".",
"data",
"=",
"{",
"}",
"@collections",
"=",
"nil",
"@regenerator",
".",
"clear_cache",
"@liquid_renderer",
".",
"reset",
"if",
"limit_posts",
"<",
"0",
"raise",
"ArgumentError",
",",
"\"limit_posts must be a non-negative number\"",
"end",
"Bunto",
"::",
"Hooks",
".",
"trigger",
":site",
",",
":after_reset",
",",
"self",
"end"
]
| Reset Site details.
Returns nothing | [
"Reset",
"Site",
"details",
"."
]
| 45d993fb22329b12c277e15195af3415c9922a28 | https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/site.rb#L84-L103 | train |
bunto/bunto | lib/bunto/site.rb | Bunto.Site.setup | def setup
ensure_not_in_dest
plugin_manager.conscientious_require
self.converters = instantiate_subclasses(Bunto::Converter)
self.generators = instantiate_subclasses(Bunto::Generator)
end | ruby | def setup
ensure_not_in_dest
plugin_manager.conscientious_require
self.converters = instantiate_subclasses(Bunto::Converter)
self.generators = instantiate_subclasses(Bunto::Generator)
end | [
"def",
"setup",
"ensure_not_in_dest",
"plugin_manager",
".",
"conscientious_require",
"self",
".",
"converters",
"=",
"instantiate_subclasses",
"(",
"Bunto",
"::",
"Converter",
")",
"self",
".",
"generators",
"=",
"instantiate_subclasses",
"(",
"Bunto",
"::",
"Generator",
")",
"end"
]
| Load necessary libraries, plugins, converters, and generators.
Returns nothing. | [
"Load",
"necessary",
"libraries",
"plugins",
"converters",
"and",
"generators",
"."
]
| 45d993fb22329b12c277e15195af3415c9922a28 | https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/site.rb#L108-L115 | train |
bunto/bunto | lib/bunto/site.rb | Bunto.Site.ensure_not_in_dest | def ensure_not_in_dest
dest_pathname = Pathname.new(dest)
Pathname.new(source).ascend do |path|
if path == dest_pathname
raise(
Errors::FatalException,
"Destination directory cannot be or contain the Source directory."
)
end
end
end | ruby | def ensure_not_in_dest
dest_pathname = Pathname.new(dest)
Pathname.new(source).ascend do |path|
if path == dest_pathname
raise(
Errors::FatalException,
"Destination directory cannot be or contain the Source directory."
)
end
end
end | [
"def",
"ensure_not_in_dest",
"dest_pathname",
"=",
"Pathname",
".",
"new",
"(",
"dest",
")",
"Pathname",
".",
"new",
"(",
"source",
")",
".",
"ascend",
"do",
"|",
"path",
"|",
"if",
"path",
"==",
"dest_pathname",
"raise",
"(",
"Errors",
"::",
"FatalException",
",",
"\"Destination directory cannot be or contain the Source directory.\"",
")",
"end",
"end",
"end"
]
| Check that the destination dir isn't the source dir or a directory
parent to the source dir. | [
"Check",
"that",
"the",
"destination",
"dir",
"isn",
"t",
"the",
"source",
"dir",
"or",
"a",
"directory",
"parent",
"to",
"the",
"source",
"dir",
"."
]
| 45d993fb22329b12c277e15195af3415c9922a28 | https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/site.rb#L119-L129 | train |
bunto/bunto | lib/bunto/site.rb | Bunto.Site.generate | def generate
generators.each do |generator|
start = Time.now
generator.generate(self)
Bunto.logger.debug "Generating:",
"#{generator.class} finished in #{Time.now - start} seconds."
end
end | ruby | def generate
generators.each do |generator|
start = Time.now
generator.generate(self)
Bunto.logger.debug "Generating:",
"#{generator.class} finished in #{Time.now - start} seconds."
end
end | [
"def",
"generate",
"generators",
".",
"each",
"do",
"|",
"generator",
"|",
"start",
"=",
"Time",
".",
"now",
"generator",
".",
"generate",
"(",
"self",
")",
"Bunto",
".",
"logger",
".",
"debug",
"\"Generating:\"",
",",
"\"#{generator.class} finished in #{Time.now - start} seconds.\"",
"end",
"end"
]
| Run each of the Generators.
Returns nothing. | [
"Run",
"each",
"of",
"the",
"Generators",
"."
]
| 45d993fb22329b12c277e15195af3415c9922a28 | https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/site.rb#L171-L178 | train |
bunto/bunto | lib/bunto/site.rb | Bunto.Site.render | def render
relative_permalinks_are_deprecated
payload = site_payload
Bunto::Hooks.trigger :site, :pre_render, self, payload
render_docs(payload)
render_pages(payload)
Bunto::Hooks.trigger :site, :post_render, self, payload
end | ruby | def render
relative_permalinks_are_deprecated
payload = site_payload
Bunto::Hooks.trigger :site, :pre_render, self, payload
render_docs(payload)
render_pages(payload)
Bunto::Hooks.trigger :site, :post_render, self, payload
end | [
"def",
"render",
"relative_permalinks_are_deprecated",
"payload",
"=",
"site_payload",
"Bunto",
"::",
"Hooks",
".",
"trigger",
":site",
",",
":pre_render",
",",
"self",
",",
"payload",
"render_docs",
"(",
"payload",
")",
"render_pages",
"(",
"payload",
")",
"Bunto",
"::",
"Hooks",
".",
"trigger",
":site",
",",
":post_render",
",",
"self",
",",
"payload",
"end"
]
| Render the site to the destination.
Returns nothing. | [
"Render",
"the",
"site",
"to",
"the",
"destination",
"."
]
| 45d993fb22329b12c277e15195af3415c9922a28 | https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/site.rb#L183-L194 | train |
bunto/bunto | lib/bunto/page.rb | Bunto.Page.dir | def dir
if url.end_with?(FORWARD_SLASH)
url
else
url_dir = File.dirname(url)
url_dir.end_with?(FORWARD_SLASH) ? url_dir : "#{url_dir}/"
end
end | ruby | def dir
if url.end_with?(FORWARD_SLASH)
url
else
url_dir = File.dirname(url)
url_dir.end_with?(FORWARD_SLASH) ? url_dir : "#{url_dir}/"
end
end | [
"def",
"dir",
"if",
"url",
".",
"end_with?",
"(",
"FORWARD_SLASH",
")",
"url",
"else",
"url_dir",
"=",
"File",
".",
"dirname",
"(",
"url",
")",
"url_dir",
".",
"end_with?",
"(",
"FORWARD_SLASH",
")",
"?",
"url_dir",
":",
"\"#{url_dir}/\"",
"end",
"end"
]
| Initialize a new Page.
site - The Site object.
base - The String path to the source.
dir - The String path between the source and the file.
name - The String filename of the file.
The generated directory into which the page will be placed
upon generation. This is derived from the permalink or, if
permalink is absent, will be '/'
Returns the String destination directory. | [
"Initialize",
"a",
"new",
"Page",
"."
]
| 45d993fb22329b12c277e15195af3415c9922a28 | https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/page.rb#L64-L71 | train |
bunto/bunto | lib/bunto/convertible.rb | Bunto.Convertible.read_yaml | def read_yaml(base, name, opts = {})
filename = File.join(base, name)
begin
self.content = File.read(@path || site.in_source_dir(base, name),
Utils.merged_file_read_opts(site, opts))
if content =~ Document::YAML_FRONT_MATTER_REGEXP
self.content = $POSTMATCH
self.data = SafeYAML.load(Regexp.last_match(1))
end
rescue SyntaxError => e
Bunto.logger.warn "YAML Exception reading #{filename}: #{e.message}"
rescue => e
Bunto.logger.warn "Error reading file #{filename}: #{e.message}"
end
self.data ||= {}
validate_data! filename
validate_permalink! filename
self.data
end | ruby | def read_yaml(base, name, opts = {})
filename = File.join(base, name)
begin
self.content = File.read(@path || site.in_source_dir(base, name),
Utils.merged_file_read_opts(site, opts))
if content =~ Document::YAML_FRONT_MATTER_REGEXP
self.content = $POSTMATCH
self.data = SafeYAML.load(Regexp.last_match(1))
end
rescue SyntaxError => e
Bunto.logger.warn "YAML Exception reading #{filename}: #{e.message}"
rescue => e
Bunto.logger.warn "Error reading file #{filename}: #{e.message}"
end
self.data ||= {}
validate_data! filename
validate_permalink! filename
self.data
end | [
"def",
"read_yaml",
"(",
"base",
",",
"name",
",",
"opts",
"=",
"{",
"}",
")",
"filename",
"=",
"File",
".",
"join",
"(",
"base",
",",
"name",
")",
"begin",
"self",
".",
"content",
"=",
"File",
".",
"read",
"(",
"@path",
"||",
"site",
".",
"in_source_dir",
"(",
"base",
",",
"name",
")",
",",
"Utils",
".",
"merged_file_read_opts",
"(",
"site",
",",
"opts",
")",
")",
"if",
"content",
"=~",
"Document",
"::",
"YAML_FRONT_MATTER_REGEXP",
"self",
".",
"content",
"=",
"$POSTMATCH",
"self",
".",
"data",
"=",
"SafeYAML",
".",
"load",
"(",
"Regexp",
".",
"last_match",
"(",
"1",
")",
")",
"end",
"rescue",
"SyntaxError",
"=>",
"e",
"Bunto",
".",
"logger",
".",
"warn",
"\"YAML Exception reading #{filename}: #{e.message}\"",
"rescue",
"=>",
"e",
"Bunto",
".",
"logger",
".",
"warn",
"\"Error reading file #{filename}: #{e.message}\"",
"end",
"self",
".",
"data",
"||=",
"{",
"}",
"validate_data!",
"filename",
"validate_permalink!",
"filename",
"self",
".",
"data",
"end"
]
| Read the YAML frontmatter.
base - The String path to the dir containing the file.
name - The String filename of the file.
opts - optional parameter to File.read, default at site configs
Returns nothing.
rubocop:disable Metrics/AbcSize | [
"Read",
"the",
"YAML",
"frontmatter",
"."
]
| 45d993fb22329b12c277e15195af3415c9922a28 | https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/convertible.rb#L39-L61 | train |
bunto/bunto | lib/bunto/filters.rb | Bunto.Filters.sassify | def sassify(input)
site = @context.registers[:site]
converter = site.find_converter_instance(Bunto::Converters::Sass)
converter.convert(input)
end | ruby | def sassify(input)
site = @context.registers[:site]
converter = site.find_converter_instance(Bunto::Converters::Sass)
converter.convert(input)
end | [
"def",
"sassify",
"(",
"input",
")",
"site",
"=",
"@context",
".",
"registers",
"[",
":site",
"]",
"converter",
"=",
"site",
".",
"find_converter_instance",
"(",
"Bunto",
"::",
"Converters",
"::",
"Sass",
")",
"converter",
".",
"convert",
"(",
"input",
")",
"end"
]
| Convert a Sass string into CSS output.
input - The Sass String to convert.
Returns the CSS formatted String. | [
"Convert",
"a",
"Sass",
"string",
"into",
"CSS",
"output",
"."
]
| 45d993fb22329b12c277e15195af3415c9922a28 | https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/filters.rb#L40-L44 | train |
bunto/bunto | lib/bunto/filters.rb | Bunto.Filters.scssify | def scssify(input)
site = @context.registers[:site]
converter = site.find_converter_instance(Bunto::Converters::Scss)
converter.convert(input)
end | ruby | def scssify(input)
site = @context.registers[:site]
converter = site.find_converter_instance(Bunto::Converters::Scss)
converter.convert(input)
end | [
"def",
"scssify",
"(",
"input",
")",
"site",
"=",
"@context",
".",
"registers",
"[",
":site",
"]",
"converter",
"=",
"site",
".",
"find_converter_instance",
"(",
"Bunto",
"::",
"Converters",
"::",
"Scss",
")",
"converter",
".",
"convert",
"(",
"input",
")",
"end"
]
| Convert a Scss string into CSS output.
input - The Scss String to convert.
Returns the CSS formatted String. | [
"Convert",
"a",
"Scss",
"string",
"into",
"CSS",
"output",
"."
]
| 45d993fb22329b12c277e15195af3415c9922a28 | https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/filters.rb#L51-L55 | train |
spk/validate-website | lib/validate_website/crawl.rb | ValidateWebsite.Crawl.extract_imgs_from_page | def extract_imgs_from_page(page)
return Set[] if page.is_redirect?
page.doc.search('//img[@src]').reduce(Set[]) do |result, elem|
u = elem.attributes['src'].content
result << page.to_absolute(URI.parse(URI.encode(u)))
end
end | ruby | def extract_imgs_from_page(page)
return Set[] if page.is_redirect?
page.doc.search('//img[@src]').reduce(Set[]) do |result, elem|
u = elem.attributes['src'].content
result << page.to_absolute(URI.parse(URI.encode(u)))
end
end | [
"def",
"extract_imgs_from_page",
"(",
"page",
")",
"return",
"Set",
"[",
"]",
"if",
"page",
".",
"is_redirect?",
"page",
".",
"doc",
".",
"search",
"(",
"'//img[@src]'",
")",
".",
"reduce",
"(",
"Set",
"[",
"]",
")",
"do",
"|",
"result",
",",
"elem",
"|",
"u",
"=",
"elem",
".",
"attributes",
"[",
"'src'",
"]",
".",
"content",
"result",
"<<",
"page",
".",
"to_absolute",
"(",
"URI",
".",
"parse",
"(",
"URI",
".",
"encode",
"(",
"u",
")",
")",
")",
"end",
"end"
]
| Extract imgs urls from page
@param [Spidr::Page] an Spidr::Page object
@return [Array] Lists of urls | [
"Extract",
"imgs",
"urls",
"from",
"page"
]
| f8e9a610592e340da6d71ff20116ff512ba7aab9 | https://github.com/spk/validate-website/blob/f8e9a610592e340da6d71ff20116ff512ba7aab9/lib/validate_website/crawl.rb#L42-L48 | train |
dark-panda/ffi-geos | lib/ffi-geos/geometry_collection.rb | Geos.GeometryCollection.each | def each
if block_given?
num_geometries.times do |n|
yield get_geometry_n(n)
end
self
else
num_geometries.times.collect { |n|
get_geometry_n(n)
}.to_enum
end
end | ruby | def each
if block_given?
num_geometries.times do |n|
yield get_geometry_n(n)
end
self
else
num_geometries.times.collect { |n|
get_geometry_n(n)
}.to_enum
end
end | [
"def",
"each",
"if",
"block_given?",
"num_geometries",
".",
"times",
"do",
"|",
"n",
"|",
"yield",
"get_geometry_n",
"(",
"n",
")",
"end",
"self",
"else",
"num_geometries",
".",
"times",
".",
"collect",
"{",
"|",
"n",
"|",
"get_geometry_n",
"(",
"n",
")",
"}",
".",
"to_enum",
"end",
"end"
]
| Yields each Geometry in the GeometryCollection. | [
"Yields",
"each",
"Geometry",
"in",
"the",
"GeometryCollection",
"."
]
| ac58e52585741ce8e10b11ec4857e5e6534cc96b | https://github.com/dark-panda/ffi-geos/blob/ac58e52585741ce8e10b11ec4857e5e6534cc96b/lib/ffi-geos/geometry_collection.rb#L8-L19 | train |
bunto/bunto | lib/bunto/collection.rb | Bunto.Collection.read | def read
filtered_entries.each do |file_path|
full_path = collection_dir(file_path)
next if File.directory?(full_path)
if Utils.has_yaml_header? full_path
read_document(full_path)
else
read_static_file(file_path, full_path)
end
end
docs.sort!
end | ruby | def read
filtered_entries.each do |file_path|
full_path = collection_dir(file_path)
next if File.directory?(full_path)
if Utils.has_yaml_header? full_path
read_document(full_path)
else
read_static_file(file_path, full_path)
end
end
docs.sort!
end | [
"def",
"read",
"filtered_entries",
".",
"each",
"do",
"|",
"file_path",
"|",
"full_path",
"=",
"collection_dir",
"(",
"file_path",
")",
"next",
"if",
"File",
".",
"directory?",
"(",
"full_path",
")",
"if",
"Utils",
".",
"has_yaml_header?",
"full_path",
"read_document",
"(",
"full_path",
")",
"else",
"read_static_file",
"(",
"file_path",
",",
"full_path",
")",
"end",
"end",
"docs",
".",
"sort!",
"end"
]
| Read the allowed documents into the collection's array of docs.
Returns the sorted array of docs. | [
"Read",
"the",
"allowed",
"documents",
"into",
"the",
"collection",
"s",
"array",
"of",
"docs",
"."
]
| 45d993fb22329b12c277e15195af3415c9922a28 | https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/collection.rb#L55-L66 | train |
bys-control/activeadmin-index_as_calendar | lib/index_as_calendar/dsl.rb | IndexAsCalendar.DSL.index_as_calendar | def index_as_calendar( options={}, &block )
default_options = {
:ajax => true, # Use AJAX to fetch events. Set to false to send data during render.
:model => nil, # Model to be used to fetch events. Defaults to ActiveAdmin resource model.
:includes => [], # Eager loading of related models
:start_date => :created_at, # Field to be used as start date for events
:end_date => nil, # Field to be used as end date for events
:block => block, # Block with the model<->event field mappings
:fullCalendarOptions => nil, # fullCalendar options to be sent upon initialization
:default => false # Set this index view as default
}
options = default_options.deep_merge(options)
# Defines controller for event_mapping model items to events
controller do
def event_mapping( items, options )
events = items.map do |item|
if !options[:block].blank?
instance_exec(item, &options[:block])
else
{
:id => item.id,
:title => item.to_s,
:start => (options[:start_date].blank? or item.send(options[:start_date]).blank?) ? Date.today.to_s : item.send(options[:start_date]),
:end => (options[:end_date].blank? or item.send(options[:end_date]).blank?) ? nil : item.send(options[:end_date])
}
end
end
end
end
# Setup AJAX
if options[:ajax]
# Setup fullCalendar to use AJAX calls to retrieve event data
index as: :calendar, default: options[:default] do |context|
context[:fullCalendarOptions] = options[:fullCalendarOptions]
events = {
url: "#{collection_path()}/index_as_events.json",
type: 'GET',
data: params
}
end
# Defines collection_action to get events data
collection_action :index_as_events, :method => :get do
items = options[:model] || end_of_association_chain
items = items.send(params[:scope]) if params[:scope].present?
items = items.includes(options[:includes]) unless options[:includes].blank?
items = items.where(options[:start_date] => params[:start].to_date...params[:end].to_date).ransack(params[:q]).result
events = event_mapping(items, options)
respond_to do |format|
format.json { render :json => events }
end
end
# Return events to be used during partial render
else
index as: :calendar, default: options[:default] do |context|
context[:fullCalendarOptions] = options[:fullCalendarOptions]
events = self.controller.event_mapping(context[:collection], options)
end
end
end | ruby | def index_as_calendar( options={}, &block )
default_options = {
:ajax => true, # Use AJAX to fetch events. Set to false to send data during render.
:model => nil, # Model to be used to fetch events. Defaults to ActiveAdmin resource model.
:includes => [], # Eager loading of related models
:start_date => :created_at, # Field to be used as start date for events
:end_date => nil, # Field to be used as end date for events
:block => block, # Block with the model<->event field mappings
:fullCalendarOptions => nil, # fullCalendar options to be sent upon initialization
:default => false # Set this index view as default
}
options = default_options.deep_merge(options)
# Defines controller for event_mapping model items to events
controller do
def event_mapping( items, options )
events = items.map do |item|
if !options[:block].blank?
instance_exec(item, &options[:block])
else
{
:id => item.id,
:title => item.to_s,
:start => (options[:start_date].blank? or item.send(options[:start_date]).blank?) ? Date.today.to_s : item.send(options[:start_date]),
:end => (options[:end_date].blank? or item.send(options[:end_date]).blank?) ? nil : item.send(options[:end_date])
}
end
end
end
end
# Setup AJAX
if options[:ajax]
# Setup fullCalendar to use AJAX calls to retrieve event data
index as: :calendar, default: options[:default] do |context|
context[:fullCalendarOptions] = options[:fullCalendarOptions]
events = {
url: "#{collection_path()}/index_as_events.json",
type: 'GET',
data: params
}
end
# Defines collection_action to get events data
collection_action :index_as_events, :method => :get do
items = options[:model] || end_of_association_chain
items = items.send(params[:scope]) if params[:scope].present?
items = items.includes(options[:includes]) unless options[:includes].blank?
items = items.where(options[:start_date] => params[:start].to_date...params[:end].to_date).ransack(params[:q]).result
events = event_mapping(items, options)
respond_to do |format|
format.json { render :json => events }
end
end
# Return events to be used during partial render
else
index as: :calendar, default: options[:default] do |context|
context[:fullCalendarOptions] = options[:fullCalendarOptions]
events = self.controller.event_mapping(context[:collection], options)
end
end
end | [
"def",
"index_as_calendar",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"default_options",
"=",
"{",
":ajax",
"=>",
"true",
",",
":model",
"=>",
"nil",
",",
":includes",
"=>",
"[",
"]",
",",
":start_date",
"=>",
":created_at",
",",
":end_date",
"=>",
"nil",
",",
":block",
"=>",
"block",
",",
":fullCalendarOptions",
"=>",
"nil",
",",
":default",
"=>",
"false",
"}",
"options",
"=",
"default_options",
".",
"deep_merge",
"(",
"options",
")",
"controller",
"do",
"def",
"event_mapping",
"(",
"items",
",",
"options",
")",
"events",
"=",
"items",
".",
"map",
"do",
"|",
"item",
"|",
"if",
"!",
"options",
"[",
":block",
"]",
".",
"blank?",
"instance_exec",
"(",
"item",
",",
"&",
"options",
"[",
":block",
"]",
")",
"else",
"{",
":id",
"=>",
"item",
".",
"id",
",",
":title",
"=>",
"item",
".",
"to_s",
",",
":start",
"=>",
"(",
"options",
"[",
":start_date",
"]",
".",
"blank?",
"or",
"item",
".",
"send",
"(",
"options",
"[",
":start_date",
"]",
")",
".",
"blank?",
")",
"?",
"Date",
".",
"today",
".",
"to_s",
":",
"item",
".",
"send",
"(",
"options",
"[",
":start_date",
"]",
")",
",",
":end",
"=>",
"(",
"options",
"[",
":end_date",
"]",
".",
"blank?",
"or",
"item",
".",
"send",
"(",
"options",
"[",
":end_date",
"]",
")",
".",
"blank?",
")",
"?",
"nil",
":",
"item",
".",
"send",
"(",
"options",
"[",
":end_date",
"]",
")",
"}",
"end",
"end",
"end",
"end",
"if",
"options",
"[",
":ajax",
"]",
"index",
"as",
":",
":calendar",
",",
"default",
":",
"options",
"[",
":default",
"]",
"do",
"|",
"context",
"|",
"context",
"[",
":fullCalendarOptions",
"]",
"=",
"options",
"[",
":fullCalendarOptions",
"]",
"events",
"=",
"{",
"url",
":",
"\"#{collection_path()}/index_as_events.json\"",
",",
"type",
":",
"'GET'",
",",
"data",
":",
"params",
"}",
"end",
"collection_action",
":index_as_events",
",",
":method",
"=>",
":get",
"do",
"items",
"=",
"options",
"[",
":model",
"]",
"||",
"end_of_association_chain",
"items",
"=",
"items",
".",
"send",
"(",
"params",
"[",
":scope",
"]",
")",
"if",
"params",
"[",
":scope",
"]",
".",
"present?",
"items",
"=",
"items",
".",
"includes",
"(",
"options",
"[",
":includes",
"]",
")",
"unless",
"options",
"[",
":includes",
"]",
".",
"blank?",
"items",
"=",
"items",
".",
"where",
"(",
"options",
"[",
":start_date",
"]",
"=>",
"params",
"[",
":start",
"]",
".",
"to_date",
"...",
"params",
"[",
":end",
"]",
".",
"to_date",
")",
".",
"ransack",
"(",
"params",
"[",
":q",
"]",
")",
".",
"result",
"events",
"=",
"event_mapping",
"(",
"items",
",",
"options",
")",
"respond_to",
"do",
"|",
"format",
"|",
"format",
".",
"json",
"{",
"render",
":json",
"=>",
"events",
"}",
"end",
"end",
"else",
"index",
"as",
":",
":calendar",
",",
"default",
":",
"options",
"[",
":default",
"]",
"do",
"|",
"context",
"|",
"context",
"[",
":fullCalendarOptions",
"]",
"=",
"options",
"[",
":fullCalendarOptions",
"]",
"events",
"=",
"self",
".",
"controller",
".",
"event_mapping",
"(",
"context",
"[",
":collection",
"]",
",",
"options",
")",
"end",
"end",
"end"
]
| Initializes activeadmin index as calendar | [
"Initializes",
"activeadmin",
"index",
"as",
"calendar"
]
| 1e07d605b536f4f9a89c054f34910728f46d3871 | https://github.com/bys-control/activeadmin-index_as_calendar/blob/1e07d605b536f4f9a89c054f34910728f46d3871/lib/index_as_calendar/dsl.rb#L7-L72 | train |
dark-panda/ffi-geos | lib/ffi-geos/geometry.rb | Geos.Geometry.union | def union(geom = nil)
if geom
check_geometry(geom)
cast_geometry_ptr(FFIGeos.GEOSUnion_r(Geos.current_handle_pointer, ptr, geom.ptr), srid_copy: pick_srid_from_geoms(srid, geom.srid))
else
if respond_to?(:unary_union)
unary_union
else
union_cascaded
end
end
end | ruby | def union(geom = nil)
if geom
check_geometry(geom)
cast_geometry_ptr(FFIGeos.GEOSUnion_r(Geos.current_handle_pointer, ptr, geom.ptr), srid_copy: pick_srid_from_geoms(srid, geom.srid))
else
if respond_to?(:unary_union)
unary_union
else
union_cascaded
end
end
end | [
"def",
"union",
"(",
"geom",
"=",
"nil",
")",
"if",
"geom",
"check_geometry",
"(",
"geom",
")",
"cast_geometry_ptr",
"(",
"FFIGeos",
".",
"GEOSUnion_r",
"(",
"Geos",
".",
"current_handle_pointer",
",",
"ptr",
",",
"geom",
".",
"ptr",
")",
",",
"srid_copy",
":",
"pick_srid_from_geoms",
"(",
"srid",
",",
"geom",
".",
"srid",
")",
")",
"else",
"if",
"respond_to?",
"(",
":unary_union",
")",
"unary_union",
"else",
"union_cascaded",
"end",
"end",
"end"
]
| Calling without a geom argument is equivalent to calling unary_union when
using GEOS 3.3+ and is equivalent to calling union_cascaded in older
versions. | [
"Calling",
"without",
"a",
"geom",
"argument",
"is",
"equivalent",
"to",
"calling",
"unary_union",
"when",
"using",
"GEOS",
"3",
".",
"3",
"+",
"and",
"is",
"equivalent",
"to",
"calling",
"union_cascaded",
"in",
"older",
"versions",
"."
]
| ac58e52585741ce8e10b11ec4857e5e6534cc96b | https://github.com/dark-panda/ffi-geos/blob/ac58e52585741ce8e10b11ec4857e5e6534cc96b/lib/ffi-geos/geometry.rb#L162-L173 | train |
dark-panda/ffi-geos | lib/ffi-geos/geometry.rb | Geos.Geometry.relate_pattern | def relate_pattern(geom, pattern)
check_geometry(geom)
bool_result(FFIGeos.GEOSRelatePattern_r(Geos.current_handle_pointer, ptr, geom.ptr, pattern))
end | ruby | def relate_pattern(geom, pattern)
check_geometry(geom)
bool_result(FFIGeos.GEOSRelatePattern_r(Geos.current_handle_pointer, ptr, geom.ptr, pattern))
end | [
"def",
"relate_pattern",
"(",
"geom",
",",
"pattern",
")",
"check_geometry",
"(",
"geom",
")",
"bool_result",
"(",
"FFIGeos",
".",
"GEOSRelatePattern_r",
"(",
"Geos",
".",
"current_handle_pointer",
",",
"ptr",
",",
"geom",
".",
"ptr",
",",
"pattern",
")",
")",
"end"
]
| Checks the DE-9IM pattern against the geoms. | [
"Checks",
"the",
"DE",
"-",
"9IM",
"pattern",
"against",
"the",
"geoms",
"."
]
| ac58e52585741ce8e10b11ec4857e5e6534cc96b | https://github.com/dark-panda/ffi-geos/blob/ac58e52585741ce8e10b11ec4857e5e6534cc96b/lib/ffi-geos/geometry.rb#L223-L226 | train |
LaunchAcademy/roboto | lib/roboto/content_provider.rb | Roboto.ContentProvider.contents | def contents(custom_binding = nil)
return @contents unless @contents.nil?
@contents = File.read(path)
if path.extname == '.erb'
@contents = ERB.new(@contents, nil, '>').result(custom_binding ? custom_binding : binding)
end
@contents
end | ruby | def contents(custom_binding = nil)
return @contents unless @contents.nil?
@contents = File.read(path)
if path.extname == '.erb'
@contents = ERB.new(@contents, nil, '>').result(custom_binding ? custom_binding : binding)
end
@contents
end | [
"def",
"contents",
"(",
"custom_binding",
"=",
"nil",
")",
"return",
"@contents",
"unless",
"@contents",
".",
"nil?",
"@contents",
"=",
"File",
".",
"read",
"(",
"path",
")",
"if",
"path",
".",
"extname",
"==",
"'.erb'",
"@contents",
"=",
"ERB",
".",
"new",
"(",
"@contents",
",",
"nil",
",",
"'>'",
")",
".",
"result",
"(",
"custom_binding",
"?",
"custom_binding",
":",
"binding",
")",
"end",
"@contents",
"end"
]
| Reads the contents of the effective robots.txt file
@return [String] the contents of the effective robots.txt file | [
"Reads",
"the",
"contents",
"of",
"the",
"effective",
"robots",
".",
"txt",
"file"
]
| c3b74aa9c7240fd557fe9317ba82c08e404bc265 | https://github.com/LaunchAcademy/roboto/blob/c3b74aa9c7240fd557fe9317ba82c08e404bc265/lib/roboto/content_provider.rb#L8-L16 | train |
bunto/bunto | lib/bunto/regenerator.rb | Bunto.Regenerator.regenerate? | def regenerate?(document)
case document
when Page
regenerate_page?(document)
when Document
regenerate_document?(document)
else
source_path = document.respond_to?(:path) ? document.path : nil
dest_path = if document.respond_to?(:destination)
document.destination(@site.dest)
end
source_modified_or_dest_missing?(source_path, dest_path)
end
end | ruby | def regenerate?(document)
case document
when Page
regenerate_page?(document)
when Document
regenerate_document?(document)
else
source_path = document.respond_to?(:path) ? document.path : nil
dest_path = if document.respond_to?(:destination)
document.destination(@site.dest)
end
source_modified_or_dest_missing?(source_path, dest_path)
end
end | [
"def",
"regenerate?",
"(",
"document",
")",
"case",
"document",
"when",
"Page",
"regenerate_page?",
"(",
"document",
")",
"when",
"Document",
"regenerate_document?",
"(",
"document",
")",
"else",
"source_path",
"=",
"document",
".",
"respond_to?",
"(",
":path",
")",
"?",
"document",
".",
"path",
":",
"nil",
"dest_path",
"=",
"if",
"document",
".",
"respond_to?",
"(",
":destination",
")",
"document",
".",
"destination",
"(",
"@site",
".",
"dest",
")",
"end",
"source_modified_or_dest_missing?",
"(",
"source_path",
",",
"dest_path",
")",
"end",
"end"
]
| Checks if a renderable object needs to be regenerated
Returns a boolean. | [
"Checks",
"if",
"a",
"renderable",
"object",
"needs",
"to",
"be",
"regenerated"
]
| 45d993fb22329b12c277e15195af3415c9922a28 | https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/regenerator.rb#L20-L33 | train |
bunto/bunto | lib/bunto/regenerator.rb | Bunto.Regenerator.read_metadata | def read_metadata
@metadata =
if !disabled? && File.file?(metadata_file)
content = File.binread(metadata_file)
begin
Marshal.load(content)
rescue TypeError
SafeYAML.load(content)
rescue ArgumentError => e
Bunto.logger.warn("Failed to load #{metadata_file}: #{e}")
{}
end
else
{}
end
end | ruby | def read_metadata
@metadata =
if !disabled? && File.file?(metadata_file)
content = File.binread(metadata_file)
begin
Marshal.load(content)
rescue TypeError
SafeYAML.load(content)
rescue ArgumentError => e
Bunto.logger.warn("Failed to load #{metadata_file}: #{e}")
{}
end
else
{}
end
end | [
"def",
"read_metadata",
"@metadata",
"=",
"if",
"!",
"disabled?",
"&&",
"File",
".",
"file?",
"(",
"metadata_file",
")",
"content",
"=",
"File",
".",
"binread",
"(",
"metadata_file",
")",
"begin",
"Marshal",
".",
"load",
"(",
"content",
")",
"rescue",
"TypeError",
"SafeYAML",
".",
"load",
"(",
"content",
")",
"rescue",
"ArgumentError",
"=>",
"e",
"Bunto",
".",
"logger",
".",
"warn",
"(",
"\"Failed to load #{metadata_file}: #{e}\"",
")",
"{",
"}",
"end",
"else",
"{",
"}",
"end",
"end"
]
| Read metadata from the metadata file, if no file is found,
initialize with an empty hash
Returns the read metadata. | [
"Read",
"metadata",
"from",
"the",
"metadata",
"file",
"if",
"no",
"file",
"is",
"found",
"initialize",
"with",
"an",
"empty",
"hash"
]
| 45d993fb22329b12c277e15195af3415c9922a28 | https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/regenerator.rb#L146-L162 | train |
bunto/bunto | lib/bunto/frontmatter_defaults.rb | Bunto.FrontmatterDefaults.applies? | def applies?(scope, path, type)
applies_path?(scope, path) && applies_type?(scope, type)
end | ruby | def applies?(scope, path, type)
applies_path?(scope, path) && applies_type?(scope, type)
end | [
"def",
"applies?",
"(",
"scope",
",",
"path",
",",
"type",
")",
"applies_path?",
"(",
"scope",
",",
"path",
")",
"&&",
"applies_type?",
"(",
"scope",
",",
"type",
")",
"end"
]
| Checks if a given default setting scope matches the given path and type
scope - the hash indicating the scope, as defined in _config.yml
path - the path to check for
type - the type (:post, :page or :draft) to check for
Returns true if the scope applies to the given path and type | [
"Checks",
"if",
"a",
"given",
"default",
"setting",
"scope",
"matches",
"the",
"given",
"path",
"and",
"type"
]
| 45d993fb22329b12c277e15195af3415c9922a28 | https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/frontmatter_defaults.rb#L94-L96 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/versions_controller.rb | Phcscriptcdn.Script::VersionsController.show | def show
@script_versions = Script::Version.friendly.find(params[:id])
@versions = Phcscriptcdn::ScriptversionVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Version')
end | ruby | def show
@script_versions = Script::Version.friendly.find(params[:id])
@versions = Phcscriptcdn::ScriptversionVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Version')
end | [
"def",
"show",
"@script_versions",
"=",
"Script",
"::",
"Version",
".",
"friendly",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"@versions",
"=",
"Phcscriptcdn",
"::",
"ScriptversionVersions",
".",
"where",
"(",
"item_id",
":",
"params",
"[",
":id",
"]",
",",
"item_type",
":",
"'Phcscriptcdn::Script::Version'",
")",
"end"
]
| DETAILS - Script Versions | [
"DETAILS",
"-",
"Script",
"Versions"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/versions_controller.rb#L18-L21 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/versions_controller.rb | Phcscriptcdn.Script::VersionsController.new | def new
@script_version = Script::Version.new
@script_version.user_id = current_user.id
@script_version.org_id = current_user.org_id
end | ruby | def new
@script_version = Script::Version.new
@script_version.user_id = current_user.id
@script_version.org_id = current_user.org_id
end | [
"def",
"new",
"@script_version",
"=",
"Script",
"::",
"Version",
".",
"new",
"@script_version",
".",
"user_id",
"=",
"current_user",
".",
"id",
"@script_version",
".",
"org_id",
"=",
"current_user",
".",
"org_id",
"end"
]
| NEW - Script Versions | [
"NEW",
"-",
"Script",
"Versions"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/versions_controller.rb#L24-L28 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/versions_controller.rb | Phcscriptcdn.Script::VersionsController.create | def create
@script_version = Script::Version.new(script_version_params)
@script_version.user_id = current_user.id
@script_version.org_id = current_user.org_id
if @script_version.save
redirect_to script_versions_url, notice: 'Version was successfully created.'
else
render :new
end
end | ruby | def create
@script_version = Script::Version.new(script_version_params)
@script_version.user_id = current_user.id
@script_version.org_id = current_user.org_id
if @script_version.save
redirect_to script_versions_url, notice: 'Version was successfully created.'
else
render :new
end
end | [
"def",
"create",
"@script_version",
"=",
"Script",
"::",
"Version",
".",
"new",
"(",
"script_version_params",
")",
"@script_version",
".",
"user_id",
"=",
"current_user",
".",
"id",
"@script_version",
".",
"org_id",
"=",
"current_user",
".",
"org_id",
"if",
"@script_version",
".",
"save",
"redirect_to",
"script_versions_url",
",",
"notice",
":",
"'Version was successfully created.'",
"else",
"render",
":new",
"end",
"end"
]
| POST - Script Versions | [
"POST",
"-",
"Script",
"Versions"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/versions_controller.rb#L35-L44 | train |
teespring/nightwing | lib/nightwing/metric.rb | Nightwing.Metric.for | def for(queue:, worker: nil)
worker_name = worker.to_s.underscore.tr("/", "_") if worker
[namespace, queue, worker_name].compact.join(".")
end | ruby | def for(queue:, worker: nil)
worker_name = worker.to_s.underscore.tr("/", "_") if worker
[namespace, queue, worker_name].compact.join(".")
end | [
"def",
"for",
"(",
"queue",
":",
",",
"worker",
":",
"nil",
")",
"worker_name",
"=",
"worker",
".",
"to_s",
".",
"underscore",
".",
"tr",
"(",
"\"/\"",
",",
"\"_\"",
")",
"if",
"worker",
"[",
"namespace",
",",
"queue",
",",
"worker_name",
"]",
".",
"compact",
".",
"join",
"(",
"\".\"",
")",
"end"
]
| Generates a metric name
@param [String] queue
@param [Class] worker
returns a String object | [
"Generates",
"a",
"metric",
"name"
]
| 619d0b3d2da29a8ca2dc82af0ce47595d435a391 | https://github.com/teespring/nightwing/blob/619d0b3d2da29a8ca2dc82af0ce47595d435a391/lib/nightwing/metric.rb#L18-L21 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/urls_controller.rb | Phcscriptcdn.Script::UrlsController.show | def show
script_listing = Script::Listing.find(params[:listing_id])
@script_url = script_listing.urls.friendly.find(params[:id])
end | ruby | def show
script_listing = Script::Listing.find(params[:listing_id])
@script_url = script_listing.urls.friendly.find(params[:id])
end | [
"def",
"show",
"script_listing",
"=",
"Script",
"::",
"Listing",
".",
"find",
"(",
"params",
"[",
":listing_id",
"]",
")",
"@script_url",
"=",
"script_listing",
".",
"urls",
".",
"friendly",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"end"
]
| DETAILED PROFILE - Script Authors | [
"DETAILED",
"PROFILE",
"-",
"Script",
"Authors"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/urls_controller.rb#L19-L22 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/urls_controller.rb | Phcscriptcdn.Script::UrlsController.new | def new
script_listing = Script::Listing.find(params[:listing_id])
@script_url = script_listing.urls.build
@script_url.user_id = current_user.id
@script_url.org_id = current_user.org_id
end | ruby | def new
script_listing = Script::Listing.find(params[:listing_id])
@script_url = script_listing.urls.build
@script_url.user_id = current_user.id
@script_url.org_id = current_user.org_id
end | [
"def",
"new",
"script_listing",
"=",
"Script",
"::",
"Listing",
".",
"find",
"(",
"params",
"[",
":listing_id",
"]",
")",
"@script_url",
"=",
"script_listing",
".",
"urls",
".",
"build",
"@script_url",
".",
"user_id",
"=",
"current_user",
".",
"id",
"@script_url",
".",
"org_id",
"=",
"current_user",
".",
"org_id",
"end"
]
| NEW - Script Athors | [
"NEW",
"-",
"Script",
"Athors"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/urls_controller.rb#L25-L30 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/urls_controller.rb | Phcscriptcdn.Script::UrlsController.edit | def edit
script_listing = Script::Listing.find(params[:listing_id])
@script_url = script_listing.urls.find(params[:id])
end | ruby | def edit
script_listing = Script::Listing.find(params[:listing_id])
@script_url = script_listing.urls.find(params[:id])
end | [
"def",
"edit",
"script_listing",
"=",
"Script",
"::",
"Listing",
".",
"find",
"(",
"params",
"[",
":listing_id",
"]",
")",
"@script_url",
"=",
"script_listing",
".",
"urls",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"end"
]
| EDIT - Script Athors | [
"EDIT",
"-",
"Script",
"Athors"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/urls_controller.rb#L33-L36 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/urls_controller.rb | Phcscriptcdn.Script::UrlsController.create | def create
@script_listing = Script::Listing.find(params[:listing_id])
@script_url = @script_listing.urls.create(script_url_params)
@script_url.user_id = current_user.id
@script_url.org_id = current_user.org_id
if @script_url.save
redirect_to script_listing_urls_path, notice: 'Author was successfully created.'
else
render :new
end
end | ruby | def create
@script_listing = Script::Listing.find(params[:listing_id])
@script_url = @script_listing.urls.create(script_url_params)
@script_url.user_id = current_user.id
@script_url.org_id = current_user.org_id
if @script_url.save
redirect_to script_listing_urls_path, notice: 'Author was successfully created.'
else
render :new
end
end | [
"def",
"create",
"@script_listing",
"=",
"Script",
"::",
"Listing",
".",
"find",
"(",
"params",
"[",
":listing_id",
"]",
")",
"@script_url",
"=",
"@script_listing",
".",
"urls",
".",
"create",
"(",
"script_url_params",
")",
"@script_url",
".",
"user_id",
"=",
"current_user",
".",
"id",
"@script_url",
".",
"org_id",
"=",
"current_user",
".",
"org_id",
"if",
"@script_url",
".",
"save",
"redirect_to",
"script_listing_urls_path",
",",
"notice",
":",
"'Author was successfully created.'",
"else",
"render",
":new",
"end",
"end"
]
| POST - Script Athors | [
"POST",
"-",
"Script",
"Athors"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/urls_controller.rb#L39-L49 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/urls_controller.rb | Phcscriptcdn.Script::UrlsController.destroy | def destroy
@script_listing = Script::Listing.find(params[:listing_id])
@script_url = @script_listing.urls.find(params[:id])
@script_url.destroy
redirect_to script_listing_urls_path, notice: 'Author was successfully destroyed.'
end | ruby | def destroy
@script_listing = Script::Listing.find(params[:listing_id])
@script_url = @script_listing.urls.find(params[:id])
@script_url.destroy
redirect_to script_listing_urls_path, notice: 'Author was successfully destroyed.'
end | [
"def",
"destroy",
"@script_listing",
"=",
"Script",
"::",
"Listing",
".",
"find",
"(",
"params",
"[",
":listing_id",
"]",
")",
"@script_url",
"=",
"@script_listing",
".",
"urls",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"@script_url",
".",
"destroy",
"redirect_to",
"script_listing_urls_path",
",",
"notice",
":",
"'Author was successfully destroyed.'",
"end"
]
| DELETE - Script Athors | [
"DELETE",
"-",
"Script",
"Athors"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/urls_controller.rb#L63-L68 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/listings_controller.rb | Phcscriptcdn.Script::ListingsController.show | def show
@script_listings = Script::Listing.friendly.find(params[:id])
@versions = Phcscriptcdn::ListingVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Listing')
end | ruby | def show
@script_listings = Script::Listing.friendly.find(params[:id])
@versions = Phcscriptcdn::ListingVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Listing')
end | [
"def",
"show",
"@script_listings",
"=",
"Script",
"::",
"Listing",
".",
"friendly",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"@versions",
"=",
"Phcscriptcdn",
"::",
"ListingVersions",
".",
"where",
"(",
"item_id",
":",
"params",
"[",
":id",
"]",
",",
"item_type",
":",
"'Phcscriptcdn::Script::Listing'",
")",
"end"
]
| DETAILS - Script Listings | [
"DETAILS",
"-",
"Script",
"Listings"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/listings_controller.rb#L18-L21 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/listings_controller.rb | Phcscriptcdn.Script::ListingsController.create | def create
@script_listing = Script::Listing.new(script_listing_params)
@script_listing.user_id = current_user.id
@script_listing.org_id = current_user.org_id
if @script_listing.save
redirect_to script_listings_path, notice: 'Listing was successfully created.'
else
render :new
end
end | ruby | def create
@script_listing = Script::Listing.new(script_listing_params)
@script_listing.user_id = current_user.id
@script_listing.org_id = current_user.org_id
if @script_listing.save
redirect_to script_listings_path, notice: 'Listing was successfully created.'
else
render :new
end
end | [
"def",
"create",
"@script_listing",
"=",
"Script",
"::",
"Listing",
".",
"new",
"(",
"script_listing_params",
")",
"@script_listing",
".",
"user_id",
"=",
"current_user",
".",
"id",
"@script_listing",
".",
"org_id",
"=",
"current_user",
".",
"org_id",
"if",
"@script_listing",
".",
"save",
"redirect_to",
"script_listings_path",
",",
"notice",
":",
"'Listing was successfully created.'",
"else",
"render",
":new",
"end",
"end"
]
| POST - Script Listings | [
"POST",
"-",
"Script",
"Listings"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/listings_controller.rb#L33-L42 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.put_object | def put_object(obj_path, data, opts = {})
url = obj_url(obj_path)
opts[:data] = data
headers = gen_headers(opts)
cors_headers = gen_cors_headers(opts)
headers = headers.concat(cors_headers)
durability_level = opts[:durability_level]
if durability_level
raise ArgumentError unless durability_level > 0
headers.push([ 'Durability-Level', durability_level ])
end
content_type = opts[:content_type]
if content_type
raise ArgumentError unless content_type.is_a? String
headers.push([ 'Content-Type', content_type ])
end
attempt(opts[:attempts]) do
result = @client.put(url, data, headers)
raise unless result.is_a? HTTP::Message
return true, result.headers if [204, 304].include? result.status
raise_error(result)
end
end | ruby | def put_object(obj_path, data, opts = {})
url = obj_url(obj_path)
opts[:data] = data
headers = gen_headers(opts)
cors_headers = gen_cors_headers(opts)
headers = headers.concat(cors_headers)
durability_level = opts[:durability_level]
if durability_level
raise ArgumentError unless durability_level > 0
headers.push([ 'Durability-Level', durability_level ])
end
content_type = opts[:content_type]
if content_type
raise ArgumentError unless content_type.is_a? String
headers.push([ 'Content-Type', content_type ])
end
attempt(opts[:attempts]) do
result = @client.put(url, data, headers)
raise unless result.is_a? HTTP::Message
return true, result.headers if [204, 304].include? result.status
raise_error(result)
end
end | [
"def",
"put_object",
"(",
"obj_path",
",",
"data",
",",
"opts",
"=",
"{",
"}",
")",
"url",
"=",
"obj_url",
"(",
"obj_path",
")",
"opts",
"[",
":data",
"]",
"=",
"data",
"headers",
"=",
"gen_headers",
"(",
"opts",
")",
"cors_headers",
"=",
"gen_cors_headers",
"(",
"opts",
")",
"headers",
"=",
"headers",
".",
"concat",
"(",
"cors_headers",
")",
"durability_level",
"=",
"opts",
"[",
":durability_level",
"]",
"if",
"durability_level",
"raise",
"ArgumentError",
"unless",
"durability_level",
">",
"0",
"headers",
".",
"push",
"(",
"[",
"'Durability-Level'",
",",
"durability_level",
"]",
")",
"end",
"content_type",
"=",
"opts",
"[",
":content_type",
"]",
"if",
"content_type",
"raise",
"ArgumentError",
"unless",
"content_type",
".",
"is_a?",
"String",
"headers",
".",
"push",
"(",
"[",
"'Content-Type'",
",",
"content_type",
"]",
")",
"end",
"attempt",
"(",
"opts",
"[",
":attempts",
"]",
")",
"do",
"result",
"=",
"@client",
".",
"put",
"(",
"url",
",",
"data",
",",
"headers",
")",
"raise",
"unless",
"result",
".",
"is_a?",
"HTTP",
"::",
"Message",
"return",
"true",
",",
"result",
".",
"headers",
"if",
"[",
"204",
",",
"304",
"]",
".",
"include?",
"result",
".",
"status",
"raise_error",
"(",
"result",
")",
"end",
"end"
]
| Initialize a MantaClient instance.
priv_key_data is data read directly from an SSH private key (i.e. RFC 4716
format). The method can also accept several optional args: :connect_timeout,
:send_timeout, :receive_timeout, :disable_ssl_verification and :attempts.
The timeouts are in seconds, and :attempts determines the default number of
attempts each method will make upon receiving recoverable errors.
Will throw an exception if given a key whose format it doesn't understand.
Uploads object data to Manta to the given path, along with a computed MD5
hash.
The path must start with /<user>/stor or /<user/public. Data can be any
sequence of octets. The HTTP Content-Type stored on Manta can be set
with an optional :content_type argument; the default is
application/octet-stream. The number of distributed replicates of an object
stored in Manta can be set with an optional :durability_level; the default
is 2.
Returns true along with received HTTP headers.
If there was an unrecoverable error, throws an exception. On connection or
corruption errors, more attempts will be made; the number of attempts can
be altered by passing in :attempts. | [
"Initialize",
"a",
"MantaClient",
"instance",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L137-L165 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.get_object | def get_object(obj_path, opts = {})
url = obj_url(obj_path)
headers = gen_headers(opts)
attempt(opts[:attempts]) do
method = opts[:head] ? :head : :get
result = @client.send(method, url, nil, headers)
raise unless result.is_a? HTTP::Message
if result.status == 200
return true, result.headers if method == :head
sent_md5 = result.headers['Content-MD5']
received_md5 = Digest::MD5.base64digest(result.body)
raise CorruptResult if sent_md5 != received_md5
return result.body, result.headers
elsif result.status == 304
return nil, result.headers
end
raise_error(result)
end
end | ruby | def get_object(obj_path, opts = {})
url = obj_url(obj_path)
headers = gen_headers(opts)
attempt(opts[:attempts]) do
method = opts[:head] ? :head : :get
result = @client.send(method, url, nil, headers)
raise unless result.is_a? HTTP::Message
if result.status == 200
return true, result.headers if method == :head
sent_md5 = result.headers['Content-MD5']
received_md5 = Digest::MD5.base64digest(result.body)
raise CorruptResult if sent_md5 != received_md5
return result.body, result.headers
elsif result.status == 304
return nil, result.headers
end
raise_error(result)
end
end | [
"def",
"get_object",
"(",
"obj_path",
",",
"opts",
"=",
"{",
"}",
")",
"url",
"=",
"obj_url",
"(",
"obj_path",
")",
"headers",
"=",
"gen_headers",
"(",
"opts",
")",
"attempt",
"(",
"opts",
"[",
":attempts",
"]",
")",
"do",
"method",
"=",
"opts",
"[",
":head",
"]",
"?",
":head",
":",
":get",
"result",
"=",
"@client",
".",
"send",
"(",
"method",
",",
"url",
",",
"nil",
",",
"headers",
")",
"raise",
"unless",
"result",
".",
"is_a?",
"HTTP",
"::",
"Message",
"if",
"result",
".",
"status",
"==",
"200",
"return",
"true",
",",
"result",
".",
"headers",
"if",
"method",
"==",
":head",
"sent_md5",
"=",
"result",
".",
"headers",
"[",
"'Content-MD5'",
"]",
"received_md5",
"=",
"Digest",
"::",
"MD5",
".",
"base64digest",
"(",
"result",
".",
"body",
")",
"raise",
"CorruptResult",
"if",
"sent_md5",
"!=",
"received_md5",
"return",
"result",
".",
"body",
",",
"result",
".",
"headers",
"elsif",
"result",
".",
"status",
"==",
"304",
"return",
"nil",
",",
"result",
".",
"headers",
"end",
"raise_error",
"(",
"result",
")",
"end",
"end"
]
| Get an object from Manta at a given path, and checks it's uncorrupted.
The path must start with /<user>/stor or /<user/public and point at an
actual object, as well as output objects for jobs. :head => true can
optionally be passed in to do a HEAD instead of a GET.
Returns the retrieved data along with received HTTP headers.
If there was an unrecoverable error, throws an exception. On connection or
corruption errors, more attempts will be made; the number of attempts can
be altered by passing in :attempts. | [
"Get",
"an",
"object",
"from",
"Manta",
"at",
"a",
"given",
"path",
"and",
"checks",
"it",
"s",
"uncorrupted",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L180-L203 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.delete_object | def delete_object(obj_path, opts = {})
url = obj_url(obj_path)
headers = gen_headers(opts)
attempt(opts[:attempts]) do
result = @client.delete(url, nil, headers)
raise unless result.is_a? HTTP::Message
return true, result.headers if result.status == 204
raise_error(result)
end
end | ruby | def delete_object(obj_path, opts = {})
url = obj_url(obj_path)
headers = gen_headers(opts)
attempt(opts[:attempts]) do
result = @client.delete(url, nil, headers)
raise unless result.is_a? HTTP::Message
return true, result.headers if result.status == 204
raise_error(result)
end
end | [
"def",
"delete_object",
"(",
"obj_path",
",",
"opts",
"=",
"{",
"}",
")",
"url",
"=",
"obj_url",
"(",
"obj_path",
")",
"headers",
"=",
"gen_headers",
"(",
"opts",
")",
"attempt",
"(",
"opts",
"[",
":attempts",
"]",
")",
"do",
"result",
"=",
"@client",
".",
"delete",
"(",
"url",
",",
"nil",
",",
"headers",
")",
"raise",
"unless",
"result",
".",
"is_a?",
"HTTP",
"::",
"Message",
"return",
"true",
",",
"result",
".",
"headers",
"if",
"result",
".",
"status",
"==",
"204",
"raise_error",
"(",
"result",
")",
"end",
"end"
]
| Deletes an object off Manta at a given path.
The path must start with /<user>/stor or /<user/public and point at an
actual object.
Returns true along with received HTTP headers.
If there was an unrecoverable error, throws an exception. On connection or
corruption errors, more attempts will be made; the number of attempts can
be altered by passing in :attempts. | [
"Deletes",
"an",
"object",
"off",
"Manta",
"at",
"a",
"given",
"path",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L217-L228 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.put_directory | def put_directory(dir_path, opts = {})
url = obj_url(dir_path)
headers = gen_headers(opts)
headers.push([ 'Content-Type', 'application/json; type=directory' ])
cors_headers = gen_cors_headers(opts)
headers = headers.concat(cors_headers)
attempt(opts[:attempts]) do
result = @client.put(url, nil, headers)
raise unless result.is_a? HTTP::Message
return true, result.headers if result.status == 204
raise_error(result)
end
end | ruby | def put_directory(dir_path, opts = {})
url = obj_url(dir_path)
headers = gen_headers(opts)
headers.push([ 'Content-Type', 'application/json; type=directory' ])
cors_headers = gen_cors_headers(opts)
headers = headers.concat(cors_headers)
attempt(opts[:attempts]) do
result = @client.put(url, nil, headers)
raise unless result.is_a? HTTP::Message
return true, result.headers if result.status == 204
raise_error(result)
end
end | [
"def",
"put_directory",
"(",
"dir_path",
",",
"opts",
"=",
"{",
"}",
")",
"url",
"=",
"obj_url",
"(",
"dir_path",
")",
"headers",
"=",
"gen_headers",
"(",
"opts",
")",
"headers",
".",
"push",
"(",
"[",
"'Content-Type'",
",",
"'application/json; type=directory'",
"]",
")",
"cors_headers",
"=",
"gen_cors_headers",
"(",
"opts",
")",
"headers",
"=",
"headers",
".",
"concat",
"(",
"cors_headers",
")",
"attempt",
"(",
"opts",
"[",
":attempts",
"]",
")",
"do",
"result",
"=",
"@client",
".",
"put",
"(",
"url",
",",
"nil",
",",
"headers",
")",
"raise",
"unless",
"result",
".",
"is_a?",
"HTTP",
"::",
"Message",
"return",
"true",
",",
"result",
".",
"headers",
"if",
"result",
".",
"status",
"==",
"204",
"raise_error",
"(",
"result",
")",
"end",
"end"
]
| Creates a directory on Manta at a given path.
The path must start with /<user>/stor or /<user/public.
Returns true along with received HTTP headers.
If there was an unrecoverable error, throws an exception. On connection or
corruption errors, more attempts will be made; the number of attempts can
be altered by passing in :attempts. | [
"Creates",
"a",
"directory",
"on",
"Manta",
"at",
"a",
"given",
"path",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L241-L256 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.list_directory | def list_directory(dir_path, opts = {})
url = obj_url(dir_path)
headers = gen_headers(opts)
query_parameters = {}
limit = opts[:limit] || MAX_LIMIT
raise ArgumentError unless 0 < limit && limit <= MAX_LIMIT
query_parameters[:limit] = limit
marker = opts[:marker]
if marker
raise ArgumentError unless marker.is_a? String
query_parameters[:marker] = marker
end
attempt(opts[:attempts]) do
method = opts[:head] ? :head : :get
result = @client.send(method, url, query_parameters, headers)
raise unless result.is_a? HTTP::Message
if result.status == 200
raise unless result.headers['Content-Type'] ==
'application/x-json-stream; type=directory'
return true, result.headers if method == :head
json_chunks = result.body.split("\n")
if json_chunks.size > limit
raise CorruptResult
end
dir_entries = json_chunks.map { |i| JSON.parse(i) }
return dir_entries, result.headers
end
raise_error(result)
end
end | ruby | def list_directory(dir_path, opts = {})
url = obj_url(dir_path)
headers = gen_headers(opts)
query_parameters = {}
limit = opts[:limit] || MAX_LIMIT
raise ArgumentError unless 0 < limit && limit <= MAX_LIMIT
query_parameters[:limit] = limit
marker = opts[:marker]
if marker
raise ArgumentError unless marker.is_a? String
query_parameters[:marker] = marker
end
attempt(opts[:attempts]) do
method = opts[:head] ? :head : :get
result = @client.send(method, url, query_parameters, headers)
raise unless result.is_a? HTTP::Message
if result.status == 200
raise unless result.headers['Content-Type'] ==
'application/x-json-stream; type=directory'
return true, result.headers if method == :head
json_chunks = result.body.split("\n")
if json_chunks.size > limit
raise CorruptResult
end
dir_entries = json_chunks.map { |i| JSON.parse(i) }
return dir_entries, result.headers
end
raise_error(result)
end
end | [
"def",
"list_directory",
"(",
"dir_path",
",",
"opts",
"=",
"{",
"}",
")",
"url",
"=",
"obj_url",
"(",
"dir_path",
")",
"headers",
"=",
"gen_headers",
"(",
"opts",
")",
"query_parameters",
"=",
"{",
"}",
"limit",
"=",
"opts",
"[",
":limit",
"]",
"||",
"MAX_LIMIT",
"raise",
"ArgumentError",
"unless",
"0",
"<",
"limit",
"&&",
"limit",
"<=",
"MAX_LIMIT",
"query_parameters",
"[",
":limit",
"]",
"=",
"limit",
"marker",
"=",
"opts",
"[",
":marker",
"]",
"if",
"marker",
"raise",
"ArgumentError",
"unless",
"marker",
".",
"is_a?",
"String",
"query_parameters",
"[",
":marker",
"]",
"=",
"marker",
"end",
"attempt",
"(",
"opts",
"[",
":attempts",
"]",
")",
"do",
"method",
"=",
"opts",
"[",
":head",
"]",
"?",
":head",
":",
":get",
"result",
"=",
"@client",
".",
"send",
"(",
"method",
",",
"url",
",",
"query_parameters",
",",
"headers",
")",
"raise",
"unless",
"result",
".",
"is_a?",
"HTTP",
"::",
"Message",
"if",
"result",
".",
"status",
"==",
"200",
"raise",
"unless",
"result",
".",
"headers",
"[",
"'Content-Type'",
"]",
"==",
"'application/x-json-stream; type=directory'",
"return",
"true",
",",
"result",
".",
"headers",
"if",
"method",
"==",
":head",
"json_chunks",
"=",
"result",
".",
"body",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"json_chunks",
".",
"size",
">",
"limit",
"raise",
"CorruptResult",
"end",
"dir_entries",
"=",
"json_chunks",
".",
"map",
"{",
"|",
"i",
"|",
"JSON",
".",
"parse",
"(",
"i",
")",
"}",
"return",
"dir_entries",
",",
"result",
".",
"headers",
"end",
"raise_error",
"(",
"result",
")",
"end",
"end"
]
| Gets a lexicographically sorted directory listing on Manta at a given path,
The path must start with /<user>/stor or /<user/public and point at an
actual directory. :limit optionally changes the maximum number of entries;
the default is 1000. If given :marker, an object name in the directory,
returned directory entries will begin from that point. :head => true can
optionally be passed in to do a HEAD instead of a GET.
Returns an array of hash objects, each object representing a directory
entry. Also returns the received HTTP headers.
If there was an unrecoverable error, throws an exception. On connection or
corruption errors, more attempts will be made; the number of attempts can
be altered by passing in :attempts. | [
"Gets",
"a",
"lexicographically",
"sorted",
"directory",
"listing",
"on",
"Manta",
"at",
"a",
"given",
"path"
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L274-L313 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.find | def find(dir_path, opts = {})
regex = opts.key?(:regex) ? opts[:regex] : nil
# We should always be doing GET because switching between methods is used
# within this function.
opts.delete(:head)
begin
exists = list_directory(dir_path, head: true).first
rescue
exists = false
end
return [] unless exists
response = list_directory(dir_path, opts)
listing = response.first
listing.inject([]) do |memo, obj|
if obj['type'] == 'directory'
sub_dir = "#{dir_path}/#{obj['name']}"
sub_search = find(sub_dir, regex: regex)
memo.push(*sub_search)
end
if obj['type'] == 'object'
file = "#{dir_path}/#{obj['name']}"
if !regex || obj['name'].match(regex)
memo.push file
end
end
memo
end
end | ruby | def find(dir_path, opts = {})
regex = opts.key?(:regex) ? opts[:regex] : nil
# We should always be doing GET because switching between methods is used
# within this function.
opts.delete(:head)
begin
exists = list_directory(dir_path, head: true).first
rescue
exists = false
end
return [] unless exists
response = list_directory(dir_path, opts)
listing = response.first
listing.inject([]) do |memo, obj|
if obj['type'] == 'directory'
sub_dir = "#{dir_path}/#{obj['name']}"
sub_search = find(sub_dir, regex: regex)
memo.push(*sub_search)
end
if obj['type'] == 'object'
file = "#{dir_path}/#{obj['name']}"
if !regex || obj['name'].match(regex)
memo.push file
end
end
memo
end
end | [
"def",
"find",
"(",
"dir_path",
",",
"opts",
"=",
"{",
"}",
")",
"regex",
"=",
"opts",
".",
"key?",
"(",
":regex",
")",
"?",
"opts",
"[",
":regex",
"]",
":",
"nil",
"opts",
".",
"delete",
"(",
":head",
")",
"begin",
"exists",
"=",
"list_directory",
"(",
"dir_path",
",",
"head",
":",
"true",
")",
".",
"first",
"rescue",
"exists",
"=",
"false",
"end",
"return",
"[",
"]",
"unless",
"exists",
"response",
"=",
"list_directory",
"(",
"dir_path",
",",
"opts",
")",
"listing",
"=",
"response",
".",
"first",
"listing",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"memo",
",",
"obj",
"|",
"if",
"obj",
"[",
"'type'",
"]",
"==",
"'directory'",
"sub_dir",
"=",
"\"#{dir_path}/#{obj['name']}\"",
"sub_search",
"=",
"find",
"(",
"sub_dir",
",",
"regex",
":",
"regex",
")",
"memo",
".",
"push",
"(",
"*",
"sub_search",
")",
"end",
"if",
"obj",
"[",
"'type'",
"]",
"==",
"'object'",
"file",
"=",
"\"#{dir_path}/#{obj['name']}\"",
"if",
"!",
"regex",
"||",
"obj",
"[",
"'name'",
"]",
".",
"match",
"(",
"regex",
")",
"memo",
".",
"push",
"file",
"end",
"end",
"memo",
"end",
"end"
]
| Finds all objects recursively under a given directory. Optionally, a regular
expression can be specified and used to filter the results returned. | [
"Finds",
"all",
"objects",
"recursively",
"under",
"a",
"given",
"directory",
".",
"Optionally",
"a",
"regular",
"expression",
"can",
"be",
"specified",
"and",
"used",
"to",
"filter",
"the",
"results",
"returned",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L318-L353 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.delete_directory | def delete_directory(dir_path, opts = {})
url = obj_url(dir_path)
headers = gen_headers(opts)
attempt(opts[:attempts]) do
result = @client.delete(url, nil, headers)
raise unless result.is_a? HTTP::Message
return true, result.headers if result.status == 204
raise_error(result)
end
end | ruby | def delete_directory(dir_path, opts = {})
url = obj_url(dir_path)
headers = gen_headers(opts)
attempt(opts[:attempts]) do
result = @client.delete(url, nil, headers)
raise unless result.is_a? HTTP::Message
return true, result.headers if result.status == 204
raise_error(result)
end
end | [
"def",
"delete_directory",
"(",
"dir_path",
",",
"opts",
"=",
"{",
"}",
")",
"url",
"=",
"obj_url",
"(",
"dir_path",
")",
"headers",
"=",
"gen_headers",
"(",
"opts",
")",
"attempt",
"(",
"opts",
"[",
":attempts",
"]",
")",
"do",
"result",
"=",
"@client",
".",
"delete",
"(",
"url",
",",
"nil",
",",
"headers",
")",
"raise",
"unless",
"result",
".",
"is_a?",
"HTTP",
"::",
"Message",
"return",
"true",
",",
"result",
".",
"headers",
"if",
"result",
".",
"status",
"==",
"204",
"raise_error",
"(",
"result",
")",
"end",
"end"
]
| Removes a directory from Manta at a given path.
The path must start with /<user>/stor or /<user/public and point at an
actual object.
Returns true along with received HTTP headers.
If there was an unrecoverable error, throws an exception. On connection or
corruption errors, more attempts will be made; the number of attempts can
be altered by passing in :attempts. | [
"Removes",
"a",
"directory",
"from",
"Manta",
"at",
"a",
"given",
"path",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L367-L378 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.put_snaplink | def put_snaplink(orig_path, link_path, opts = {})
headers = gen_headers(opts)
headers.push([ 'Content-Type', 'application/json; type=link' ],
[ 'Location', obj_url(orig_path) ])
attempt(opts[:attempts]) do
result = @client.put(obj_url(link_path), nil, headers)
raise unless result.is_a? HTTP::Message
return true, result.headers if result.status == 204
raise_error(result)
end
end | ruby | def put_snaplink(orig_path, link_path, opts = {})
headers = gen_headers(opts)
headers.push([ 'Content-Type', 'application/json; type=link' ],
[ 'Location', obj_url(orig_path) ])
attempt(opts[:attempts]) do
result = @client.put(obj_url(link_path), nil, headers)
raise unless result.is_a? HTTP::Message
return true, result.headers if result.status == 204
raise_error(result)
end
end | [
"def",
"put_snaplink",
"(",
"orig_path",
",",
"link_path",
",",
"opts",
"=",
"{",
"}",
")",
"headers",
"=",
"gen_headers",
"(",
"opts",
")",
"headers",
".",
"push",
"(",
"[",
"'Content-Type'",
",",
"'application/json; type=link'",
"]",
",",
"[",
"'Location'",
",",
"obj_url",
"(",
"orig_path",
")",
"]",
")",
"attempt",
"(",
"opts",
"[",
":attempts",
"]",
")",
"do",
"result",
"=",
"@client",
".",
"put",
"(",
"obj_url",
"(",
"link_path",
")",
",",
"nil",
",",
"headers",
")",
"raise",
"unless",
"result",
".",
"is_a?",
"HTTP",
"::",
"Message",
"return",
"true",
",",
"result",
".",
"headers",
"if",
"result",
".",
"status",
"==",
"204",
"raise_error",
"(",
"result",
")",
"end",
"end"
]
| Creates a snaplink from one object in Manta at a given path to a different
path.
Both paths should start with /<user>/stor or /<user/public.
Returns true along with received HTTP headers.
If there was an unrecoverable error, throws an exception. On connection or
corruption errors, more attempts will be made; the number of attempts can
be altered by passing in :attempts. | [
"Creates",
"a",
"snaplink",
"from",
"one",
"object",
"in",
"Manta",
"at",
"a",
"given",
"path",
"to",
"a",
"different",
"path",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L392-L404 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.create_job | def create_job(job, opts = {})
raise ArgumentError unless job[:phases] || job['phases']
headers = gen_headers(opts)
headers.push([ 'Content-Type', 'application/json; type=job' ])
data = job.to_json
attempt(opts[:attempts]) do
result = @client.post(job_url(), data, headers)
raise unless result.is_a? HTTP::Message
if result.status == 201
location = result.headers['Location']
raise unless location
return location, result.headers
end
raise_error(result)
end
end | ruby | def create_job(job, opts = {})
raise ArgumentError unless job[:phases] || job['phases']
headers = gen_headers(opts)
headers.push([ 'Content-Type', 'application/json; type=job' ])
data = job.to_json
attempt(opts[:attempts]) do
result = @client.post(job_url(), data, headers)
raise unless result.is_a? HTTP::Message
if result.status == 201
location = result.headers['Location']
raise unless location
return location, result.headers
end
raise_error(result)
end
end | [
"def",
"create_job",
"(",
"job",
",",
"opts",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
"unless",
"job",
"[",
":phases",
"]",
"||",
"job",
"[",
"'phases'",
"]",
"headers",
"=",
"gen_headers",
"(",
"opts",
")",
"headers",
".",
"push",
"(",
"[",
"'Content-Type'",
",",
"'application/json; type=job'",
"]",
")",
"data",
"=",
"job",
".",
"to_json",
"attempt",
"(",
"opts",
"[",
":attempts",
"]",
")",
"do",
"result",
"=",
"@client",
".",
"post",
"(",
"job_url",
"(",
")",
",",
"data",
",",
"headers",
")",
"raise",
"unless",
"result",
".",
"is_a?",
"HTTP",
"::",
"Message",
"if",
"result",
".",
"status",
"==",
"201",
"location",
"=",
"result",
".",
"headers",
"[",
"'Location'",
"]",
"raise",
"unless",
"location",
"return",
"location",
",",
"result",
".",
"headers",
"end",
"raise_error",
"(",
"result",
")",
"end",
"end"
]
| Creates a job in Manta.
The job must be a hash, containing at minimum a :phases key. See README.md
or the Manta docs to see the format and options for setting up a job on
Manta; this method effectively just converts the job hash to JSON and sends
to the Manta service.
Returns the path for the new job, along with received HTTP headers.
If there was an unrecoverable error, throws an exception. On connection or
corruption errors, more attempts will be made; the number of attempts can
be altered by passing in :attempts. | [
"Creates",
"a",
"job",
"in",
"Manta",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L420-L440 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.get_job | def get_job(job_path, opts = {})
url = job_url(job_path, '/live/status')
headers = gen_headers(opts)
attempt(opts[:attempts]) do
method = opts[:head] ? :head : :get
result = @client.send(method, url, nil, headers)
raise unless result.is_a? HTTP::Message
if result.status == 200
raise unless result.headers['Content-Type'] == 'application/json'
return true, result.headers if method == :head
job = JSON.parse(result.body)
return job, result.headers
end
raise_error(result)
end
end | ruby | def get_job(job_path, opts = {})
url = job_url(job_path, '/live/status')
headers = gen_headers(opts)
attempt(opts[:attempts]) do
method = opts[:head] ? :head : :get
result = @client.send(method, url, nil, headers)
raise unless result.is_a? HTTP::Message
if result.status == 200
raise unless result.headers['Content-Type'] == 'application/json'
return true, result.headers if method == :head
job = JSON.parse(result.body)
return job, result.headers
end
raise_error(result)
end
end | [
"def",
"get_job",
"(",
"job_path",
",",
"opts",
"=",
"{",
"}",
")",
"url",
"=",
"job_url",
"(",
"job_path",
",",
"'/live/status'",
")",
"headers",
"=",
"gen_headers",
"(",
"opts",
")",
"attempt",
"(",
"opts",
"[",
":attempts",
"]",
")",
"do",
"method",
"=",
"opts",
"[",
":head",
"]",
"?",
":head",
":",
":get",
"result",
"=",
"@client",
".",
"send",
"(",
"method",
",",
"url",
",",
"nil",
",",
"headers",
")",
"raise",
"unless",
"result",
".",
"is_a?",
"HTTP",
"::",
"Message",
"if",
"result",
".",
"status",
"==",
"200",
"raise",
"unless",
"result",
".",
"headers",
"[",
"'Content-Type'",
"]",
"==",
"'application/json'",
"return",
"true",
",",
"result",
".",
"headers",
"if",
"method",
"==",
":head",
"job",
"=",
"JSON",
".",
"parse",
"(",
"result",
".",
"body",
")",
"return",
"job",
",",
"result",
".",
"headers",
"end",
"raise_error",
"(",
"result",
")",
"end",
"end"
]
| Gets various information about a job in Manta at a given path.
The path must start with /<user>/jobs/<job UUID> and point at an actual job.
:head => true can optionally be passed in to do a HEAD instead of a GET.
Returns a hash with job information, along with received HTTP headers.
If there was an unrecoverable error, throws an exception. On connection or
corruption errors, more attempts will be made; the number of attempts can
be altered by passing in :attempts. | [
"Gets",
"various",
"information",
"about",
"a",
"job",
"in",
"Manta",
"at",
"a",
"given",
"path",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L454-L474 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.get_job_errors | def get_job_errors(job_path, opts = {})
url = job_url(job_path, '/live/err')
headers = gen_headers(opts)
attempt(opts[:attempts]) do
method = opts[:head] ? :head : :get
result = @client.send(method, url, nil, headers)
raise unless result.is_a? HTTP::Message
if result.status == 200
raise unless result.headers['Content-Type'] ==
'application/x-json-stream; type=job-error'
return true, result.headers if method == :head
json_chunks = result.body.split("\n")
errors = json_chunks.map { |i| JSON.parse(i) }
return errors, result.headers
end
raise_error(result)
end
end | ruby | def get_job_errors(job_path, opts = {})
url = job_url(job_path, '/live/err')
headers = gen_headers(opts)
attempt(opts[:attempts]) do
method = opts[:head] ? :head : :get
result = @client.send(method, url, nil, headers)
raise unless result.is_a? HTTP::Message
if result.status == 200
raise unless result.headers['Content-Type'] ==
'application/x-json-stream; type=job-error'
return true, result.headers if method == :head
json_chunks = result.body.split("\n")
errors = json_chunks.map { |i| JSON.parse(i) }
return errors, result.headers
end
raise_error(result)
end
end | [
"def",
"get_job_errors",
"(",
"job_path",
",",
"opts",
"=",
"{",
"}",
")",
"url",
"=",
"job_url",
"(",
"job_path",
",",
"'/live/err'",
")",
"headers",
"=",
"gen_headers",
"(",
"opts",
")",
"attempt",
"(",
"opts",
"[",
":attempts",
"]",
")",
"do",
"method",
"=",
"opts",
"[",
":head",
"]",
"?",
":head",
":",
":get",
"result",
"=",
"@client",
".",
"send",
"(",
"method",
",",
"url",
",",
"nil",
",",
"headers",
")",
"raise",
"unless",
"result",
".",
"is_a?",
"HTTP",
"::",
"Message",
"if",
"result",
".",
"status",
"==",
"200",
"raise",
"unless",
"result",
".",
"headers",
"[",
"'Content-Type'",
"]",
"==",
"'application/x-json-stream; type=job-error'",
"return",
"true",
",",
"result",
".",
"headers",
"if",
"method",
"==",
":head",
"json_chunks",
"=",
"result",
".",
"body",
".",
"split",
"(",
"\"\\n\"",
")",
"errors",
"=",
"json_chunks",
".",
"map",
"{",
"|",
"i",
"|",
"JSON",
".",
"parse",
"(",
"i",
")",
"}",
"return",
"errors",
",",
"result",
".",
"headers",
"end",
"raise_error",
"(",
"result",
")",
"end",
"end"
]
| Gets errors that occured during the execution of a job in Manta at a given
path.
The path must start with /<user>/jobs/<job UUID> and point at an actual job.
:head => true can optionally be passed in to do a HEAD instead of a GET.
Returns an array of hashes, each hash containing information about an
error; this information is best-effort by Manta, so it may not be complete.
Also returns received HTTP headers.
If there was an unrecoverable error, throws an exception. On connection or
corruption errors, more attempts will be made; the number of attempts can
be altered by passing in :attempts. | [
"Gets",
"errors",
"that",
"occured",
"during",
"the",
"execution",
"of",
"a",
"job",
"in",
"Manta",
"at",
"a",
"given",
"path",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L491-L514 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.cancel_job | def cancel_job(job_path, opts = {})
url = job_url(job_path, 'live/cancel')
body = '{}'
opts[:data] = body
headers = gen_headers(opts)
headers << [ 'Accept', 'application/json' ]
headers << [ 'Content-Type', 'application/json']
headers << [ 'Content-Length', body.bytesize ]
args = {
header: headers,
body: body
}
attempt(opts[:attempts]) do
result = @client.post(url, args)
raise unless result.is_a? HTTP::Message
return true, result.headers if result.status == 202
raise_error(result)
end
end | ruby | def cancel_job(job_path, opts = {})
url = job_url(job_path, 'live/cancel')
body = '{}'
opts[:data] = body
headers = gen_headers(opts)
headers << [ 'Accept', 'application/json' ]
headers << [ 'Content-Type', 'application/json']
headers << [ 'Content-Length', body.bytesize ]
args = {
header: headers,
body: body
}
attempt(opts[:attempts]) do
result = @client.post(url, args)
raise unless result.is_a? HTTP::Message
return true, result.headers if result.status == 202
raise_error(result)
end
end | [
"def",
"cancel_job",
"(",
"job_path",
",",
"opts",
"=",
"{",
"}",
")",
"url",
"=",
"job_url",
"(",
"job_path",
",",
"'live/cancel'",
")",
"body",
"=",
"'{}'",
"opts",
"[",
":data",
"]",
"=",
"body",
"headers",
"=",
"gen_headers",
"(",
"opts",
")",
"headers",
"<<",
"[",
"'Accept'",
",",
"'application/json'",
"]",
"headers",
"<<",
"[",
"'Content-Type'",
",",
"'application/json'",
"]",
"headers",
"<<",
"[",
"'Content-Length'",
",",
"body",
".",
"bytesize",
"]",
"args",
"=",
"{",
"header",
":",
"headers",
",",
"body",
":",
"body",
"}",
"attempt",
"(",
"opts",
"[",
":attempts",
"]",
")",
"do",
"result",
"=",
"@client",
".",
"post",
"(",
"url",
",",
"args",
")",
"raise",
"unless",
"result",
".",
"is_a?",
"HTTP",
"::",
"Message",
"return",
"true",
",",
"result",
".",
"headers",
"if",
"result",
".",
"status",
"==",
"202",
"raise_error",
"(",
"result",
")",
"end",
"end"
]
| Cancels a running job in Manta at a given path.
The path must start with /<user>/jobs/<job UUID> and point at an actual job.
Returns true, along with received HTTP headers.
If there was an unrecoverable error, throws an exception. On connection or
corruption errors, more attempts will be made; the number of attempts can
be altered by passing in :attempts. | [
"Cancels",
"a",
"running",
"job",
"in",
"Manta",
"at",
"a",
"given",
"path",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L527-L552 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.add_job_keys | def add_job_keys(job_path, obj_paths, opts = {})
url = job_url(job_path, '/live/in')
headers = gen_headers(opts)
headers.push([ 'Content-Type', 'text/plain' ])
data = obj_paths.join("\n")
attempt(opts[:attempts]) do
result = @client.post(url, data, headers)
raise unless result.is_a? HTTP::Message
return true, result.headers if result.status == 204
raise_error(result)
end
end | ruby | def add_job_keys(job_path, obj_paths, opts = {})
url = job_url(job_path, '/live/in')
headers = gen_headers(opts)
headers.push([ 'Content-Type', 'text/plain' ])
data = obj_paths.join("\n")
attempt(opts[:attempts]) do
result = @client.post(url, data, headers)
raise unless result.is_a? HTTP::Message
return true, result.headers if result.status == 204
raise_error(result)
end
end | [
"def",
"add_job_keys",
"(",
"job_path",
",",
"obj_paths",
",",
"opts",
"=",
"{",
"}",
")",
"url",
"=",
"job_url",
"(",
"job_path",
",",
"'/live/in'",
")",
"headers",
"=",
"gen_headers",
"(",
"opts",
")",
"headers",
".",
"push",
"(",
"[",
"'Content-Type'",
",",
"'text/plain'",
"]",
")",
"data",
"=",
"obj_paths",
".",
"join",
"(",
"\"\\n\"",
")",
"attempt",
"(",
"opts",
"[",
":attempts",
"]",
")",
"do",
"result",
"=",
"@client",
".",
"post",
"(",
"url",
",",
"data",
",",
"headers",
")",
"raise",
"unless",
"result",
".",
"is_a?",
"HTTP",
"::",
"Message",
"return",
"true",
",",
"result",
".",
"headers",
"if",
"result",
".",
"status",
"==",
"204",
"raise_error",
"(",
"result",
")",
"end",
"end"
]
| Adds objects for a running job in Manta to process.
The job_path must start with /<user>/jobs/<job UUID> and point at an actual
running job. The obj_paths must be an array of paths, starting with
/<user>/stor or /<user>/public, pointing at actual objects.
Returns true, along with received HTTP headers.
If there was an unrecoverable error, throws an exception. On connection or
corruption errors, more attempts will be made; the number of attempts can
be altered by passing in :attempts. | [
"Adds",
"objects",
"for",
"a",
"running",
"job",
"in",
"Manta",
"to",
"process",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L567-L581 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.end_job_input | def end_job_input(job_path, opts = {})
url = job_url(job_path, '/live/in/end')
headers = gen_headers(opts)
attempt(opts[:attempts]) do
result = @client.post(url, nil, headers)
raise unless result.is_a? HTTP::Message
return true, result.headers if result.status == 202
raise_error(result)
end
end | ruby | def end_job_input(job_path, opts = {})
url = job_url(job_path, '/live/in/end')
headers = gen_headers(opts)
attempt(opts[:attempts]) do
result = @client.post(url, nil, headers)
raise unless result.is_a? HTTP::Message
return true, result.headers if result.status == 202
raise_error(result)
end
end | [
"def",
"end_job_input",
"(",
"job_path",
",",
"opts",
"=",
"{",
"}",
")",
"url",
"=",
"job_url",
"(",
"job_path",
",",
"'/live/in/end'",
")",
"headers",
"=",
"gen_headers",
"(",
"opts",
")",
"attempt",
"(",
"opts",
"[",
":attempts",
"]",
")",
"do",
"result",
"=",
"@client",
".",
"post",
"(",
"url",
",",
"nil",
",",
"headers",
")",
"raise",
"unless",
"result",
".",
"is_a?",
"HTTP",
"::",
"Message",
"return",
"true",
",",
"result",
".",
"headers",
"if",
"result",
".",
"status",
"==",
"202",
"raise_error",
"(",
"result",
")",
"end",
"end"
]
| Inform Manta that no more objects will be added for processing by a job,
and that the job should finish all phases and terminate.
The job_path must start with /<user>/jobs/<job UUID> and point at an actual
running job.
Returns true, along with received HTTP headers.
If there was an unrecoverable error, throws an exception. On connection or
corruption errors, more attempts will be made; the number of attempts can
be altered by passing in :attempts. | [
"Inform",
"Manta",
"that",
"no",
"more",
"objects",
"will",
"be",
"added",
"for",
"processing",
"by",
"a",
"job",
"and",
"that",
"the",
"job",
"should",
"finish",
"all",
"phases",
"and",
"terminate",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L596-L607 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.list_jobs | def list_jobs(state, opts = {})
raise ArgumentError unless [:all, :running, :done].include? state
state = nil if state == :all
headers = gen_headers(opts)
attempt(opts[:attempts]) do
# method = opts[:head] ? :head : :get
method = :get # until added to Manta service
result = @client.send(method, job_url(), { :state => state }, headers)
raise unless result.is_a? HTTP::Message
if result.status == 200
# return true, result.headers if method == :head
return [], result.headers if result.body.size == 0
raise unless result.headers['Content-Type'] ==
'application/x-json-stream; type=job'
json_chunks = result.body.split("\n")
job_entries = json_chunks.map { |i| JSON.parse(i) }
return job_entries, result.headers
end
raise_error(result)
end
end | ruby | def list_jobs(state, opts = {})
raise ArgumentError unless [:all, :running, :done].include? state
state = nil if state == :all
headers = gen_headers(opts)
attempt(opts[:attempts]) do
# method = opts[:head] ? :head : :get
method = :get # until added to Manta service
result = @client.send(method, job_url(), { :state => state }, headers)
raise unless result.is_a? HTTP::Message
if result.status == 200
# return true, result.headers if method == :head
return [], result.headers if result.body.size == 0
raise unless result.headers['Content-Type'] ==
'application/x-json-stream; type=job'
json_chunks = result.body.split("\n")
job_entries = json_chunks.map { |i| JSON.parse(i) }
return job_entries, result.headers
end
raise_error(result)
end
end | [
"def",
"list_jobs",
"(",
"state",
",",
"opts",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
"unless",
"[",
":all",
",",
":running",
",",
":done",
"]",
".",
"include?",
"state",
"state",
"=",
"nil",
"if",
"state",
"==",
":all",
"headers",
"=",
"gen_headers",
"(",
"opts",
")",
"attempt",
"(",
"opts",
"[",
":attempts",
"]",
")",
"do",
"method",
"=",
":get",
"result",
"=",
"@client",
".",
"send",
"(",
"method",
",",
"job_url",
"(",
")",
",",
"{",
":state",
"=>",
"state",
"}",
",",
"headers",
")",
"raise",
"unless",
"result",
".",
"is_a?",
"HTTP",
"::",
"Message",
"if",
"result",
".",
"status",
"==",
"200",
"return",
"[",
"]",
",",
"result",
".",
"headers",
"if",
"result",
".",
"body",
".",
"size",
"==",
"0",
"raise",
"unless",
"result",
".",
"headers",
"[",
"'Content-Type'",
"]",
"==",
"'application/x-json-stream; type=job'",
"json_chunks",
"=",
"result",
".",
"body",
".",
"split",
"(",
"\"\\n\"",
")",
"job_entries",
"=",
"json_chunks",
".",
"map",
"{",
"|",
"i",
"|",
"JSON",
".",
"parse",
"(",
"i",
")",
"}",
"return",
"job_entries",
",",
"result",
".",
"headers",
"end",
"raise_error",
"(",
"result",
")",
"end",
"end"
]
| Get lists of Manta jobs.
The state indicates which kind of jobs to return. :running is for jobs
that are currently processing, :done and :all should be obvious. Be careful
of the latter two if you've run a lot of jobs -- the list could be quite
long.
Returns an array of hashes, each hash containing some information about a
job. Also returns received HTTP headers.
If there was an unrecoverable error, throws an exception. On connection or
corruption errors, more attempts will be made; the number of attempts can
be altered by passing in :attempts. | [
"Get",
"lists",
"of",
"Manta",
"jobs",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L673-L700 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.gen_signed_url | def gen_signed_url(expires, method, path, args=[])
methods = method.is_a?(Array) ? method : [method]
raise ArgumentError unless (methods - [:get, :put, :post, :delete, :options]).empty?
raise ArgumentError unless path =~ OBJ_PATH_REGEX
key_id = '/%s/keys/%s' % [user_path, @fingerprint]
args.push([ 'expires', expires.to_i ])
args.push([ 'algorithm', @digest_name ])
args.push([ 'keyId', key_id ])
method = methods.map {|m| m.to_s.upcase }.sort.join(",")
host = URI.encode(@host.split('/').last)
path = URI.encode(path)
args.push(['method', method]) if methods.count > 1
encoded_args = args.sort.map do |key, val|
# to comply with RFC 3986
CGI.escape(key.to_s) + '=' + CGI.escape(val.to_s)
end.join('&')
plaintext = "#{method}\n#{host}\n#{path}\n#{encoded_args}"
signature = @priv_key.sign(@digest, plaintext)
encoded_signature = CGI.escape(Base64.strict_encode64(signature))
host + path + '?' + encoded_args + '&signature=' + encoded_signature
end | ruby | def gen_signed_url(expires, method, path, args=[])
methods = method.is_a?(Array) ? method : [method]
raise ArgumentError unless (methods - [:get, :put, :post, :delete, :options]).empty?
raise ArgumentError unless path =~ OBJ_PATH_REGEX
key_id = '/%s/keys/%s' % [user_path, @fingerprint]
args.push([ 'expires', expires.to_i ])
args.push([ 'algorithm', @digest_name ])
args.push([ 'keyId', key_id ])
method = methods.map {|m| m.to_s.upcase }.sort.join(",")
host = URI.encode(@host.split('/').last)
path = URI.encode(path)
args.push(['method', method]) if methods.count > 1
encoded_args = args.sort.map do |key, val|
# to comply with RFC 3986
CGI.escape(key.to_s) + '=' + CGI.escape(val.to_s)
end.join('&')
plaintext = "#{method}\n#{host}\n#{path}\n#{encoded_args}"
signature = @priv_key.sign(@digest, plaintext)
encoded_signature = CGI.escape(Base64.strict_encode64(signature))
host + path + '?' + encoded_args + '&signature=' + encoded_signature
end | [
"def",
"gen_signed_url",
"(",
"expires",
",",
"method",
",",
"path",
",",
"args",
"=",
"[",
"]",
")",
"methods",
"=",
"method",
".",
"is_a?",
"(",
"Array",
")",
"?",
"method",
":",
"[",
"method",
"]",
"raise",
"ArgumentError",
"unless",
"(",
"methods",
"-",
"[",
":get",
",",
":put",
",",
":post",
",",
":delete",
",",
":options",
"]",
")",
".",
"empty?",
"raise",
"ArgumentError",
"unless",
"path",
"=~",
"OBJ_PATH_REGEX",
"key_id",
"=",
"'/%s/keys/%s'",
"%",
"[",
"user_path",
",",
"@fingerprint",
"]",
"args",
".",
"push",
"(",
"[",
"'expires'",
",",
"expires",
".",
"to_i",
"]",
")",
"args",
".",
"push",
"(",
"[",
"'algorithm'",
",",
"@digest_name",
"]",
")",
"args",
".",
"push",
"(",
"[",
"'keyId'",
",",
"key_id",
"]",
")",
"method",
"=",
"methods",
".",
"map",
"{",
"|",
"m",
"|",
"m",
".",
"to_s",
".",
"upcase",
"}",
".",
"sort",
".",
"join",
"(",
"\",\"",
")",
"host",
"=",
"URI",
".",
"encode",
"(",
"@host",
".",
"split",
"(",
"'/'",
")",
".",
"last",
")",
"path",
"=",
"URI",
".",
"encode",
"(",
"path",
")",
"args",
".",
"push",
"(",
"[",
"'method'",
",",
"method",
"]",
")",
"if",
"methods",
".",
"count",
">",
"1",
"encoded_args",
"=",
"args",
".",
"sort",
".",
"map",
"do",
"|",
"key",
",",
"val",
"|",
"CGI",
".",
"escape",
"(",
"key",
".",
"to_s",
")",
"+",
"'='",
"+",
"CGI",
".",
"escape",
"(",
"val",
".",
"to_s",
")",
"end",
".",
"join",
"(",
"'&'",
")",
"plaintext",
"=",
"\"#{method}\\n#{host}\\n#{path}\\n#{encoded_args}\"",
"signature",
"=",
"@priv_key",
".",
"sign",
"(",
"@digest",
",",
"plaintext",
")",
"encoded_signature",
"=",
"CGI",
".",
"escape",
"(",
"Base64",
".",
"strict_encode64",
"(",
"signature",
")",
")",
"host",
"+",
"path",
"+",
"'?'",
"+",
"encoded_args",
"+",
"'&signature='",
"+",
"encoded_signature",
"end"
]
| Generates a signed URL which can be used by unauthenticated users to
make a request to Manta at the given path. This is typically used to GET
an object, or to make a CORS preflighted PUT request.
expires is a Time object or integer representing time after epoch; this
determines how long the signed URL will be valid for. The method is either a
single HTTP method (:get, :put, :post, :delete, :options) or a list of such
methods that the signed URL is allowed to be used for. The path must start
with /<user>/stor. Lastly, the optional args is an array containing pairs of
query args that will be appended at the end of the URL.
The returned URL is signed, and can be used either over HTTP or HTTPS until
it reaches the expiry date. | [
"Generates",
"a",
"signed",
"URL",
"which",
"can",
"be",
"used",
"by",
"unauthenticated",
"users",
"to",
"make",
"a",
"request",
"to",
"Manta",
"at",
"the",
"given",
"path",
".",
"This",
"is",
"typically",
"used",
"to",
"GET",
"an",
"object",
"or",
"to",
"make",
"a",
"CORS",
"preflighted",
"PUT",
"request",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L717-L744 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.get_job_state_streams | def get_job_state_streams(type, path, opts)
raise ArgumentError unless [:in, :out, :fail].include? type
url = job_url(path, '/live/' + type.to_s)
headers = gen_headers(opts)
attempt(opts[:attempts]) do
#method = opts[:head] ? :head : :get
method = :get # until added to Manta service
result = @client.send(method, url, nil, headers)
raise unless result.is_a? HTTP::Message
if result.status == 200
raise unless result.headers['Content-Type'] == 'text/plain'
return true, result.headers if method == :head
paths = result.body.split("\n")
return paths, result.headers
end
raise_error(result)
end
end | ruby | def get_job_state_streams(type, path, opts)
raise ArgumentError unless [:in, :out, :fail].include? type
url = job_url(path, '/live/' + type.to_s)
headers = gen_headers(opts)
attempt(opts[:attempts]) do
#method = opts[:head] ? :head : :get
method = :get # until added to Manta service
result = @client.send(method, url, nil, headers)
raise unless result.is_a? HTTP::Message
if result.status == 200
raise unless result.headers['Content-Type'] == 'text/plain'
return true, result.headers if method == :head
paths = result.body.split("\n")
return paths, result.headers
end
raise_error(result)
end
end | [
"def",
"get_job_state_streams",
"(",
"type",
",",
"path",
",",
"opts",
")",
"raise",
"ArgumentError",
"unless",
"[",
":in",
",",
":out",
",",
":fail",
"]",
".",
"include?",
"type",
"url",
"=",
"job_url",
"(",
"path",
",",
"'/live/'",
"+",
"type",
".",
"to_s",
")",
"headers",
"=",
"gen_headers",
"(",
"opts",
")",
"attempt",
"(",
"opts",
"[",
":attempts",
"]",
")",
"do",
"method",
"=",
":get",
"result",
"=",
"@client",
".",
"send",
"(",
"method",
",",
"url",
",",
"nil",
",",
"headers",
")",
"raise",
"unless",
"result",
".",
"is_a?",
"HTTP",
"::",
"Message",
"if",
"result",
".",
"status",
"==",
"200",
"raise",
"unless",
"result",
".",
"headers",
"[",
"'Content-Type'",
"]",
"==",
"'text/plain'",
"return",
"true",
",",
"result",
".",
"headers",
"if",
"method",
"==",
":head",
"paths",
"=",
"result",
".",
"body",
".",
"split",
"(",
"\"\\n\"",
")",
"return",
"paths",
",",
"result",
".",
"headers",
"end",
"raise_error",
"(",
"result",
")",
"end",
"end"
]
| Fetch lists of objects that have a given status.
type takes one of three values (:in, :out, fail), path must start with
/<user>/jobs/<job UUID> and point at an actual job.
Returns an array of object paths, along with received HTTP headers.
If there was an unrecoverable error, throws an exception. On connection or
corruption errors, more attempts will be made; the number of attempts can
be altered by passing in :attempts. | [
"Fetch",
"lists",
"of",
"objects",
"that",
"have",
"a",
"given",
"status",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L779-L800 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.job_url | def job_url(*args)
path = if args.size == 0
@job_base
else
raise ArgumentError unless args.first =~ JOB_PATH_REGEX
args.join('/')
end
URI.encode(@host + path)
end | ruby | def job_url(*args)
path = if args.size == 0
@job_base
else
raise ArgumentError unless args.first =~ JOB_PATH_REGEX
args.join('/')
end
URI.encode(@host + path)
end | [
"def",
"job_url",
"(",
"*",
"args",
")",
"path",
"=",
"if",
"args",
".",
"size",
"==",
"0",
"@job_base",
"else",
"raise",
"ArgumentError",
"unless",
"args",
".",
"first",
"=~",
"JOB_PATH_REGEX",
"args",
".",
"join",
"(",
"'/'",
")",
"end",
"URI",
".",
"encode",
"(",
"@host",
"+",
"path",
")",
"end"
]
| Returns a full URL for a given path to a job. | [
"Returns",
"a",
"full",
"URL",
"for",
"a",
"given",
"path",
"to",
"a",
"job",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L814-L823 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.gen_headers | def gen_headers(opts)
now = Time.now.httpdate
sig = gen_signature('date: ' + now)
headers = [[ 'Date', now ],
[ 'Authorization', sig ],
[ 'User-Agent', HTTP_AGENT ],
[ 'Accept-Version', '~1.0' ]]
# headers for conditional requests (dates)
for arg, conditional in [[:if_modified_since, 'If-Modified-Since' ],
[:if_unmodified_since, 'If-Unmodified-Since']]
date = opts[arg]
next unless date
date = Time.parse(date.to_s) unless date.kind_of? Time
headers.push([conditional, date])
end
# headers for conditional requests (etags)
for arg, conditional in [[:if_match, 'If-Match' ],
[:if_none_match, 'If-None-Match']]
etag = opts[arg]
next unless etag
raise ArgumentError unless etag.kind_of? String
headers.push([conditional, etag])
end
origin = opts[:origin]
if origin
raise ArgumentError unless origin == 'null' || origin =~ CORS_ORIGIN_REGEX
headers.push([ 'Origin', origin ])
end
custom_headers = opts.keys.select { |key| key.to_s.start_with? 'm_' }
unless custom_headers.empty?
headers += custom_headers.map do |header_key|
[ symbol_to_header(header_key), opts[header_key] ]
end
end
# add md5 hash when sending data
data = opts[:data]
if data
md5 = Digest::MD5.base64digest(data)
headers.push([ 'Content-MD5', md5 ])
end
return headers
end | ruby | def gen_headers(opts)
now = Time.now.httpdate
sig = gen_signature('date: ' + now)
headers = [[ 'Date', now ],
[ 'Authorization', sig ],
[ 'User-Agent', HTTP_AGENT ],
[ 'Accept-Version', '~1.0' ]]
# headers for conditional requests (dates)
for arg, conditional in [[:if_modified_since, 'If-Modified-Since' ],
[:if_unmodified_since, 'If-Unmodified-Since']]
date = opts[arg]
next unless date
date = Time.parse(date.to_s) unless date.kind_of? Time
headers.push([conditional, date])
end
# headers for conditional requests (etags)
for arg, conditional in [[:if_match, 'If-Match' ],
[:if_none_match, 'If-None-Match']]
etag = opts[arg]
next unless etag
raise ArgumentError unless etag.kind_of? String
headers.push([conditional, etag])
end
origin = opts[:origin]
if origin
raise ArgumentError unless origin == 'null' || origin =~ CORS_ORIGIN_REGEX
headers.push([ 'Origin', origin ])
end
custom_headers = opts.keys.select { |key| key.to_s.start_with? 'm_' }
unless custom_headers.empty?
headers += custom_headers.map do |header_key|
[ symbol_to_header(header_key), opts[header_key] ]
end
end
# add md5 hash when sending data
data = opts[:data]
if data
md5 = Digest::MD5.base64digest(data)
headers.push([ 'Content-MD5', md5 ])
end
return headers
end | [
"def",
"gen_headers",
"(",
"opts",
")",
"now",
"=",
"Time",
".",
"now",
".",
"httpdate",
"sig",
"=",
"gen_signature",
"(",
"'date: '",
"+",
"now",
")",
"headers",
"=",
"[",
"[",
"'Date'",
",",
"now",
"]",
",",
"[",
"'Authorization'",
",",
"sig",
"]",
",",
"[",
"'User-Agent'",
",",
"HTTP_AGENT",
"]",
",",
"[",
"'Accept-Version'",
",",
"'~1.0'",
"]",
"]",
"for",
"arg",
",",
"conditional",
"in",
"[",
"[",
":if_modified_since",
",",
"'If-Modified-Since'",
"]",
",",
"[",
":if_unmodified_since",
",",
"'If-Unmodified-Since'",
"]",
"]",
"date",
"=",
"opts",
"[",
"arg",
"]",
"next",
"unless",
"date",
"date",
"=",
"Time",
".",
"parse",
"(",
"date",
".",
"to_s",
")",
"unless",
"date",
".",
"kind_of?",
"Time",
"headers",
".",
"push",
"(",
"[",
"conditional",
",",
"date",
"]",
")",
"end",
"for",
"arg",
",",
"conditional",
"in",
"[",
"[",
":if_match",
",",
"'If-Match'",
"]",
",",
"[",
":if_none_match",
",",
"'If-None-Match'",
"]",
"]",
"etag",
"=",
"opts",
"[",
"arg",
"]",
"next",
"unless",
"etag",
"raise",
"ArgumentError",
"unless",
"etag",
".",
"kind_of?",
"String",
"headers",
".",
"push",
"(",
"[",
"conditional",
",",
"etag",
"]",
")",
"end",
"origin",
"=",
"opts",
"[",
":origin",
"]",
"if",
"origin",
"raise",
"ArgumentError",
"unless",
"origin",
"==",
"'null'",
"||",
"origin",
"=~",
"CORS_ORIGIN_REGEX",
"headers",
".",
"push",
"(",
"[",
"'Origin'",
",",
"origin",
"]",
")",
"end",
"custom_headers",
"=",
"opts",
".",
"keys",
".",
"select",
"{",
"|",
"key",
"|",
"key",
".",
"to_s",
".",
"start_with?",
"'m_'",
"}",
"unless",
"custom_headers",
".",
"empty?",
"headers",
"+=",
"custom_headers",
".",
"map",
"do",
"|",
"header_key",
"|",
"[",
"symbol_to_header",
"(",
"header_key",
")",
",",
"opts",
"[",
"header_key",
"]",
"]",
"end",
"end",
"data",
"=",
"opts",
"[",
":data",
"]",
"if",
"data",
"md5",
"=",
"Digest",
"::",
"MD5",
".",
"base64digest",
"(",
"data",
")",
"headers",
".",
"push",
"(",
"[",
"'Content-MD5'",
",",
"md5",
"]",
")",
"end",
"return",
"headers",
"end"
]
| Creates headers to be given to the HTTP client and sent to the Manta
service. The most important is the Authorization header, without which
none of this class would work. | [
"Creates",
"headers",
"to",
"be",
"given",
"to",
"the",
"HTTP",
"client",
"and",
"sent",
"to",
"the",
"Manta",
"service",
".",
"The",
"most",
"important",
"is",
"the",
"Authorization",
"header",
"without",
"which",
"none",
"of",
"this",
"class",
"would",
"work",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L863-L914 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.gen_cors_headers | def gen_cors_headers(opts)
headers = []
allow_credentials = opts[:access_control_allow_credentials]
if allow_credentials
allow_credentials = allow_credentials.to_s
raise ArgumentError unless allow_credentials == 'true' ||
allow_credentials == 'false'
headers.push([ 'Access-Control-Allow-Credentials', allow_credentials ])
end
allow_headers = opts[:access_control_allow_headers]
if allow_headers
raise ArgumentError unless allow_headers =~ CORS_HEADERS_REGEX
allow_headers = allow_headers.split(', ').map(&:downcase).sort.join(', ')
headers.push([ 'Access-Control-Allow-Headers', allow_headers ])
end
allow_methods = opts[:access_control_allow_methods]
if allow_methods
raise ArgumentError unless allow_methods.kind_of? String
unknown_methods = allow_methods.split(', ').reject do |str|
CORS_METHODS.include? str
end
raise ArgumentError unless unknown_methods.size == 0
headers.push([ 'Access-Control-Allow-Methods', allow_methods ])
end
allow_origin = opts[:access_control_allow_origin]
if allow_origin
raise ArgumentError unless allow_origin.kind_of? String
raise ArgumentError unless allow_origin == '*' ||
allow_origin == 'null' ||
allow_origin =~ CORS_ORIGIN_REGEX
headers.push([ 'Access-Control-Allow-Origin', allow_origin ])
end
expose_headers = opts[:access_control_expose_headers]
if expose_headers
raise ArgumentError unless expose_headers =~ CORS_HEADERS_REGEX
expose_headers = expose_headers.split(', ').map(&:downcase).sort.join(', ')
headers.push([ 'Access-Control-Expose-Headers', expose_headers ])
end
max_age = opts[:access_control_max_age]
if max_age
raise ArgumentError unless max_age.kind_of?(Integer) && max_age >= 0
headers.push([ 'Access-Control-Max-Age', max_age.to_s ])
end
headers
end | ruby | def gen_cors_headers(opts)
headers = []
allow_credentials = opts[:access_control_allow_credentials]
if allow_credentials
allow_credentials = allow_credentials.to_s
raise ArgumentError unless allow_credentials == 'true' ||
allow_credentials == 'false'
headers.push([ 'Access-Control-Allow-Credentials', allow_credentials ])
end
allow_headers = opts[:access_control_allow_headers]
if allow_headers
raise ArgumentError unless allow_headers =~ CORS_HEADERS_REGEX
allow_headers = allow_headers.split(', ').map(&:downcase).sort.join(', ')
headers.push([ 'Access-Control-Allow-Headers', allow_headers ])
end
allow_methods = opts[:access_control_allow_methods]
if allow_methods
raise ArgumentError unless allow_methods.kind_of? String
unknown_methods = allow_methods.split(', ').reject do |str|
CORS_METHODS.include? str
end
raise ArgumentError unless unknown_methods.size == 0
headers.push([ 'Access-Control-Allow-Methods', allow_methods ])
end
allow_origin = opts[:access_control_allow_origin]
if allow_origin
raise ArgumentError unless allow_origin.kind_of? String
raise ArgumentError unless allow_origin == '*' ||
allow_origin == 'null' ||
allow_origin =~ CORS_ORIGIN_REGEX
headers.push([ 'Access-Control-Allow-Origin', allow_origin ])
end
expose_headers = opts[:access_control_expose_headers]
if expose_headers
raise ArgumentError unless expose_headers =~ CORS_HEADERS_REGEX
expose_headers = expose_headers.split(', ').map(&:downcase).sort.join(', ')
headers.push([ 'Access-Control-Expose-Headers', expose_headers ])
end
max_age = opts[:access_control_max_age]
if max_age
raise ArgumentError unless max_age.kind_of?(Integer) && max_age >= 0
headers.push([ 'Access-Control-Max-Age', max_age.to_s ])
end
headers
end | [
"def",
"gen_cors_headers",
"(",
"opts",
")",
"headers",
"=",
"[",
"]",
"allow_credentials",
"=",
"opts",
"[",
":access_control_allow_credentials",
"]",
"if",
"allow_credentials",
"allow_credentials",
"=",
"allow_credentials",
".",
"to_s",
"raise",
"ArgumentError",
"unless",
"allow_credentials",
"==",
"'true'",
"||",
"allow_credentials",
"==",
"'false'",
"headers",
".",
"push",
"(",
"[",
"'Access-Control-Allow-Credentials'",
",",
"allow_credentials",
"]",
")",
"end",
"allow_headers",
"=",
"opts",
"[",
":access_control_allow_headers",
"]",
"if",
"allow_headers",
"raise",
"ArgumentError",
"unless",
"allow_headers",
"=~",
"CORS_HEADERS_REGEX",
"allow_headers",
"=",
"allow_headers",
".",
"split",
"(",
"', '",
")",
".",
"map",
"(",
"&",
":downcase",
")",
".",
"sort",
".",
"join",
"(",
"', '",
")",
"headers",
".",
"push",
"(",
"[",
"'Access-Control-Allow-Headers'",
",",
"allow_headers",
"]",
")",
"end",
"allow_methods",
"=",
"opts",
"[",
":access_control_allow_methods",
"]",
"if",
"allow_methods",
"raise",
"ArgumentError",
"unless",
"allow_methods",
".",
"kind_of?",
"String",
"unknown_methods",
"=",
"allow_methods",
".",
"split",
"(",
"', '",
")",
".",
"reject",
"do",
"|",
"str",
"|",
"CORS_METHODS",
".",
"include?",
"str",
"end",
"raise",
"ArgumentError",
"unless",
"unknown_methods",
".",
"size",
"==",
"0",
"headers",
".",
"push",
"(",
"[",
"'Access-Control-Allow-Methods'",
",",
"allow_methods",
"]",
")",
"end",
"allow_origin",
"=",
"opts",
"[",
":access_control_allow_origin",
"]",
"if",
"allow_origin",
"raise",
"ArgumentError",
"unless",
"allow_origin",
".",
"kind_of?",
"String",
"raise",
"ArgumentError",
"unless",
"allow_origin",
"==",
"'*'",
"||",
"allow_origin",
"==",
"'null'",
"||",
"allow_origin",
"=~",
"CORS_ORIGIN_REGEX",
"headers",
".",
"push",
"(",
"[",
"'Access-Control-Allow-Origin'",
",",
"allow_origin",
"]",
")",
"end",
"expose_headers",
"=",
"opts",
"[",
":access_control_expose_headers",
"]",
"if",
"expose_headers",
"raise",
"ArgumentError",
"unless",
"expose_headers",
"=~",
"CORS_HEADERS_REGEX",
"expose_headers",
"=",
"expose_headers",
".",
"split",
"(",
"', '",
")",
".",
"map",
"(",
"&",
":downcase",
")",
".",
"sort",
".",
"join",
"(",
"', '",
")",
"headers",
".",
"push",
"(",
"[",
"'Access-Control-Expose-Headers'",
",",
"expose_headers",
"]",
")",
"end",
"max_age",
"=",
"opts",
"[",
":access_control_max_age",
"]",
"if",
"max_age",
"raise",
"ArgumentError",
"unless",
"max_age",
".",
"kind_of?",
"(",
"Integer",
")",
"&&",
"max_age",
">=",
"0",
"headers",
".",
"push",
"(",
"[",
"'Access-Control-Max-Age'",
",",
"max_age",
".",
"to_s",
"]",
")",
"end",
"headers",
"end"
]
| Do some sanity checks and create CORS-related headers
For more details, see http://www.w3.org/TR/cors/ and
https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Expose-Headers | [
"Do",
"some",
"sanity",
"checks",
"and",
"create",
"CORS",
"-",
"related",
"headers"
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L922-L975 | train |
joyent/ruby-manta | lib/ruby-manta/manta_client.rb | RubyManta.MantaClient.gen_signature | def gen_signature(data)
raise ArgumentError unless data
sig = @priv_key.sign(@digest, data)
base64sig = Base64.strict_encode64(sig)
return HTTP_SIGNATURE % [user_path, @fingerprint, @digest_name, base64sig]
end | ruby | def gen_signature(data)
raise ArgumentError unless data
sig = @priv_key.sign(@digest, data)
base64sig = Base64.strict_encode64(sig)
return HTTP_SIGNATURE % [user_path, @fingerprint, @digest_name, base64sig]
end | [
"def",
"gen_signature",
"(",
"data",
")",
"raise",
"ArgumentError",
"unless",
"data",
"sig",
"=",
"@priv_key",
".",
"sign",
"(",
"@digest",
",",
"data",
")",
"base64sig",
"=",
"Base64",
".",
"strict_encode64",
"(",
"sig",
")",
"return",
"HTTP_SIGNATURE",
"%",
"[",
"user_path",
",",
"@fingerprint",
",",
"@digest_name",
",",
"base64sig",
"]",
"end"
]
| Given a chunk of data, creates an HTTP signature which the Manta service
understands and uses for authentication. | [
"Given",
"a",
"chunk",
"of",
"data",
"creates",
"an",
"HTTP",
"signature",
"which",
"the",
"Manta",
"service",
"understands",
"and",
"uses",
"for",
"authentication",
"."
]
| 56fc959a6c0143a17a379cc27404b59f996f1f2d | https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L979-L986 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/authors_controller.rb | Phcscriptcdn.Script::AuthorsController.show | def show
@script_authors = Script::Author.friendly.find(params[:id])
@versions = Phcscriptcdn::AuthorVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Author')
end | ruby | def show
@script_authors = Script::Author.friendly.find(params[:id])
@versions = Phcscriptcdn::AuthorVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Author')
end | [
"def",
"show",
"@script_authors",
"=",
"Script",
"::",
"Author",
".",
"friendly",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"@versions",
"=",
"Phcscriptcdn",
"::",
"AuthorVersions",
".",
"where",
"(",
"item_id",
":",
"params",
"[",
":id",
"]",
",",
"item_type",
":",
"'Phcscriptcdn::Script::Author'",
")",
"end"
]
| DETAILS - Script Author | [
"DETAILS",
"-",
"Script",
"Author"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/authors_controller.rb#L18-L21 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/authors_controller.rb | Phcscriptcdn.Script::AuthorsController.new | def new
@script_author = Script::Author.new
@script_author.user_id = current_user.id
@script_author.org_id = current_user.org_id
end | ruby | def new
@script_author = Script::Author.new
@script_author.user_id = current_user.id
@script_author.org_id = current_user.org_id
end | [
"def",
"new",
"@script_author",
"=",
"Script",
"::",
"Author",
".",
"new",
"@script_author",
".",
"user_id",
"=",
"current_user",
".",
"id",
"@script_author",
".",
"org_id",
"=",
"current_user",
".",
"org_id",
"end"
]
| NEW - Script Author | [
"NEW",
"-",
"Script",
"Author"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/authors_controller.rb#L24-L28 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/authors_controller.rb | Phcscriptcdn.Script::AuthorsController.create | def create
@script_author = Script::Author.new(script_author_params)
@script_author.user_id = current_user.id
@script_author.org_id = current_user.org_id
if @script_author.save
redirect_to script_authors_url, notice: 'Author was successfully created.'
else
render :new
end
end | ruby | def create
@script_author = Script::Author.new(script_author_params)
@script_author.user_id = current_user.id
@script_author.org_id = current_user.org_id
if @script_author.save
redirect_to script_authors_url, notice: 'Author was successfully created.'
else
render :new
end
end | [
"def",
"create",
"@script_author",
"=",
"Script",
"::",
"Author",
".",
"new",
"(",
"script_author_params",
")",
"@script_author",
".",
"user_id",
"=",
"current_user",
".",
"id",
"@script_author",
".",
"org_id",
"=",
"current_user",
".",
"org_id",
"if",
"@script_author",
".",
"save",
"redirect_to",
"script_authors_url",
",",
"notice",
":",
"'Author was successfully created.'",
"else",
"render",
":new",
"end",
"end"
]
| CREATE - Script Author | [
"CREATE",
"-",
"Script",
"Author"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/authors_controller.rb#L35-L44 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/extensions_controller.rb | Phcscriptcdn.Script::ExtensionsController.show | def show
@script_extensions = Script::Extension.friendly.find(params[:id])
@versions = Phcscriptcdn::ExtensionVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Extension')
end | ruby | def show
@script_extensions = Script::Extension.friendly.find(params[:id])
@versions = Phcscriptcdn::ExtensionVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Extension')
end | [
"def",
"show",
"@script_extensions",
"=",
"Script",
"::",
"Extension",
".",
"friendly",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"@versions",
"=",
"Phcscriptcdn",
"::",
"ExtensionVersions",
".",
"where",
"(",
"item_id",
":",
"params",
"[",
":id",
"]",
",",
"item_type",
":",
"'Phcscriptcdn::Script::Extension'",
")",
"end"
]
| DETAILS - Script Extension | [
"DETAILS",
"-",
"Script",
"Extension"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/extensions_controller.rb#L18-L21 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/extensions_controller.rb | Phcscriptcdn.Script::ExtensionsController.new | def new
@script_extension = Script::Extension.new
@script_extension.user_id = current_user.id
@script_extension.org_id = current_user.org_id
end | ruby | def new
@script_extension = Script::Extension.new
@script_extension.user_id = current_user.id
@script_extension.org_id = current_user.org_id
end | [
"def",
"new",
"@script_extension",
"=",
"Script",
"::",
"Extension",
".",
"new",
"@script_extension",
".",
"user_id",
"=",
"current_user",
".",
"id",
"@script_extension",
".",
"org_id",
"=",
"current_user",
".",
"org_id",
"end"
]
| NEW - Script Extension | [
"NEW",
"-",
"Script",
"Extension"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/extensions_controller.rb#L24-L28 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/extensions_controller.rb | Phcscriptcdn.Script::ExtensionsController.create | def create
@script_extension = Script::Extension.new(script_extension_params)
@script_extension.user_id = current_user.id
@script_extension.org_id = current_user.org_id
if @script_extension.save
redirect_to script_extensions_url, notice: 'Extension was successfully created.'
else
render :new
end
end | ruby | def create
@script_extension = Script::Extension.new(script_extension_params)
@script_extension.user_id = current_user.id
@script_extension.org_id = current_user.org_id
if @script_extension.save
redirect_to script_extensions_url, notice: 'Extension was successfully created.'
else
render :new
end
end | [
"def",
"create",
"@script_extension",
"=",
"Script",
"::",
"Extension",
".",
"new",
"(",
"script_extension_params",
")",
"@script_extension",
".",
"user_id",
"=",
"current_user",
".",
"id",
"@script_extension",
".",
"org_id",
"=",
"current_user",
".",
"org_id",
"if",
"@script_extension",
".",
"save",
"redirect_to",
"script_extensions_url",
",",
"notice",
":",
"'Extension was successfully created.'",
"else",
"render",
":new",
"end",
"end"
]
| CREATE - Script Extension | [
"CREATE",
"-",
"Script",
"Extension"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/extensions_controller.rb#L35-L44 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/licences_controller.rb | Phcscriptcdn.Script::LicencesController.show | def show
@script_licences = Script::Licence.friendly.find(params[:id])
@versions = Phcscriptcdn::LicenceVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Licence')
end | ruby | def show
@script_licences = Script::Licence.friendly.find(params[:id])
@versions = Phcscriptcdn::LicenceVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Licence')
end | [
"def",
"show",
"@script_licences",
"=",
"Script",
"::",
"Licence",
".",
"friendly",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"@versions",
"=",
"Phcscriptcdn",
"::",
"LicenceVersions",
".",
"where",
"(",
"item_id",
":",
"params",
"[",
":id",
"]",
",",
"item_type",
":",
"'Phcscriptcdn::Script::Licence'",
")",
"end"
]
| DETAILS - Script Licences | [
"DETAILS",
"-",
"Script",
"Licences"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/licences_controller.rb#L18-L21 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/licences_controller.rb | Phcscriptcdn.Script::LicencesController.new | def new
@script_licence = Script::Licence.new
@script_licence.user_id = current_user.id
@script_licence.org_id = current_user.org_id
end | ruby | def new
@script_licence = Script::Licence.new
@script_licence.user_id = current_user.id
@script_licence.org_id = current_user.org_id
end | [
"def",
"new",
"@script_licence",
"=",
"Script",
"::",
"Licence",
".",
"new",
"@script_licence",
".",
"user_id",
"=",
"current_user",
".",
"id",
"@script_licence",
".",
"org_id",
"=",
"current_user",
".",
"org_id",
"end"
]
| NEW - Script Licences | [
"NEW",
"-",
"Script",
"Licences"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/licences_controller.rb#L24-L28 | train |
phcdevworks/phc-scriptcdn | app/controllers/phcscriptcdn/script/licences_controller.rb | Phcscriptcdn.Script::LicencesController.create | def create
@script_licence = Script::Licence.new(script_licence_params)
@script_licence.user_id = current_user.id
@script_licence.org_id = current_user.org_id
if @script_licence.save
redirect_to script_licences_url, notice: 'Licence was successfully created.'
else
render :new
end
end | ruby | def create
@script_licence = Script::Licence.new(script_licence_params)
@script_licence.user_id = current_user.id
@script_licence.org_id = current_user.org_id
if @script_licence.save
redirect_to script_licences_url, notice: 'Licence was successfully created.'
else
render :new
end
end | [
"def",
"create",
"@script_licence",
"=",
"Script",
"::",
"Licence",
".",
"new",
"(",
"script_licence_params",
")",
"@script_licence",
".",
"user_id",
"=",
"current_user",
".",
"id",
"@script_licence",
".",
"org_id",
"=",
"current_user",
".",
"org_id",
"if",
"@script_licence",
".",
"save",
"redirect_to",
"script_licences_url",
",",
"notice",
":",
"'Licence was successfully created.'",
"else",
"render",
":new",
"end",
"end"
]
| POST - Script Licences | [
"POST",
"-",
"Script",
"Licences"
]
| 5679f9ae4da5e88d7173ddae0192a36d4b91d80f | https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/licences_controller.rb#L35-L44 | train |
kostyantyn/hydra_attribute | lib/hydra_attribute/hydra_value.rb | HydraAttribute.HydraValue.save | def save
raise EntityModelIsNotPersistedError unless entity.persisted?
if persisted?
return false unless changed?
update
else
create
end
@previously_changed = changes
@changed_attributes.clear
true
end | ruby | def save
raise EntityModelIsNotPersistedError unless entity.persisted?
if persisted?
return false unless changed?
update
else
create
end
@previously_changed = changes
@changed_attributes.clear
true
end | [
"def",
"save",
"raise",
"EntityModelIsNotPersistedError",
"unless",
"entity",
".",
"persisted?",
"if",
"persisted?",
"return",
"false",
"unless",
"changed?",
"update",
"else",
"create",
"end",
"@previously_changed",
"=",
"changes",
"@changed_attributes",
".",
"clear",
"true",
"end"
]
| Saves model
Performs +insert+ or +update+ sql query
Method doesn't perform sql query if model isn't modified
@return [TrueClass, FalseClass] | [
"Saves",
"model",
"Performs",
"+",
"insert",
"+",
"or",
"+",
"update",
"+",
"sql",
"query",
"Method",
"doesn",
"t",
"perform",
"sql",
"query",
"if",
"model",
"isn",
"t",
"modified"
]
| 64ba3ccb5c0d6cec6276a6a01734389b8f695572 | https://github.com/kostyantyn/hydra_attribute/blob/64ba3ccb5c0d6cec6276a6a01734389b8f695572/lib/hydra_attribute/hydra_value.rb#L156-L170 | train |
kostyantyn/hydra_attribute | lib/hydra_attribute/hydra_value.rb | HydraAttribute.HydraValue.arel_insert | def arel_insert
table = self.class.arel_tables[entity.class.table_name][hydra_attribute.backend_type]
fields = {}
fields[table[:entity_id]] = entity.id
fields[table[:hydra_attribute_id]] = hydra_attribute.id
fields[table[:value]] = value
fields[table[:created_at]] = Time.now
fields[table[:updated_at]] = Time.now
table.compile_insert(fields)
end | ruby | def arel_insert
table = self.class.arel_tables[entity.class.table_name][hydra_attribute.backend_type]
fields = {}
fields[table[:entity_id]] = entity.id
fields[table[:hydra_attribute_id]] = hydra_attribute.id
fields[table[:value]] = value
fields[table[:created_at]] = Time.now
fields[table[:updated_at]] = Time.now
table.compile_insert(fields)
end | [
"def",
"arel_insert",
"table",
"=",
"self",
".",
"class",
".",
"arel_tables",
"[",
"entity",
".",
"class",
".",
"table_name",
"]",
"[",
"hydra_attribute",
".",
"backend_type",
"]",
"fields",
"=",
"{",
"}",
"fields",
"[",
"table",
"[",
":entity_id",
"]",
"]",
"=",
"entity",
".",
"id",
"fields",
"[",
"table",
"[",
":hydra_attribute_id",
"]",
"]",
"=",
"hydra_attribute",
".",
"id",
"fields",
"[",
"table",
"[",
":value",
"]",
"]",
"=",
"value",
"fields",
"[",
"table",
"[",
":created_at",
"]",
"]",
"=",
"Time",
".",
"now",
"fields",
"[",
"table",
"[",
":updated_at",
"]",
"]",
"=",
"Time",
".",
"now",
"table",
".",
"compile_insert",
"(",
"fields",
")",
"end"
]
| Creates arel insert manager
@return [Arel::InsertManager] | [
"Creates",
"arel",
"insert",
"manager"
]
| 64ba3ccb5c0d6cec6276a6a01734389b8f695572 | https://github.com/kostyantyn/hydra_attribute/blob/64ba3ccb5c0d6cec6276a6a01734389b8f695572/lib/hydra_attribute/hydra_value.rb#L176-L185 | train |
kostyantyn/hydra_attribute | lib/hydra_attribute/hydra_value.rb | HydraAttribute.HydraValue.arel_update | def arel_update
table = self.class.arel_tables[entity.class.table_name][hydra_attribute.backend_type]
arel = table.from(table)
arel.where(table[:id].eq(id)).compile_update(table[:value] => value, table[:updated_at] => Time.now)
end | ruby | def arel_update
table = self.class.arel_tables[entity.class.table_name][hydra_attribute.backend_type]
arel = table.from(table)
arel.where(table[:id].eq(id)).compile_update(table[:value] => value, table[:updated_at] => Time.now)
end | [
"def",
"arel_update",
"table",
"=",
"self",
".",
"class",
".",
"arel_tables",
"[",
"entity",
".",
"class",
".",
"table_name",
"]",
"[",
"hydra_attribute",
".",
"backend_type",
"]",
"arel",
"=",
"table",
".",
"from",
"(",
"table",
")",
"arel",
".",
"where",
"(",
"table",
"[",
":id",
"]",
".",
"eq",
"(",
"id",
")",
")",
".",
"compile_update",
"(",
"table",
"[",
":value",
"]",
"=>",
"value",
",",
"table",
"[",
":updated_at",
"]",
"=>",
"Time",
".",
"now",
")",
"end"
]
| Creates arel update manager
@return [Arel::UpdateManager] | [
"Creates",
"arel",
"update",
"manager"
]
| 64ba3ccb5c0d6cec6276a6a01734389b8f695572 | https://github.com/kostyantyn/hydra_attribute/blob/64ba3ccb5c0d6cec6276a6a01734389b8f695572/lib/hydra_attribute/hydra_value.rb#L190-L194 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/search_index.rb | ActsAsIndexed.SearchIndex.add_records | def add_records(records)
atoms = ActiveSupport::OrderedHash.new
records_count = 0
records.each do |record|
next unless allow_indexing?(record)
records_count += 1
condensed_record = condense_record(record)
atoms = add_occurences(condensed_record, record.id, atoms)
end
@storage.add(atoms, records_count)
end | ruby | def add_records(records)
atoms = ActiveSupport::OrderedHash.new
records_count = 0
records.each do |record|
next unless allow_indexing?(record)
records_count += 1
condensed_record = condense_record(record)
atoms = add_occurences(condensed_record, record.id, atoms)
end
@storage.add(atoms, records_count)
end | [
"def",
"add_records",
"(",
"records",
")",
"atoms",
"=",
"ActiveSupport",
"::",
"OrderedHash",
".",
"new",
"records_count",
"=",
"0",
"records",
".",
"each",
"do",
"|",
"record",
"|",
"next",
"unless",
"allow_indexing?",
"(",
"record",
")",
"records_count",
"+=",
"1",
"condensed_record",
"=",
"condense_record",
"(",
"record",
")",
"atoms",
"=",
"add_occurences",
"(",
"condensed_record",
",",
"record",
".",
"id",
",",
"atoms",
")",
"end",
"@storage",
".",
"add",
"(",
"atoms",
",",
"records_count",
")",
"end"
]
| Adds multiple records to the index. Accepts an array of +records+. | [
"Adds",
"multiple",
"records",
"to",
"the",
"index",
".",
"Accepts",
"an",
"array",
"of",
"+",
"records",
"+",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_index.rb#L27-L40 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/search_index.rb | ActsAsIndexed.SearchIndex.remove_record | def remove_record(record)
condensed_record = condense_record(record)
atoms = add_occurences(condensed_record,record.id)
@storage.remove(atoms)
end | ruby | def remove_record(record)
condensed_record = condense_record(record)
atoms = add_occurences(condensed_record,record.id)
@storage.remove(atoms)
end | [
"def",
"remove_record",
"(",
"record",
")",
"condensed_record",
"=",
"condense_record",
"(",
"record",
")",
"atoms",
"=",
"add_occurences",
"(",
"condensed_record",
",",
"record",
".",
"id",
")",
"@storage",
".",
"remove",
"(",
"atoms",
")",
"end"
]
| Removes +record+ from the index. | [
"Removes",
"+",
"record",
"+",
"from",
"the",
"index",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_index.rb#L43-L48 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/search_index.rb | ActsAsIndexed.SearchIndex.search | def search(query)
return [] if query.nil?
@atoms = @storage.fetch(cleanup_atoms(query), query[/\^/])
queries = parse_query(query.dup)
positive = run_queries(queries[:positive])
positive_quoted = run_quoted_queries(queries[:positive_quoted])
negative = run_queries(queries[:negative])
negative_quoted = run_quoted_queries(queries[:negative_quoted])
starts_with = run_queries(queries[:starts_with], true)
start_quoted = run_quoted_queries(queries[:start_quoted], true)
results = ActiveSupport::OrderedHash.new
if queries[:start_quoted].any?
results = merge_query_results(results, start_quoted)
end
if queries[:starts_with].any?
results = merge_query_results(results, starts_with)
end
if queries[:positive_quoted].any?
results = merge_query_results(results, positive_quoted)
end
if queries[:positive].any?
results = merge_query_results(results, positive)
end
negative_results = (negative.keys + negative_quoted.keys)
results.delete_if { |r_id, w| negative_results.include?(r_id) }
results
end | ruby | def search(query)
return [] if query.nil?
@atoms = @storage.fetch(cleanup_atoms(query), query[/\^/])
queries = parse_query(query.dup)
positive = run_queries(queries[:positive])
positive_quoted = run_quoted_queries(queries[:positive_quoted])
negative = run_queries(queries[:negative])
negative_quoted = run_quoted_queries(queries[:negative_quoted])
starts_with = run_queries(queries[:starts_with], true)
start_quoted = run_quoted_queries(queries[:start_quoted], true)
results = ActiveSupport::OrderedHash.new
if queries[:start_quoted].any?
results = merge_query_results(results, start_quoted)
end
if queries[:starts_with].any?
results = merge_query_results(results, starts_with)
end
if queries[:positive_quoted].any?
results = merge_query_results(results, positive_quoted)
end
if queries[:positive].any?
results = merge_query_results(results, positive)
end
negative_results = (negative.keys + negative_quoted.keys)
results.delete_if { |r_id, w| negative_results.include?(r_id) }
results
end | [
"def",
"search",
"(",
"query",
")",
"return",
"[",
"]",
"if",
"query",
".",
"nil?",
"@atoms",
"=",
"@storage",
".",
"fetch",
"(",
"cleanup_atoms",
"(",
"query",
")",
",",
"query",
"[",
"/",
"\\^",
"/",
"]",
")",
"queries",
"=",
"parse_query",
"(",
"query",
".",
"dup",
")",
"positive",
"=",
"run_queries",
"(",
"queries",
"[",
":positive",
"]",
")",
"positive_quoted",
"=",
"run_quoted_queries",
"(",
"queries",
"[",
":positive_quoted",
"]",
")",
"negative",
"=",
"run_queries",
"(",
"queries",
"[",
":negative",
"]",
")",
"negative_quoted",
"=",
"run_quoted_queries",
"(",
"queries",
"[",
":negative_quoted",
"]",
")",
"starts_with",
"=",
"run_queries",
"(",
"queries",
"[",
":starts_with",
"]",
",",
"true",
")",
"start_quoted",
"=",
"run_quoted_queries",
"(",
"queries",
"[",
":start_quoted",
"]",
",",
"true",
")",
"results",
"=",
"ActiveSupport",
"::",
"OrderedHash",
".",
"new",
"if",
"queries",
"[",
":start_quoted",
"]",
".",
"any?",
"results",
"=",
"merge_query_results",
"(",
"results",
",",
"start_quoted",
")",
"end",
"if",
"queries",
"[",
":starts_with",
"]",
".",
"any?",
"results",
"=",
"merge_query_results",
"(",
"results",
",",
"starts_with",
")",
"end",
"if",
"queries",
"[",
":positive_quoted",
"]",
".",
"any?",
"results",
"=",
"merge_query_results",
"(",
"results",
",",
"positive_quoted",
")",
"end",
"if",
"queries",
"[",
":positive",
"]",
".",
"any?",
"results",
"=",
"merge_query_results",
"(",
"results",
",",
"positive",
")",
"end",
"negative_results",
"=",
"(",
"negative",
".",
"keys",
"+",
"negative_quoted",
".",
"keys",
")",
"results",
".",
"delete_if",
"{",
"|",
"r_id",
",",
"w",
"|",
"negative_results",
".",
"include?",
"(",
"r_id",
")",
"}",
"results",
"end"
]
| Returns an array of IDs for records matching +query+. | [
"Returns",
"an",
"array",
"of",
"IDs",
"for",
"records",
"matching",
"+",
"query",
"+",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_index.rb#L63-L96 | train |
dougal/acts_as_indexed | lib/acts_as_indexed/search_index.rb | ActsAsIndexed.SearchIndex.record_unchanged? | def record_unchanged?(record_new, record_old)
# NOTE: Using the dirty state would be great here, but it doesn't keep track of
# in-place changes.
allow_indexing?(record_old) == allow_indexing?(record_new) &&
[email protected] { |field| record_old.send(field) == record_new.send(field) }.include?(false)
end | ruby | def record_unchanged?(record_new, record_old)
# NOTE: Using the dirty state would be great here, but it doesn't keep track of
# in-place changes.
allow_indexing?(record_old) == allow_indexing?(record_new) &&
[email protected] { |field| record_old.send(field) == record_new.send(field) }.include?(false)
end | [
"def",
"record_unchanged?",
"(",
"record_new",
",",
"record_old",
")",
"allow_indexing?",
"(",
"record_old",
")",
"==",
"allow_indexing?",
"(",
"record_new",
")",
"&&",
"!",
"@fields",
".",
"map",
"{",
"|",
"field",
"|",
"record_old",
".",
"send",
"(",
"field",
")",
"==",
"record_new",
".",
"send",
"(",
"field",
")",
"}",
".",
"include?",
"(",
"false",
")",
"end"
]
| The record is unchanged for our purposes if all the fields are the same
and the if_proc returns the same result for both. | [
"The",
"record",
"is",
"unchanged",
"for",
"our",
"purposes",
"if",
"all",
"the",
"fields",
"are",
"the",
"same",
"and",
"the",
"if_proc",
"returns",
"the",
"same",
"result",
"for",
"both",
"."
]
| 172dac7899b31857a6513786355b7c4a9bb75093 | https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_index.rb#L102-L108 | train |
threez/ruby-vmstat | lib/vmstat/procfs.rb | Vmstat.ProcFS.memory | def memory
@pagesize ||= Vmstat.pagesize
has_available = false
total = free = active = inactive = pageins = pageouts = available = 0
procfs_file("meminfo") do |file|
content = file.read(2048) # the requested information is in the first bytes
content.scan(/(\w+):\s+(\d+) kB/) do |name, kbytes|
pages = (kbytes.to_i * 1024) / @pagesize
case name
when "MemTotal" then total = pages
when "MemFree" then free = pages
when "MemAvailable"
available = pages
has_available = true
when "Active" then active = pages
when "Inactive" then inactive = pages
end
end
end
procfs_file("vmstat") do |file|
content = file.read
if content =~ /pgpgin\s+(\d+)/
pageins = $1.to_i
end
if content =~ /pgpgout\s+(\d+)/
pageouts = $1.to_i
end
end
mem_klass = has_available ? LinuxMemory : Memory
mem_klass.new(@pagesize, total-free-active-inactive, active,
inactive, free, pageins, pageouts).tap do |mem|
mem.available = available if has_available
end
end | ruby | def memory
@pagesize ||= Vmstat.pagesize
has_available = false
total = free = active = inactive = pageins = pageouts = available = 0
procfs_file("meminfo") do |file|
content = file.read(2048) # the requested information is in the first bytes
content.scan(/(\w+):\s+(\d+) kB/) do |name, kbytes|
pages = (kbytes.to_i * 1024) / @pagesize
case name
when "MemTotal" then total = pages
when "MemFree" then free = pages
when "MemAvailable"
available = pages
has_available = true
when "Active" then active = pages
when "Inactive" then inactive = pages
end
end
end
procfs_file("vmstat") do |file|
content = file.read
if content =~ /pgpgin\s+(\d+)/
pageins = $1.to_i
end
if content =~ /pgpgout\s+(\d+)/
pageouts = $1.to_i
end
end
mem_klass = has_available ? LinuxMemory : Memory
mem_klass.new(@pagesize, total-free-active-inactive, active,
inactive, free, pageins, pageouts).tap do |mem|
mem.available = available if has_available
end
end | [
"def",
"memory",
"@pagesize",
"||=",
"Vmstat",
".",
"pagesize",
"has_available",
"=",
"false",
"total",
"=",
"free",
"=",
"active",
"=",
"inactive",
"=",
"pageins",
"=",
"pageouts",
"=",
"available",
"=",
"0",
"procfs_file",
"(",
"\"meminfo\"",
")",
"do",
"|",
"file",
"|",
"content",
"=",
"file",
".",
"read",
"(",
"2048",
")",
"content",
".",
"scan",
"(",
"/",
"\\w",
"\\s",
"\\d",
"/",
")",
"do",
"|",
"name",
",",
"kbytes",
"|",
"pages",
"=",
"(",
"kbytes",
".",
"to_i",
"*",
"1024",
")",
"/",
"@pagesize",
"case",
"name",
"when",
"\"MemTotal\"",
"then",
"total",
"=",
"pages",
"when",
"\"MemFree\"",
"then",
"free",
"=",
"pages",
"when",
"\"MemAvailable\"",
"available",
"=",
"pages",
"has_available",
"=",
"true",
"when",
"\"Active\"",
"then",
"active",
"=",
"pages",
"when",
"\"Inactive\"",
"then",
"inactive",
"=",
"pages",
"end",
"end",
"end",
"procfs_file",
"(",
"\"vmstat\"",
")",
"do",
"|",
"file",
"|",
"content",
"=",
"file",
".",
"read",
"if",
"content",
"=~",
"/",
"\\s",
"\\d",
"/",
"pageins",
"=",
"$1",
".",
"to_i",
"end",
"if",
"content",
"=~",
"/",
"\\s",
"\\d",
"/",
"pageouts",
"=",
"$1",
".",
"to_i",
"end",
"end",
"mem_klass",
"=",
"has_available",
"?",
"LinuxMemory",
":",
"Memory",
"mem_klass",
".",
"new",
"(",
"@pagesize",
",",
"total",
"-",
"free",
"-",
"active",
"-",
"inactive",
",",
"active",
",",
"inactive",
",",
"free",
",",
"pageins",
",",
"pageouts",
")",
".",
"tap",
"do",
"|",
"mem",
"|",
"mem",
".",
"available",
"=",
"available",
"if",
"has_available",
"end",
"end"
]
| Fetches the memory usage information.
@return [Vmstat::Memory] the memory data like free, used und total.
@example
Vmstat.memory # => #<struct Vmstat::Memory ...> | [
"Fetches",
"the",
"memory",
"usage",
"information",
"."
]
| f762a6a5c6627182d6c1bb33f6605da2d3d4ef45 | https://github.com/threez/ruby-vmstat/blob/f762a6a5c6627182d6c1bb33f6605da2d3d4ef45/lib/vmstat/procfs.rb#L46-L86 | train |
threez/ruby-vmstat | lib/vmstat/procfs.rb | Vmstat.ProcFS.network_interfaces | def network_interfaces
netifcs = []
procfs_file("net", "dev") do |file|
file.read.scan(NET_DATA) do |columns|
type = case columns[0]
when /^eth/ then NetworkInterface::ETHERNET_TYPE
when /^lo/ then NetworkInterface::LOOPBACK_TYPE
end
netifcs << NetworkInterface.new(columns[0].to_sym, columns[1].to_i,
columns[3].to_i, columns[4].to_i,
columns[9].to_i, columns[11].to_i,
type)
end
end
netifcs
end | ruby | def network_interfaces
netifcs = []
procfs_file("net", "dev") do |file|
file.read.scan(NET_DATA) do |columns|
type = case columns[0]
when /^eth/ then NetworkInterface::ETHERNET_TYPE
when /^lo/ then NetworkInterface::LOOPBACK_TYPE
end
netifcs << NetworkInterface.new(columns[0].to_sym, columns[1].to_i,
columns[3].to_i, columns[4].to_i,
columns[9].to_i, columns[11].to_i,
type)
end
end
netifcs
end | [
"def",
"network_interfaces",
"netifcs",
"=",
"[",
"]",
"procfs_file",
"(",
"\"net\"",
",",
"\"dev\"",
")",
"do",
"|",
"file",
"|",
"file",
".",
"read",
".",
"scan",
"(",
"NET_DATA",
")",
"do",
"|",
"columns",
"|",
"type",
"=",
"case",
"columns",
"[",
"0",
"]",
"when",
"/",
"/",
"then",
"NetworkInterface",
"::",
"ETHERNET_TYPE",
"when",
"/",
"/",
"then",
"NetworkInterface",
"::",
"LOOPBACK_TYPE",
"end",
"netifcs",
"<<",
"NetworkInterface",
".",
"new",
"(",
"columns",
"[",
"0",
"]",
".",
"to_sym",
",",
"columns",
"[",
"1",
"]",
".",
"to_i",
",",
"columns",
"[",
"3",
"]",
".",
"to_i",
",",
"columns",
"[",
"4",
"]",
".",
"to_i",
",",
"columns",
"[",
"9",
"]",
".",
"to_i",
",",
"columns",
"[",
"11",
"]",
".",
"to_i",
",",
"type",
")",
"end",
"end",
"netifcs",
"end"
]
| Fetches the information for all available network devices.
@return [Array<Vmstat::NetworkInterface>] the network device information
@example
Vmstat.network_interfaces # => [#<struct Vmstat::NetworkInterface ...>, ...] | [
"Fetches",
"the",
"information",
"for",
"all",
"available",
"network",
"devices",
"."
]
| f762a6a5c6627182d6c1bb33f6605da2d3d4ef45 | https://github.com/threez/ruby-vmstat/blob/f762a6a5c6627182d6c1bb33f6605da2d3d4ef45/lib/vmstat/procfs.rb#L92-L108 | train |
threez/ruby-vmstat | lib/vmstat/procfs.rb | Vmstat.ProcFS.task | def task
@pagesize ||= Vmstat.pagesize
procfs_file("self", "stat") do |file|
data = file.read.split(/ /)
Task.new(data[22].to_i / @pagesize, data[23].to_i,
data[13].to_i * 1000, data[14].to_i * 1000)
end
end | ruby | def task
@pagesize ||= Vmstat.pagesize
procfs_file("self", "stat") do |file|
data = file.read.split(/ /)
Task.new(data[22].to_i / @pagesize, data[23].to_i,
data[13].to_i * 1000, data[14].to_i * 1000)
end
end | [
"def",
"task",
"@pagesize",
"||=",
"Vmstat",
".",
"pagesize",
"procfs_file",
"(",
"\"self\"",
",",
"\"stat\"",
")",
"do",
"|",
"file",
"|",
"data",
"=",
"file",
".",
"read",
".",
"split",
"(",
"/",
"/",
")",
"Task",
".",
"new",
"(",
"data",
"[",
"22",
"]",
".",
"to_i",
"/",
"@pagesize",
",",
"data",
"[",
"23",
"]",
".",
"to_i",
",",
"data",
"[",
"13",
"]",
".",
"to_i",
"*",
"1000",
",",
"data",
"[",
"14",
"]",
".",
"to_i",
"*",
"1000",
")",
"end",
"end"
]
| Fetches the current process cpu and memory data.
@return [Vmstat::Task] the task data for the current process | [
"Fetches",
"the",
"current",
"process",
"cpu",
"and",
"memory",
"data",
"."
]
| f762a6a5c6627182d6c1bb33f6605da2d3d4ef45 | https://github.com/threez/ruby-vmstat/blob/f762a6a5c6627182d6c1bb33f6605da2d3d4ef45/lib/vmstat/procfs.rb#L112-L120 | train |
threez/ruby-vmstat | lib/vmstat/procfs.rb | Vmstat.ProcFS.boot_time | def boot_time
raw = procfs_file("uptime") { |file| file.read }
Time.now - raw.split(/\s/).first.to_f
end | ruby | def boot_time
raw = procfs_file("uptime") { |file| file.read }
Time.now - raw.split(/\s/).first.to_f
end | [
"def",
"boot_time",
"raw",
"=",
"procfs_file",
"(",
"\"uptime\"",
")",
"{",
"|",
"file",
"|",
"file",
".",
"read",
"}",
"Time",
".",
"now",
"-",
"raw",
".",
"split",
"(",
"/",
"\\s",
"/",
")",
".",
"first",
".",
"to_f",
"end"
]
| Fetches the boot time of the system.
@return [Time] the boot time as regular time object.
@example
Vmstat.boot_time # => 2012-10-09 18:42:37 +0200 | [
"Fetches",
"the",
"boot",
"time",
"of",
"the",
"system",
"."
]
| f762a6a5c6627182d6c1bb33f6605da2d3d4ef45 | https://github.com/threez/ruby-vmstat/blob/f762a6a5c6627182d6c1bb33f6605da2d3d4ef45/lib/vmstat/procfs.rb#L126-L129 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.