id
int32
0
24.9k
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
16,300
igor-makarov/xcake
lib/xcake/dsl/target/sugar.rb
Xcake.Target.copy_files_build_phase
def copy_files_build_phase(name, &block) phase = CopyFilesBuildPhase.new(&block) phase.name = name build_phases << phase phase end
ruby
def copy_files_build_phase(name, &block) phase = CopyFilesBuildPhase.new(&block) phase.name = name build_phases << phase phase end
[ "def", "copy_files_build_phase", "(", "name", ",", "&", "block", ")", "phase", "=", "CopyFilesBuildPhase", ".", "new", "(", "block", ")", "phase", ".", "name", "=", "name", "build_phases", "<<", "phase", "phase", "end" ]
Creates a new Copy Files build phase for the target @param [String] name the name to use for the build phase @param [Proc] block an optional block that configures the build phase through the DSL. @return [CopyFilesBuildPhase] the new xcode build phase
[ "Creates", "a", "new", "Copy", "Files", "build", "phase", "for", "the", "target" ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/target/sugar.rb#L16-L21
16,301
igor-makarov/xcake
lib/xcake/dsl/target/sugar.rb
Xcake.Target.pre_shell_script_build_phase
def pre_shell_script_build_phase(name, script, &block) phase = ShellScriptBuildPhase.new(&block) phase.name = name phase.script = script pinned_build_phases << phase phase end
ruby
def pre_shell_script_build_phase(name, script, &block) phase = ShellScriptBuildPhase.new(&block) phase.name = name phase.script = script pinned_build_phases << phase phase end
[ "def", "pre_shell_script_build_phase", "(", "name", ",", "script", ",", "&", "block", ")", "phase", "=", "ShellScriptBuildPhase", ".", "new", "(", "block", ")", "phase", ".", "name", "=", "name", "phase", ".", "script", "=", "script", "pinned_build_phases", "<<", "phase", "phase", "end" ]
Creates a new Shell Script build phase for the target before all of the other build phases @param [String] name the name to use for the build phase @param [Proc] block an optional block that configures the build phase through the DSL. @return [ShellScriptBuildPhase] the new xcode build phase
[ "Creates", "a", "new", "Shell", "Script", "build", "phase", "for", "the", "target", "before", "all", "of", "the", "other", "build", "phases" ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/target/sugar.rb#L48-L54
16,302
igor-makarov/xcake
lib/xcake/dsl/target/sugar.rb
Xcake.Target.shell_script_build_phase
def shell_script_build_phase(name, script, &block) phase = ShellScriptBuildPhase.new(&block) phase.name = name phase.script = script build_phases << phase phase end
ruby
def shell_script_build_phase(name, script, &block) phase = ShellScriptBuildPhase.new(&block) phase.name = name phase.script = script build_phases << phase phase end
[ "def", "shell_script_build_phase", "(", "name", ",", "script", ",", "&", "block", ")", "phase", "=", "ShellScriptBuildPhase", ".", "new", "(", "block", ")", "phase", ".", "name", "=", "name", "phase", ".", "script", "=", "script", "build_phases", "<<", "phase", "phase", "end" ]
Creates a new Shell Script build phase for the target @param [String] name the name to use for the build phase @param [Proc] block an optional block that configures the build phase through the DSL. @return [ShellScriptBuildPhase] the new xcode build phase
[ "Creates", "a", "new", "Shell", "Script", "build", "phase", "for", "the", "target" ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/target/sugar.rb#L67-L73
16,303
igor-makarov/xcake
lib/xcake/dsl/target/sugar.rb
Xcake.Target.build_rule
def build_rule(name, file_type, output_files, output_files_compiler_flags, script, &block) rule = BuildRule.new(&block) rule.name = name rule.file_type = file_type rule.output_files = output_files rule.output_files_compiler_flags = output_files_compiler_flags rule.script = script build_rules << rule rule end
ruby
def build_rule(name, file_type, output_files, output_files_compiler_flags, script, &block) rule = BuildRule.new(&block) rule.name = name rule.file_type = file_type rule.output_files = output_files rule.output_files_compiler_flags = output_files_compiler_flags rule.script = script build_rules << rule rule end
[ "def", "build_rule", "(", "name", ",", "file_type", ",", "output_files", ",", "output_files_compiler_flags", ",", "script", ",", "&", "block", ")", "rule", "=", "BuildRule", ".", "new", "(", "block", ")", "rule", ".", "name", "=", "name", "rule", ".", "file_type", "=", "file_type", "rule", ".", "output_files", "=", "output_files", "rule", ".", "output_files_compiler_flags", "=", "output_files_compiler_flags", "rule", ".", "script", "=", "script", "build_rules", "<<", "rule", "rule", "end" ]
Creates a new build rule for the target @param [String] name the name to use for the build rule @param [Proc] block an optional block that configures the build rule through the DSL. @return [BuildRule] the new xcode build rule
[ "Creates", "a", "new", "build", "rule", "for", "the", "target" ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/target/sugar.rb#L86-L95
16,304
igor-makarov/xcake
lib/xcake/dsl/configurable.rb
Xcake.Configurable.configuration
def configuration(name, type) default_settings = default_settings_for_type(type) configurations = configurations_of_type(type) build_configuration = if name.nil? configurations.first else configurations.detect do |c| c.name == name.to_s end end if build_configuration.nil? name = type.to_s.capitalize if name.nil? build_configuration = Configuration.new(name) do |b| b.type = type b.settings.merge!(default_settings) yield(b) if block_given? end @configurations ||= [] @configurations << build_configuration end build_configuration end
ruby
def configuration(name, type) default_settings = default_settings_for_type(type) configurations = configurations_of_type(type) build_configuration = if name.nil? configurations.first else configurations.detect do |c| c.name == name.to_s end end if build_configuration.nil? name = type.to_s.capitalize if name.nil? build_configuration = Configuration.new(name) do |b| b.type = type b.settings.merge!(default_settings) yield(b) if block_given? end @configurations ||= [] @configurations << build_configuration end build_configuration end
[ "def", "configuration", "(", "name", ",", "type", ")", "default_settings", "=", "default_settings_for_type", "(", "type", ")", "configurations", "=", "configurations_of_type", "(", "type", ")", "build_configuration", "=", "if", "name", ".", "nil?", "configurations", ".", "first", "else", "configurations", ".", "detect", "do", "|", "c", "|", "c", ".", "name", "==", "name", ".", "to_s", "end", "end", "if", "build_configuration", ".", "nil?", "name", "=", "type", ".", "to_s", ".", "capitalize", "if", "name", ".", "nil?", "build_configuration", "=", "Configuration", ".", "new", "(", "name", ")", "do", "|", "b", "|", "b", ".", "type", "=", "type", "b", ".", "settings", ".", "merge!", "(", "default_settings", ")", "yield", "(", "b", ")", "if", "block_given?", "end", "@configurations", "||=", "[", "]", "@configurations", "<<", "build_configuration", "end", "build_configuration", "end" ]
This either finds a configuration with the same name and type or creates one. @return [Configuration] the new or existing configuration
[ "This", "either", "finds", "a", "configuration", "with", "the", "same", "name", "and", "type", "or", "creates", "one", "." ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/configurable.rb#L94-L122
16,305
igor-makarov/xcake
lib/xcake/dsl/project/sugar.rb
Xcake.Project.application_for
def application_for(platform, deployment_target, language = :objc) target do |t| t.type = :application t.platform = platform t.deployment_target = deployment_target t.language = language yield(t) if block_given? end end
ruby
def application_for(platform, deployment_target, language = :objc) target do |t| t.type = :application t.platform = platform t.deployment_target = deployment_target t.language = language yield(t) if block_given? end end
[ "def", "application_for", "(", "platform", ",", "deployment_target", ",", "language", "=", ":objc", ")", "target", "do", "|", "t", "|", "t", ".", "type", "=", ":application", "t", ".", "platform", "=", "platform", "t", ".", "deployment_target", "=", "deployment_target", "t", ".", "language", "=", "language", "yield", "(", "t", ")", "if", "block_given?", "end", "end" ]
Defines a new application target. @param [Symbol] platform platform for the application, can be either `:ios`, `:osx`, `:tvos` or `:watchos`. @param [Float] deployment_target the minimum deployment version for the platform. @param [Symbol] language language for application, can be either `:objc` or `:swift`. @param [Proc] block an optional block that configures the target through the DSL. @return [Target] the application target the newly created application target
[ "Defines", "a", "new", "application", "target", "." ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/project/sugar.rb#L34-L43
16,306
igor-makarov/xcake
lib/xcake/dsl/project/sugar.rb
Xcake.Project.extension_for
def extension_for(host_target) target = target do |t| t.type = :app_extension t.platform = host_target.platform t.deployment_target = host_target.deployment_target t.language = host_target.language end host_target.target_dependencies << target yield(target) if block_given? target end
ruby
def extension_for(host_target) target = target do |t| t.type = :app_extension t.platform = host_target.platform t.deployment_target = host_target.deployment_target t.language = host_target.language end host_target.target_dependencies << target yield(target) if block_given? target end
[ "def", "extension_for", "(", "host_target", ")", "target", "=", "target", "do", "|", "t", "|", "t", ".", "type", "=", ":app_extension", "t", ".", "platform", "=", "host_target", ".", "platform", "t", ".", "deployment_target", "=", "host_target", ".", "deployment_target", "t", ".", "language", "=", "host_target", ".", "language", "end", "host_target", ".", "target_dependencies", "<<", "target", "yield", "(", "target", ")", "if", "block_given?", "target", "end" ]
Defines a extension target. @param [Target] host target host target for which the extension is for. @param [Proc] block an optional block that configures the target through the DSL. @return [Target] the extension target the newly created extension target
[ "Defines", "a", "extension", "target", "." ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/project/sugar.rb#L126-L139
16,307
igor-makarov/xcake
lib/xcake/dsl/project/sugar.rb
Xcake.Project.watch_app_for
def watch_app_for(host_target, deployment_target, language = :objc) watch_app_target = target do |t| t.name = "#{host_target.name}-Watch" t.type = :watch2_app t.platform = :watchos t.deployment_target = deployment_target t.language = language end watch_extension_target = target do |t| t.name = "#{host_target.name}-Watch Extension" t.type = :watch2_extension t.platform = :watchos t.deployment_target = deployment_target t.language = language end host_target.target_dependencies << watch_app_target watch_app_target.target_dependencies << watch_extension_target yield(watch_app_target, watch_extension_target) if block_given? nil end
ruby
def watch_app_for(host_target, deployment_target, language = :objc) watch_app_target = target do |t| t.name = "#{host_target.name}-Watch" t.type = :watch2_app t.platform = :watchos t.deployment_target = deployment_target t.language = language end watch_extension_target = target do |t| t.name = "#{host_target.name}-Watch Extension" t.type = :watch2_extension t.platform = :watchos t.deployment_target = deployment_target t.language = language end host_target.target_dependencies << watch_app_target watch_app_target.target_dependencies << watch_extension_target yield(watch_app_target, watch_extension_target) if block_given? nil end
[ "def", "watch_app_for", "(", "host_target", ",", "deployment_target", ",", "language", "=", ":objc", ")", "watch_app_target", "=", "target", "do", "|", "t", "|", "t", ".", "name", "=", "\"#{host_target.name}-Watch\"", "t", ".", "type", "=", ":watch2_app", "t", ".", "platform", "=", ":watchos", "t", ".", "deployment_target", "=", "deployment_target", "t", ".", "language", "=", "language", "end", "watch_extension_target", "=", "target", "do", "|", "t", "|", "t", ".", "name", "=", "\"#{host_target.name}-Watch Extension\"", "t", ".", "type", "=", ":watch2_extension", "t", ".", "platform", "=", ":watchos", "t", ".", "deployment_target", "=", "deployment_target", "t", ".", "language", "=", "language", "end", "host_target", ".", "target_dependencies", "<<", "watch_app_target", "watch_app_target", ".", "target_dependencies", "<<", "watch_extension_target", "yield", "(", "watch_app_target", ",", "watch_extension_target", ")", "if", "block_given?", "nil", "end" ]
Defines targets for watch app. @param [Target] watch app's compantion app iOS target for the watch app @param [Proc] block an optional block that configures the targets through the DSL. @return Void
[ "Defines", "targets", "for", "watch", "app", "." ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/project/sugar.rb#L151-L176
16,308
igor-makarov/xcake
lib/xcake/dsl/target.rb
Xcake.Target.default_system_frameworks_for
def default_system_frameworks_for(platform) case platform when :ios %w(Foundation UIKit) when :osx %w(Cocoa) when :tvos %w(Foundation UIKit) when :watchos %w(Foundation UIKit WatchKit) else abort 'Platform not supported!' end end
ruby
def default_system_frameworks_for(platform) case platform when :ios %w(Foundation UIKit) when :osx %w(Cocoa) when :tvos %w(Foundation UIKit) when :watchos %w(Foundation UIKit WatchKit) else abort 'Platform not supported!' end end
[ "def", "default_system_frameworks_for", "(", "platform", ")", "case", "platform", "when", ":ios", "%w(", "Foundation", "UIKit", ")", "when", ":osx", "%w(", "Cocoa", ")", "when", ":tvos", "%w(", "Foundation", "UIKit", ")", "when", ":watchos", "%w(", "Foundation", "UIKit", "WatchKit", ")", "else", "abort", "'Platform not supported!'", "end", "end" ]
Returns an array of default system frameworks to use for a given platform. @param [Symbol] platform platform the frameworks are for. @return [Array<String>] system frameworks to use
[ "Returns", "an", "array", "of", "default", "system", "frameworks", "to", "use", "for", "a", "given", "platform", "." ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/dsl/target.rb#L256-L269
16,309
amatsuda/stateful_enum
lib/stateful_enum/state_inspection.rb
StatefulEnum.StateInspector.possible_states
def possible_states col = @stateful_enum.instance_variable_get :@column possible_events.flat_map {|e| e.instance_variable_get(:@transitions)[@model_instance.send(col).to_sym].first } end
ruby
def possible_states col = @stateful_enum.instance_variable_get :@column possible_events.flat_map {|e| e.instance_variable_get(:@transitions)[@model_instance.send(col).to_sym].first } end
[ "def", "possible_states", "col", "=", "@stateful_enum", ".", "instance_variable_get", ":@column", "possible_events", ".", "flat_map", "{", "|", "e", "|", "e", ".", "instance_variable_get", "(", ":@transitions", ")", "[", "@model_instance", ".", "send", "(", "col", ")", ".", "to_sym", "]", ".", "first", "}", "end" ]
List of transitionable states from the current state
[ "List", "of", "transitionable", "states", "from", "the", "current", "state" ]
38eafa5e05869e10b8e7f287185accea5913cfd6
https://github.com/amatsuda/stateful_enum/blob/38eafa5e05869e10b8e7f287185accea5913cfd6/lib/stateful_enum/state_inspection.rb#L36-L39
16,310
tzinfo/tzinfo
lib/tzinfo/timezone.rb
TZInfo.Timezone.to_local
def to_local(time) raise ArgumentError, 'time must be specified' unless time Timestamp.for(time) do |ts| TimestampWithOffset.set_timezone_offset(ts, period_for(ts).offset) end end
ruby
def to_local(time) raise ArgumentError, 'time must be specified' unless time Timestamp.for(time) do |ts| TimestampWithOffset.set_timezone_offset(ts, period_for(ts).offset) end end
[ "def", "to_local", "(", "time", ")", "raise", "ArgumentError", ",", "'time must be specified'", "unless", "time", "Timestamp", ".", "for", "(", "time", ")", "do", "|", "ts", "|", "TimestampWithOffset", ".", "set_timezone_offset", "(", "ts", ",", "period_for", "(", "ts", ")", ".", "offset", ")", "end", "end" ]
Converts a time to the local time for the time zone. The result will be of type {TimeWithOffset} (if passed a `Time`), {DateTimeWithOffset} (if passed a `DateTime`) or {TimestampWithOffset} (if passed a {Timestamp}). {TimeWithOffset}, {DateTimeWithOffset} and {TimestampWithOffset} are subclasses of `Time`, `DateTime` and {Timestamp} that provide additional information about the local result. Unlike {utc_to_local}, {to_local} takes the UTC offset of the given time into consideration. @param time [Object] a `Time`, `DateTime` or {Timestamp}. @return [Object] the local equivalent of `time` as a {TimeWithOffset}, {DateTimeWithOffset} or {TimestampWithOffset}. @raise [ArgumentError] if `time` is `nil`. @raise [ArgumentError] if `time` is a {Timestamp} that does not have a specified UTC offset.
[ "Converts", "a", "time", "to", "the", "local", "time", "for", "the", "time", "zone", "." ]
8fdf06ed9a4b935864e19794187d091219de481a
https://github.com/tzinfo/tzinfo/blob/8fdf06ed9a4b935864e19794187d091219de481a/lib/tzinfo/timezone.rb#L548-L554
16,311
tzinfo/tzinfo
lib/tzinfo/timezone.rb
TZInfo.Timezone.utc_to_local
def utc_to_local(utc_time) raise ArgumentError, 'utc_time must be specified' unless utc_time Timestamp.for(utc_time, :treat_as_utc) do |ts| to_local(ts) end end
ruby
def utc_to_local(utc_time) raise ArgumentError, 'utc_time must be specified' unless utc_time Timestamp.for(utc_time, :treat_as_utc) do |ts| to_local(ts) end end
[ "def", "utc_to_local", "(", "utc_time", ")", "raise", "ArgumentError", ",", "'utc_time must be specified'", "unless", "utc_time", "Timestamp", ".", "for", "(", "utc_time", ",", ":treat_as_utc", ")", "do", "|", "ts", "|", "to_local", "(", "ts", ")", "end", "end" ]
Converts a time in UTC to the local time for the time zone. The result will be of type {TimeWithOffset} (if passed a `Time`), {DateTimeWithOffset} (if passed a `DateTime`) or {TimestampWithOffset} (if passed a {Timestamp}). {TimeWithOffset}, {DateTimeWithOffset} and {TimestampWithOffset} are subclasses of `Time`, `DateTime` and {Timestamp} that provide additional information about the local result. The UTC offset of the `utc_time` parameter is ignored (it is treated as a UTC time). Use the {to_local} method instead if the the UTC offset of the time needs to be taken into consideration. @param utc_time [Object] a `Time`, `DateTime` or {Timestamp}. @return [Object] the local equivalent of `utc_time` as a {TimeWithOffset}, {DateTimeWithOffset} or {TimestampWithOffset}. @raise [ArgumentError] if `utc_time` is `nil`.
[ "Converts", "a", "time", "in", "UTC", "to", "the", "local", "time", "for", "the", "time", "zone", "." ]
8fdf06ed9a4b935864e19794187d091219de481a
https://github.com/tzinfo/tzinfo/blob/8fdf06ed9a4b935864e19794187d091219de481a/lib/tzinfo/timezone.rb#L572-L578
16,312
tzinfo/tzinfo
lib/tzinfo/timezone.rb
TZInfo.Timezone.local_to_utc
def local_to_utc(local_time, dst = Timezone.default_dst) raise ArgumentError, 'local_time must be specified' unless local_time Timestamp.for(local_time, :ignore) do |ts| period = if block_given? period_for_local(ts, dst) {|periods| yield periods } else period_for_local(ts, dst) end ts.add_and_set_utc_offset(-period.observed_utc_offset, :utc) end end
ruby
def local_to_utc(local_time, dst = Timezone.default_dst) raise ArgumentError, 'local_time must be specified' unless local_time Timestamp.for(local_time, :ignore) do |ts| period = if block_given? period_for_local(ts, dst) {|periods| yield periods } else period_for_local(ts, dst) end ts.add_and_set_utc_offset(-period.observed_utc_offset, :utc) end end
[ "def", "local_to_utc", "(", "local_time", ",", "dst", "=", "Timezone", ".", "default_dst", ")", "raise", "ArgumentError", ",", "'local_time must be specified'", "unless", "local_time", "Timestamp", ".", "for", "(", "local_time", ",", ":ignore", ")", "do", "|", "ts", "|", "period", "=", "if", "block_given?", "period_for_local", "(", "ts", ",", "dst", ")", "{", "|", "periods", "|", "yield", "periods", "}", "else", "period_for_local", "(", "ts", ",", "dst", ")", "end", "ts", ".", "add_and_set_utc_offset", "(", "-", "period", ".", "observed_utc_offset", ",", ":utc", ")", "end", "end" ]
Converts a local time for the time zone to UTC. The result will either be a `Time`, `DateTime` or {Timestamp} according to the type of the `local_time` parameter. The UTC offset of the `local_time` parameter is ignored (it is treated as a time in the time zone represented by `self`). _Warning:_ There are local times that have no equivalent UTC times (for example, during the transition from standard time to daylight savings time). There are also local times that have more than one UTC equivalent (for example, during the transition from daylight savings time to standard time). In the first case (no equivalent UTC time), a {PeriodNotFound} exception will be raised. In the second case (more than one equivalent UTC time), an {AmbiguousTime} exception will be raised unless the optional `dst` parameter or block handles the ambiguity. If the ambiguity is due to a transition from daylight savings time to standard time, the `dst` parameter can be used to select whether the daylight savings time or local time is used. For example, the following code would raise an {AmbiguousTime} exception: tz = TZInfo::Timezone.get('America/New_York') tz.period_for_local(Time.new(2004,10,31,1,30,0)) Specifying `dst = true` would select the daylight savings period from April to October 2004. Specifying `dst = false` would return the standard time period from October 2004 to April 2005. The `dst` parameter will not be able to resolve an ambiguity resulting from the clocks being set back without changing from daylight savings time to standard time. In this case, if a block is specified, it will be called to resolve the ambiguity. The block must take a single parameter - an `Array` of {TimezonePeriod}s that need to be resolved. The block can select and return a single {TimezonePeriod} or return `nil` or an empty `Array` to cause an {AmbiguousTime} exception to be raised. The default value of the `dst` parameter can be specified using {Timezone.default_dst=}. @param local_time [Object] a `Time`, `DateTime` or {Timestamp}. @param dst [Boolean] whether to resolve ambiguous local times by always selecting the period observing daylight savings time (`true`), always selecting the period observing standard time (`false`), or leaving the ambiguity unresolved (`nil`). @yield [periods] if the `dst` parameter did not resolve an ambiguity, an optional block is yielded to. @yieldparam periods [Array<TimezonePeriod>] an `Array` containing all the {TimezonePeriod}s that still match `local_time` after applying the `dst` parameter. @yieldreturn [Object] to resolve the ambiguity: a chosen {TimezonePeriod} or an `Array` containing a chosen {TimezonePeriod}; to leave the ambiguity unresolved: an empty `Array`, an `Array` containing more than one {TimezonePeriod}, or `nil`. @return [Object] the UTC equivalent of `local_time` as a `Time`, `DateTime` or {Timestamp}. @raise [ArgumentError] if `local_time` is `nil`. @raise [PeriodNotFound] if `local_time` is not valid for the time zone (there is no equivalent UTC time). @raise [AmbiguousTime] if `local_time` was ambiguous for the time zone and the `dst` parameter or block did not resolve the ambiguity.
[ "Converts", "a", "local", "time", "for", "the", "time", "zone", "to", "UTC", "." ]
8fdf06ed9a4b935864e19794187d091219de481a
https://github.com/tzinfo/tzinfo/blob/8fdf06ed9a4b935864e19794187d091219de481a/lib/tzinfo/timezone.rb#L645-L657
16,313
tzinfo/tzinfo
lib/tzinfo/data_source.rb
TZInfo.DataSource.try_with_encoding
def try_with_encoding(string, encoding) result = yield string return result if result unless encoding == string.encoding string = string.encode(encoding) yield string end end
ruby
def try_with_encoding(string, encoding) result = yield string return result if result unless encoding == string.encoding string = string.encode(encoding) yield string end end
[ "def", "try_with_encoding", "(", "string", ",", "encoding", ")", "result", "=", "yield", "string", "return", "result", "if", "result", "unless", "encoding", "==", "string", ".", "encoding", "string", "=", "string", ".", "encode", "(", "encoding", ")", "yield", "string", "end", "end" ]
Tries an operation using `string` directly. If the operation fails, the string is copied and encoded with `encoding` and the operation is tried again. @param string [String] The `String` to perform the operation on. @param encoding [Encoding] The `Encoding` to use if the initial attempt fails. @yield [s] the caller will be yielded to once or twice to attempt the operation. @yieldparam s [String] either `string` or an encoded copy of `string`. @yieldreturn [Object] The result of the operation. Must be truthy if successful. @return [Object] the result of the operation or `nil` if the first attempt fails and `string` is already encoded with `encoding`.
[ "Tries", "an", "operation", "using", "string", "directly", ".", "If", "the", "operation", "fails", "the", "string", "is", "copied", "and", "encoded", "with", "encoding", "and", "the", "operation", "is", "tried", "again", "." ]
8fdf06ed9a4b935864e19794187d091219de481a
https://github.com/tzinfo/tzinfo/blob/8fdf06ed9a4b935864e19794187d091219de481a/lib/tzinfo/data_source.rb#L425-L433
16,314
markets/invisible_captcha
lib/invisible_captcha/view_helpers.rb
InvisibleCaptcha.ViewHelpers.invisible_captcha
def invisible_captcha(honeypot = nil, scope = nil, options = {}) if InvisibleCaptcha.timestamp_enabled session[:invisible_captcha_timestamp] = Time.zone.now.iso8601 end build_invisible_captcha(honeypot, scope, options) end
ruby
def invisible_captcha(honeypot = nil, scope = nil, options = {}) if InvisibleCaptcha.timestamp_enabled session[:invisible_captcha_timestamp] = Time.zone.now.iso8601 end build_invisible_captcha(honeypot, scope, options) end
[ "def", "invisible_captcha", "(", "honeypot", "=", "nil", ",", "scope", "=", "nil", ",", "options", "=", "{", "}", ")", "if", "InvisibleCaptcha", ".", "timestamp_enabled", "session", "[", ":invisible_captcha_timestamp", "]", "=", "Time", ".", "zone", ".", "now", ".", "iso8601", "end", "build_invisible_captcha", "(", "honeypot", ",", "scope", ",", "options", ")", "end" ]
Builds the honeypot html @param honeypot [Symbol] name of honeypot, ie: subtitle => input name: subtitle @param scope [Symbol] name of honeypot scope, ie: topic => input name: topic[subtitle] @param options [Hash] html_options for input and invisible_captcha options @return [String] the generated html
[ "Builds", "the", "honeypot", "html" ]
3da1ead83efa20579c8e1fbb7e040fc4e5810eb2
https://github.com/markets/invisible_captcha/blob/3da1ead83efa20579c8e1fbb7e040fc4e5810eb2/lib/invisible_captcha/view_helpers.rb#L10-L15
16,315
leejarvis/slop
lib/slop/result.rb
Slop.Result.fetch
def fetch(flag) o = option(flag) if o.nil? cleaned_key = clean_key(flag) raise UnknownOption.new("option not found: '#{cleaned_key}'", "#{cleaned_key}") else o.value end end
ruby
def fetch(flag) o = option(flag) if o.nil? cleaned_key = clean_key(flag) raise UnknownOption.new("option not found: '#{cleaned_key}'", "#{cleaned_key}") else o.value end end
[ "def", "fetch", "(", "flag", ")", "o", "=", "option", "(", "flag", ")", "if", "o", ".", "nil?", "cleaned_key", "=", "clean_key", "(", "flag", ")", "raise", "UnknownOption", ".", "new", "(", "\"option not found: '#{cleaned_key}'\"", ",", "\"#{cleaned_key}\"", ")", "else", "o", ".", "value", "end", "end" ]
Returns an option's value, raises UnknownOption if the option does not exist.
[ "Returns", "an", "option", "s", "value", "raises", "UnknownOption", "if", "the", "option", "does", "not", "exist", "." ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/result.rb#L24-L32
16,316
leejarvis/slop
lib/slop/result.rb
Slop.Result.[]=
def []=(flag, value) if o = option(flag) o.value = value else raise ArgumentError, "no option with flag `#{flag}'" end end
ruby
def []=(flag, value) if o = option(flag) o.value = value else raise ArgumentError, "no option with flag `#{flag}'" end end
[ "def", "[]=", "(", "flag", ",", "value", ")", "if", "o", "=", "option", "(", "flag", ")", "o", ".", "value", "=", "value", "else", "raise", "ArgumentError", ",", "\"no option with flag `#{flag}'\"", "end", "end" ]
Set the value for an option. Raises an ArgumentError if the option does not exist.
[ "Set", "the", "value", "for", "an", "option", ".", "Raises", "an", "ArgumentError", "if", "the", "option", "does", "not", "exist", "." ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/result.rb#L36-L42
16,317
leejarvis/slop
lib/slop/result.rb
Slop.Result.option
def option(flag) options.find do |o| o.flags.any? { |f| clean_key(f) == clean_key(flag) } end end
ruby
def option(flag) options.find do |o| o.flags.any? { |f| clean_key(f) == clean_key(flag) } end end
[ "def", "option", "(", "flag", ")", "options", ".", "find", "do", "|", "o", "|", "o", ".", "flags", ".", "any?", "{", "|", "f", "|", "clean_key", "(", "f", ")", "==", "clean_key", "(", "flag", ")", "}", "end", "end" ]
Returns an Option if it exists. Ignores any prefixed hyphens.
[ "Returns", "an", "Option", "if", "it", "exists", ".", "Ignores", "any", "prefixed", "hyphens", "." ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/result.rb#L46-L50
16,318
leejarvis/slop
lib/slop/result.rb
Slop.Result.to_hash
def to_hash Hash[options.reject(&:null?).map { |o| [o.key, o.value] }] end
ruby
def to_hash Hash[options.reject(&:null?).map { |o| [o.key, o.value] }] end
[ "def", "to_hash", "Hash", "[", "options", ".", "reject", "(", ":null?", ")", ".", "map", "{", "|", "o", "|", "[", "o", ".", "key", ",", "o", ".", "value", "]", "}", "]", "end" ]
Returns a hash with option key => value.
[ "Returns", "a", "hash", "with", "option", "key", "=", ">", "value", "." ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/result.rb#L91-L93
16,319
leejarvis/slop
lib/slop/parser.rb
Slop.Parser.try_process
def try_process(flag, arg) if option = matching_option(flag) process(option, arg) elsif flag.start_with?("--no-") && option = matching_option(flag.sub("no-", "")) process(option, false) elsif flag =~ /\A-[^-]{2,}/ try_process_smashed_arg(flag) || try_process_grouped_flags(flag, arg) else if flag.start_with?("-") && !suppress_errors? raise UnknownOption.new("unknown option `#{flag}'", "#{flag}") end end end
ruby
def try_process(flag, arg) if option = matching_option(flag) process(option, arg) elsif flag.start_with?("--no-") && option = matching_option(flag.sub("no-", "")) process(option, false) elsif flag =~ /\A-[^-]{2,}/ try_process_smashed_arg(flag) || try_process_grouped_flags(flag, arg) else if flag.start_with?("-") && !suppress_errors? raise UnknownOption.new("unknown option `#{flag}'", "#{flag}") end end end
[ "def", "try_process", "(", "flag", ",", "arg", ")", "if", "option", "=", "matching_option", "(", "flag", ")", "process", "(", "option", ",", "arg", ")", "elsif", "flag", ".", "start_with?", "(", "\"--no-\"", ")", "&&", "option", "=", "matching_option", "(", "flag", ".", "sub", "(", "\"no-\"", ",", "\"\"", ")", ")", "process", "(", "option", ",", "false", ")", "elsif", "flag", "=~", "/", "\\A", "/", "try_process_smashed_arg", "(", "flag", ")", "||", "try_process_grouped_flags", "(", "flag", ",", "arg", ")", "else", "if", "flag", ".", "start_with?", "(", "\"-\"", ")", "&&", "!", "suppress_errors?", "raise", "UnknownOption", ".", "new", "(", "\"unknown option `#{flag}'\"", ",", "\"#{flag}\"", ")", "end", "end", "end" ]
Try and find an option to process
[ "Try", "and", "find", "an", "option", "to", "process" ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/parser.rb#L116-L128
16,320
leejarvis/slop
lib/slop/option.rb
Slop.Option.key
def key key = config[:key] || flags.last.sub(/\A--?/, '') key = key.tr '-', '_' if underscore_flags? key.to_sym end
ruby
def key key = config[:key] || flags.last.sub(/\A--?/, '') key = key.tr '-', '_' if underscore_flags? key.to_sym end
[ "def", "key", "key", "=", "config", "[", ":key", "]", "||", "flags", ".", "last", ".", "sub", "(", "/", "\\A", "/", ",", "''", ")", "key", "=", "key", ".", "tr", "'-'", ",", "'_'", "if", "underscore_flags?", "key", ".", "to_sym", "end" ]
Returns the last key as a symbol. Used in Options.to_hash.
[ "Returns", "the", "last", "key", "as", "a", "symbol", ".", "Used", "in", "Options", ".", "to_hash", "." ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/option.rb#L116-L120
16,321
leejarvis/slop
lib/slop/options.rb
Slop.Options.separator
def separator(string = "") if separators[options.size] separators[-1] += "\n#{string}" else separators[options.size] = string end end
ruby
def separator(string = "") if separators[options.size] separators[-1] += "\n#{string}" else separators[options.size] = string end end
[ "def", "separator", "(", "string", "=", "\"\"", ")", "if", "separators", "[", "options", ".", "size", "]", "separators", "[", "-", "1", "]", "+=", "\"\\n#{string}\"", "else", "separators", "[", "options", ".", "size", "]", "=", "string", "end", "end" ]
Add a separator between options. Used when displaying the help text.
[ "Add", "a", "separator", "between", "options", ".", "Used", "when", "displaying", "the", "help", "text", "." ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/options.rb#L62-L68
16,322
leejarvis/slop
lib/slop/options.rb
Slop.Options.method_missing
def method_missing(name, *args, **config, &block) if respond_to_missing?(name) config[:type] = name on(*args, config, &block) else super end end
ruby
def method_missing(name, *args, **config, &block) if respond_to_missing?(name) config[:type] = name on(*args, config, &block) else super end end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "**", "config", ",", "&", "block", ")", "if", "respond_to_missing?", "(", "name", ")", "config", "[", ":type", "]", "=", "name", "on", "(", "args", ",", "config", ",", "block", ")", "else", "super", "end", "end" ]
Handle custom option types. Will fall back to raising an exception if an option is not defined.
[ "Handle", "custom", "option", "types", ".", "Will", "fall", "back", "to", "raising", "an", "exception", "if", "an", "option", "is", "not", "defined", "." ]
aa233ababf00cd32f46a278ca030d5c40281e7c1
https://github.com/leejarvis/slop/blob/aa233ababf00cd32f46a278ca030d5c40281e7c1/lib/slop/options.rb#L82-L89
16,323
guard/guard-rspec
lib/guard/rspec_formatter.rb
Guard.RSpecFormatter.write_summary
def write_summary(duration, total, failures, pending) _write do |f| f.puts _message(total, failures, pending, duration) f.puts _failed_paths.join("\n") if failures > 0 end end
ruby
def write_summary(duration, total, failures, pending) _write do |f| f.puts _message(total, failures, pending, duration) f.puts _failed_paths.join("\n") if failures > 0 end end
[ "def", "write_summary", "(", "duration", ",", "total", ",", "failures", ",", "pending", ")", "_write", "do", "|", "f", "|", "f", ".", "puts", "_message", "(", "total", ",", "failures", ",", "pending", ",", "duration", ")", "f", ".", "puts", "_failed_paths", ".", "join", "(", "\"\\n\"", ")", "if", "failures", ">", "0", "end", "end" ]
Write summary to temporary file for runner
[ "Write", "summary", "to", "temporary", "file", "for", "runner" ]
1cf25c7127112c246b6e1a38208c32a6aee8a6c7
https://github.com/guard/guard-rspec/blob/1cf25c7127112c246b6e1a38208c32a6aee8a6c7/lib/guard/rspec_formatter.rb#L109-L114
16,324
nixme/pry-nav
lib/pry-nav/pry_remote_ext.rb
PryRemote.Server.run
def run if PryNav.current_remote_server raise 'Already running a pry-remote session!' else PryNav.current_remote_server = self end setup Pry.start @object, { :input => client.input_proxy, :output => client.output, :pry_remote => true } end
ruby
def run if PryNav.current_remote_server raise 'Already running a pry-remote session!' else PryNav.current_remote_server = self end setup Pry.start @object, { :input => client.input_proxy, :output => client.output, :pry_remote => true } end
[ "def", "run", "if", "PryNav", ".", "current_remote_server", "raise", "'Already running a pry-remote session!'", "else", "PryNav", ".", "current_remote_server", "=", "self", "end", "setup", "Pry", ".", "start", "@object", ",", "{", ":input", "=>", "client", ".", "input_proxy", ",", ":output", "=>", "client", ".", "output", ",", ":pry_remote", "=>", "true", "}", "end" ]
Override the call to Pry.start to save off current Server, pass a pry_remote flag so pry-nav knows this is a remote session, and not kill the server right away
[ "Override", "the", "call", "to", "Pry", ".", "start", "to", "save", "off", "current", "Server", "pass", "a", "pry_remote", "flag", "so", "pry", "-", "nav", "knows", "this", "is", "a", "remote", "session", "and", "not", "kill", "the", "server", "right", "away" ]
56139f68fec5d89427147606adf9d819c3dee94c
https://github.com/nixme/pry-nav/blob/56139f68fec5d89427147606adf9d819c3dee94c/lib/pry-nav/pry_remote_ext.rb#L9-L22
16,325
pluginaweek/state_machine
lib/state_machine/transition.rb
StateMachine.Transition.pausable
def pausable begin halted = !catch(:halt) { yield; true } rescue Exception => error raise unless @resume_block end if @resume_block @resume_block.call(halted, error) else halted end end
ruby
def pausable begin halted = !catch(:halt) { yield; true } rescue Exception => error raise unless @resume_block end if @resume_block @resume_block.call(halted, error) else halted end end
[ "def", "pausable", "begin", "halted", "=", "!", "catch", "(", ":halt", ")", "{", "yield", ";", "true", "}", "rescue", "Exception", "=>", "error", "raise", "unless", "@resume_block", "end", "if", "@resume_block", "@resume_block", ".", "call", "(", "halted", ",", "error", ")", "else", "halted", "end", "end" ]
Runs a block that may get paused. If the block doesn't pause, then execution will continue as normal. If the block gets paused, then it will take care of switching the execution context when it's resumed. This will return true if the given block halts for a reason other than getting paused.
[ "Runs", "a", "block", "that", "may", "get", "paused", ".", "If", "the", "block", "doesn", "t", "pause", "then", "execution", "will", "continue", "as", "normal", ".", "If", "the", "block", "gets", "paused", "then", "it", "will", "take", "care", "of", "switching", "the", "execution", "context", "when", "it", "s", "resumed", "." ]
8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0
https://github.com/pluginaweek/state_machine/blob/8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0/lib/state_machine/transition.rb#L346-L358
16,326
pluginaweek/state_machine
lib/state_machine/event.rb
StateMachine.Event.transition
def transition(options) raise ArgumentError, 'Must specify as least one transition requirement' if options.empty? # Only a certain subset of explicit options are allowed for transition # requirements assert_valid_keys(options, :from, :to, :except_from, :except_to, :if, :unless) if (options.keys - [:from, :to, :on, :except_from, :except_to, :except_on, :if, :unless]).empty? branches << branch = Branch.new(options.merge(:on => name)) @known_states |= branch.known_states branch end
ruby
def transition(options) raise ArgumentError, 'Must specify as least one transition requirement' if options.empty? # Only a certain subset of explicit options are allowed for transition # requirements assert_valid_keys(options, :from, :to, :except_from, :except_to, :if, :unless) if (options.keys - [:from, :to, :on, :except_from, :except_to, :except_on, :if, :unless]).empty? branches << branch = Branch.new(options.merge(:on => name)) @known_states |= branch.known_states branch end
[ "def", "transition", "(", "options", ")", "raise", "ArgumentError", ",", "'Must specify as least one transition requirement'", "if", "options", ".", "empty?", "# Only a certain subset of explicit options are allowed for transition", "# requirements", "assert_valid_keys", "(", "options", ",", ":from", ",", ":to", ",", ":except_from", ",", ":except_to", ",", ":if", ",", ":unless", ")", "if", "(", "options", ".", "keys", "-", "[", ":from", ",", ":to", ",", ":on", ",", ":except_from", ",", ":except_to", ",", ":except_on", ",", ":if", ",", ":unless", "]", ")", ".", "empty?", "branches", "<<", "branch", "=", "Branch", ".", "new", "(", "options", ".", "merge", "(", ":on", "=>", "name", ")", ")", "@known_states", "|=", "branch", ".", "known_states", "branch", "end" ]
Creates a new transition that determines what to change the current state to when this event fires. Since this transition is being defined within an event context, you do *not* need to specify the <tt>:on</tt> option for the transition. For example: state_machine do event :ignite do transition :parked => :idling, :idling => same, :if => :seatbelt_on? # Transitions to :idling if seatbelt is on transition all => :parked, :unless => :seatbelt_on? # Transitions to :parked if seatbelt is off end end See StateMachine::Machine#transition for a description of the possible configurations for defining transitions.
[ "Creates", "a", "new", "transition", "that", "determines", "what", "to", "change", "the", "current", "state", "to", "when", "this", "event", "fires", "." ]
8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0
https://github.com/pluginaweek/state_machine/blob/8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0/lib/state_machine/event.rb#L105-L115
16,327
pluginaweek/state_machine
lib/state_machine/state_context.rb
StateMachine.StateContext.transition
def transition(options) assert_valid_keys(options, :from, :to, :on, :if, :unless) raise ArgumentError, 'Must specify :on event' unless options[:on] raise ArgumentError, 'Must specify either :to or :from state' unless !options[:to] ^ !options[:from] machine.transition(options.merge(options[:to] ? {:from => state.name} : {:to => state.name})) end
ruby
def transition(options) assert_valid_keys(options, :from, :to, :on, :if, :unless) raise ArgumentError, 'Must specify :on event' unless options[:on] raise ArgumentError, 'Must specify either :to or :from state' unless !options[:to] ^ !options[:from] machine.transition(options.merge(options[:to] ? {:from => state.name} : {:to => state.name})) end
[ "def", "transition", "(", "options", ")", "assert_valid_keys", "(", "options", ",", ":from", ",", ":to", ",", ":on", ",", ":if", ",", ":unless", ")", "raise", "ArgumentError", ",", "'Must specify :on event'", "unless", "options", "[", ":on", "]", "raise", "ArgumentError", ",", "'Must specify either :to or :from state'", "unless", "!", "options", "[", ":to", "]", "^", "!", "options", "[", ":from", "]", "machine", ".", "transition", "(", "options", ".", "merge", "(", "options", "[", ":to", "]", "?", "{", ":from", "=>", "state", ".", "name", "}", ":", "{", ":to", "=>", "state", ".", "name", "}", ")", ")", "end" ]
Creates a new context for the given state Creates a new transition that determines what to change the current state to when an event fires from this state. Since this transition is being defined within a state context, you do *not* need to specify the <tt>:from</tt> option for the transition. For example: state_machine do state :parked do transition :to => :idling, :on => [:ignite, :shift_up] # Transitions to :idling transition :from => [:idling, :parked], :on => :park, :unless => :seatbelt_on? # Transitions to :parked if seatbelt is off end end See StateMachine::Machine#transition for a description of the possible configurations for defining transitions.
[ "Creates", "a", "new", "context", "for", "the", "given", "state", "Creates", "a", "new", "transition", "that", "determines", "what", "to", "change", "the", "current", "state", "to", "when", "an", "event", "fires", "from", "this", "state", "." ]
8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0
https://github.com/pluginaweek/state_machine/blob/8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0/lib/state_machine/state_context.rb#L95-L101
16,328
pluginaweek/state_machine
lib/state_machine/node_collection.rb
StateMachine.NodeCollection.initialize_copy
def initialize_copy(orig) #:nodoc: super nodes = @nodes contexts = @contexts @nodes = [] @contexts = [] @indices = @indices.inject({}) {|indices, (name, *)| indices[name] = {}; indices} # Add nodes *prior* to copying over the contexts so that they don't get # evaluated multiple times concat(nodes.map {|n| n.dup}) @contexts = contexts.dup end
ruby
def initialize_copy(orig) #:nodoc: super nodes = @nodes contexts = @contexts @nodes = [] @contexts = [] @indices = @indices.inject({}) {|indices, (name, *)| indices[name] = {}; indices} # Add nodes *prior* to copying over the contexts so that they don't get # evaluated multiple times concat(nodes.map {|n| n.dup}) @contexts = contexts.dup end
[ "def", "initialize_copy", "(", "orig", ")", "#:nodoc:", "super", "nodes", "=", "@nodes", "contexts", "=", "@contexts", "@nodes", "=", "[", "]", "@contexts", "=", "[", "]", "@indices", "=", "@indices", ".", "inject", "(", "{", "}", ")", "{", "|", "indices", ",", "(", "name", ",", "*", ")", "|", "indices", "[", "name", "]", "=", "{", "}", ";", "indices", "}", "# Add nodes *prior* to copying over the contexts so that they don't get", "# evaluated multiple times", "concat", "(", "nodes", ".", "map", "{", "|", "n", "|", "n", ".", "dup", "}", ")", "@contexts", "=", "contexts", ".", "dup", "end" ]
Creates a new collection of nodes for the given state machine. By default, the collection is empty. Configuration options: * <tt>:index</tt> - One or more attributes to automatically generate hashed indices for in order to perform quick lookups. Default is to index by the :name attribute Creates a copy of this collection such that modifications don't affect the original collection
[ "Creates", "a", "new", "collection", "of", "nodes", "for", "the", "given", "state", "machine", ".", "By", "default", "the", "collection", "is", "empty", "." ]
8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0
https://github.com/pluginaweek/state_machine/blob/8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0/lib/state_machine/node_collection.rb#L40-L53
16,329
pluginaweek/state_machine
lib/state_machine/node_collection.rb
StateMachine.NodeCollection.context
def context(nodes, &block) nodes = nodes.first.is_a?(Matcher) ? nodes.first : WhitelistMatcher.new(nodes) @contexts << context = {:nodes => nodes, :block => block} # Evaluate the new context for existing nodes each {|node| eval_context(context, node)} context end
ruby
def context(nodes, &block) nodes = nodes.first.is_a?(Matcher) ? nodes.first : WhitelistMatcher.new(nodes) @contexts << context = {:nodes => nodes, :block => block} # Evaluate the new context for existing nodes each {|node| eval_context(context, node)} context end
[ "def", "context", "(", "nodes", ",", "&", "block", ")", "nodes", "=", "nodes", ".", "first", ".", "is_a?", "(", "Matcher", ")", "?", "nodes", ".", "first", ":", "WhitelistMatcher", ".", "new", "(", "nodes", ")", "@contexts", "<<", "context", "=", "{", ":nodes", "=>", "nodes", ",", ":block", "=>", "block", "}", "# Evaluate the new context for existing nodes", "each", "{", "|", "node", "|", "eval_context", "(", "context", ",", "node", ")", "}", "context", "end" ]
Tracks a context that should be evaluated for any nodes that get added which match the given set of nodes. Matchers can be used so that the context can get added once and evaluated after multiple adds.
[ "Tracks", "a", "context", "that", "should", "be", "evaluated", "for", "any", "nodes", "that", "get", "added", "which", "match", "the", "given", "set", "of", "nodes", ".", "Matchers", "can", "be", "used", "so", "that", "the", "context", "can", "get", "added", "once", "and", "evaluated", "after", "multiple", "adds", "." ]
8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0
https://github.com/pluginaweek/state_machine/blob/8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0/lib/state_machine/node_collection.rb#L75-L83
16,330
pluginaweek/state_machine
lib/state_machine/machine.rb
StateMachine.Machine.owner_class=
def owner_class=(klass) @owner_class = klass # Create modules for extending the class with state/event-specific methods @helper_modules = helper_modules = {:instance => HelperModule.new(self, :instance), :class => HelperModule.new(self, :class)} owner_class.class_eval do extend helper_modules[:class] include helper_modules[:instance] end # Add class-/instance-level methods to the owner class for state initialization unless owner_class < StateMachine::InstanceMethods owner_class.class_eval do extend StateMachine::ClassMethods include StateMachine::InstanceMethods end define_state_initializer if @initialize_state end # Record this machine as matched to the name in the current owner class. # This will override any machines mapped to the same name in any superclasses. owner_class.state_machines[name] = self end
ruby
def owner_class=(klass) @owner_class = klass # Create modules for extending the class with state/event-specific methods @helper_modules = helper_modules = {:instance => HelperModule.new(self, :instance), :class => HelperModule.new(self, :class)} owner_class.class_eval do extend helper_modules[:class] include helper_modules[:instance] end # Add class-/instance-level methods to the owner class for state initialization unless owner_class < StateMachine::InstanceMethods owner_class.class_eval do extend StateMachine::ClassMethods include StateMachine::InstanceMethods end define_state_initializer if @initialize_state end # Record this machine as matched to the name in the current owner class. # This will override any machines mapped to the same name in any superclasses. owner_class.state_machines[name] = self end
[ "def", "owner_class", "=", "(", "klass", ")", "@owner_class", "=", "klass", "# Create modules for extending the class with state/event-specific methods", "@helper_modules", "=", "helper_modules", "=", "{", ":instance", "=>", "HelperModule", ".", "new", "(", "self", ",", ":instance", ")", ",", ":class", "=>", "HelperModule", ".", "new", "(", "self", ",", ":class", ")", "}", "owner_class", ".", "class_eval", "do", "extend", "helper_modules", "[", ":class", "]", "include", "helper_modules", "[", ":instance", "]", "end", "# Add class-/instance-level methods to the owner class for state initialization", "unless", "owner_class", "<", "StateMachine", "::", "InstanceMethods", "owner_class", ".", "class_eval", "do", "extend", "StateMachine", "::", "ClassMethods", "include", "StateMachine", "::", "InstanceMethods", "end", "define_state_initializer", "if", "@initialize_state", "end", "# Record this machine as matched to the name in the current owner class.", "# This will override any machines mapped to the same name in any superclasses.", "owner_class", ".", "state_machines", "[", "name", "]", "=", "self", "end" ]
Sets the class which is the owner of this state machine. Any methods generated by states, events, or other parts of the machine will be defined on the given owner class.
[ "Sets", "the", "class", "which", "is", "the", "owner", "of", "this", "state", "machine", ".", "Any", "methods", "generated", "by", "states", "events", "or", "other", "parts", "of", "the", "machine", "will", "be", "defined", "on", "the", "given", "owner", "class", "." ]
8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0
https://github.com/pluginaweek/state_machine/blob/8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0/lib/state_machine/machine.rb#L601-L624
16,331
pluginaweek/state_machine
lib/state_machine/callback.rb
StateMachine.Callback.run_methods
def run_methods(object, context = {}, index = 0, *args, &block) if type == :around if current_method = @methods[index] yielded = false evaluate_method(object, current_method, *args) do yielded = true run_methods(object, context, index + 1, *args, &block) end throw :halt unless yielded else yield if block_given? end else @methods.each do |method| result = evaluate_method(object, method, *args) throw :halt if @terminator && @terminator.call(result) end end end
ruby
def run_methods(object, context = {}, index = 0, *args, &block) if type == :around if current_method = @methods[index] yielded = false evaluate_method(object, current_method, *args) do yielded = true run_methods(object, context, index + 1, *args, &block) end throw :halt unless yielded else yield if block_given? end else @methods.each do |method| result = evaluate_method(object, method, *args) throw :halt if @terminator && @terminator.call(result) end end end
[ "def", "run_methods", "(", "object", ",", "context", "=", "{", "}", ",", "index", "=", "0", ",", "*", "args", ",", "&", "block", ")", "if", "type", "==", ":around", "if", "current_method", "=", "@methods", "[", "index", "]", "yielded", "=", "false", "evaluate_method", "(", "object", ",", "current_method", ",", "args", ")", "do", "yielded", "=", "true", "run_methods", "(", "object", ",", "context", ",", "index", "+", "1", ",", "args", ",", "block", ")", "end", "throw", ":halt", "unless", "yielded", "else", "yield", "if", "block_given?", "end", "else", "@methods", ".", "each", "do", "|", "method", "|", "result", "=", "evaluate_method", "(", "object", ",", "method", ",", "args", ")", "throw", ":halt", "if", "@terminator", "&&", "@terminator", ".", "call", "(", "result", ")", "end", "end", "end" ]
Runs all of the methods configured for this callback. When running +around+ callbacks, this will evaluate each method and yield when the last method has yielded. The callback will only halt if one of the methods does not yield. For all other types of callbacks, this will evaluate each method in order. The callback will only halt if the resulting value from the method passes the terminator.
[ "Runs", "all", "of", "the", "methods", "configured", "for", "this", "callback", "." ]
8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0
https://github.com/pluginaweek/state_machine/blob/8a3ba81801782ac4ef9d4ace1209d8d50ffccdb0/lib/state_machine/callback.rb#L176-L195
16,332
teampoltergeist/poltergeist
lib/capybara/poltergeist/web_socket_server.rb
Capybara::Poltergeist.WebSocketServer.accept
def accept @socket = server.accept @messages = {} @driver = ::WebSocket::Driver.server(self) @driver.on(:connect) { |_event| @driver.start } @driver.on(:message) do |event| command_id = JSON.parse(event.data)['command_id'] @messages[command_id] = event.data end end
ruby
def accept @socket = server.accept @messages = {} @driver = ::WebSocket::Driver.server(self) @driver.on(:connect) { |_event| @driver.start } @driver.on(:message) do |event| command_id = JSON.parse(event.data)['command_id'] @messages[command_id] = event.data end end
[ "def", "accept", "@socket", "=", "server", ".", "accept", "@messages", "=", "{", "}", "@driver", "=", "::", "WebSocket", "::", "Driver", ".", "server", "(", "self", ")", "@driver", ".", "on", "(", ":connect", ")", "{", "|", "_event", "|", "@driver", ".", "start", "}", "@driver", ".", "on", "(", ":message", ")", "do", "|", "event", "|", "command_id", "=", "JSON", ".", "parse", "(", "event", ".", "data", ")", "[", "'command_id'", "]", "@messages", "[", "command_id", "]", "=", "event", ".", "data", "end", "end" ]
Accept a client on the TCP server socket, then receive its initial HTTP request and use that to initialize a Web Socket.
[ "Accept", "a", "client", "on", "the", "TCP", "server", "socket", "then", "receive", "its", "initial", "HTTP", "request", "and", "use", "that", "to", "initialize", "a", "Web", "Socket", "." ]
6a27b00407b7845d2b19d4ec1a1e269c207f8957
https://github.com/teampoltergeist/poltergeist/blob/6a27b00407b7845d2b19d4ec1a1e269c207f8957/lib/capybara/poltergeist/web_socket_server.rb#L53-L63
16,333
teampoltergeist/poltergeist
lib/capybara/poltergeist/web_socket_server.rb
Capybara::Poltergeist.WebSocketServer.send
def send(cmd_id, message, accept_timeout = nil) accept unless connected? driver.text(message) receive(cmd_id, accept_timeout) rescue Errno::EWOULDBLOCK raise TimeoutError, message end
ruby
def send(cmd_id, message, accept_timeout = nil) accept unless connected? driver.text(message) receive(cmd_id, accept_timeout) rescue Errno::EWOULDBLOCK raise TimeoutError, message end
[ "def", "send", "(", "cmd_id", ",", "message", ",", "accept_timeout", "=", "nil", ")", "accept", "unless", "connected?", "driver", ".", "text", "(", "message", ")", "receive", "(", "cmd_id", ",", "accept_timeout", ")", "rescue", "Errno", "::", "EWOULDBLOCK", "raise", "TimeoutError", ",", "message", "end" ]
Send a message and block until there is a response
[ "Send", "a", "message", "and", "block", "until", "there", "is", "a", "response" ]
6a27b00407b7845d2b19d4ec1a1e269c207f8957
https://github.com/teampoltergeist/poltergeist/blob/6a27b00407b7845d2b19d4ec1a1e269c207f8957/lib/capybara/poltergeist/web_socket_server.rb#L94-L100
16,334
makandra/active_type
lib/active_type/util.rb
ActiveType.Util.using_single_table_inheritance?
def using_single_table_inheritance?(klass, record) inheritance_column = klass.inheritance_column record[inheritance_column].present? && record.has_attribute?(inheritance_column) end
ruby
def using_single_table_inheritance?(klass, record) inheritance_column = klass.inheritance_column record[inheritance_column].present? && record.has_attribute?(inheritance_column) end
[ "def", "using_single_table_inheritance?", "(", "klass", ",", "record", ")", "inheritance_column", "=", "klass", ".", "inheritance_column", "record", "[", "inheritance_column", "]", ".", "present?", "&&", "record", ".", "has_attribute?", "(", "inheritance_column", ")", "end" ]
Backport for Rails 3.2
[ "Backport", "for", "Rails", "3", ".", "2" ]
11212248ab668f4a9ddeef4df79e6029c95c5cee
https://github.com/makandra/active_type/blob/11212248ab668f4a9ddeef4df79e6029c95c5cee/lib/active_type/util.rb#L52-L55
16,335
chef/cheffish
lib/cheffish/node_properties.rb
Cheffish.NodeProperties.tag
def tag(*tags) attribute "tags" do |existing_tags| existing_tags ||= [] tags.each do |tag| if !existing_tags.include?(tag.to_s) existing_tags << tag.to_s end end existing_tags end end
ruby
def tag(*tags) attribute "tags" do |existing_tags| existing_tags ||= [] tags.each do |tag| if !existing_tags.include?(tag.to_s) existing_tags << tag.to_s end end existing_tags end end
[ "def", "tag", "(", "*", "tags", ")", "attribute", "\"tags\"", "do", "|", "existing_tags", "|", "existing_tags", "||=", "[", "]", "tags", ".", "each", "do", "|", "tag", "|", "if", "!", "existing_tags", ".", "include?", "(", "tag", ".", "to_s", ")", "existing_tags", "<<", "tag", ".", "to_s", "end", "end", "existing_tags", "end", "end" ]
Patchy tags tag 'webserver', 'apache', 'myenvironment'
[ "Patchy", "tags", "tag", "webserver", "apache", "myenvironment" ]
00e4475208c67d3578b83c2c987322e5fa70ec0f
https://github.com/chef/cheffish/blob/00e4475208c67d3578b83c2c987322e5fa70ec0f/lib/cheffish/node_properties.rb#L38-L48
16,336
jamesmartin/inline_svg
lib/inline_svg/transform_pipeline/transformations/transformation.rb
InlineSvg::TransformPipeline::Transformations.Transformation.with_svg
def with_svg(doc) doc = Nokogiri::XML::Document.parse( doc.to_html(encoding: "UTF-8"), nil, "UTF-8" ) svg = doc.at_css "svg" yield svg if svg && block_given? doc end
ruby
def with_svg(doc) doc = Nokogiri::XML::Document.parse( doc.to_html(encoding: "UTF-8"), nil, "UTF-8" ) svg = doc.at_css "svg" yield svg if svg && block_given? doc end
[ "def", "with_svg", "(", "doc", ")", "doc", "=", "Nokogiri", "::", "XML", "::", "Document", ".", "parse", "(", "doc", ".", "to_html", "(", "encoding", ":", "\"UTF-8\"", ")", ",", "nil", ",", "\"UTF-8\"", ")", "svg", "=", "doc", ".", "at_css", "\"svg\"", "yield", "svg", "if", "svg", "&&", "block_given?", "doc", "end" ]
Parses a document and yields the contained SVG nodeset to the given block if it exists. Returns a Nokogiri::XML::Document.
[ "Parses", "a", "document", "and", "yields", "the", "contained", "SVG", "nodeset", "to", "the", "given", "block", "if", "it", "exists", "." ]
9cdc503632eae4b7e44e9502c5af79e8f9aa85d2
https://github.com/jamesmartin/inline_svg/blob/9cdc503632eae4b7e44e9502c5af79e8f9aa85d2/lib/inline_svg/transform_pipeline/transformations/transformation.rb#L21-L28
16,337
jamesmartin/inline_svg
lib/inline_svg/cached_asset_file.rb
InlineSvg.CachedAssetFile.named
def named(asset_name) assets[key_for_asset(asset_name)] or raise InlineSvg::AssetFile::FileNotFound.new("Asset not found: #{asset_name}") end
ruby
def named(asset_name) assets[key_for_asset(asset_name)] or raise InlineSvg::AssetFile::FileNotFound.new("Asset not found: #{asset_name}") end
[ "def", "named", "(", "asset_name", ")", "assets", "[", "key_for_asset", "(", "asset_name", ")", "]", "or", "raise", "InlineSvg", "::", "AssetFile", "::", "FileNotFound", ".", "new", "(", "\"Asset not found: #{asset_name}\"", ")", "end" ]
For each of the given paths, recursively reads each asset and stores its contents alongside the full path to the asset. paths - One or more String representing directories on disk to search for asset files. Note: paths are searched recursively. filters - One or more Strings/Regexps to match assets against. Only assets matching all filters will be cached and available to load. Note: Specifying no filters will cache every file found in paths. Public: Finds the named asset and returns the contents as a string. asset_name - A string representing the name of the asset to load Returns: A String or raises InlineSvg::AssetFile::FileNotFound error
[ "For", "each", "of", "the", "given", "paths", "recursively", "reads", "each", "asset", "and", "stores", "its", "contents", "alongside", "the", "full", "path", "to", "the", "asset", "." ]
9cdc503632eae4b7e44e9502c5af79e8f9aa85d2
https://github.com/jamesmartin/inline_svg/blob/9cdc503632eae4b7e44e9502c5af79e8f9aa85d2/lib/inline_svg/cached_asset_file.rb#L28-L31
16,338
yob/pdf-reader
lib/pdf/reader.rb
PDF.Reader.doc_strings_to_utf8
def doc_strings_to_utf8(obj) case obj when ::Hash then {}.tap { |new_hash| obj.each do |key, value| new_hash[key] = doc_strings_to_utf8(value) end } when Array then obj.map { |item| doc_strings_to_utf8(item) } when String then if obj[0,2].unpack("C*") == [254, 255] utf16_to_utf8(obj) else pdfdoc_to_utf8(obj) end else @objects.deref(obj) end end
ruby
def doc_strings_to_utf8(obj) case obj when ::Hash then {}.tap { |new_hash| obj.each do |key, value| new_hash[key] = doc_strings_to_utf8(value) end } when Array then obj.map { |item| doc_strings_to_utf8(item) } when String then if obj[0,2].unpack("C*") == [254, 255] utf16_to_utf8(obj) else pdfdoc_to_utf8(obj) end else @objects.deref(obj) end end
[ "def", "doc_strings_to_utf8", "(", "obj", ")", "case", "obj", "when", "::", "Hash", "then", "{", "}", ".", "tap", "{", "|", "new_hash", "|", "obj", ".", "each", "do", "|", "key", ",", "value", "|", "new_hash", "[", "key", "]", "=", "doc_strings_to_utf8", "(", "value", ")", "end", "}", "when", "Array", "then", "obj", ".", "map", "{", "|", "item", "|", "doc_strings_to_utf8", "(", "item", ")", "}", "when", "String", "then", "if", "obj", "[", "0", ",", "2", "]", ".", "unpack", "(", "\"C*\"", ")", "==", "[", "254", ",", "255", "]", "utf16_to_utf8", "(", "obj", ")", "else", "pdfdoc_to_utf8", "(", "obj", ")", "end", "else", "@objects", ".", "deref", "(", "obj", ")", "end", "end" ]
recursively convert strings from outside a content stream into UTF-8
[ "recursively", "convert", "strings", "from", "outside", "a", "content", "stream", "into", "UTF", "-", "8" ]
2f91e4912c2ddd2d1ca447c2d1df9623fb833601
https://github.com/yob/pdf-reader/blob/2f91e4912c2ddd2d1ca447c2d1df9623fb833601/lib/pdf/reader.rb#L213-L232
16,339
yob/pdf-reader
examples/extract_images.rb
ExtractImages.Tiff.save_group_four
def save_group_four(filename) k = stream.hash[:DecodeParms][:K] h = stream.hash[:Height] w = stream.hash[:Width] bpc = stream.hash[:BitsPerComponent] mask = stream.hash[:ImageMask] len = stream.hash[:Length] cols = stream.hash[:DecodeParms][:Columns] puts "#{filename}: h=#{h}, w=#{w}, bpc=#{bpc}, mask=#{mask}, len=#{len}, cols=#{cols}, k=#{k}" # Synthesize a TIFF header long_tag = lambda {|tag, value| [ tag, 4, 1, value ].pack( "ssII" ) } short_tag = lambda {|tag, value| [ tag, 3, 1, value ].pack( "ssII" ) } # header = byte order, version magic, offset of directory, directory count, # followed by a series of tags containing metadata: 259 is a magic number for # the compression type; 273 is the offset of the image data. tiff = [ 73, 73, 42, 8, 5 ].pack("ccsIs") \ + short_tag.call( 256, cols ) \ + short_tag.call( 257, h ) \ + short_tag.call( 259, 4 ) \ + long_tag.call( 273, (10 + (5*12) + 4) ) \ + long_tag.call( 279, len) \ + [0].pack("I") \ + stream.data File.open(filename, "wb") { |file| file.write tiff } end
ruby
def save_group_four(filename) k = stream.hash[:DecodeParms][:K] h = stream.hash[:Height] w = stream.hash[:Width] bpc = stream.hash[:BitsPerComponent] mask = stream.hash[:ImageMask] len = stream.hash[:Length] cols = stream.hash[:DecodeParms][:Columns] puts "#{filename}: h=#{h}, w=#{w}, bpc=#{bpc}, mask=#{mask}, len=#{len}, cols=#{cols}, k=#{k}" # Synthesize a TIFF header long_tag = lambda {|tag, value| [ tag, 4, 1, value ].pack( "ssII" ) } short_tag = lambda {|tag, value| [ tag, 3, 1, value ].pack( "ssII" ) } # header = byte order, version magic, offset of directory, directory count, # followed by a series of tags containing metadata: 259 is a magic number for # the compression type; 273 is the offset of the image data. tiff = [ 73, 73, 42, 8, 5 ].pack("ccsIs") \ + short_tag.call( 256, cols ) \ + short_tag.call( 257, h ) \ + short_tag.call( 259, 4 ) \ + long_tag.call( 273, (10 + (5*12) + 4) ) \ + long_tag.call( 279, len) \ + [0].pack("I") \ + stream.data File.open(filename, "wb") { |file| file.write tiff } end
[ "def", "save_group_four", "(", "filename", ")", "k", "=", "stream", ".", "hash", "[", ":DecodeParms", "]", "[", ":K", "]", "h", "=", "stream", ".", "hash", "[", ":Height", "]", "w", "=", "stream", ".", "hash", "[", ":Width", "]", "bpc", "=", "stream", ".", "hash", "[", ":BitsPerComponent", "]", "mask", "=", "stream", ".", "hash", "[", ":ImageMask", "]", "len", "=", "stream", ".", "hash", "[", ":Length", "]", "cols", "=", "stream", ".", "hash", "[", ":DecodeParms", "]", "[", ":Columns", "]", "puts", "\"#{filename}: h=#{h}, w=#{w}, bpc=#{bpc}, mask=#{mask}, len=#{len}, cols=#{cols}, k=#{k}\"", "# Synthesize a TIFF header", "long_tag", "=", "lambda", "{", "|", "tag", ",", "value", "|", "[", "tag", ",", "4", ",", "1", ",", "value", "]", ".", "pack", "(", "\"ssII\"", ")", "}", "short_tag", "=", "lambda", "{", "|", "tag", ",", "value", "|", "[", "tag", ",", "3", ",", "1", ",", "value", "]", ".", "pack", "(", "\"ssII\"", ")", "}", "# header = byte order, version magic, offset of directory, directory count,", "# followed by a series of tags containing metadata: 259 is a magic number for", "# the compression type; 273 is the offset of the image data.", "tiff", "=", "[", "73", ",", "73", ",", "42", ",", "8", ",", "5", "]", ".", "pack", "(", "\"ccsIs\"", ")", "+", "short_tag", ".", "call", "(", "256", ",", "cols", ")", "+", "short_tag", ".", "call", "(", "257", ",", "h", ")", "+", "short_tag", ".", "call", "(", "259", ",", "4", ")", "+", "long_tag", ".", "call", "(", "273", ",", "(", "10", "+", "(", "5", "*", "12", ")", "+", "4", ")", ")", "+", "long_tag", ".", "call", "(", "279", ",", "len", ")", "+", "[", "0", "]", ".", "pack", "(", "\"I\"", ")", "+", "stream", ".", "data", "File", ".", "open", "(", "filename", ",", "\"wb\"", ")", "{", "|", "file", "|", "file", ".", "write", "tiff", "}", "end" ]
Group 4, 2D
[ "Group", "4", "2D" ]
2f91e4912c2ddd2d1ca447c2d1df9623fb833601
https://github.com/yob/pdf-reader/blob/2f91e4912c2ddd2d1ca447c2d1df9623fb833601/examples/extract_images.rb#L196-L221
16,340
rails/rails-observers
lib/rails/observers/active_model/observing.rb
ActiveModel.Observer.disabled_for?
def disabled_for?(object) #:nodoc: klass = object.class return false unless klass.respond_to?(:observers) klass.observers.disabled_for?(self) end
ruby
def disabled_for?(object) #:nodoc: klass = object.class return false unless klass.respond_to?(:observers) klass.observers.disabled_for?(self) end
[ "def", "disabled_for?", "(", "object", ")", "#:nodoc:", "klass", "=", "object", ".", "class", "return", "false", "unless", "klass", ".", "respond_to?", "(", ":observers", ")", "klass", ".", "observers", ".", "disabled_for?", "(", "self", ")", "end" ]
Returns true if notifications are disabled for this object.
[ "Returns", "true", "if", "notifications", "are", "disabled", "for", "this", "object", "." ]
25eb685d68e8fcd0675fff33852ee341f7ec2a53
https://github.com/rails/rails-observers/blob/25eb685d68e8fcd0675fff33852ee341f7ec2a53/lib/rails/observers/active_model/observing.rb#L368-L372
16,341
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.copy
def copy(from) @scalar = from.scalar @numerator = from.numerator @denominator = from.denominator @base = from.base? @signature = from.signature @base_scalar = from.base_scalar @unit_name = begin from.unit_name rescue nil end self end
ruby
def copy(from) @scalar = from.scalar @numerator = from.numerator @denominator = from.denominator @base = from.base? @signature = from.signature @base_scalar = from.base_scalar @unit_name = begin from.unit_name rescue nil end self end
[ "def", "copy", "(", "from", ")", "@scalar", "=", "from", ".", "scalar", "@numerator", "=", "from", ".", "numerator", "@denominator", "=", "from", ".", "denominator", "@base", "=", "from", ".", "base?", "@signature", "=", "from", ".", "signature", "@base_scalar", "=", "from", ".", "base_scalar", "@unit_name", "=", "begin", "from", ".", "unit_name", "rescue", "nil", "end", "self", "end" ]
Used to copy one unit to another @param [Unit] from Unit to copy definition from @return [Unit]
[ "Used", "to", "copy", "one", "unit", "to", "another" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L430-L443
16,342
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.base?
def base? return @base if defined? @base @base = (@numerator + @denominator) .compact .uniq .map { |unit| RubyUnits::Unit.definition(unit) } .all? { |element| element.unity? || element.base? } @base end
ruby
def base? return @base if defined? @base @base = (@numerator + @denominator) .compact .uniq .map { |unit| RubyUnits::Unit.definition(unit) } .all? { |element| element.unity? || element.base? } @base end
[ "def", "base?", "return", "@base", "if", "defined?", "@base", "@base", "=", "(", "@numerator", "+", "@denominator", ")", ".", "compact", ".", "uniq", ".", "map", "{", "|", "unit", "|", "RubyUnits", "::", "Unit", ".", "definition", "(", "unit", ")", "}", ".", "all?", "{", "|", "element", "|", "element", ".", "unity?", "||", "element", ".", "base?", "}", "@base", "end" ]
Is this unit in base form? @return [Boolean]
[ "Is", "this", "unit", "in", "base", "form?" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L563-L571
16,343
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.to_base
def to_base return self if base? if @@unit_map[units] =~ /\A<(?:temp|deg)[CRF]>\Z/ @signature = @@kinds.key(:temperature) base = if temperature? convert_to('tempK') elsif degree? convert_to('degK') end return base end cached = (begin (@@base_unit_cache[units] * scalar) rescue nil end) return cached if cached num = [] den = [] q = Rational(1) @numerator.compact.each do |num_unit| if @@prefix_values[num_unit] q *= @@prefix_values[num_unit] else q *= @@unit_values[num_unit][:scalar] if @@unit_values[num_unit] num << @@unit_values[num_unit][:numerator] if @@unit_values[num_unit] && @@unit_values[num_unit][:numerator] den << @@unit_values[num_unit][:denominator] if @@unit_values[num_unit] && @@unit_values[num_unit][:denominator] end end @denominator.compact.each do |num_unit| if @@prefix_values[num_unit] q /= @@prefix_values[num_unit] else q /= @@unit_values[num_unit][:scalar] if @@unit_values[num_unit] den << @@unit_values[num_unit][:numerator] if @@unit_values[num_unit] && @@unit_values[num_unit][:numerator] num << @@unit_values[num_unit][:denominator] if @@unit_values[num_unit] && @@unit_values[num_unit][:denominator] end end num = num.flatten.compact den = den.flatten.compact num = UNITY_ARRAY if num.empty? base = RubyUnits::Unit.new(RubyUnits::Unit.eliminate_terms(q, num, den)) @@base_unit_cache[units] = base base * @scalar end
ruby
def to_base return self if base? if @@unit_map[units] =~ /\A<(?:temp|deg)[CRF]>\Z/ @signature = @@kinds.key(:temperature) base = if temperature? convert_to('tempK') elsif degree? convert_to('degK') end return base end cached = (begin (@@base_unit_cache[units] * scalar) rescue nil end) return cached if cached num = [] den = [] q = Rational(1) @numerator.compact.each do |num_unit| if @@prefix_values[num_unit] q *= @@prefix_values[num_unit] else q *= @@unit_values[num_unit][:scalar] if @@unit_values[num_unit] num << @@unit_values[num_unit][:numerator] if @@unit_values[num_unit] && @@unit_values[num_unit][:numerator] den << @@unit_values[num_unit][:denominator] if @@unit_values[num_unit] && @@unit_values[num_unit][:denominator] end end @denominator.compact.each do |num_unit| if @@prefix_values[num_unit] q /= @@prefix_values[num_unit] else q /= @@unit_values[num_unit][:scalar] if @@unit_values[num_unit] den << @@unit_values[num_unit][:numerator] if @@unit_values[num_unit] && @@unit_values[num_unit][:numerator] num << @@unit_values[num_unit][:denominator] if @@unit_values[num_unit] && @@unit_values[num_unit][:denominator] end end num = num.flatten.compact den = den.flatten.compact num = UNITY_ARRAY if num.empty? base = RubyUnits::Unit.new(RubyUnits::Unit.eliminate_terms(q, num, den)) @@base_unit_cache[units] = base base * @scalar end
[ "def", "to_base", "return", "self", "if", "base?", "if", "@@unit_map", "[", "units", "]", "=~", "/", "\\A", "\\Z", "/", "@signature", "=", "@@kinds", ".", "key", "(", ":temperature", ")", "base", "=", "if", "temperature?", "convert_to", "(", "'tempK'", ")", "elsif", "degree?", "convert_to", "(", "'degK'", ")", "end", "return", "base", "end", "cached", "=", "(", "begin", "(", "@@base_unit_cache", "[", "units", "]", "*", "scalar", ")", "rescue", "nil", "end", ")", "return", "cached", "if", "cached", "num", "=", "[", "]", "den", "=", "[", "]", "q", "=", "Rational", "(", "1", ")", "@numerator", ".", "compact", ".", "each", "do", "|", "num_unit", "|", "if", "@@prefix_values", "[", "num_unit", "]", "q", "*=", "@@prefix_values", "[", "num_unit", "]", "else", "q", "*=", "@@unit_values", "[", "num_unit", "]", "[", ":scalar", "]", "if", "@@unit_values", "[", "num_unit", "]", "num", "<<", "@@unit_values", "[", "num_unit", "]", "[", ":numerator", "]", "if", "@@unit_values", "[", "num_unit", "]", "&&", "@@unit_values", "[", "num_unit", "]", "[", ":numerator", "]", "den", "<<", "@@unit_values", "[", "num_unit", "]", "[", ":denominator", "]", "if", "@@unit_values", "[", "num_unit", "]", "&&", "@@unit_values", "[", "num_unit", "]", "[", ":denominator", "]", "end", "end", "@denominator", ".", "compact", ".", "each", "do", "|", "num_unit", "|", "if", "@@prefix_values", "[", "num_unit", "]", "q", "/=", "@@prefix_values", "[", "num_unit", "]", "else", "q", "/=", "@@unit_values", "[", "num_unit", "]", "[", ":scalar", "]", "if", "@@unit_values", "[", "num_unit", "]", "den", "<<", "@@unit_values", "[", "num_unit", "]", "[", ":numerator", "]", "if", "@@unit_values", "[", "num_unit", "]", "&&", "@@unit_values", "[", "num_unit", "]", "[", ":numerator", "]", "num", "<<", "@@unit_values", "[", "num_unit", "]", "[", ":denominator", "]", "if", "@@unit_values", "[", "num_unit", "]", "&&", "@@unit_values", "[", "num_unit", "]", "[", ":denominator", "]", "end", "end", "num", "=", "num", ".", "flatten", ".", "compact", "den", "=", "den", ".", "flatten", ".", "compact", "num", "=", "UNITY_ARRAY", "if", "num", ".", "empty?", "base", "=", "RubyUnits", "::", "Unit", ".", "new", "(", "RubyUnits", "::", "Unit", ".", "eliminate_terms", "(", "q", ",", "num", ",", "den", ")", ")", "@@base_unit_cache", "[", "units", "]", "=", "base", "base", "*", "@scalar", "end" ]
convert to base SI units results of the conversion are cached so subsequent calls to this will be fast @return [Unit] @todo this is brittle as it depends on the display_name of a unit, which can be changed
[ "convert", "to", "base", "SI", "units", "results", "of", "the", "conversion", "are", "cached", "so", "subsequent", "calls", "to", "this", "will", "be", "fast" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L579-L626
16,344
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.to_s
def to_s(target_units = nil) out = @output[target_units] return out if out separator = RubyUnits.configuration.separator case target_units when :ft inches = convert_to('in').scalar.to_int out = "#{(inches / 12).truncate}\'#{(inches % 12).round}\"" when :lbs ounces = convert_to('oz').scalar.to_int out = "#{(ounces / 16).truncate}#{separator}lbs, #{(ounces % 16).round}#{separator}oz" when :stone pounds = convert_to('lbs').scalar.to_int out = "#{(pounds / 14).truncate}#{separator}stone, #{(pounds % 14).round}#{separator}lb" when String out = case target_units.strip when /\A\s*\Z/ # whitespace only '' when /(%[\-+\.\w#]+)\s*(.+)*/ # format string like '%0.2f in' begin if Regexp.last_match(2) # unit specified, need to convert convert_to(Regexp.last_match(2)).to_s(Regexp.last_match(1)) else "#{Regexp.last_match(1) % @scalar}#{separator}#{Regexp.last_match(2) || units}".strip end rescue # parse it like a strftime format string (DateTime.new(0) + self).strftime(target_units) end when /(\S+)/ # unit only 'mm' or '1/mm' convert_to(Regexp.last_match(1)).to_s else raise 'unhandled case' end else out = case @scalar when Complex "#{@scalar}#{separator}#{units}" when Rational "#{@scalar == @scalar.to_i ? @scalar.to_i : @scalar}#{separator}#{units}" else "#{'%g' % @scalar}#{separator}#{units}" end.strip end @output[target_units] = out out end
ruby
def to_s(target_units = nil) out = @output[target_units] return out if out separator = RubyUnits.configuration.separator case target_units when :ft inches = convert_to('in').scalar.to_int out = "#{(inches / 12).truncate}\'#{(inches % 12).round}\"" when :lbs ounces = convert_to('oz').scalar.to_int out = "#{(ounces / 16).truncate}#{separator}lbs, #{(ounces % 16).round}#{separator}oz" when :stone pounds = convert_to('lbs').scalar.to_int out = "#{(pounds / 14).truncate}#{separator}stone, #{(pounds % 14).round}#{separator}lb" when String out = case target_units.strip when /\A\s*\Z/ # whitespace only '' when /(%[\-+\.\w#]+)\s*(.+)*/ # format string like '%0.2f in' begin if Regexp.last_match(2) # unit specified, need to convert convert_to(Regexp.last_match(2)).to_s(Regexp.last_match(1)) else "#{Regexp.last_match(1) % @scalar}#{separator}#{Regexp.last_match(2) || units}".strip end rescue # parse it like a strftime format string (DateTime.new(0) + self).strftime(target_units) end when /(\S+)/ # unit only 'mm' or '1/mm' convert_to(Regexp.last_match(1)).to_s else raise 'unhandled case' end else out = case @scalar when Complex "#{@scalar}#{separator}#{units}" when Rational "#{@scalar == @scalar.to_i ? @scalar.to_i : @scalar}#{separator}#{units}" else "#{'%g' % @scalar}#{separator}#{units}" end.strip end @output[target_units] = out out end
[ "def", "to_s", "(", "target_units", "=", "nil", ")", "out", "=", "@output", "[", "target_units", "]", "return", "out", "if", "out", "separator", "=", "RubyUnits", ".", "configuration", ".", "separator", "case", "target_units", "when", ":ft", "inches", "=", "convert_to", "(", "'in'", ")", ".", "scalar", ".", "to_int", "out", "=", "\"#{(inches / 12).truncate}\\'#{(inches % 12).round}\\\"\"", "when", ":lbs", "ounces", "=", "convert_to", "(", "'oz'", ")", ".", "scalar", ".", "to_int", "out", "=", "\"#{(ounces / 16).truncate}#{separator}lbs, #{(ounces % 16).round}#{separator}oz\"", "when", ":stone", "pounds", "=", "convert_to", "(", "'lbs'", ")", ".", "scalar", ".", "to_int", "out", "=", "\"#{(pounds / 14).truncate}#{separator}stone, #{(pounds % 14).round}#{separator}lb\"", "when", "String", "out", "=", "case", "target_units", ".", "strip", "when", "/", "\\A", "\\s", "\\Z", "/", "# whitespace only", "''", "when", "/", "\\-", "\\.", "\\w", "\\s", "/", "# format string like '%0.2f in'", "begin", "if", "Regexp", ".", "last_match", "(", "2", ")", "# unit specified, need to convert", "convert_to", "(", "Regexp", ".", "last_match", "(", "2", ")", ")", ".", "to_s", "(", "Regexp", ".", "last_match", "(", "1", ")", ")", "else", "\"#{Regexp.last_match(1) % @scalar}#{separator}#{Regexp.last_match(2) || units}\"", ".", "strip", "end", "rescue", "# parse it like a strftime format string", "(", "DateTime", ".", "new", "(", "0", ")", "+", "self", ")", ".", "strftime", "(", "target_units", ")", "end", "when", "/", "\\S", "/", "# unit only 'mm' or '1/mm'", "convert_to", "(", "Regexp", ".", "last_match", "(", "1", ")", ")", ".", "to_s", "else", "raise", "'unhandled case'", "end", "else", "out", "=", "case", "@scalar", "when", "Complex", "\"#{@scalar}#{separator}#{units}\"", "when", "Rational", "\"#{@scalar == @scalar.to_i ? @scalar.to_i : @scalar}#{separator}#{units}\"", "else", "\"#{'%g' % @scalar}#{separator}#{units}\"", "end", ".", "strip", "end", "@output", "[", "target_units", "]", "=", "out", "out", "end" ]
Generate human readable output. If the name of a unit is passed, the unit will first be converted to the target unit before output. some named conversions are available @example unit.to_s(:ft) - outputs in feet and inches (e.g., 6'4") unit.to_s(:lbs) - outputs in pounds and ounces (e.g, 8 lbs, 8 oz) You can also pass a standard format string (i.e., '%0.2f') or a strftime format string. output is cached so subsequent calls for the same format will be fast @note Rational scalars that are equal to an integer will be represented as integers (i.e, 6/1 => 6, 4/2 => 2, etc..) @param [Symbol] target_units @return [String]
[ "Generate", "human", "readable", "output", ".", "If", "the", "name", "of", "a", "unit", "is", "passed", "the", "unit", "will", "first", "be", "converted", "to", "the", "target", "unit", "before", "output", ".", "some", "named", "conversions", "are", "available" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L646-L691
16,345
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.=~
def =~(other) case other when Unit signature == other.signature else begin x, y = coerce(other) return x =~ y rescue ArgumentError return false end end end
ruby
def =~(other) case other when Unit signature == other.signature else begin x, y = coerce(other) return x =~ y rescue ArgumentError return false end end end
[ "def", "=~", "(", "other", ")", "case", "other", "when", "Unit", "signature", "==", "other", ".", "signature", "else", "begin", "x", ",", "y", "=", "coerce", "(", "other", ")", "return", "x", "=~", "y", "rescue", "ArgumentError", "return", "false", "end", "end", "end" ]
Compare two Unit objects. Throws an exception if they are not of compatible types. Comparisons are done based on the value of the unit in base SI units. @param [Object] other @return [-1|0|1|nil] @raise [NoMethodError] when other does not define <=> @raise [ArgumentError] when units are not compatible Compare Units for equality this is necessary mostly for Complex units. Complex units do not have a <=> operator so we define this one here so that we can properly check complex units for equality. Units of incompatible types are not equal, except when they are both zero and neither is a temperature Equality checks can be tricky since round off errors may make essentially equivalent units appear to be different. @param [Object] other @return [Boolean] check to see if units are compatible, but not the scalar part this check is done by comparing signatures for performance reasons if passed a string, it will create a unit object with the string and then do the comparison @example this permits a syntax like: unit =~ "mm" @note if you want to do a regexp comparison of the unit string do this ... unit.units =~ /regexp/ @param [Object] other @return [Boolean]
[ "Compare", "two", "Unit", "objects", ".", "Throws", "an", "exception", "if", "they", "are", "not", "of", "compatible", "types", ".", "Comparisons", "are", "done", "based", "on", "the", "value", "of", "the", "unit", "in", "base", "SI", "units", "." ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L787-L799
16,346
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.+
def +(other) case other when Unit if zero? other.dup elsif self =~ other raise ArgumentError, 'Cannot add two temperatures' if [self, other].all?(&:temperature?) if [self, other].any?(&:temperature?) if temperature? RubyUnits::Unit.new(scalar: (scalar + other.convert_to(temperature_scale).scalar), numerator: @numerator, denominator: @denominator, signature: @signature) else RubyUnits::Unit.new(scalar: (other.scalar + convert_to(other.temperature_scale).scalar), numerator: other.numerator, denominator: other.denominator, signature: other.signature) end else RubyUnits::Unit.new(scalar: (base_scalar + other.base_scalar), numerator: base.numerator, denominator: base.denominator, signature: @signature).convert_to(self) end else raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')" end when Date, Time raise ArgumentError, 'Date and Time objects represent fixed points in time and cannot be added to a Unit' else x, y = coerce(other) y + x end end
ruby
def +(other) case other when Unit if zero? other.dup elsif self =~ other raise ArgumentError, 'Cannot add two temperatures' if [self, other].all?(&:temperature?) if [self, other].any?(&:temperature?) if temperature? RubyUnits::Unit.new(scalar: (scalar + other.convert_to(temperature_scale).scalar), numerator: @numerator, denominator: @denominator, signature: @signature) else RubyUnits::Unit.new(scalar: (other.scalar + convert_to(other.temperature_scale).scalar), numerator: other.numerator, denominator: other.denominator, signature: other.signature) end else RubyUnits::Unit.new(scalar: (base_scalar + other.base_scalar), numerator: base.numerator, denominator: base.denominator, signature: @signature).convert_to(self) end else raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')" end when Date, Time raise ArgumentError, 'Date and Time objects represent fixed points in time and cannot be added to a Unit' else x, y = coerce(other) y + x end end
[ "def", "+", "(", "other", ")", "case", "other", "when", "Unit", "if", "zero?", "other", ".", "dup", "elsif", "self", "=~", "other", "raise", "ArgumentError", ",", "'Cannot add two temperatures'", "if", "[", "self", ",", "other", "]", ".", "all?", "(", ":temperature?", ")", "if", "[", "self", ",", "other", "]", ".", "any?", "(", ":temperature?", ")", "if", "temperature?", "RubyUnits", "::", "Unit", ".", "new", "(", "scalar", ":", "(", "scalar", "+", "other", ".", "convert_to", "(", "temperature_scale", ")", ".", "scalar", ")", ",", "numerator", ":", "@numerator", ",", "denominator", ":", "@denominator", ",", "signature", ":", "@signature", ")", "else", "RubyUnits", "::", "Unit", ".", "new", "(", "scalar", ":", "(", "other", ".", "scalar", "+", "convert_to", "(", "other", ".", "temperature_scale", ")", ".", "scalar", ")", ",", "numerator", ":", "other", ".", "numerator", ",", "denominator", ":", "other", ".", "denominator", ",", "signature", ":", "other", ".", "signature", ")", "end", "else", "RubyUnits", "::", "Unit", ".", "new", "(", "scalar", ":", "(", "base_scalar", "+", "other", ".", "base_scalar", ")", ",", "numerator", ":", "base", ".", "numerator", ",", "denominator", ":", "base", ".", "denominator", ",", "signature", ":", "@signature", ")", ".", "convert_to", "(", "self", ")", "end", "else", "raise", "ArgumentError", ",", "\"Incompatible Units ('#{self}' not compatible with '#{other}')\"", "end", "when", "Date", ",", "Time", "raise", "ArgumentError", ",", "'Date and Time objects represent fixed points in time and cannot be added to a Unit'", "else", "x", ",", "y", "=", "coerce", "(", "other", ")", "y", "+", "x", "end", "end" ]
Add two units together. Result is same units as receiver and scalar and base_scalar are updated appropriately throws an exception if the units are not compatible. It is possible to add Time objects to units of time @param [Object] other @return [Unit] @raise [ArgumentError] when two temperatures are added @raise [ArgumentError] when units are not compatible @raise [ArgumentError] when adding a fixed time or date to a time span
[ "Add", "two", "units", "together", ".", "Result", "is", "same", "units", "as", "receiver", "and", "scalar", "and", "base_scalar", "are", "updated", "appropriately", "throws", "an", "exception", "if", "the", "units", "are", "not", "compatible", ".", "It", "is", "possible", "to", "add", "Time", "objects", "to", "units", "of", "time" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L835-L860
16,347
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.*
def *(other) case other when Unit raise ArgumentError, 'Cannot multiply by temperatures' if [other, self].any?(&:temperature?) opts = RubyUnits::Unit.eliminate_terms(@scalar * other.scalar, @numerator + other.numerator, @denominator + other.denominator) opts[:signature] = @signature + other.signature RubyUnits::Unit.new(opts) when Numeric RubyUnits::Unit.new(scalar: @scalar * other, numerator: @numerator, denominator: @denominator, signature: @signature) else x, y = coerce(other) x * y end end
ruby
def *(other) case other when Unit raise ArgumentError, 'Cannot multiply by temperatures' if [other, self].any?(&:temperature?) opts = RubyUnits::Unit.eliminate_terms(@scalar * other.scalar, @numerator + other.numerator, @denominator + other.denominator) opts[:signature] = @signature + other.signature RubyUnits::Unit.new(opts) when Numeric RubyUnits::Unit.new(scalar: @scalar * other, numerator: @numerator, denominator: @denominator, signature: @signature) else x, y = coerce(other) x * y end end
[ "def", "*", "(", "other", ")", "case", "other", "when", "Unit", "raise", "ArgumentError", ",", "'Cannot multiply by temperatures'", "if", "[", "other", ",", "self", "]", ".", "any?", "(", ":temperature?", ")", "opts", "=", "RubyUnits", "::", "Unit", ".", "eliminate_terms", "(", "@scalar", "*", "other", ".", "scalar", ",", "@numerator", "+", "other", ".", "numerator", ",", "@denominator", "+", "other", ".", "denominator", ")", "opts", "[", ":signature", "]", "=", "@signature", "+", "other", ".", "signature", "RubyUnits", "::", "Unit", ".", "new", "(", "opts", ")", "when", "Numeric", "RubyUnits", "::", "Unit", ".", "new", "(", "scalar", ":", "@scalar", "*", "other", ",", "numerator", ":", "@numerator", ",", "denominator", ":", "@denominator", ",", "signature", ":", "@signature", ")", "else", "x", ",", "y", "=", "coerce", "(", "other", ")", "x", "*", "y", "end", "end" ]
Multiply two units. @param [Numeric] other @return [Unit] @raise [ArgumentError] when attempting to multiply two temperatures
[ "Multiply", "two", "units", "." ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L902-L915
16,348
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit./
def /(other) case other when Unit raise ZeroDivisionError if other.zero? raise ArgumentError, 'Cannot divide with temperatures' if [other, self].any?(&:temperature?) sc = Rational(@scalar, other.scalar) sc = sc.numerator if sc.denominator == 1 opts = RubyUnits::Unit.eliminate_terms(sc, @numerator + other.denominator, @denominator + other.numerator) opts[:signature] = @signature - other.signature RubyUnits::Unit.new(opts) when Numeric raise ZeroDivisionError if other.zero? sc = Rational(@scalar, other) sc = sc.numerator if sc.denominator == 1 RubyUnits::Unit.new(scalar: sc, numerator: @numerator, denominator: @denominator, signature: @signature) else x, y = coerce(other) y / x end end
ruby
def /(other) case other when Unit raise ZeroDivisionError if other.zero? raise ArgumentError, 'Cannot divide with temperatures' if [other, self].any?(&:temperature?) sc = Rational(@scalar, other.scalar) sc = sc.numerator if sc.denominator == 1 opts = RubyUnits::Unit.eliminate_terms(sc, @numerator + other.denominator, @denominator + other.numerator) opts[:signature] = @signature - other.signature RubyUnits::Unit.new(opts) when Numeric raise ZeroDivisionError if other.zero? sc = Rational(@scalar, other) sc = sc.numerator if sc.denominator == 1 RubyUnits::Unit.new(scalar: sc, numerator: @numerator, denominator: @denominator, signature: @signature) else x, y = coerce(other) y / x end end
[ "def", "/", "(", "other", ")", "case", "other", "when", "Unit", "raise", "ZeroDivisionError", "if", "other", ".", "zero?", "raise", "ArgumentError", ",", "'Cannot divide with temperatures'", "if", "[", "other", ",", "self", "]", ".", "any?", "(", ":temperature?", ")", "sc", "=", "Rational", "(", "@scalar", ",", "other", ".", "scalar", ")", "sc", "=", "sc", ".", "numerator", "if", "sc", ".", "denominator", "==", "1", "opts", "=", "RubyUnits", "::", "Unit", ".", "eliminate_terms", "(", "sc", ",", "@numerator", "+", "other", ".", "denominator", ",", "@denominator", "+", "other", ".", "numerator", ")", "opts", "[", ":signature", "]", "=", "@signature", "-", "other", ".", "signature", "RubyUnits", "::", "Unit", ".", "new", "(", "opts", ")", "when", "Numeric", "raise", "ZeroDivisionError", "if", "other", ".", "zero?", "sc", "=", "Rational", "(", "@scalar", ",", "other", ")", "sc", "=", "sc", ".", "numerator", "if", "sc", ".", "denominator", "==", "1", "RubyUnits", "::", "Unit", ".", "new", "(", "scalar", ":", "sc", ",", "numerator", ":", "@numerator", ",", "denominator", ":", "@denominator", ",", "signature", ":", "@signature", ")", "else", "x", ",", "y", "=", "coerce", "(", "other", ")", "y", "/", "x", "end", "end" ]
Divide two units. Throws an exception if divisor is 0 @param [Numeric] other @return [Unit] @raise [ZeroDivisionError] if divisor is zero @raise [ArgumentError] if attempting to divide a temperature by another temperature
[ "Divide", "two", "units", ".", "Throws", "an", "exception", "if", "divisor", "is", "0" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L923-L942
16,349
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.divmod
def divmod(other) raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')" unless self =~ other return scalar.divmod(other.scalar) if units == other.units to_base.scalar.divmod(other.to_base.scalar) end
ruby
def divmod(other) raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')" unless self =~ other return scalar.divmod(other.scalar) if units == other.units to_base.scalar.divmod(other.to_base.scalar) end
[ "def", "divmod", "(", "other", ")", "raise", "ArgumentError", ",", "\"Incompatible Units ('#{self}' not compatible with '#{other}')\"", "unless", "self", "=~", "other", "return", "scalar", ".", "divmod", "(", "other", ".", "scalar", ")", "if", "units", "==", "other", ".", "units", "to_base", ".", "scalar", ".", "divmod", "(", "other", ".", "to_base", ".", "scalar", ")", "end" ]
divide two units and return quotient and remainder when both units are in the same units we just use divmod on the raw scalars otherwise we use the scalar of the base unit which will be a float @param [Object] other @return [Array]
[ "divide", "two", "units", "and", "return", "quotient", "and", "remainder", "when", "both", "units", "are", "in", "the", "same", "units", "we", "just", "use", "divmod", "on", "the", "raw", "scalars", "otherwise", "we", "use", "the", "scalar", "of", "the", "base", "unit", "which", "will", "be", "a", "float" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L949-L953
16,350
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.**
def **(other) raise ArgumentError, 'Cannot raise a temperature to a power' if temperature? if other.is_a?(Numeric) return inverse if other == -1 return self if other == 1 return 1 if other.zero? end case other when Rational return power(other.numerator).root(other.denominator) when Integer return power(other) when Float return self**other.to_i if other == other.to_i valid = (1..9).map { |n| Rational(1, n) } raise ArgumentError, 'Not a n-th root (1..9), use 1/n' unless valid.include? other.abs return root(Rational(1, other).to_int) when Complex raise ArgumentError, 'exponentiation of complex numbers is not supported.' else raise ArgumentError, 'Invalid Exponent' end end
ruby
def **(other) raise ArgumentError, 'Cannot raise a temperature to a power' if temperature? if other.is_a?(Numeric) return inverse if other == -1 return self if other == 1 return 1 if other.zero? end case other when Rational return power(other.numerator).root(other.denominator) when Integer return power(other) when Float return self**other.to_i if other == other.to_i valid = (1..9).map { |n| Rational(1, n) } raise ArgumentError, 'Not a n-th root (1..9), use 1/n' unless valid.include? other.abs return root(Rational(1, other).to_int) when Complex raise ArgumentError, 'exponentiation of complex numbers is not supported.' else raise ArgumentError, 'Invalid Exponent' end end
[ "def", "**", "(", "other", ")", "raise", "ArgumentError", ",", "'Cannot raise a temperature to a power'", "if", "temperature?", "if", "other", ".", "is_a?", "(", "Numeric", ")", "return", "inverse", "if", "other", "==", "-", "1", "return", "self", "if", "other", "==", "1", "return", "1", "if", "other", ".", "zero?", "end", "case", "other", "when", "Rational", "return", "power", "(", "other", ".", "numerator", ")", ".", "root", "(", "other", ".", "denominator", ")", "when", "Integer", "return", "power", "(", "other", ")", "when", "Float", "return", "self", "**", "other", ".", "to_i", "if", "other", "==", "other", ".", "to_i", "valid", "=", "(", "1", "..", "9", ")", ".", "map", "{", "|", "n", "|", "Rational", "(", "1", ",", "n", ")", "}", "raise", "ArgumentError", ",", "'Not a n-th root (1..9), use 1/n'", "unless", "valid", ".", "include?", "other", ".", "abs", "return", "root", "(", "Rational", "(", "1", ",", "other", ")", ".", "to_int", ")", "when", "Complex", "raise", "ArgumentError", ",", "'exponentiation of complex numbers is not supported.'", "else", "raise", "ArgumentError", ",", "'Invalid Exponent'", "end", "end" ]
Exponentiate. Only takes integer powers. Note that anything raised to the power of 0 results in a Unit object with a scalar of 1, and no units. Throws an exception if exponent is not an integer. Ideally this routine should accept a float for the exponent It should then convert the float to a rational and raise the unit by the numerator and root it by the denominator but, sadly, floats can't be converted to rationals. For now, if a rational is passed in, it will be used, otherwise we are stuck with integers and certain floats < 1 @param [Numeric] other @return [Unit] @raise [ArgumentError] when raising a temperature to a power @raise [ArgumentError] when n not in the set integers from (1..9) @raise [ArgumentError] when attempting to raise to a complex number @raise [ArgumentError] when an invalid exponent is passed
[ "Exponentiate", ".", "Only", "takes", "integer", "powers", ".", "Note", "that", "anything", "raised", "to", "the", "power", "of", "0", "results", "in", "a", "Unit", "object", "with", "a", "scalar", "of", "1", "and", "no", "units", ".", "Throws", "an", "exception", "if", "exponent", "is", "not", "an", "integer", ".", "Ideally", "this", "routine", "should", "accept", "a", "float", "for", "the", "exponent", "It", "should", "then", "convert", "the", "float", "to", "a", "rational", "and", "raise", "the", "unit", "by", "the", "numerator", "and", "root", "it", "by", "the", "denominator", "but", "sadly", "floats", "can", "t", "be", "converted", "to", "rationals", "." ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L976-L998
16,351
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.power
def power(n) raise ArgumentError, 'Cannot raise a temperature to a power' if temperature? raise ArgumentError, 'Exponent must an Integer' unless n.is_a?(Integer) return inverse if n == -1 return 1 if n.zero? return self if n == 1 return (1..(n - 1).to_i).inject(self) { |acc, _elem| acc * self } if n >= 0 (1..-(n - 1).to_i).inject(self) { |acc, _elem| acc / self } end
ruby
def power(n) raise ArgumentError, 'Cannot raise a temperature to a power' if temperature? raise ArgumentError, 'Exponent must an Integer' unless n.is_a?(Integer) return inverse if n == -1 return 1 if n.zero? return self if n == 1 return (1..(n - 1).to_i).inject(self) { |acc, _elem| acc * self } if n >= 0 (1..-(n - 1).to_i).inject(self) { |acc, _elem| acc / self } end
[ "def", "power", "(", "n", ")", "raise", "ArgumentError", ",", "'Cannot raise a temperature to a power'", "if", "temperature?", "raise", "ArgumentError", ",", "'Exponent must an Integer'", "unless", "n", ".", "is_a?", "(", "Integer", ")", "return", "inverse", "if", "n", "==", "-", "1", "return", "1", "if", "n", ".", "zero?", "return", "self", "if", "n", "==", "1", "return", "(", "1", "..", "(", "n", "-", "1", ")", ".", "to_i", ")", ".", "inject", "(", "self", ")", "{", "|", "acc", ",", "_elem", "|", "acc", "*", "self", "}", "if", "n", ">=", "0", "(", "1", "..", "-", "(", "n", "-", "1", ")", ".", "to_i", ")", ".", "inject", "(", "self", ")", "{", "|", "acc", ",", "_elem", "|", "acc", "/", "self", "}", "end" ]
returns the unit raised to the n-th power @param [Integer] n @return [Unit] @raise [ArgumentError] when attempting to raise a temperature to a power @raise [ArgumentError] when n is not an integer
[ "returns", "the", "unit", "raised", "to", "the", "n", "-", "th", "power" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L1005-L1013
16,352
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.units
def units(with_prefix: true) return '' if @numerator == UNITY_ARRAY && @denominator == UNITY_ARRAY output_numerator = ['1'] output_denominator = [] num = @numerator.clone.compact den = @denominator.clone.compact unless num == UNITY_ARRAY definitions = num.map { |element| RubyUnits::Unit.definition(element) } definitions.reject!(&:prefix?) unless with_prefix # there is a bug in jruby 9.1.6.0's implementation of chunk_while # see https://github.com/jruby/jruby/issues/4410 # TODO: fix this after jruby fixes their bug. definitions = if definitions.respond_to?(:chunk_while) && RUBY_ENGINE != 'jruby' definitions.chunk_while { |defn, _| defn.prefix? }.to_a else # chunk_while is new to ruby 2.3+, so fallback to less efficient methods for older ruby result = [] enumerator = definitions.to_enum loop do first = enumerator.next result << (first.prefix? ? [first, enumerator.next] : [first]) end result end output_numerator = definitions.map { |element| element.map(&:display_name).join } end unless den == UNITY_ARRAY definitions = den.map { |element| RubyUnits::Unit.definition(element) } definitions.reject!(&:prefix?) unless with_prefix # there is a bug in jruby 9.1.6.0's implementation of chunk_while # see https://github.com/jruby/jruby/issues/4410 # TODO: fix this after jruby fixes their bug. definitions = if definitions.respond_to?(:chunk_while) && RUBY_ENGINE != 'jruby' definitions.chunk_while { |defn, _| defn.prefix? }.to_a else # chunk_while is new to ruby 2.3+, so fallback to less efficient methods for older ruby result = [] enumerator = definitions.to_enum loop do first = enumerator.next result << (first.prefix? ? [first, enumerator.next] : [first]) end result end output_denominator = definitions.map { |element| element.map(&:display_name).join } end on = output_numerator .uniq .map { |x| [x, output_numerator.count(x)] } .map { |element, power| (element.to_s.strip + (power > 1 ? "^#{power}" : '')) } od = output_denominator .uniq .map { |x| [x, output_denominator.count(x)] } .map { |element, power| (element.to_s.strip + (power > 1 ? "^#{power}" : '')) } "#{on.join('*')}#{od.empty? ? '' : '/' + od.join('*')}".strip end
ruby
def units(with_prefix: true) return '' if @numerator == UNITY_ARRAY && @denominator == UNITY_ARRAY output_numerator = ['1'] output_denominator = [] num = @numerator.clone.compact den = @denominator.clone.compact unless num == UNITY_ARRAY definitions = num.map { |element| RubyUnits::Unit.definition(element) } definitions.reject!(&:prefix?) unless with_prefix # there is a bug in jruby 9.1.6.0's implementation of chunk_while # see https://github.com/jruby/jruby/issues/4410 # TODO: fix this after jruby fixes their bug. definitions = if definitions.respond_to?(:chunk_while) && RUBY_ENGINE != 'jruby' definitions.chunk_while { |defn, _| defn.prefix? }.to_a else # chunk_while is new to ruby 2.3+, so fallback to less efficient methods for older ruby result = [] enumerator = definitions.to_enum loop do first = enumerator.next result << (first.prefix? ? [first, enumerator.next] : [first]) end result end output_numerator = definitions.map { |element| element.map(&:display_name).join } end unless den == UNITY_ARRAY definitions = den.map { |element| RubyUnits::Unit.definition(element) } definitions.reject!(&:prefix?) unless with_prefix # there is a bug in jruby 9.1.6.0's implementation of chunk_while # see https://github.com/jruby/jruby/issues/4410 # TODO: fix this after jruby fixes their bug. definitions = if definitions.respond_to?(:chunk_while) && RUBY_ENGINE != 'jruby' definitions.chunk_while { |defn, _| defn.prefix? }.to_a else # chunk_while is new to ruby 2.3+, so fallback to less efficient methods for older ruby result = [] enumerator = definitions.to_enum loop do first = enumerator.next result << (first.prefix? ? [first, enumerator.next] : [first]) end result end output_denominator = definitions.map { |element| element.map(&:display_name).join } end on = output_numerator .uniq .map { |x| [x, output_numerator.count(x)] } .map { |element, power| (element.to_s.strip + (power > 1 ? "^#{power}" : '')) } od = output_denominator .uniq .map { |x| [x, output_denominator.count(x)] } .map { |element, power| (element.to_s.strip + (power > 1 ? "^#{power}" : '')) } "#{on.join('*')}#{od.empty? ? '' : '/' + od.join('*')}".strip end
[ "def", "units", "(", "with_prefix", ":", "true", ")", "return", "''", "if", "@numerator", "==", "UNITY_ARRAY", "&&", "@denominator", "==", "UNITY_ARRAY", "output_numerator", "=", "[", "'1'", "]", "output_denominator", "=", "[", "]", "num", "=", "@numerator", ".", "clone", ".", "compact", "den", "=", "@denominator", ".", "clone", ".", "compact", "unless", "num", "==", "UNITY_ARRAY", "definitions", "=", "num", ".", "map", "{", "|", "element", "|", "RubyUnits", "::", "Unit", ".", "definition", "(", "element", ")", "}", "definitions", ".", "reject!", "(", ":prefix?", ")", "unless", "with_prefix", "# there is a bug in jruby 9.1.6.0's implementation of chunk_while", "# see https://github.com/jruby/jruby/issues/4410", "# TODO: fix this after jruby fixes their bug.", "definitions", "=", "if", "definitions", ".", "respond_to?", "(", ":chunk_while", ")", "&&", "RUBY_ENGINE", "!=", "'jruby'", "definitions", ".", "chunk_while", "{", "|", "defn", ",", "_", "|", "defn", ".", "prefix?", "}", ".", "to_a", "else", "# chunk_while is new to ruby 2.3+, so fallback to less efficient methods for older ruby", "result", "=", "[", "]", "enumerator", "=", "definitions", ".", "to_enum", "loop", "do", "first", "=", "enumerator", ".", "next", "result", "<<", "(", "first", ".", "prefix?", "?", "[", "first", ",", "enumerator", ".", "next", "]", ":", "[", "first", "]", ")", "end", "result", "end", "output_numerator", "=", "definitions", ".", "map", "{", "|", "element", "|", "element", ".", "map", "(", ":display_name", ")", ".", "join", "}", "end", "unless", "den", "==", "UNITY_ARRAY", "definitions", "=", "den", ".", "map", "{", "|", "element", "|", "RubyUnits", "::", "Unit", ".", "definition", "(", "element", ")", "}", "definitions", ".", "reject!", "(", ":prefix?", ")", "unless", "with_prefix", "# there is a bug in jruby 9.1.6.0's implementation of chunk_while", "# see https://github.com/jruby/jruby/issues/4410", "# TODO: fix this after jruby fixes their bug.", "definitions", "=", "if", "definitions", ".", "respond_to?", "(", ":chunk_while", ")", "&&", "RUBY_ENGINE", "!=", "'jruby'", "definitions", ".", "chunk_while", "{", "|", "defn", ",", "_", "|", "defn", ".", "prefix?", "}", ".", "to_a", "else", "# chunk_while is new to ruby 2.3+, so fallback to less efficient methods for older ruby", "result", "=", "[", "]", "enumerator", "=", "definitions", ".", "to_enum", "loop", "do", "first", "=", "enumerator", ".", "next", "result", "<<", "(", "first", ".", "prefix?", "?", "[", "first", ",", "enumerator", ".", "next", "]", ":", "[", "first", "]", ")", "end", "result", "end", "output_denominator", "=", "definitions", ".", "map", "{", "|", "element", "|", "element", ".", "map", "(", ":display_name", ")", ".", "join", "}", "end", "on", "=", "output_numerator", ".", "uniq", ".", "map", "{", "|", "x", "|", "[", "x", ",", "output_numerator", ".", "count", "(", "x", ")", "]", "}", ".", "map", "{", "|", "element", ",", "power", "|", "(", "element", ".", "to_s", ".", "strip", "+", "(", "power", ">", "1", "?", "\"^#{power}\"", ":", "''", ")", ")", "}", "od", "=", "output_denominator", ".", "uniq", ".", "map", "{", "|", "x", "|", "[", "x", ",", "output_denominator", ".", "count", "(", "x", ")", "]", "}", ".", "map", "{", "|", "element", ",", "power", "|", "(", "element", ".", "to_s", ".", "strip", "+", "(", "power", ">", "1", "?", "\"^#{power}\"", ":", "''", ")", ")", "}", "\"#{on.join('*')}#{od.empty? ? '' : '/' + od.join('*')}\"", ".", "strip", "end" ]
returns the 'unit' part of the Unit object without the scalar @return [String]
[ "returns", "the", "unit", "part", "of", "the", "Unit", "object", "without", "the", "scalar" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L1174-L1230
16,353
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.coerce
def coerce(other) return [other.to_unit, self] if other.respond_to? :to_unit case other when Unit [other, self] else [RubyUnits::Unit.new(other), self] end end
ruby
def coerce(other) return [other.to_unit, self] if other.respond_to? :to_unit case other when Unit [other, self] else [RubyUnits::Unit.new(other), self] end end
[ "def", "coerce", "(", "other", ")", "return", "[", "other", ".", "to_unit", ",", "self", "]", "if", "other", ".", "respond_to?", ":to_unit", "case", "other", "when", "Unit", "[", "other", ",", "self", "]", "else", "[", "RubyUnits", "::", "Unit", ".", "new", "(", "other", ")", ",", "self", "]", "end", "end" ]
automatically coerce objects to units when possible if an object defines a 'to_unit' method, it will be coerced using that method @param [Object, #to_unit] @return [Array]
[ "automatically", "coerce", "objects", "to", "units", "when", "possible", "if", "an", "object", "defines", "a", "to_unit", "method", "it", "will", "be", "coerced", "using", "that", "method" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L1393-L1401
16,354
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.best_prefix
def best_prefix return to_base if scalar.zero? best_prefix = if kind == :information @@prefix_values.key(2**((Math.log(base_scalar, 2) / 10.0).floor * 10)) else @@prefix_values.key(10**((Math.log10(base_scalar) / 3.0).floor * 3)) end to(RubyUnits::Unit.new(@@prefix_map.key(best_prefix) + units(with_prefix: false))) end
ruby
def best_prefix return to_base if scalar.zero? best_prefix = if kind == :information @@prefix_values.key(2**((Math.log(base_scalar, 2) / 10.0).floor * 10)) else @@prefix_values.key(10**((Math.log10(base_scalar) / 3.0).floor * 3)) end to(RubyUnits::Unit.new(@@prefix_map.key(best_prefix) + units(with_prefix: false))) end
[ "def", "best_prefix", "return", "to_base", "if", "scalar", ".", "zero?", "best_prefix", "=", "if", "kind", "==", ":information", "@@prefix_values", ".", "key", "(", "2", "**", "(", "(", "Math", ".", "log", "(", "base_scalar", ",", "2", ")", "/", "10.0", ")", ".", "floor", "*", "10", ")", ")", "else", "@@prefix_values", ".", "key", "(", "10", "**", "(", "(", "Math", ".", "log10", "(", "base_scalar", ")", "/", "3.0", ")", ".", "floor", "*", "3", ")", ")", "end", "to", "(", "RubyUnits", "::", "Unit", ".", "new", "(", "@@prefix_map", ".", "key", "(", "best_prefix", ")", "+", "units", "(", "with_prefix", ":", "false", ")", ")", ")", "end" ]
returns a new unit that has been scaled to be more in line with typical usage.
[ "returns", "a", "new", "unit", "that", "has", "been", "scaled", "to", "be", "more", "in", "line", "with", "typical", "usage", "." ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L1404-L1412
16,355
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.unit_signature_vector
def unit_signature_vector return to_base.unit_signature_vector unless base? vector = Array.new(SIGNATURE_VECTOR.size, 0) # it's possible to have a kind that misses the array... kinds like :counting # are more like prefixes, so don't use them to calculate the vector @numerator.map { |element| RubyUnits::Unit.definition(element) }.each do |definition| index = SIGNATURE_VECTOR.index(definition.kind) vector[index] += 1 if index end @denominator.map { |element| RubyUnits::Unit.definition(element) }.each do |definition| index = SIGNATURE_VECTOR.index(definition.kind) vector[index] -= 1 if index end raise ArgumentError, 'Power out of range (-20 < net power of a unit < 20)' if vector.any? { |x| x.abs >= 20 } vector end
ruby
def unit_signature_vector return to_base.unit_signature_vector unless base? vector = Array.new(SIGNATURE_VECTOR.size, 0) # it's possible to have a kind that misses the array... kinds like :counting # are more like prefixes, so don't use them to calculate the vector @numerator.map { |element| RubyUnits::Unit.definition(element) }.each do |definition| index = SIGNATURE_VECTOR.index(definition.kind) vector[index] += 1 if index end @denominator.map { |element| RubyUnits::Unit.definition(element) }.each do |definition| index = SIGNATURE_VECTOR.index(definition.kind) vector[index] -= 1 if index end raise ArgumentError, 'Power out of range (-20 < net power of a unit < 20)' if vector.any? { |x| x.abs >= 20 } vector end
[ "def", "unit_signature_vector", "return", "to_base", ".", "unit_signature_vector", "unless", "base?", "vector", "=", "Array", ".", "new", "(", "SIGNATURE_VECTOR", ".", "size", ",", "0", ")", "# it's possible to have a kind that misses the array... kinds like :counting", "# are more like prefixes, so don't use them to calculate the vector", "@numerator", ".", "map", "{", "|", "element", "|", "RubyUnits", "::", "Unit", ".", "definition", "(", "element", ")", "}", ".", "each", "do", "|", "definition", "|", "index", "=", "SIGNATURE_VECTOR", ".", "index", "(", "definition", ".", "kind", ")", "vector", "[", "index", "]", "+=", "1", "if", "index", "end", "@denominator", ".", "map", "{", "|", "element", "|", "RubyUnits", "::", "Unit", ".", "definition", "(", "element", ")", "}", ".", "each", "do", "|", "definition", "|", "index", "=", "SIGNATURE_VECTOR", ".", "index", "(", "definition", ".", "kind", ")", "vector", "[", "index", "]", "-=", "1", "if", "index", "end", "raise", "ArgumentError", ",", "'Power out of range (-20 < net power of a unit < 20)'", "if", "vector", ".", "any?", "{", "|", "x", "|", "x", ".", "abs", ">=", "20", "}", "vector", "end" ]
calculates the unit signature vector used by unit_signature @return [Array] @raise [ArgumentError] when exponent associated with a unit is > 20 or < -20
[ "calculates", "the", "unit", "signature", "vector", "used", "by", "unit_signature" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L1446-L1461
16,356
olbrich/ruby-units
lib/ruby_units/unit.rb
RubyUnits.Unit.unit_signature
def unit_signature return @signature unless @signature.nil? vector = unit_signature_vector vector.each_with_index { |item, index| vector[index] = item * 20**index } @signature = vector.inject(0) { |acc, elem| acc + elem } @signature end
ruby
def unit_signature return @signature unless @signature.nil? vector = unit_signature_vector vector.each_with_index { |item, index| vector[index] = item * 20**index } @signature = vector.inject(0) { |acc, elem| acc + elem } @signature end
[ "def", "unit_signature", "return", "@signature", "unless", "@signature", ".", "nil?", "vector", "=", "unit_signature_vector", "vector", ".", "each_with_index", "{", "|", "item", ",", "index", "|", "vector", "[", "index", "]", "=", "item", "*", "20", "**", "index", "}", "@signature", "=", "vector", ".", "inject", "(", "0", ")", "{", "|", "acc", ",", "elem", "|", "acc", "+", "elem", "}", "@signature", "end" ]
calculates the unit signature id for use in comparing compatible units and simplification the signature is based on a simple classification of units and is based on the following publication Novak, G.S., Jr. "Conversion of units of measurement", IEEE Transactions on Software Engineering, 21(8), Aug 1995, pp.651-661 @see http://doi.ieeecomputersociety.org/10.1109/32.403789 @return [Array]
[ "calculates", "the", "unit", "signature", "id", "for", "use", "in", "comparing", "compatible", "units", "and", "simplification", "the", "signature", "is", "based", "on", "a", "simple", "classification", "of", "units", "and", "is", "based", "on", "the", "following", "publication" ]
6224400575e49177a2f118d279d612d620aa054a
https://github.com/olbrich/ruby-units/blob/6224400575e49177a2f118d279d612d620aa054a/lib/ruby_units/unit.rb#L1479-L1485
16,357
jonhue/acts_as_favoritor
lib/acts_as_favoritor/favoritor_lib.rb
ActsAsFavoritor.FavoritorLib.parent_class_name
def parent_class_name(obj) unless DEFAULT_PARENTS.include? obj.class.superclass return obj.class.base_class.name end obj.class.name end
ruby
def parent_class_name(obj) unless DEFAULT_PARENTS.include? obj.class.superclass return obj.class.base_class.name end obj.class.name end
[ "def", "parent_class_name", "(", "obj", ")", "unless", "DEFAULT_PARENTS", ".", "include?", "obj", ".", "class", ".", "superclass", "return", "obj", ".", "class", ".", "base_class", ".", "name", "end", "obj", ".", "class", ".", "name", "end" ]
Retrieves the parent class name if using STI.
[ "Retrieves", "the", "parent", "class", "name", "if", "using", "STI", "." ]
d85342b2d8d2b5bab328f980bb351a667faafb3a
https://github.com/jonhue/acts_as_favoritor/blob/d85342b2d8d2b5bab328f980bb351a667faafb3a/lib/acts_as_favoritor/favoritor_lib.rb#L10-L16
16,358
moneta-rb/moneta
lib/moneta/mixins.rb
Moneta.OptionSupport.with
def with(options = nil, &block) adapter = self if block builder = Builder.new(&block) builder.adapter(adapter) adapter = builder.build.last end options ? OptionMerger.new(adapter, options) : adapter end
ruby
def with(options = nil, &block) adapter = self if block builder = Builder.new(&block) builder.adapter(adapter) adapter = builder.build.last end options ? OptionMerger.new(adapter, options) : adapter end
[ "def", "with", "(", "options", "=", "nil", ",", "&", "block", ")", "adapter", "=", "self", "if", "block", "builder", "=", "Builder", ".", "new", "(", "block", ")", "builder", ".", "adapter", "(", "adapter", ")", "adapter", "=", "builder", ".", "build", ".", "last", "end", "options", "?", "OptionMerger", ".", "new", "(", "adapter", ",", "options", ")", ":", "adapter", "end" ]
Return Moneta store with default options or additional proxies @param [Hash] options Options to merge @return [Moneta store] @api public
[ "Return", "Moneta", "store", "with", "default", "options", "or", "additional", "proxies" ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/mixins.rb#L10-L18
16,359
moneta-rb/moneta
lib/moneta/mixins.rb
Moneta.Defaults.fetch
def fetch(key, default = nil, options = nil) if block_given? raise ArgumentError, 'Only one argument accepted if block is given' if options result = load(key, default || {}) result == nil ? yield(key) : result else result = load(key, options || {}) result == nil ? default : result end end
ruby
def fetch(key, default = nil, options = nil) if block_given? raise ArgumentError, 'Only one argument accepted if block is given' if options result = load(key, default || {}) result == nil ? yield(key) : result else result = load(key, options || {}) result == nil ? default : result end end
[ "def", "fetch", "(", "key", ",", "default", "=", "nil", ",", "options", "=", "nil", ")", "if", "block_given?", "raise", "ArgumentError", ",", "'Only one argument accepted if block is given'", "if", "options", "result", "=", "load", "(", "key", ",", "default", "||", "{", "}", ")", "result", "==", "nil", "?", "yield", "(", "key", ")", ":", "result", "else", "result", "=", "load", "(", "key", ",", "options", "||", "{", "}", ")", "result", "==", "nil", "?", "default", ":", "result", "end", "end" ]
Fetch a value with a key @overload fetch(key, options = {}, &block) retrieve a key. if the key is not available, execute the block and return its return value. @param [Object] key @param [Hash] options @option options [Integer] :expires Update expiration time (See {Expires}) @option options [Boolean] :raw Raw access without value transformation (See {Transformer}) @option options [String] :prefix Prefix key (See {Transformer}) @return [Object] value from store @overload fetch(key, default, options = {}) retrieve a key. if the key is not available, return the default value. @param [Object] key @param [Object] default Default value @param [Hash] options @option options [Integer] :expires Update expiration time (See {Expires}) @option options [Boolean] :raw Raw access without value transformation (See {Transformer}) @option options [String] :prefix Prefix key (See {Transformer}) @return [Object] value from store @api public
[ "Fetch", "a", "value", "with", "a", "key" ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/mixins.rb#L180-L189
16,360
moneta-rb/moneta
lib/moneta/mixins.rb
Moneta.Defaults.slice
def slice(*keys, **options) keys.zip(values_at(*keys, **options)).reject do |_, value| value == nil end end
ruby
def slice(*keys, **options) keys.zip(values_at(*keys, **options)).reject do |_, value| value == nil end end
[ "def", "slice", "(", "*", "keys", ",", "**", "options", ")", "keys", ".", "zip", "(", "values_at", "(", "keys", ",", "**", "options", ")", ")", ".", "reject", "do", "|", "_", ",", "value", "|", "value", "==", "nil", "end", "end" ]
Returns a collection of key-value pairs corresponding to those supplied keys which are present in the key-value store, and their associated values. Only those keys present in the store will have pairs in the return value. The return value can be any enumerable object that yields pairs, so it could be a hash, but needn't be. @note The keys in the return value may be the same objects that were supplied (i.e. {Object#equal?}), or may simply be equal (i.e. {Object#==}). @note Some adapters may implement this method atomically. The default implmentation uses {#values_at}. @param (see #values_at) @option options (see #values_at) @return [<(Object, Object)>] A collection of key-value pairs @api public
[ "Returns", "a", "collection", "of", "key", "-", "value", "pairs", "corresponding", "to", "those", "supplied", "keys", "which", "are", "present", "in", "the", "key", "-", "value", "store", "and", "their", "associated", "values", ".", "Only", "those", "keys", "present", "in", "the", "store", "will", "have", "pairs", "in", "the", "return", "value", ".", "The", "return", "value", "can", "be", "any", "enumerable", "object", "that", "yields", "pairs", "so", "it", "could", "be", "a", "hash", "but", "needn", "t", "be", "." ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/mixins.rb#L311-L315
16,361
moneta-rb/moneta
lib/moneta/mixins.rb
Moneta.ExpiresSupport.expires_at
def expires_at(options, default = @default_expires) value = expires_value(options, default) Numeric === value ? Time.now + value : value end
ruby
def expires_at(options, default = @default_expires) value = expires_value(options, default) Numeric === value ? Time.now + value : value end
[ "def", "expires_at", "(", "options", ",", "default", "=", "@default_expires", ")", "value", "=", "expires_value", "(", "options", ",", "default", ")", "Numeric", "===", "value", "?", "Time", ".", "now", "+", "value", ":", "value", "end" ]
Calculates the time when something will expire. This method considers false and 0 as "no-expire" and every positive number as a time to live in seconds. @param [Hash] options Options hash @option options [0,false,nil,Numeric] :expires expires value given by user @param [0,false,nil,Numeric] default default expiration time @return [false] if it should not expire @return [Time] the time when something should expire @return [nil] if it is not known
[ "Calculates", "the", "time", "when", "something", "will", "expire", "." ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/mixins.rb#L583-L586
16,362
moneta-rb/moneta
lib/moneta/mixins.rb
Moneta.ExpiresSupport.expires_value
def expires_value(options, default = @default_expires) case value = options[:expires] when 0, false false when nil default ? default.to_r : nil when Numeric value = value.to_r raise ArgumentError, ":expires must be a positive value, got #{value}" if value < 0 value else raise ArgumentError, ":expires must be Numeric or false, got #{value.inspect}" end end
ruby
def expires_value(options, default = @default_expires) case value = options[:expires] when 0, false false when nil default ? default.to_r : nil when Numeric value = value.to_r raise ArgumentError, ":expires must be a positive value, got #{value}" if value < 0 value else raise ArgumentError, ":expires must be Numeric or false, got #{value.inspect}" end end
[ "def", "expires_value", "(", "options", ",", "default", "=", "@default_expires", ")", "case", "value", "=", "options", "[", ":expires", "]", "when", "0", ",", "false", "false", "when", "nil", "default", "?", "default", ".", "to_r", ":", "nil", "when", "Numeric", "value", "=", "value", ".", "to_r", "raise", "ArgumentError", ",", "\":expires must be a positive value, got #{value}\"", "if", "value", "<", "0", "value", "else", "raise", "ArgumentError", ",", "\":expires must be Numeric or false, got #{value.inspect}\"", "end", "end" ]
Calculates the number of seconds something should last. This method considers false and 0 as "no-expire" and every positive number as a time to live in seconds. @param [Hash] options Options hash @option options [0,false,nil,Numeric] :expires expires value given by user @param [0,false,nil,Numeric] default default expiration time @return [false] if it should not expire @return [Numeric] seconds until expiration @return [nil] if it is not known
[ "Calculates", "the", "number", "of", "seconds", "something", "should", "last", "." ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/mixins.rb#L600-L613
16,363
moneta-rb/moneta
lib/moneta/builder.rb
Moneta.Builder.use
def use(proxy, options = {}, &block) proxy = Moneta.const_get(proxy) if Symbol === proxy raise ArgumentError, 'You must give a Class or a Symbol' unless Class === proxy @proxies.unshift [proxy, options, block] nil end
ruby
def use(proxy, options = {}, &block) proxy = Moneta.const_get(proxy) if Symbol === proxy raise ArgumentError, 'You must give a Class or a Symbol' unless Class === proxy @proxies.unshift [proxy, options, block] nil end
[ "def", "use", "(", "proxy", ",", "options", "=", "{", "}", ",", "&", "block", ")", "proxy", "=", "Moneta", ".", "const_get", "(", "proxy", ")", "if", "Symbol", "===", "proxy", "raise", "ArgumentError", ",", "'You must give a Class or a Symbol'", "unless", "Class", "===", "proxy", "@proxies", ".", "unshift", "[", "proxy", ",", "options", ",", "block", "]", "nil", "end" ]
Add proxy to stack @param [Symbol/Class] proxy Name of proxy class or proxy class @param [Hash] options Options hash @api public
[ "Add", "proxy", "to", "stack" ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/builder.rb#L36-L41
16,364
moneta-rb/moneta
lib/moneta/builder.rb
Moneta.Builder.adapter
def adapter(adapter, options = {}, &block) case adapter when Symbol use(Adapters.const_get(adapter), options, &block) when Class use(adapter, options, &block) else raise ArgumentError, 'Adapter must be a Moneta store' unless adapter.respond_to?(:load) && adapter.respond_to?(:store) raise ArgumentError, 'No options allowed' unless options.empty? @proxies.unshift adapter nil end end
ruby
def adapter(adapter, options = {}, &block) case adapter when Symbol use(Adapters.const_get(adapter), options, &block) when Class use(adapter, options, &block) else raise ArgumentError, 'Adapter must be a Moneta store' unless adapter.respond_to?(:load) && adapter.respond_to?(:store) raise ArgumentError, 'No options allowed' unless options.empty? @proxies.unshift adapter nil end end
[ "def", "adapter", "(", "adapter", ",", "options", "=", "{", "}", ",", "&", "block", ")", "case", "adapter", "when", "Symbol", "use", "(", "Adapters", ".", "const_get", "(", "adapter", ")", ",", "options", ",", "block", ")", "when", "Class", "use", "(", "adapter", ",", "options", ",", "block", ")", "else", "raise", "ArgumentError", ",", "'Adapter must be a Moneta store'", "unless", "adapter", ".", "respond_to?", "(", ":load", ")", "&&", "adapter", ".", "respond_to?", "(", ":store", ")", "raise", "ArgumentError", ",", "'No options allowed'", "unless", "options", ".", "empty?", "@proxies", ".", "unshift", "adapter", "nil", "end", "end" ]
Add adapter to stack @param [Symbol/Class/Moneta store] adapter Name of adapter class, adapter class or Moneta store @param [Hash] options Options hash @api public
[ "Add", "adapter", "to", "stack" ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/builder.rb#L48-L60
16,365
moneta-rb/moneta
lib/moneta/server.rb
Moneta.Server.run
def run raise 'Already running' if @running @stop = false @running = true begin until @stop mainloop end ensure File.unlink(@socket) if @socket @ios.each{ |io| io.close rescue nil } end end
ruby
def run raise 'Already running' if @running @stop = false @running = true begin until @stop mainloop end ensure File.unlink(@socket) if @socket @ios.each{ |io| io.close rescue nil } end end
[ "def", "run", "raise", "'Already running'", "if", "@running", "@stop", "=", "false", "@running", "=", "true", "begin", "until", "@stop", "mainloop", "end", "ensure", "File", ".", "unlink", "(", "@socket", ")", "if", "@socket", "@ios", ".", "each", "{", "|", "io", "|", "io", ".", "close", "rescue", "nil", "}", "end", "end" ]
Run the server @note This method blocks!
[ "Run", "the", "server" ]
26a118c8b2c93d11257f4a5fe9334a8157f4db47
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/server.rb#L28-L40
16,366
jeremyevans/erubi
lib/erubi/capture_end.rb
Erubi.CaptureEndEngine.handle
def handle(indicator, code, tailch, rspace, lspace) case indicator when '|=', '|==' rspace = nil if tailch && !tailch.empty? add_text(lspace) if lspace escape_capture = !((indicator == '|=') ^ @escape_capture) src << "begin; (#{@bufstack} ||= []) << #{@bufvar}; #{@bufvar} = #{@bufval}; #{@bufstack}.last << #{@escapefunc if escape_capture}((" << code add_text(rspace) if rspace when '|' rspace = nil if tailch && !tailch.empty? add_text(lspace) if lspace result = @yield_returns_buffer ? " #{@bufvar}; " : "" src << result << code << ")).to_s; ensure; #{@bufvar} = #{@bufstack}.pop; end;" add_text(rspace) if rspace else super end end
ruby
def handle(indicator, code, tailch, rspace, lspace) case indicator when '|=', '|==' rspace = nil if tailch && !tailch.empty? add_text(lspace) if lspace escape_capture = !((indicator == '|=') ^ @escape_capture) src << "begin; (#{@bufstack} ||= []) << #{@bufvar}; #{@bufvar} = #{@bufval}; #{@bufstack}.last << #{@escapefunc if escape_capture}((" << code add_text(rspace) if rspace when '|' rspace = nil if tailch && !tailch.empty? add_text(lspace) if lspace result = @yield_returns_buffer ? " #{@bufvar}; " : "" src << result << code << ")).to_s; ensure; #{@bufvar} = #{@bufstack}.pop; end;" add_text(rspace) if rspace else super end end
[ "def", "handle", "(", "indicator", ",", "code", ",", "tailch", ",", "rspace", ",", "lspace", ")", "case", "indicator", "when", "'|='", ",", "'|=='", "rspace", "=", "nil", "if", "tailch", "&&", "!", "tailch", ".", "empty?", "add_text", "(", "lspace", ")", "if", "lspace", "escape_capture", "=", "!", "(", "(", "indicator", "==", "'|='", ")", "^", "@escape_capture", ")", "src", "<<", "\"begin; (#{@bufstack} ||= []) << #{@bufvar}; #{@bufvar} = #{@bufval}; #{@bufstack}.last << #{@escapefunc if escape_capture}((\"", "<<", "code", "add_text", "(", "rspace", ")", "if", "rspace", "when", "'|'", "rspace", "=", "nil", "if", "tailch", "&&", "!", "tailch", ".", "empty?", "add_text", "(", "lspace", ")", "if", "lspace", "result", "=", "@yield_returns_buffer", "?", "\" #{@bufvar}; \"", ":", "\"\"", "src", "<<", "result", "<<", "code", "<<", "\")).to_s; ensure; #{@bufvar} = #{@bufstack}.pop; end;\"", "add_text", "(", "rspace", ")", "if", "rspace", "else", "super", "end", "end" ]
Handle the <%|= and <%|== tags
[ "Handle", "the", "<%|", "=", "and", "<%|", "==", "tags" ]
e33a64773990959e70f44046dab1f754c38deb54
https://github.com/jeremyevans/erubi/blob/e33a64773990959e70f44046dab1f754c38deb54/lib/erubi/capture_end.rb#L33-L50
16,367
chef/win32-certstore
lib/win32/certstore.rb
Win32.Certstore.open
def open(store_name) certstore_handler = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, nil, CERT_SYSTEM_STORE_LOCAL_MACHINE, wstring(store_name)) unless certstore_handler last_error = FFI::LastError.error raise SystemCallError.new("Unable to open the Certificate Store `#{store_name}`.", last_error) end add_finalizer(certstore_handler) certstore_handler end
ruby
def open(store_name) certstore_handler = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, nil, CERT_SYSTEM_STORE_LOCAL_MACHINE, wstring(store_name)) unless certstore_handler last_error = FFI::LastError.error raise SystemCallError.new("Unable to open the Certificate Store `#{store_name}`.", last_error) end add_finalizer(certstore_handler) certstore_handler end
[ "def", "open", "(", "store_name", ")", "certstore_handler", "=", "CertOpenStore", "(", "CERT_STORE_PROV_SYSTEM", ",", "0", ",", "nil", ",", "CERT_SYSTEM_STORE_LOCAL_MACHINE", ",", "wstring", "(", "store_name", ")", ")", "unless", "certstore_handler", "last_error", "=", "FFI", "::", "LastError", ".", "error", "raise", "SystemCallError", ".", "new", "(", "\"Unable to open the Certificate Store `#{store_name}`.\"", ",", "last_error", ")", "end", "add_finalizer", "(", "certstore_handler", ")", "certstore_handler", "end" ]
To open certstore and return open certificate store pointer
[ "To", "open", "certstore", "and", "return", "open", "certificate", "store", "pointer" ]
2fe520f7b235ee8c9aef780940cdb8f8c47f3b28
https://github.com/chef/win32-certstore/blob/2fe520f7b235ee8c9aef780940cdb8f8c47f3b28/lib/win32/certstore.rb#L120-L128
16,368
judofyr/temple
lib/temple/utils.rb
Temple.Utils.empty_exp?
def empty_exp?(exp) case exp[0] when :multi exp[1..-1].all? {|e| empty_exp?(e) } when :newline true else false end end
ruby
def empty_exp?(exp) case exp[0] when :multi exp[1..-1].all? {|e| empty_exp?(e) } when :newline true else false end end
[ "def", "empty_exp?", "(", "exp", ")", "case", "exp", "[", "0", "]", "when", ":multi", "exp", "[", "1", "..", "-", "1", "]", ".", "all?", "{", "|", "e", "|", "empty_exp?", "(", "e", ")", "}", "when", ":newline", "true", "else", "false", "end", "end" ]
Check if expression is empty @param exp [Array] Temple expression @return true if expression is empty
[ "Check", "if", "expression", "is", "empty" ]
7987ab67af00a598eb3d83192415371498a0f125
https://github.com/judofyr/temple/blob/7987ab67af00a598eb3d83192415371498a0f125/lib/temple/utils.rb#L76-L85
16,369
chef/mixlib-log
lib/mixlib/log.rb
Mixlib.Log.loggers_to_close
def loggers_to_close loggers_to_close = [] all_loggers.each do |logger| # unfortunately Logger does not provide access to the logdev # via public API. In order to reduce amount of impact and # handle only File type log devices I had to use this method # to get access to it. next unless (logdev = logger.instance_variable_get(:"@logdev")) loggers_to_close << logger if logdev.filename end loggers_to_close end
ruby
def loggers_to_close loggers_to_close = [] all_loggers.each do |logger| # unfortunately Logger does not provide access to the logdev # via public API. In order to reduce amount of impact and # handle only File type log devices I had to use this method # to get access to it. next unless (logdev = logger.instance_variable_get(:"@logdev")) loggers_to_close << logger if logdev.filename end loggers_to_close end
[ "def", "loggers_to_close", "loggers_to_close", "=", "[", "]", "all_loggers", ".", "each", "do", "|", "logger", "|", "# unfortunately Logger does not provide access to the logdev", "# via public API. In order to reduce amount of impact and", "# handle only File type log devices I had to use this method", "# to get access to it.", "next", "unless", "(", "logdev", "=", "logger", ".", "instance_variable_get", "(", ":\"", "\"", ")", ")", "loggers_to_close", "<<", "logger", "if", "logdev", ".", "filename", "end", "loggers_to_close", "end" ]
select all loggers with File log devices
[ "select", "all", "loggers", "with", "File", "log", "devices" ]
00dfe62ceb83a4a4ac1268622edb6e949b2fb0cf
https://github.com/chef/mixlib-log/blob/00dfe62ceb83a4a4ac1268622edb6e949b2fb0cf/lib/mixlib/log.rb#L186-L197
16,370
travis-ci/travis-core
spec/support/formats.rb
Support.Formats.normalize_json
def normalize_json(json) json = json.to_json unless json.is_a?(String) JSON.parse(json) end
ruby
def normalize_json(json) json = json.to_json unless json.is_a?(String) JSON.parse(json) end
[ "def", "normalize_json", "(", "json", ")", "json", "=", "json", ".", "to_json", "unless", "json", ".", "is_a?", "(", "String", ")", "JSON", ".", "parse", "(", "json", ")", "end" ]
normalizes datetime objects to strings etc. more similar to what the client would see.
[ "normalizes", "datetime", "objects", "to", "strings", "etc", ".", "more", "similar", "to", "what", "the", "client", "would", "see", "." ]
bf944c952724dd2f00ff0c466a5e217d10f73bea
https://github.com/travis-ci/travis-core/blob/bf944c952724dd2f00ff0c466a5e217d10f73bea/spec/support/formats.rb#L30-L33
16,371
travis-ci/travis-core
lib/travis/features.rb
Travis.Features.active?
def active?(feature, repository) feature_active?(feature) or (rollout.active?(feature, repository.owner) or repository_active?(feature, repository)) end
ruby
def active?(feature, repository) feature_active?(feature) or (rollout.active?(feature, repository.owner) or repository_active?(feature, repository)) end
[ "def", "active?", "(", "feature", ",", "repository", ")", "feature_active?", "(", "feature", ")", "or", "(", "rollout", ".", "active?", "(", "feature", ",", "repository", ".", "owner", ")", "or", "repository_active?", "(", "feature", ",", "repository", ")", ")", "end" ]
Returns whether a given feature is enabled either globally or for a given repository. By default, this will return false.
[ "Returns", "whether", "a", "given", "feature", "is", "enabled", "either", "globally", "or", "for", "a", "given", "repository", "." ]
bf944c952724dd2f00ff0c466a5e217d10f73bea
https://github.com/travis-ci/travis-core/blob/bf944c952724dd2f00ff0c466a5e217d10f73bea/lib/travis/features.rb#L26-L30
16,372
travis-ci/travis-core
lib/travis/features.rb
Travis.Features.owner_active?
def owner_active?(feature, owner) redis.sismember(owner_key(feature, owner), owner.id) end
ruby
def owner_active?(feature, owner) redis.sismember(owner_key(feature, owner), owner.id) end
[ "def", "owner_active?", "(", "feature", ",", "owner", ")", "redis", ".", "sismember", "(", "owner_key", "(", "feature", ",", "owner", ")", ",", "owner", ".", "id", ")", "end" ]
Return whether a feature has been enabled for a user. By default, this return false.
[ "Return", "whether", "a", "feature", "has", "been", "enabled", "for", "a", "user", "." ]
bf944c952724dd2f00ff0c466a5e217d10f73bea
https://github.com/travis-ci/travis-core/blob/bf944c952724dd2f00ff0c466a5e217d10f73bea/lib/travis/features.rb#L113-L115
16,373
travis-ci/travis-core
lib/travis/advisory_locks.rb
Travis.AdvisoryLocks.exclusive
def exclusive(timeout = 30) give_up_at = Time.now + timeout if timeout while timeout.nil? || Time.now < give_up_at do if obtained_lock? return yield else # Randomizing sleep time may help reduce contention. sleep(rand(0.1..0.2)) end end ensure release_lock unless transactional end
ruby
def exclusive(timeout = 30) give_up_at = Time.now + timeout if timeout while timeout.nil? || Time.now < give_up_at do if obtained_lock? return yield else # Randomizing sleep time may help reduce contention. sleep(rand(0.1..0.2)) end end ensure release_lock unless transactional end
[ "def", "exclusive", "(", "timeout", "=", "30", ")", "give_up_at", "=", "Time", ".", "now", "+", "timeout", "if", "timeout", "while", "timeout", ".", "nil?", "||", "Time", ".", "now", "<", "give_up_at", "do", "if", "obtained_lock?", "return", "yield", "else", "# Randomizing sleep time may help reduce contention.", "sleep", "(", "rand", "(", "0.1", "..", "0.2", ")", ")", "end", "end", "ensure", "release_lock", "unless", "transactional", "end" ]
must be used within a transaction
[ "must", "be", "used", "within", "a", "transaction" ]
bf944c952724dd2f00ff0c466a5e217d10f73bea
https://github.com/travis-ci/travis-core/blob/bf944c952724dd2f00ff0c466a5e217d10f73bea/lib/travis/advisory_locks.rb#L25-L37
16,374
mbj/unparser
lib/unparser/cli.rb
Unparser.CLI.exit_status
def exit_status effective_sources.each do |source| next if @ignore.include?(source) process_source(source) break if @fail_fast && !@success end @success ? EXIT_SUCCESS : EXIT_FAILURE end
ruby
def exit_status effective_sources.each do |source| next if @ignore.include?(source) process_source(source) break if @fail_fast && !@success end @success ? EXIT_SUCCESS : EXIT_FAILURE end
[ "def", "exit_status", "effective_sources", ".", "each", "do", "|", "source", "|", "next", "if", "@ignore", ".", "include?", "(", "source", ")", "process_source", "(", "source", ")", "break", "if", "@fail_fast", "&&", "!", "@success", "end", "@success", "?", "EXIT_SUCCESS", ":", "EXIT_FAILURE", "end" ]
Return exit status @return [Fixnum] @api private
[ "Return", "exit", "status" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/cli.rb#L96-L105
16,375
mbj/unparser
lib/unparser/cli.rb
Unparser.CLI.effective_sources
def effective_sources if @start_with reject = true @sources.reject do |source| if reject && source.eql?(@start_with) reject = false end reject end else @sources end end
ruby
def effective_sources if @start_with reject = true @sources.reject do |source| if reject && source.eql?(@start_with) reject = false end reject end else @sources end end
[ "def", "effective_sources", "if", "@start_with", "reject", "=", "true", "@sources", ".", "reject", "do", "|", "source", "|", "if", "reject", "&&", "source", ".", "eql?", "(", "@start_with", ")", "reject", "=", "false", "end", "reject", "end", "else", "@sources", "end", "end" ]
Return effective sources @return [Enumerable<CLI::Source>] @api private
[ "Return", "effective", "sources" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/cli.rb#L134-L147
16,376
mbj/unparser
lib/unparser/cli.rb
Unparser.CLI.sources
def sources(file_name) files = if File.directory?(file_name) Dir.glob(File.join(file_name, '**/*.rb')).sort elsif File.file?(file_name) [file_name] else Dir.glob(file_name).sort end files.map(&Source::File.method(:new)) end
ruby
def sources(file_name) files = if File.directory?(file_name) Dir.glob(File.join(file_name, '**/*.rb')).sort elsif File.file?(file_name) [file_name] else Dir.glob(file_name).sort end files.map(&Source::File.method(:new)) end
[ "def", "sources", "(", "file_name", ")", "files", "=", "if", "File", ".", "directory?", "(", "file_name", ")", "Dir", ".", "glob", "(", "File", ".", "join", "(", "file_name", ",", "'**/*.rb'", ")", ")", ".", "sort", "elsif", "File", ".", "file?", "(", "file_name", ")", "[", "file_name", "]", "else", "Dir", ".", "glob", "(", "file_name", ")", ".", "sort", "end", "files", ".", "map", "(", "Source", "::", "File", ".", "method", "(", ":new", ")", ")", "end" ]
Return sources for file name @param [String] file_name @return [Enumerable<CLI::Source>] @api private ignore :reek:UtilityFunction
[ "Return", "sources", "for", "file", "name" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/cli.rb#L158-L169
16,377
mbj/unparser
lib/unparser/dsl.rb
Unparser.DSL.define_child
def define_child(name, index) define_method(name) do children.at(index) end private name end
ruby
def define_child(name, index) define_method(name) do children.at(index) end private name end
[ "def", "define_child", "(", "name", ",", "index", ")", "define_method", "(", "name", ")", "do", "children", ".", "at", "(", "index", ")", "end", "private", "name", "end" ]
Define named child @param [Symbol] name @param [Fixnum] index @return [undefined] @api private
[ "Define", "named", "child" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/dsl.rb#L34-L39
16,378
mbj/unparser
lib/unparser/dsl.rb
Unparser.DSL.define_group
def define_group(name, range) define_method(name) do children[range] end private(name) memoize(name) end
ruby
def define_group(name, range) define_method(name) do children[range] end private(name) memoize(name) end
[ "def", "define_group", "(", "name", ",", "range", ")", "define_method", "(", "name", ")", "do", "children", "[", "range", "]", "end", "private", "(", "name", ")", "memoize", "(", "name", ")", "end" ]
Define a group of children @param [Symbol] name @param [Range] range @return [undefined] @pai private
[ "Define", "a", "group", "of", "children" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/dsl.rb#L50-L56
16,379
mbj/unparser
lib/unparser/dsl.rb
Unparser.DSL.children
def children(*names) define_remaining_children(names) names.each_with_index do |name, index| define_child(name, index) end end
ruby
def children(*names) define_remaining_children(names) names.each_with_index do |name, index| define_child(name, index) end end
[ "def", "children", "(", "*", "names", ")", "define_remaining_children", "(", "names", ")", "names", ".", "each_with_index", "do", "|", "name", ",", "index", "|", "define_child", "(", "name", ",", "index", ")", "end", "end" ]
Create name helpers @return [undefined] @api private
[ "Create", "name", "helpers" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/dsl.rb#L64-L70
16,380
mbj/unparser
lib/unparser/preprocessor.rb
Unparser.Preprocessor.visited_children
def visited_children children.map do |node| if node.is_a?(Parser::AST::Node) visit(node) else node end end end
ruby
def visited_children children.map do |node| if node.is_a?(Parser::AST::Node) visit(node) else node end end end
[ "def", "visited_children", "children", ".", "map", "do", "|", "node", "|", "if", "node", ".", "is_a?", "(", "Parser", "::", "AST", "::", "Node", ")", "visit", "(", "node", ")", "else", "node", "end", "end", "end" ]
Return visited children @return [Array<Parser::Ast::Node>] @api private
[ "Return", "visited", "children" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/preprocessor.rb#L79-L87
16,381
mbj/unparser
lib/unparser/emitter.rb
Unparser.Emitter.write_to_buffer
def write_to_buffer emit_comments_before if buffer.fresh_line? dispatch comments.consume(node) emit_eof_comments if parent.is_a?(Root) self end
ruby
def write_to_buffer emit_comments_before if buffer.fresh_line? dispatch comments.consume(node) emit_eof_comments if parent.is_a?(Root) self end
[ "def", "write_to_buffer", "emit_comments_before", "if", "buffer", ".", "fresh_line?", "dispatch", "comments", ".", "consume", "(", "node", ")", "emit_eof_comments", "if", "parent", ".", "is_a?", "(", "Root", ")", "self", "end" ]
Trigger write to buffer @return [self] @api private
[ "Trigger", "write", "to", "buffer" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/emitter.rb#L101-L107
16,382
mbj/unparser
lib/unparser/emitter.rb
Unparser.Emitter.visit
def visit(node) emitter = emitter(node) conditional_parentheses(!emitter.terminated?) do emitter.write_to_buffer end end
ruby
def visit(node) emitter = emitter(node) conditional_parentheses(!emitter.terminated?) do emitter.write_to_buffer end end
[ "def", "visit", "(", "node", ")", "emitter", "=", "emitter", "(", "node", ")", "conditional_parentheses", "(", "!", "emitter", ".", "terminated?", ")", "do", "emitter", ".", "write_to_buffer", "end", "end" ]
Visit ambiguous node @param [Parser::AST::Node] node @return [undefined] @api private
[ "Visit", "ambiguous", "node" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/emitter.rb#L199-L204
16,383
mbj/unparser
lib/unparser/emitter.rb
Unparser.Emitter.delimited
def delimited(nodes, &block) return if nodes.empty? block ||= method(:visit) head, *tail = nodes block.call(head) tail.each do |node| write(DEFAULT_DELIMITER) block.call(node) end end
ruby
def delimited(nodes, &block) return if nodes.empty? block ||= method(:visit) head, *tail = nodes block.call(head) tail.each do |node| write(DEFAULT_DELIMITER) block.call(node) end end
[ "def", "delimited", "(", "nodes", ",", "&", "block", ")", "return", "if", "nodes", ".", "empty?", "block", "||=", "method", "(", ":visit", ")", "head", ",", "*", "tail", "=", "nodes", "block", ".", "call", "(", "head", ")", "tail", ".", "each", "do", "|", "node", "|", "write", "(", "DEFAULT_DELIMITER", ")", "block", ".", "call", "(", "node", ")", "end", "end" ]
Emit delimited body @param [Enumerable<Parser::AST::Node>] nodes @param [String] delimiter @return [undefined] @api private
[ "Emit", "delimited", "body" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/emitter.rb#L271-L281
16,384
mbj/unparser
lib/unparser/emitter.rb
Unparser.Emitter.emit_comments_before
def emit_comments_before(source_part = :expression) comments_before = comments.take_before(node, source_part) return if comments_before.empty? emit_comments(comments_before) buffer.nl end
ruby
def emit_comments_before(source_part = :expression) comments_before = comments.take_before(node, source_part) return if comments_before.empty? emit_comments(comments_before) buffer.nl end
[ "def", "emit_comments_before", "(", "source_part", "=", ":expression", ")", "comments_before", "=", "comments", ".", "take_before", "(", "node", ",", "source_part", ")", "return", "if", "comments_before", ".", "empty?", "emit_comments", "(", "comments_before", ")", "buffer", ".", "nl", "end" ]
Write comments that appeared before source_part in the source @param [Symbol] source_part @return [undefined] @api private
[ "Write", "comments", "that", "appeared", "before", "source_part", "in", "the", "source" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/emitter.rb#L312-L318
16,385
mbj/unparser
lib/unparser/emitter.rb
Unparser.Emitter.emit_eof_comments
def emit_eof_comments emit_eol_comments comments_left = comments.take_all return if comments_left.empty? buffer.nl emit_comments(comments_left) end
ruby
def emit_eof_comments emit_eol_comments comments_left = comments.take_all return if comments_left.empty? buffer.nl emit_comments(comments_left) end
[ "def", "emit_eof_comments", "emit_eol_comments", "comments_left", "=", "comments", ".", "take_all", "return", "if", "comments_left", ".", "empty?", "buffer", ".", "nl", "emit_comments", "(", "comments_left", ")", "end" ]
Write end-of-file comments @return [undefined] @api private
[ "Write", "end", "-", "of", "-", "file", "comments" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/emitter.rb#L338-L345
16,386
mbj/unparser
lib/unparser/emitter.rb
Unparser.Emitter.emit_comments
def emit_comments(comments) max = comments.size - 1 comments.each_with_index do |comment, index| if comment.type.equal?(:document) buffer.append_without_prefix(comment.text.chomp) else write(comment.text) end buffer.nl if index < max end end
ruby
def emit_comments(comments) max = comments.size - 1 comments.each_with_index do |comment, index| if comment.type.equal?(:document) buffer.append_without_prefix(comment.text.chomp) else write(comment.text) end buffer.nl if index < max end end
[ "def", "emit_comments", "(", "comments", ")", "max", "=", "comments", ".", "size", "-", "1", "comments", ".", "each_with_index", "do", "|", "comment", ",", "index", "|", "if", "comment", ".", "type", ".", "equal?", "(", ":document", ")", "buffer", ".", "append_without_prefix", "(", "comment", ".", "text", ".", "chomp", ")", "else", "write", "(", "comment", ".", "text", ")", "end", "buffer", ".", "nl", "if", "index", "<", "max", "end", "end" ]
Write each comment to a separate line @param [Array] comments @return [undefined] @api private
[ "Write", "each", "comment", "to", "a", "separate", "line" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/emitter.rb#L355-L365
16,387
mbj/unparser
lib/unparser/emitter.rb
Unparser.Emitter.emit_body
def emit_body(body = body()) unless body buffer.indent nl buffer.unindent return end visit_indented(body) end
ruby
def emit_body(body = body()) unless body buffer.indent nl buffer.unindent return end visit_indented(body) end
[ "def", "emit_body", "(", "body", "=", "body", "(", ")", ")", "unless", "body", "buffer", ".", "indent", "nl", "buffer", ".", "unindent", "return", "end", "visit_indented", "(", "body", ")", "end" ]
Emit non nil body @param [Parser::AST::Node] node @return [undefined] @api private rubocop:disable MethodCallWithoutArgsParentheses
[ "Emit", "non", "nil", "body" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/emitter.rb#L442-L450
16,388
mbj/unparser
lib/unparser/comments.rb
Unparser.Comments.take_before
def take_before(node, source_part) range = source_range(node, source_part) if range take_while { |comment| comment.location.expression.end_pos <= range.begin_pos } else EMPTY_ARRAY end end
ruby
def take_before(node, source_part) range = source_range(node, source_part) if range take_while { |comment| comment.location.expression.end_pos <= range.begin_pos } else EMPTY_ARRAY end end
[ "def", "take_before", "(", "node", ",", "source_part", ")", "range", "=", "source_range", "(", "node", ",", "source_part", ")", "if", "range", "take_while", "{", "|", "comment", "|", "comment", ".", "location", ".", "expression", ".", "end_pos", "<=", "range", ".", "begin_pos", "}", "else", "EMPTY_ARRAY", "end", "end" ]
Take comments appear in the source before the specified part of the node @param [Parser::AST::Node] node @param [Symbol] source_part @return [Array] @api private
[ "Take", "comments", "appear", "in", "the", "source", "before", "the", "specified", "part", "of", "the", "node" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/comments.rb#L83-L90
16,389
mbj/unparser
lib/unparser/comments.rb
Unparser.Comments.unshift_documents
def unshift_documents(comments) doc_comments, other_comments = comments.partition(&:document?) doc_comments.reverse_each { |comment| @comments.unshift(comment) } other_comments end
ruby
def unshift_documents(comments) doc_comments, other_comments = comments.partition(&:document?) doc_comments.reverse_each { |comment| @comments.unshift(comment) } other_comments end
[ "def", "unshift_documents", "(", "comments", ")", "doc_comments", ",", "other_comments", "=", "comments", ".", "partition", "(", ":document?", ")", "doc_comments", ".", "reverse_each", "{", "|", "comment", "|", "@comments", ".", "unshift", "(", "comment", ")", "}", "other_comments", "end" ]
Unshift document comments and return the rest @param [Array] comments @return [Array] @api private
[ "Unshift", "document", "comments", "and", "return", "the", "rest" ]
aa5112a60fcf384b8837348a4e80a928a215fd1e
https://github.com/mbj/unparser/blob/aa5112a60fcf384b8837348a4e80a928a215fd1e/lib/unparser/comments.rb#L149-L153
16,390
chef/appbundler
lib/appbundler/app.rb
Appbundler.App.copy_bundler_env
def copy_bundler_env gem_path = installed_spec.gem_dir # If we're already using that directory, don't copy (it won't work anyway) return if gem_path == File.dirname(gemfile_lock) FileUtils.install(gemfile_lock, gem_path, mode: 0644) if File.exist?(dot_bundle_dir) && File.directory?(dot_bundle_dir) FileUtils.cp_r(dot_bundle_dir, gem_path) FileUtils.chmod_R("ugo+rX", File.join(gem_path, ".bundle")) end end
ruby
def copy_bundler_env gem_path = installed_spec.gem_dir # If we're already using that directory, don't copy (it won't work anyway) return if gem_path == File.dirname(gemfile_lock) FileUtils.install(gemfile_lock, gem_path, mode: 0644) if File.exist?(dot_bundle_dir) && File.directory?(dot_bundle_dir) FileUtils.cp_r(dot_bundle_dir, gem_path) FileUtils.chmod_R("ugo+rX", File.join(gem_path, ".bundle")) end end
[ "def", "copy_bundler_env", "gem_path", "=", "installed_spec", ".", "gem_dir", "# If we're already using that directory, don't copy (it won't work anyway)", "return", "if", "gem_path", "==", "File", ".", "dirname", "(", "gemfile_lock", ")", "FileUtils", ".", "install", "(", "gemfile_lock", ",", "gem_path", ",", "mode", ":", "0644", ")", "if", "File", ".", "exist?", "(", "dot_bundle_dir", ")", "&&", "File", ".", "directory?", "(", "dot_bundle_dir", ")", "FileUtils", ".", "cp_r", "(", "dot_bundle_dir", ",", "gem_path", ")", "FileUtils", ".", "chmod_R", "(", "\"ugo+rX\"", ",", "File", ".", "join", "(", "gem_path", ",", "\".bundle\"", ")", ")", "end", "end" ]
Copy over any .bundler and Gemfile.lock files to the target gem directory. This will let us run tests from under that directory. This is only on the 2-arg implementations pathway. This is not used for the 3-arg version.
[ "Copy", "over", "any", ".", "bundler", "and", "Gemfile", ".", "lock", "files", "to", "the", "target", "gem", "directory", ".", "This", "will", "let", "us", "run", "tests", "from", "under", "that", "directory", "." ]
7f5782012cf8c3ef5d7590870e3f33a9537b99b2
https://github.com/chef/appbundler/blob/7f5782012cf8c3ef5d7590870e3f33a9537b99b2/lib/appbundler/app.rb#L126-L135
16,391
chef/appbundler
lib/appbundler/app.rb
Appbundler.App.write_merged_lockfiles
def write_merged_lockfiles(without: []) unless external_lockfile? copy_bundler_env return end # handle external lockfile Tempfile.open(".appbundler-gemfile", app_dir) do |t| t.puts "source 'https://rubygems.org'" locked_gems = {} gemfile_lock_specs.each do |s| # next if SHITLIST.include?(s.name) spec = safe_resolve_local_gem(s) next if spec.nil? case s.source when Bundler::Source::Path locked_gems[spec.name] = %Q{gem "#{spec.name}", path: "#{spec.gem_dir}"} when Bundler::Source::Rubygems # FIXME: should add the spec.version as a gem requirement below locked_gems[spec.name] = %Q{gem "#{spec.name}", "= #{spec.version}"} when Bundler::Source::Git raise "FIXME: appbundler needs a patch to support Git gems" else raise "appbundler doens't know this source type" end end seen_gems = {} t.puts "# GEMS FROM GEMFILE:" requested_dependencies(without).each do |dep| next if SHITLIST.include?(dep.name) if locked_gems[dep.name] t.puts locked_gems[dep.name] else string = %Q{gem "#{dep.name}", #{requirement_to_str(dep.requirement)}} string << %Q{, platform: #{dep.platforms}} unless dep.platforms.empty? t.puts string end seen_gems[dep.name] = true end t.puts "# GEMS FROM LOCKFILE: " locked_gems.each do |name, line| next if SHITLIST.include?(name) next if seen_gems[name] t.puts line end t.close puts IO.read(t.path) # debugging Dir.chdir(app_dir) do FileUtils.rm_f "#{app_dir}/Gemfile.lock" Bundler.with_clean_env do so = Mixlib::ShellOut.new("bundle lock", env: { "BUNDLE_GEMFILE" => t.path }) so.run_command so.error! end FileUtils.mv t.path, "#{app_dir}/Gemfile" end end "#{app_dir}/Gemfile" end
ruby
def write_merged_lockfiles(without: []) unless external_lockfile? copy_bundler_env return end # handle external lockfile Tempfile.open(".appbundler-gemfile", app_dir) do |t| t.puts "source 'https://rubygems.org'" locked_gems = {} gemfile_lock_specs.each do |s| # next if SHITLIST.include?(s.name) spec = safe_resolve_local_gem(s) next if spec.nil? case s.source when Bundler::Source::Path locked_gems[spec.name] = %Q{gem "#{spec.name}", path: "#{spec.gem_dir}"} when Bundler::Source::Rubygems # FIXME: should add the spec.version as a gem requirement below locked_gems[spec.name] = %Q{gem "#{spec.name}", "= #{spec.version}"} when Bundler::Source::Git raise "FIXME: appbundler needs a patch to support Git gems" else raise "appbundler doens't know this source type" end end seen_gems = {} t.puts "# GEMS FROM GEMFILE:" requested_dependencies(without).each do |dep| next if SHITLIST.include?(dep.name) if locked_gems[dep.name] t.puts locked_gems[dep.name] else string = %Q{gem "#{dep.name}", #{requirement_to_str(dep.requirement)}} string << %Q{, platform: #{dep.platforms}} unless dep.platforms.empty? t.puts string end seen_gems[dep.name] = true end t.puts "# GEMS FROM LOCKFILE: " locked_gems.each do |name, line| next if SHITLIST.include?(name) next if seen_gems[name] t.puts line end t.close puts IO.read(t.path) # debugging Dir.chdir(app_dir) do FileUtils.rm_f "#{app_dir}/Gemfile.lock" Bundler.with_clean_env do so = Mixlib::ShellOut.new("bundle lock", env: { "BUNDLE_GEMFILE" => t.path }) so.run_command so.error! end FileUtils.mv t.path, "#{app_dir}/Gemfile" end end "#{app_dir}/Gemfile" end
[ "def", "write_merged_lockfiles", "(", "without", ":", "[", "]", ")", "unless", "external_lockfile?", "copy_bundler_env", "return", "end", "# handle external lockfile", "Tempfile", ".", "open", "(", "\".appbundler-gemfile\"", ",", "app_dir", ")", "do", "|", "t", "|", "t", ".", "puts", "\"source 'https://rubygems.org'\"", "locked_gems", "=", "{", "}", "gemfile_lock_specs", ".", "each", "do", "|", "s", "|", "# next if SHITLIST.include?(s.name)", "spec", "=", "safe_resolve_local_gem", "(", "s", ")", "next", "if", "spec", ".", "nil?", "case", "s", ".", "source", "when", "Bundler", "::", "Source", "::", "Path", "locked_gems", "[", "spec", ".", "name", "]", "=", "%Q{gem \"#{spec.name}\", path: \"#{spec.gem_dir}\"}", "when", "Bundler", "::", "Source", "::", "Rubygems", "# FIXME: should add the spec.version as a gem requirement below", "locked_gems", "[", "spec", ".", "name", "]", "=", "%Q{gem \"#{spec.name}\", \"= #{spec.version}\"}", "when", "Bundler", "::", "Source", "::", "Git", "raise", "\"FIXME: appbundler needs a patch to support Git gems\"", "else", "raise", "\"appbundler doens't know this source type\"", "end", "end", "seen_gems", "=", "{", "}", "t", ".", "puts", "\"# GEMS FROM GEMFILE:\"", "requested_dependencies", "(", "without", ")", ".", "each", "do", "|", "dep", "|", "next", "if", "SHITLIST", ".", "include?", "(", "dep", ".", "name", ")", "if", "locked_gems", "[", "dep", ".", "name", "]", "t", ".", "puts", "locked_gems", "[", "dep", ".", "name", "]", "else", "string", "=", "%Q{gem \"#{dep.name}\", #{requirement_to_str(dep.requirement)}}", "string", "<<", "%Q{, platform: #{dep.platforms}}", "unless", "dep", ".", "platforms", ".", "empty?", "t", ".", "puts", "string", "end", "seen_gems", "[", "dep", ".", "name", "]", "=", "true", "end", "t", ".", "puts", "\"# GEMS FROM LOCKFILE: \"", "locked_gems", ".", "each", "do", "|", "name", ",", "line", "|", "next", "if", "SHITLIST", ".", "include?", "(", "name", ")", "next", "if", "seen_gems", "[", "name", "]", "t", ".", "puts", "line", "end", "t", ".", "close", "puts", "IO", ".", "read", "(", "t", ".", "path", ")", "# debugging", "Dir", ".", "chdir", "(", "app_dir", ")", "do", "FileUtils", ".", "rm_f", "\"#{app_dir}/Gemfile.lock\"", "Bundler", ".", "with_clean_env", "do", "so", "=", "Mixlib", "::", "ShellOut", ".", "new", "(", "\"bundle lock\"", ",", "env", ":", "{", "\"BUNDLE_GEMFILE\"", "=>", "t", ".", "path", "}", ")", "so", ".", "run_command", "so", ".", "error!", "end", "FileUtils", ".", "mv", "t", ".", "path", ",", "\"#{app_dir}/Gemfile\"", "end", "end", "\"#{app_dir}/Gemfile\"", "end" ]
This is the implementation of the 3-arg version of writing the merged lockfiles, when called with the 2-arg version it short-circuits, however, to the copy_bundler_env version above. This code does not affect the generated binstubs at all.
[ "This", "is", "the", "implementation", "of", "the", "3", "-", "arg", "version", "of", "writing", "the", "merged", "lockfiles", "when", "called", "with", "the", "2", "-", "arg", "version", "it", "short", "-", "circuits", "however", "to", "the", "copy_bundler_env", "version", "above", "." ]
7f5782012cf8c3ef5d7590870e3f33a9537b99b2
https://github.com/chef/appbundler/blob/7f5782012cf8c3ef5d7590870e3f33a9537b99b2/lib/appbundler/app.rb#L143-L210
16,392
tmm1/ripper-tags
lib/ripper-tags/vim_formatter.rb
RipperTags.VimFormatter.with_output
def with_output super do |out| out.puts header @queued_write = [] yield out @queued_write.sort.each do |line| out.puts(line) end end end
ruby
def with_output super do |out| out.puts header @queued_write = [] yield out @queued_write.sort.each do |line| out.puts(line) end end end
[ "def", "with_output", "super", "do", "|", "out", "|", "out", ".", "puts", "header", "@queued_write", "=", "[", "]", "yield", "out", "@queued_write", ".", "sort", ".", "each", "do", "|", "line", "|", "out", ".", "puts", "(", "line", ")", "end", "end", "end" ]
prepend header and sort lines before closing output
[ "prepend", "header", "and", "sort", "lines", "before", "closing", "output" ]
7f31ab7d9009ea2c566e81901cd344b04e6356e1
https://github.com/tmm1/ripper-tags/blob/7f31ab7d9009ea2c566e81901cd344b04e6356e1/lib/ripper-tags/vim_formatter.rb#L21-L30
16,393
tmm1/ripper-tags
lib/ripper-tags/parser.rb
RipperTags.Parser.on_command_call
def on_command_call(*args) if args.last && :args == args.last[0] args_add = args.pop call = on_call(*args) on_method_add_arg(call, args_add) else super end end
ruby
def on_command_call(*args) if args.last && :args == args.last[0] args_add = args.pop call = on_call(*args) on_method_add_arg(call, args_add) else super end end
[ "def", "on_command_call", "(", "*", "args", ")", "if", "args", ".", "last", "&&", ":args", "==", "args", ".", "last", "[", "0", "]", "args_add", "=", "args", ".", "pop", "call", "=", "on_call", "(", "args", ")", "on_method_add_arg", "(", "call", ",", "args_add", ")", "else", "super", "end", "end" ]
handle `Class.new arg` call without parens
[ "handle", "Class", ".", "new", "arg", "call", "without", "parens" ]
7f31ab7d9009ea2c566e81901cd344b04e6356e1
https://github.com/tmm1/ripper-tags/blob/7f31ab7d9009ea2c566e81901cd344b04e6356e1/lib/ripper-tags/parser.rb#L245-L253
16,394
tmm1/ripper-tags
lib/ripper-tags/parser.rb
RipperTags.Visitor.on_assign
def on_assign(name, rhs, line, *junk) return unless name =~ /^[A-Z]/ && junk.empty? if rhs && :call == rhs[0] && rhs[1] && "#{rhs[1][0]}.#{rhs[2]}" =~ /^(Class|Module|Struct)\.new$/ kind = $1 == 'Module' ? :module : :class superclass = $1 == 'Class' ? rhs[3] : nil superclass.flatten! if superclass return on_module_or_class(kind, [name, line], superclass, rhs[4]) end namespace = @namespace if name.include?('::') parts = name.split('::') name = parts.pop namespace = namespace + parts end process(rhs) emit_tag :constant, line, :name => name, :full_name => (namespace + [name]).join('::'), :class => namespace.join('::') end
ruby
def on_assign(name, rhs, line, *junk) return unless name =~ /^[A-Z]/ && junk.empty? if rhs && :call == rhs[0] && rhs[1] && "#{rhs[1][0]}.#{rhs[2]}" =~ /^(Class|Module|Struct)\.new$/ kind = $1 == 'Module' ? :module : :class superclass = $1 == 'Class' ? rhs[3] : nil superclass.flatten! if superclass return on_module_or_class(kind, [name, line], superclass, rhs[4]) end namespace = @namespace if name.include?('::') parts = name.split('::') name = parts.pop namespace = namespace + parts end process(rhs) emit_tag :constant, line, :name => name, :full_name => (namespace + [name]).join('::'), :class => namespace.join('::') end
[ "def", "on_assign", "(", "name", ",", "rhs", ",", "line", ",", "*", "junk", ")", "return", "unless", "name", "=~", "/", "/", "&&", "junk", ".", "empty?", "if", "rhs", "&&", ":call", "==", "rhs", "[", "0", "]", "&&", "rhs", "[", "1", "]", "&&", "\"#{rhs[1][0]}.#{rhs[2]}\"", "=~", "/", "\\.", "/", "kind", "=", "$1", "==", "'Module'", "?", ":module", ":", ":class", "superclass", "=", "$1", "==", "'Class'", "?", "rhs", "[", "3", "]", ":", "nil", "superclass", ".", "flatten!", "if", "superclass", "return", "on_module_or_class", "(", "kind", ",", "[", "name", ",", "line", "]", ",", "superclass", ",", "rhs", "[", "4", "]", ")", "end", "namespace", "=", "@namespace", "if", "name", ".", "include?", "(", "'::'", ")", "parts", "=", "name", ".", "split", "(", "'::'", ")", "name", "=", "parts", ".", "pop", "namespace", "=", "namespace", "+", "parts", "end", "process", "(", "rhs", ")", "emit_tag", ":constant", ",", "line", ",", ":name", "=>", "name", ",", ":full_name", "=>", "(", "namespace", "+", "[", "name", "]", ")", ".", "join", "(", "'::'", ")", ",", ":class", "=>", "namespace", ".", "join", "(", "'::'", ")", "end" ]
Ripper trips up on keyword arguments in pre-2.1 Ruby and supplies extra arguments that we just ignore here
[ "Ripper", "trips", "up", "on", "keyword", "arguments", "in", "pre", "-", "2", ".", "1", "Ruby", "and", "supplies", "extra", "arguments", "that", "we", "just", "ignore", "here" ]
7f31ab7d9009ea2c566e81901cd344b04e6356e1
https://github.com/tmm1/ripper-tags/blob/7f31ab7d9009ea2c566e81901cd344b04e6356e1/lib/ripper-tags/parser.rb#L423-L446
16,395
prograils/lit
lib/lit/i18n_backend.rb
Lit.I18nBackend.store_translations
def store_translations(locale, data, options = {}) super ActiveRecord::Base.transaction do store_item(locale, data) end if store_items? && valid_locale?(locale) end
ruby
def store_translations(locale, data, options = {}) super ActiveRecord::Base.transaction do store_item(locale, data) end if store_items? && valid_locale?(locale) end
[ "def", "store_translations", "(", "locale", ",", "data", ",", "options", "=", "{", "}", ")", "super", "ActiveRecord", "::", "Base", ".", "transaction", "do", "store_item", "(", "locale", ",", "data", ")", "end", "if", "store_items?", "&&", "valid_locale?", "(", "locale", ")", "end" ]
Stores the given translations. @param [String] locale the locale (ie "en") to store translations for @param [Hash] data nested key-value pairs to be added as blurbs
[ "Stores", "the", "given", "translations", "." ]
a230cb450694848834c1afb9f26d5c24bc54e68e
https://github.com/prograils/lit/blob/a230cb450694848834c1afb9f26d5c24bc54e68e/lib/lit/i18n_backend.rb#L48-L53
16,396
prograils/lit
lib/lit/cache.rb
Lit.Cache.fallback_localization
def fallback_localization(locale, key_without_locale) value = nil return nil unless fallbacks = ::Rails.application.config.i18n.fallbacks keys = fallbacks == true ? @locale_cache.keys : fallbacks keys.map(&:to_s).each do |lc| if lc != locale.locale && value.nil? nk = "#{lc}.#{key_without_locale}" v = localizations[nk] value = v if v.present? && value.nil? end end value end
ruby
def fallback_localization(locale, key_without_locale) value = nil return nil unless fallbacks = ::Rails.application.config.i18n.fallbacks keys = fallbacks == true ? @locale_cache.keys : fallbacks keys.map(&:to_s).each do |lc| if lc != locale.locale && value.nil? nk = "#{lc}.#{key_without_locale}" v = localizations[nk] value = v if v.present? && value.nil? end end value end
[ "def", "fallback_localization", "(", "locale", ",", "key_without_locale", ")", "value", "=", "nil", "return", "nil", "unless", "fallbacks", "=", "::", "Rails", ".", "application", ".", "config", ".", "i18n", ".", "fallbacks", "keys", "=", "fallbacks", "==", "true", "?", "@locale_cache", ".", "keys", ":", "fallbacks", "keys", ".", "map", "(", ":to_s", ")", ".", "each", "do", "|", "lc", "|", "if", "lc", "!=", "locale", ".", "locale", "&&", "value", ".", "nil?", "nk", "=", "\"#{lc}.#{key_without_locale}\"", "v", "=", "localizations", "[", "nk", "]", "value", "=", "v", "if", "v", ".", "present?", "&&", "value", ".", "nil?", "end", "end", "value", "end" ]
fallback to translation in different locale
[ "fallback", "to", "translation", "in", "different", "locale" ]
a230cb450694848834c1afb9f26d5c24bc54e68e
https://github.com/prograils/lit/blob/a230cb450694848834c1afb9f26d5c24bc54e68e/lib/lit/cache.rb#L204-L216
16,397
prograils/lit
lib/lit/cache.rb
Lit.Cache.fallback_to_default
def fallback_to_default(localization_key, localization) localization_key.localizations.where.not(default_value: nil). \ where.not(id: localization.id).first&.default_value end
ruby
def fallback_to_default(localization_key, localization) localization_key.localizations.where.not(default_value: nil). \ where.not(id: localization.id).first&.default_value end
[ "def", "fallback_to_default", "(", "localization_key", ",", "localization", ")", "localization_key", ".", "localizations", ".", "where", ".", "not", "(", "default_value", ":", "nil", ")", ".", "where", ".", "not", "(", "id", ":", "localization", ".", "id", ")", ".", "first", "&.", "default_value", "end" ]
tries to get `default_value` from localization_key - checks other localizations
[ "tries", "to", "get", "default_value", "from", "localization_key", "-", "checks", "other", "localizations" ]
a230cb450694848834c1afb9f26d5c24bc54e68e
https://github.com/prograils/lit/blob/a230cb450694848834c1afb9f26d5c24bc54e68e/lib/lit/cache.rb#L220-L223
16,398
prograils/lit
lib/lit/cloud_translation.rb
Lit.CloudTranslation.translate
def translate(text:, from: nil, to:, **opts) provider.translate(text: text, from: from, to: to, **opts) end
ruby
def translate(text:, from: nil, to:, **opts) provider.translate(text: text, from: from, to: to, **opts) end
[ "def", "translate", "(", "text", ":", ",", "from", ":", "nil", ",", "to", ":", ",", "**", "opts", ")", "provider", ".", "translate", "(", "text", ":", "text", ",", "from", ":", "from", ",", "to", ":", "to", ",", "**", "opts", ")", "end" ]
Uses the active translation provider to translate a text or array of texts. @param [String, Array] text The text (or array of texts) to translate @param [Symbol, String] from The language to translate from. If not given, auto-detection will be attempted. @param [Symbol, String] to The language to translate to. @param [Hash] opts Additional, provider-specific optional parameters.
[ "Uses", "the", "active", "translation", "provider", "to", "translate", "a", "text", "or", "array", "of", "texts", "." ]
a230cb450694848834c1afb9f26d5c24bc54e68e
https://github.com/prograils/lit/blob/a230cb450694848834c1afb9f26d5c24bc54e68e/lib/lit/cloud_translation.rb#L29-L31
16,399
prograils/lit
lib/lit/cloud_translation.rb
Lit.CloudTranslation.configure
def configure(&block) unless provider raise 'Translation provider not selected yet. Use `Lit::CloudTranslation' \ '.provider = PROVIDER_KLASS` before calling #configure.' end provider.tap do |p| p.configure(&block) end end
ruby
def configure(&block) unless provider raise 'Translation provider not selected yet. Use `Lit::CloudTranslation' \ '.provider = PROVIDER_KLASS` before calling #configure.' end provider.tap do |p| p.configure(&block) end end
[ "def", "configure", "(", "&", "block", ")", "unless", "provider", "raise", "'Translation provider not selected yet. Use `Lit::CloudTranslation'", "'.provider = PROVIDER_KLASS` before calling #configure.'", "end", "provider", ".", "tap", "do", "|", "p", "|", "p", ".", "configure", "(", "block", ")", "end", "end" ]
Optional if provider-speciffic environment variables are set correctly. Configures the cloud translation provider with specific settings, overriding those from environment if needed. @example Lit::CloudTranslation.configure do |config| # For Yandex, this overrides the YANDEX_TRANSLATE_API_KEY env config.api_key = 'my_awesome_api_key' end
[ "Optional", "if", "provider", "-", "speciffic", "environment", "variables", "are", "set", "correctly", ".", "Configures", "the", "cloud", "translation", "provider", "with", "specific", "settings", "overriding", "those", "from", "environment", "if", "needed", "." ]
a230cb450694848834c1afb9f26d5c24bc54e68e
https://github.com/prograils/lit/blob/a230cb450694848834c1afb9f26d5c24bc54e68e/lib/lit/cloud_translation.rb#L42-L50