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
7,500
Potpourri-Projects/fbuser
app/controllers/fbuser/api/v1/users_controller.rb
Fbuser.Api::V1::UsersController.index_authorize
def index_authorize if !::Authorization::Fbuser::V1::User.index?(current_user) render :json => {errors: "User is not authorized for this action"}, status: :forbidden end end
ruby
def index_authorize if !::Authorization::Fbuser::V1::User.index?(current_user) render :json => {errors: "User is not authorized for this action"}, status: :forbidden end end
[ "def", "index_authorize", "if", "!", "::", "Authorization", "::", "Fbuser", "::", "V1", "::", "User", ".", "index?", "(", "current_user", ")", "render", ":json", "=>", "{", "errors", ":", "\"User is not authorized for this action\"", "}", ",", "status", ":", ":forbidden", "end", "end" ]
Authorizations below here
[ "Authorizations", "below", "here" ]
d39e6f107bdcf9d969df5e7b175e0e4f229e877d
https://github.com/Potpourri-Projects/fbuser/blob/d39e6f107bdcf9d969df5e7b175e0e4f229e877d/app/controllers/fbuser/api/v1/users_controller.rb#L70-L74
7,501
ccclin/decay_heat_with_nuclear
lib/decay_heat_with_nuclear/thermal_data.rb
ThermalData.DataForANS_5_1_1979.thePi
def thePi hash = HashWithThermalFission.new hash.thermal_fission[:U235] = 0.98 hash.thermal_fission[:Pu239] = 0.01 hash.thermal_fission[:U238] = 0.01 hash.thermal_fission end
ruby
def thePi hash = HashWithThermalFission.new hash.thermal_fission[:U235] = 0.98 hash.thermal_fission[:Pu239] = 0.01 hash.thermal_fission[:U238] = 0.01 hash.thermal_fission end
[ "def", "thePi", "hash", "=", "HashWithThermalFission", ".", "new", "hash", ".", "thermal_fission", "[", ":U235", "]", "=", "0.98", "hash", ".", "thermal_fission", "[", ":Pu239", "]", "=", "0.01", "hash", ".", "thermal_fission", "[", ":U238", "]", "=", "0.01", "hash", ".", "thermal_fission", "end" ]
thePi is Pi in ANS-5.1-1979.
[ "thePi", "is", "Pi", "in", "ANS", "-", "5", ".", "1", "-", "1979", "." ]
fc81505803c9d8488420216ca6f0e6597b2c47d7
https://github.com/ccclin/decay_heat_with_nuclear/blob/fc81505803c9d8488420216ca6f0e6597b2c47d7/lib/decay_heat_with_nuclear/thermal_data.rb#L35-L43
7,502
ccclin/decay_heat_with_nuclear
lib/decay_heat_with_nuclear/thermal_data.rb
ThermalData.DataForANS_5_1_1979.theU235_alpha
def theU235_alpha array = Array.new(23) array[0] = 6.5057E-01 array[1] = 5.1264E-01 array[2] = 2.4384E-01 array[3] = 1.3850E-01 array[4] = 5.544E-02 array[5] = 2.2225E-02 array[6] = 3.3088E-03 array[7] = 9.3015E-04 array[8] = 8.0943E-04 array[9] = 1.9567E-04 array[10] = 3.2535E-05 array[11] = 7.5595E-06 array[12] = 2.5232E-06 array[13] = 4.9948E-07 array[14] = 1.8531E-07 array[15] = 2.6608E-08 array[16] = 2.2398E-09 array[17] = 8.1641E-12 array[18] = 8.7797E-11 array[19] = 2.5131E-14 array[20] = 3.2176E-16 array[21] = 4.5038E-17 array[22] = 7.4791E-17 array end
ruby
def theU235_alpha array = Array.new(23) array[0] = 6.5057E-01 array[1] = 5.1264E-01 array[2] = 2.4384E-01 array[3] = 1.3850E-01 array[4] = 5.544E-02 array[5] = 2.2225E-02 array[6] = 3.3088E-03 array[7] = 9.3015E-04 array[8] = 8.0943E-04 array[9] = 1.9567E-04 array[10] = 3.2535E-05 array[11] = 7.5595E-06 array[12] = 2.5232E-06 array[13] = 4.9948E-07 array[14] = 1.8531E-07 array[15] = 2.6608E-08 array[16] = 2.2398E-09 array[17] = 8.1641E-12 array[18] = 8.7797E-11 array[19] = 2.5131E-14 array[20] = 3.2176E-16 array[21] = 4.5038E-17 array[22] = 7.4791E-17 array end
[ "def", "theU235_alpha", "array", "=", "Array", ".", "new", "(", "23", ")", "array", "[", "0", "]", "=", "6.5057E-01", "array", "[", "1", "]", "=", "5.1264E-01", "array", "[", "2", "]", "=", "2.4384E-01", "array", "[", "3", "]", "=", "1.3850E-01", "array", "[", "4", "]", "=", "5.544E-02", "array", "[", "5", "]", "=", "2.2225E-02", "array", "[", "6", "]", "=", "3.3088E-03", "array", "[", "7", "]", "=", "9.3015E-04", "array", "[", "8", "]", "=", "8.0943E-04", "array", "[", "9", "]", "=", "1.9567E-04", "array", "[", "10", "]", "=", "3.2535E-05", "array", "[", "11", "]", "=", "7.5595E-06", "array", "[", "12", "]", "=", "2.5232E-06", "array", "[", "13", "]", "=", "4.9948E-07", "array", "[", "14", "]", "=", "1.8531E-07", "array", "[", "15", "]", "=", "2.6608E-08", "array", "[", "16", "]", "=", "2.2398E-09", "array", "[", "17", "]", "=", "8.1641E-12", "array", "[", "18", "]", "=", "8.7797E-11", "array", "[", "19", "]", "=", "2.5131E-14", "array", "[", "20", "]", "=", "3.2176E-16", "array", "[", "21", "]", "=", "4.5038E-17", "array", "[", "22", "]", "=", "7.4791E-17", "array", "end" ]
theU235_alpha is alpha in ANS-5.1-1979 Table 7.
[ "theU235_alpha", "is", "alpha", "in", "ANS", "-", "5", ".", "1", "-", "1979", "Table", "7", "." ]
fc81505803c9d8488420216ca6f0e6597b2c47d7
https://github.com/ccclin/decay_heat_with_nuclear/blob/fc81505803c9d8488420216ca6f0e6597b2c47d7/lib/decay_heat_with_nuclear/thermal_data.rb#L55-L83
7,503
ccclin/decay_heat_with_nuclear
lib/decay_heat_with_nuclear/thermal_data.rb
ThermalData.DataForANS_5_1_1979.theU235_lamda
def theU235_lamda array = Array.new(23) array[0] = 2.2138E+01 array[1] = 5.1587E-01 array[2] = 1.9594E-01 array[3] = 1.0314E-01 array[4] = 3.3656E-02 array[5] = 1.1681E-02 array[6] = 3.5870E-03 array[7] = 1.3930E-03 array[8] = 6.2630E-04 array[9] = 1.8906E-04 array[10] = 5.4988E-05 array[11] = 2.0958E-05 array[12] = 1.0010E-05 array[13] = 2.5438E-06 array[14] = 6.6361E-07 array[15] = 1.2290E-07 array[16] = 2.7213E-08 array[17] = 4.3714E-09 array[18] = 7.5780E-10 array[19] = 2.4786E-10 array[20] = 2.2384E-13 array[21] = 2.4600E-14 array[22] = 1.5699E-14 array end
ruby
def theU235_lamda array = Array.new(23) array[0] = 2.2138E+01 array[1] = 5.1587E-01 array[2] = 1.9594E-01 array[3] = 1.0314E-01 array[4] = 3.3656E-02 array[5] = 1.1681E-02 array[6] = 3.5870E-03 array[7] = 1.3930E-03 array[8] = 6.2630E-04 array[9] = 1.8906E-04 array[10] = 5.4988E-05 array[11] = 2.0958E-05 array[12] = 1.0010E-05 array[13] = 2.5438E-06 array[14] = 6.6361E-07 array[15] = 1.2290E-07 array[16] = 2.7213E-08 array[17] = 4.3714E-09 array[18] = 7.5780E-10 array[19] = 2.4786E-10 array[20] = 2.2384E-13 array[21] = 2.4600E-14 array[22] = 1.5699E-14 array end
[ "def", "theU235_lamda", "array", "=", "Array", ".", "new", "(", "23", ")", "array", "[", "0", "]", "=", "2.2138E+01", "array", "[", "1", "]", "=", "5.1587E-01", "array", "[", "2", "]", "=", "1.9594E-01", "array", "[", "3", "]", "=", "1.0314E-01", "array", "[", "4", "]", "=", "3.3656E-02", "array", "[", "5", "]", "=", "1.1681E-02", "array", "[", "6", "]", "=", "3.5870E-03", "array", "[", "7", "]", "=", "1.3930E-03", "array", "[", "8", "]", "=", "6.2630E-04", "array", "[", "9", "]", "=", "1.8906E-04", "array", "[", "10", "]", "=", "5.4988E-05", "array", "[", "11", "]", "=", "2.0958E-05", "array", "[", "12", "]", "=", "1.0010E-05", "array", "[", "13", "]", "=", "2.5438E-06", "array", "[", "14", "]", "=", "6.6361E-07", "array", "[", "15", "]", "=", "1.2290E-07", "array", "[", "16", "]", "=", "2.7213E-08", "array", "[", "17", "]", "=", "4.3714E-09", "array", "[", "18", "]", "=", "7.5780E-10", "array", "[", "19", "]", "=", "2.4786E-10", "array", "[", "20", "]", "=", "2.2384E-13", "array", "[", "21", "]", "=", "2.4600E-14", "array", "[", "22", "]", "=", "1.5699E-14", "array", "end" ]
theU235_lamda is lamda in ANS-5.1-1979 Table 7.
[ "theU235_lamda", "is", "lamda", "in", "ANS", "-", "5", ".", "1", "-", "1979", "Table", "7", "." ]
fc81505803c9d8488420216ca6f0e6597b2c47d7
https://github.com/ccclin/decay_heat_with_nuclear/blob/fc81505803c9d8488420216ca6f0e6597b2c47d7/lib/decay_heat_with_nuclear/thermal_data.rb#L86-L114
7,504
ccclin/decay_heat_with_nuclear
lib/decay_heat_with_nuclear/thermal_data.rb
ThermalData.DataForANS_5_1_1979.thePu239_alpha
def thePu239_alpha array = Array.new(23) array[0] = 2.083E-01 array[1] = 3.853E-01 array[2] = 2.213E-01 array[3] = 9.460E-02 array[4] = 3.531E-02 array[5] = 2.292E-02 array[6] = 3.946E-03 array[7] = 1.317E-03 array[8] = 7.052E-04 array[9] = 1.432E-04 array[10] = 1.765E-05 array[11] = 7.347E-06 array[12] = 1.747E-06 array[13] = 5.481E-07 array[14] = 1.671E-07 array[15] = 2.112E-08 array[16] = 2.996E-09 array[17] = 5.107E-11 array[18] = 5.730E-11 array[19] = 4.138E-14 array[20] = 1.088E-15 array[21] = 2.454E-17 array[22] = 7.557E-17 array end
ruby
def thePu239_alpha array = Array.new(23) array[0] = 2.083E-01 array[1] = 3.853E-01 array[2] = 2.213E-01 array[3] = 9.460E-02 array[4] = 3.531E-02 array[5] = 2.292E-02 array[6] = 3.946E-03 array[7] = 1.317E-03 array[8] = 7.052E-04 array[9] = 1.432E-04 array[10] = 1.765E-05 array[11] = 7.347E-06 array[12] = 1.747E-06 array[13] = 5.481E-07 array[14] = 1.671E-07 array[15] = 2.112E-08 array[16] = 2.996E-09 array[17] = 5.107E-11 array[18] = 5.730E-11 array[19] = 4.138E-14 array[20] = 1.088E-15 array[21] = 2.454E-17 array[22] = 7.557E-17 array end
[ "def", "thePu239_alpha", "array", "=", "Array", ".", "new", "(", "23", ")", "array", "[", "0", "]", "=", "2.083E-01", "array", "[", "1", "]", "=", "3.853E-01", "array", "[", "2", "]", "=", "2.213E-01", "array", "[", "3", "]", "=", "9.460E-02", "array", "[", "4", "]", "=", "3.531E-02", "array", "[", "5", "]", "=", "2.292E-02", "array", "[", "6", "]", "=", "3.946E-03", "array", "[", "7", "]", "=", "1.317E-03", "array", "[", "8", "]", "=", "7.052E-04", "array", "[", "9", "]", "=", "1.432E-04", "array", "[", "10", "]", "=", "1.765E-05", "array", "[", "11", "]", "=", "7.347E-06", "array", "[", "12", "]", "=", "1.747E-06", "array", "[", "13", "]", "=", "5.481E-07", "array", "[", "14", "]", "=", "1.671E-07", "array", "[", "15", "]", "=", "2.112E-08", "array", "[", "16", "]", "=", "2.996E-09", "array", "[", "17", "]", "=", "5.107E-11", "array", "[", "18", "]", "=", "5.730E-11", "array", "[", "19", "]", "=", "4.138E-14", "array", "[", "20", "]", "=", "1.088E-15", "array", "[", "21", "]", "=", "2.454E-17", "array", "[", "22", "]", "=", "7.557E-17", "array", "end" ]
thePu239_alpha is alpha in ANS-5.1-1979 Table 8.
[ "thePu239_alpha", "is", "alpha", "in", "ANS", "-", "5", ".", "1", "-", "1979", "Table", "8", "." ]
fc81505803c9d8488420216ca6f0e6597b2c47d7
https://github.com/ccclin/decay_heat_with_nuclear/blob/fc81505803c9d8488420216ca6f0e6597b2c47d7/lib/decay_heat_with_nuclear/thermal_data.rb#L117-L145
7,505
ccclin/decay_heat_with_nuclear
lib/decay_heat_with_nuclear/thermal_data.rb
ThermalData.DataForANS_5_1_1979.thePu239_lamda
def thePu239_lamda array = Array.new(23) array[0] = 1.002E+01 array[1] = 6.433E-01 array[2] = 2.186E-01 array[3] = 1.004E-01 array[4] = 3.728E-02 array[5] = 1.435E-02 array[6] = 4.549E-03 array[7] = 1.328E-03 array[8] = 5.356E-04 array[9] = 1.730E-04 array[10] = 4.881E-05 array[11] = 2.006E-05 array[12] = 8.319E-06 array[13] = 2.358E-06 array[14] = 6.450E-07 array[15] = 1.278E-07 array[16] = 2.466E-08 array[17] = 9.378E-09 array[18] = 7.450E-10 array[19] = 2.426E-10 array[20] = 2.210E-13 array[21] = 2.640E-14 array[22] = 1.380E-14 array end
ruby
def thePu239_lamda array = Array.new(23) array[0] = 1.002E+01 array[1] = 6.433E-01 array[2] = 2.186E-01 array[3] = 1.004E-01 array[4] = 3.728E-02 array[5] = 1.435E-02 array[6] = 4.549E-03 array[7] = 1.328E-03 array[8] = 5.356E-04 array[9] = 1.730E-04 array[10] = 4.881E-05 array[11] = 2.006E-05 array[12] = 8.319E-06 array[13] = 2.358E-06 array[14] = 6.450E-07 array[15] = 1.278E-07 array[16] = 2.466E-08 array[17] = 9.378E-09 array[18] = 7.450E-10 array[19] = 2.426E-10 array[20] = 2.210E-13 array[21] = 2.640E-14 array[22] = 1.380E-14 array end
[ "def", "thePu239_lamda", "array", "=", "Array", ".", "new", "(", "23", ")", "array", "[", "0", "]", "=", "1.002E+01", "array", "[", "1", "]", "=", "6.433E-01", "array", "[", "2", "]", "=", "2.186E-01", "array", "[", "3", "]", "=", "1.004E-01", "array", "[", "4", "]", "=", "3.728E-02", "array", "[", "5", "]", "=", "1.435E-02", "array", "[", "6", "]", "=", "4.549E-03", "array", "[", "7", "]", "=", "1.328E-03", "array", "[", "8", "]", "=", "5.356E-04", "array", "[", "9", "]", "=", "1.730E-04", "array", "[", "10", "]", "=", "4.881E-05", "array", "[", "11", "]", "=", "2.006E-05", "array", "[", "12", "]", "=", "8.319E-06", "array", "[", "13", "]", "=", "2.358E-06", "array", "[", "14", "]", "=", "6.450E-07", "array", "[", "15", "]", "=", "1.278E-07", "array", "[", "16", "]", "=", "2.466E-08", "array", "[", "17", "]", "=", "9.378E-09", "array", "[", "18", "]", "=", "7.450E-10", "array", "[", "19", "]", "=", "2.426E-10", "array", "[", "20", "]", "=", "2.210E-13", "array", "[", "21", "]", "=", "2.640E-14", "array", "[", "22", "]", "=", "1.380E-14", "array", "end" ]
thePu239_lamda is lamda in ANS-5.1-1979 Table 8.
[ "thePu239_lamda", "is", "lamda", "in", "ANS", "-", "5", ".", "1", "-", "1979", "Table", "8", "." ]
fc81505803c9d8488420216ca6f0e6597b2c47d7
https://github.com/ccclin/decay_heat_with_nuclear/blob/fc81505803c9d8488420216ca6f0e6597b2c47d7/lib/decay_heat_with_nuclear/thermal_data.rb#L148-L176
7,506
ccclin/decay_heat_with_nuclear
lib/decay_heat_with_nuclear/thermal_data.rb
ThermalData.DataForANS_5_1_1979.theU238_alpha
def theU238_alpha array = Array.new(23) array[0] = 1.2311E+0 array[1] = 1.1486E+0 array[2] = 7.0701E-01 array[3] = 2.5209E-01 array[4] = 7.187E-02 array[5] = 2.8291E-02 array[6] = 6.8382E-03 array[7] = 1.2322E-03 array[8] = 6.8409E-04 array[9] = 1.6975E-04 array[10] = 2.4182E-05 array[11] = 6.6356E-06 array[12] = 1.0075E-06 array[13] = 4.9894E-07 array[14] = 1.6352E-07 array[15] = 2.3355E-08 array[16] = 2.8094E-09 array[17] = 3.6236E-11 array[18] = 6.4577E-11 array[19] = 4.4963E-14 array[20] = 3.6654E-16 array[21] = 5.6293E-17 array[22] = 7.1602E-17 array end
ruby
def theU238_alpha array = Array.new(23) array[0] = 1.2311E+0 array[1] = 1.1486E+0 array[2] = 7.0701E-01 array[3] = 2.5209E-01 array[4] = 7.187E-02 array[5] = 2.8291E-02 array[6] = 6.8382E-03 array[7] = 1.2322E-03 array[8] = 6.8409E-04 array[9] = 1.6975E-04 array[10] = 2.4182E-05 array[11] = 6.6356E-06 array[12] = 1.0075E-06 array[13] = 4.9894E-07 array[14] = 1.6352E-07 array[15] = 2.3355E-08 array[16] = 2.8094E-09 array[17] = 3.6236E-11 array[18] = 6.4577E-11 array[19] = 4.4963E-14 array[20] = 3.6654E-16 array[21] = 5.6293E-17 array[22] = 7.1602E-17 array end
[ "def", "theU238_alpha", "array", "=", "Array", ".", "new", "(", "23", ")", "array", "[", "0", "]", "=", "1.2311E+0", "array", "[", "1", "]", "=", "1.1486E+0", "array", "[", "2", "]", "=", "7.0701E-01", "array", "[", "3", "]", "=", "2.5209E-01", "array", "[", "4", "]", "=", "7.187E-02", "array", "[", "5", "]", "=", "2.8291E-02", "array", "[", "6", "]", "=", "6.8382E-03", "array", "[", "7", "]", "=", "1.2322E-03", "array", "[", "8", "]", "=", "6.8409E-04", "array", "[", "9", "]", "=", "1.6975E-04", "array", "[", "10", "]", "=", "2.4182E-05", "array", "[", "11", "]", "=", "6.6356E-06", "array", "[", "12", "]", "=", "1.0075E-06", "array", "[", "13", "]", "=", "4.9894E-07", "array", "[", "14", "]", "=", "1.6352E-07", "array", "[", "15", "]", "=", "2.3355E-08", "array", "[", "16", "]", "=", "2.8094E-09", "array", "[", "17", "]", "=", "3.6236E-11", "array", "[", "18", "]", "=", "6.4577E-11", "array", "[", "19", "]", "=", "4.4963E-14", "array", "[", "20", "]", "=", "3.6654E-16", "array", "[", "21", "]", "=", "5.6293E-17", "array", "[", "22", "]", "=", "7.1602E-17", "array", "end" ]
theU238_alpha is alpha in ANS-5.1-1979 Table 9.
[ "theU238_alpha", "is", "alpha", "in", "ANS", "-", "5", ".", "1", "-", "1979", "Table", "9", "." ]
fc81505803c9d8488420216ca6f0e6597b2c47d7
https://github.com/ccclin/decay_heat_with_nuclear/blob/fc81505803c9d8488420216ca6f0e6597b2c47d7/lib/decay_heat_with_nuclear/thermal_data.rb#L179-L207
7,507
ccclin/decay_heat_with_nuclear
lib/decay_heat_with_nuclear/thermal_data.rb
ThermalData.DataForANS_5_1_1979.theU238_lamda
def theU238_lamda array = Array.new(23) array[0] = 3.2881E+0 array[1] = 9.3805E-01 array[2] = 3.7073E-01 array[3] = 1.1118E-01 array[4] = 3.6143E-02 array[5] = 1.3272E-02 array[6] = 5.0133E-03 array[7] = 1.3655E-03 array[8] = 5.5158E-04 array[9] = 1.7873E-04 array[10] = 4.9032E-05 array[11] = 1.7058E-05 array[12] = 7.0465E-06 array[13] = 2.3190E-06 array[14] = 6.4480E-07 array[15] = 1.2649E-07 array[16] = 2.5548E-08 array[17] = 8.4782E-09 array[18] = 7.5130E-10 array[19] = 2.4188E-10 array[20] = 2.2739E-13 array[21] = 9.0536E-14 array[22] = 5.6098E-15 array end
ruby
def theU238_lamda array = Array.new(23) array[0] = 3.2881E+0 array[1] = 9.3805E-01 array[2] = 3.7073E-01 array[3] = 1.1118E-01 array[4] = 3.6143E-02 array[5] = 1.3272E-02 array[6] = 5.0133E-03 array[7] = 1.3655E-03 array[8] = 5.5158E-04 array[9] = 1.7873E-04 array[10] = 4.9032E-05 array[11] = 1.7058E-05 array[12] = 7.0465E-06 array[13] = 2.3190E-06 array[14] = 6.4480E-07 array[15] = 1.2649E-07 array[16] = 2.5548E-08 array[17] = 8.4782E-09 array[18] = 7.5130E-10 array[19] = 2.4188E-10 array[20] = 2.2739E-13 array[21] = 9.0536E-14 array[22] = 5.6098E-15 array end
[ "def", "theU238_lamda", "array", "=", "Array", ".", "new", "(", "23", ")", "array", "[", "0", "]", "=", "3.2881E+0", "array", "[", "1", "]", "=", "9.3805E-01", "array", "[", "2", "]", "=", "3.7073E-01", "array", "[", "3", "]", "=", "1.1118E-01", "array", "[", "4", "]", "=", "3.6143E-02", "array", "[", "5", "]", "=", "1.3272E-02", "array", "[", "6", "]", "=", "5.0133E-03", "array", "[", "7", "]", "=", "1.3655E-03", "array", "[", "8", "]", "=", "5.5158E-04", "array", "[", "9", "]", "=", "1.7873E-04", "array", "[", "10", "]", "=", "4.9032E-05", "array", "[", "11", "]", "=", "1.7058E-05", "array", "[", "12", "]", "=", "7.0465E-06", "array", "[", "13", "]", "=", "2.3190E-06", "array", "[", "14", "]", "=", "6.4480E-07", "array", "[", "15", "]", "=", "1.2649E-07", "array", "[", "16", "]", "=", "2.5548E-08", "array", "[", "17", "]", "=", "8.4782E-09", "array", "[", "18", "]", "=", "7.5130E-10", "array", "[", "19", "]", "=", "2.4188E-10", "array", "[", "20", "]", "=", "2.2739E-13", "array", "[", "21", "]", "=", "9.0536E-14", "array", "[", "22", "]", "=", "5.6098E-15", "array", "end" ]
theU238_lamda is lamda in ANS-5.1-1979 Table 9.
[ "theU238_lamda", "is", "lamda", "in", "ANS", "-", "5", ".", "1", "-", "1979", "Table", "9", "." ]
fc81505803c9d8488420216ca6f0e6597b2c47d7
https://github.com/ccclin/decay_heat_with_nuclear/blob/fc81505803c9d8488420216ca6f0e6597b2c47d7/lib/decay_heat_with_nuclear/thermal_data.rb#L210-L238
7,508
bwillis/rockit
lib/rockit/application.rb
Rockit.Application.run
def run rockit_file = CONFIG_FILES.select { |f| File.exists?(f) }.first raise ArgumentError "No Rockitfile found (looking for: #{CONFIG_FILES.join(',')})" unless rockit_file Dsl.new(self).instance_eval(File.read(rockit_file), rockit_file) end
ruby
def run rockit_file = CONFIG_FILES.select { |f| File.exists?(f) }.first raise ArgumentError "No Rockitfile found (looking for: #{CONFIG_FILES.join(',')})" unless rockit_file Dsl.new(self).instance_eval(File.read(rockit_file), rockit_file) end
[ "def", "run", "rockit_file", "=", "CONFIG_FILES", ".", "select", "{", "|", "f", "|", "File", ".", "exists?", "(", "f", ")", "}", ".", "first", "raise", "ArgumentError", "\"No Rockitfile found (looking for: #{CONFIG_FILES.join(',')})\"", "unless", "rockit_file", "Dsl", ".", "new", "(", "self", ")", ".", "instance_eval", "(", "File", ".", "read", "(", "rockit_file", ")", ",", "rockit_file", ")", "end" ]
Run a Rockit configuration file and Rails dependency checks unless turned off by configuration.
[ "Run", "a", "Rockit", "configuration", "file", "and", "Rails", "dependency", "checks", "unless", "turned", "off", "by", "configuration", "." ]
b0604538e2436d6c26a4e29c605235638e819fee
https://github.com/bwillis/rockit/blob/b0604538e2436d6c26a4e29c605235638e819fee/lib/rockit/application.rb#L26-L30
7,509
bwillis/rockit
lib/rockit/application.rb
Rockit.Application.if_string_digest_changed
def if_string_digest_changed(key, input, &block) if_string_changed(key, Digest::SHA256.new.update(input.to_s).hexdigest.to_s, &block) end
ruby
def if_string_digest_changed(key, input, &block) if_string_changed(key, Digest::SHA256.new.update(input.to_s).hexdigest.to_s, &block) end
[ "def", "if_string_digest_changed", "(", "key", ",", "input", ",", "&", "block", ")", "if_string_changed", "(", "key", ",", "Digest", "::", "SHA256", ".", "new", ".", "update", "(", "input", ".", "to_s", ")", ".", "hexdigest", ".", "to_s", ",", "block", ")", "end" ]
If the digest of the input is different from the stored key, execute the block.
[ "If", "the", "digest", "of", "the", "input", "is", "different", "from", "the", "stored", "key", "execute", "the", "block", "." ]
b0604538e2436d6c26a4e29c605235638e819fee
https://github.com/bwillis/rockit/blob/b0604538e2436d6c26a4e29c605235638e819fee/lib/rockit/application.rb#L78-L80
7,510
bwillis/rockit
lib/rockit/application.rb
Rockit.Application.if_file_changed
def if_file_changed(file, &block) if_string_changed(file, Digest::SHA256.file(file).hexdigest.to_s, &block) end
ruby
def if_file_changed(file, &block) if_string_changed(file, Digest::SHA256.file(file).hexdigest.to_s, &block) end
[ "def", "if_file_changed", "(", "file", ",", "&", "block", ")", "if_string_changed", "(", "file", ",", "Digest", "::", "SHA256", ".", "file", "(", "file", ")", ".", "hexdigest", ".", "to_s", ",", "block", ")", "end" ]
If the digest of the file is different from the stored digest, execute the block.
[ "If", "the", "digest", "of", "the", "file", "is", "different", "from", "the", "stored", "digest", "execute", "the", "block", "." ]
b0604538e2436d6c26a4e29c605235638e819fee
https://github.com/bwillis/rockit/blob/b0604538e2436d6c26a4e29c605235638e819fee/lib/rockit/application.rb#L83-L85
7,511
bwillis/rockit
lib/rockit/application.rb
Rockit.Application.if_string_changed
def if_string_changed(key, new_value, &block) if new_value != @hash_store[key] old_value = @hash_store[key] @hash_store[key] = new_value block.call(key, new_value, old_value) if block_given? end end
ruby
def if_string_changed(key, new_value, &block) if new_value != @hash_store[key] old_value = @hash_store[key] @hash_store[key] = new_value block.call(key, new_value, old_value) if block_given? end end
[ "def", "if_string_changed", "(", "key", ",", "new_value", ",", "&", "block", ")", "if", "new_value", "!=", "@hash_store", "[", "key", "]", "old_value", "=", "@hash_store", "[", "key", "]", "@hash_store", "[", "key", "]", "=", "new_value", "block", ".", "call", "(", "key", ",", "new_value", ",", "old_value", ")", "if", "block_given?", "end", "end" ]
Execute the given block if the input is different from the output . key - the key to lookup the stored hash value new_value - the value to compare with the stored hash value block - block to execute if the hash value does not match the stored hash value return if the block was not executed, false, if it is executed, the return status of the block
[ "Execute", "the", "given", "block", "if", "the", "input", "is", "different", "from", "the", "output", "." ]
b0604538e2436d6c26a4e29c605235638e819fee
https://github.com/bwillis/rockit/blob/b0604538e2436d6c26a4e29c605235638e819fee/lib/rockit/application.rb#L96-L102
7,512
bwillis/rockit
lib/rockit/application.rb
Rockit.Application.system_exit_on_error
def system_exit_on_error(command, options={}) options = {'print_command' => true}.merge(string_keys(options)) output command if options['print_command'] || @debug command_output = system_command(command) output command_output if @debug unless last_process.success? result = options['on_failure'].call(command, options) if options['on_failure'].is_a?(Proc) return true if result output options['failure_message'] || command_output return exit(last_process.exitstatus) end options['on_success'].call(command, options) if options['on_success'].is_a?(Proc) true end
ruby
def system_exit_on_error(command, options={}) options = {'print_command' => true}.merge(string_keys(options)) output command if options['print_command'] || @debug command_output = system_command(command) output command_output if @debug unless last_process.success? result = options['on_failure'].call(command, options) if options['on_failure'].is_a?(Proc) return true if result output options['failure_message'] || command_output return exit(last_process.exitstatus) end options['on_success'].call(command, options) if options['on_success'].is_a?(Proc) true end
[ "def", "system_exit_on_error", "(", "command", ",", "options", "=", "{", "}", ")", "options", "=", "{", "'print_command'", "=>", "true", "}", ".", "merge", "(", "string_keys", "(", "options", ")", ")", "output", "command", "if", "options", "[", "'print_command'", "]", "||", "@debug", "command_output", "=", "system_command", "(", "command", ")", "output", "command_output", "if", "@debug", "unless", "last_process", ".", "success?", "result", "=", "options", "[", "'on_failure'", "]", ".", "call", "(", "command", ",", "options", ")", "if", "options", "[", "'on_failure'", "]", ".", "is_a?", "(", "Proc", ")", "return", "true", "if", "result", "output", "options", "[", "'failure_message'", "]", "||", "command_output", "return", "exit", "(", "last_process", ".", "exitstatus", ")", "end", "options", "[", "'on_success'", "]", ".", "call", "(", "command", ",", "options", ")", "if", "options", "[", "'on_success'", "]", ".", "is_a?", "(", "Proc", ")", "true", "end" ]
Run system commands and if not successful exit and print out an error message. Default behavior is to print output of a command when it does not return success. command - the system command you want to execute options - 'error_message' - a message to print when command is not successful 'print_command' - displays the command being run 'failure_callback' - Proc to execute when the command fails. If a callback returns true then it will avoid 'on_success' - Proc to execute when the command is successful returns only true, will perform exit() when not successful
[ "Run", "system", "commands", "and", "if", "not", "successful", "exit", "and", "print", "out", "an", "error", "message", ".", "Default", "behavior", "is", "to", "print", "output", "of", "a", "command", "when", "it", "does", "not", "return", "success", "." ]
b0604538e2436d6c26a4e29c605235638e819fee
https://github.com/bwillis/rockit/blob/b0604538e2436d6c26a4e29c605235638e819fee/lib/rockit/application.rb#L117-L130
7,513
epuber-io/bade
lib/bade/renderer.rb
Bade.Renderer._find_file!
def _find_file!(name, reference_path) sub_path = File.expand_path(name, File.dirname(reference_path)) if File.exist?(sub_path) return if sub_path.end_with?('.rb') # handled in Generator sub_path else bade_path = "#{sub_path}.bade" rb_path = "#{sub_path}.rb" bade_exist = File.exist?(bade_path) rb_exist = File.exist?(rb_path) relative = Pathname.new(reference_path).relative_path_from(Pathname.new(File.dirname(file_path))).to_s if bade_exist && rb_exist message = "Found both .bade and .rb files for `#{name}` in file #{relative}, "\ 'change the import path so it references uniq file.' raise LoadError.new(name, reference_path, message) elsif bade_exist return bade_path elsif rb_exist return # handled in Generator else message = "Can't find file matching name `#{name}` referenced from file #{relative}" raise LoadError.new(name, reference_path, message) end end end
ruby
def _find_file!(name, reference_path) sub_path = File.expand_path(name, File.dirname(reference_path)) if File.exist?(sub_path) return if sub_path.end_with?('.rb') # handled in Generator sub_path else bade_path = "#{sub_path}.bade" rb_path = "#{sub_path}.rb" bade_exist = File.exist?(bade_path) rb_exist = File.exist?(rb_path) relative = Pathname.new(reference_path).relative_path_from(Pathname.new(File.dirname(file_path))).to_s if bade_exist && rb_exist message = "Found both .bade and .rb files for `#{name}` in file #{relative}, "\ 'change the import path so it references uniq file.' raise LoadError.new(name, reference_path, message) elsif bade_exist return bade_path elsif rb_exist return # handled in Generator else message = "Can't find file matching name `#{name}` referenced from file #{relative}" raise LoadError.new(name, reference_path, message) end end end
[ "def", "_find_file!", "(", "name", ",", "reference_path", ")", "sub_path", "=", "File", ".", "expand_path", "(", "name", ",", "File", ".", "dirname", "(", "reference_path", ")", ")", "if", "File", ".", "exist?", "(", "sub_path", ")", "return", "if", "sub_path", ".", "end_with?", "(", "'.rb'", ")", "# handled in Generator", "sub_path", "else", "bade_path", "=", "\"#{sub_path}.bade\"", "rb_path", "=", "\"#{sub_path}.rb\"", "bade_exist", "=", "File", ".", "exist?", "(", "bade_path", ")", "rb_exist", "=", "File", ".", "exist?", "(", "rb_path", ")", "relative", "=", "Pathname", ".", "new", "(", "reference_path", ")", ".", "relative_path_from", "(", "Pathname", ".", "new", "(", "File", ".", "dirname", "(", "file_path", ")", ")", ")", ".", "to_s", "if", "bade_exist", "&&", "rb_exist", "message", "=", "\"Found both .bade and .rb files for `#{name}` in file #{relative}, \"", "'change the import path so it references uniq file.'", "raise", "LoadError", ".", "new", "(", "name", ",", "reference_path", ",", "message", ")", "elsif", "bade_exist", "return", "bade_path", "elsif", "rb_exist", "return", "# handled in Generator", "else", "message", "=", "\"Can't find file matching name `#{name}` referenced from file #{relative}\"", "raise", "LoadError", ".", "new", "(", "name", ",", "reference_path", ",", "message", ")", "end", "end", "end" ]
Tries to find file with name, if no file could be found or there are multiple files matching the name error is raised @param [String] name name of the file that should be found @param [String] reference_path path to file from which is loading/finding @return [String, nil] returns nil when this file should be skipped otherwise absolute path to file
[ "Tries", "to", "find", "file", "with", "name", "if", "no", "file", "could", "be", "found", "or", "there", "are", "multiple", "files", "matching", "the", "name", "error", "is", "raised" ]
fe128e0178d28b5a789d94b861ac6c6d2e4a3a8e
https://github.com/epuber-io/bade/blob/fe128e0178d28b5a789d94b861ac6c6d2e4a3a8e/lib/bade/renderer.rb#L247-L274
7,514
Raybeam/myreplicator
lib/exporter/export_metadata.rb
Myreplicator.ExportMetadata.equals
def equals object if table == object.table && database == object.database return true end return false end
ruby
def equals object if table == object.table && database == object.database return true end return false end
[ "def", "equals", "object", "if", "table", "==", "object", ".", "table", "&&", "database", "==", "object", ".", "database", "return", "true", "end", "return", "false", "end" ]
Compares the object with another metadata object Return true if they are for the same table
[ "Compares", "the", "object", "with", "another", "metadata", "object", "Return", "true", "if", "they", "are", "for", "the", "same", "table" ]
470938e70f46886b525c65a4a464b4cf8383d00d
https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/lib/exporter/export_metadata.rb#L60-L65
7,515
Raybeam/myreplicator
lib/exporter/export_metadata.rb
Myreplicator.ExportMetadata.store!
def store! Kernel.p "$$$$$$$$$$$$$$$$$$ @ssh CHECK $$$$$$$$$$$$$$$$$$" cmd = "echo \"#{self.to_json.gsub("\"","\\\\\"")}\" > #{@filepath}.json" puts cmd result = @ssh.exec!(cmd) puts result end
ruby
def store! Kernel.p "$$$$$$$$$$$$$$$$$$ @ssh CHECK $$$$$$$$$$$$$$$$$$" cmd = "echo \"#{self.to_json.gsub("\"","\\\\\"")}\" > #{@filepath}.json" puts cmd result = @ssh.exec!(cmd) puts result end
[ "def", "store!", "Kernel", ".", "p", "\"$$$$$$$$$$$$$$$$$$ @ssh CHECK $$$$$$$$$$$$$$$$$$\"", "cmd", "=", "\"echo \\\"#{self.to_json.gsub(\"\\\"\",\"\\\\\\\\\\\"\")}\\\" > #{@filepath}.json\"", "puts", "cmd", "result", "=", "@ssh", ".", "exec!", "(", "cmd", ")", "puts", "result", "end" ]
Writes Json to file using echo file is written to remote server via SSH Echo is used for writing the file
[ "Writes", "Json", "to", "file", "using", "echo", "file", "is", "written", "to", "remote", "server", "via", "SSH", "Echo", "is", "used", "for", "writing", "the", "file" ]
470938e70f46886b525c65a4a464b4cf8383d00d
https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/lib/exporter/export_metadata.rb#L192-L198
7,516
nulogy/spreadsheet
lib/spreadsheet/row.rb
Spreadsheet.Row.formatted
def formatted copy = dup @formats.rcompact! if copy.length < @formats.size copy.concat Array.new(@formats.size - copy.length) end copy end
ruby
def formatted copy = dup @formats.rcompact! if copy.length < @formats.size copy.concat Array.new(@formats.size - copy.length) end copy end
[ "def", "formatted", "copy", "=", "dup", "@formats", ".", "rcompact!", "if", "copy", ".", "length", "<", "@formats", ".", "size", "copy", ".", "concat", "Array", ".", "new", "(", "@formats", ".", "size", "-", "copy", ".", "length", ")", "end", "copy", "end" ]
Returns a copy of self with nil-values appended for empty cells that have an associated Format. This is primarily a helper-function for the writer classes.
[ "Returns", "a", "copy", "of", "self", "with", "nil", "-", "values", "appended", "for", "empty", "cells", "that", "have", "an", "associated", "Format", ".", "This", "is", "primarily", "a", "helper", "-", "function", "for", "the", "writer", "classes", "." ]
c89825047f02ab26deddaab779f3b4ca349b6a0c
https://github.com/nulogy/spreadsheet/blob/c89825047f02ab26deddaab779f3b4ca349b6a0c/lib/spreadsheet/row.rb#L91-L98
7,517
kenpratt/dbox
lib/dbox/utils.rb
Dbox.Utils.relative_to_local_path
def relative_to_local_path(path) if path && path.length > 0 case_insensitive_join(local_path, path) else case_insensitive_resolve(local_path) end end
ruby
def relative_to_local_path(path) if path && path.length > 0 case_insensitive_join(local_path, path) else case_insensitive_resolve(local_path) end end
[ "def", "relative_to_local_path", "(", "path", ")", "if", "path", "&&", "path", ".", "length", ">", "0", "case_insensitive_join", "(", "local_path", ",", "path", ")", "else", "case_insensitive_resolve", "(", "local_path", ")", "end", "end" ]
assumes local_path is defined
[ "assumes", "local_path", "is", "defined" ]
f75dbc9dfd8d6ddba24a812ac676cf07325f1899
https://github.com/kenpratt/dbox/blob/f75dbc9dfd8d6ddba24a812ac676cf07325f1899/lib/dbox/utils.rb#L45-L51
7,518
kenpratt/dbox
lib/dbox/utils.rb
Dbox.Utils.relative_to_remote_path
def relative_to_remote_path(path) if path && path.length > 0 File.join(remote_path, path) else remote_path end end
ruby
def relative_to_remote_path(path) if path && path.length > 0 File.join(remote_path, path) else remote_path end end
[ "def", "relative_to_remote_path", "(", "path", ")", "if", "path", "&&", "path", ".", "length", ">", "0", "File", ".", "join", "(", "remote_path", ",", "path", ")", "else", "remote_path", "end", "end" ]
assumes remote_path is defined
[ "assumes", "remote_path", "is", "defined" ]
f75dbc9dfd8d6ddba24a812ac676cf07325f1899
https://github.com/kenpratt/dbox/blob/f75dbc9dfd8d6ddba24a812ac676cf07325f1899/lib/dbox/utils.rb#L54-L60
7,519
botanicus/nake
lib/nake/abstract_task.rb
Nake.AbstractTask.config
def config @config ||= begin Hash.new do |hash, key| raise ConfigurationError, "Configuration key #{key} in task #{name} doesn't exist" end.tap do |hash| hash.define_singleton_method(:declare) do |*keys| keys.each { |key| self[key] = nil unless self.has_key?(key) } end end end end
ruby
def config @config ||= begin Hash.new do |hash, key| raise ConfigurationError, "Configuration key #{key} in task #{name} doesn't exist" end.tap do |hash| hash.define_singleton_method(:declare) do |*keys| keys.each { |key| self[key] = nil unless self.has_key?(key) } end end end end
[ "def", "config", "@config", "||=", "begin", "Hash", ".", "new", "do", "|", "hash", ",", "key", "|", "raise", "ConfigurationError", ",", "\"Configuration key #{key} in task #{name} doesn't exist\"", "end", ".", "tap", "do", "|", "hash", "|", "hash", ".", "define_singleton_method", "(", ":declare", ")", "do", "|", "*", "keys", "|", "keys", ".", "each", "{", "|", "key", "|", "self", "[", "key", "]", "=", "nil", "unless", "self", ".", "has_key?", "(", "key", ")", "}", "end", "end", "end", "end" ]
don't use this if you don't have to!
[ "don", "t", "use", "this", "if", "you", "don", "t", "have", "to!" ]
d0ca22c3ce686dc916bdbe5bbd5475a18371a41d
https://github.com/botanicus/nake/blob/d0ca22c3ce686dc916bdbe5bbd5475a18371a41d/lib/nake/abstract_task.rb#L61-L71
7,520
apostle/apostle-ruby
lib/apostle/mail.rb
Apostle.Mail.deliver!
def deliver! return true unless Apostle.deliver unless template_id && template_id != '' raise DeliveryError, 'No email template_id provided' end queue = Apostle::Queue.new queue.add self queue.deliver! # Return true or false depending on successful delivery if queue.results[:valid].include?(self) return true else raise _exception end end
ruby
def deliver! return true unless Apostle.deliver unless template_id && template_id != '' raise DeliveryError, 'No email template_id provided' end queue = Apostle::Queue.new queue.add self queue.deliver! # Return true or false depending on successful delivery if queue.results[:valid].include?(self) return true else raise _exception end end
[ "def", "deliver!", "return", "true", "unless", "Apostle", ".", "deliver", "unless", "template_id", "&&", "template_id", "!=", "''", "raise", "DeliveryError", ",", "'No email template_id provided'", "end", "queue", "=", "Apostle", "::", "Queue", ".", "new", "queue", ".", "add", "self", "queue", ".", "deliver!", "# Return true or false depending on successful delivery", "if", "queue", ".", "results", "[", ":valid", "]", ".", "include?", "(", "self", ")", "return", "true", "else", "raise", "_exception", "end", "end" ]
Shortcut method to deliver a single message
[ "Shortcut", "method", "to", "deliver", "a", "single", "message" ]
1d3a99d62da4f4c6cdbc8f061ab7640b8f85d1e2
https://github.com/apostle/apostle-ruby/blob/1d3a99d62da4f4c6cdbc8f061ab7640b8f85d1e2/lib/apostle/mail.rb#L59-L77
7,521
patchapps/rabbit-hutch
lib/worker.rb
RabbitHutch.Worker.start
def start @exchange = @channel.topic(@exchange_name, :durable => true, :auto_delete => false, :internal => true) @queue = @channel.queue(@queue_name, :durable => true, :auto_delete => false) @queue.bind(@exchange, :routing_key => 'publish.#') @queue.subscribe(&@consumer.method(:handle_message)) end
ruby
def start @exchange = @channel.topic(@exchange_name, :durable => true, :auto_delete => false, :internal => true) @queue = @channel.queue(@queue_name, :durable => true, :auto_delete => false) @queue.bind(@exchange, :routing_key => 'publish.#') @queue.subscribe(&@consumer.method(:handle_message)) end
[ "def", "start", "@exchange", "=", "@channel", ".", "topic", "(", "@exchange_name", ",", ":durable", "=>", "true", ",", ":auto_delete", "=>", "false", ",", ":internal", "=>", "true", ")", "@queue", "=", "@channel", ".", "queue", "(", "@queue_name", ",", ":durable", "=>", "true", ",", ":auto_delete", "=>", "false", ")", "@queue", ".", "bind", "(", "@exchange", ",", ":routing_key", "=>", "'publish.#'", ")", "@queue", ".", "subscribe", "(", "@consumer", ".", "method", "(", ":handle_message", ")", ")", "end" ]
begin listening for all topics in publish.
[ "begin", "listening", "for", "all", "topics", "in", "publish", "." ]
42337b0ddda60b749fc2fe088f4e8dba674d198d
https://github.com/patchapps/rabbit-hutch/blob/42337b0ddda60b749fc2fe088f4e8dba674d198d/lib/worker.rb#L20-L25
7,522
codegram/simple_currency
lib/simple_currency/currency_convertible.rb
CurrencyConvertible.Proxy.cached_rate
def cached_rate(original, target) if defined?(Rails) unless rate = Rails.cache.read("#{original}_#{target}_#{stringified_exchange_date}") rate = (1.0 / Rails.cache.read("#{target}_#{original}_#{stringified_exchange_date}")) rescue nil end rate end end
ruby
def cached_rate(original, target) if defined?(Rails) unless rate = Rails.cache.read("#{original}_#{target}_#{stringified_exchange_date}") rate = (1.0 / Rails.cache.read("#{target}_#{original}_#{stringified_exchange_date}")) rescue nil end rate end end
[ "def", "cached_rate", "(", "original", ",", "target", ")", "if", "defined?", "(", "Rails", ")", "unless", "rate", "=", "Rails", ".", "cache", ".", "read", "(", "\"#{original}_#{target}_#{stringified_exchange_date}\"", ")", "rate", "=", "(", "1.0", "/", "Rails", ".", "cache", ".", "read", "(", "\"#{target}_#{original}_#{stringified_exchange_date}\"", ")", ")", "rescue", "nil", "end", "rate", "end", "end" ]
Tries to either get rate or calculate the inverse rate from cache. First looks for an "usd_eur_25-8-2010" entry in the cache, and if it does not find it, it looks for "eur_usd_25-8-2010" and inverts it.
[ "Tries", "to", "either", "get", "rate", "or", "calculate", "the", "inverse", "rate", "from", "cache", "." ]
4bc4406735dc095ed9ba97ee3a4dcb9b72d047ec
https://github.com/codegram/simple_currency/blob/4bc4406735dc095ed9ba97ee3a4dcb9b72d047ec/lib/simple_currency/currency_convertible.rb#L189-L196
7,523
reggieb/ominous
app/models/ominous/warning.rb
Ominous.Warning.pass_method_to_warning_closer
def pass_method_to_warning_closer(symbol, closer) raise "A closer is needed to identify the warning_closer" unless closer.kind_of? Closer warning_closer = warning_closers.where(:closer_id => closer.id).first warning_closer.send(symbol) if warning_closer end
ruby
def pass_method_to_warning_closer(symbol, closer) raise "A closer is needed to identify the warning_closer" unless closer.kind_of? Closer warning_closer = warning_closers.where(:closer_id => closer.id).first warning_closer.send(symbol) if warning_closer end
[ "def", "pass_method_to_warning_closer", "(", "symbol", ",", "closer", ")", "raise", "\"A closer is needed to identify the warning_closer\"", "unless", "closer", ".", "kind_of?", "Closer", "warning_closer", "=", "warning_closers", ".", "where", "(", ":closer_id", "=>", "closer", ".", "id", ")", ".", "first", "warning_closer", ".", "send", "(", "symbol", ")", "if", "warning_closer", "end" ]
Allows acts_as_list methods to be used within the warning. If closers were the act_as_list object, you could do things like this warning.closers.last.move_higher However, as closers are used on multiple warnings and they need to be independently sortable within each warning, it is the through table model WarningCloser that acts_as_list. To change position the change must be made in the context of the warning. pass_method_to_warning_closer in combination with method_missing, allows you to pass to a warning the acts_as_list method together with the closer it needs to effect. The equivalent move_higher call then becomes: warning.move_higher(warning.closers.last) You can also do: warning.move_to_top(closer) warning.last?(closer)
[ "Allows", "acts_as_list", "methods", "to", "be", "used", "within", "the", "warning", ".", "If", "closers", "were", "the", "act_as_list", "object", "you", "could", "do", "things", "like", "this" ]
725ec70e9cc718f07a72bb8dd68ed2da4c8a6a13
https://github.com/reggieb/ominous/blob/725ec70e9cc718f07a72bb8dd68ed2da4c8a6a13/app/models/ominous/warning.rb#L75-L79
7,524
26fe/tree.rb
lib/tree_rb/core/tree_node.rb
TreeRb.TreeNode.find
def find(content = nil, &block) if content and block_given? raise "TreeNode::find - passed content AND block" end if content if content.class == Regexp block = proc { |l| l.content =~ content } else block = proc { |l| l.content == content } end end return self if block.call(self) leaf = @leaves.find { |l| block.call(l) } return leaf if leaf @children.each do |child| node = child.find &block return node if node end nil end
ruby
def find(content = nil, &block) if content and block_given? raise "TreeNode::find - passed content AND block" end if content if content.class == Regexp block = proc { |l| l.content =~ content } else block = proc { |l| l.content == content } end end return self if block.call(self) leaf = @leaves.find { |l| block.call(l) } return leaf if leaf @children.each do |child| node = child.find &block return node if node end nil end
[ "def", "find", "(", "content", "=", "nil", ",", "&", "block", ")", "if", "content", "and", "block_given?", "raise", "\"TreeNode::find - passed content AND block\"", "end", "if", "content", "if", "content", ".", "class", "==", "Regexp", "block", "=", "proc", "{", "|", "l", "|", "l", ".", "content", "=~", "content", "}", "else", "block", "=", "proc", "{", "|", "l", "|", "l", ".", "content", "==", "content", "}", "end", "end", "return", "self", "if", "block", ".", "call", "(", "self", ")", "leaf", "=", "@leaves", ".", "find", "{", "|", "l", "|", "block", ".", "call", "(", "l", ")", "}", "return", "leaf", "if", "leaf", "@children", ".", "each", "do", "|", "child", "|", "node", "=", "child", ".", "find", "block", "return", "node", "if", "node", "end", "nil", "end" ]
Find a node down the hierarchy with content @param [Object,Regexp] content of searched node @return [Object, nil] nil if not found
[ "Find", "a", "node", "down", "the", "hierarchy", "with", "content" ]
5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b
https://github.com/26fe/tree.rb/blob/5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b/lib/tree_rb/core/tree_node.rb#L229-L251
7,525
kamui/rack-accept_headers
lib/rack/accept_headers/charset.rb
Rack::AcceptHeaders.Charset.matches
def matches(charset) values.select {|v| v == charset || v == '*' }.sort {|a, b| # "*" gets least precedence, any others should be equal. a == '*' ? 1 : (b == '*' ? -1 : 0) } end
ruby
def matches(charset) values.select {|v| v == charset || v == '*' }.sort {|a, b| # "*" gets least precedence, any others should be equal. a == '*' ? 1 : (b == '*' ? -1 : 0) } end
[ "def", "matches", "(", "charset", ")", "values", ".", "select", "{", "|", "v", "|", "v", "==", "charset", "||", "v", "==", "'*'", "}", ".", "sort", "{", "|", "a", ",", "b", "|", "# \"*\" gets least precedence, any others should be equal.", "a", "==", "'*'", "?", "1", ":", "(", "b", "==", "'*'", "?", "-", "1", ":", "0", ")", "}", "end" ]
Returns an array of character sets from this header that match the given +charset+, ordered by precedence.
[ "Returns", "an", "array", "of", "character", "sets", "from", "this", "header", "that", "match", "the", "given", "+", "charset", "+", "ordered", "by", "precedence", "." ]
099bfbb919de86b5842c8e14be42b8b784e53f03
https://github.com/kamui/rack-accept_headers/blob/099bfbb919de86b5842c8e14be42b8b784e53f03/lib/rack/accept_headers/charset.rb#L27-L34
7,526
timwaters/nypl_repo
lib/nypl_repo.rb
NyplRepo.Client.get_capture_items
def get_capture_items(c_uuid) url = "#{@server_url}/items/#{c_uuid}.json?per_page=500" json = self.get_json(url) captures = [] capture = json["nyplAPI"]["response"]["capture"] captures << capture totalPages = json["nyplAPI"]["request"]["totalPages"].to_i if totalPages >= 2 puts "total pages " + totalPages.to_s if @debug (2..totalPages).each do | page | puts "page: "+page.to_s if @debug newurl = url + "&page=#{page}" json = self.get_json(newurl) newcapture = json["nyplAPI"]["response"]["capture"] captures << newcapture end end captures.flatten! captures end
ruby
def get_capture_items(c_uuid) url = "#{@server_url}/items/#{c_uuid}.json?per_page=500" json = self.get_json(url) captures = [] capture = json["nyplAPI"]["response"]["capture"] captures << capture totalPages = json["nyplAPI"]["request"]["totalPages"].to_i if totalPages >= 2 puts "total pages " + totalPages.to_s if @debug (2..totalPages).each do | page | puts "page: "+page.to_s if @debug newurl = url + "&page=#{page}" json = self.get_json(newurl) newcapture = json["nyplAPI"]["response"]["capture"] captures << newcapture end end captures.flatten! captures end
[ "def", "get_capture_items", "(", "c_uuid", ")", "url", "=", "\"#{@server_url}/items/#{c_uuid}.json?per_page=500\"", "json", "=", "self", ".", "get_json", "(", "url", ")", "captures", "=", "[", "]", "capture", "=", "json", "[", "\"nyplAPI\"", "]", "[", "\"response\"", "]", "[", "\"capture\"", "]", "captures", "<<", "capture", "totalPages", "=", "json", "[", "\"nyplAPI\"", "]", "[", "\"request\"", "]", "[", "\"totalPages\"", "]", ".", "to_i", "if", "totalPages", ">=", "2", "puts", "\"total pages \"", "+", "totalPages", ".", "to_s", "if", "@debug", "(", "2", "..", "totalPages", ")", ".", "each", "do", "|", "page", "|", "puts", "\"page: \"", "+", "page", ".", "to_s", "if", "@debug", "newurl", "=", "url", "+", "\"&page=#{page}\"", "json", "=", "self", ".", "get_json", "(", "newurl", ")", "newcapture", "=", "json", "[", "\"nyplAPI\"", "]", "[", "\"response\"", "]", "[", "\"capture\"", "]", "captures", "<<", "newcapture", "end", "end", "captures", ".", "flatten!", "captures", "end" ]
Given a container uuid, or biblographic uuid, returns a list of mods uuids.
[ "Given", "a", "container", "uuid", "or", "biblographic", "uuid", "returns", "a", "list", "of", "mods", "uuids", "." ]
213180a6dbeb1608aed0e615f239ee7e7551539c
https://github.com/timwaters/nypl_repo/blob/213180a6dbeb1608aed0e615f239ee7e7551539c/lib/nypl_repo.rb#L44-L65
7,527
timwaters/nypl_repo
lib/nypl_repo.rb
NyplRepo.Client.get_mods_item
def get_mods_item(mods_uuid) url = "#{@server_url}/items/mods/#{mods_uuid}.json" json = self.get_json(url) item = nil if json["nyplAPI"]["response"]["mods"] item = json["nyplAPI"]["response"]["mods"] end return item end
ruby
def get_mods_item(mods_uuid) url = "#{@server_url}/items/mods/#{mods_uuid}.json" json = self.get_json(url) item = nil if json["nyplAPI"]["response"]["mods"] item = json["nyplAPI"]["response"]["mods"] end return item end
[ "def", "get_mods_item", "(", "mods_uuid", ")", "url", "=", "\"#{@server_url}/items/mods/#{mods_uuid}.json\"", "json", "=", "self", ".", "get_json", "(", "url", ")", "item", "=", "nil", "if", "json", "[", "\"nyplAPI\"", "]", "[", "\"response\"", "]", "[", "\"mods\"", "]", "item", "=", "json", "[", "\"nyplAPI\"", "]", "[", "\"response\"", "]", "[", "\"mods\"", "]", "end", "return", "item", "end" ]
get the item detail from a uuid
[ "get", "the", "item", "detail", "from", "a", "uuid" ]
213180a6dbeb1608aed0e615f239ee7e7551539c
https://github.com/timwaters/nypl_repo/blob/213180a6dbeb1608aed0e615f239ee7e7551539c/lib/nypl_repo.rb#L68-L78
7,528
timwaters/nypl_repo
lib/nypl_repo.rb
NyplRepo.Client.get_bibl_uuid
def get_bibl_uuid(image_id) url = "#{@server_url}/items/local_image_id/#{image_id}.json" json = self.get_json(url) bibl_uuid = nil if json["nyplAPI"]["response"]["numResults"].to_i > 0 bibl_uuid = json["nyplAPI"]["response"]["uuid"] end return bibl_uuid end
ruby
def get_bibl_uuid(image_id) url = "#{@server_url}/items/local_image_id/#{image_id}.json" json = self.get_json(url) bibl_uuid = nil if json["nyplAPI"]["response"]["numResults"].to_i > 0 bibl_uuid = json["nyplAPI"]["response"]["uuid"] end return bibl_uuid end
[ "def", "get_bibl_uuid", "(", "image_id", ")", "url", "=", "\"#{@server_url}/items/local_image_id/#{image_id}.json\"", "json", "=", "self", ".", "get_json", "(", "url", ")", "bibl_uuid", "=", "nil", "if", "json", "[", "\"nyplAPI\"", "]", "[", "\"response\"", "]", "[", "\"numResults\"", "]", ".", "to_i", ">", "0", "bibl_uuid", "=", "json", "[", "\"nyplAPI\"", "]", "[", "\"response\"", "]", "[", "\"uuid\"", "]", "end", "return", "bibl_uuid", "end" ]
get bibliographic container uuid from an image_id
[ "get", "bibliographic", "container", "uuid", "from", "an", "image_id" ]
213180a6dbeb1608aed0e615f239ee7e7551539c
https://github.com/timwaters/nypl_repo/blob/213180a6dbeb1608aed0e615f239ee7e7551539c/lib/nypl_repo.rb#L117-L126
7,529
timwaters/nypl_repo
lib/nypl_repo.rb
NyplRepo.Client.get_highreslink
def get_highreslink(bibl_uuid, image_id) url = "#{@server_url}/items/#{bibl_uuid}.json?per_page=500" json = self.get_json(url) highreslink = nil json["nyplAPI"]["response"]["capture"].each do | capture| if capture["imageID"] == image_id highreslink = capture["highResLink"] break end #if end if json["nyplAPI"]["response"]["numResults"].to_i > 0 return highreslink end
ruby
def get_highreslink(bibl_uuid, image_id) url = "#{@server_url}/items/#{bibl_uuid}.json?per_page=500" json = self.get_json(url) highreslink = nil json["nyplAPI"]["response"]["capture"].each do | capture| if capture["imageID"] == image_id highreslink = capture["highResLink"] break end #if end if json["nyplAPI"]["response"]["numResults"].to_i > 0 return highreslink end
[ "def", "get_highreslink", "(", "bibl_uuid", ",", "image_id", ")", "url", "=", "\"#{@server_url}/items/#{bibl_uuid}.json?per_page=500\"", "json", "=", "self", ".", "get_json", "(", "url", ")", "highreslink", "=", "nil", "json", "[", "\"nyplAPI\"", "]", "[", "\"response\"", "]", "[", "\"capture\"", "]", ".", "each", "do", "|", "capture", "|", "if", "capture", "[", "\"imageID\"", "]", "==", "image_id", "highreslink", "=", "capture", "[", "\"highResLink\"", "]", "break", "end", "#if", "end", "if", "json", "[", "\"nyplAPI\"", "]", "[", "\"response\"", "]", "[", "\"numResults\"", "]", ".", "to_i", ">", "0", "return", "highreslink", "end" ]
get highreslink from an item, matching up the image idi since some bibliographic items may have many maps under them
[ "get", "highreslink", "from", "an", "item", "matching", "up", "the", "image", "idi", "since", "some", "bibliographic", "items", "may", "have", "many", "maps", "under", "them" ]
213180a6dbeb1608aed0e615f239ee7e7551539c
https://github.com/timwaters/nypl_repo/blob/213180a6dbeb1608aed0e615f239ee7e7551539c/lib/nypl_repo.rb#L131-L145
7,530
cordawyn/kalimba
lib/kalimba/attribute_assignment.rb
Kalimba.AttributeAssignment.assign_attributes
def assign_attributes(new_attributes = {}, options = {}) return if new_attributes.blank? attributes = new_attributes.stringify_keys multi_parameter_attributes = [] nested_parameter_attributes = [] attributes.each do |k, v| if k.include?("(") multi_parameter_attributes << [ k, v ] elsif respond_to?("#{k}=") if v.is_a?(Hash) nested_parameter_attributes << [ k, v ] else send("#{k}=", v) end else raise UnknownAttributeError, "unknown attribute: #{k}" end end # assign any deferred nested attributes after the base attributes have been set nested_parameter_attributes.each do |k,v| send("#{k}=", v) end assign_multiparameter_attributes(multi_parameter_attributes) end
ruby
def assign_attributes(new_attributes = {}, options = {}) return if new_attributes.blank? attributes = new_attributes.stringify_keys multi_parameter_attributes = [] nested_parameter_attributes = [] attributes.each do |k, v| if k.include?("(") multi_parameter_attributes << [ k, v ] elsif respond_to?("#{k}=") if v.is_a?(Hash) nested_parameter_attributes << [ k, v ] else send("#{k}=", v) end else raise UnknownAttributeError, "unknown attribute: #{k}" end end # assign any deferred nested attributes after the base attributes have been set nested_parameter_attributes.each do |k,v| send("#{k}=", v) end assign_multiparameter_attributes(multi_parameter_attributes) end
[ "def", "assign_attributes", "(", "new_attributes", "=", "{", "}", ",", "options", "=", "{", "}", ")", "return", "if", "new_attributes", ".", "blank?", "attributes", "=", "new_attributes", ".", "stringify_keys", "multi_parameter_attributes", "=", "[", "]", "nested_parameter_attributes", "=", "[", "]", "attributes", ".", "each", "do", "|", "k", ",", "v", "|", "if", "k", ".", "include?", "(", "\"(\"", ")", "multi_parameter_attributes", "<<", "[", "k", ",", "v", "]", "elsif", "respond_to?", "(", "\"#{k}=\"", ")", "if", "v", ".", "is_a?", "(", "Hash", ")", "nested_parameter_attributes", "<<", "[", "k", ",", "v", "]", "else", "send", "(", "\"#{k}=\"", ",", "v", ")", "end", "else", "raise", "UnknownAttributeError", ",", "\"unknown attribute: #{k}\"", "end", "end", "# assign any deferred nested attributes after the base attributes have been set", "nested_parameter_attributes", ".", "each", "do", "|", "k", ",", "v", "|", "send", "(", "\"#{k}=\"", ",", "v", ")", "end", "assign_multiparameter_attributes", "(", "multi_parameter_attributes", ")", "end" ]
Assign attributes from the given hash @param [Hash<[Symbol, String] => Any>] new_attributes @param [Hash] options @return [void]
[ "Assign", "attributes", "from", "the", "given", "hash" ]
c1b29948744a66cadb643213785a9cdd4c07be83
https://github.com/cordawyn/kalimba/blob/c1b29948744a66cadb643213785a9cdd4c07be83/lib/kalimba/attribute_assignment.rb#L8-L35
7,531
forecastxl/twinfield-ruby
lib/twinfield/customer.rb
Twinfield.Customer.find_by_code
def find_by_code(code) Twinfield::Process.new(@session). request(:process_xml_document, get_dimension_xml(@company, 'DEB', { code: code })). body[:process_xml_document_response][:process_xml_document_result][:dimension] end
ruby
def find_by_code(code) Twinfield::Process.new(@session). request(:process_xml_document, get_dimension_xml(@company, 'DEB', { code: code })). body[:process_xml_document_response][:process_xml_document_result][:dimension] end
[ "def", "find_by_code", "(", "code", ")", "Twinfield", "::", "Process", ".", "new", "(", "@session", ")", ".", "request", "(", ":process_xml_document", ",", "get_dimension_xml", "(", "@company", ",", "'DEB'", ",", "{", "code", ":", "code", "}", ")", ")", ".", "body", "[", ":process_xml_document_response", "]", "[", ":process_xml_document_result", "]", "[", ":dimension", "]", "end" ]
Find customer by twinfield customer code
[ "Find", "customer", "by", "twinfield", "customer", "code" ]
90591ba1f11875c0f5b73c02a5ef5a88fef3ee45
https://github.com/forecastxl/twinfield-ruby/blob/90591ba1f11875c0f5b73c02a5ef5a88fef3ee45/lib/twinfield/customer.rb#L19-L23
7,532
forecastxl/twinfield-ruby
lib/twinfield/customer.rb
Twinfield.Customer.find_by_name
def find_by_name(name) Twinfield::Finder.new(@session). search(Twinfield::FinderSearch.new('DIM', name, 0, 1, 0, { office: @company, dimtype: 'DEB'} )). body[:search_response][:data] end
ruby
def find_by_name(name) Twinfield::Finder.new(@session). search(Twinfield::FinderSearch.new('DIM', name, 0, 1, 0, { office: @company, dimtype: 'DEB'} )). body[:search_response][:data] end
[ "def", "find_by_name", "(", "name", ")", "Twinfield", "::", "Finder", ".", "new", "(", "@session", ")", ".", "search", "(", "Twinfield", "::", "FinderSearch", ".", "new", "(", "'DIM'", ",", "name", ",", "0", ",", "1", ",", "0", ",", "{", "office", ":", "@company", ",", "dimtype", ":", "'DEB'", "}", ")", ")", ".", "body", "[", ":search_response", "]", "[", ":data", "]", "end" ]
Find customer by name
[ "Find", "customer", "by", "name" ]
90591ba1f11875c0f5b73c02a5ef5a88fef3ee45
https://github.com/forecastxl/twinfield-ruby/blob/90591ba1f11875c0f5b73c02a5ef5a88fef3ee45/lib/twinfield/customer.rb#L26-L30
7,533
forecastxl/twinfield-ruby
lib/twinfield/customer.rb
Twinfield.Customer.get_dimension_xml
def get_dimension_xml(office, dimtype, opts = {}) xml = Builder::XmlMarkup.new xml = xml.read do xml.type('dimensions') xml.office(office) xml.dimtype(dimtype) xml.code(opts.fetch(:code){}) end end
ruby
def get_dimension_xml(office, dimtype, opts = {}) xml = Builder::XmlMarkup.new xml = xml.read do xml.type('dimensions') xml.office(office) xml.dimtype(dimtype) xml.code(opts.fetch(:code){}) end end
[ "def", "get_dimension_xml", "(", "office", ",", "dimtype", ",", "opts", "=", "{", "}", ")", "xml", "=", "Builder", "::", "XmlMarkup", ".", "new", "xml", "=", "xml", ".", "read", "do", "xml", ".", "type", "(", "'dimensions'", ")", "xml", ".", "office", "(", "office", ")", "xml", ".", "dimtype", "(", "dimtype", ")", "xml", ".", "code", "(", "opts", ".", "fetch", "(", ":code", ")", "{", "}", ")", "end", "end" ]
The request for getting all elements in a Twinfield dimension
[ "The", "request", "for", "getting", "all", "elements", "in", "a", "Twinfield", "dimension" ]
90591ba1f11875c0f5b73c02a5ef5a88fef3ee45
https://github.com/forecastxl/twinfield-ruby/blob/90591ba1f11875c0f5b73c02a5ef5a88fef3ee45/lib/twinfield/customer.rb#L40-L49
7,534
mirego/emotions
lib/emotions/emotional.rb
Emotions.Emotional.express!
def express!(emotion, emotive) emotion = _emotions_about(emotive).where(emotion: emotion).first_or_initialize begin emotion.tap(&:save!) rescue ActiveRecord::RecordInvalid => e raise InvalidEmotion.new(e.record) end end
ruby
def express!(emotion, emotive) emotion = _emotions_about(emotive).where(emotion: emotion).first_or_initialize begin emotion.tap(&:save!) rescue ActiveRecord::RecordInvalid => e raise InvalidEmotion.new(e.record) end end
[ "def", "express!", "(", "emotion", ",", "emotive", ")", "emotion", "=", "_emotions_about", "(", "emotive", ")", ".", "where", "(", "emotion", ":", "emotion", ")", ".", "first_or_initialize", "begin", "emotion", ".", "tap", "(", ":save!", ")", "rescue", "ActiveRecord", "::", "RecordInvalid", "=>", "e", "raise", "InvalidEmotion", ".", "new", "(", "e", ".", "record", ")", "end", "end" ]
Express an emotion towards another record @example user = User.first picture = Picture.first user.express! :happy, picture
[ "Express", "an", "emotion", "towards", "another", "record" ]
f0adc687dbdac906d9fcebfb0f3bf6afb6fa5d56
https://github.com/mirego/emotions/blob/f0adc687dbdac906d9fcebfb0f3bf6afb6fa5d56/lib/emotions/emotional.rb#L37-L45
7,535
mirego/emotions
lib/emotions/emotional.rb
Emotions.Emotional.no_longer_express!
def no_longer_express!(emotion, emotive) _emotions_about(emotive).where(emotion: emotion).first.tap { |e| e.try(:destroy) } end
ruby
def no_longer_express!(emotion, emotive) _emotions_about(emotive).where(emotion: emotion).first.tap { |e| e.try(:destroy) } end
[ "def", "no_longer_express!", "(", "emotion", ",", "emotive", ")", "_emotions_about", "(", "emotive", ")", ".", "where", "(", "emotion", ":", "emotion", ")", ".", "first", ".", "tap", "{", "|", "e", "|", "e", ".", "try", "(", ":destroy", ")", "}", "end" ]
No longer express an emotion towards another record @example user = User.first picture = Picture.first user.no_longer_express! :happy, picture
[ "No", "longer", "express", "an", "emotion", "towards", "another", "record" ]
f0adc687dbdac906d9fcebfb0f3bf6afb6fa5d56
https://github.com/mirego/emotions/blob/f0adc687dbdac906d9fcebfb0f3bf6afb6fa5d56/lib/emotions/emotional.rb#L53-L55
7,536
26fe/tree.rb
lib/tree_rb/output_plugins/dircat/dircat_visitor.rb
TreeRb.DirCatVisitor.add_entry
def add_entry(e) @entries.push(e) if @md5_to_entries.has_key?(e.md5) @md5_to_entries[e.md5].push(e) else @md5_to_entries[e.md5] = [e] end end
ruby
def add_entry(e) @entries.push(e) if @md5_to_entries.has_key?(e.md5) @md5_to_entries[e.md5].push(e) else @md5_to_entries[e.md5] = [e] end end
[ "def", "add_entry", "(", "e", ")", "@entries", ".", "push", "(", "e", ")", "if", "@md5_to_entries", ".", "has_key?", "(", "e", ".", "md5", ")", "@md5_to_entries", "[", "e", ".", "md5", "]", ".", "push", "(", "e", ")", "else", "@md5_to_entries", "[", "e", ".", "md5", "]", "=", "[", "e", "]", "end", "end" ]
add entry to this catalog @private
[ "add", "entry", "to", "this", "catalog" ]
5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b
https://github.com/26fe/tree.rb/blob/5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b/lib/tree_rb/output_plugins/dircat/dircat_visitor.rb#L35-L42
7,537
holman/stars
lib/stars/services/favstar.rb
Stars.Favstar.parse_title
def parse_title(title) strip = title.split(':').first title = title.gsub(strip,'') title = title[2..-1] if title[0..1] == ": " title end
ruby
def parse_title(title) strip = title.split(':').first title = title.gsub(strip,'') title = title[2..-1] if title[0..1] == ": " title end
[ "def", "parse_title", "(", "title", ")", "strip", "=", "title", ".", "split", "(", "':'", ")", ".", "first", "title", "=", "title", ".", "gsub", "(", "strip", ",", "''", ")", "title", "=", "title", "[", "2", "..", "-", "1", "]", "if", "title", "[", "0", "..", "1", "]", "==", "\": \"", "title", "end" ]
Parse the title from a Favstar RSS title. title - a Favstar-formatted String (x stars: title here) This splits on the first colon, and then use everything after that. To account for tweets with colons in them, we have to strip the first ": " String we find, and then shift the String back two characters.
[ "Parse", "the", "title", "from", "a", "Favstar", "RSS", "title", "." ]
4c12a7d2fa935fe746d263aad5208ed0630c0b1e
https://github.com/holman/stars/blob/4c12a7d2fa935fe746d263aad5208ed0630c0b1e/lib/stars/services/favstar.rb#L50-L55
7,538
jemmyw/bisques
lib/bisques/client.rb
Bisques.Client.create_queue
def create_queue(name, attributes = {}) response = action("CreateQueue", {"QueueName" => Queue.sanitize_name("#{queue_prefix}#{name}")}.merge(attributes)) if response.success? Queue.new(self, response.doc.xpath("//QueueUrl").text) else raise "Could not create queue #{name}" end rescue AwsActionError => error if error.code == "AWS.SimpleQueueService.QueueDeletedRecently" raise QueueDeletedRecentlyError, error.message else raise error end end
ruby
def create_queue(name, attributes = {}) response = action("CreateQueue", {"QueueName" => Queue.sanitize_name("#{queue_prefix}#{name}")}.merge(attributes)) if response.success? Queue.new(self, response.doc.xpath("//QueueUrl").text) else raise "Could not create queue #{name}" end rescue AwsActionError => error if error.code == "AWS.SimpleQueueService.QueueDeletedRecently" raise QueueDeletedRecentlyError, error.message else raise error end end
[ "def", "create_queue", "(", "name", ",", "attributes", "=", "{", "}", ")", "response", "=", "action", "(", "\"CreateQueue\"", ",", "{", "\"QueueName\"", "=>", "Queue", ".", "sanitize_name", "(", "\"#{queue_prefix}#{name}\"", ")", "}", ".", "merge", "(", "attributes", ")", ")", "if", "response", ".", "success?", "Queue", ".", "new", "(", "self", ",", "response", ".", "doc", ".", "xpath", "(", "\"//QueueUrl\"", ")", ".", "text", ")", "else", "raise", "\"Could not create queue #{name}\"", "end", "rescue", "AwsActionError", "=>", "error", "if", "error", ".", "code", "==", "\"AWS.SimpleQueueService.QueueDeletedRecently\"", "raise", "QueueDeletedRecentlyError", ",", "error", ".", "message", "else", "raise", "error", "end", "end" ]
Creates a new SQS queue and returns a Queue object. @param [String] name @param [Hash] attributes @return [Queue] @raise [AwsActionError]
[ "Creates", "a", "new", "SQS", "queue", "and", "returns", "a", "Queue", "object", "." ]
c48ab555f07664752bcbf9e8deb99bd75cbdc41b
https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/client.rb#L52-L67
7,539
jemmyw/bisques
lib/bisques/client.rb
Bisques.Client.get_queue
def get_queue(name, options = {}) response = action("GetQueueUrl", {"QueueName" => Queue.sanitize_name("#{queue_prefix}#{name}")}.merge(options)) if response.success? Queue.new(self, response.doc.xpath("//QueueUrl").text) end rescue Bisques::AwsActionError => e raise unless e.code == "AWS.SimpleQueueService.NonExistentQueue" end
ruby
def get_queue(name, options = {}) response = action("GetQueueUrl", {"QueueName" => Queue.sanitize_name("#{queue_prefix}#{name}")}.merge(options)) if response.success? Queue.new(self, response.doc.xpath("//QueueUrl").text) end rescue Bisques::AwsActionError => e raise unless e.code == "AWS.SimpleQueueService.NonExistentQueue" end
[ "def", "get_queue", "(", "name", ",", "options", "=", "{", "}", ")", "response", "=", "action", "(", "\"GetQueueUrl\"", ",", "{", "\"QueueName\"", "=>", "Queue", ".", "sanitize_name", "(", "\"#{queue_prefix}#{name}\"", ")", "}", ".", "merge", "(", "options", ")", ")", "if", "response", ".", "success?", "Queue", ".", "new", "(", "self", ",", "response", ".", "doc", ".", "xpath", "(", "\"//QueueUrl\"", ")", ".", "text", ")", "end", "rescue", "Bisques", "::", "AwsActionError", "=>", "e", "raise", "unless", "e", ".", "code", "==", "\"AWS.SimpleQueueService.NonExistentQueue\"", "end" ]
Get an SQS queue by name. @param [String] name @param [Hash] options @return [Queue,nil] Returns a Queue object if the queue is found, otherwise nil. @raise [AwsActionError]
[ "Get", "an", "SQS", "queue", "by", "name", "." ]
c48ab555f07664752bcbf9e8deb99bd75cbdc41b
https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/client.rb#L82-L91
7,540
jemmyw/bisques
lib/bisques/client.rb
Bisques.Client.list_queues
def list_queues(prefix = "") response = action("ListQueues", "QueueNamePrefix" => "#{queue_prefix}#{prefix}") response.doc.xpath("//ListQueuesResult/QueueUrl").map(&:text).map do |url| Queue.new(self, url) end end
ruby
def list_queues(prefix = "") response = action("ListQueues", "QueueNamePrefix" => "#{queue_prefix}#{prefix}") response.doc.xpath("//ListQueuesResult/QueueUrl").map(&:text).map do |url| Queue.new(self, url) end end
[ "def", "list_queues", "(", "prefix", "=", "\"\"", ")", "response", "=", "action", "(", "\"ListQueues\"", ",", "\"QueueNamePrefix\"", "=>", "\"#{queue_prefix}#{prefix}\"", ")", "response", ".", "doc", ".", "xpath", "(", "\"//ListQueuesResult/QueueUrl\"", ")", ".", "map", "(", ":text", ")", ".", "map", "do", "|", "url", "|", "Queue", ".", "new", "(", "self", ",", "url", ")", "end", "end" ]
Return an array of Queue objects representing the queues found in SQS. An optional prefix can be supplied to restrict the queues found. This prefix is additional to the client prefix. @param [String] prefix option prefix to restrict the queues found. @return [Array<Queue>] queue objects found. @raise [AwsActionError] @example Delete all the queues client.list_queues.each do |queue| queue.delete end
[ "Return", "an", "array", "of", "Queue", "objects", "representing", "the", "queues", "found", "in", "SQS", ".", "An", "optional", "prefix", "can", "be", "supplied", "to", "restrict", "the", "queues", "found", ".", "This", "prefix", "is", "additional", "to", "the", "client", "prefix", "." ]
c48ab555f07664752bcbf9e8deb99bd75cbdc41b
https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/client.rb#L107-L112
7,541
jemmyw/bisques
lib/bisques/client.rb
Bisques.Client.send_message
def send_message(queue_url, message_body, delay_seconds=nil) options = {"MessageBody" => message_body} options["DelaySeconds"] = delay_seconds if delay_seconds tries = 0 md5 = Digest::MD5.hexdigest(message_body) begin tries += 1 response = action("SendMessage", queue_url, options) returned_md5 = response.doc.xpath("//MD5OfMessageBody").text raise MessageHasWrongMd5Error.new(message_body, md5, returned_md5) unless md5 == returned_md5 rescue MessageHasWrongMd5Error if tries < 2 retry else raise end end end
ruby
def send_message(queue_url, message_body, delay_seconds=nil) options = {"MessageBody" => message_body} options["DelaySeconds"] = delay_seconds if delay_seconds tries = 0 md5 = Digest::MD5.hexdigest(message_body) begin tries += 1 response = action("SendMessage", queue_url, options) returned_md5 = response.doc.xpath("//MD5OfMessageBody").text raise MessageHasWrongMd5Error.new(message_body, md5, returned_md5) unless md5 == returned_md5 rescue MessageHasWrongMd5Error if tries < 2 retry else raise end end end
[ "def", "send_message", "(", "queue_url", ",", "message_body", ",", "delay_seconds", "=", "nil", ")", "options", "=", "{", "\"MessageBody\"", "=>", "message_body", "}", "options", "[", "\"DelaySeconds\"", "]", "=", "delay_seconds", "if", "delay_seconds", "tries", "=", "0", "md5", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "message_body", ")", "begin", "tries", "+=", "1", "response", "=", "action", "(", "\"SendMessage\"", ",", "queue_url", ",", "options", ")", "returned_md5", "=", "response", ".", "doc", ".", "xpath", "(", "\"//MD5OfMessageBody\"", ")", ".", "text", "raise", "MessageHasWrongMd5Error", ".", "new", "(", "message_body", ",", "md5", ",", "returned_md5", ")", "unless", "md5", "==", "returned_md5", "rescue", "MessageHasWrongMd5Error", "if", "tries", "<", "2", "retry", "else", "raise", "end", "end", "end" ]
Put a message on a queue. Takes the queue url and the message body, which should be a string. An optional delay seconds argument can be added if the message should not become visible immediately. @param [String] queue_url @param [String] message_body @param [Fixnum] delay_seconds @return nil @raise [MessageHasWrongMd5Error] @raise [AwsActionError] @example client.send_message(queue.path, "test message")
[ "Put", "a", "message", "on", "a", "queue", ".", "Takes", "the", "queue", "url", "and", "the", "message", "body", "which", "should", "be", "a", "string", ".", "An", "optional", "delay", "seconds", "argument", "can", "be", "added", "if", "the", "message", "should", "not", "become", "visible", "immediately", "." ]
c48ab555f07664752bcbf9e8deb99bd75cbdc41b
https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/client.rb#L146-L166
7,542
ntalbott/mupnp
lib/UPnP.rb
UPnP.UPnP.externalIP
def externalIP() joinThread() external_ip = getCString() r = MiniUPnP.UPNP_GetExternalIPAddress(@urls.controlURL, @data.servicetype,external_ip) if r != 0 then raise UPnPException.new, "Error while retriving the external ip address. #{code2error(r)}." end return external_ip.rstrip() end
ruby
def externalIP() joinThread() external_ip = getCString() r = MiniUPnP.UPNP_GetExternalIPAddress(@urls.controlURL, @data.servicetype,external_ip) if r != 0 then raise UPnPException.new, "Error while retriving the external ip address. #{code2error(r)}." end return external_ip.rstrip() end
[ "def", "externalIP", "(", ")", "joinThread", "(", ")", "external_ip", "=", "getCString", "(", ")", "r", "=", "MiniUPnP", ".", "UPNP_GetExternalIPAddress", "(", "@urls", ".", "controlURL", ",", "@data", ".", "servicetype", ",", "external_ip", ")", "if", "r", "!=", "0", "then", "raise", "UPnPException", ".", "new", ",", "\"Error while retriving the external ip address. #{code2error(r)}.\"", "end", "return", "external_ip", ".", "rstrip", "(", ")", "end" ]
Returns the external network ip
[ "Returns", "the", "external", "network", "ip" ]
c3c566cd2d7c9ecf1cb2baff253d116be163384d
https://github.com/ntalbott/mupnp/blob/c3c566cd2d7c9ecf1cb2baff253d116be163384d/lib/UPnP.rb#L154-L163
7,543
ntalbott/mupnp
lib/UPnP.rb
UPnP.UPnP.status
def status() joinThread() lastconnerror = getCString() status = getCString() uptime = 0 begin uptime_uint = MiniUPnP.new_uintp() r = MiniUPnP.UPNP_GetStatusInfo(@urls.controlURL, @data.servicetype, status, uptime_uint, lastconnerror) if r != 0 then raise UPnPException.new, "Error while retriving status info. #{code2error(r)}." end uptime = MiniUPnP.uintp_value(uptime_uint) rescue raise ensure MiniUPnP.delete_uintp(uptime_uint) end return status.rstrip,lastconnerror.rstrip,uptime end
ruby
def status() joinThread() lastconnerror = getCString() status = getCString() uptime = 0 begin uptime_uint = MiniUPnP.new_uintp() r = MiniUPnP.UPNP_GetStatusInfo(@urls.controlURL, @data.servicetype, status, uptime_uint, lastconnerror) if r != 0 then raise UPnPException.new, "Error while retriving status info. #{code2error(r)}." end uptime = MiniUPnP.uintp_value(uptime_uint) rescue raise ensure MiniUPnP.delete_uintp(uptime_uint) end return status.rstrip,lastconnerror.rstrip,uptime end
[ "def", "status", "(", ")", "joinThread", "(", ")", "lastconnerror", "=", "getCString", "(", ")", "status", "=", "getCString", "(", ")", "uptime", "=", "0", "begin", "uptime_uint", "=", "MiniUPnP", ".", "new_uintp", "(", ")", "r", "=", "MiniUPnP", ".", "UPNP_GetStatusInfo", "(", "@urls", ".", "controlURL", ",", "@data", ".", "servicetype", ",", "status", ",", "uptime_uint", ",", "lastconnerror", ")", "if", "r", "!=", "0", "then", "raise", "UPnPException", ".", "new", ",", "\"Error while retriving status info. #{code2error(r)}.\"", "end", "uptime", "=", "MiniUPnP", ".", "uintp_value", "(", "uptime_uint", ")", "rescue", "raise", "ensure", "MiniUPnP", ".", "delete_uintp", "(", "uptime_uint", ")", "end", "return", "status", ".", "rstrip", ",", "lastconnerror", ".", "rstrip", ",", "uptime", "end" ]
Returns the status of the router which is an array of 3 elements. Connection status, Last error, Uptime.
[ "Returns", "the", "status", "of", "the", "router", "which", "is", "an", "array", "of", "3", "elements", ".", "Connection", "status", "Last", "error", "Uptime", "." ]
c3c566cd2d7c9ecf1cb2baff253d116be163384d
https://github.com/ntalbott/mupnp/blob/c3c566cd2d7c9ecf1cb2baff253d116be163384d/lib/UPnP.rb#L173-L193
7,544
ntalbott/mupnp
lib/UPnP.rb
UPnP.UPnP.connectionType
def connectionType() joinThread() type = getCString() if MiniUPnP.UPNP_GetConnectionTypeInfo(@urls.controlURL, @data.servicetype,type) != 0 then raise UPnPException.new, "Error while retriving connection info." end type.rstrip end
ruby
def connectionType() joinThread() type = getCString() if MiniUPnP.UPNP_GetConnectionTypeInfo(@urls.controlURL, @data.servicetype,type) != 0 then raise UPnPException.new, "Error while retriving connection info." end type.rstrip end
[ "def", "connectionType", "(", ")", "joinThread", "(", ")", "type", "=", "getCString", "(", ")", "if", "MiniUPnP", ".", "UPNP_GetConnectionTypeInfo", "(", "@urls", ".", "controlURL", ",", "@data", ".", "servicetype", ",", "type", ")", "!=", "0", "then", "raise", "UPnPException", ".", "new", ",", "\"Error while retriving connection info.\"", "end", "type", ".", "rstrip", "end" ]
Router connection information
[ "Router", "connection", "information" ]
c3c566cd2d7c9ecf1cb2baff253d116be163384d
https://github.com/ntalbott/mupnp/blob/c3c566cd2d7c9ecf1cb2baff253d116be163384d/lib/UPnP.rb#L196-L204
7,545
ntalbott/mupnp
lib/UPnP.rb
UPnP.UPnP.totalBytesSent
def totalBytesSent() joinThread() v = MiniUPnP.UPNP_GetTotalBytesSent(@urls.controlURL_CIF, @data.servicetype_CIF) if v < 0 then raise UPnPException.new, "Error while retriving total bytes sent." end return v end
ruby
def totalBytesSent() joinThread() v = MiniUPnP.UPNP_GetTotalBytesSent(@urls.controlURL_CIF, @data.servicetype_CIF) if v < 0 then raise UPnPException.new, "Error while retriving total bytes sent." end return v end
[ "def", "totalBytesSent", "(", ")", "joinThread", "(", ")", "v", "=", "MiniUPnP", ".", "UPNP_GetTotalBytesSent", "(", "@urls", ".", "controlURL_CIF", ",", "@data", ".", "servicetype_CIF", ")", "if", "v", "<", "0", "then", "raise", "UPnPException", ".", "new", ",", "\"Error while retriving total bytes sent.\"", "end", "return", "v", "end" ]
Total bytes sent from the router to external network
[ "Total", "bytes", "sent", "from", "the", "router", "to", "external", "network" ]
c3c566cd2d7c9ecf1cb2baff253d116be163384d
https://github.com/ntalbott/mupnp/blob/c3c566cd2d7c9ecf1cb2baff253d116be163384d/lib/UPnP.rb#L207-L215
7,546
ntalbott/mupnp
lib/UPnP.rb
UPnP.UPnP.totalBytesReceived
def totalBytesReceived() joinThread() v = MiniUPnP.UPNP_GetTotalBytesReceived(@urls.controlURL_CIF, @data.servicetype_CIF) if v < 0 then raise UPnPException.new, "Error while retriving total bytes received." end return v end
ruby
def totalBytesReceived() joinThread() v = MiniUPnP.UPNP_GetTotalBytesReceived(@urls.controlURL_CIF, @data.servicetype_CIF) if v < 0 then raise UPnPException.new, "Error while retriving total bytes received." end return v end
[ "def", "totalBytesReceived", "(", ")", "joinThread", "(", ")", "v", "=", "MiniUPnP", ".", "UPNP_GetTotalBytesReceived", "(", "@urls", ".", "controlURL_CIF", ",", "@data", ".", "servicetype_CIF", ")", "if", "v", "<", "0", "then", "raise", "UPnPException", ".", "new", ",", "\"Error while retriving total bytes received.\"", "end", "return", "v", "end" ]
Total bytes received from the external network.
[ "Total", "bytes", "received", "from", "the", "external", "network", "." ]
c3c566cd2d7c9ecf1cb2baff253d116be163384d
https://github.com/ntalbott/mupnp/blob/c3c566cd2d7c9ecf1cb2baff253d116be163384d/lib/UPnP.rb#L218-L226
7,547
ntalbott/mupnp
lib/UPnP.rb
UPnP.UPnP.totalPacketsSent
def totalPacketsSent() joinThread() v = MiniUPnP.UPNP_GetTotalPacketsSent(@urls.controlURL_CIF, @data.servicetype_CIF); if v < 0 then raise UPnPException.new, "Error while retriving total packets sent." end return v end
ruby
def totalPacketsSent() joinThread() v = MiniUPnP.UPNP_GetTotalPacketsSent(@urls.controlURL_CIF, @data.servicetype_CIF); if v < 0 then raise UPnPException.new, "Error while retriving total packets sent." end return v end
[ "def", "totalPacketsSent", "(", ")", "joinThread", "(", ")", "v", "=", "MiniUPnP", ".", "UPNP_GetTotalPacketsSent", "(", "@urls", ".", "controlURL_CIF", ",", "@data", ".", "servicetype_CIF", ")", ";", "if", "v", "<", "0", "then", "raise", "UPnPException", ".", "new", ",", "\"Error while retriving total packets sent.\"", "end", "return", "v", "end" ]
Total packets sent from the router to the external network.
[ "Total", "packets", "sent", "from", "the", "router", "to", "the", "external", "network", "." ]
c3c566cd2d7c9ecf1cb2baff253d116be163384d
https://github.com/ntalbott/mupnp/blob/c3c566cd2d7c9ecf1cb2baff253d116be163384d/lib/UPnP.rb#L229-L237
7,548
ntalbott/mupnp
lib/UPnP.rb
UPnP.UPnP.portMappings
def portMappings() joinThread() i, r = 0, 0 mappings = Array.new while r == 0 rhost = getCString() enabled = getCString() duration = getCString() description = getCString() nport = getCString() lport = getCString() duration = getCString() client = getCString() protocol = getCString() r = MiniUPnP.UPNP_GetGenericPortMappingEntry(@urls.controlURL, @data.servicetype,i.to_s,nport,client,lport, protocol,description,enabled,rhost,duration) if r != 0 then break; end i = i+1 mappings << PortMapping.new(client.rstrip,lport.rstrip.to_i, nport.rstrip.to_i,protocol.rstrip, description.rstrip,enabled.rstrip, rhost.rstrip,duration.rstrip) end return mappings end
ruby
def portMappings() joinThread() i, r = 0, 0 mappings = Array.new while r == 0 rhost = getCString() enabled = getCString() duration = getCString() description = getCString() nport = getCString() lport = getCString() duration = getCString() client = getCString() protocol = getCString() r = MiniUPnP.UPNP_GetGenericPortMappingEntry(@urls.controlURL, @data.servicetype,i.to_s,nport,client,lport, protocol,description,enabled,rhost,duration) if r != 0 then break; end i = i+1 mappings << PortMapping.new(client.rstrip,lport.rstrip.to_i, nport.rstrip.to_i,protocol.rstrip, description.rstrip,enabled.rstrip, rhost.rstrip,duration.rstrip) end return mappings end
[ "def", "portMappings", "(", ")", "joinThread", "(", ")", "i", ",", "r", "=", "0", ",", "0", "mappings", "=", "Array", ".", "new", "while", "r", "==", "0", "rhost", "=", "getCString", "(", ")", "enabled", "=", "getCString", "(", ")", "duration", "=", "getCString", "(", ")", "description", "=", "getCString", "(", ")", "nport", "=", "getCString", "(", ")", "lport", "=", "getCString", "(", ")", "duration", "=", "getCString", "(", ")", "client", "=", "getCString", "(", ")", "protocol", "=", "getCString", "(", ")", "r", "=", "MiniUPnP", ".", "UPNP_GetGenericPortMappingEntry", "(", "@urls", ".", "controlURL", ",", "@data", ".", "servicetype", ",", "i", ".", "to_s", ",", "nport", ",", "client", ",", "lport", ",", "protocol", ",", "description", ",", "enabled", ",", "rhost", ",", "duration", ")", "if", "r", "!=", "0", "then", "break", ";", "end", "i", "=", "i", "+", "1", "mappings", "<<", "PortMapping", ".", "new", "(", "client", ".", "rstrip", ",", "lport", ".", "rstrip", ".", "to_i", ",", "nport", ".", "rstrip", ".", "to_i", ",", "protocol", ".", "rstrip", ",", "description", ".", "rstrip", ",", "enabled", ".", "rstrip", ",", "rhost", ".", "rstrip", ",", "duration", ".", "rstrip", ")", "end", "return", "mappings", "end" ]
An array of mappings registered on the router
[ "An", "array", "of", "mappings", "registered", "on", "the", "router" ]
c3c566cd2d7c9ecf1cb2baff253d116be163384d
https://github.com/ntalbott/mupnp/blob/c3c566cd2d7c9ecf1cb2baff253d116be163384d/lib/UPnP.rb#L275-L303
7,549
ntalbott/mupnp
lib/UPnP.rb
UPnP.UPnP.portMapping
def portMapping(nport,proto) checkProto(proto) checkPort(nport) if nport.to_i == 0 then raise ArgumentError, "Port must be an int value and greater then 0." end joinThread() client = getCString() lport = getCString() if MiniUPnP.UPNP_GetSpecificPortMappingEntry(@urls.controlURL, @data.servicetype, nport.to_s,proto, client,lport) != 0 then raise UPnPException.new, "Error while retriving the port mapping." end return client.rstrip, lport.rstrip.to_i end
ruby
def portMapping(nport,proto) checkProto(proto) checkPort(nport) if nport.to_i == 0 then raise ArgumentError, "Port must be an int value and greater then 0." end joinThread() client = getCString() lport = getCString() if MiniUPnP.UPNP_GetSpecificPortMappingEntry(@urls.controlURL, @data.servicetype, nport.to_s,proto, client,lport) != 0 then raise UPnPException.new, "Error while retriving the port mapping." end return client.rstrip, lport.rstrip.to_i end
[ "def", "portMapping", "(", "nport", ",", "proto", ")", "checkProto", "(", "proto", ")", "checkPort", "(", "nport", ")", "if", "nport", ".", "to_i", "==", "0", "then", "raise", "ArgumentError", ",", "\"Port must be an int value and greater then 0.\"", "end", "joinThread", "(", ")", "client", "=", "getCString", "(", ")", "lport", "=", "getCString", "(", ")", "if", "MiniUPnP", ".", "UPNP_GetSpecificPortMappingEntry", "(", "@urls", ".", "controlURL", ",", "@data", ".", "servicetype", ",", "nport", ".", "to_s", ",", "proto", ",", "client", ",", "lport", ")", "!=", "0", "then", "raise", "UPnPException", ".", "new", ",", "\"Error while retriving the port mapping.\"", "end", "return", "client", ".", "rstrip", ",", "lport", ".", "rstrip", ".", "to_i", "end" ]
Get the mapping registered for a specific port and protocol
[ "Get", "the", "mapping", "registered", "for", "a", "specific", "port", "and", "protocol" ]
c3c566cd2d7c9ecf1cb2baff253d116be163384d
https://github.com/ntalbott/mupnp/blob/c3c566cd2d7c9ecf1cb2baff253d116be163384d/lib/UPnP.rb#L306-L321
7,550
ntalbott/mupnp
lib/UPnP.rb
UPnP.UPnP.deletePortMapping
def deletePortMapping(nport,proto) checkProto(proto) checkPort(nport) joinThread() r = MiniUPnP.UPNP_DeletePortMapping(@urls.controlURL,@data.servicetype, nport.to_s,proto) if r != 0 then raise UPnPException.new , "Failed delete mapping: #{code2error(r)}." end end
ruby
def deletePortMapping(nport,proto) checkProto(proto) checkPort(nport) joinThread() r = MiniUPnP.UPNP_DeletePortMapping(@urls.controlURL,@data.servicetype, nport.to_s,proto) if r != 0 then raise UPnPException.new , "Failed delete mapping: #{code2error(r)}." end end
[ "def", "deletePortMapping", "(", "nport", ",", "proto", ")", "checkProto", "(", "proto", ")", "checkPort", "(", "nport", ")", "joinThread", "(", ")", "r", "=", "MiniUPnP", ".", "UPNP_DeletePortMapping", "(", "@urls", ".", "controlURL", ",", "@data", ".", "servicetype", ",", "nport", ".", "to_s", ",", "proto", ")", "if", "r", "!=", "0", "then", "raise", "UPnPException", ".", "new", ",", "\"Failed delete mapping: #{code2error(r)}.\"", "end", "end" ]
Delete the port mapping for specified network port and protocol
[ "Delete", "the", "port", "mapping", "for", "specified", "network", "port", "and", "protocol" ]
c3c566cd2d7c9ecf1cb2baff253d116be163384d
https://github.com/ntalbott/mupnp/blob/c3c566cd2d7c9ecf1cb2baff253d116be163384d/lib/UPnP.rb#L341-L350
7,551
ntalbott/mupnp
lib/UPnP.rb
UPnP.UPnP.checkProto
def checkProto(proto) if proto != Protocol::UDP && proto != Protocol::TCP then raise ArgumentError, "Unknown protocol #{proto}, only Protocol::TCP and Protocol::UDP are valid." end end
ruby
def checkProto(proto) if proto != Protocol::UDP && proto != Protocol::TCP then raise ArgumentError, "Unknown protocol #{proto}, only Protocol::TCP and Protocol::UDP are valid." end end
[ "def", "checkProto", "(", "proto", ")", "if", "proto", "!=", "Protocol", "::", "UDP", "&&", "proto", "!=", "Protocol", "::", "TCP", "then", "raise", "ArgumentError", ",", "\"Unknown protocol #{proto}, only Protocol::TCP and Protocol::UDP are valid.\"", "end", "end" ]
Check that the protocol is a correct value
[ "Check", "that", "the", "protocol", "is", "a", "correct", "value" ]
c3c566cd2d7c9ecf1cb2baff253d116be163384d
https://github.com/ntalbott/mupnp/blob/c3c566cd2d7c9ecf1cb2baff253d116be163384d/lib/UPnP.rb#L367-L371
7,552
bilus/akasha
lib/akasha/command_router.rb
Akasha.CommandRouter.register
def register(command, aggregate_class = nil, &block) raise ArgumentError, 'Pass either aggregate class or block' if aggregate_class && block handler = aggregate_class || block @routes[command] = handler end
ruby
def register(command, aggregate_class = nil, &block) raise ArgumentError, 'Pass either aggregate class or block' if aggregate_class && block handler = aggregate_class || block @routes[command] = handler end
[ "def", "register", "(", "command", ",", "aggregate_class", "=", "nil", ",", "&", "block", ")", "raise", "ArgumentError", ",", "'Pass either aggregate class or block'", "if", "aggregate_class", "&&", "block", "handler", "=", "aggregate_class", "||", "block", "@routes", "[", "command", "]", "=", "handler", "end" ]
Registers a handler. As a result, when `#route!` is called for that command, the aggregate will be loaded from repository, the command will be sent to the object to invoke the object's method, and finally the aggregate will be saved.
[ "Registers", "a", "handler", "." ]
5fadefc249f520ae909b762956ac23a6f916b021
https://github.com/bilus/akasha/blob/5fadefc249f520ae909b762956ac23a6f916b021/lib/akasha/command_router.rb#L18-L22
7,553
bilus/akasha
lib/akasha/command_router.rb
Akasha.CommandRouter.route!
def route!(command, aggregate_id, options = {}, **data) handler = @routes[command] case handler when Class transactor = options.fetch(:transactor, default_transactor) transactor.call(handler, command, aggregate_id, options, **data) when handler.respond_to?(:call) handler.call(command, aggregate_id, options, **data) when Proc handler.call(command, aggregate_id, options, **data) when nil raise HandlerNotFoundError, "Handler for command #{command.inspect} not found" else raise UnsupportedHandlerError, "Unsupported command handler #{handler.inspect}" end end
ruby
def route!(command, aggregate_id, options = {}, **data) handler = @routes[command] case handler when Class transactor = options.fetch(:transactor, default_transactor) transactor.call(handler, command, aggregate_id, options, **data) when handler.respond_to?(:call) handler.call(command, aggregate_id, options, **data) when Proc handler.call(command, aggregate_id, options, **data) when nil raise HandlerNotFoundError, "Handler for command #{command.inspect} not found" else raise UnsupportedHandlerError, "Unsupported command handler #{handler.inspect}" end end
[ "def", "route!", "(", "command", ",", "aggregate_id", ",", "options", "=", "{", "}", ",", "**", "data", ")", "handler", "=", "@routes", "[", "command", "]", "case", "handler", "when", "Class", "transactor", "=", "options", ".", "fetch", "(", ":transactor", ",", "default_transactor", ")", "transactor", ".", "call", "(", "handler", ",", "command", ",", "aggregate_id", ",", "options", ",", "**", "data", ")", "when", "handler", ".", "respond_to?", "(", ":call", ")", "handler", ".", "call", "(", "command", ",", "aggregate_id", ",", "options", ",", "**", "data", ")", "when", "Proc", "handler", ".", "call", "(", "command", ",", "aggregate_id", ",", "options", ",", "**", "data", ")", "when", "nil", "raise", "HandlerNotFoundError", ",", "\"Handler for command #{command.inspect} not found\"", "else", "raise", "UnsupportedHandlerError", ",", "\"Unsupported command handler #{handler.inspect}\"", "end", "end" ]
Routes a command to the registered target. Raises `NotFoundError` if no corresponding target can be found. Arguments: - command - name of the command - aggregate_id - aggregate id - options - flags: - transactor - transactor instance to replace the default one (`OptimisticTransactor`); See docs for `OptimisticTransactor` for a list of additional supported options.
[ "Routes", "a", "command", "to", "the", "registered", "target", ".", "Raises", "NotFoundError", "if", "no", "corresponding", "target", "can", "be", "found", "." ]
5fadefc249f520ae909b762956ac23a6f916b021
https://github.com/bilus/akasha/blob/5fadefc249f520ae909b762956ac23a6f916b021/lib/akasha/command_router.rb#L33-L48
7,554
emancu/ork
lib/ork/model/class_methods.rb
Ork::Model.ClassMethods.attribute
def attribute(name, options = {}) attributes << name unless attributes.include?(name) defaults[name] = options[:default] if options.has_key?(:default) if options.has_key?(:accessors) to_define = Array(options[:accessors]) & accessor_options else # Default methods to_define = [:reader, :writer] end to_define.each{|m| send("#{m}_for", name) } end
ruby
def attribute(name, options = {}) attributes << name unless attributes.include?(name) defaults[name] = options[:default] if options.has_key?(:default) if options.has_key?(:accessors) to_define = Array(options[:accessors]) & accessor_options else # Default methods to_define = [:reader, :writer] end to_define.each{|m| send("#{m}_for", name) } end
[ "def", "attribute", "(", "name", ",", "options", "=", "{", "}", ")", "attributes", "<<", "name", "unless", "attributes", ".", "include?", "(", "name", ")", "defaults", "[", "name", "]", "=", "options", "[", ":default", "]", "if", "options", ".", "has_key?", "(", ":default", ")", "if", "options", ".", "has_key?", "(", ":accessors", ")", "to_define", "=", "Array", "(", "options", "[", ":accessors", "]", ")", "&", "accessor_options", "else", "# Default methods", "to_define", "=", "[", ":reader", ",", ":writer", "]", "end", "to_define", ".", "each", "{", "|", "m", "|", "send", "(", "\"#{m}_for\"", ",", "name", ")", "}", "end" ]
Declares persisted attributes. All attributes are stored on the Riak hash. Example: class User include Ork::Document attribute :name end # It's the same as: class User include Ork::Document def name @attributes[:name] end def name=(name) @attributes[:name] = name end end
[ "Declares", "persisted", "attributes", ".", "All", "attributes", "are", "stored", "on", "the", "Riak", "hash", "." ]
83b2deaef0e790d90f98c031f254b5f438b19edf
https://github.com/emancu/ork/blob/83b2deaef0e790d90f98c031f254b5f438b19edf/lib/ork/model/class_methods.rb#L83-L94
7,555
emancu/ork
lib/ork/model/class_methods.rb
Ork::Model.ClassMethods.index
def index(name) indices[name] = Index.new(name) unless indices.include?(name) end
ruby
def index(name) indices[name] = Index.new(name) unless indices.include?(name) end
[ "def", "index", "(", "name", ")", "indices", "[", "name", "]", "=", "Index", ".", "new", "(", "name", ")", "unless", "indices", ".", "include?", "(", "name", ")", "end" ]
Index any attribute on your model. Once you index an attribute, you can use it in `find` statements.
[ "Index", "any", "attribute", "on", "your", "model", ".", "Once", "you", "index", "an", "attribute", "you", "can", "use", "it", "in", "find", "statements", "." ]
83b2deaef0e790d90f98c031f254b5f438b19edf
https://github.com/emancu/ork/blob/83b2deaef0e790d90f98c031f254b5f438b19edf/lib/ork/model/class_methods.rb#L99-L101
7,556
gzigzigzeo/stateful_link
lib/stateful_link/action_any_of.rb
StatefulLink.ActionAnyOf.action_any_of?
def action_any_of?(*actions) actions.any? do |sub_ca| if sub_ca.present? sub_controller, sub_action = extract_controller_and_action(sub_ca) ((self.controller_path == sub_controller) || (sub_controller.blank?)) && (self.action_name == sub_action || (sub_action == '' || sub_action == '*')) end end end
ruby
def action_any_of?(*actions) actions.any? do |sub_ca| if sub_ca.present? sub_controller, sub_action = extract_controller_and_action(sub_ca) ((self.controller_path == sub_controller) || (sub_controller.blank?)) && (self.action_name == sub_action || (sub_action == '' || sub_action == '*')) end end end
[ "def", "action_any_of?", "(", "*", "actions", ")", "actions", ".", "any?", "do", "|", "sub_ca", "|", "if", "sub_ca", ".", "present?", "sub_controller", ",", "sub_action", "=", "extract_controller_and_action", "(", "sub_ca", ")", "(", "(", "self", ".", "controller_path", "==", "sub_controller", ")", "||", "(", "sub_controller", ".", "blank?", ")", ")", "&&", "(", "self", ".", "action_name", "==", "sub_action", "||", "(", "sub_action", "==", "''", "||", "sub_action", "==", "'*'", ")", ")", "end", "end", "end" ]
Returns true if current controller and action names equals to any of passed. Asterik as action name matches all controller's action. Examples: <%= "we are in PostsController::index" if action_any_of?("posts#index") %> <%= "we are not in PostsController::index" unless action_any_of?("posts#index") %> <% if action_any_of?("posts#index", "messages#index") %> we are in PostsController or in MessagesController <% end %>
[ "Returns", "true", "if", "current", "controller", "and", "action", "names", "equals", "to", "any", "of", "passed", ".", "Asterik", "as", "action", "name", "matches", "all", "controller", "s", "action", "." ]
e9073fcb3523bb15e17cc1bf40ca813dd0fd7659
https://github.com/gzigzigzeo/stateful_link/blob/e9073fcb3523bb15e17cc1bf40ca813dd0fd7659/lib/stateful_link/action_any_of.rb#L21-L28
7,557
gzigzigzeo/stateful_link
lib/stateful_link/action_any_of.rb
StatefulLink.ActionAnyOf.extract_controller_and_action
def extract_controller_and_action(ca) raise ArgumentError, "Pass the string" if ca.nil? slash_pos = ca.rindex('#') raise ArgumentError, "Invalid action: #{ca}" if slash_pos.nil? controller = ca[0, slash_pos] action = ca[slash_pos+1..-1] || "" raise ArgumentError, "Invalid action or controller" if action.nil? [controller, action] end
ruby
def extract_controller_and_action(ca) raise ArgumentError, "Pass the string" if ca.nil? slash_pos = ca.rindex('#') raise ArgumentError, "Invalid action: #{ca}" if slash_pos.nil? controller = ca[0, slash_pos] action = ca[slash_pos+1..-1] || "" raise ArgumentError, "Invalid action or controller" if action.nil? [controller, action] end
[ "def", "extract_controller_and_action", "(", "ca", ")", "raise", "ArgumentError", ",", "\"Pass the string\"", "if", "ca", ".", "nil?", "slash_pos", "=", "ca", ".", "rindex", "(", "'#'", ")", "raise", "ArgumentError", ",", "\"Invalid action: #{ca}\"", "if", "slash_pos", ".", "nil?", "controller", "=", "ca", "[", "0", ",", "slash_pos", "]", "action", "=", "ca", "[", "slash_pos", "+", "1", "..", "-", "1", "]", "||", "\"\"", "raise", "ArgumentError", ",", "\"Invalid action or controller\"", "if", "action", ".", "nil?", "[", "controller", ",", "action", "]", "end" ]
Extracts controller and action names from a string. Examples: extract_controller_and_action("posts#index") # ["posts", "index"] extract_controller_and_action("admin/posts#index") # ["admin/posts", "index"] extract_controller_and_action("admin/posts#index") # raises ArgumentError
[ "Extracts", "controller", "and", "action", "names", "from", "a", "string", "." ]
e9073fcb3523bb15e17cc1bf40ca813dd0fd7659
https://github.com/gzigzigzeo/stateful_link/blob/e9073fcb3523bb15e17cc1bf40ca813dd0fd7659/lib/stateful_link/action_any_of.rb#L38-L47
7,558
bumi/validation_rage
lib/validation_rage/fnord_metric_notifier.rb
ValidationRage.FnordMetricNotifier.call
def call(event_name, payload) return unless data_present?(payload) # global validation error event self.fnord.event({ :_type => event_name, :payload => payload }) # class level validation error event self.fnord.event({ :_type => "validation_rage_error.#{payload.keys.first.to_s.downcase}", :payload => payload.values.first.keys }) # two events are enough for now ## attribute level validation error event #payload.values.first.each do |attribute, error_messages| # self.fnord.event({ # :_type => "validation_rage_error.#{payload.keys.first.to_s.downcase}.#{attribute}", # :payload => error_messages # }) #end end
ruby
def call(event_name, payload) return unless data_present?(payload) # global validation error event self.fnord.event({ :_type => event_name, :payload => payload }) # class level validation error event self.fnord.event({ :_type => "validation_rage_error.#{payload.keys.first.to_s.downcase}", :payload => payload.values.first.keys }) # two events are enough for now ## attribute level validation error event #payload.values.first.each do |attribute, error_messages| # self.fnord.event({ # :_type => "validation_rage_error.#{payload.keys.first.to_s.downcase}.#{attribute}", # :payload => error_messages # }) #end end
[ "def", "call", "(", "event_name", ",", "payload", ")", "return", "unless", "data_present?", "(", "payload", ")", "# global validation error event", "self", ".", "fnord", ".", "event", "(", "{", ":_type", "=>", "event_name", ",", ":payload", "=>", "payload", "}", ")", "# class level validation error event", "self", ".", "fnord", ".", "event", "(", "{", ":_type", "=>", "\"validation_rage_error.#{payload.keys.first.to_s.downcase}\"", ",", ":payload", "=>", "payload", ".", "values", ".", "first", ".", "keys", "}", ")", "# two events are enough for now", "## attribute level validation error event", "#payload.values.first.each do |attribute, error_messages|", "# self.fnord.event({", "# :_type => \"validation_rage_error.#{payload.keys.first.to_s.downcase}.#{attribute}\",", "# :payload => error_messages", "# })", "#end", "end" ]
I guess this is toooooo sloooow but anyhow let's play with it
[ "I", "guess", "this", "is", "toooooo", "sloooow", "but", "anyhow", "let", "s", "play", "with", "it" ]
0680444bac70e1d9ab42a7b421a09e8ba9d0d7c6
https://github.com/bumi/validation_rage/blob/0680444bac70e1d9ab42a7b421a09e8ba9d0d7c6/lib/validation_rage/fnord_metric_notifier.rb#L11-L32
7,559
vidibus/vidibus-tempfile
lib/vidibus/tempfile.rb
Vidibus.Tempfile.make_tmpname
def make_tmpname(basename, n) extension = File.extname(basename) sprintf("%s,%d,%d%s", File.basename(basename, extension), $$, n.to_i, extension) end
ruby
def make_tmpname(basename, n) extension = File.extname(basename) sprintf("%s,%d,%d%s", File.basename(basename, extension), $$, n.to_i, extension) end
[ "def", "make_tmpname", "(", "basename", ",", "n", ")", "extension", "=", "File", ".", "extname", "(", "basename", ")", "sprintf", "(", "\"%s,%d,%d%s\"", ",", "File", ".", "basename", "(", "basename", ",", "extension", ")", ",", "$$", ",", "n", ".", "to_i", ",", "extension", ")", "end" ]
Replaces Tempfile's +make_tmpname+ with one that honors file extensions. Copied from Paperclip
[ "Replaces", "Tempfile", "s", "+", "make_tmpname", "+", "with", "one", "that", "honors", "file", "extensions", ".", "Copied", "from", "Paperclip" ]
3c06359ccb28cfc36a4dfcbb856d257a18df7c95
https://github.com/vidibus/vidibus-tempfile/blob/3c06359ccb28cfc36a4dfcbb856d257a18df7c95/lib/vidibus/tempfile.rb#L34-L37
7,560
kennon/litmos-client
lib/litmos_client.rb
LitmosClient.API.get
def get(path, params={}) dont_parse_response = params.delete(:dont_parse_response) options = { :content_type => :json, :accept => :json, :params => params.merge(:apikey => @api_key, :source => @source) } RestClient.get("#{@litmosURL}/#{path}", options) do |response, request, result| case response.code when 200, 201 # 200 Success. User/Course etc updated, deleted or retrieved # 201 Success. User/Course etc created if response.blank? true else if dont_parse_response response else parse_response(response) end end when 404 # 404 Not Found. The User/Course etc that you requested does not exist raise NotFound.new(response) else # 400 Bad Request. Check that your Uri and request body is well formed # 403 Forbidden. Check your API key, HTTPS setting, Source parameter etc # 409 Conflict. Often occurs when trying to create an item that already exists raise ApiError.new(response) end end end
ruby
def get(path, params={}) dont_parse_response = params.delete(:dont_parse_response) options = { :content_type => :json, :accept => :json, :params => params.merge(:apikey => @api_key, :source => @source) } RestClient.get("#{@litmosURL}/#{path}", options) do |response, request, result| case response.code when 200, 201 # 200 Success. User/Course etc updated, deleted or retrieved # 201 Success. User/Course etc created if response.blank? true else if dont_parse_response response else parse_response(response) end end when 404 # 404 Not Found. The User/Course etc that you requested does not exist raise NotFound.new(response) else # 400 Bad Request. Check that your Uri and request body is well formed # 403 Forbidden. Check your API key, HTTPS setting, Source parameter etc # 409 Conflict. Often occurs when trying to create an item that already exists raise ApiError.new(response) end end end
[ "def", "get", "(", "path", ",", "params", "=", "{", "}", ")", "dont_parse_response", "=", "params", ".", "delete", "(", ":dont_parse_response", ")", "options", "=", "{", ":content_type", "=>", ":json", ",", ":accept", "=>", ":json", ",", ":params", "=>", "params", ".", "merge", "(", ":apikey", "=>", "@api_key", ",", ":source", "=>", "@source", ")", "}", "RestClient", ".", "get", "(", "\"#{@litmosURL}/#{path}\"", ",", "options", ")", "do", "|", "response", ",", "request", ",", "result", "|", "case", "response", ".", "code", "when", "200", ",", "201", "# 200 Success. User/Course etc updated, deleted or retrieved", "# 201 Success. User/Course etc created", "if", "response", ".", "blank?", "true", "else", "if", "dont_parse_response", "response", "else", "parse_response", "(", "response", ")", "end", "end", "when", "404", "# 404 Not Found. The User/Course etc that you requested does not exist", "raise", "NotFound", ".", "new", "(", "response", ")", "else", "# 400 Bad Request. Check that your Uri and request body is well formed", "# 403 Forbidden. Check your API key, HTTPS setting, Source parameter etc", "# 409 Conflict. Often occurs when trying to create an item that already exists", "raise", "ApiError", ".", "new", "(", "response", ")", "end", "end", "end" ]
Initialize with an API key and config options
[ "Initialize", "with", "an", "API", "key", "and", "config", "options" ]
376008a961ee33543853790a0172c571b31d81f1
https://github.com/kennon/litmos-client/blob/376008a961ee33543853790a0172c571b31d81f1/lib/litmos_client.rb#L36-L70
7,561
kencrocken/dcmetro
lib/dcmetro.rb
DCMetro.Information.station_time
def station_time(station) # If a station has multiple stations codes we join the codes together @station_code = station['Code'] if !station['StationTogether1'].empty? @station_code += ",#{station['StationTogether1']}" end if !station['StationTogether2'].empty? @station_code += ",#{station['StationTogether2']}" end # The call to the api is made and the prediction times are returned @metro_time = RestClient.get "#{BASE_URL}/StationPrediction.svc/json/GetPrediction/#{@station_code}", :params => { "api_key" => API_KEY, "subscription-key" => API_KEY } @metro_time end
ruby
def station_time(station) # If a station has multiple stations codes we join the codes together @station_code = station['Code'] if !station['StationTogether1'].empty? @station_code += ",#{station['StationTogether1']}" end if !station['StationTogether2'].empty? @station_code += ",#{station['StationTogether2']}" end # The call to the api is made and the prediction times are returned @metro_time = RestClient.get "#{BASE_URL}/StationPrediction.svc/json/GetPrediction/#{@station_code}", :params => { "api_key" => API_KEY, "subscription-key" => API_KEY } @metro_time end
[ "def", "station_time", "(", "station", ")", "# If a station has multiple stations codes we join the codes together", "@station_code", "=", "station", "[", "'Code'", "]", "if", "!", "station", "[", "'StationTogether1'", "]", ".", "empty?", "@station_code", "+=", "\",#{station['StationTogether1']}\"", "end", "if", "!", "station", "[", "'StationTogether2'", "]", ".", "empty?", "@station_code", "+=", "\",#{station['StationTogether2']}\"", "end", "# The call to the api is made and the prediction times are returned", "@metro_time", "=", "RestClient", ".", "get", "\"#{BASE_URL}/StationPrediction.svc/json/GetPrediction/#{@station_code}\"", ",", ":params", "=>", "{", "\"api_key\"", "=>", "API_KEY", ",", "\"subscription-key\"", "=>", "API_KEY", "}", "@metro_time", "end" ]
This makes an api call to grab the train arrival and departure predictions. If more than one line is present at a station, such is concatenated and the call is made on all lines.
[ "This", "makes", "an", "api", "call", "to", "grab", "the", "train", "arrival", "and", "departure", "predictions", ".", "If", "more", "than", "one", "line", "is", "present", "at", "a", "station", "such", "is", "concatenated", "and", "the", "call", "is", "made", "on", "all", "lines", "." ]
9fecdea1e619da4828ae7b94c156ce705c2975fc
https://github.com/kencrocken/dcmetro/blob/9fecdea1e619da4828ae7b94c156ce705c2975fc/lib/dcmetro.rb#L168-L185
7,562
gnumarcelo/campaigning
lib/campaigning/template.rb
Campaigning.Template.update!
def update!(params) response = @@soap.updateTemplate( :apiKey => params[:apiKey] || CAMPAIGN_MONITOR_API_KEY, :templateID => @templateID, :templateName => params[:templateName], :hTMLPageURL => params[:htmlPageURL], :zipFileURL => params[:zipFileURL], :screenshotURL => params[:screenshotURL] ) handle_response response.template_UpdateResult end
ruby
def update!(params) response = @@soap.updateTemplate( :apiKey => params[:apiKey] || CAMPAIGN_MONITOR_API_KEY, :templateID => @templateID, :templateName => params[:templateName], :hTMLPageURL => params[:htmlPageURL], :zipFileURL => params[:zipFileURL], :screenshotURL => params[:screenshotURL] ) handle_response response.template_UpdateResult end
[ "def", "update!", "(", "params", ")", "response", "=", "@@soap", ".", "updateTemplate", "(", ":apiKey", "=>", "params", "[", ":apiKey", "]", "||", "CAMPAIGN_MONITOR_API_KEY", ",", ":templateID", "=>", "@templateID", ",", ":templateName", "=>", "params", "[", ":templateName", "]", ",", ":hTMLPageURL", "=>", "params", "[", ":htmlPageURL", "]", ",", ":zipFileURL", "=>", "params", "[", ":zipFileURL", "]", ",", ":screenshotURL", "=>", "params", "[", ":screenshotURL", "]", ")", "handle_response", "response", ".", "template_UpdateResult", "end" ]
Updates an existing template. Available _params_ argument are: * :templateID - The ID of the template to be updated. * :templateName - The name of the template. Maximum of 30 characters (will be truncated to 30 characters if longer). * :htmlPageURL - The URL of the HTML page you have created for the template. * :zipFileURL - Optional URL of a zip file containing any other files required by the template. * :screenshotURL - Optional URL of a screenshot of the template. Must be in jpeg format and at least 218 pixels wide. * :apiKey - optional API key to use to make request. Will use CAMPAIGN_MONITOR_API_KEY if not set. *Return*: *Success*: Upon a successful call, this method will return a Campaigning::Result object wich consists of a +code+ and +message+ fields containing a successful message. *Error*: An Exception containing the cause of the error will be raised.
[ "Updates", "an", "existing", "template", "." ]
f3d7da053b65cfa376269533183919dc890964fd
https://github.com/gnumarcelo/campaigning/blob/f3d7da053b65cfa376269533183919dc890964fd/lib/campaigning/template.rb#L79-L89
7,563
godfat/jellyfish
lib/jellyfish/normalized_params.rb
Jellyfish.NormalizedParams.force_encoding
def force_encoding(data, encoding=Encoding.default_external) return data if data.respond_to?(:rewind) # e.g. Tempfile, File, etc if data.respond_to?(:force_encoding) data.force_encoding(encoding).encode! elsif data.respond_to?(:each_value) data.each_value{ |v| force_encoding(v, encoding) } elsif data.respond_to?(:each) data.each{ |v| force_encoding(v, encoding) } end data end
ruby
def force_encoding(data, encoding=Encoding.default_external) return data if data.respond_to?(:rewind) # e.g. Tempfile, File, etc if data.respond_to?(:force_encoding) data.force_encoding(encoding).encode! elsif data.respond_to?(:each_value) data.each_value{ |v| force_encoding(v, encoding) } elsif data.respond_to?(:each) data.each{ |v| force_encoding(v, encoding) } end data end
[ "def", "force_encoding", "(", "data", ",", "encoding", "=", "Encoding", ".", "default_external", ")", "return", "data", "if", "data", ".", "respond_to?", "(", ":rewind", ")", "# e.g. Tempfile, File, etc", "if", "data", ".", "respond_to?", "(", ":force_encoding", ")", "data", ".", "force_encoding", "(", "encoding", ")", ".", "encode!", "elsif", "data", ".", "respond_to?", "(", ":each_value", ")", "data", ".", "each_value", "{", "|", "v", "|", "force_encoding", "(", "v", ",", "encoding", ")", "}", "elsif", "data", ".", "respond_to?", "(", ":each", ")", "data", ".", "each", "{", "|", "v", "|", "force_encoding", "(", "v", ",", "encoding", ")", "}", "end", "data", "end" ]
stolen from sinatra Fixes encoding issues by casting params to Encoding.default_external
[ "stolen", "from", "sinatra", "Fixes", "encoding", "issues", "by", "casting", "params", "to", "Encoding", ".", "default_external" ]
e0a9e07ee010d5f097dc62348b0b83d17d3143ff
https://github.com/godfat/jellyfish/blob/e0a9e07ee010d5f097dc62348b0b83d17d3143ff/lib/jellyfish/normalized_params.rb#L43-L53
7,564
experteer/codeqa
lib/codeqa/installer.rb
Codeqa.Installer.install_codeqa_git_hook
def install_codeqa_git_hook git_root = app_path.join('.git') pre_commit_path = git_root.join 'hooks', 'pre-commit' return false unless File.exist?(git_root) return false if File.exist?(pre_commit_path) # an alternative would be to backup the old hook # FileUtils.mv(pre_commit_path, # git_root.join('hooks', 'pre-commit.bkp'), # :force => true) pre_commit_path.make_symlink('../../.codeqa/git_hook.rb') # relative path! true end
ruby
def install_codeqa_git_hook git_root = app_path.join('.git') pre_commit_path = git_root.join 'hooks', 'pre-commit' return false unless File.exist?(git_root) return false if File.exist?(pre_commit_path) # an alternative would be to backup the old hook # FileUtils.mv(pre_commit_path, # git_root.join('hooks', 'pre-commit.bkp'), # :force => true) pre_commit_path.make_symlink('../../.codeqa/git_hook.rb') # relative path! true end
[ "def", "install_codeqa_git_hook", "git_root", "=", "app_path", ".", "join", "(", "'.git'", ")", "pre_commit_path", "=", "git_root", ".", "join", "'hooks'", ",", "'pre-commit'", "return", "false", "unless", "File", ".", "exist?", "(", "git_root", ")", "return", "false", "if", "File", ".", "exist?", "(", "pre_commit_path", ")", "# an alternative would be to backup the old hook", "# FileUtils.mv(pre_commit_path,", "# git_root.join('hooks', 'pre-commit.bkp'),", "# :force => true)", "pre_commit_path", ".", "make_symlink", "(", "'../../.codeqa/git_hook.rb'", ")", "# relative path!", "true", "end" ]
return true if installation succeeded return false if either no git repo or hook already present
[ "return", "true", "if", "installation", "succeeded", "return", "false", "if", "either", "no", "git", "repo", "or", "hook", "already", "present" ]
199fa9b686737293a3c20148ad708a60e6fef667
https://github.com/experteer/codeqa/blob/199fa9b686737293a3c20148ad708a60e6fef667/lib/codeqa/installer.rb#L34-L46
7,565
jtimberman/ubuntu_ami
lib/chef/knife/ec2_amis_ubuntu.rb
KnifePlugins.Ec2AmisUbuntu.list_amis
def list_amis(distro) amis = Hash.new Ubuntu.release(distro).amis.each do |ami| amis[build_type(ami.region, ami.arch, ami.root_store, ami.virtualization_type)] = ami.name end amis end
ruby
def list_amis(distro) amis = Hash.new Ubuntu.release(distro).amis.each do |ami| amis[build_type(ami.region, ami.arch, ami.root_store, ami.virtualization_type)] = ami.name end amis end
[ "def", "list_amis", "(", "distro", ")", "amis", "=", "Hash", ".", "new", "Ubuntu", ".", "release", "(", "distro", ")", ".", "amis", ".", "each", "do", "|", "ami", "|", "amis", "[", "build_type", "(", "ami", ".", "region", ",", "ami", ".", "arch", ",", "ami", ".", "root_store", ",", "ami", ".", "virtualization_type", ")", "]", "=", "ami", ".", "name", "end", "amis", "end" ]
Iterates over the AMIs available for the specified distro. === Parameters distro<String>:: Release name of the distro to display. === Returns Hash:: Keys are the AMI type, values are the AMI ID.
[ "Iterates", "over", "the", "AMIs", "available", "for", "the", "specified", "distro", "." ]
6df6308be3c90d038ffb5a93c4967b0444a635c8
https://github.com/jtimberman/ubuntu_ami/blob/6df6308be3c90d038ffb5a93c4967b0444a635c8/lib/chef/knife/ec2_amis_ubuntu.rb#L110-L116
7,566
26fe/tree.rb
lib/tree_rb/core/tree_node_visitor.rb
TreeRb.TreeNodeVisitor.exit_node
def exit_node(tree_node) parent = @stack.last if @delegate @delegate.exit_node(tree_node) if @delegate.respond_to? :exit_node else @on_exit_tree_node_blocks.each do |b| if b.arity == 1 b.call(tree_node) elsif b.arity == 2 b.call(tree_node, parent) end end end @stack.pop end
ruby
def exit_node(tree_node) parent = @stack.last if @delegate @delegate.exit_node(tree_node) if @delegate.respond_to? :exit_node else @on_exit_tree_node_blocks.each do |b| if b.arity == 1 b.call(tree_node) elsif b.arity == 2 b.call(tree_node, parent) end end end @stack.pop end
[ "def", "exit_node", "(", "tree_node", ")", "parent", "=", "@stack", ".", "last", "if", "@delegate", "@delegate", ".", "exit_node", "(", "tree_node", ")", "if", "@delegate", ".", "respond_to?", ":exit_node", "else", "@on_exit_tree_node_blocks", ".", "each", "do", "|", "b", "|", "if", "b", ".", "arity", "==", "1", "b", ".", "call", "(", "tree_node", ")", "elsif", "b", ".", "arity", "==", "2", "b", ".", "call", "(", "tree_node", ",", "parent", ")", "end", "end", "end", "@stack", ".", "pop", "end" ]
called on tree node at end of the visit i.e. oll subtree are visited
[ "called", "on", "tree", "node", "at", "end", "of", "the", "visit", "i", ".", "e", ".", "oll", "subtree", "are", "visited" ]
5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b
https://github.com/26fe/tree.rb/blob/5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b/lib/tree_rb/core/tree_node_visitor.rb#L64-L78
7,567
26fe/tree.rb
lib/tree_rb/core/tree_node_visitor.rb
TreeRb.TreeNodeVisitor.visit_leaf
def visit_leaf(leaf_node) parent = @stack.last if @delegate @delegate.visit_leaf(leaf_node) if @delegate.respond_to? :visit_leaf else @on_visit_leaf_node_blocks.each do |b| if b.arity == 1 b.call(leaf_node) elsif b.arity == 2 b.call(leaf_node, parent) end end end end
ruby
def visit_leaf(leaf_node) parent = @stack.last if @delegate @delegate.visit_leaf(leaf_node) if @delegate.respond_to? :visit_leaf else @on_visit_leaf_node_blocks.each do |b| if b.arity == 1 b.call(leaf_node) elsif b.arity == 2 b.call(leaf_node, parent) end end end end
[ "def", "visit_leaf", "(", "leaf_node", ")", "parent", "=", "@stack", ".", "last", "if", "@delegate", "@delegate", ".", "visit_leaf", "(", "leaf_node", ")", "if", "@delegate", ".", "respond_to?", ":visit_leaf", "else", "@on_visit_leaf_node_blocks", ".", "each", "do", "|", "b", "|", "if", "b", ".", "arity", "==", "1", "b", ".", "call", "(", "leaf_node", ")", "elsif", "b", ".", "arity", "==", "2", "b", ".", "call", "(", "leaf_node", ",", "parent", ")", "end", "end", "end", "end" ]
called when visit leaf node
[ "called", "when", "visit", "leaf", "node" ]
5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b
https://github.com/26fe/tree.rb/blob/5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b/lib/tree_rb/core/tree_node_visitor.rb#L83-L96
7,568
kirkbowers/rdoc2md
lib/rdoc2md.rb
Rdoc2md.Document.to_md
def to_md # Usually ruby is extremely readable, but I think "-1" means "give me all the # trailing blank lines" is surprisingly opaque. That's what the -1 does... lines = @text.split("\n", -1) lines.collect do |line| result = line # Leave lines that start with 4 spaces alone. These are code blocks and # should pass through unchanged. unless result =~ /^\s{4,}/ # Convert headers result.sub!(/^(=){1,6}/) { |s| "#" * s.length} unless result =~ /^={7,}/ # Convert strong to have two stars # The matching pair of stars should start with a single star that is either at # the beginning of the line or not following a backslash, have at least one # non-star and non-backslash in between, then end in one star result.gsub!(/(\A|[^\\\*])\*([^\*]*[^\*\\])\*/, '\1**\2**') # Convert inline code spans to use backticks result.gsub!(/(\A|[^\\])\+([^\+]+)\+/, '\1`\2`') # Convert bare http:, mailto: and ftp: links result.gsub!(/(\A|\s)(http:|https:|mailto:|ftp:)(\S*)/, '\1[\2\3](\2\3)') # Convert bare www to an http: link result.gsub!(/(\A|\s)www\.(\S*)/, '\1[www.\2](http://www.\2)') # Convert link: links to refer to local files result.gsub!(/(\A|\s)link:(\S*)/, '\1[\2](\2)') # Convert multi word labels surrounded by {} with a url result.gsub!(/\{([^\}]*)\}\[(\S*)\]/, '[\1](\2)') # Convert one word labels with a url result.gsub!(/(\A|\s)([^\{\s]\S*)\[(\S*)\]/, '\1[\2](\3)') end result end.join("\n") end
ruby
def to_md # Usually ruby is extremely readable, but I think "-1" means "give me all the # trailing blank lines" is surprisingly opaque. That's what the -1 does... lines = @text.split("\n", -1) lines.collect do |line| result = line # Leave lines that start with 4 spaces alone. These are code blocks and # should pass through unchanged. unless result =~ /^\s{4,}/ # Convert headers result.sub!(/^(=){1,6}/) { |s| "#" * s.length} unless result =~ /^={7,}/ # Convert strong to have two stars # The matching pair of stars should start with a single star that is either at # the beginning of the line or not following a backslash, have at least one # non-star and non-backslash in between, then end in one star result.gsub!(/(\A|[^\\\*])\*([^\*]*[^\*\\])\*/, '\1**\2**') # Convert inline code spans to use backticks result.gsub!(/(\A|[^\\])\+([^\+]+)\+/, '\1`\2`') # Convert bare http:, mailto: and ftp: links result.gsub!(/(\A|\s)(http:|https:|mailto:|ftp:)(\S*)/, '\1[\2\3](\2\3)') # Convert bare www to an http: link result.gsub!(/(\A|\s)www\.(\S*)/, '\1[www.\2](http://www.\2)') # Convert link: links to refer to local files result.gsub!(/(\A|\s)link:(\S*)/, '\1[\2](\2)') # Convert multi word labels surrounded by {} with a url result.gsub!(/\{([^\}]*)\}\[(\S*)\]/, '[\1](\2)') # Convert one word labels with a url result.gsub!(/(\A|\s)([^\{\s]\S*)\[(\S*)\]/, '\1[\2](\3)') end result end.join("\n") end
[ "def", "to_md", "# Usually ruby is extremely readable, but I think \"-1\" means \"give me all the ", "# trailing blank lines\" is surprisingly opaque. That's what the -1 does...", "lines", "=", "@text", ".", "split", "(", "\"\\n\"", ",", "-", "1", ")", "lines", ".", "collect", "do", "|", "line", "|", "result", "=", "line", "# Leave lines that start with 4 spaces alone. These are code blocks and", "# should pass through unchanged.", "unless", "result", "=~", "/", "\\s", "/", "# Convert headers", "result", ".", "sub!", "(", "/", "/", ")", "{", "|", "s", "|", "\"#\"", "*", "s", ".", "length", "}", "unless", "result", "=~", "/", "/", "# Convert strong to have two stars", "# The matching pair of stars should start with a single star that is either at", "# the beginning of the line or not following a backslash, have at least one", "# non-star and non-backslash in between, then end in one star", "result", ".", "gsub!", "(", "/", "\\A", "\\\\", "\\*", "\\*", "\\*", "\\*", "\\\\", "\\*", "/", ",", "'\\1**\\2**'", ")", "# Convert inline code spans to use backticks", "result", ".", "gsub!", "(", "/", "\\A", "\\\\", "\\+", "\\+", "\\+", "/", ",", "'\\1`\\2`'", ")", "# Convert bare http:, mailto: and ftp: links", "result", ".", "gsub!", "(", "/", "\\A", "\\s", "\\S", "/", ",", "'\\1[\\2\\3](\\2\\3)'", ")", "# Convert bare www to an http: link", "result", ".", "gsub!", "(", "/", "\\A", "\\s", "\\.", "\\S", "/", ",", "'\\1[www.\\2](http://www.\\2)'", ")", "# Convert link: links to refer to local files", "result", ".", "gsub!", "(", "/", "\\A", "\\s", "\\S", "/", ",", "'\\1[\\2](\\2)'", ")", "# Convert multi word labels surrounded by {} with a url", "result", ".", "gsub!", "(", "/", "\\{", "\\}", "\\}", "\\[", "\\S", "\\]", "/", ",", "'[\\1](\\2)'", ")", "# Convert one word labels with a url", "result", ".", "gsub!", "(", "/", "\\A", "\\s", "\\{", "\\s", "\\S", "\\[", "\\S", "\\]", "/", ",", "'\\1[\\2](\\3)'", ")", "end", "result", "end", ".", "join", "(", "\"\\n\"", ")", "end" ]
The initializer takes an optional text, which is the document to be converted from rdoc style to markdown. Convert the existing document to markdown. The result is returned as a String.
[ "The", "initializer", "takes", "an", "optional", "text", "which", "is", "the", "document", "to", "be", "converted", "from", "rdoc", "style", "to", "markdown", ".", "Convert", "the", "existing", "document", "to", "markdown", ".", "The", "result", "is", "returned", "as", "a", "String", "." ]
5e32cc2de9e64140034a3fbb767ef52c8261ce06
https://github.com/kirkbowers/rdoc2md/blob/5e32cc2de9e64140034a3fbb767ef52c8261ce06/lib/rdoc2md.rb#L23-L65
7,569
gnumarcelo/campaigning
lib/campaigning/client.rb
Campaigning.Client.templates
def templates response = @@soap.getClientTemplates(:apiKey => @apiKey, :clientID => @clientID) templates = handle_response response.client_GetTemplatesResult templates.collect {|template| Template.new(template.templateID, template.name, template.previewURL, template.screenshotURL, :apiKey=> @apiKey)} end
ruby
def templates response = @@soap.getClientTemplates(:apiKey => @apiKey, :clientID => @clientID) templates = handle_response response.client_GetTemplatesResult templates.collect {|template| Template.new(template.templateID, template.name, template.previewURL, template.screenshotURL, :apiKey=> @apiKey)} end
[ "def", "templates", "response", "=", "@@soap", ".", "getClientTemplates", "(", ":apiKey", "=>", "@apiKey", ",", ":clientID", "=>", "@clientID", ")", "templates", "=", "handle_response", "response", ".", "client_GetTemplatesResult", "templates", ".", "collect", "{", "|", "template", "|", "Template", ".", "new", "(", "template", ".", "templateID", ",", "template", ".", "name", ",", "template", ".", "previewURL", ",", "template", ".", "screenshotURL", ",", ":apiKey", "=>", "@apiKey", ")", "}", "end" ]
Gets a list of all templates for a client. *Return*: *Success*: Upon a successful call, this method will return a collection of Campaigning::Template objects. *Error*: An Exception containing the cause of the error will be raised.
[ "Gets", "a", "list", "of", "all", "templates", "for", "a", "client", "." ]
f3d7da053b65cfa376269533183919dc890964fd
https://github.com/gnumarcelo/campaigning/blob/f3d7da053b65cfa376269533183919dc890964fd/lib/campaigning/client.rb#L24-L28
7,570
gnumarcelo/campaigning
lib/campaigning/client.rb
Campaigning.Client.lists
def lists response = @@soap.getClientLists(:apiKey => @apiKey, :clientID => @clientID) lists = handle_response response.client_GetListsResult lists.collect {|list| List.new(list.listID, list.name, :apiKey=> @apiKey)} end
ruby
def lists response = @@soap.getClientLists(:apiKey => @apiKey, :clientID => @clientID) lists = handle_response response.client_GetListsResult lists.collect {|list| List.new(list.listID, list.name, :apiKey=> @apiKey)} end
[ "def", "lists", "response", "=", "@@soap", ".", "getClientLists", "(", ":apiKey", "=>", "@apiKey", ",", ":clientID", "=>", "@clientID", ")", "lists", "=", "handle_response", "response", ".", "client_GetListsResult", "lists", ".", "collect", "{", "|", "list", "|", "List", ".", "new", "(", "list", ".", "listID", ",", "list", ".", "name", ",", ":apiKey", "=>", "@apiKey", ")", "}", "end" ]
Gets a list of all subscriber lists for a client. *Return*: *Success*: Upon a successful call, this method will return a collection of Campaigning::List objects. *Error*: An Exception containing the cause of the error will be raised.
[ "Gets", "a", "list", "of", "all", "subscriber", "lists", "for", "a", "client", "." ]
f3d7da053b65cfa376269533183919dc890964fd
https://github.com/gnumarcelo/campaigning/blob/f3d7da053b65cfa376269533183919dc890964fd/lib/campaigning/client.rb#L38-L42
7,571
gnumarcelo/campaigning
lib/campaigning/client.rb
Campaigning.Client.campaigns
def campaigns response = @@soap.getClientCampaigns(:apiKey => @apiKey, :clientID => @clientID ) campaign_list = handle_response response.client_GetCampaignsResult campaign_list.collect do |campaign| Campaign.new(campaign.campaignID, campaign.subject, campaign.name, campaign.sentDate, campaign.totalRecipients, :apiKey=> @apiKey) end end
ruby
def campaigns response = @@soap.getClientCampaigns(:apiKey => @apiKey, :clientID => @clientID ) campaign_list = handle_response response.client_GetCampaignsResult campaign_list.collect do |campaign| Campaign.new(campaign.campaignID, campaign.subject, campaign.name, campaign.sentDate, campaign.totalRecipients, :apiKey=> @apiKey) end end
[ "def", "campaigns", "response", "=", "@@soap", ".", "getClientCampaigns", "(", ":apiKey", "=>", "@apiKey", ",", ":clientID", "=>", "@clientID", ")", "campaign_list", "=", "handle_response", "response", ".", "client_GetCampaignsResult", "campaign_list", ".", "collect", "do", "|", "campaign", "|", "Campaign", ".", "new", "(", "campaign", ".", "campaignID", ",", "campaign", ".", "subject", ",", "campaign", ".", "name", ",", "campaign", ".", "sentDate", ",", "campaign", ".", "totalRecipients", ",", ":apiKey", "=>", "@apiKey", ")", "end", "end" ]
Gets a list of all campaigns that have been sent for a client. *Return*: *Success*: Upon a successful call, this method will return a collection of Campaigning::Campaign objects. *Error*: An Exception containing the cause of the error will be raised.
[ "Gets", "a", "list", "of", "all", "campaigns", "that", "have", "been", "sent", "for", "a", "client", "." ]
f3d7da053b65cfa376269533183919dc890964fd
https://github.com/gnumarcelo/campaigning/blob/f3d7da053b65cfa376269533183919dc890964fd/lib/campaigning/client.rb#L195-L201
7,572
gnumarcelo/campaigning
lib/campaigning/client.rb
Campaigning.Client.update_access_and_billing!
def update_access_and_billing!(params) response = @@soap.updateClientAccessAndBilling( :apiKey => @apiKey, :clientID => @clientID, :accessLevel => params[:accessLevel], :username => params.fetch(:username, ""), :password => params.fetch(:password, ""), :billingType => params.fetch(:billingType, ""), :currency => params.fetch(:currency, ""), :deliveryFee => params.fetch(:deliveryFee, ""), :costPerRecipient => params.fetch(:costPerRecipient, ""), :designAndSpamTestFee => params.fetch(:designAndSpamTestFee, "") ) handle_response response.client_UpdateAccessAndBillingResult end
ruby
def update_access_and_billing!(params) response = @@soap.updateClientAccessAndBilling( :apiKey => @apiKey, :clientID => @clientID, :accessLevel => params[:accessLevel], :username => params.fetch(:username, ""), :password => params.fetch(:password, ""), :billingType => params.fetch(:billingType, ""), :currency => params.fetch(:currency, ""), :deliveryFee => params.fetch(:deliveryFee, ""), :costPerRecipient => params.fetch(:costPerRecipient, ""), :designAndSpamTestFee => params.fetch(:designAndSpamTestFee, "") ) handle_response response.client_UpdateAccessAndBillingResult end
[ "def", "update_access_and_billing!", "(", "params", ")", "response", "=", "@@soap", ".", "updateClientAccessAndBilling", "(", ":apiKey", "=>", "@apiKey", ",", ":clientID", "=>", "@clientID", ",", ":accessLevel", "=>", "params", "[", ":accessLevel", "]", ",", ":username", "=>", "params", ".", "fetch", "(", ":username", ",", "\"\"", ")", ",", ":password", "=>", "params", ".", "fetch", "(", ":password", ",", "\"\"", ")", ",", ":billingType", "=>", "params", ".", "fetch", "(", ":billingType", ",", "\"\"", ")", ",", ":currency", "=>", "params", ".", "fetch", "(", ":currency", ",", "\"\"", ")", ",", ":deliveryFee", "=>", "params", ".", "fetch", "(", ":deliveryFee", ",", "\"\"", ")", ",", ":costPerRecipient", "=>", "params", ".", "fetch", "(", ":costPerRecipient", ",", "\"\"", ")", ",", ":designAndSpamTestFee", "=>", "params", ".", "fetch", "(", ":designAndSpamTestFee", ",", "\"\"", ")", ")", "handle_response", "response", ".", "client_UpdateAccessAndBillingResult", "end" ]
Update the access and billing settings of an existing client, leaving the basic details untouched. Here's a list of all the parameters you'll need to pass to the Campaigning::Client#update_access_and_billing! method. Only the :+access_level+ parameter is required for all calls. The relevance and necessity of the other parameters depends on the chosen AccessLevel (and BillingType), and will be fully described along with each parameter. Available _params_ argument are: * :accessLevel - An integer describing the client's ability to access different areas of the application. Influences the significance and requirements of the following parameters. See http://www.campaignmonitor.com/api/method/client-updateaccessandbilling/#accesslevels for a full description of available levels. * :username - Client login username. Not required and ignored if AccessLevel is set to 0. * :password - Client login password. Not required and ignored if AccessLevel is set to 0. * :billingType - Client billing type, only required if :accessLevel is set to allow the client to create and send campaigns * :currency - Billing currency for this client, only required if :billingType is set to either ClientPaysAtStandardRate or ClientPaysWithMarkup. See full details: http://www.campaignmonitor.com/api/method/client-updateaccessandbilling/#currencies. * :deliveryFee - Flat rate delivery fee to be charged to the client for each campaign sent, expressed in the chosen currency's major unit, but without the currency symbol (for example, sending "6.5" means "$6.50" if USD is used). Only required if BillingType is set to ClientPaysWithMarkup, in which case it should be at least equal to the standard rate. Further detail is available at http://help.campaignmonitor.com/topic.aspx?t=118. * :costPerRecipient - Additional cost added to the campaign for each email address the campaign is sent to, expressed in the chosen currency's minor unit (for example, sending "1.5" means 1.5 cents per email address if USD is used). Only required if BillingType is set to ClientPaysWithMarkup, in which case it should be at least equal to the standard cost/recipient rate. Further detail is available at http://help.campaignmonitor.com/topic.aspx?t=118. * :designAndSpamTestFee - Expressed in the chosen currency's major unit (for example, sending "10" means "$10" if USD is used). Only required if BillingType is set to ClientPaysWithMarkup and client has access to design and spam tests, in which case the fee should be equal to or higher than the standard rate (identical to the standard DeliveryFee for that currency). Please note that for reasons of security there is no way to set a client's credit card details via the API. It will have to be done in the application. *Return*: *Success*: Upon a successful call, this method will return a Campaigning::Result object wich consists of a +code+ and +message+ fields containing a successful message. *Error*: An Exception containing the cause of the error will be raised.
[ "Update", "the", "access", "and", "billing", "settings", "of", "an", "existing", "client", "leaving", "the", "basic", "details", "untouched", "." ]
f3d7da053b65cfa376269533183919dc890964fd
https://github.com/gnumarcelo/campaigning/blob/f3d7da053b65cfa376269533183919dc890964fd/lib/campaigning/client.rb#L286-L300
7,573
gnumarcelo/campaigning
lib/campaigning/client.rb
Campaigning.Client.update_basics!
def update_basics!(params) response = @@soap.updateClientBasics( :apiKey => @apiKey, :clientID => @clientID, :companyName => params[:companyName], :contactName => params[:contactName], :emailAddress => params[:emailAddress], :country => params[:country], :timezone => params[:timezone] ) handle_response response.client_UpdateBasicsResult end
ruby
def update_basics!(params) response = @@soap.updateClientBasics( :apiKey => @apiKey, :clientID => @clientID, :companyName => params[:companyName], :contactName => params[:contactName], :emailAddress => params[:emailAddress], :country => params[:country], :timezone => params[:timezone] ) handle_response response.client_UpdateBasicsResult end
[ "def", "update_basics!", "(", "params", ")", "response", "=", "@@soap", ".", "updateClientBasics", "(", ":apiKey", "=>", "@apiKey", ",", ":clientID", "=>", "@clientID", ",", ":companyName", "=>", "params", "[", ":companyName", "]", ",", ":contactName", "=>", "params", "[", ":contactName", "]", ",", ":emailAddress", "=>", "params", "[", ":emailAddress", "]", ",", ":country", "=>", "params", "[", ":country", "]", ",", ":timezone", "=>", "params", "[", ":timezone", "]", ")", "handle_response", "response", ".", "client_UpdateBasicsResult", "end" ]
Updates the basic details of an existing client. If you wish to change only some details, the others must be included as they currently are. Please note that the client's existing access and billing details will remain unchanged by a call to this method. Available _params_ argument are: * :companyName - The client company name. * :contactName - The personal name of the principle contact for this client. * :emailAddress - An email address to which this client will be sent application-related emails. * :country - This client's country. * :timezone - Client timezone for tracking and reporting data. Valid timezone strings are obtainable by means of the API procedure Campaigning.timezones. *Return*: *Success*: Upon a successful call, this method will return a Campaigning::Result object wich consists of a +code+ and +message+ fields containing a successful message. *Error*: An Exception containing the cause of the error will be raised.
[ "Updates", "the", "basic", "details", "of", "an", "existing", "client", ".", "If", "you", "wish", "to", "change", "only", "some", "details", "the", "others", "must", "be", "included", "as", "they", "currently", "are", ".", "Please", "note", "that", "the", "client", "s", "existing", "access", "and", "billing", "details", "will", "remain", "unchanged", "by", "a", "call", "to", "this", "method", "." ]
f3d7da053b65cfa376269533183919dc890964fd
https://github.com/gnumarcelo/campaigning/blob/f3d7da053b65cfa376269533183919dc890964fd/lib/campaigning/client.rb#L320-L331
7,574
bilus/akasha
lib/akasha/repository.rb
Akasha.Repository.save_aggregate
def save_aggregate(aggregate, concurrency: :none) changeset = aggregate.changeset events = changeset.events.map { |event| event.with_metadata(namespace: @namespace) } revision = aggregate.revision if concurrency == :optimistic stream(aggregate.class, changeset.aggregate_id).write_events(events, revision: revision) notify_subscribers(changeset.aggregate_id, events) end
ruby
def save_aggregate(aggregate, concurrency: :none) changeset = aggregate.changeset events = changeset.events.map { |event| event.with_metadata(namespace: @namespace) } revision = aggregate.revision if concurrency == :optimistic stream(aggregate.class, changeset.aggregate_id).write_events(events, revision: revision) notify_subscribers(changeset.aggregate_id, events) end
[ "def", "save_aggregate", "(", "aggregate", ",", "concurrency", ":", ":none", ")", "changeset", "=", "aggregate", ".", "changeset", "events", "=", "changeset", ".", "events", ".", "map", "{", "|", "event", "|", "event", ".", "with_metadata", "(", "namespace", ":", "@namespace", ")", "}", "revision", "=", "aggregate", ".", "revision", "if", "concurrency", "==", ":optimistic", "stream", "(", "aggregate", ".", "class", ",", "changeset", ".", "aggregate_id", ")", ".", "write_events", "(", "events", ",", "revision", ":", "revision", ")", "notify_subscribers", "(", "changeset", ".", "aggregate_id", ",", "events", ")", "end" ]
Saves an aggregate to the repository, appending events to the corresponding stream.
[ "Saves", "an", "aggregate", "to", "the", "repository", "appending", "events", "to", "the", "corresponding", "stream", "." ]
5fadefc249f520ae909b762956ac23a6f916b021
https://github.com/bilus/akasha/blob/5fadefc249f520ae909b762956ac23a6f916b021/lib/akasha/repository.rb#L35-L41
7,575
xinge/gcm_helper
lib/gcm_helper/sender.rb
GcmHelper.Sender.update_status
def update_status(unsent_reg_ids, all_results, multicast_result) results = multicast_result.results raise RuntimeError, "Internal error: sizes do not match. currentResults: #{results}; unsentRegIds: #{unsent_reg_ids}" unless results.size==unsent_reg_ids.size new_unsent_reg_ids = [] unsent_reg_ids.each_with_index {|reg_id, index| result = results[index] all_results[reg_id]= result new_unsent_reg_ids << reg_id unless (result.error_code.nil? || result.error_code.eql?(ERROR_UNAVAILABLE)) } new_unsent_reg_ids end
ruby
def update_status(unsent_reg_ids, all_results, multicast_result) results = multicast_result.results raise RuntimeError, "Internal error: sizes do not match. currentResults: #{results}; unsentRegIds: #{unsent_reg_ids}" unless results.size==unsent_reg_ids.size new_unsent_reg_ids = [] unsent_reg_ids.each_with_index {|reg_id, index| result = results[index] all_results[reg_id]= result new_unsent_reg_ids << reg_id unless (result.error_code.nil? || result.error_code.eql?(ERROR_UNAVAILABLE)) } new_unsent_reg_ids end
[ "def", "update_status", "(", "unsent_reg_ids", ",", "all_results", ",", "multicast_result", ")", "results", "=", "multicast_result", ".", "results", "raise", "RuntimeError", ",", "\"Internal error: sizes do not match. currentResults: #{results}; unsentRegIds: #{unsent_reg_ids}\"", "unless", "results", ".", "size", "==", "unsent_reg_ids", ".", "size", "new_unsent_reg_ids", "=", "[", "]", "unsent_reg_ids", ".", "each_with_index", "{", "|", "reg_id", ",", "index", "|", "result", "=", "results", "[", "index", "]", "all_results", "[", "reg_id", "]", "=", "result", "new_unsent_reg_ids", "<<", "reg_id", "unless", "(", "result", ".", "error_code", ".", "nil?", "||", "result", ".", "error_code", ".", "eql?", "(", "ERROR_UNAVAILABLE", ")", ")", "}", "new_unsent_reg_ids", "end" ]
Updates the status of the messages sent to devices and the list of devices that should be retried. @param [Array] unsent_reg_ids @param [Hash] all_results @param [GcmHelper::MulticastResult] multicast_result
[ "Updates", "the", "status", "of", "the", "messages", "sent", "to", "devices", "and", "the", "list", "of", "devices", "that", "should", "be", "retried", "." ]
f998f0e6bde0147613a9cb2ff2f62363adf2b227
https://github.com/xinge/gcm_helper/blob/f998f0e6bde0147613a9cb2ff2f62363adf2b227/lib/gcm_helper/sender.rb#L218-L228
7,576
nigelr/selections
lib/selections/form_builder_extensions.rb
Selections.FormBuilderExtensions.selections
def selections(field, options = {}, html_options = {}) SelectionTag.new(self, object, field, options, html_options).select_tag end
ruby
def selections(field, options = {}, html_options = {}) SelectionTag.new(self, object, field, options, html_options).select_tag end
[ "def", "selections", "(", "field", ",", "options", "=", "{", "}", ",", "html_options", "=", "{", "}", ")", "SelectionTag", ".", "new", "(", "self", ",", "object", ",", "field", ",", "options", ",", "html_options", ")", ".", "select_tag", "end" ]
Create a select list based on the field name finding items within Selection. Example form_for(@ticket) do |f| f.select("priority") Uses priority_id from the ticket table and creates options list based on items in Selection table with a system_code of either priority or ticket_priority options = {} and html_options = {} suport all the keys as the rails library select_tag does. options * +system_code+ - Overrides the automatic system_code name based on the fieldname and looks up the list of items in Selection
[ "Create", "a", "select", "list", "based", "on", "the", "field", "name", "finding", "items", "within", "Selection", "." ]
f4702869ffaf11fbcdc8fdad4c0e91b3d0a1ce45
https://github.com/nigelr/selections/blob/f4702869ffaf11fbcdc8fdad4c0e91b3d0a1ce45/lib/selections/form_builder_extensions.rb#L17-L19
7,577
nigelr/selections
lib/selections/form_builder_extensions.rb
Selections.FormBuilderExtensions.radios
def radios(field, options = {}) html_options = options.clone html_options.delete_if {|key, value| key == :system_code} SelectionTag.new(self, object, field, options, html_options).radio_tag end
ruby
def radios(field, options = {}) html_options = options.clone html_options.delete_if {|key, value| key == :system_code} SelectionTag.new(self, object, field, options, html_options).radio_tag end
[ "def", "radios", "(", "field", ",", "options", "=", "{", "}", ")", "html_options", "=", "options", ".", "clone", "html_options", ".", "delete_if", "{", "|", "key", ",", "value", "|", "key", "==", ":system_code", "}", "SelectionTag", ".", "new", "(", "self", ",", "object", ",", "field", ",", "options", ",", "html_options", ")", ".", "radio_tag", "end" ]
Build a radio button list based field name finding items within Selection Example form_for(@ticket) do |f| f.select :priority options * +system_code+ - Overrides the automatic system_code name based on the fieldname and looks up the list of items in Selection
[ "Build", "a", "radio", "button", "list", "based", "field", "name", "finding", "items", "within", "Selection" ]
f4702869ffaf11fbcdc8fdad4c0e91b3d0a1ce45
https://github.com/nigelr/selections/blob/f4702869ffaf11fbcdc8fdad4c0e91b3d0a1ce45/lib/selections/form_builder_extensions.rb#L29-L33
7,578
jarhart/rattler
lib/rattler/util/node.rb
Rattler::Util.Node.method_missing
def method_missing(symbol, *args) (args.empty? and attrs.has_key?(symbol)) ? attrs[symbol] : super end
ruby
def method_missing(symbol, *args) (args.empty? and attrs.has_key?(symbol)) ? attrs[symbol] : super end
[ "def", "method_missing", "(", "symbol", ",", "*", "args", ")", "(", "args", ".", "empty?", "and", "attrs", ".", "has_key?", "(", "symbol", ")", ")", "?", "attrs", "[", "symbol", "]", ":", "super", "end" ]
Return +true+ if the node is equal to +other+. Normally this means +other+ is an instance of the same class or a subclass and has equal children and attributes. @return [Boolean] +true+ if the node is equal to +other+ Return +true+ if the node has the same value as +other+, i.e. +other+ is an instance of the same class and has equal children and attributes. @return [Boolean] +true+ the node has the same value as +other+ Allow attributes to be accessed as methods.
[ "Return", "+", "true", "+", "if", "the", "node", "is", "equal", "to", "+", "other", "+", ".", "Normally", "this", "means", "+", "other", "+", "is", "an", "instance", "of", "the", "same", "class", "or", "a", "subclass", "and", "has", "equal", "children", "and", "attributes", "." ]
8b4efde2a05e9e790955bb635d4a1a9615893719
https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/util/node.rb#L166-L168
7,579
jmpage/dirty_associations
lib/dirty_associations.rb
DirtyAssociations.ClassMethods.monitor_association_changes
def monitor_association_changes(association) define_method "#{association}=" do |value| attribute_will_change!(association.to_s) if _association_will_change?(association, value) super(value) end ids = "#{association.to_s.singularize}_ids" define_method "#{ids}=" do |value| attribute_will_change!(association.to_s) if _ids_will_change?(ids, value) super(value) end define_method "#{association}_attributes=" do |value| attribute_will_change!(association.to_s) if _nested_attributes_will_change?(value) super(value) end [association, ids].each do |name| define_method "#{name}_change" do changes[name] end define_method "#{name}_changed?" do changes.has_key?(association.to_s) end define_method "#{name}_previously_changed?" do previous_changes.has_key?(association.to_s) end end end
ruby
def monitor_association_changes(association) define_method "#{association}=" do |value| attribute_will_change!(association.to_s) if _association_will_change?(association, value) super(value) end ids = "#{association.to_s.singularize}_ids" define_method "#{ids}=" do |value| attribute_will_change!(association.to_s) if _ids_will_change?(ids, value) super(value) end define_method "#{association}_attributes=" do |value| attribute_will_change!(association.to_s) if _nested_attributes_will_change?(value) super(value) end [association, ids].each do |name| define_method "#{name}_change" do changes[name] end define_method "#{name}_changed?" do changes.has_key?(association.to_s) end define_method "#{name}_previously_changed?" do previous_changes.has_key?(association.to_s) end end end
[ "def", "monitor_association_changes", "(", "association", ")", "define_method", "\"#{association}=\"", "do", "|", "value", "|", "attribute_will_change!", "(", "association", ".", "to_s", ")", "if", "_association_will_change?", "(", "association", ",", "value", ")", "super", "(", "value", ")", "end", "ids", "=", "\"#{association.to_s.singularize}_ids\"", "define_method", "\"#{ids}=\"", "do", "|", "value", "|", "attribute_will_change!", "(", "association", ".", "to_s", ")", "if", "_ids_will_change?", "(", "ids", ",", "value", ")", "super", "(", "value", ")", "end", "define_method", "\"#{association}_attributes=\"", "do", "|", "value", "|", "attribute_will_change!", "(", "association", ".", "to_s", ")", "if", "_nested_attributes_will_change?", "(", "value", ")", "super", "(", "value", ")", "end", "[", "association", ",", "ids", "]", ".", "each", "do", "|", "name", "|", "define_method", "\"#{name}_change\"", "do", "changes", "[", "name", "]", "end", "define_method", "\"#{name}_changed?\"", "do", "changes", ".", "has_key?", "(", "association", ".", "to_s", ")", "end", "define_method", "\"#{name}_previously_changed?\"", "do", "previous_changes", ".", "has_key?", "(", "association", ".", "to_s", ")", "end", "end", "end" ]
Creates methods that allows an +association+ to be monitored. The +association+ parameter should be a string or symbol representing the name of an association.
[ "Creates", "methods", "that", "allows", "an", "+", "association", "+", "to", "be", "monitored", "." ]
33e9cb36e93632d3fee69277063eb42f56c9b7bf
https://github.com/jmpage/dirty_associations/blob/33e9cb36e93632d3fee69277063eb42f56c9b7bf/lib/dirty_associations.rb#L15-L46
7,580
jrochkind/borrow_direct
lib/borrow_direct/encryption.rb
BorrowDirect.Encryption.encode_with_ts
def encode_with_ts(value) # Not sure if this object is thread-safe, so we re-create # each time. public_key = OpenSSL::PKey::RSA.new(self.public_key_str) payload = "#{value}|#{self.now_timestamp}" return Base64.encode64(public_key.public_encrypt(payload)) end
ruby
def encode_with_ts(value) # Not sure if this object is thread-safe, so we re-create # each time. public_key = OpenSSL::PKey::RSA.new(self.public_key_str) payload = "#{value}|#{self.now_timestamp}" return Base64.encode64(public_key.public_encrypt(payload)) end
[ "def", "encode_with_ts", "(", "value", ")", "# Not sure if this object is thread-safe, so we re-create", "# each time. ", "public_key", "=", "OpenSSL", "::", "PKey", "::", "RSA", ".", "new", "(", "self", ".", "public_key_str", ")", "payload", "=", "\"#{value}|#{self.now_timestamp}\"", "return", "Base64", ".", "encode64", "(", "public_key", ".", "public_encrypt", "(", "payload", ")", ")", "end" ]
Will add on timestamp according to Relais protocol, encrypt, and Base64-encode, all per Relais protocol.
[ "Will", "add", "on", "timestamp", "according", "to", "Relais", "protocol", "encrypt", "and", "Base64", "-", "encode", "all", "per", "Relais", "protocol", "." ]
f2f53760e15d742a5c5584dd641f20dea315f99f
https://github.com/jrochkind/borrow_direct/blob/f2f53760e15d742a5c5584dd641f20dea315f99f/lib/borrow_direct/encryption.rb#L18-L27
7,581
elifoster/weatheruby
lib/weather/actions.rb
Weather.Actions.moon_phase
def moon_phase(location) response = get('astronomy', location) { age: response['moon_phase']['ageOfMoon'].to_i, illumination: response['moon_phase']['percentIlluminated'].to_i } end
ruby
def moon_phase(location) response = get('astronomy', location) { age: response['moon_phase']['ageOfMoon'].to_i, illumination: response['moon_phase']['percentIlluminated'].to_i } end
[ "def", "moon_phase", "(", "location", ")", "response", "=", "get", "(", "'astronomy'", ",", "location", ")", "{", "age", ":", "response", "[", "'moon_phase'", "]", "[", "'ageOfMoon'", "]", ".", "to_i", ",", "illumination", ":", "response", "[", "'moon_phase'", "]", "[", "'percentIlluminated'", "]", ".", "to_i", "}", "end" ]
Gets the current moon phase of the location. @param location [String] The place to get the phase for. @return [Hash<Symbol, Integer>] A hash of two integers for the moon phase information. The `:age` key in the hash contains the moon's age in days, and the `:illumination` key contains the percentage of how illuminated it is.
[ "Gets", "the", "current", "moon", "phase", "of", "the", "location", "." ]
4d97db082448765b67ef5112c89346e502a74858
https://github.com/elifoster/weatheruby/blob/4d97db082448765b67ef5112c89346e502a74858/lib/weather/actions.rb#L39-L45
7,582
elifoster/weatheruby
lib/weather/actions.rb
Weather.Actions.sun_info
def sun_info(location) response = get('astronomy', location) { rise: { hour: response['moon_phase']['sunrise']['hour'].to_i, minute: response['moon_phase']['sunrise']['minute'].to_i }, set: { hour: response['moon_phase']['sunset']['hour'].to_i, minute: response['moon_phase']['sunset']['minute'].to_i } } end
ruby
def sun_info(location) response = get('astronomy', location) { rise: { hour: response['moon_phase']['sunrise']['hour'].to_i, minute: response['moon_phase']['sunrise']['minute'].to_i }, set: { hour: response['moon_phase']['sunset']['hour'].to_i, minute: response['moon_phase']['sunset']['minute'].to_i } } end
[ "def", "sun_info", "(", "location", ")", "response", "=", "get", "(", "'astronomy'", ",", "location", ")", "{", "rise", ":", "{", "hour", ":", "response", "[", "'moon_phase'", "]", "[", "'sunrise'", "]", "[", "'hour'", "]", ".", "to_i", ",", "minute", ":", "response", "[", "'moon_phase'", "]", "[", "'sunrise'", "]", "[", "'minute'", "]", ".", "to_i", "}", ",", "set", ":", "{", "hour", ":", "response", "[", "'moon_phase'", "]", "[", "'sunset'", "]", "[", "'hour'", "]", ".", "to_i", ",", "minute", ":", "response", "[", "'moon_phase'", "]", "[", "'sunset'", "]", "[", "'minute'", "]", ".", "to_i", "}", "}", "end" ]
Gets sunrise and sunset information for the current day at the current location. @param location [String] The place to get the info for. @return [Hash<Symbol, Hash<Symbol, Integer>>] A hash containing two hashes at keys :rise and :set for sunrise and sunset information respectively. They each contain an :hour key and a :minute key which point to the hour and minute that the sun will rise or set.
[ "Gets", "sunrise", "and", "sunset", "information", "for", "the", "current", "day", "at", "the", "current", "location", "." ]
4d97db082448765b67ef5112c89346e502a74858
https://github.com/elifoster/weatheruby/blob/4d97db082448765b67ef5112c89346e502a74858/lib/weather/actions.rb#L52-L64
7,583
elifoster/weatheruby
lib/weather/actions.rb
Weather.Actions.parse_simple_forecast
def parse_simple_forecast(response) ret = {} response['forecast']['txt_forecast']['forecastday'].each do |f| ret[f['period']] = { weekday_name: f['title'], text: f['fcttext'], text_metric: f['fcttext_metric'], image_url: f['icon_url'] } end ret end
ruby
def parse_simple_forecast(response) ret = {} response['forecast']['txt_forecast']['forecastday'].each do |f| ret[f['period']] = { weekday_name: f['title'], text: f['fcttext'], text_metric: f['fcttext_metric'], image_url: f['icon_url'] } end ret end
[ "def", "parse_simple_forecast", "(", "response", ")", "ret", "=", "{", "}", "response", "[", "'forecast'", "]", "[", "'txt_forecast'", "]", "[", "'forecastday'", "]", ".", "each", "do", "|", "f", "|", "ret", "[", "f", "[", "'period'", "]", "]", "=", "{", "weekday_name", ":", "f", "[", "'title'", "]", ",", "text", ":", "f", "[", "'fcttext'", "]", ",", "text_metric", ":", "f", "[", "'fcttext_metric'", "]", ",", "image_url", ":", "f", "[", "'icon_url'", "]", "}", "end", "ret", "end" ]
Parses the simple forecast information.
[ "Parses", "the", "simple", "forecast", "information", "." ]
4d97db082448765b67ef5112c89346e502a74858
https://github.com/elifoster/weatheruby/blob/4d97db082448765b67ef5112c89346e502a74858/lib/weather/actions.rb#L257-L270
7,584
elifoster/weatheruby
lib/weather/actions.rb
Weather.Actions.parse_complex_forecast
def parse_complex_forecast(response) ret = {} response['forecast']['simpleforecast']['forecastday'].each do |f| date = f['date'] ret[f['period'] - 1] = { date: DateTime.new(date['year'], date['month'], date['day'], date['hour'], date['min'].to_i, date['sec'], date['tz_short']), weekday_name: date['weekday'], high_f: f['high']['fahrenheit'].to_i, high_c: f['high']['celsius'].to_i, low_f: f['low']['fahrenheit'].to_i, low_c: f['low']['celsius'].to_i, conditions: f['conditions'].to_i, image_url: f['icon_url'], snow: { snow_total_in: f['snow_allday']['in'], snow_total_cm: f['snow_allday']['cm'], snow_night_in: f['snow_night']['in'], snow_night_cm: f['snow_night']['cm'], snow_day_in: f['snow_day']['in'], snow_day_cm: f['snow_day']['cm'] }, quantative_precipitation: { qpf_total_in: f['qpf_allday']['in'], qpf_total_cm: f['qpf_allday']['cm'], qpf_night_in: f['qpf_night']['in'], qpf_night_cm: f['qpf_night']['cm'], qpf_day_in: f['qpf_day']['in'], qpf_day_cm: f['qpf_day']['cm'] }, wind: { average_mph: f['avewind']['mph'], average_kph: f['avewind']['kph'], average_dir: f['avewind']['dir'], average_temp: f['avewind']['degrees'], max_mph: f['maxwind']['mph'], max_kph: f['maxwind']['kph'], max_dir: f['maxwind']['dir'], max_temp: f['maxwind']['degrees'] } } end ret end
ruby
def parse_complex_forecast(response) ret = {} response['forecast']['simpleforecast']['forecastday'].each do |f| date = f['date'] ret[f['period'] - 1] = { date: DateTime.new(date['year'], date['month'], date['day'], date['hour'], date['min'].to_i, date['sec'], date['tz_short']), weekday_name: date['weekday'], high_f: f['high']['fahrenheit'].to_i, high_c: f['high']['celsius'].to_i, low_f: f['low']['fahrenheit'].to_i, low_c: f['low']['celsius'].to_i, conditions: f['conditions'].to_i, image_url: f['icon_url'], snow: { snow_total_in: f['snow_allday']['in'], snow_total_cm: f['snow_allday']['cm'], snow_night_in: f['snow_night']['in'], snow_night_cm: f['snow_night']['cm'], snow_day_in: f['snow_day']['in'], snow_day_cm: f['snow_day']['cm'] }, quantative_precipitation: { qpf_total_in: f['qpf_allday']['in'], qpf_total_cm: f['qpf_allday']['cm'], qpf_night_in: f['qpf_night']['in'], qpf_night_cm: f['qpf_night']['cm'], qpf_day_in: f['qpf_day']['in'], qpf_day_cm: f['qpf_day']['cm'] }, wind: { average_mph: f['avewind']['mph'], average_kph: f['avewind']['kph'], average_dir: f['avewind']['dir'], average_temp: f['avewind']['degrees'], max_mph: f['maxwind']['mph'], max_kph: f['maxwind']['kph'], max_dir: f['maxwind']['dir'], max_temp: f['maxwind']['degrees'] } } end ret end
[ "def", "parse_complex_forecast", "(", "response", ")", "ret", "=", "{", "}", "response", "[", "'forecast'", "]", "[", "'simpleforecast'", "]", "[", "'forecastday'", "]", ".", "each", "do", "|", "f", "|", "date", "=", "f", "[", "'date'", "]", "ret", "[", "f", "[", "'period'", "]", "-", "1", "]", "=", "{", "date", ":", "DateTime", ".", "new", "(", "date", "[", "'year'", "]", ",", "date", "[", "'month'", "]", ",", "date", "[", "'day'", "]", ",", "date", "[", "'hour'", "]", ",", "date", "[", "'min'", "]", ".", "to_i", ",", "date", "[", "'sec'", "]", ",", "date", "[", "'tz_short'", "]", ")", ",", "weekday_name", ":", "date", "[", "'weekday'", "]", ",", "high_f", ":", "f", "[", "'high'", "]", "[", "'fahrenheit'", "]", ".", "to_i", ",", "high_c", ":", "f", "[", "'high'", "]", "[", "'celsius'", "]", ".", "to_i", ",", "low_f", ":", "f", "[", "'low'", "]", "[", "'fahrenheit'", "]", ".", "to_i", ",", "low_c", ":", "f", "[", "'low'", "]", "[", "'celsius'", "]", ".", "to_i", ",", "conditions", ":", "f", "[", "'conditions'", "]", ".", "to_i", ",", "image_url", ":", "f", "[", "'icon_url'", "]", ",", "snow", ":", "{", "snow_total_in", ":", "f", "[", "'snow_allday'", "]", "[", "'in'", "]", ",", "snow_total_cm", ":", "f", "[", "'snow_allday'", "]", "[", "'cm'", "]", ",", "snow_night_in", ":", "f", "[", "'snow_night'", "]", "[", "'in'", "]", ",", "snow_night_cm", ":", "f", "[", "'snow_night'", "]", "[", "'cm'", "]", ",", "snow_day_in", ":", "f", "[", "'snow_day'", "]", "[", "'in'", "]", ",", "snow_day_cm", ":", "f", "[", "'snow_day'", "]", "[", "'cm'", "]", "}", ",", "quantative_precipitation", ":", "{", "qpf_total_in", ":", "f", "[", "'qpf_allday'", "]", "[", "'in'", "]", ",", "qpf_total_cm", ":", "f", "[", "'qpf_allday'", "]", "[", "'cm'", "]", ",", "qpf_night_in", ":", "f", "[", "'qpf_night'", "]", "[", "'in'", "]", ",", "qpf_night_cm", ":", "f", "[", "'qpf_night'", "]", "[", "'cm'", "]", ",", "qpf_day_in", ":", "f", "[", "'qpf_day'", "]", "[", "'in'", "]", ",", "qpf_day_cm", ":", "f", "[", "'qpf_day'", "]", "[", "'cm'", "]", "}", ",", "wind", ":", "{", "average_mph", ":", "f", "[", "'avewind'", "]", "[", "'mph'", "]", ",", "average_kph", ":", "f", "[", "'avewind'", "]", "[", "'kph'", "]", ",", "average_dir", ":", "f", "[", "'avewind'", "]", "[", "'dir'", "]", ",", "average_temp", ":", "f", "[", "'avewind'", "]", "[", "'degrees'", "]", ",", "max_mph", ":", "f", "[", "'maxwind'", "]", "[", "'mph'", "]", ",", "max_kph", ":", "f", "[", "'maxwind'", "]", "[", "'kph'", "]", ",", "max_dir", ":", "f", "[", "'maxwind'", "]", "[", "'dir'", "]", ",", "max_temp", ":", "f", "[", "'maxwind'", "]", "[", "'degrees'", "]", "}", "}", "end", "ret", "end" ]
Parses the complex forecast information.
[ "Parses", "the", "complex", "forecast", "information", "." ]
4d97db082448765b67ef5112c89346e502a74858
https://github.com/elifoster/weatheruby/blob/4d97db082448765b67ef5112c89346e502a74858/lib/weather/actions.rb#L273-L317
7,585
wilson/revenant
lib/revenant/manager.rb
Revenant.Manager.reopen_io
def reopen_io(io, path, mode = nil) begin if mode io.reopen(path, mode) else io.reopen(path) end io.binmode rescue ::Exception end end
ruby
def reopen_io(io, path, mode = nil) begin if mode io.reopen(path, mode) else io.reopen(path) end io.binmode rescue ::Exception end end
[ "def", "reopen_io", "(", "io", ",", "path", ",", "mode", "=", "nil", ")", "begin", "if", "mode", "io", ".", "reopen", "(", "path", ",", "mode", ")", "else", "io", ".", "reopen", "(", "path", ")", "end", "io", ".", "binmode", "rescue", "::", "Exception", "end", "end" ]
Attempts to reopen an IO object.
[ "Attempts", "to", "reopen", "an", "IO", "object", "." ]
80fe65742de54ce0c5a8e6c56cea7003fe286746
https://github.com/wilson/revenant/blob/80fe65742de54ce0c5a8e6c56cea7003fe286746/lib/revenant/manager.rb#L49-L59
7,586
dlangevin/gxapi_rails
lib/gxapi/controller_methods.rb
Gxapi.ControllerMethods.gxapi_get_variant
def gxapi_get_variant(identifier, ivar_name = :variant) # handle override if params[ivar_name] val = Gxapi::Ostruct.new( value: { index: -1, experiment_id: nil, name: params[ivar_name] } ) else val = self.gxapi_base.get_variant(identifier) end return instance_variable_set("@#{ivar_name}", val) end
ruby
def gxapi_get_variant(identifier, ivar_name = :variant) # handle override if params[ivar_name] val = Gxapi::Ostruct.new( value: { index: -1, experiment_id: nil, name: params[ivar_name] } ) else val = self.gxapi_base.get_variant(identifier) end return instance_variable_set("@#{ivar_name}", val) end
[ "def", "gxapi_get_variant", "(", "identifier", ",", "ivar_name", "=", ":variant", ")", "# handle override", "if", "params", "[", "ivar_name", "]", "val", "=", "Gxapi", "::", "Ostruct", ".", "new", "(", "value", ":", "{", "index", ":", "-", "1", ",", "experiment_id", ":", "nil", ",", "name", ":", "params", "[", "ivar_name", "]", "}", ")", "else", "val", "=", "self", ".", "gxapi_base", ".", "get_variant", "(", "identifier", ")", "end", "return", "instance_variable_set", "(", "\"@#{ivar_name}\"", ",", "val", ")", "end" ]
Get the variant and set it as an instance variable, handling overriding by passing in the URL @param identifier [String, Hash] Name for the experiment or ID hash for the experiment @param ivar_name [String, Symbol] Name for the variable @example def my_action gxapi_get_variant("Name") end # OR def my_action gxapi_get_variant(id: 'id_from_google') end @return [Celluloid::Future, Gxapi::Ostruct] Variant value
[ "Get", "the", "variant", "and", "set", "it", "as", "an", "instance", "variable", "handling", "overriding", "by", "passing", "in", "the", "URL" ]
21361227f0c70118b38f7fa372a18c0ae7aab810
https://github.com/dlangevin/gxapi_rails/blob/21361227f0c70118b38f7fa372a18c0ae7aab810/lib/gxapi/controller_methods.rb#L25-L39
7,587
rack-webprofiler/rack-webprofiler
lib/rack/web_profiler.rb
Rack.WebProfiler.process
def process(request, body, status, headers, exception = nil) request.env[ENV_RUNTIME] = Time.now.to_f - request.env[ENV_RUNTIME_START] request.env[ENV_EXCEPTION] = nil if !exception.nil? request.env[ENV_EXCEPTION] = exception WebProfiler::Engine.process_exception(request).finish else WebProfiler::Engine.process(request, body, status, headers).finish end end
ruby
def process(request, body, status, headers, exception = nil) request.env[ENV_RUNTIME] = Time.now.to_f - request.env[ENV_RUNTIME_START] request.env[ENV_EXCEPTION] = nil if !exception.nil? request.env[ENV_EXCEPTION] = exception WebProfiler::Engine.process_exception(request).finish else WebProfiler::Engine.process(request, body, status, headers).finish end end
[ "def", "process", "(", "request", ",", "body", ",", "status", ",", "headers", ",", "exception", "=", "nil", ")", "request", ".", "env", "[", "ENV_RUNTIME", "]", "=", "Time", ".", "now", ".", "to_f", "-", "request", ".", "env", "[", "ENV_RUNTIME_START", "]", "request", ".", "env", "[", "ENV_EXCEPTION", "]", "=", "nil", "if", "!", "exception", ".", "nil?", "request", ".", "env", "[", "ENV_EXCEPTION", "]", "=", "exception", "WebProfiler", "::", "Engine", ".", "process_exception", "(", "request", ")", ".", "finish", "else", "WebProfiler", "::", "Engine", ".", "process", "(", "request", ",", "body", ",", "status", ",", "headers", ")", ".", "finish", "end", "end" ]
Process the request. @param request [Rack::WebProfiler::Request] @param body @param status [Integer] @param headers [Hash] @param exception [Exception, nil] @return [Rack::Response]
[ "Process", "the", "request", "." ]
bdb411fbb41eeddf612bbde91301ff94b3853a12
https://github.com/rack-webprofiler/rack-webprofiler/blob/bdb411fbb41eeddf612bbde91301ff94b3853a12/lib/rack/web_profiler.rb#L134-L144
7,588
strong-code/pirata
lib/pirata/search.rb
Pirata.Search.search
def search(page = 0) #build URL ex: http://thepiratebay.se/search/cats/0/99/0 url = Pirata.config[:base_url] + "/search/#{URI.escape(@query)}" + "/#{page.to_s}" + "/#{@sort_type}" + "/#{@category}" html = Pirata::Search.parse_html(url) Pirata::Search::parse_search_page(html, self) end
ruby
def search(page = 0) #build URL ex: http://thepiratebay.se/search/cats/0/99/0 url = Pirata.config[:base_url] + "/search/#{URI.escape(@query)}" + "/#{page.to_s}" + "/#{@sort_type}" + "/#{@category}" html = Pirata::Search.parse_html(url) Pirata::Search::parse_search_page(html, self) end
[ "def", "search", "(", "page", "=", "0", ")", "#build URL ex: http://thepiratebay.se/search/cats/0/99/0", "url", "=", "Pirata", ".", "config", "[", ":base_url", "]", "+", "\"/search/#{URI.escape(@query)}\"", "+", "\"/#{page.to_s}\"", "+", "\"/#{@sort_type}\"", "+", "\"/#{@category}\"", "html", "=", "Pirata", "::", "Search", ".", "parse_html", "(", "url", ")", "Pirata", "::", "Search", "::", "parse_search_page", "(", "html", ",", "self", ")", "end" ]
Perform a search and return an array of Torrent objects
[ "Perform", "a", "search", "and", "return", "an", "array", "of", "Torrent", "objects" ]
6b4b0d58bda71caf053aeadaae59834e5a45a1c6
https://github.com/strong-code/pirata/blob/6b4b0d58bda71caf053aeadaae59834e5a45a1c6/lib/pirata/search.rb#L24-L29
7,589
strong-code/pirata
lib/pirata/search.rb
Pirata.Search.search_page
def search_page(page) raise "Search must be multipage to search pages" if !multipage? raise "Page must be a valid, positive integer" if page.class != Fixnum || page < 0 raise "Invalid page range" if page > @pages self.search(page) end
ruby
def search_page(page) raise "Search must be multipage to search pages" if !multipage? raise "Page must be a valid, positive integer" if page.class != Fixnum || page < 0 raise "Invalid page range" if page > @pages self.search(page) end
[ "def", "search_page", "(", "page", ")", "raise", "\"Search must be multipage to search pages\"", "if", "!", "multipage?", "raise", "\"Page must be a valid, positive integer\"", "if", "page", ".", "class", "!=", "Fixnum", "||", "page", "<", "0", "raise", "\"Invalid page range\"", "if", "page", ">", "@pages", "self", ".", "search", "(", "page", ")", "end" ]
Return the n page results of a search, assuming it is multipage
[ "Return", "the", "n", "page", "results", "of", "a", "search", "assuming", "it", "is", "multipage" ]
6b4b0d58bda71caf053aeadaae59834e5a45a1c6
https://github.com/strong-code/pirata/blob/6b4b0d58bda71caf053aeadaae59834e5a45a1c6/lib/pirata/search.rb#L32-L38
7,590
strong-code/pirata
lib/pirata/search.rb
Pirata.Search.parse_html
def parse_html(url) response = open(url, :allow_redirections => Pirata.config[:redirect]) Nokogiri::HTML(response) end
ruby
def parse_html(url) response = open(url, :allow_redirections => Pirata.config[:redirect]) Nokogiri::HTML(response) end
[ "def", "parse_html", "(", "url", ")", "response", "=", "open", "(", "url", ",", ":allow_redirections", "=>", "Pirata", ".", "config", "[", ":redirect", "]", ")", "Nokogiri", "::", "HTML", "(", "response", ")", "end" ]
Parse HTML body of a supplied URL
[ "Parse", "HTML", "body", "of", "a", "supplied", "URL" ]
6b4b0d58bda71caf053aeadaae59834e5a45a1c6
https://github.com/strong-code/pirata/blob/6b4b0d58bda71caf053aeadaae59834e5a45a1c6/lib/pirata/search.rb#L70-L73
7,591
etailer/parcel_api
lib/parcel_api/shipping_options.rb
ParcelApi.ShippingOptions.get_international
def get_international(parcel_params) response = @connection.get INTERNATIONAL_URL, params: parcel_params options = response.parsed.tap do |so| so.delete('success') so.delete('message_id') end RecursiveOpenStruct.new(options, recurse_over_arrays: true) end
ruby
def get_international(parcel_params) response = @connection.get INTERNATIONAL_URL, params: parcel_params options = response.parsed.tap do |so| so.delete('success') so.delete('message_id') end RecursiveOpenStruct.new(options, recurse_over_arrays: true) end
[ "def", "get_international", "(", "parcel_params", ")", "response", "=", "@connection", ".", "get", "INTERNATIONAL_URL", ",", "params", ":", "parcel_params", "options", "=", "response", ".", "parsed", ".", "tap", "do", "|", "so", "|", "so", ".", "delete", "(", "'success'", ")", "so", ".", "delete", "(", "'message_id'", ")", "end", "RecursiveOpenStruct", ".", "new", "(", "options", ",", "recurse_over_arrays", ":", "true", ")", "end" ]
Search for International Shipping Options @param parcel_params [Hash] parcel parameters @return [Array] return array of shipping options
[ "Search", "for", "International", "Shipping", "Options" ]
fcb8d64e45f7ba72bab48f143ac5115b0441aced
https://github.com/etailer/parcel_api/blob/fcb8d64e45f7ba72bab48f143ac5115b0441aced/lib/parcel_api/shipping_options.rb#L34-L41
7,592
26fe/tree.rb
lib/tree_rb/input_plugins/file_system/directory_walker.rb
TreeRb.DirTreeWalker.run
def run(dirname = nil, tree_node_visitor = nil, &block) # # args detection # if dirname and dirname.respond_to?(:enter_node) tree_node_visitor = dirname dirname = nil end # # check dirname # if @dirname.nil? and dirname.nil? raise 'missing starting directory' end @dirname = dirname if dirname # # check visitor # if tree_node_visitor and block raise 'cannot use block and parameter together' end if tree_node_visitor @visitor = tree_node_visitor end if block @visitor = TreeNodeVisitor.new(&block) end unless @visitor raise 'missing visitor' end # # finally starts to process # process_directory(File.expand_path(@dirname)) @visitor end
ruby
def run(dirname = nil, tree_node_visitor = nil, &block) # # args detection # if dirname and dirname.respond_to?(:enter_node) tree_node_visitor = dirname dirname = nil end # # check dirname # if @dirname.nil? and dirname.nil? raise 'missing starting directory' end @dirname = dirname if dirname # # check visitor # if tree_node_visitor and block raise 'cannot use block and parameter together' end if tree_node_visitor @visitor = tree_node_visitor end if block @visitor = TreeNodeVisitor.new(&block) end unless @visitor raise 'missing visitor' end # # finally starts to process # process_directory(File.expand_path(@dirname)) @visitor end
[ "def", "run", "(", "dirname", "=", "nil", ",", "tree_node_visitor", "=", "nil", ",", "&", "block", ")", "#", "# args detection", "#", "if", "dirname", "and", "dirname", ".", "respond_to?", "(", ":enter_node", ")", "tree_node_visitor", "=", "dirname", "dirname", "=", "nil", "end", "#", "# check dirname", "#", "if", "@dirname", ".", "nil?", "and", "dirname", ".", "nil?", "raise", "'missing starting directory'", "end", "@dirname", "=", "dirname", "if", "dirname", "#", "# check visitor", "#", "if", "tree_node_visitor", "and", "block", "raise", "'cannot use block and parameter together'", "end", "if", "tree_node_visitor", "@visitor", "=", "tree_node_visitor", "end", "if", "block", "@visitor", "=", "TreeNodeVisitor", ".", "new", "(", "block", ")", "end", "unless", "@visitor", "raise", "'missing visitor'", "end", "#", "# finally starts to process", "#", "process_directory", "(", "File", ".", "expand_path", "(", "@dirname", ")", ")", "@visitor", "end" ]
Run the visitor through the directory tree @overload run @overload run(dirname) @param [String] dirname @yield define TreeNodeVisitor @overload run(tree_node_visitor) @param [TreeNodeVisitor] @yield define TreeNodeVisitor @overload run(dirname, tree_node_visitor) @param [String] dirname @param [TreeNodeVisitor] @yield define TreeNodeVisitor @return [TreeNodeVisitor] the visitor @example Print the contents of tmp directory w = DirTreeWalker.new w.run("/tmp") do on_visit_leaf_node { |pathname| puts pathname } end.run
[ "Run", "the", "visitor", "through", "the", "directory", "tree" ]
5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b
https://github.com/26fe/tree.rb/blob/5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b/lib/tree_rb/input_plugins/file_system/directory_walker.rb#L215-L257
7,593
26fe/tree.rb
lib/tree_rb/input_plugins/file_system/directory_walker.rb
TreeRb.DirTreeWalker.process_directory
def process_directory(dirname, level=1) begin entries = Dir.entries(dirname).sort rescue Errno::EACCES => e $stderr.puts e @visitor.cannot_enter_node(dirname, e) return rescue Errno::EPERM => e $stderr.puts e @visitor.cannot_enter_node(dirname, e) return rescue Errno::ENOENT => e $stderr.puts e @visitor.cannot_enter_node(dirname, e) return end @visitor.enter_node(dirname) entries.each do |basename| begin next if basename == '.' or basename == '..' # ignore always "." and ".." pathname = File.join(dirname, basename) if File.directory?(pathname) if not ignore_dir?(basename) and (@max_level.nil? or @max_level > level) process_directory(pathname, level+1) end else if !!@visit_file && match?(basename) && !ignore_file?(basename) @visitor.visit_leaf(pathname) end end rescue Errno::EACCES => e $stderr.puts e rescue Errno::EPERM => e $stderr.puts e rescue Errno::ENOENT => e $stderr.puts e end end @visitor.exit_node(dirname) end
ruby
def process_directory(dirname, level=1) begin entries = Dir.entries(dirname).sort rescue Errno::EACCES => e $stderr.puts e @visitor.cannot_enter_node(dirname, e) return rescue Errno::EPERM => e $stderr.puts e @visitor.cannot_enter_node(dirname, e) return rescue Errno::ENOENT => e $stderr.puts e @visitor.cannot_enter_node(dirname, e) return end @visitor.enter_node(dirname) entries.each do |basename| begin next if basename == '.' or basename == '..' # ignore always "." and ".." pathname = File.join(dirname, basename) if File.directory?(pathname) if not ignore_dir?(basename) and (@max_level.nil? or @max_level > level) process_directory(pathname, level+1) end else if !!@visit_file && match?(basename) && !ignore_file?(basename) @visitor.visit_leaf(pathname) end end rescue Errno::EACCES => e $stderr.puts e rescue Errno::EPERM => e $stderr.puts e rescue Errno::ENOENT => e $stderr.puts e end end @visitor.exit_node(dirname) end
[ "def", "process_directory", "(", "dirname", ",", "level", "=", "1", ")", "begin", "entries", "=", "Dir", ".", "entries", "(", "dirname", ")", ".", "sort", "rescue", "Errno", "::", "EACCES", "=>", "e", "$stderr", ".", "puts", "e", "@visitor", ".", "cannot_enter_node", "(", "dirname", ",", "e", ")", "return", "rescue", "Errno", "::", "EPERM", "=>", "e", "$stderr", ".", "puts", "e", "@visitor", ".", "cannot_enter_node", "(", "dirname", ",", "e", ")", "return", "rescue", "Errno", "::", "ENOENT", "=>", "e", "$stderr", ".", "puts", "e", "@visitor", ".", "cannot_enter_node", "(", "dirname", ",", "e", ")", "return", "end", "@visitor", ".", "enter_node", "(", "dirname", ")", "entries", ".", "each", "do", "|", "basename", "|", "begin", "next", "if", "basename", "==", "'.'", "or", "basename", "==", "'..'", "# ignore always \".\" and \"..\"", "pathname", "=", "File", ".", "join", "(", "dirname", ",", "basename", ")", "if", "File", ".", "directory?", "(", "pathname", ")", "if", "not", "ignore_dir?", "(", "basename", ")", "and", "(", "@max_level", ".", "nil?", "or", "@max_level", ">", "level", ")", "process_directory", "(", "pathname", ",", "level", "+", "1", ")", "end", "else", "if", "!", "!", "@visit_file", "&&", "match?", "(", "basename", ")", "&&", "!", "ignore_file?", "(", "basename", ")", "@visitor", ".", "visit_leaf", "(", "pathname", ")", "end", "end", "rescue", "Errno", "::", "EACCES", "=>", "e", "$stderr", ".", "puts", "e", "rescue", "Errno", "::", "EPERM", "=>", "e", "$stderr", ".", "puts", "e", "rescue", "Errno", "::", "ENOENT", "=>", "e", "$stderr", ".", "puts", "e", "end", "end", "@visitor", ".", "exit_node", "(", "dirname", ")", "end" ]
recurse on other directories
[ "recurse", "on", "other", "directories" ]
5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b
https://github.com/26fe/tree.rb/blob/5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b/lib/tree_rb/input_plugins/file_system/directory_walker.rb#L274-L317
7,594
marcmo/cxxproject
lib/cxxproject/plugin_context.rb
Cxxproject.PluginContext.cxx_plugin
def cxx_plugin(&blk) if blk.arity != @expected_arity return end case blk.arity when 0 blk.call() when 3 blk.call(@cxxproject2rake, @building_blocks, @log) end end
ruby
def cxx_plugin(&blk) if blk.arity != @expected_arity return end case blk.arity when 0 blk.call() when 3 blk.call(@cxxproject2rake, @building_blocks, @log) end end
[ "def", "cxx_plugin", "(", "&", "blk", ")", "if", "blk", ".", "arity", "!=", "@expected_arity", "return", "end", "case", "blk", ".", "arity", "when", "0", "blk", ".", "call", "(", ")", "when", "3", "blk", ".", "call", "(", "@cxxproject2rake", ",", "@building_blocks", ",", "@log", ")", "end", "end" ]
method for plugins to get the cxxproject2rake building_blocks log
[ "method", "for", "plugins", "to", "get", "the", "cxxproject2rake", "building_blocks", "log" ]
3740a09d6a143acd96bde3d2ff79055a6b810da4
https://github.com/marcmo/cxxproject/blob/3740a09d6a143acd96bde3d2ff79055a6b810da4/lib/cxxproject/plugin_context.rb#L37-L48
7,595
payout/podbay
lib/podbay/consul.rb
Podbay.Consul.node_healthy?
def node_healthy?(hostname, services = [], iterations = 60) print "Waiting for #{hostname} to become healthy" services = services.reject { |s| get_service_check(s).empty? }.freeze iterations.times do print '.' checks = hostname_health_checks(hostname) has_services = (services - checks.map { |c| c['ServiceName'] }).empty? passing_checks = checks.all? { |c| c['Status'] == 'passing' } if !checks.empty? && has_services && passing_checks unless services.empty? print " Services: #{services.join(', ').inspect} Healthy and".green end puts ' Node Healthy!'.green return true end sleep(6) end false end
ruby
def node_healthy?(hostname, services = [], iterations = 60) print "Waiting for #{hostname} to become healthy" services = services.reject { |s| get_service_check(s).empty? }.freeze iterations.times do print '.' checks = hostname_health_checks(hostname) has_services = (services - checks.map { |c| c['ServiceName'] }).empty? passing_checks = checks.all? { |c| c['Status'] == 'passing' } if !checks.empty? && has_services && passing_checks unless services.empty? print " Services: #{services.join(', ').inspect} Healthy and".green end puts ' Node Healthy!'.green return true end sleep(6) end false end
[ "def", "node_healthy?", "(", "hostname", ",", "services", "=", "[", "]", ",", "iterations", "=", "60", ")", "print", "\"Waiting for #{hostname} to become healthy\"", "services", "=", "services", ".", "reject", "{", "|", "s", "|", "get_service_check", "(", "s", ")", ".", "empty?", "}", ".", "freeze", "iterations", ".", "times", "do", "print", "'.'", "checks", "=", "hostname_health_checks", "(", "hostname", ")", "has_services", "=", "(", "services", "-", "checks", ".", "map", "{", "|", "c", "|", "c", "[", "'ServiceName'", "]", "}", ")", ".", "empty?", "passing_checks", "=", "checks", ".", "all?", "{", "|", "c", "|", "c", "[", "'Status'", "]", "==", "'passing'", "}", "if", "!", "checks", ".", "empty?", "&&", "has_services", "&&", "passing_checks", "unless", "services", ".", "empty?", "print", "\" Services: #{services.join(', ').inspect} Healthy and\"", ".", "green", "end", "puts", "' Node Healthy!'", ".", "green", "return", "true", "end", "sleep", "(", "6", ")", "end", "false", "end" ]
Wait for all health checks on the host to become healthy. services - services to perform health checks on (if health checks are defined)
[ "Wait", "for", "all", "health", "checks", "on", "the", "host", "to", "become", "healthy", "." ]
a17cc1db6a1f032d9d7005136e4176dbe7f3a73d
https://github.com/payout/podbay/blob/a17cc1db6a1f032d9d7005136e4176dbe7f3a73d/lib/podbay/consul.rb#L31-L56
7,596
payout/podbay
lib/podbay/consul.rb
Podbay.Consul.available_services
def available_services(index = nil) loop do begin resp, nindex = _service.get_all(index: index) return [resp.keys - ['consul'], nindex] if nindex != index rescue Diplomat::Timeout # Continue waiting end end end
ruby
def available_services(index = nil) loop do begin resp, nindex = _service.get_all(index: index) return [resp.keys - ['consul'], nindex] if nindex != index rescue Diplomat::Timeout # Continue waiting end end end
[ "def", "available_services", "(", "index", "=", "nil", ")", "loop", "do", "begin", "resp", ",", "nindex", "=", "_service", ".", "get_all", "(", "index", ":", "index", ")", "return", "[", "resp", ".", "keys", "-", "[", "'consul'", "]", ",", "nindex", "]", "if", "nindex", "!=", "index", "rescue", "Diplomat", "::", "Timeout", "# Continue waiting", "end", "end", "end" ]
Blocks forever waiting for updates to the list of available services.
[ "Blocks", "forever", "waiting", "for", "updates", "to", "the", "list", "of", "available", "services", "." ]
a17cc1db6a1f032d9d7005136e4176dbe7f3a73d
https://github.com/payout/podbay/blob/a17cc1db6a1f032d9d7005136e4176dbe7f3a73d/lib/podbay/consul.rb#L102-L111
7,597
payout/podbay
lib/podbay/consul.rb
Podbay.Consul.service_addresses
def service_addresses(service, index = nil) loop do addresses, nindex = service_addresses!(service, index) return [addresses, nindex] if addresses && nindex end end
ruby
def service_addresses(service, index = nil) loop do addresses, nindex = service_addresses!(service, index) return [addresses, nindex] if addresses && nindex end end
[ "def", "service_addresses", "(", "service", ",", "index", "=", "nil", ")", "loop", "do", "addresses", ",", "nindex", "=", "service_addresses!", "(", "service", ",", "index", ")", "return", "[", "addresses", ",", "nindex", "]", "if", "addresses", "&&", "nindex", "end", "end" ]
Blocks forever waiting for updates to service addresses.
[ "Blocks", "forever", "waiting", "for", "updates", "to", "service", "addresses", "." ]
a17cc1db6a1f032d9d7005136e4176dbe7f3a73d
https://github.com/payout/podbay/blob/a17cc1db6a1f032d9d7005136e4176dbe7f3a73d/lib/podbay/consul.rb#L115-L120
7,598
payout/podbay
lib/podbay/consul.rb
Podbay.Consul.service_addresses!
def service_addresses!(service, index = nil) meta = {} resp = _service.get(service, :all, {index: index, wait: '2s'}, meta) if (nindex = meta[:index]) != index addresses = resp.map do |address| { id: address.ServiceID, ip: address.ServiceAddress, node: address.Node, port: address.ServicePort } end [addresses, nindex] end end
ruby
def service_addresses!(service, index = nil) meta = {} resp = _service.get(service, :all, {index: index, wait: '2s'}, meta) if (nindex = meta[:index]) != index addresses = resp.map do |address| { id: address.ServiceID, ip: address.ServiceAddress, node: address.Node, port: address.ServicePort } end [addresses, nindex] end end
[ "def", "service_addresses!", "(", "service", ",", "index", "=", "nil", ")", "meta", "=", "{", "}", "resp", "=", "_service", ".", "get", "(", "service", ",", ":all", ",", "{", "index", ":", "index", ",", "wait", ":", "'2s'", "}", ",", "meta", ")", "if", "(", "nindex", "=", "meta", "[", ":index", "]", ")", "!=", "index", "addresses", "=", "resp", ".", "map", "do", "|", "address", "|", "{", "id", ":", "address", ".", "ServiceID", ",", "ip", ":", "address", ".", "ServiceAddress", ",", "node", ":", "address", ".", "Node", ",", "port", ":", "address", ".", "ServicePort", "}", "end", "[", "addresses", ",", "nindex", "]", "end", "end" ]
Non-blocking request for service_addresses.
[ "Non", "-", "blocking", "request", "for", "service_addresses", "." ]
a17cc1db6a1f032d9d7005136e4176dbe7f3a73d
https://github.com/payout/podbay/blob/a17cc1db6a1f032d9d7005136e4176dbe7f3a73d/lib/podbay/consul.rb#L124-L140
7,599
kamui/rack-accept_headers
lib/rack/accept_headers/media_type.rb
Rack::AcceptHeaders.MediaType.matches
def matches(media_type) type, subtype, params = parse_media_type(media_type) values.select {|v| if v == media_type || v == '*/*' true else t, s, p = parse_media_type(v) t == type && (s == '*' || s == subtype) && (p == '' || params_match?(params, p)) end }.sort_by {|v| # Most specific gets precedence. v.length }.reverse end
ruby
def matches(media_type) type, subtype, params = parse_media_type(media_type) values.select {|v| if v == media_type || v == '*/*' true else t, s, p = parse_media_type(v) t == type && (s == '*' || s == subtype) && (p == '' || params_match?(params, p)) end }.sort_by {|v| # Most specific gets precedence. v.length }.reverse end
[ "def", "matches", "(", "media_type", ")", "type", ",", "subtype", ",", "params", "=", "parse_media_type", "(", "media_type", ")", "values", ".", "select", "{", "|", "v", "|", "if", "v", "==", "media_type", "||", "v", "==", "'*/*'", "true", "else", "t", ",", "s", ",", "p", "=", "parse_media_type", "(", "v", ")", "t", "==", "type", "&&", "(", "s", "==", "'*'", "||", "s", "==", "subtype", ")", "&&", "(", "p", "==", "''", "||", "params_match?", "(", "params", ",", "p", ")", ")", "end", "}", ".", "sort_by", "{", "|", "v", "|", "# Most specific gets precedence.", "v", ".", "length", "}", ".", "reverse", "end" ]
Returns an array of media types from this header that match the given +media_type+, ordered by precedence.
[ "Returns", "an", "array", "of", "media", "types", "from", "this", "header", "that", "match", "the", "given", "+", "media_type", "+", "ordered", "by", "precedence", "." ]
099bfbb919de86b5842c8e14be42b8b784e53f03
https://github.com/kamui/rack-accept_headers/blob/099bfbb919de86b5842c8e14be42b8b784e53f03/lib/rack/accept_headers/media_type.rb#L27-L40