Q: Ruby: Should strings in a frozen array also be individually frozen? Ruby 2.2.3, Rails 4.2.1
I have a large number of arrays of strings that I define as constants for use throughout an application. They are various sets of ISO country codes, language codes, that sort of thing, so two to four characters, numbered in the hundreds of unique values each.
The different arrays are collections of these, so NORTH_AMERICA_COUNTRY_CODES might be an array of a dozen of so country codes, AFRICA_COUNTRY_CODES might be an array of around 60. Many of them overlap (various versions of the Commonwealth countries,  for example).
The arrays are used in comparison with other arbitrary arrays of country codes for logic such as "Subtract this list of countries from Africa".
So I'm wondering whether, when I generate these constants, I ought to freeze the strings within the arrays, so instead of:
WORLD_COUNTRIES = Countries.pluck(:country_code).freeze

... maybe ...
WORLD_COUNTRIES = Countries.pluck(:country_code).map{|c| c.freeze}.freeze

Is there a way of quantifying the potential benefits?
I considered using arrays of symbols instead of arrays of strings, but the arbitrary arrays that these are used with are stored in PostgreSQL text arrays, and it seems like I'd need to serialise those columns instead, or maybe override the getter and setter methods to change the values between arrays of strings and arrays of symbols. Ugh.
Edit
Testing results, in which I've attempted to benchmark three situations:

*

*Comparing a frozen array of unfrozen strings with an unfrozen array of unfrozen strings

*Comparing a frozen array of frozen strings with an unfrozen array of unfrozen strings

*Comparing a frozen array of symbols with an unfrozen array of symbols (in case I bit the bullet and went all symbolic on this).

Any thoughts on methodology or interpretation gratefully received. I'm not sure whether the similarity in results between the first two indicates that they are in all respects the same, but I'd be keen on anything that can directly point to differences in memory allocation.
Script:
require 'benchmark'

country_list             = ["AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CS", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS", "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "YU", "ZA", "ZM", "ZW"]
FROZEN_ARRAY             = country_list.dup.freeze
puts FROZEN_ARRAY.size
FROZEN_ARRAY_AND_STRINGS = country_list.dup.map{|x| x.freeze}.freeze
FROZEN_ARRAY_AND_SYMBOLS = country_list.dup.map{|x| x.to_sym}.freeze
comp_s                   = %w(AD AT BE CY EE FI FR DE ES GR IE IT LU LV MC ME MT NL PT SI SK SM VA)
comp_sym                 = %w(AD AT BE CY EE FI FR DE ES GR IE IT LU LV MC ME MT NL PT SI SK SM VA).map{|x| x.to_sym}

Benchmark.bm do |x|
  x.report("frozen string"  )  { 10000.times {|i| c = (FROZEN_ARRAY_AND_STRINGS & comp_s.dup) }}
  x.report("unfrozen string")  { 10000.times {|i| c = (FROZEN_ARRAY             & comp_s.dup) }}
  x.report("symbols"        )  { 10000.times {|i| c = (FROZEN_ARRAY_AND_SYMBOLS & comp_sym.dup) }}
end

Benchmark.bmbm do |x|
  x.report("frozen string"  )  { 10000.times {|i| c = (FROZEN_ARRAY_AND_STRINGS & comp_s.dup) }}
  x.report("unfrozen string")  { 10000.times {|i| c = (FROZEN_ARRAY             & comp_s.dup) }}
  x.report("symbols"        )  { 10000.times {|i| c = (FROZEN_ARRAY_AND_SYMBOLS & comp_sym.dup) }}
end

Result:
2.2.3 :001 > require 'benchmark'
 => false
2.2.3 :002 >
2.2.3 :003 >   country_list             = ["AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CS", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS", "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "YU", "ZA", "ZM", "ZW"]
 => ["AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CS", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS", "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "YU", "ZA", "ZM", "ZW"]
2.2.3 :004 > FROZEN_ARRAY             = country_list.dup.freeze
 => ["AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CS", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS", "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "YU", "ZA", "ZM", "ZW"]
2.2.3 :005 > puts FROZEN_ARRAY.size
252
 => nil
2.2.3 :006 > FROZEN_ARRAY_AND_STRINGS = country_list.dup.map{|x| x.freeze}.freeze
 => ["AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CS", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS", "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "YU", "ZA", "ZM", "ZW"]
2.2.3 :007 > FROZEN_ARRAY_AND_SYMBOLS = country_list.dup.map{|x| x.to_sym}.freeze
 => [:AD, :AE, :AF, :AG, :AI, :AL, :AM, :AN, :AO, :AQ, :AR, :AS, :AT, :AU, :AW, :AX, :AZ, :BA, :BB, :BD, :BE, :BF, :BG, :BH, :BI, :BJ, :BL, :BM, :BN, :BO, :BQ, :BR, :BS, :BT, :BV, :BW, :BY, :BZ, :CA, :CC, :CD, :CF, :CG, :CH, :CI, :CK, :CL, :CM, :CN, :CO, :CR, :CS, :CU, :CV, :CW, :CX, :CY, :CZ, :DE, :DJ, :DK, :DM, :DO, :DZ, :EC, :EE, :EG, :EH, :ER, :ES, :ET, :FI, :FJ, :FK, :FM, :FO, :FR, :GA, :GB, :GD, :GE, :GF, :GG, :GH, :GI, :GL, :GM, :GN, :GP, :GQ, :GR, :GS, :GT, :GU, :GW, :GY, :HK, :HM, :HN, :HR, :HT, :HU, :ID, :IE, :IL, :IM, :IN, :IO, :IQ, :IR, :IS, :IT, :JE, :JM, :JO, :JP, :KE, :KG, :KH, :KI, :KM, :KN, :KP, :KR, :KW, :KY, :KZ, :LA, :LB, :LC, :LI, :LK, :LR, :LS, :LT, :LU, :LV, :LY, :MA, :MC, :MD, :ME, :MF, :MG, :MH, :MK, :ML, :MM, :MN, :MO, :MP, :MQ, :MR, :MS, :MT, :MU, :MV, :MW, :MX, :MY, :MZ, :NA, :NC, :NE, :NF, :NG, :NI, :NL, :NO, :NP, :NR, :NU, :NZ, :OM, :PA, :PE, :PF, :PG, :PH, :PK, :PL, :PM, :PN, :PR, :PS, :PT, :PW, :PY, :QA, :RE, :RO, :RS, :RU, :RW, :SA, :SB, :SC, :SD, :SE, :SG, :SH, :SI, :SJ, :SK, :SL, :SM, :SN, :SO, :SR, :SS, :ST, :SV, :SX, :SY, :SZ, :TC, :TD, :TF, :TG, :TH, :TJ, :TK, :TL, :TM, :TN, :TO, :TR, :TT, :TV, :TW, :TZ, :UA, :UG, :UM, :US, :UY, :UZ, :VA, :VC, :VE, :VG, :VI, :VN, :VU, :WF, :WS, :YE, :YT, :YU, :ZA, :ZM, :ZW]
2.2.3 :008 > comp_s                   = %w(AD AT BE CY EE FI FR DE ES GR IE IT LU LV MC ME MT NL PT SI SK SM VA)
 => ["AD", "AT", "BE", "CY", "EE", "FI", "FR", "DE", "ES", "GR", "IE", "IT", "LU", "LV", "MC", "ME", "MT", "NL", "PT", "SI", "SK", "SM", "VA"]
2.2.3 :009 > comp_sym                 = %w(AD AT BE CY EE FI FR DE ES GR IE IT LU LV MC ME MT NL PT SI SK SM VA).map{|x| x.to_sym}
 => [:AD, :AT, :BE, :CY, :EE, :FI, :FR, :DE, :ES, :GR, :IE, :IT, :LU, :LV, :MC, :ME, :MT, :NL, :PT, :SI, :SK, :SM, :VA]
2.2.3 :010 >
2.2.3 :011 >
2.2.3 :012 >   Benchmark.bm do |x|
2.2.3 :013 >       x.report("frozen string"  )  { 10000.times {|i| c = (FROZEN_ARRAY_AND_STRINGS & comp_s.dup) }}
2.2.3 :014?>     x.report("unfrozen string")  { 10000.times {|i| c = (FROZEN_ARRAY             & comp_s.dup) }}
2.2.3 :015?>     x.report("symbols"        )  { 10000.times {|i| c = (FROZEN_ARRAY_AND_SYMBOLS & comp_sym.dup) }}
2.2.3 :016?>   end
       user     system      total        real
frozen string  0.190000   0.000000   0.190000 (  0.194141)
unfrozen string  0.170000   0.010000   0.180000 (  0.174675)
symbols  0.080000   0.000000   0.080000 (  0.081507)
 => [#<Benchmark::Tms:0x007f810c3aca70 @label="frozen string", @real=0.1941408810671419, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.1899999999999995, @total=0.1899999999999995>, #<Benchmark::Tms:0x007f810c82b538 @label="unfrozen string", @real=0.1746752569451928, @cstime=0.0, @cutime=0.0, @stime=0.010000000000000009, @utime=0.16999999999999993, @total=0.17999999999999994>, #<Benchmark::Tms:0x007f810af2cfa0 @label="symbols", @real=0.08150708093307912, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.08000000000000007, @total=0.08000000000000007>]
2.2.3 :017 >
2.2.3 :018 >
2.2.3 :019 >   Benchmark.bmbm do |x|
2.2.3 :020 >       x.report("frozen string"  )  { 10000.times {|i| c = (FROZEN_ARRAY_AND_STRINGS & comp_s.dup) }}
2.2.3 :021?>     x.report("unfrozen string")  { 10000.times {|i| c = (FROZEN_ARRAY             & comp_s.dup) }}
2.2.3 :022?>     x.report("symbols"        )  { 10000.times {|i| c = (FROZEN_ARRAY_AND_SYMBOLS & comp_sym.dup) }}
2.2.3 :023?>   end
Rehearsal ---------------------------------------------------
frozen string     0.180000   0.000000   0.180000 (  0.183846)
unfrozen string   0.200000   0.000000   0.200000 (  0.196311)
symbols           0.080000   0.000000   0.080000 (  0.082794)
------------------------------------------ total: 0.460000sec

                      user     system      total        real
frozen string     0.160000   0.000000   0.160000 (  0.167051)
unfrozen string   0.170000   0.000000   0.170000 (  0.171601)
symbols           0.080000   0.000000   0.080000 (  0.078746)
 => [#<Benchmark::Tms:0x007f811022a388 @label="frozen string", @real=0.1670510449912399, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.16000000000000014, @total=0.16000000000000014>, #<Benchmark::Tms:0x007f811022a4c8 @label="unfrozen string", @real=0.17160122003406286, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.16999999999999993, @total=0.16999999999999993>, #<Benchmark::Tms:0x007f8108eb1c58 @label="symbols", @real=0.07874645793344826, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.08000000000000007, @total=0.08000000000000007>]
2.2.3 :024 >
2.2.3 :025 >
2.2.3 :026 >

A: Since you're dealing with a small number of values, and since the performance benefits of symbols are evident from your testing, just go with symbols.
BTW, you can use map(&:to_sym) instead of map {|x| x.to_sym}.


Q: Getting fonts, sizes, bold,...etc I'm having trouble finding stuff on accessing Windows fonts or predefined fonts, and sizes. So for my java program I have a JComboBox with fonts, sizes, and colors. The problem is that I need to pre-Enter the fonts, sizes and colors. How would I be able to get the predefined fonts, colors, and sizes? So far this is what I have for this font but its not in the correct way.
               if (font.equals("Arial")) {

                if (size.equals("8")) {
                    setSize = 8;
                } else if (size.equals("10")) {
                    setSize = 10;
                } else if (size.equals("12")) {
                    setSize = 12;
                }

                if (color.equals("Black")) {
                    setColor = Color.BLACK;
                } else if (color.equals("Blue")) {
                    setColor = Color.BLUE;
                } else if (color.equals("Red")) {
                    setColor = Color.red;
                }

                Font font = new Font("Arial", setAttribute, setSize);
                Writer.setFont(font);
                Writer.setForeground(setColor);

A: GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fonts = ge.getAvailableFontFamilyNames();

The sizes and styles can be set at run-time.
E.G.

import java.awt.*;
import javax.swing.*;

public class ShowFonts {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            String[] fonts = ge.getAvailableFontFamilyNames();
            JComboBox fontChooser = new JComboBox(fonts);
            fontChooser.setRenderer(new FontCellRenderer());
            JOptionPane.showMessageDialog(null, fontChooser);
        });
    }
}

class FontCellRenderer extends DefaultListCellRenderer {

    public Component getListCellRendererComponent(
            JList list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus) {
        JLabel label = (JLabel)super.getListCellRendererComponent(
                list,value,index,isSelected,cellHasFocus);
        Font font = new Font(value.toString(), Font.PLAIN, 20);
        label.setFont(font);
        return label;
    }
}

JavaDoc
The JDoc for GraphicsEnvironment.getAvailableFontFamilyNames() state in part..

Returns an array containing the names of all font families in this GraphicsEnvironment localized for the default locale, as returned by Locale.getDefault()..

See also:
getAllFonts()..


Q: Accept parameters of URL in .NET CORE I'm new in .NET CORE and I would like if its possible to change the default format for request urls. Let me explain. I have two get method on a controller for get a list and get info of 1 element
[Route("api/[controller]/")]
[ApiController]
public class Department : ControllerBase
{
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    [HttpGet("{id:int}")]
    public string GetDepartamento(int id)
    {
        return "value";
    }

    [HttpPost]
    public void Post([FromBody] string value)
    {
    }
  }
}

In order to call these resource u use
https://localhost:44309/api/department
https://localhost:44309/api/department/1

But I need to use this format not just for this controller but all the controllers
GET:https://localhost:44309/api/department
GET:https://localhost:44309/api/department?id=1
POST:https://localhost:44309/api/department (data on the body of http call)
PUT:https://localhost:44309/api/department?id=1 (data on the body of http call)
DELETE:https://localhost:44309/api/department?id=1

I'm working over a new project (.net core web application MVC)so Startup and Program files were not modified.

A:
I have two get method on a controller for get a list and get info of 1 element

I need to use this format

GET:https://localhost:44309/api/department

GET:https://localhost:44309/api/department?id=1

If you'd like to match request(s) to expected action(s) based on the query string, you can try to implement a custom ActionMethodSelectorAttribute and apply it to your actions, like below.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class CheckQueryStingAttribute : ActionMethodSelectorAttribute
{
    public string QueryStingName { get; set; }
    public bool CanPass { get; set; }
    public CheckQueryStingAttribute(string qname, bool canpass)
    {
        QueryStingName = qname;
        CanPass = canpass;
    }

    public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
    {
        StringValues value;

        routeContext.HttpContext.Request.Query.TryGetValue(QueryStingName, out value);

        if (QueryStingName == "" && CanPass)
        {
            return true;
        }
        else
        {
            if (CanPass)
            {
                return !StringValues.IsNullOrEmpty(value);
            }

            return StringValues.IsNullOrEmpty(value);
        }
    }
}

Apply it to actions
[HttpGet]
[CheckQuerySting("id", false)]
[CheckQuerySting("", true)]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

[HttpGet]
[CheckQuerySting("id", true)]
[CheckQuerySting("", false)]
public string GetDepartamento(int id)
{
    return "value";
}

Test Result


Q: Save and call random variables I'm attempting to have my code create a number of random values, save those values, then allow me to manipulate those random values to create a number of profiles.
I'm currently having issues with both saving the numbers and with global and local values.
I have tried this so far:
import random

HP = random.randint(30,70)
Strength = random.randint (30,70)

M_HP = random.randint(30,70)-10
M_Strength = random.randint (30,70)-10

def pilot_print():
    print ("Your pilot HP is " +str(HP))
    print ("Your pilot Strength is " +str(Strength))

def mech_print():
    print ("Your Mech HP is " +str(M_HP))
    print ("Your Mech Strength is " +str(M_Strength))

My issue is that I'm also attempting to put something like
def combine():
    HP+(M_HP/2) = C_HP
    Strength+(M_Strength/2) = C_Strength

My aim is to eventually create a game with character profiles generated randomly.
Would anyone be kind enough to point me in the right direction?
Thank you

A:
I'm attempting to have my code create a number of random values, save those values, then allow me to manipulate those random values to create a number of profiles

This is, in general, wrong approach. Right one is to have RNG internal state saved, so then after restoring it you'll get the same sequence of random numbers
Along the lines:
import random

state = random.getstate()
# save it, pickle it, ...

...

# restore state, unpickle it, ...
random.setstate(state)

# call to random.randint() will produce controllable sequence of numbers


Q: Dynamically create a class inherited from neomodel.StructuredNode Python's library neomodel provides the ability to define a relationship with a class that hasn't been defined yet, by using its name as string, which works fine as follows:
from neomodel import StructuredNode, RelationshipTo
# if Foo is already defined
class Bar (structuredNode):
    rel = RelationshipTo(Foo, 'REL')
# if Foo isn't defined
class Bar(StructuredNode):
    rel = RelationshipTo('Foo', 'REL')

I want to create a class in the runtime and provide it with the attribute RelationshipTo, which should make a relationship with undefined yet class, so I did:
Bar = type('Bar', (StructuredNode,), {'rel': RelationshipTo('Foo', 'REL')})

In some point in the runtime later, I define Foo:
Foo = type('Foo', (StructuredNode,), {})

Now if I want to use the class I've just made:
bar = Bar()

The next error still pops up as if I haven't defined Foo:

AttributeError: module '_pydevd_bundle.pydevd_exec2' has no attribute
'Foo'

Note: This error doesn't appear if I at least define Bar statically (not in the runtime)
Would someone explain why that happens and how to define them properly in runtime, please?
I appreciate any help!


Q: Where can you find out to whom a given Mac is registered? Is there a place in the OS that we can see to which person the OS is registered to?

A: The registration information that you enter when you setup OS X is stored in a hidden plist file in the system.
That data is stored the file /var/db/.AppleSetupDone if you run the following command in terminal you should be able to see that information:
sudo cat /var/db/.AppleSetupDone

This will show you the information entered. You will need to modify this information with a plist editor. For warranty claims Apple will know who registered the machine for AppleCare.

A: I don't know whether the registration information is stored locally. If you call Apple, they can certainly tell you under which person the Mac is registered.


Q: Display Conky output on login screen I am trying to display some basic system info on the login screen before any user logs in like hostname, kernel version, IP etc.
I can configure Conky to show all this info on the desktop once someone has logged in, but I cant find a way to make it show on the GDM3 login screen.
Has anyone done this or know how it can be done ? I have tried a few methods found by searching but none seem to work.
Thanks.
Dean.


Q: how to use cd command properly in batch file? I am new to batch scripting, just trying to write a simple batch file that would go to the directory that I frequently use, without having to do cd everytime.
@ECHO OFF
CD /
CD D:
CD programming/

when I save and try to run this it gives error:
the system cannot find the file specified path

Even though these commands run fine while doing it directly on prompt

A: First off, the Windows path separator is \ but not /.
Then you need to get aware that there is a current directory for every drive to fully understand what is going on.
But anyway, here is an adapted version of your code with some explanations:
rem /* This changes to the root directory of the drive you are working on (say `C:`);
rem    note that I replaced `/` by `\`, which is the correct path separator: */
cd \
rem /* This changes the current directory of drive `D:` to the current directory of drive `D:`,
rem    note that this does NOT switch to the specified drive as there is no `/D` option: */
cd D:
rem /* This is actually the same as `cd programming` and changes to the sub-directory
rem    `programming` of your current working directory: */
cd programming\
rem /* The final working directory is now `C:\programming`, assuming that the original
rem    working drive was `C:`. */

However, what I think you are trying to achieve is the following:
rem // This switches to the drive `D:`; regard that there is NO `cd` command:
D:
rem // This changes to the root directory of the drive you are working on, which is `D:`:
cd \
rem // This changes into the directory `programming`:
cd programming
rem // The final working directory is now `D:\programming`.

This can be shortened to:
D:
cd \programming

Or even this:
rem // Note the `/D` option that is required to also switch to the given drive:
cd /D D:\programming

A: When you use
cd d:
the current directory of D: may not be D:\
To set the root you need to use CD D:\
In Windows, use backslashes


Q: Derivative of the upper incomplete gamma function. I wish to compute the derivative of the upper incomplete gamma function
\begin{equation}
\Gamma(s,x) = \int_{x}^\infty t^{s-1}e^{-t} \, dt .
\end{equation}
Wikipedia states of the derivative of $\Gamma(s,x)$ as
\begin{equation}
\frac{\partial \Gamma(s,x)}{\partial s} = \ln x \Gamma(s,x) + x \Gamma(3,s,x).
\end{equation}
where
\begin{equation}
\Gamma(K,s,x) = G_{K-1,K}^{K,0} \left(\frac{0,0,\cdots,0}{s-1,-1,\cdots,-1}\mid x\right)
\end{equation}
is the Meijer G function. My question is, if I evaluate this equation at x=0, I should get the psi function but instead I get $-\infty$. Could someone please confirm how to use this, and also clarify if the first term is $\ln (x) \Gamma(s,x)$ or $\ln (x \Gamma(s,x))$.
Thanks.


Q: Automated installation with Brew/cask in apps folder I want create an automated script to use on a post installation.
For this reason i want use brew and cask to make it all.
So, i think that my script should start with that to install brew:
echo << "Installing homebrew..."
if test ! $(which brew); then
    echo "Homebrew not found, Installing..."
    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
fi

Then i need to install some useful stuff as i see here:
http://lapwinglabs.com/blog/hacker-guide-to-setting-up-your-mac
So i put this too on my script:
# Install GNU core utilities (those that come with OS X are outdated)
brew install coreutils

# Install GNU `find`, `locate`, `updatedb`, and `xargs`, g-prefixed
brew install findutils

# Install Bash 4
brew install bash

# Install more recent versions of some OS X tools
brew tap homebrew/dupes
brew install homebrew/dupes/grep
$PATH=$(brew --prefix coreutils)/libexec/gnubin:$PATH

After that, the guide on the link says to install all the apps with cask and clean.
Here is my question.
I wish install and can update them in future using the classical Application folder of mac
How i can do that?
Maybe i should put this line:
export HOMEBREW_CASK_OPTS="--appdir=/Applications --caskroom=/usr/local/Caskroom"

Before all the commands to install the apps? May it works? (I have found this line here around)
If this line is correct can I update my apps using a brew/cask command?
Sorry for the dumbs questions, I've just discovered brew and cask yesterday :)
Any suggestion or example for this script is well accepted :)

A: brew cask install <formula> is supposed to symlink your app in Applications automatically.


Q: how can I add admonition in angular-markdown-editor Directive How can I add admontiton in markdown editor.
like this.
https://python-markdown.github.io/extensions/admonition/


Q: How could I select a column based on another column in mySQL? The following script works fine. But I want to write it in one line rather than three lines. 'Size" is passed from my main program and its used here to test. Simply I want to get Price based on size.
Table columns :
LISTING_ID, PRICE_LARGE_PRICE, PRICE_SMALL_PRICE.
SET @Size = 'SMALL';

SELECT
    PRICE_LARGE_PRICE,PRICE_SMALL_PRICE
INTO
    @PRICE_LARGE_PRICE,@PRICE_SMALL_PRICE
FROM
    prices
WHERE
    PRICE_LISTING_ID = 60;

SET @ITEM_PRICE = (CASE @Size WHEN 'REGULAR' THEN @PRICE_LARGE_PRICE
WHEN 'SMALL' THEN @PRICE_SMALL_PRICE
ELSE null
END);

SELECT @ITEM_PRICE;

Any help is appreciated.

A: I think you want
SELECT
  IF(@size == 'SMALL', PRICE_SMALL_PRICE, PRICE_LARGE_PRICE) AS ITEM_PRICE
FROM prices;

A: Following may work.
SET @Size = 'SMALL';

SELECT
    PRICE_LARGE_PRICE,
    PRICE_SMALL_PRICE,
    CASE WHEN @Size = 'REGULAR' THEN PRICE_LARGE_PRICE
         WHEN @Size = 'SMALL' THEN PRICE_SMALL_PRICE
    END AS ITEM_PRICE
INTO
    @PRICE_LARGE_PRICE,
    @PRICE_SMALL_PRICE,
    @ITEM_PRICE
FROM
    prices
WHERE
    PRICE_LISTING_ID = 60;


Q: Вывод части записей и довывод остальных при прокрутке Вывод определенного количества записей, а при прокрутке страницы вниз - вывод остальных. На примере аудиозаписей, друзей, новостей и прочего в контакте. Как такое же можно сделать?
Я вывел из базы допустим 20 записей, а чтобы при прокрутке вниз выводились по очереди остальные.
A: Реализация довольно проста,

*

*Отлавливаете событие onscroll у окна

*Проверяете, находиться ли пользователь внизу страницы

*Если да, то загружаете посредством ajax доп. контент

С jquery получиться что-то вроде:
var page = 1; //Счетчик загруженых данных
$(window).scroll(function()
{
     if  ($(window).scrollTop() == $(document).height() - $(window).height())
     {
          //Пользователь внизу страницы, подгружаем контент
          page++;
          $.ajax({
              type: "GET",
              cache: false,
              url: '[ПУТЬ]?page=' + page,
              success: function(data) {
                   $('#container').append(data);
              }
          }
      }
});


Q: How to run multiple locusts each with different parameters? I am trying to load our online gaming platform which has many games in it that can be accessed/played via RESTful endpoints.
I want to use locust to simulate players where each player plays a certain kind of a game. I want to have a player locust class something like:
class Player(HttpLocust):
    def __init__(self, host, config, delay_between_plays):
        super().__init__()
        self.task_set = Game(config)
        self.wait_time = delay_between_plays
        self.host = host

My game taskset is like this:
class Game(TaskSet):
    def __init__(self, config, parent):
        super().__init__(parent)
        self.config = config

    @task
    def play(self):
        ...
        ...

I don't see anywhere in docs where it mentions how to do this. Would appreciate some inputs.


Q: Changing welcome screen of Nginx Hi i have setup nginx  and works fine. I have added some config to accept the subdomain and that is also working fine no problem. My major concern is i have a meteor app that takes the username and creates nginx subdomain config in the fly. and currently i have listed * in my A/AAAA record in server so it accepts all subdomain. now i wanna show different view if the user request the subdomain that is not created in nginx config.
for eg,
i have setup subdomain A,B in nginx config pointing different application
A.example.com //works fine
B.example.com //works fine
if i Enter
C.example.com // shows me welcome to nginx screen
I wanna show my custom page there
Thanks in advance

A: This has nothing to do with Meteor, rather it is about setting up your nginx's default page. Try the below links
http://gpiot.com/blog/setup-default-server-landing-page-with-nginx/
NGinx Default public www location?


Q: Como executar SQL com Entity Framework? Tentei executar um comando SQL pelo Entity Framework, tentei das seguintes formas:
string cmd = "UPDATE t0071_compra SET t0071_status = 'Enviado' WHERE t0071_id_compra = 4 AND t0020_id_empresa = 1";
context.Database.SqlQuery<string>(cmd);
context.SaveChanges();

string cmd = "UPDATE t0071_compra SET t0071_status = 'Enviado' WHERE t0071_id_compra = 4 AND t0020_id_empresa = 1";
context.Database.ExecuteSqlCommand(cmd);
context.SaveChanges();

mas em nenhum das formas funcionou, estou usando Mysql, o que esta errado ai?

A: Se você deseja executar um comando que não retorna resultados (não é um SELECT)
basta utilizar DbContext.Database.ExecuteSqlCommand, onde DbContext é o seu contexto.
Não é necessário utilizar o método SaveChanges neste caso, porque o comando já irá executar diretamente no banco e não irá afetar as entidades do EF no contexto.
Lembrando que depois de executar o comando desta forma você precisa atualizar as entidades manualmente (via DbContext.Entry(entity).Reload();) caso deseje utilizar os valores atualizados no mesmo lifecycle da aplicação (ou seja, antes de descartar e reiniciar o contexto)
Seguem alguns links falando sobre:

*

*https://msdn.microsoft.com/en-us/library/jj592907(v=vs.113).aspx

*https://stackoverflow.com/questions/9081244/reload-an-entity-and-all-navigation-property-association-dbset-entity-framework


Q: SWT incorrectly detects key combinations I have two languages on my Windows 10 (english and russian). I run the following code snippet:
public static void main(String[] args) throws Exception {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setSize(640, 480);
    shell.setLocation(500, 250);
    shell.setText("SWT");

    FillLayout layout = new FillLayout();
    shell.setLayout(layout);

    shell.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            List<String> keys = new ArrayList<>();
            if ((e.stateMask & SWT.CTRL) != 0) {
                keys.add("Ctrl");
            }
            if ((e.stateMask & SWT.ALT) != 0) {
                keys.add("Alt");
            }
            if ((e.stateMask & SWT.SHIFT) != 0) {
                keys.add("Shift");
            }
            keys.add(Character.toString((char) e.keyCode));
            System.out.println(keys);
        }
    });

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }

    display.dispose();
}

When the language is set to english and I press Right Alt + T, the program correctly prints [Alt, t].
However, when I switch the language to russian and press Right Alt+T, the program prints [Ctrl, Alt, t]. This is incorrect because I didn't press Ctrl.
This is annoying because our Eclipse RCP key bindings (such as Alt+F7 or Alt+Shift+F5) do not work correctly.
Any ideas why SWT incorrectly detects Ctrl?
I'm using SWT from the latest Eclipse 4.6 (SWT 3.105.0).

A: For historical reasons, the AltGr (right Alt) key used in non-US keyboard layouts is automatically converted by the operating system as Ctrl + Alt (see Wikipedia about this).
So this is not specifically related to SWT.
To avoid this problem users should just use the standard Alt (left Alt) key.

A: Have you tried disabling shortcut to change language in windows 10.


Q: Working within FME and trying to snap newly created line features together within a certain distance of each other I have two features, a point feature (addresses) and a line feature (fiber). My end goal is to create a new line feature from the point to the nearest spot on the existing line. I have that process figured out but now I am wanting to fine tune it a bit which is where I am stuck. Currently, it will "snap" the new lines within feet of each other on the existing line and I would like to get it set so that if the new lines snap point is within a certain distance, they snap together at a single spot on the existing span. I have attached a screen capture of my current work flow for reference. I feel like I need another CoordinateExtractor + AnchoredSnapper but my attempts with those aren't returning what I am hoping to do. I have also tried using the plain Snapper but not getting the outcome I wanted.
I am new to FME.


Q: JAXB serializer from java objects to xml I'm a newbie of XML programming, I'm trying to write some java objects to a well formed and valid XML file (with respect to a DTD file),
I found out that I can do this kind of things using JAXP with Java.
My application is going to retrieve some data using an interface, and then I need to write that data into an XML file with respect of a DTD I previously and already created.
I tried to find some informations about this operations but I failed.
How am I supposed to do this operation?
EDIT: Please note that I need to stick with DTD (Can't switch to a XML schema) and that I need to go FROM Java Objects TO XML, and not viceversa.
I found that the Duplicated Answer is not applying for my question.
Don't know if the DTD can be of any help, but here it is.
DTD
<!ELEMENT AIRCRAFTS (AIRCRAFT+)>
<!ELEMENT AIRCRAFT (MODEL, SEATS)>
<!ELEMENT MODEL (#PCDATA)>
<!ELEMENT SEATS (SEAT+)>
<!ELEMENT SEAT (#PCDATA)>

<!ELEMENT FLIGHTS (FLIGHTREADER+)>
<!ELEMENT FLIGHTREADER (DEPARTURE, TIME, DESTINATION)>
<!ELEMENT DEPARTURE (#PCDATA)>
<!ELEMENT TIME (HOUR, MINUTE)>
<!ELEMENT HOUR (#PCDATA)>
<!ELEMENT MINUTE (#PCDATA)>
<!ELEMENT DESTINATION (#PCDATA)>

<!ELEMENT FLIGHTINSTANCES (FLIGHTINSTANCEREADER+)>
<!ELEMENT FLIGHTINSTANCEREADER (AIRCRAFTID, DATE, DELAY, DEPARTUREGATE, FLIGHTREADERID, PASSENGERREADER+, STATUS)>
<!ELEMENT AIRCRAFTID (#PCDATA)>
<!ELEMENT DATE (#PCDATA)>
<!ELEMENT DELAY (#PCDATA)>
<!ELEMENT DEPARTUREGATE (#PCDATA)>
<!ELEMENT FLIGHTREADERID (#PCDATA)>
<!ELEMENT PASSENGERREADER (NAME, FLIGHTINSTANCEID, SEATID, BOARDED)>
<!ELEMENT FLIGHTINSTANCEID (#PCDATA)>
<!ELEMENT BOARDED (#PCDATA)>
<!ELEMENT NAME (#PCDATA)>
<!ELEMENT SEATID (#PCDATA)>
<!ELEMENT STATUS (#PCDATA)>

<!ATTLIST FLIGHTINSTANCEREADER id ID #REQUIRED>
<!ATTLIST FLIGHTREADER id ID #REQUIRED>
<!ATTLIST AIRCRAFT id ID #REQUIRED>

A: It's basically the same way to convert Java Object to XML with JAXBContext and Marshaller with an addition of validation the XML validation with DTD.
See the sample code:
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();

    JAXBContext jc = JAXBContext.newInstance("blog.log4j");
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler();
    xr.setContentHandler(unmarshallerHandler);

    FileInputStream xmlStream = new FileInputStream("src/blog/log4j/sample1.xml");
    InputSource xmlSource = new InputSource(xmlStream);
    xr.parse(xmlSource);

    Log4JConfiguration config = (Log4JConfiguration) unmarshallerHandler.getResult();

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(config, System.out);

Source.

A: First you need to serialize object to xml, then you need validate id against dtd.
Here
you have example how to serialzie classes to xml.
This one shows how to validate xml file with dtd that is outside or inside xml file.


Q: Pcretest seems to be gone from libpcre3 package pcretest in 11.04 seems to be missing from libpcre packages and I can't seem to find where it went off to.  I kind of love using it to test regular expressions. Where did it go?

A: It was dropped in version 8.12-3ubuntu1:
pcre3 (8.12-3ubuntu1) natty; urgency=low

  * FFe LP: #733501
  * Drop pcretest from the libpcre3 package, to allow for correct
    coinstallability.
  * Build for multiarch, pre-depending on multiarch-support.

 -- Steve Langasek <steve.langasek@ubuntu.com>  Thu, 17 Mar 2011 11:05:43 -0700

The relevant commit can be found here.
The file is still available in Maverick's package.
Other than using older builds (discouraged) or building it from source, I suggest you to fill a bug against the pcre3 source package.


Q: Make radio buttons Sorry for this question, but is it possible to make radio buttons instead of select list from this piece of code?
function _nodereview_form_review(&$form, $axis, $node) {
  static $options;
  if (!isset($options)) {
    $options = array(
    20 => -2,
    40 => -1,
    60 => 0,
    80 => 1,
    100 => 2,
    );
 }

$form['reviews'][$axis->aid] = array(
  '#type' => 'fieldset',
  '#title' => $axis->tag,
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
);

$form['reviews'][$axis->aid]['score'] = array(
  '#type' => 'select',
  '#title' => t('Score'),
  '#options' => $options,
  '#default_value' => $node->reviews[$axis->aid]['score'] ? $node->reviews[$axis->aid]['score'] : 50,
  '#description' => $axis->description,
  '#required' => TRUE,
);

if (NODEREVIEW_FIVESTAR_ENABLE) {
  $form['reviews'][$axis->aid]['score']['#type'] = 'fivestar';
  $form['reviews'][$axis->aid]['score']['#stars'] = variable_get('nodereview_fivestar_stars', 5);
}

$form['reviews'][$axis->aid]['review'] = array(
  '#type' => 'textarea',
  '#title' => t('Review'),
  '#default_value' => $node->reviews[$axis->aid]['review'],
  '#required' => TRUE,
);
}

I know that '#type' => 'select' should be '#type' => 'radio', but something else also should be changed. I don't know what exactly.
Any suggestions are gratefully accepted.

A: Well, for starters, the #options will need to be converted to the value for each radio button. You'll also probably need to add labels for each button as well.


Q: How to do something at the end of a Youtube video I'm currently launching a Youtube video using this piece of code:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://"+token));
activity.startActivityForResult(intent, SmartBrowserWebViewActivity.ACT_YOUTUBE);

It works great. But I would like at the end of the video play to get the capability to do what I want. For example how to change activity when the video is over ?
Currently the user has to click back and I can handle it through the onActivityResult, but is there a way to avoid the user click on "back"?
Maybe I should play flash video to do it or HTML5 video ?
Thank you!

A: Implement and OnCompletionListener. Here is an example of my code. It should work the same as a RAW file video.
 final VideoView vs = (VideoView) findViewById(R.id.imlsplash);
// Set video link (mp4 format )
Uri video = Uri.parse("android.resource://"+getPackageName() +"/" +R.raw.iphonesplashfinal);
vs.setVideoURI(video);
vs.requestFocus();
vs.start();
vs.setOnCompletionListener(new OnCompletionListener(){
    @Override
    public void onCompletion(MediaPlayer mp) {

        startActivity(new Intent(CurrentActivity.this, NextActivity.class));
                CurrentActivity.this.finish();
}
});
}

you may have to replace the videoView with whatever you are using.
If you are using a URL change URI to URL and add URL in place of    "android.resource://"+getPackageName() +"/" +R.raw.iphonesplashfinal


Q: How to kill running Ports using Linux Console? In my scenario I am try to run Django code using
~$ python manage.py runserver command. While  running it, I get:

port 8000 already running

How can I kill the running process of port number?

A: This is the command which I used to kill the process of running port number 8000:
~$ sudo fuser -k 8000/tcp

Its working perfectly...


Q: Smart shell script to search for text in file name with error handling I am trying to get a shell script built with some error handling but I have limited knowledge. I am searching for any files with a string say tests in it. However if this string is found I would to report an error. I can use the find . -name "*tests*" -print to list the files that contain the string but how do I list the file then report an error in the output if there are results, if it's null then it passes?
Thanks

A: The manual page has this to say:

find exits with status 0 if all files are processed
  successfully, greater than 0   if  errors occur.
  This is deliberately a very broad
  description, but if the return value is non-zero,
  you should  not  rely
  on the correctness of the results of find.

This is a bit of a conundrum, but if you can be reasonably sure that there will be no unrelated errors, you could do something like
find . -name '*tests*' -print -exec false \;

If you want the list of found files on standard error, add a redirection >&2


Q: In angular form how to get an array of Client object and use the id value as a value in a form group's member We have an API POST method called CreateEvent(obj) that takes an object. One of the properties in the object is an int ClientId
We have a GET method called GetClients() that returns the list of Client objects in the database.
In our angular reactive form's ts and html we want to be able to have a dropdown with the returned array of the GetClients. Like so: {{clnt.id}} - {{clnt.FirstName}} {{clnt.LastName}}.
How would I go about mapping the selected clnt.id value to the form's ClientId value.
You might be able to see the idea I have so far with the code below:
<select [(ngModel)]="clientsClone" formControlName="clientId" (change)="doSomething()">
<option *ngFor="let clnt of clientsClone"  [ngValue]="clnt.id">{{clnt.id}} - {{clnt.pointOfContact}} </option>
</select>

A: having the [{ngModel}] in there was bad.
the code below allowed me to make it so that: 'clientsClone' is an array of objects returned from the server and the [value]="clnt.id" with the formControlName="clientId" lets me say "hey this id int is what you need for that form's value!"
code here:
<select formControlName="clientId" (change)="onOptionsChanged(2)">
<option *ngFor="let clnt of clientsClone" [value]="clnt.id">{{clnt.id}} - {{clnt.pointOfContact}} </option>
</select>


Q: Is it possible to convert this Delphi function to a C# Method? and How? I have been working on a conversion from Delphi to C#.  This is not normally something I deal with. So, I come here humbly to ask for some help.
Here is what I have so far:
Delphi code:
program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  Console in 'Console.pas';

const
  CKEY1 = 11111;
  CKEY2 = 22222;
function EncryptStr(const s: WideString; Key: word): String;
var
  i: integer;
  RStr: RawByteString;
  RStrB: TBytes Absolute RStr;
begin
  Result := '';
  RStr := UTF8Encode(s);
  for i := 0 to Length(RStr) - 1 do
  begin
    RStrB[i] := RStrB[i] xor (Key shr 8);
    Key := (RStrB[i] + Key) * CKEY1 + CKEY2;
  end;
  for i := 0 to Length(RStr) - 1 do
  begin
    Result := Result + IntToHex(RStrB[i], 2);
  end;
end;

function DecryptStr(const s: String; Key: word): String;
var
  i, tmpKey: integer;
  RStr: RawByteString;
  RStrB: TBytes Absolute RStr;
  tmpStr: string;
begin
  tmpStr := UpperCase(s);
  SetLength(RStr, Length(tmpStr) div 2);
  i := 1;
  try
    while (i < Length(tmpStr)) do
    begin
      RStrB[i div 2] := StrToInt('$' + tmpStr[i] + tmpStr[i + 1]);
      Inc(i, 2);
    end;
  except
    Result := '';
    Exit;
  end;
  for i := 0 to Length(RStr) - 1 do
  begin
    tmpKey := RStrB[i];
    RStrB[i] := RStrB[i] xor (Key shr 8);
    Key := (tmpKey + Key) * CKEY1 + CKEY2;
  end;
  Result := UTF8Decode(RStr);
end;

var myEncrypted: string;
begin
  try
    myEncrypted := EncryptStr('TheTestString', 4444);
    WriteLn('Encrypted: '+myEncrypted);
    ExitCode := 1;
    Console.WaitAnyKeyPressed('Press any key to continue ...');
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Part of the reason I am putting this out here is that this code originated here (not mine) delphi-simple-string-encryption.
Here is what I have attempted thus far:
C# code:
private const int CKEY1 = 11111;
private const int CKEY2 = 22222;
public static string EncryptAString(string s, int Key)
{
    try
    {
        var encryptedValue = string.Empty;
        // Create a UTF-8 encoding.
        UTF8Encoding utf8 = new UTF8Encoding();
        // Encode the string.
        byte[] RStrB = utf8.GetBytes(s);

        for (var i = 0; i <= RStrB.Length - 1; i++)
        {
            RStrB[i] = Convert.ToByte(RStrB[i] ^ (Key >> 8));
            Key = (RStrB[i] + Key) * CKEY1 + CKEY2;
            //I have a problem right here. See screen shot for values
        }
        for (var i = 0; i <= RStrB.Length - 1; i++)
        {
            encryptedValue = encryptedValue + RStrB[i].ToString("X2");
        }
        return encryptedValue;
    }
    catch (Exception)
    {
        throw;
    }
}

Delphi

C#

The C# code ultimately gives this error:
Error:

System.OverflowException: Value was either too large or too small for
  an unsigned byte.    at System.Convert.ToByte(Int32 value)    at
  ChronicleConvertText.Program.EncryptAString(String s, Int32 Key) in
  C:\Users\todd7\source\repos\ChronicleConvertText\ChronicleConvertText\Program.cs:line
  70    at ChronicleConvertText.Program.Main(String[] args) in
  C:\Users\todd7\source\repos\ChronicleConvertText\ChronicleConvertText\Program.cs:line
  17

In the process of researching this a few things came into focus.

*

*In Delphi the I have this warning: [dcc32 Warning] Project1.dpr(58): W1000 Symbol 'UTF8Decode' is deprecated: 'Use UTF8ToWideString or UTF8ToString'. Bear in mind this is in use existing code. So, I have not looked directly at what if any impact switching to 'UTF8ToWideString or UTF8ToString' would have. My job as this point is to see if I can duplicate it if possible.

*Another issue is this: hazards-of-converting-binary-data-to-a-string.

I suspect that this may be my lack of understanding of what is going on in the "xor" in Delphi verses "^" in C#. The main question remains can this be done? and How?  Thanks for any assistance.

A: Your constants CKEY1 and CKEY2 and argument Key have int type. So expression
Key = (RStrB[i] + Key) * CKEY1 + CKEY2;

is calculated using 32-bit values. For example:
(4444 + 84) * 11111 + 22222 = 50 332 830

is close to your shown value, isn't it?
Delphi code uses 16-bit unsigned variables and corresponding arithmetics, C# equivalent for Delphi word is ushort

A: Here is what I ended up with:
    private const short CKEY1 = 11111;
    private const short CKEY2 = 22222;
    public static string EncryptAString(string s, ushort Key)
    {
        try
        {
            var encryptedValue = string.Empty;
            // Create a UTF-8 encoding.
            UTF8Encoding utf8 = new UTF8Encoding();
            // Encode the string.
            byte[] RStrB = utf8.GetBytes(s);

            for (var i = 0; i <= RStrB.Length - 1; i++)
            {
                RStrB[i] = Convert.ToByte(RStrB[i] ^ (Key >> 8));
                Key = (ushort)(((RStrB[i] + Key) * CKEY1) + CKEY2);
            }
            for (var i = 0; i <= RStrB.Length - 1; i++)
            {
                encryptedValue = encryptedValue + RStrB[i].ToString("X2");
            }
            return encryptedValue;
        }
        catch (Exception)
        {
            throw;
        }
    }

Tested against the Delphi code and it works marvelously.


Q: Are there different types of race conditions? I know there are data races, can other race conditions be broken down into distinct categories?
Ultimately all race conditions are due to data being accessed in the wrong order, therefore leading threads to misbehave, but data races are a very specific case where data is read, changed, and written all at once, correct?
What else can cause a race condition?

A: Threading problems can be categorized like this:
Correctness (nothing bad happens)

*

*race condition

Liveness (something good happens eventually)

*

*deadlock

*starvation

*livelock

I do not know of a further categorization of race conditions.
A data race is a more lower level problem and happens if you have conflicting memory accesses (so at least one of them is a write) on the same memory location and these are not ordered by a happens before relation. Data races are part of memory models like the Java Memory Model and that of C++ 11. A race condition and a data race are different types of problems.


Q: setInterval, clearInterval, setTimeout conflict messing up slideshow I've got a slideshow that autoplays on document.ready by triggering my left arrow click on setInterval. I'm trying to stop the autoplay when the nav arrows are clicked, while still allowing the arrows to navigate the slides.
This accomplishes that.
var intervalId = window.setInterval(switchLeft, 4000);

$("#leftarrow, #rightarrow").click(function() {
    window.clearInterval(intervalId);
});

But I want the autoplay to kick back in if the arrows haven't been clicked in 8 seconds. I have tried turning the setInterval back in by adding this setTimeout into the click function, but it counts all the clicks of user navigation during the pause and starts throwing my slides around like crazy. (I've got two layers of images moving on every click.)
setTimeout(function() {
  intervalId = window.setInterval(switchLeft, 4000)
}, 8000);

I've tried wrapping stuff in a setTimeout function but I just end up getting different weirdness.
Thanks for any help,
Charlie Magee

A: You need to cancel the setTimeout() if the arrows are clicked before it fires so you don't get multiple timers going at once (which will certainly exhibit weirdness).
I don't follow exactly what you're trying to do on the arrows, but this code should manage the timers:
var intervalId = setInterval(switchLeft, 4000);
var timeoutId;

$("#leftarrow, #rightarrow").click(function() {

    // clear any relevant timers that might be going
    // so we never get multiple timers going
    clearInterval(intervalId);
    clearTimeout(timeoutId);

    // restart the interval in 8 seconds
    timeoutId = setTimeout(function() {
        intervalId = window.setInterval(switchLeft, 4000)
    }, 8000);
});


Q: Deny acess to file-shares (SMB)? There are security policies like:

*

*Deny logon locally

*Deny logon on through Remote Desktop Services

*Deny access this computer from network

Is there any policy to deny specific users/groups to access a file-share? It means deny only file-access (SMB share), and nothing else. Hence, I wouldn't want to use any of above' deny policies. As far as share-level and NTFS permissions are concerned, I am pretty aware how to setup. I would like to deny particular user/group to access any share, even if Everyone is allowed to access the shared resource.


Q: Ubuntu 22.10 fresh install error message on inspiron 5310 I have a fresh install like the title said. I wiped all the disk and using a swap partition. I had the same problem with just one partition. I already know that the clean message is just to indicate boot fast disk check-up, that the dev loop0 is related to Snap Store so it's nothing to worry about. But both the PCI, spi-nor and dell_smm_hwmon are bothering me since I can't find related information. I don't have any Nvidia hardware and packages. It's an Inspiron 13 5310 with a i7-11390H . Disk mode are in NVMe , disable the smm security too in BIOS. The system boot and work correctly, but those messages seem like something is wrong behind the curtain.


Q: Interesting sum Hi could you demostrated that
$$\sum _{m=1}^{\infty } (-1)^{m+1} \log (\Gamma (m+1))=\frac{1}{4} \log \left(\frac{2}{\pi }\right)$$ and
$$\sum _{m=1}^{\infty } \log (\Gamma (m+1))=\log \left((2 \pi )^{3/4} A\right)-\frac{3}{4}$$
I know this series are divergent.

A: The sum can have the following integral representation

$$\sum _{m=1}^{\infty } (-1)^{m+1} \log (\Gamma (m+1))=-\frac{1}{4}\,\int _{0}^{1}\!{\frac {u\ln  \left( u \right)+\ln  \left( u
 \right) -2\,u+2}{\ln  \left( u \right)  \left( {u}^{2}-1 \right) }}{d
u}-\frac{\gamma}{4}\sim -.1128956763. $$

where $\gamma$ is the Euler constant.


Q: Databricks - Reduce delta version compute time I've got a process which is really bogged down by the version computing for the target delta table.
Little bit of context - there are other things that run, all contributing uniform structured dataframes that I want to persist in a delta table. Ultimately these are all compiled into lots_of_dataframes to be logged.
for i in lots_of_dataframes:
    i.write.insertInto("target_delta_table")
    # ... take a while to compute version

I've got in to the documentation but couldn't find any setting to ignore the version compute. I did see vacuuming, but not sure that'll do the since there will still be a lot of activity in a small window of time.
I know that I can union all of the dataframes together and just do the insert once, but I'm wondering if there is a more Databricks-ian way to do it. Like a configuration to only maintain 1 version at a time and not worry about computing for a restore.

A: Most probably, but it's hard to say exactly without details, the problem arise from the following facts:

*

*Spark is lazy - the actual data processing doesn't happen until you perform action, like writing data into a destination table. So if you have a lot of transformations, etc., they will happen when you're writing data.

*You're writing data in the loop - you can potentially speedup it a bit by doing a union of all tables into a single dataframe, that will be written into one go:
import functools
unioned = functools.reduce(lambda x,y: x.union(y), lots_of_dataframes)
unioned.write.insertInto("target_delta_table")


Q: overloading primitive variables code is
public class TestOverload {

    public static void print(Float f, double d) {
        System.out.println("Float,double");
    }

    public static void print(float f, double d) {
        System.out.println("float,double");
    }

    public static void print(int f, double d) {
        System.out.println("int,double");
    }
//  public static void print(int f, float d) {
//      System.out.println("int,float");
//  }

    public static void print(double d1, double d) {
        System.out.println("double,double");
    }

    public static void print(float d1, float d) {
        System.out.println("float,float");
    }

    public static void main(String[] args) {
        TestOverload.print(2, 3.0);

        TestOverload.print(2, 3.0f);//Compiler error:The method print(float, double) is ambiguous for the type TestOverload
    }
}

why it is giving error , instead it should pick print(float d1, float d)
PS:
in the above code,if i comment :
//  public static void print(int f, double d) {
//      System.out.println("int,double");
//  }

then print(float d1, float d) is called...

A: print(2, 3.0f);

Could be both print(int, float) and print(float, double) since implicit type conversions are done in the backgound. An int can be converted to a float. Javac (or the compiler) cannot know for sure which one you meant.
If you want to choose for your self you can add casts:
print((float) 2, (float) 3.0f);

(Note that the second cast (float => float) isn't necessary.)


Q: Not reading utf-8 marks I have a .txt file on my sdcard with utf-8 marks e.g.:
"Jak przetrwać wśród czarnych dziur"
And this is how I try to read them from this file:
public static void readBooksFromTxtFile(Context context, String filePath, ArrayList<SingleBook> books) {
    BufferedReader in;
    try {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
        String line = null;
        while ((line = in.readLine()) != null) {
            String title = line;
            String author = in.readLine();
            String pages = in.readLine();
            String date = in.readLine();

            // just for debugging
            System.out.println(title);

            books.add(new SingleBook(title, author, pages, date));
        }
    } catch (Exception e) {
        Toast.makeText(context, "Error during reading file.", Toast.LENGTH_LONG).show();
        return;
    }
}

But it doesn't read the file correctly:

What am I doing wrong?

A: I believe your issue is here:
in = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));

Instead it should be
in = new BufferedReader(new FileReader(new File(filePath));

This should read it correctly. If not, you can just use RandomAccessFile:
public static void readBooksFromTxtFile(Context context, String filePath, ArrayList<SingleBook> books) {
RandomAccessFile in;
try {
    in = new RandomAccessFile(new File(filePath), "r");
    String line = null;
    while ((line = in.readUTF8()) != null) {
        String title = line;
        String author = in.readUTF8();
        String pages = in.readUTF8();
        String date = in.readUTF8();

        // just for debugging
        System.out.println(title);

        books.add(new SingleBook(title, author, pages, date));
    }
} catch (Exception e) {
    Toast.makeText(context, "Error during reading file.", Toast.LENGTH_LONG).show();
    return;
}
}


Q: tikz-uml reduce distance between timelines I created a sequence diagram with tikz-uml and I would like to reduce the distance between the involved entities.
I currently have:
\begin{tikzpicture}
\begin{umlseqdiag}
% Entities required for interaction
\umlactor[class=User]{user}
\umlobject[class=App]{app}
\umlobject[class=Script]{api}
\umlobject[class=Controller]{sessionCtrl}
% User creates a session
\begin{umlcall}[op=create(name), type=synchron, return=sessionView]{user}{app}
  % App posts session data to server
  \begin{umlcall}[op=create(name), type=synchron, return=sessionId]{app}{api}
    \begin{umlcall}[op=create(name), type=synchron, return=session]{api}{sessionCtrl}
    \end{umlcall}
  \end{umlcall}
  % App navigates to new session
  \begin{umlcall}[op=open(id), type=synchron, return=session]{app}{api}
  \end{umlcall}
\end{umlcall}
\end{umlseqdiag}
\end{tikzpicture}

and it creates the following the result:

How can I reduce the distance between the objects to make it fit the page?

A: Been struggling with that, you can define the x coordinate like this:
\umlobject[x=12, class=Controller]{sessionCtrl}

Use option x on the object you are creating, that will do the trick!


Q: Visual C++: ATL Implementation of an Interface I guess this is a real dumb question, but I couldn't find an answer. I'm trying to implement an COM interface using ATL. According to this I should use the Implement Interface Wizard. My question is how can I find the desired interface in this wizard. Do I have to go over all the libraries? Does is specified somewhere in the documentation of the interface (IOleCommandTarget)

A: To implement an interface you need:

*

*inherit your class from it

*add it onto interface map

*implement its methods

For example:
class CFoo :
  // regular COM object base class, esp. those generated by ATL Simple Object Class Wizard
  public IOleCommandTarget
{

BEGIN_COM_MAP(CFoo)
  // ...
  COM_INTERFACE_ENTRY(IOleCommandTarget)
END_COM_MAP()

// ...

public:
// IOleCommandTarget
  STDMETHOD(Exec)(...) // IOleCommandTarget methods go here
  {
    // ...
  }
};

A: To implement you need to do:

*

*In the *h file let your CoClass inherit from interface.

2.In the *h file ,add an interface entry in the COM Map.
In the *h file ,add the prototype of interface methods.
In the *cpp file, implement the method of interface.


Q: VBScript Search Excel Workbook for Value from another Workbook I am new to VB scripting, so please, bear with me!  I am trying to create a script that uses worksheets from two different excel workbooks.  It opens the first worksheet and iterates through a specified range.  I want it to then take the value of each cell in that range and search the second worksheet (in a different workbook) and search for the value that was found in the first worksheet, and if the value is found, return the address of the cell it was found in.  For example:
Worksheet1
╔══════╦═════╗
║ Name ║ Age ║
╠══════╬═════╣
║ Matt ║  22 ║
║ Jeff ║  13 ║
╚══════╩═════╝

Worksheet2
╔═══════╦════════════╗
║ Name  ║    DOB     ║
╠═══════╬════════════╣
║ Dave  ║ 09/12/2001 ║
║ Frank ║ 01/25/1992 ║
║ Jeff  ║ 10/10/2013 ║
╚═══════╩════════════╝

So the script would output: A4
Because it found one of the values from the specified range (A2:A3) of the first worksheet in the second worksheet and is returning the location of that cell.
Here is the code I have:
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True

Dim val

Set objWorkbook = objExcel.Workbooks.Open("C:\Users\username\file.xlsx")
Set objWorksheet = objWorkbook.Worksheets("Sheet1")

Set objWorkbook2 = objExcel.Workbooks.Open("C:\Users\username\file2.xlsx")
Set objWorksheet2 = objWorkbook2.Worksheets("Sheet1")

For Each c In objworksheet.Range("A2:A3").Cells
    val = c.value
    Set objRange = objWorksheet2.UsedRange
    Set found = objRange.Find(val)
    Wscript.Echo found.AddressLocal(False,False)
Next

When I run this code, I get the following error:

Error: Object required: 'found'

I am sure there is something obvious I am missing here but I have been spinning my wheels for quite some time and was hoping someone could provide some feedback.  Any help is greatly appreciated!

A: The Find() function returns a Range object if successful or Nothing if not. So you need to test the return value to ensure it's a Range object before you try accessing its properties and methods.
For Each c In objworksheet.Range("A2:A3").Cells
    val = c.value
    Set objRange = objWorksheet2.UsedRange
    Set found = objRange.Find(val)

    ' Test for success!
    If Not found Is Nothing Then
        Wscript.Echo found.AddressLocal(False,False)
    End If
Next


Q: Best way to unset a flag in C when using Enum that is signed I'm trying to use enum in C to create a flags variable, as discussed here: Flags, enum (C)
How should I reset a single enum flag, when the compiler represents the enum as signed?
Problem:
Say I declare my flags type like this:
typedef enum {
     FLAGS_A = 1 << 0,
     FLAGS_B = 1 << 1,
     FLAGS_C = 1 << 2,
     FLAGS_D = 1 << 3
} flags_t;

flags_t flags;

I would like to reset a flag like this:
flags |=   FLAGS_A;   // Set A
flags &= (~FLAGS_A);  // Reset A

However the compiler (Microchip XC8 Compiler V2.32) throws an error because bitwise operators should only be used on unsigned types. It looks like the enum is actually a signed integer under the hood.
Based on this question, it looks like there's no good way to force the compiler to use unsigned for enum: Is there a way to make an enum unsigned in the C90 standard? (MISRA-C 2004 compliant)
Things I've Tried:
One workaround I found was to add a special enumerated variable that has all the other flags set. I can use that as a mask to reset flag A:
typedef enum {
     ....
     FLAGS_RESET_A  = (FLAGS_B | FLAGS_C | FLAGS_D)
} flags_t

flag_t flags &= (FLAGS_RESET_A);  // Reset A

This workaround is cumbersome. Any time I modify the flags type, such as adding a flag, I also have to remember to modify all the reset masks. I'm hoping there is a method that preserves the enum as a "single source of truth" for the flag definitions.
Another workaround is type casting to an unsigned integer, but that defeats the safety of using an enumerated type.


Q: How to get time difference between two ZonedDateTimes and pretty print it like "4 hours, 1 minute, 40 seconds ago"? This is how I call getTimeBetween function:
getTimeBetween(ZonedDateTime.now().minusHours(4).minusMinutes(1).minusSeconds(40), ZonedDateTime.now());

And I expect this output:
4 hours, 1 minute, 40 seconds ago

This is my getTimeBetween function:
private String getTimeBetween(ZonedDateTime zonedDateTime1, ZonedDateTime zonedDateTime2) {
    Duration timeDifference = Duration.between(zonedDateTime1, zonedDateTime2);
    if (timeDifference.getSeconds() == 0) return "now";
    String timeDifferenceAsPrettyString = "";
    Boolean putComma = false;
    if (timeDifference.toDays() > 0) {
        if (timeDifference.toDays() == 1) timeDifferenceAsPrettyString += timeDifference.toDays() + " day";
        else timeDifferenceAsPrettyString += timeDifference.toDays() + " days";
        putComma = true;
    }
    if (timeDifference.toHours() > 0) {
        if (putComma) timeDifferenceAsPrettyString += ", ";
        if (timeDifference.toHours() == 1) timeDifferenceAsPrettyString += timeDifference.toHours() + " hour";
        else timeDifferenceAsPrettyString += timeDifference.toHours() % 24 + " hours";
        putComma = true;
    }
    if (timeDifference.toMinutes() > 0) {
        if (putComma) timeDifferenceAsPrettyString += ", ";
        if (timeDifference.toMinutes() == 1) timeDifferenceAsPrettyString += timeDifference.toMinutes() + " minute";
        else timeDifferenceAsPrettyString += timeDifference.toMinutes() % 60 + " minutes";
        putComma = true;
    }
    if (timeDifference.getSeconds() > 0) {
        if (putComma) timeDifferenceAsPrettyString += ", ";
        if (timeDifference.getSeconds() == 1) timeDifferenceAsPrettyString += timeDifference.getSeconds() + " second";
        else timeDifferenceAsPrettyString += timeDifference.getSeconds() % 60 + " seconds";
    }
    timeDifferenceAsPrettyString += " ago";
    return timeDifferenceAsPrettyString;
}

This function works as expected but is it really necessary to do it like this? Perhaps there is a better way to achieve this?
I'm using Java 8.

A: How about this?
static String getTimeBetween(ZonedDateTime from, ZonedDateTime to) {
    StringBuilder builder = new StringBuilder();
    long epochA = from.toEpochSecond(), epochB = to.toEpochSecond();
    long secs = Math.abs(epochB - epochA);
    if (secs == 0) return "now";
    Map<String, Integer> units = new LinkedHashMap<>();
    units.put("day", 86400);
    units.put("hour", 3600);
    units.put("minute", 60);
    units.put("second", 1);
    boolean separator = false;
    for (Map.Entry<String, Integer> unit : units.entrySet()) {
        if (secs >= unit.getValue()) {
            long count = secs / unit.getValue();
            if (separator) builder.append(", ");
            builder.append(count).append(' ').append(unit.getKey());
            if (count != 1) builder.append('s');
            secs %= unit.getValue();
            separator = true;
        }
    }
    return builder.append(epochA > epochB ? " ago" : " in the future").toString();
}

You could probably store the LinkedHashMap instead of instantiating it every method call, but this should work.


Q: ios: Wrong image loading from php script In my app, I use a php script that redirects to an image. After I changed the picture on the server, the app on only one device continued to load the older picture. I don't save the picture locally anywhere, and I load the picture from the server every time. The right picture was loading correctly on other devices and after I deleted and re-built the app on my current device. What could have caused the problem?
my php code looks like this:

$userid = $_POST['userid'];

$query = "SELECT image FROM Users WHERE userid='$userid'";

$results = mysql_query($query);

$user = mysql_fetch_array($results);

$image = $user['image'];

header("Location:../profile_images/".$image);

A: Try something like this to do a force reload of the image. So every time the image is requested a new one will appear. Change your header like this.
header("Location:../profile_images/".$image."?".rand(1,3000));


Q: Given a sample of random variables, and n, how do I find the ecdf of the sum of n Xs? I can't fit X to a common distribution so currently I just have X ~ ecdf(sample_data).
How do I calculate the empirical distribution of sum(X1 + ... + Xn), given n? X1 to Xn are iid.

A: To estimate the distribution of that sum, you can repeatedly sample with replacement (and then take the sum of) n variates from sample_data. (sample() places equal probability mass on each element of sample_data, just as the ecdf does, so you don't need to calculate ecdf(sample_data) as an intermediate step.)
# Create some example data
sample_data <- runif(100)

n <- 10
X <- replicate(1000, sum(sample(sample_data, size=n, replace=TRUE)))

# Plot the estimated distribution of the sum of n variates.
hist(X, breaks=40, col="grey", main=expression(sum(x[i], i==1, n)))
box(bty="l")

# Plot the ecdf of the sum
plot(ecdf(X))

A: First, generalize and simplify: solve for step function CDFs X and Y, independent but not identically distributed. For every step jump xi and every step jump yi, there will be a corresponding step jump at xi+yi in the CDF of X + Y, So the CDF of X + Y will be characterized by the list:
sorted(x + y for x in X for y in Y)

That means if there are k points in X's CDF, there will be kn in (X1 + ... + Xn). We can cut that down to a manageable number at the end by throwing away all but k again, but clearly the intermediate calculations will be costly in time and space.
Also, note that even though the original CDF is an ECDF for X, the result will not be an ECDF for (X1 + ... + Xn), even if you keep all kn points.
In conclusion, use Josh's solution.


Q: How to load Notes for Projects in Salesforce I have notes in my Pipedrive tool for each deals. Now i need to migrate those notes for each deal in Pipedrive to my Salesforce. How can I get the notes for each project loaded to its corresponding project. I try loading notes by giving project ID through Data Loader Wizard. Even-though the tool says that the data is loaded successfully, When I go to my Project in Salesforce, I am not able to see the Notes for the project.
Please help.
Thanks
Niki


Q: hide tabs in Access 2010 with vba I'm using Access 2010 and I'd like to hide the tabs, when the person is not admin. My admin variable is stored Temp Variable.
How can I do that?
Best regards
Matthias

A: Hiding and showing the tabs (ie a tab for an open access object - ie a form, query, report, etc) is a setting for the current database project, that only takes effect once the database file is closed and re-opened.  Although the value can be set by code, it is not practical as it would apply to all users who then open the the file.  (and you would need to set it, close, repoen ...)
You might like to have two copies of the database front end file held on a server  with windows file permissions such that admin opens a different file to plebs, the admin file  shows the tabs and other users open a file that doesn't.


Q: What about a branch on Stack Exchange for temporal/trend based questions? Many questions along the lines of

*

*"which is the best X, amongst competitors",

*"what are the features of X"

… and other similar questions get removed from Stack Exchange sites; justifiably as well.
Users then must go either to chat or look on blogs, other forums, or review sites for answers or alternative opinions.
Having questions that can later become redundant of course do not belong on the sites, but I was wondering if some accommodation can be made as an assistance? I can imagine that some solution can be devised to include these queries. Maybe not in the main trunk of a site, but in a blog-like branch?
That is just a random possibility that comes to mind.

A: There are definitely initiatives to support a blog-based arm of many sites:
see
http://blogoverflow.com
and
https://blog.stackoverflow.com/2011/06/blog-overflow/


Q: How to login on divshot cli inside a vagrant box? Divshot has a nice command line interface. The first thing you should do after installing it with npm is to login.
divshot login

It should open a browser tab/window, you login on the divshot website and you authorise the CLI client by pressing a button at the end of the process.
But I have all my development environment on a vagrant box. When I type "divshot login" nothing happens. No browser tab appears.
What should I do?

A: *

*Run "divshot login" from your command line on you local machine and
follow the instructions to login.

*Run "divshot auth:token" to get
your auth token from the command line.

*When running commands that
interact with the Divshot API, use the flag "--token " to
give it authorization (on the vagrant box)

A: Another solution:

*

*Run divshot login on your local computer

*Inspect $HOME/.divshot/config/user.json, check it has a key token

*Copy that file to the corresponding path on the other computer


Q: Scala: Is it possible to indicate a generic class which implements a certain method I thinks it's easier to explain it with a simple example. (help rephrasing the title is welcome ;-)
I'd like to implement a squared method and, using implicit def, automatically add it to any class that supports the *-operator.
With an Int it's very easy:
class EnhancedInt(x: Int) { def squared = x * x }

implicit def IntToEnchancedInt(x: Int) = new EnhancedInt(x)

But with Any or AnyVal I get the following error:
scala> class EnhanceAny(x: AnyVal) { def squared = x * x }
<console>:7: error: value * is not a member of AnyVal
       class EnhanceAny(x: AnyVal) { def squared = x * x }

I'd like to know how I could apply it to any numeric class, or, even better, to any class supporting the *-operator.

A: It's not possible to have solution that works on any type with a * method without writing a boilerplate conversion for each type you want to deal with.  Essentially to do that you would need a recursive structural type, and Scala does not support those because of JVM type erasure.  See this post for more details.
You can get fairly close to what you want using a type class along with the Numeric type class, (inspired by the answers to this and this question).  This will work with most primitives:
//define the type class
trait Multipliable[X] { def *(x: X): X}

//define an implicit from A <% Numeric[A] -> Multipliable[Numeric[A]]
implicit def Numeric2Mult[A](a: A)(implicit num: Numeric[A]): Multipliable[A] = new Multipliable[A]{def *(b: A) = num.times(a, b)}

//now define your Enhanced class using the type class
class EnhancedMultipliable[T <% Multipliable[T]](x: T){ def squared = x * x}

//lastly define the conversion to the enhanced class
implicit def Mult2EnhancedMult[T <% Multipliable[T]](x: T) = new EnhancedMultipliable[T](x)

3.squared
//Int = 9

3.1415F.squared
//Float = 9.869022

123456789L.squared
//Long = 15241578750190521

A: Go visit Scala: How to define “generic” function parameters?

A: Think about it. Multiplication have different properties on different objects. Integer multiplication, for example, is associative and commutative, scalar multiplication is not commutative. And multiplication on floating point numbers...
But, of course, you can have what you want with trait or with "trait and implicit" construction which resembles a typeclass.


Q: c# how can return value from class? I have class !
class Reg_v_no_string
{
    public static string key_place = "";
    public static string key = "";
    public static string value = "";
    public string reg_value(string key_place, string key)
    {
        string value = string.Empty;

            RegistryKey klase = Registry.CurrentUser;
            klase = klase.OpenSubKey(key_place);
            value = klase.GetValue(key).ToString();
            klase.Close();

        return value;
    }
}

and this returns blank message box.
How can solve this problem !?
Thanks !
how can i return value from this class ?
I tryed
private void kryptonButton1_Click(object sender, EventArgs e)
    {
        Reg_v_no_string.key_place = @"Control Panel\Desktop";
        Reg_v_no_string.key_place = "WheelScrollLines";
        MessageBox.Show(Reg_v_no_string.value);

    }

A: You need to actually call the method:
private void kryptonButton1_Click(object sender, EventArgs e)
{
    var value = reg_value(@"Control Panel\Desktop", "WheelScrollLines");
    MessageBox.Show(value);
}

Also consider some changes to your class:
public static class Reg_v_no_string
{
    public static string reg_value(string key_place, string key)
    {
        string value = string.Empty;

         RegistryKey klase = Registry.CurrentUser;
         // todo: add some error checking to make sure the key is opened, etc.
         klase = klase.OpenSubKey(key_place);
         value = klase.GetValue(key).ToString();
         klase.Close();

        return value;
    }
}

And then when you call this static class it is like this:
// you don't need to `new` this class if it is static:
var value = Reg_v_no_string.reg_value(@"Control Panel\Desktop", "WheelScrollLines");

Or, to keep it so that it is not static:
public class Reg_v_no_string
{
    public string reg_value(string key_place, string key)
    {
        string value = string.Empty;

         RegistryKey klase = Registry.CurrentUser;
         // todo: add some error checking to make sure the key is opened, etc.
         klase = klase.OpenSubKey(key_place);
         value = klase.GetValue(key).ToString();
         klase.Close();

        return value;
    }
}

Then call it like this:
Reg_v_no_string obj = new Reg_v_no_string ();
var value = reg_value(@"Control Panel\Desktop", "WheelScrollLines");

A: There is no code that calls reg_value.
As result you are getting default (also shared between instances) value of value field.

A: Reg_v_no_string.value is not set yet.
You have to call reg_value(string key_place, string key) function that will return the value.


Q: New elements vanish when function ends I have created a simple form that allows the user to create a number of blank tables with a variable number of rows and columns. The code generates no errors, and briefly creates the new table elements, but when the function ends the tables vanish. What am I doing wrong?
function genTable(){
    var numRows = parseInt(document.getElementById("numRows").value); // Number of rows per table
    var numCols = parseInt(document.getElementById("numCols").value); // Number of columns per table
    var numTabs = parseInt(document.getElementById("numTabs").value); // number of tables

    var startDiv = document.getElementById("start");
    var oneCell = "	"; // HTML for a single cell
    var myHTML = ""; // An empty string to contain the tables

    for(i=0; i<numTabs; i++){
        myHTML += "

";

        for(k=0; k<numRows; k++){
            myHTML += "
";

            for(j=0; j<numCols; j++){
            myHTML += oneCell;
            }

            myHTML += "
";
        }

        myHTML += "

" + (i+1) + "
";
    }

    startDiv.innerHTML= myHTML;

}

A: It sounds like you have a trigger built into a hyperlink or a form... so although your script runs, the browser navigates and refreshes the page.
If you have a click event, you need to stop the event from propagating.
Short example:
HTML

<form>
    <input type="number" id="num" />
    <button id="clicker">
    Go
    </button>
</form>

JavaScript
document.getElementById('clicker').onclick = function () {
    document.getElementById('example').innerHTML = 'Content';
    // return false; // <-- without this (or an alternative) the form posts
}


Q: Placing a revolution slider on a wordpress woocommerce store So I am trying to place a Revolution slider on top of our Wocommerce shop pages, a lot like we already have on all of our other pages bar the shop.
I've provided the screenshots of how it is now and how I'd like it to look.
We're using a custom theme.
I know how to update my .PHP code if I'm pointed to the right file with the right bit of code!
Suggestions most welcome :)
This is what our shop currently looks like:

This is what our homepage looks like with the revolution slide (mid transition):

This is how we'd like the shop to look with the revolution slider:


Q: Formatting error in NPOI I'm developing an accountancy software, which will also create a report in Excel format (.xls).
I've used NPOI in almost every project that requires an Excel report, without any major problem.
But i'm now facing a problem, and can't seem to find any solution browsing the Internet.

As you can see, midway the report, the Currency column automatically changes format, not formatting properly currency, border, and everything in that column.
I've been working on it for several time, with no success.
Here's the code I've used to create the style (C#):
var baseStyle = workBook.CreateCellStyle();
        baseStyle.VerticalAlignment = VerticalAlignment.Top;
        baseStyle.FillForegroundColor = IndexedColors.White.Index;
        baseStyle.FillPattern = FillPattern.SolidForeground;
        baseStyle.BorderTop = BorderStyle.Thin;
        baseStyle.BorderBottom = BorderStyle.Thin;
        baseStyle.BorderLeft = BorderStyle.Thin;
        baseStyle.BorderRight = BorderStyle.Thin;
        baseStyle.WrapText = true;

private static void SetCellValuePrice(IRow row, ICellStyle cellStyle, int colIndex, decimal value)
    {
        var xlCell = row.CreateCell(colIndex);

        xlCell.SetCellValue(Convert.ToDouble(value));

        var newStyle = row.Sheet.Workbook.CreateCellStyle();
        newStyle.CloneStyleFrom(cellStyle);

        newStyle.DataFormat = row.Sheet.Workbook.CreateDataFormat().GetFormat("€ #,##0.00");

        xlCell.CellStyle = newStyle;
    }

And an example of the usage (that seems to give no problems in other cells:
SetCellValue(row, baseStyle, colIndex++, data.Description);

Any guesses?
Thanks in advance!

A: The problem is that you're creating a style for each cell, while you should create just ONE style for each type of cell.
var baseStyle = workBook.CreateCellStyle();
...
var priceStyle = workBook.CreateCellStyle();
priceStyle.CloneStyleFrom(numberStyle);
priceStyle.DataFormat = workBook.CreateDataFormat().GetFormat("€ #,##0.00");

private static void SetCellValuePrice(IRow row, ICellStyle cellStyle, int colIndex, decimal value)
{
    var xlCell = row.CreateCell(colIndex);

    xlCell.SetCellValue(Convert.ToDouble(value));

    xlCell.CellStyle = cellStyle;
}

Usage:
SetCellValue(row, priceStyle, colIndex++, data.Description);


Q: Google Cloud Build GitHub App - auto trigger for all projects in organization Up until a few weeks ago, when installing the Google Cloud Build GitHub app in a GitHub organization, it was possible to specify that all GitHub projects within that organization would create a build trigger.
Yesterday I noticed that this no longer happens, and new projects added to the GitHub organizations don't trigger a build and I can see a message on the specific commit saying that "this repository is not mapped to a Google Cloud platform project".
Is this an intentional change in spec - so one needs to manually link every new repo via the Console/API - or something I'm missing?

A: yes. for a new project, you have to manually set up on the cloud build page by "Connect repository". then you can use gcp cli comamnd set the trigger,
gcloud beta builds triggers create github


Q: Django Haystack faceting multivalued strings -- unknown field tags_exact The content on my site is tagged with strings of variable length, and I want to do faceted search on these tags.  For example, a story might have tags, "civil war," "general grant," and "battle of gettysburg."  I want to be able to do faceted search on the exact, non-tokenized strings.
Within my search_index.py, I defined:
tags = MultiValueField(faceted=True, indexed=True)

and I edited the schema.xml generated by build_solr_schema to make tags a string instead of text:
<field name="tags" type="string" indexed="true" stored="true" multiValued="true" />

Unfortunately when I get an error about tags_exact:
Failed to add documents to Solr: [Reason: None]
ERROR: [doc=treelines_stories.story.1] unknown field 'tags_exact'

I understand that the tags_exact field has something to do w/ Haystack's internal implementation of faceting, but how can I work around this?
Thanks!

A: search_index.py:
    tags = MultiValueField(faceted=True)

schema.xml:
<field name="tags" type="text" indexed="true" stored="true" multiValued="true" />
<field name="tags_exact" type="string" indexed="true" stored="true" multiValued="true" />


Q: Python: How to get CSV to write colums (using API) I am trying to create a spreadsheet out of API data, but I am having trouble getting it to work. The .csv file will only contain the last line of information it collected. What I want is 2 columns, both with about 2800 items in each. Instead I have 2 columns with one line in each. Is there a way to write columns instead? I think my problem is that since the myFile = open('AutoCSV.csv', "w") is in a for loop it just continues to "open and close" the file? Im pretty new to python and brand new to API and CSV files so any suggestions are appreciated.
for x in range(0,5):
string1 = "https://api.rainforestcloud.com/rest/device?networkName=Company&take=500&skip="+str(x*500)
response = requests.get(string1,headers=headers).json()

for y in range (0,499):
    myData = [(response[y]['deviceGuid']),(response[y]['status'])]
    myFile = open('AutoCSV.csv', "w")
    with myFile:
        writer = csv.writer(myFile)
        writer.writerow(myData)

A: This has nothing to do with API nor with the csv format actually, it's just that:

since the myFile = open('AutoCSV.csv', "w") is in a for loop it just continues to "open and close" the file

Indeed - and not only that but it clears the file each time it reopens it, as documented here:

'w' for writing (truncating the file if it already exists)

Also, you're not using with open() correctly, you want:
with open("path/to/your/file.ext") as f:
    # your code using the file here

Hopefully the fix is simple: open the file before your outer loop. Now may I ask why you didn't tried this directly instead of posting here ?

A: Since you don't provide any input data, I'll have to do this blindly. Does this works for you?:
import csv
import requests

headers = {} #something

with open('AutoCSV.csv', "w", , newline='') as csv_output_file:
    file_writer = csv.writer(csv_output_file)

    for current_page_start in range(0, 2500, 500):
        url_to_retrieve = f"https://api.rainforestcloud.com/rest/device?networkName=Company&take=500&skip={current_page_start}"
        json_response = requests.get(url_to_retrieve, headers=headers).json()

        for response_element in json_response:
            data_to_write = (response_element['deviceGuid'], response_element['status'])
            file_writer.writerow(data_to_write)


Q: step by step solr katta integration I am trying to find the solr and katta integration.
But didn't find any good tutorial for the same.
Could you please give me step by step integration of katta and solr.
Many thanks in advance.


Q: how to show warning of empty field on form validation? these are my code for form validation :
     <form action="<?php echo base_url().'data_laporan/tambah_aksi';?>"method="post" enctype="multipart/form-data">

            Jenis Laporan
            <select class="form-control" name="jenis_laporan">
            <option>Penemuan hewan</option>
            <option>Kehilangan Hewan</option>
            </select>

            Jenis Hewan
            <input type="text" name="jenis_hewan" class="form-control">

            Lokasi
            <input type="text" name="lokasi" class="form-control">

            Deskripsi
            <input type="text" name="deskripsi" class="form-control">

            Nama Pelapor
            <input type="text" name="nama_pelapor" class="form-control">

            No Hp
            <input type="text" name="no_hp" class="form-control">

            Gambar Hewan
            <input type="file" name="gambar" class="form-control">

    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Save changes</button>

  </form>

i want to show a simple warning when i click "Save Changes" as a submit button like this :
image for example warning
and these are my code for tambah_aksi() function :
public function tambah_aksi()
{
    $jenis_laporan = $this->input->post('jenis_laporan');
    $jenis_hewan = $this->input->post('jenis_hewan');
    $deskripsi = $this->input->post('deskripsi');
    $lokasi = $this->input->post('lokasi');
    $nama_pelapor = $this->input->post('nama_pelapor');
    $no_hp = $this->input->post('no_hp');
    $gambar = $_FILES['gambar']['name'];
    if ($gambar = '') {} else{
        $config ['upload_path'] = './upload';
        $config ['allowed_types'] = 'jpg|jpeg|png|gif';

        $this->load->library('upload', $config);
        if(!$this->upload->do_upload('gambar')){
            echo "Gambar gagal di Upload";
        }else{
            $gambar=$this->upload->data('file_name');
        }
    }
    $data = array (
        'jenis_laporan' => $jenis_laporan,
        'jenis_hewan' => $jenis_hewan,
        'deskripsi' => $deskripsi,
        'lokasi' => $lokasi,
        'nama_pelapor' => $nama_pelapor,
        'no_hp' => $no_hp,
        'gambar' => $gambar,
    );

    $this->model_laporan->tambah_aksi($data, 'tb_laporan');
    redirect('data_laporan/index');
}

i tried using if-else form validation run checking but it does not goes well, could you please help me to fix this with another way or the efficient way of if-else checking?

A: You can do this many ways
Via codeigniter 3.x
then first load form validation library in controller function and set rules and place holder for showing errors in view file. See for reference
https://codeigniter.com/userguide3/libraries/form_validation.html#the-controller
https://codeigniter.com/userguide3/libraries/form_validation.html#showing-errors-individually
Via HTML
You can simply do this by adding required attribute to all html elements which are required, browser will show warning automatically after clicking on submit button for required fields. see example for input html element
<input type="text" name="nama_pelapor" required class="form-control">

See for dropdown
<select class="form-control" required name="jenis_laporan">
        <option>Penemuan hewan</option>
        <option>Kehilangan Hewan</option>
        </select>

Via Jquery
If you want to customize error messages then you do this via your own code in jquery or jquery validator library. See this documentation for jquery validation
https://jqueryvalidation.org/validate/

A: Comparison operator should be double == not single =. Edit your line of code to this.
 if ($gambar =='') {} else{