Q:

Regular expression to match numbers with or without commas and decimals in text

I'm trying to locate and replace all numbers in a body of text.  I've found a few example regex's, which almost solve the problem, but none are perfect yet.  The problem I have is that the numbers in my text may or may not have decimals and commas.  For example:

"The 5000 lb. fox jumped over a 99,999.99998713 foot fence."

The regex should return "5000" and "99,999.99998713".  Examples I've found break-up the numbers on the comma or are limited to two decimal places.  I'm starting to understand regex's enough to see why some examples are limited to two decimal places, but I haven't yet learned how to overcome it and also include the comma to get the entire sequence.
Here is my latest version:
[0-9]+(\.[0-9][0-9]?)?

Which returns, "5000", "99,99", "9.99", and "998713" for the above text.

A:

EDIT: Since this has gotten a lot of views, let me start by giving everybody what they Googled for:
#ALL THESE REQUIRE THE WHOLE STRING TO BE A NUMBER
#For numbers embedded in sentences, see discussion below

#### NUMBERS AND DECIMALS ONLY ####
#No commas allowed
#Pass: (1000.0), (001), (.001)
#Fail: (1,000.0)
^\d*\.?\d+$

#No commas allowed
#Can't start with "."
#Pass: (0.01)
#Fail: (.01)
^(\d+\.)?\d+$

#### CURRENCY ####
#No commas allowed
#"$" optional
#Can't start with "."
#Either 0 or 2 decimal digits
#Pass: ($1000), (1.00), ($0.11)
#Fail: ($1.0), (1.), ($1.000), ($.11)
^\$?\d+(\.\d{2})?$

#### COMMA-GROUPED ####
#Commas required between powers of 1,000
#Can't start with "."
#Pass: (1,000,000), (0.001)
#Fail: (1000000), (1,00,00,00), (.001)
^\d{1,3}(,\d{3})*(\.\d+)?$

#Commas required
#Cannot be empty
#Pass: (1,000.100), (.001)
#Fail: (1000), ()
^(?=.)(\d{1,3}(,\d{3})*)?(\.\d+)?$

#Commas optional as long as they're consistent
#Can't start with "."
#Pass: (1,000,000), (1000000)
#Fail: (10000,000), (1,00,00)
^(\d+|\d{1,3}(,\d{3})*)(\.\d+)?$

#### LEADING AND TRAILING ZEROES ####
#No commas allowed
#Can't start with "."
#No leading zeroes in integer part
#Pass: (1.00), (0.00)
#Fail: (001)
^([1-9]\d*|0)(\.\d+)?$

#No commas allowed
#Can't start with "."
#No trailing zeroes in decimal part
#Pass: (1), (0.1)
#Fail: (1.00), (0.1000)
^\d+(\.\d*[1-9])?$

Now that that's out of the way, most of the following is meant as commentary on how complex regex can get if you try to be clever with it, and why you should seek alternatives. Read at your own risk.

This is a very common task, but all the answers I see here so far will accept inputs that don't match your number format, such as ,111, 9,9,9, or even .,,.. That's simple enough to fix, even if the numbers are embedded in other text. IMHO anything that fails to pull 1,234.56 and 1234—and only those numbers—out of abc22 1,234.56 9.9.9.9 def 1234 is a wrong answer.
First of all, if you don't need to do this all in one regex, don't. A single regex for two different number formats is hard to maintain even when they aren't embedded in other text. What you should really do is split the whole thing on whitespace, then run two or three smaller regexes on the results. If that's not an option for you, keep reading.
Basic pattern
Considering the examples you've given, here's a simple regex that allows pretty much any integer or decimal in 0000 format and blocks everything else:
^\d*\.?\d+$

Here's one that requires 0,000 format:
^\d{1,3}(,\d{3})*(\.\d+)?$

Put them together, and commas become optional as long as they're consistent:
^(\d*\.?\d+|\d{1,3}(,\d{3})*(\.\d+)?)$

Embedded numbers
The patterns above require the entire input to be a number. You're looking for numbers embedded in text, so you have to loosen that part. On the other hand, you don't want it to see catch22 and think it's found the number 22. If you're using something with lookbehind support (like .NET), this is pretty easy: replace ^ with (?<!\S) and $ with (?!\S) and you're good to go:
(?<!\S)(\d*\.?\d+|\d{1,3}(,\d{3})*(\.\d+)?)(?!\S)

If you're working with JavaScript or Ruby or something, things start looking more complex:
(?:^|\s)(\d*\.?\d+|\d{1,3}(?:,\d{3})*(?:\.\d+)?)(?!\S)

You'll have to use capture groups; I can't think of an alternative without lookbehind support. The numbers you want will be in Group 1 (assuming the whole match is Group 0).
Validation and more complex rules
I think that covers your question, so if that's all you need, stop reading now. If you want to get fancier, things turn very complex very quickly. Depending on your situation, you may want to block any or all of the following:

Empty input
Leading zeroes (e.g. 000123)
Trailing zeroes (e.g. 1.2340000)
Decimals starting with the decimal point (e.g. .001 as opposed to 0.001)

Just for the hell of it, let's assume you want to block the first 3, but allow the last one. What should you do? I'll tell you what you should do, you should use a different regex for each rule and progressively narrow down your matches. But for the sake of the challenge, here's how you do it all in one giant pattern:
(?<!\S)(?=.)(0|([1-9](\d*|\d{0,2}(,\d{3})*)))?(\.\d*[1-9])?(?!\S)

And here's what it means:
(?<!\S) to (?!\S) #The whole match must be surrounded by either whitespace or line boundaries. So if you see something bogus like :;:9.:, ignore the 9.
(?=.)             #The whole thing can't be blank.

(                    #Rules for the integer part:
  0                  #1. The integer part could just be 0...
  |                  #
  [1-9]              #   ...otherwise, it can't have leading zeroes.
  (                  #
    \d*              #2. It could use no commas at all...
    |                #
    \d{0,2}(,\d{3})* #   ...or it could be comma-separated groups of 3 digits each.
  )                  #
)?                   #3. Or there could be no integer part at all.

(       #Rules for the decimal part:
  \.    #1. It must start with a decimal point...
  \d*   #2. ...followed by a string of numeric digits only.
  [1-9] #3. It can't be just the decimal point, and it can't end in 0.
)?      #4. The whole decimal part is also optional. Remember, we checked at the beginning to make sure the whole thing wasn't blank.

Tested here: http://rextester.com/YPG96786
This will allow things like:
100,000
999.999
90.0009
1,000,023.999
0.111
.111
0

It will block things like:
1,1,1.111
000,001.111
999.
0.
111.110000
1.1.1.111
9.909,888

There are several ways to make this regex simpler and shorter, but understand that changing the pattern will loosen what it considers a number.
Since many regex engines (e.g. JavaScript and Ruby) don't support the negative lookbehind, the only way to do this correctly is with capture groups:
(:?^|\s)(?=.)((?:0|(?:[1-9](?:\d*|\d{0,2}(?:,\d{3})*)))?(?:\.\d*[1-9])?)(?!\S)

The numbers you're looking for will be in capture group 1.
Tested here: http://rubular.com/r/3HCSkndzhT
One final note
Obviously, this is a massive, complicated, nigh-unreadable regex. I enjoyed the challenge, but you should consider whether you really want to use this in a production environment. Instead of trying to do everything in one step, you could do it in two: a regex to catch anything that might be a number, then another one to weed out whatever isn't a number. Or you could do some basic processing, then use your language's built-in number parsing functions. Your choice.

A:

Some days ago, I worked on the problem of removing trailing zeros from the string of a number.
In the continuity of that problem, I find this one interesting because it widens the problem to numbers comprising commas.
I have taken the regex's pattern I had writen in that previous  problem I worked on and I improved it in order that it can treat the numbers with commas as an answer for this problem.
I've been carried away with my enthusiasm and my liking of regexes. I don't know if the result fits exactly to the need  expressed by Michael Prescott. I would be interested to know the points that are in excess or in lack in my regex, and to correct it to make it more suitable for you.
Now, after a long session of work on this regex, I have a sort of weight in the brain, so I'm not fresh enough to give a lot of explanation. If points are obscure, and if anybody may come to be interested enough,  please, ask me.
The regex is built in order that it can detect the numbers expressed in scientific notation 2E10 or even 5,22,454.12E-00.0478 , removing unnecessary zeros in the two parts of such numbers too. If an exponent is equal to zero , the number is modified so that there is no more exponent.
I put some verification in the pattern so that some particular cases will not match, for exemple '12..57' won't match. But in ',111' the string '111' matches because the preceding comma is considered a comma not being in a number but a comma of sentence.
I think that the managing of commas should be improved, because it seems to me that there are only 2 digits between commas in Indian numbering. It won't be dificult to correct, I presume
Here after is a code demonstrating how my regex works. There are two functions, according if one wants the numbers '.1245' to be transformed in '0.1245' or not.  I wouldn't be surprised if errors or unwanted matchings or unmatchings will remain for certain cases of number strings; then I'd like to know these cases to understand and correct the deficiency.
I apologize for this code written in Python, but regexes are trans-langage and I think everybody will be capable of undertsanding the reex's pattern
import re

regx = re.compile('(?<![\d.])(?!\.\.)(?<![\d.][eE][+-])(?<![\d.][eE])(?<!\d[.,])'
                  '' #---------------------------------
                  '([+-]?)'
                  '(?![\d,]*?\.[\d,]*?\.[\d,]*?)'
                  '(?:0|,(?=0)|(?<!\d),)*'
                  '(?:'
                  '((?:\d(?!\.[1-9])|,(?=\d))+)[.,]?'
                  '|\.(0)'
                  '|((?<!\.)\.\d+?)'
                  '|([\d,]+\.\d+?))'
                  '0*'
                  '' #---------------------------------
                  '(?:'
                  '([eE][+-]?)(?:0|,(?=0))*'
                  '(?:'
                  '(?!0+(?=\D|\Z))((?:\d(?!\.[1-9])|,(?=\d))+)[.,]?'
                  '|((?<!\.)\.(?!0+(?=\D|\Z))\d+?)'
                  '|([\d,]+\.(?!0+(?=\D|\Z))\d+?))'
                  '0*'
                  ')?'
                  '' #---------------------------------
                  '(?![.,]?\d)')

def dzs_numbs(x,regx = regx): # ds = detect and zeros-shave
    if not regx.findall(x):
        yield ('No match,', 'No catched string,', 'No groups.')
    for mat in regx.finditer(x):
        yield (mat.group(), ''.join(mat.groups('')), mat.groups(''))

def dzs_numbs2(x,regx = regx): # ds = detect and zeros-shave
    if not regx.findall(x):
        yield ('No match,', 'No catched string,', 'No groups.')
    for mat in regx.finditer(x):
        yield (mat.group(),
               ''.join(('0' if n.startswith('.') else '')+n for n in mat.groups('')),
               mat.groups(''))

NS = ['  23456000and23456000. or23456000.000  00023456000 s000023456000.  000023456000.000 ',
      'arf 10000 sea10000.+10000.000  00010000-00010000. kant00010000.000 ',
      '  24:  24,  24.   24.000  24.000,   00024r 00024. blue 00024.000  ',
      '  8zoom8.  8.000  0008  0008. and0008.000  ',
      '  0   00000M0. = 000.  0.0  0.000    000.0   000.000   .000000   .0   ',
      '  .0000023456    .0000023456000   '
      '  .0005872    .0005872000   .00503   .00503000   ',
      '  .068    .0680000   .8   .8000  .123456123456    .123456123456000    ',
      '  .657   .657000   .45    .4500000   .7    .70000  0.0000023230000   000.0000023230000   ',
      '  0.0081000    0000.0081000  0.059000   0000.059000     ',
      '  0.78987400000 snow  00000.78987400000  0.4400000   00000.4400000   ',
      '  -0.5000  -0000.5000   0.90   000.90   0.7   000.7   ',
      '  2.6    00002.6   00002.60000  4.71   0004.71    0004.7100   ',
      '  23.49   00023.49   00023.490000  103.45   0000103.45   0000103.45000    ',
      '  10003.45067   000010003.45067   000010003.4506700 ',
      '  +15000.0012   +000015000.0012   +000015000.0012000    ',
      '  78000.89   000078000.89   000078000.89000    ',
      '  .0457e10   .0457000e10   00000.0457000e10  ',
      '   258e8   2580000e4   0000000002580000e4   ',
      '  0.782e10   0000.782e10   0000.7820000e10  ',
      '  1.23E2   0001.23E2  0001.2300000E2   ',
      '  432e-102  0000432e-102   004320000e-106   ',
      '  1.46e10and0001.46e10  0001.4600000e10   ',
      '  1.077e-300  0001.077e-300  0001.077000e-300   ',
      '  1.069e10   0001.069e10   0001.069000e10   ',
      '  105040.03e10  000105040.03e10  105040.0300e10    ',
      '  +286E000024.487900  -78.4500e.14500   .0140E789.  ',
      '  081,12.40E07,95.0120     0045,78,123.03500e-0.00  ',
      '  0096,78,473.0380e-0.    0008,78,373.066000E0.    0004512300.E0000  ',
      '  ..18000  25..00 36...77   2..8  ',
      '  3.8..9    .12500.     12.51.400  ',
      '  00099,111.8713000   -0012,45,83,987.26+0.000,099,88,44.or00,00,00.00must',
      '  00099,44,and   0000,099,88,44.bom',
      '00,000,00.587000  77,98,23,45.,  this,that ',
      '  ,111  145.20  +9,9,9  0012800  .,,.  1  100,000 ',
      '1,1,1.111  000,001.111   -999.  0.  111.110000  1.1.1.111  9.909,888']

for ch in NS:
    print 'string: '+repr(ch)
    for strmatch, modified, the_groups in dzs_numbs2(ch):
        print strmatch.rjust(20),'',modified,'',the_groups
    print

result
string: '  23456000and23456000. or23456000.000  00023456000 s000023456000.  000023456000.000 '
            23456000  23456000  ('', '23456000', '', '', '', '', '', '', '')
           23456000.  23456000  ('', '23456000', '', '', '', '', '', '', '')
        23456000.000  23456000  ('', '23456000', '', '', '', '', '', '', '')
         00023456000  23456000  ('', '23456000', '', '', '', '', '', '', '')
       000023456000.  23456000  ('', '23456000', '', '', '', '', '', '', '')
    000023456000.000  23456000  ('', '23456000', '', '', '', '', '', '', '')

string: 'arf 10000 sea10000.+10000.000  00010000-00010000. kant00010000.000 '
               10000  10000  ('', '10000', '', '', '', '', '', '', '')
              10000.  10000  ('', '10000', '', '', '', '', '', '', '')
           10000.000  10000  ('', '10000', '', '', '', '', '', '', '')
            00010000  10000  ('', '10000', '', '', '', '', '', '', '')
           00010000.  10000  ('', '10000', '', '', '', '', '', '', '')
        00010000.000  10000  ('', '10000', '', '', '', '', '', '', '')

string: '  24:  24,  24.   24.000  24.000,   00024r 00024. blue 00024.000  '
                  24  24  ('', '24', '', '', '', '', '', '', '')
                 24,  24  ('', '24', '', '', '', '', '', '', '')
                 24.  24  ('', '24', '', '', '', '', '', '', '')
              24.000  24  ('', '24', '', '', '', '', '', '', '')
              24.000  24  ('', '24', '', '', '', '', '', '', '')
               00024  24  ('', '24', '', '', '', '', '', '', '')
              00024.  24  ('', '24', '', '', '', '', '', '', '')
           00024.000  24  ('', '24', '', '', '', '', '', '', '')

string: '  8zoom8.  8.000  0008  0008. and0008.000  '
                   8  8  ('', '8', '', '', '', '', '', '', '')
                  8.  8  ('', '8', '', '', '', '', '', '', '')
               8.000  8  ('', '8', '', '', '', '', '', '', '')
                0008  8  ('', '8', '', '', '', '', '', '', '')
               0008.  8  ('', '8', '', '', '', '', '', '', '')
            0008.000  8  ('', '8', '', '', '', '', '', '', '')

string: '  0   00000M0. = 000.  0.0  0.000    000.0   000.000   .000000   .0   '
                   0  0  ('', '0', '', '', '', '', '', '', '')
               00000  0  ('', '0', '', '', '', '', '', '', '')
                  0.  0  ('', '0', '', '', '', '', '', '', '')
                000.  0  ('', '0', '', '', '', '', '', '', '')
                 0.0  0  ('', '', '0', '', '', '', '', '', '')
               0.000  0  ('', '', '0', '', '', '', '', '', '')
               000.0  0  ('', '', '0', '', '', '', '', '', '')
             000.000  0  ('', '', '0', '', '', '', '', '', '')
             .000000  0  ('', '', '0', '', '', '', '', '', '')
                  .0  0  ('', '', '0', '', '', '', '', '', '')

string: '  .0000023456    .0000023456000     .0005872    .0005872000   .00503   .00503000   '
         .0000023456  0.0000023456  ('', '', '', '.0000023456', '', '', '', '', '')
      .0000023456000  0.0000023456  ('', '', '', '.0000023456', '', '', '', '', '')
            .0005872  0.0005872  ('', '', '', '.0005872', '', '', '', '', '')
         .0005872000  0.0005872  ('', '', '', '.0005872', '', '', '', '', '')
              .00503  0.00503  ('', '', '', '.00503', '', '', '', '', '')
           .00503000  0.00503  ('', '', '', '.00503', '', '', '', '', '')

string: '  .068    .0680000   .8   .8000  .123456123456    .123456123456000    '
                .068  0.068  ('', '', '', '.068', '', '', '', '', '')
            .0680000  0.068  ('', '', '', '.068', '', '', '', '', '')
                  .8  0.8  ('', '', '', '.8', '', '', '', '', '')
               .8000  0.8  ('', '', '', '.8', '', '', '', '', '')
       .123456123456  0.123456123456  ('', '', '', '.123456123456', '', '', '', '', '')
    .123456123456000  0.123456123456  ('', '', '', '.123456123456', '', '', '', '', '')

string: '  .657   .657000   .45    .4500000   .7    .70000  0.0000023230000   000.0000023230000   '
                .657  0.657  ('', '', '', '.657', '', '', '', '', '')
             .657000  0.657  ('', '', '', '.657', '', '', '', '', '')
                 .45  0.45  ('', '', '', '.45', '', '', '', '', '')
            .4500000  0.45  ('', '', '', '.45', '', '', '', '', '')
                  .7  0.7  ('', '', '', '.7', '', '', '', '', '')
              .70000  0.7  ('', '', '', '.7', '', '', '', '', '')
     0.0000023230000  0.000002323  ('', '', '', '.000002323', '', '', '', '', '')
   000.0000023230000  0.000002323  ('', '', '', '.000002323', '', '', '', '', '')

string: '  0.0081000    0000.0081000  0.059000   0000.059000     '
           0.0081000  0.0081  ('', '', '', '.0081', '', '', '', '', '')
        0000.0081000  0.0081  ('', '', '', '.0081', '', '', '', '', '')
            0.059000  0.059  ('', '', '', '.059', '', '', '', '', '')
         0000.059000  0.059  ('', '', '', '.059', '', '', '', '', '')

string: '  0.78987400000 snow  00000.78987400000  0.4400000   00000.4400000   '
       0.78987400000  0.789874  ('', '', '', '.789874', '', '', '', '', '')
   00000.78987400000  0.789874  ('', '', '', '.789874', '', '', '', '', '')
           0.4400000  0.44  ('', '', '', '.44', '', '', '', '', '')
       00000.4400000  0.44  ('', '', '', '.44', '', '', '', '', '')

string: '  -0.5000  -0000.5000   0.90   000.90   0.7   000.7   '
             -0.5000  -0.5  ('-', '', '', '.5', '', '', '', '', '')
          -0000.5000  -0.5  ('-', '', '', '.5', '', '', '', '', '')
                0.90  0.9  ('', '', '', '.9', '', '', '', '', '')
              000.90  0.9  ('', '', '', '.9', '', '', '', '', '')
                 0.7  0.7  ('', '', '', '.7', '', '', '', '', '')
               000.7  0.7  ('', '', '', '.7', '', '', '', '', '')

string: '  2.6    00002.6   00002.60000  4.71   0004.71    0004.7100   '
                 2.6  2.6  ('', '', '', '', '2.6', '', '', '', '')
             00002.6  2.6  ('', '', '', '', '2.6', '', '', '', '')
         00002.60000  2.6  ('', '', '', '', '2.6', '', '', '', '')
                4.71  4.71  ('', '', '', '', '4.71', '', '', '', '')
             0004.71  4.71  ('', '', '', '', '4.71', '', '', '', '')
           0004.7100  4.71  ('', '', '', '', '4.71', '', '', '', '')

string: '  23.49   00023.49   00023.490000  103.45   0000103.45   0000103.45000    '
               23.49  23.49  ('', '', '', '', '23.49', '', '', '', '')
            00023.49  23.49  ('', '', '', '', '23.49', '', '', '', '')
        00023.490000  23.49  ('', '', '', '', '23.49', '', '', '', '')
              103.45  103.45  ('', '', '', '', '103.45', '', '', '', '')
          0000103.45  103.45  ('', '', '', '', '103.45', '', '', '', '')
       0000103.45000  103.45  ('', '', '', '', '103.45', '', '', '', '')

string: '  10003.45067   000010003.45067   000010003.4506700 '
         10003.45067  10003.45067  ('', '', '', '', '10003.45067', '', '', '', '')
     000010003.45067  10003.45067  ('', '', '', '', '10003.45067', '', '', '', '')
   000010003.4506700  10003.45067  ('', '', '', '', '10003.45067', '', '', '', '')

string: '  +15000.0012   +000015000.0012   +000015000.0012000    '
         +15000.0012  +15000.0012  ('+', '', '', '', '15000.0012', '', '', '', '')
     +000015000.0012  +15000.0012  ('+', '', '', '', '15000.0012', '', '', '', '')
  +000015000.0012000  +15000.0012  ('+', '', '', '', '15000.0012', '', '', '', '')

string: '  78000.89   000078000.89   000078000.89000    '
            78000.89  78000.89  ('', '', '', '', '78000.89', '', '', '', '')
        000078000.89  78000.89  ('', '', '', '', '78000.89', '', '', '', '')
     000078000.89000  78000.89  ('', '', '', '', '78000.89', '', '', '', '')

string: '  .0457e10   .0457000e10   00000.0457000e10  '
            .0457e10  0.0457e10  ('', '', '', '.0457', '', 'e', '10', '', '')
         .0457000e10  0.0457e10  ('', '', '', '.0457', '', 'e', '10', '', '')
    00000.0457000e10  0.0457e10  ('', '', '', '.0457', '', 'e', '10', '', '')

string: '   258e8   2580000e4   0000000002580000e4   '
               258e8  258e8  ('', '258', '', '', '', 'e', '8', '', '')
           2580000e4  2580000e4  ('', '2580000', '', '', '', 'e', '4', '', '')
  0000000002580000e4  2580000e4  ('', '2580000', '', '', '', 'e', '4', '', '')

string: '  0.782e10   0000.782e10   0000.7820000e10  '
            0.782e10  0.782e10  ('', '', '', '.782', '', 'e', '10', '', '')
         0000.782e10  0.782e10  ('', '', '', '.782', '', 'e', '10', '', '')
     0000.7820000e10  0.782e10  ('', '', '', '.782', '', 'e', '10', '', '')

string: '  1.23E2   0001.23E2  0001.2300000E2   '
              1.23E2  1.23E2  ('', '', '', '', '1.23', 'E', '2', '', '')
           0001.23E2  1.23E2  ('', '', '', '', '1.23', 'E', '2', '', '')
      0001.2300000E2  1.23E2  ('', '', '', '', '1.23', 'E', '2', '', '')

string: '  432e-102  0000432e-102   004320000e-106   '
            432e-102  432e-102  ('', '432', '', '', '', 'e-', '102', '', '')
        0000432e-102  432e-102  ('', '432', '', '', '', 'e-', '102', '', '')
      004320000e-106  4320000e-106  ('', '4320000', '', '', '', 'e-', '106', '', '')

string: '  1.46e10and0001.46e10  0001.4600000e10   '
             1.46e10  1.46e10  ('', '', '', '', '1.46', 'e', '10', '', '')
          0001.46e10  1.46e10  ('', '', '', '', '1.46', 'e', '10', '', '')
     0001.4600000e10  1.46e10  ('', '', '', '', '1.46', 'e', '10', '', '')

string: '  1.077e-300  0001.077e-300  0001.077000e-300   '
          1.077e-300  1.077e-300  ('', '', '', '', '1.077', 'e-', '300', '', '')
       0001.077e-300  1.077e-300  ('', '', '', '', '1.077', 'e-', '300', '', '')
    0001.077000e-300  1.077e-300  ('', '', '', '', '1.077', 'e-', '300', '', '')

string: '  1.069e10   0001.069e10   0001.069000e10   '
            1.069e10  1.069e10  ('', '', '', '', '1.069', 'e', '10', '', '')
         0001.069e10  1.069e10  ('', '', '', '', '1.069', 'e', '10', '', '')
      0001.069000e10  1.069e10  ('', '', '', '', '1.069', 'e', '10', '', '')

string: '  105040.03e10  000105040.03e10  105040.0300e10    '
        105040.03e10  105040.03e10  ('', '', '', '', '105040.03', 'e', '10', '', '')
     000105040.03e10  105040.03e10  ('', '', '', '', '105040.03', 'e', '10', '', '')
      105040.0300e10  105040.03e10  ('', '', '', '', '105040.03', 'e', '10', '', '')

string: '  +286E000024.487900  -78.4500e.14500   .0140E789.  '
  +286E000024.487900  +286E24.4879  ('+', '286', '', '', '', 'E', '', '', '24.4879')
     -78.4500e.14500  -78.45e0.145  ('-', '', '', '', '78.45', 'e', '', '.145', '')
          .0140E789.  0.014E789  ('', '', '', '.014', '', 'E', '789', '', '')

string: '  081,12.40E07,95.0120     0045,78,123.03500e-0.00  '
081,12.40E07,95.0120  81,12.4E7,95.012  ('', '', '', '', '81,12.4', 'E', '', '', '7,95.012')
   0045,78,123.03500  45,78,123.035  ('', '', '', '', '45,78,123.035', '', '', '', '')

string: '  0096,78,473.0380e-0.    0008,78,373.066000E0.    0004512300.E0000  '
    0096,78,473.0380  96,78,473.038  ('', '', '', '', '96,78,473.038', '', '', '', '')
  0008,78,373.066000  8,78,373.066  ('', '', '', '', '8,78,373.066', '', '', '', '')
         0004512300.  4512300  ('', '4512300', '', '', '', '', '', '', '')

string: '  ..18000  25..00 36...77   2..8  '
           No match,  No catched string,  No groups.

string: '  3.8..9    .12500.     12.51.400  '
           No match,  No catched string,  No groups.

string: '  00099,111.8713000   -0012,45,83,987.26+0.000,099,88,44.or00,00,00.00must'
   00099,111.8713000  99,111.8713  ('', '', '', '', '99,111.8713', '', '', '', '')
  -0012,45,83,987.26  -12,45,83,987.26  ('-', '', '', '', '12,45,83,987.26', '', '', '', '')
         00,00,00.00  0  ('', '', '0', '', '', '', '', '', '')

string: '  00099,44,and   0000,099,88,44.bom'
           00099,44,  99,44  ('', '99,44', '', '', '', '', '', '', '')
     0000,099,88,44.  99,88,44  ('', '99,88,44', '', '', '', '', '', '', '')

string: '00,000,00.587000  77,98,23,45.,  this,that '
    00,000,00.587000  0.587  ('', '', '', '.587', '', '', '', '', '')
        77,98,23,45.  77,98,23,45  ('', '77,98,23,45', '', '', '', '', '', '', '')

string: '  ,111  145.20  +9,9,9  0012800  .,,.  1  100,000 '
                ,111  111  ('', '111', '', '', '', '', '', '', '')
              145.20  145.2  ('', '', '', '', '145.2', '', '', '', '')
              +9,9,9  +9,9,9  ('+', '9,9,9', '', '', '', '', '', '', '')
             0012800  12800  ('', '12800', '', '', '', '', '', '', '')
                   1  1  ('', '1', '', '', '', '', '', '', '')
             100,000  100,000  ('', '100,000', '', '', '', '', '', '', '')

string: '1,1,1.111  000,001.111   -999.  0.  111.110000  1.1.1.111  9.909,888'
           1,1,1.111  1,1,1.111  ('', '', '', '', '1,1,1.111', '', '', '', '')
         000,001.111  1.111  ('', '', '', '', '1.111', '', '', '', '')
               -999.  -999  ('-', '999', '', '', '', '', '', '', '')
                  0.  0  ('', '0', '', '', '', '', '', '', '')
          111.110000  111.11  ('', '', '', '', '111.11', '', '', '', '')

A:

The regex below will match both numbers from your example.
\b\d[\d,.]*\b

It will return 5000 and 99,999.99998713 - matching your requirements.


Q:

Fitness based ranking

If 3 variables $x[0]$, $x[1]$, $x[2]$ and their sum give the probability of the variable being selected as follows
$$\begin{align}
p[0] &= \frac{\text{sum}-x[0]}{2\times\text{sum}}\\
p[1] &= \frac{\text{sum}-x[1]}{2\times\text{sum}}\\
p[2] &= \frac{\text{sum}-x[2]}{2\times\text{sum}}
\end{align}$$
then, it is not a very good fitness based probability. because for the numbers $0.426, 0.036, 0.325$ the corresponding probabilities are $0.23, 0.48, 0.29$, although the second number is 10 times smaller than the other two, it only receives half the share.
Can someone suggest a better approach?

A:

[assuming I understood what you meant] use Exponential ranking: $p_j = \frac{e^{- \alpha x_j}}{\sum_j e^{- \alpha x_j}}$
Where $\alpha$ is a coefficient $>1$ if you need to increase the 'weight' of the individual with the lower value


Q:

ubuntu server unresponsive

Ubuntu server unresponsive 12.04
1) My site is not responding by http:
curl --request GET 'http://mysite.com'
curl: (7) couldn't connect to host
(doesn't respond on a web browser either)
2) Tried to ssh into it:
 ssh username@ip
ssh: connect to host ip_address port 22: Operation timed out
Is there another way to remotely check what's wrong with the server, without having to go to it?

A:

I would try to use nmap to see if the host is up or down (running nmap as sudo makes it report more accurately).  I would also suggest running dig or traceroute on your domain in order to make sure that it is not a problem somewhere in between you and your server.


Q:

Using menhir with sedlex

I need to use menhir with sedlex for whatever reason (utf-8), but don't know how to make the generated parser depend on Sedlexing instead of Lexing. Any tips?
When I run
menhir --infer parser.mly

the generated program has lines with Lexing.... I could change it manually, but there must be another way, no?

A:

EDIT: The parser.ml that is generated should have references to Lexing. Sedlexing is used to create the lexbuf that you send in to the parser, but the parser doesn't care if that lexbuf was created by Lexing or Sedlexing, as long as it can use functions like Lexing.lex_start_p and Lexing.lex_curr_p on it.

I used something like
ocamlbuild -use-menhir -tag thread -use-ocamlfind -quiet -pkg menhirLib \
  -pkg sedlex test.native

where test.ml uses parser.mly via calls to Parser.

For completeness, the command that's run by ocamlbuild is:
menhir --ocamlc 'ocamlfind ocamlc -thread -package sedlex -package menhirLib' \
  --explain --infer parser.mly

See a full example at https://github.com/unhammer/ocaml_cg_streamparse
(branch https://github.com/unhammer/ocaml_cg_streamparse/tree/match-singlechar-example shows a rule that matches a single code point like a or ß but not aa).


Q:

In $\mathbb{R}^n$, locally lipschitz on compact set implies lipschitz

I need to prove:

Let $A$ be open in $\mathbb{R}^m$, $g:A \longrightarrow \mathbb{R}^n$ a  locally lipschitz function and $C$ a compact subset of $A$.
Show that $g$ is lipschitz on $C$.

Can anyone help me?

A:

In general I prefer covering arguments (such as the one @WillieWong posted) to "choose a sequence and get a contradiction", but in this particular problem the second approach could be easier to implement (it avoids the technicalities pointed out by Willie).
Suppose $g$ is not Lipschitz on $C$: that is, there exists two sequences $x_n,y_n\in C$ such that $|g(x_n)-g(y_n)|/|x_n-y_n|\to \infty$. Since $g$ is bounded on $C$ (why?), we have $|x_n-y_n|\to 0$. Choose a convergent subsequence $x_{n_k}\to x$. Observe that the local Lipschitz-ness fails at $x$.

A:

Hint: $C$ being compact means for any open cover it has a finite subcover. Let $x\in C$ and let $U_x$ be the corresponding open set on which $g:U_x\to\mathbb{R}^n$ is Lipschitz. This means that $C$ can be covered by finitely many of the $U_x$. Lastly use the fact that the among a finite set of positive numbers you can choose a maximum one.

A:

Maximize the continuous function $f(x,y)=\frac{|g(x)-g(y)|}{|x-y|}$ over the compact set $C\times C\cap\{|x-y| \geq \varepsilon\}$ with a sufficiently small $\varepsilon>0$. Locally Lipschitz condition is used to show that $f$ is bounded in $C\times C\cap\{|x-y|<\varepsilon\}$.


Q:

Bootstrap - input-group-addon labels width alignment

Below you can see a picture of how my input groups are as of right now. I want the widths of the labels to be equal

(fx. the label takes up 25% of the width, and the input takes up the
  last 75%)

I have tried adding custom CSS, but that just ended up (for some reason) shrinking the entire thing.

I would prefer to make this dynamic

(as in not hardcoded px values, but % values, so it scales if you make
  the window smaller).

My code looks like this:

      Område:
      <select name="AreaId" asp-for="AreaId" class="form-control">
         <option disabled selected value=""> -- Vælg et område -- </option>
            @foreach (var a in Model.Areas) {
               <option value="@a.ProfileID">@a.Name</option>
            }
      </select>

      Varenummer:
      <input name="ProductNumber" asp-for="ProductNumber" class="form-control" type="text" placeholder="Indtast varenummer" maxlength="8" />

      Ordrenummer:
      <input name="OrderNumber" asp-for="OrderNumber" class="form-control" type="text" placeholder="Indtast ordrenummer" />

      Dato (Fra-Til):
      <input id="daterange" name="DateRange" asp-for="DateRange" class="form-control" type="text" value="" placeholder="Klik i boksen og vælg til/fra dato" />

Any help is GREATLY appreciated. Thanks in advance!
EDIT: Fixed my combination of form-group with input-group - The classes are no longer added at the same div
Also added a JSFiddle

A:

Add some css to your code it will work...
.input-group-addon {
    min-width:60%;
    text-align:left;
}

working code snippet

<meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

      Område:
      <select name="AreaId" asp-for="AreaId" class="form-control">
         <option disabled selected value=""> -- Vælg et område -- </option>
            @foreach (var a in Model.Areas) {
               <option value="@a.ProfileID">@a.Name</option>
            }
      </select>

      Varenummer:
      <input name="ProductNumber" asp-for="ProductNumber" class="form-control" type="text" placeholder="Indtast varenummer" maxlength="8" />

      Ordrenummer:
      <input name="OrderNumber" asp-for="OrderNumber" class="form-control" type="text" placeholder="Indtast ordrenummer" />

      Dato (Fra-Til):
      <input id="daterange" name="DateRange" asp-for="DateRange" class="form-control" type="text" value="" placeholder="Klik i boksen og vælg til/fra dato" />


Q:

Where is server.js in Bitnami?

bitnami server.js in the course
The teacher has the following directory for server.js in Bitnami. But I don't have this directory and I can't even find documentation for this

A:

You teacher is using a really old version of Parse (from 2016). The new Bitnami Parse solution includes the Parse files inside the /opt/bitnami/parse directory. You can find the server.js file in there.
If you want to perform any change in the configuration in the solution, we suggest you take a look at our documentation or our community forums in case you have any questions.
https://docs.bitnami.com/aws/apps/parse/
https://community.bitnami.com/


Q:

mysql: get record count between two date-time

I am stuck with a problem in MySQL. I want to get the count of records between two date-time entries.
For example:
I have a column in my table named 'created' having the datetime data type.
I want to count records which were created date-time between "TODAY'S 4:30 AM" and "CURRENT DATE TIME".
I tried some of MySQL's functions but still no luck with it.
Can you please help me with this?
thanks.

A:

May be with:
SELECT count(*) FROM `table`
where
    created_at>='2011-03-17 06:42:10' and created_at<='2011-03-17 07:42:50';

or use between:
SELECT count(*) FROM `table`
where
    created_at between '2011-03-17 06:42:10' and '2011-03-17 07:42:50';

You can change the datetime as per your need. May be use curdate() or now() to get the desired dates.

A:

select * from yourtable where created < now() and created > '2011-04-25 04:00:00'

A:

select * from yourtable
   where created < now()
     and created > concat(curdate(),' 4:30:00 AM')


Q:

Regular expression to match sets of numbers that are not equal nor reversed

I am referring as a follow up on this question here: Regular expression to match two numbers that are not equal
Now my other question scenario is this:
P121324 - T
P1212 - F - we got this covered in the message on link above (no same "sets")
P1221 - F - now new restriction - not even the reversed digits 12 - 21

But, the problem now is that the P string can be very long! - like this:
P121315162324

please notice this is ok since the "sets" are:
12 13 14 15 16 23 24

Now, I could make this in the code (PHP) by checking if there are repetitions, but I was wondering if this can be done with single regex command?

A:

Try this:
^P(?:([0-9])(?!\1)([0-9])(?!(?:..)*(?:\1\2|\2\1)))*$

If you want the digits to be restricted to [1-6] like in your previous question then change [0-9] to [1-6].
See it working online: rubular

Here is a breakdown of the regular expression:

^          Start of string/line.
P          Literal P
(?:<snip>) Non-capturing group that matches a distinct pair of digits. See below.
*          Zero or more pairs (use + if you want to require at least one pair).
$          End of string/line.

Explanation of ([0-9])(?!\1)([0-9])(?!(?:..)*(?:\1\2|\2\1)) - match one pair:

([0-9])    Match and capture the first digit. Later refered to as \1.
(?!\1)     Negative lookahead. The next character must not be the same as \1.
([0-9])    Match and capture a digit. Later refered to as \2.
(?!<snip>) Negative lookahead. Check that the pair doesn't occur again.

Explanation of (?:..)*(?:\1\2|\2\1) - try to find the same pair again:

(?:..)*       Match any number of pairs.
(?:\1\2|\2\1) Match either \1\2 or \2\1.


Q:

Virtualbox host-only network route is preempted by Pulse Secure VPN client

Virtualbox becomes unavailable for incoming connections from host OS when VPN is on. Accordingly, I cannot use http/ssh/rdp clients to access guest OS from host OS while Pulse Secure VPN stays connected.
Host OS: OSX High Sierra. My understanding is that a VPN client should not preempt routes in private IPv4 address space. Any workarounds to resolve this?

A:

I end up creating a script to launch my virtual machine. Limitation is that you have to launch the VM when VPN is off because Pulse Secure blocks creation of routes required.
I made this script a docked command for convenience -
#!/bin/bash

# visudo as root, add your_username ALL = (ALL) NOPASSWD:ALL

# vboxmanage list vms

guestip="192.168.86.3"
guestmac="8:0:27:22:4c:27"
vmname="WIN_ENT_10_64B"

# if the VM is running, leave it alone in peace:
vboxmanage showvminfo $vmname |grep "running (since"
[ "$?" -eq "0" ] && exit

# hide terminal window:
osascript -e 'tell application "Finder" to set visible of process "Terminal" to false'

# shutdown vbox network:
while [ -n "`netstat -rnf inet |grep $guestip`" ]; do
  sudo ifconfig vboxnet0 down
  sleep 1
done

# start VM and wait:
vboxmanage startvm $vmname --type separate
while [ -z "`netstat -rnf inet |grep $guestip`" ]; do
  sleep 1
done

# delete original route:
sudo route -n delete ${guestip%.*}.0

# create a network singularity in routing table:
sudo route -n add $guestip/32 -interface vboxnet0

# create the host on the network:
sudo arp -s $guestip $guestmac

osascript -e 'tell application "Terminal" to quit' &

The scripts assumes that you can use sudo without a password.
guestip is manually configured in guest OS on the "host only interface" (normally #2). When you create a "host only network adapter" in VirtualBox, it has DHCP enabled by default. I disable DHCP and assign a static IP in the guest OS manually for consistency reasons (here - 192.168.86.3, netmask 255.255.255.0 or CIDR /24, DNS left blank).
guestmac is MAC address of the network interface in the guest OS that has the IP 192.168.86.3. Do not confuse it with MAC address of the "host only network adapter" in VirtualBox configuration. The latter is configured with 192.168.86.1/24 in our case (MAC a:0:27:0:0:0 below).
After the script completes (terminal app disappears from the dock), expected output of netstat -rnf inet shall comprise similar entries:
192.168.86.3       8:0:27:22:4c:27    UHLS            3     4884 vboxnet
192.168.86.3/32    a:0:27:0:0:0       ULSc            0        0 vboxnet

These entries will persist across VPN connects/disconnects and let you access your VM locally regardless of the VPN state.


Q:

Adding Html Code Dynamically to a div

private void GetGroupListHtml()
{
                //...Code omitted
                String htmlCode = String.Empty;

                foreach (DataRow _DataRow in _DataTable.Rows)
                {
                    htmlCode += @"

                                  <asp:Label ID=""groupTitleLabel"" runat=""server"" Text=" +_DataRow["groupName"] +  @"""></asp:Label>

                                 <button class=""btn btn-box-tool"" data-widget=""collapse"" data-toggle=""tooltip"" title=""Expand""></button>

";
                }
}

I want to add the htmlCodes to a div. Is it possible to do it this way? Basically i have a string variable which appends the html codes. I want to dump this code in between the div tag and return the new webpage to the user.

A:

First of all use StringBuilder for concatenating strings instead of using the += sign.
StringBuilder sb = new StringBuilder();
sb.Append("<...>"); // Your html code

After that if you want to append this generated html to your page, use a <asp:Panel runat="server" id="pnlCode"></asp:Panel> tag that is located on your page where you want to add the html code.
Then in your code behind simply do:
this.pnlCode.Controls.add(new LiteralControl() { Text = sb.ToString() });

This takes your html as a string, put it into a control and then append it to your panel onto your page.


Q:

How does the opencl command queue work, and what can I ask of it

I'm working on an algorithm that does prettymuch the same operation a bunch of times. Since the operation consists of some linear algebra(BLAS), I thourght I would try using the GPU for this.
I've writen my kernel and started pushing kernels on the command queue. Since I don't wanna wait after each call I figures I would try daisy-chaining my calls with events and just start pushing these on the queue.
call kernel1(return event1)
call kernel2(wait for event 1, return event 2)
...
call kernel1000000(vait for event 999999)

Now my question is, does all of this get pushed to the graphic chip of does the driver store the queue? It there a bound on the number of event I can use, or to the length of the command queue, I've looked around but I've not been able to find this.
I'm using atMonitor to check the utilization of my gpu' and its pretty hard to push it above 20%, could this simply be becaurse I'm not able to push the calls out there fast enough? My data is already stored on the GPU and all I'm passing out there is the actual calls.

A:

First, you shouldn't wait for an event from a previous kernel unless the next kernel has data dependencies on that previous kernel. Device utilization (normally) depends on there always being something ready-to-go in the queue. Only wait for an event when you need to wait for an event.

"does all of this get pushed to the graphic chip of does the driver store the queue?"

That's implementation-defined. Remember, OpenCL works on more than just GPUs! In terms of the CUDA-style device/host dichotomy, you should probably consider command queue operations (for most implementations) on the "host."
Try queuing up multiple kernels calls without waits in-between them. Also, make sure you are a using an optimal work group size. If you do both of those, you should be able to max out your device.


Q:

Covid-19: can a UV-C source be improvised from a standard mercury vapor lamp?

I suggest it because the usual professional UV-C sources are in short supply and very costly.
A common 175 W mercury lamp designed for illumination includes the quartz 'lamp' tube itself, inside an outer bulb designed to block UV-C (< 300 nm) radiation. If the outer bulb were removed, this kind of lamp would seem to be able to provide UV-C to destroy a virus.
I don't have a UV-C capable spectrometer nor a power meter filtered for UV-C only, so I can't test/do the experiment myself. Maybe someone else has such gear.
A document on this is here, and it includes references. I do not suggest that this be done except by those who understand the hazards of the experiment.
I believe that it's better to throw an idea on the table in front of engineers and technicians, than to hide ideas that may be helpful or to post untried projects on hack sites and prepper forums where they may do more harm than good. Known hazards include: UV radiation, high voltage, high temperature, broken glass.
If someone has the gear to try it, maybe it could help the situation.
The document is here, somewat hidden by obscurity.
ADDED 4/3/ 2020:
I should have stated that my goal was primarily to disinfect masks for re-use. I didn't want to limit the scope, being more interested in spectrum and power per square area at given distance.
I too, worked with an e-prom eraser, but from a repair perspective. The original UV tube was broken and unavailable. I put in two UV-C germicidal lamps. It worked perfectly and saved the customer money.
Some masks can be treated by heat or chemicals, and some may contain materials that are ruined quickly or are not properly disinfected by those and other methods. The type and construction of mask will dictate the best way to disinfect it for maximum re-use.
Treating every surface of an arbitrarily shaped object with sufficient UV intensity for sufficient time is a challenge. It's not impossible. Two UV lamps could be used, or a rotisserie arrangement, using an alligator clip to hold a mask, or any other arrangement, may be worthwhile. We can use our imaginations.
The risk of transmission from handling objects is significant and supported by expert opinion of an experienced doctor, James Robb, MD FCAP, here.
There was, and will not be, any suggestion whatsoever that anyone get some Covid-19 Coronavirus and irradiate it, then try to prove it’s worked. There are experts in the field who know how much UV-C intensity per area and irradiation time is required to inactivate the virus. There is such information for other viruses online.
While there are no studies specifically on Covid-19, Ozone has been shown to kill the SARS Coronavirus. Ozone is unstable and wants to revert to O2 and lose the third Oxygen atom. If the third atom of Oxygen does not find another Oxygen atom to combine with, it can break the virus so that it can't function. While Ozone can damage some materials, it does disinfect them.
There are several references, to scholarly work, in online articles to support the statement made in the comment.
Link1 to references
and
Link2 to references
At least one paper states that atomic Oxygen can recombine in a time scale of a few milliseconds. Our senses and the above references tell us that it can be produced in copious enough amounts to be effective in spite of this.
Solutions don't have to be clever, they only have to be workable. A Dallas, Texas mattress-cleaning company is already using its production line to sterilize masks for hospitals. It seems obvious but it's extending the lifetime of disposable masks from 1 day to > a week.
What the UV (and Ozone comment) information may mean for the public, who may soon be told to wear masks or face coverings outdoors, that that a mask could be safely used for a very long time. Ozone generation is another topic.
I clarify that I am not posting here for any pecuniary purpose. I have only one old set of PPE. Unfortunately it is only effective on October 31. A bit of levity keeps me motivated.

A:

Yes, but only for killing viruses in the near vicinity. Not to use it when live people, animals are nearby. Also it would accelerate ageing of colours, plastics, wood,...Not a very clever solution, but if desperately needed could be a way to go.


Q:

Removing a substring from a column in a text file

I have a shell script:
a ab.mi
3 jm.mi
56 uh.mi

I want to remove .mi from the 2nd column and make it like:
a ab
3 jm
56 uh

How can I do this with shell script?

A:

Using awk:
awk 'gsub("\.mi", "", $2)1' inputfile

This would remove .mi from the second column.


Q:

Do the tasks on the active workspace have higher priority?

For this time I won't bother anyone with technical problems. I just had a philosophical question. Well it's in the title, I guess it's clear enough :p
Well actually the question is more general: what are workspaces? Do they differ only by what is displayed on it (the processes being totally independently defined/prioritized)? Or do they really kindof own or are connected to the applications you launch on them?
Yop, that's all! Thanks you for reading!
Julien

A:

Workspaces are just something to structure your windows better. They don't group processes, or edit their priority.


Q:

Putting a method with arguments into a variable, in JavaScript

Sometimes I have difficulty in understanding the logic behind JavaScript and this is one example of something I often see. Here is a simple function that will be passed to a timer:
function myCounter() {
   //do something...
}

You can just pass it like this:
setInterval(myCounter, 1000);
But, often we need to have the means to stop it so we assign it to a variable:
var t = setInterval(myCounter, 1000);

This allows it to be cleared later like this:
clearInterval(t);

I use this all the time but it bothers me that I don't understand exactly what I am putting into the variable, and why typeof t returns a number. What exactly have I put in t? Can anyone explain the logic behind this?

A:

When you assign an interval to a variable, you are actually assigning an ID. That ID is then used when you use clearInterval to select which timer to clear. The reason typeof returns a number, is because an ID is a number.
Here is a detailed explanation.
MDN is a fantastic resource for this sort of thing, I highly recommend it


Q:

Resizing images (jpeg or decompressed image)

In my last question I asked whether there was a better way to rotate images than I had thought of. I ended up discovering jpegtran and have since found libjpeg-turbo.
Now I am looking for a better way to resize the images (jpegs) than imagemagick and graphicsmagick.
Is there a specialized commandline tool to resize the images in a more efficient way than imagemagick or graphicsmagick? Maybe the resizing can be done on the GPU using opencl or opengl?
The provided hardware is the same as in the other post:

Intel Atom D525 (1,8 Ghz)
Mobility Radeon HD 5430 Series
4 GB of RAM
SSD Vertility 3

A:

Check this link out: http://leocharre.com/articles/faster-image-resizing-in-linux/
In particular the author mentions that imgresize is faster than imagemagick, and epeg is extremely fast.
epeg (http://www.systhread.net/texts/200507epeg1.php) seems quite well documented for generating thumbnails. If the quality is good enough, this could be the solution.

A:

OpenCL is a standard for cross-platform, parallel programming of modern processors found in personal computers, servers and handheld/embedded devices. It's directly supported by ATI. You'll need to get AMD APP SDK (formerly known as AMD Stream SDK) to get GPU support (also check out this getting started guide).
Take a look at Intel's IPP - Integrated Performance Primitives. It's a multi-threaded software library of functions for multimedia and data processing applications. Among other features, it's has functions to resize images (bilinear, nearest neighbor, etc). Unfortunately, it is not free (cheapest version costs $199).
VIPS is a free image processing system. It claims that compared to most image processing libraries, VIPS needs little memory and runs quickly, especially on machines with more than one CPU. See the Speed and Memory Use page for a simple benchmark against other similar systems.


Q:

DB2 alias in WHERE clause

I have a couple DB2 tables, one for users and one for newsletters and I want to select using an alias in the WHERE clause.
SELECT a.*, b.tech_id as user FROM users a
JOIN newsletter b ON b.tech_id = a.newsletter_id
WHERE timestamp(user) < current_timestamp

This is radically simplified so I can see what's going on, but I am getting an error that makes me think that the user alias isn't getting passed correctly:
ERROR: An invalid datetime format was detected; that is, an
invalid string representation or value was specified.

The user.tech_id is a string built from the datetime when the record was created, so it looks something like 20150210175040951186000000. I've verified that I can execute a timestamp(tech_id) successfully-- so it can't be the format of the field causing the problem.
Any ideas?
More information:
There's multiple newsletters per user. I need to get the most recent newsletter (by the tech_id) and check if that was created in the past week. So the more complex version would be something like:
SELECT a.*, b.tech_id as user FROM users a
JOIN newsletter b ON b.tech_id = a.newsletter_id
WHERE timestamp(max(user)) < current_timestamp

Is there a way to JOIN only on the most recent record?

A:

To get most recent newsletter of user, consider ordering the join query, then select top record (in DB2 you would use FETCH FIRST ONLY):
SELECT a.*, b.tech_id as user
  FROM users a
INNER JOIN newsletter b ON b.tech_id = a.newsletter_id
ORDER BY b.tech_id
FETCH FIRST 1 ROW ONLY;

Alternatively, you can use a subquery in WHERE clause that aggregates the max user:
SELECT a.*, b.tech_id as user
  FROM users a
WHERE b.tech_id IN (
  SELECT Max(n.tech_id) as maxUser
  FROM users u
  INNER JOIN newsletter n ON n.tech_id = u.newsletter_id)

I left out the condition of timestamp(user) < current_timestamp as data stored in database will always be less than current time (i.e., now).


Q:

Page Object Model or JavaScript testing alternatives?

Is the Page Object Model still the best way to automate web applications ?
For me the Screenplay pattern seems a nicer way to manage it.
Or using JavaScript alternatives like Acceptance Testing with Cucumber.js & WebdriverIO for example.

A:

Your question makes it sound like there is only one answer, but actually you can merge these all together if you code it correctly.
Page Object Model
This is good for separation of the elements on the page from the rest of your code. If implemented correctly, a change on the page can be corrected for all scenarios using that page by simply changing one line in the POM.
nextButton.click();
fullName.sendKeys("John Doe");

Screenplay Pattern
This is good for separation of actions that occur on the different pages, the different workflows.
james.attemptsTo(
   goToTheNextPage(),
   fillOutHisDetails()
);

If the journey has workflow that is slightly changed, the idea is that you can simply reorder the Screenplay pattern, or remove the actions that are no longer necessary.
In the example above, if the business were to decide that the registration form should be a single page instead of multiple, it would make more sense to delete this single line:
goToTheNextPage(),

instead of deleting the 2 that I would have put in:
driver.findElement({css:"#next"}).click();
driver.findElement({css:"#registrationDetails"});

CucumberJS + WebdriverIO
This is good to portray the information of a scenario in pure business language.
Scenario: I am filling out the registration form
   Given I am a new user
     And I want to register for an account
   When I fill out the registration form
   Then I should be able to log in

Merging them
If you want truely human readable code, you can merge all 3 of these.
You have your feature file at business level language.
You have your step definitions written with the Screenplay pattern in mind.
You have the Screenplay pattern steps written with the Page Object Model.
This may seem like a lot of layers, but it means that the business will be able to understand the scenarios, the testers and developers looking back over the code will understand the workflow of a certain journey, and looking further into the code on debugging will allow the tester to change the element values across multiple journeys by only changing one line of code.


Q:

What happens to the old object if you set a variable equal to a new object?

Say we have a class X that does not have an overloaded operator=() function.
class X {
    int n;

    X() {n = 0;}
    X(int _n) {n = _n;}
};

int main() {
    X a;    // (1) an object gets constructed here

    // more code...

    a = X(7);    // (2) another object gets constructed here (?)

    // some more code...

    a = X(12);    // (3) yet another object constructed here (?)
    return 0;
}

Is a new object constructed at (2)? If it is, what happens to the old object that was constructed at (1)? Is it automatically destructed or deallocated (which is it)? Is it overwritten?
And what happens farther down the code at (3)?
And most importantly, is there ever a chance of causing a memory leak by writing code like in the above?

A:

At point (2) three things happen:

A temp object is constructed using the X(int _n) constructor.
The default assignment operator is used to copy the contents of the temporary to a.
The temporary goes out of scope and its default destructor is invoked.

The same thing happens at point (3).
At the end of the function, the default destructor on a is invoked.

A:

What you need to understand is that there's a lot of "implicit" code generated by the compiler that you, as a novice, don't know about. We'll use your code for class X as a direct example:
class X {
    int n;
public: //You didn't include this, but this won't work at all unless your constructors are public
    X() {n = 0;}
    X(int _n) {n = _n;}
};

Before the code gets turned into Object Code, but after your compiler gets ahold of your class definition, it transforms your class into something that looks (roughly) like this:
class X {
    int n;
public:
    X() {n = 0;} //Default-Constructor
    X(int _n) {n = _n;} //Other Constructor
    //GENERATED BY COMPILER
    X(X const& x) {n = x.n;} //Copy-Constructor
    X(X && x) {n = x.n;} //Move-Constructor
    X & operator=(X const& x) {n = x.n; return *this;} //Copy-Assignment
    X & operator=(X && x) {n = x.n; return *this;} //Move-Assignment
    ~X() noexcept {} //Destructor
};

The rules for when these members are automatically created are not super-obvious (A good starting reference here), but for now, you can trust that in this case, that's exactly what happens.
So in your main function, let's go over what happens, with the specifics called attention to with comments:
int main() {
    X a; //Default-Constructor called
    a = X(7);//Other Constructor called, then Move-Assignment operator called,
    //then Destructor called on temporary created by `X(7)`
    a = X(12); //Same as previous line

    return 0;
    //Destructor called on `a`
}

We'll add a few more lines to show most (if not all) of the various permutations of these calls:
int main() {
    X a; //Default-Constructor
    X b = a; //Copy-Constructor (uses copy-elision to avoid calling Default + copy-assign)
    X c(5); //Other Constructor
    X d{7}; //Also Other Constructor
    X e(); //Declares a function! Probably not what you intended!
    X f{}; //Default-Constructor
    X g = X(8); //Other Constructor (uses copy-elision to avoid calling Other + move-assign + Destructor)
    X h = std::move(b); //Move-Constructor (uses copy-elision to avoid calling Default + move-assign)
    b = c; //Copy-assignment
    b = std::move(d); //Move-assignment
    d = X{15}; //Other Constructor, then Move-Assignment, then Destructor on `X{15}`.
    //e = f; //Will not compile because `e` is a function declaration!
    return 0;
    //Destructor on `h`
    //Destructor on `g`
    //Destructor on `f`
    //Destructor will NOT be called on `e` because `e` was a function declaration,
    //not an object, and thus has nothing to clean up!
    //Destructor on `d`
    //Destructor on `c`
    //Destructor on `b`
    //Destructor on `a`
}

That should cover the basics.

And most importantly, is there ever a chance of causing a memory leak by writing code like in the above?

As written, no. However, suppose your class did something like this instead:
class X {
    int * ptr;
public:
    X() {
        ptr = new int{0};
    }
};

Now, your code would leak, because every time an X was created, you'd have a pointer that never gets deleted.
To solve this, you need to make sure that A) The destructor properly cleans up the pointer, and B) that your copy/move constructors/operators are correct.
class X {
    int * ptr;
public:
    X() {
        ptr = new int{0};
    }
    X(int val) {
        ptr = new int{val};
    }
    X(X const& x) : X() {
        *ptr = *(x.ptr);
    }
    X(X && x) : X() {
        std::swap(ptr, x.ptr);
    }
    X & operator=(X const& x) {
        *ptr = *(x.ptr);
        return *this;
    }
    X & operator=(X && x) {
        std::swap(ptr, x.ptr);
        return *this;
    }
    ~X() noexcept {
        delete ptr;
    }
};

This code will not leak memory if used as-is in either your main function or mine. But of course, it doesn't stop the leaks if you do something like this:
int main() {
    X * ptr = new X{};
    return 0;
    //Whelp.
}

In general, if you never need to use pointers at all, it's recommended you use something like std::unique_ptr instead, as it gives most of this stuff for free.
int main() {
    std::unique_ptr<X> ptr{new X{}};
    return 0;
    //Destructor called on *ptr
    //`delete` called on ptr
}

And it's a good idea in your original class, with a caveat that, unless you explicitly change it, your class won't by copyable anymore (though it'll still be movable):
class X {
    std::unique_ptr<int> ptr;
public:
    X() {
        ptr.reset(new int{0});
    }
    X(int val) {
        ptr.reset(new int{val});
    }
    //X(X && x); //auto generated by compiler
    //X & operator=(X && x); //auto generated by compiler
    //~X() noexcept; //auto generated by compiler

    //X(X const& x); //Deleted by compiler
    //X & operator=(X const& x); //Deleted by compiler
};

We can see the changes in my previous version of main:
int main() {
    X a; //Default-Constructor
    //X b = a; //Was Copy-Constructor, no longer compiles
    X c(5); //Other Constructor
    X d{7}; //Also Other Constructor
    X f{}; //Default-Constructor
    X g = X(8); //Other Constructor (uses copy-elision to avoid calling Other + move-assign + Destructor)
    X h = std::move(c); //Move-Constructor (uses copy-elision to avoid calling Default + move-assign)
    //b = c; //Was Copy-assignment, no longer compiles
    c = std::move(d); //Move-assignment
    d = X{15}; //Other Constructor, then Move-Assignment, then Destructor on `X{15}`.
    return 0;
    //Destructor on `h`
    //Destructor on `g`
    //Destructor on `f`
    //Destructor on `d`
    //Destructor on `c`
    //Destructor on `a`
}

If you want to use std::unique_ptr, but also want the resulting class to be copyable, you'll need to implement the copy constructor yourself using the techniques I discussed.
And that should be about it! Let me know if I missed anything.


Q:

STM32F4 - counting DMA wraps

I am using DMA on an STM32F4 Discovery board to push values from an array into a peripheral. This needs to be done repeatedly, so I am using the circular DMA mode:

DMA_InitStruct.DMA_Mode = DMA_Mode_Circular;

which gets the DMA source address to jump back to the start of the array automatically.
I would like to count how many times this wrap has happened. Is there an interrupt or other feature built in to do this?

A:

STM32 DMA has some interrupts. You can try to use the DMA_IT_TC flag. I have not tested it with mode from array to periph, but it worked with periph to array (example from my code):
DMA_ITConfig(DMA2_Stream0, DMA_IT_TC, ENABLE);

You should have also to set up NVIC interrupt (example):
ADCNVICConfig.NVIC_IRQChannel = DMA2_Stream0_IRQn;
ADCNVICConfig.NVIC_IRQChannelPreemptionPriority = 0;
ADCNVICConfig.NVIC_IRQChannelSubPriority = 1;
ADCNVICConfig.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&ADCNVICConfig);

TC flag means "transfer completed".
Example interrupt:
void DMA2_Stream0_IRQHandler(void)
{

    //Something

    if(DMA_GetITStatus(DMA2_Stream0, DMA_IT_TCIF0) != RESET)
    {
        DMA_ClearITPendingBit(DMA2_Stream0, DMA_IT_TCIF0);
        //Something
    }

    //Something

}


Q:

Проблема закрытия файла fclose (язык С)

По заданию мне нужно считать базу данных из файла .txt в поля структуры. По отладчику смотрела, что все хорошо записывается(в сами структуры). Но при закрытии файла ловлю exception.
3456109
Kirov
Nikolay
Olegovich
M
12
12
1993
184
86
Minsk
guitar playing, painting
smoking
Surgeon
20
25
-

Это пример информации из файла для записи в поля структуры (последующие лежат в таком же виде, начиная со следующей строки)
.
На строке fclose(f) ломается. Может кто знает, в чем может быть проблема?
#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h >
#define LINE 1024

typedef struct DateOfBirth {
    int day;
    int month;
    int year;
};

typedef struct Human {
    char id[7];        //регистрационный номер
    char surname[20];   //фамилия
    char name[20];      //имя
    char patronymic[20];  //отчество
    char sex[2];  //пол
    DateOfBirth dateOfBirth;  //дата рождения
    int height;   //рост
    int weight;   //вес
    char city[15];   //город
    char interests[30]; //интересы
    char badHabits[20]; //вредные привычки
    char textMyself[30];  //информация о себе
    int prefAgeMin;  //желаемый диапазон возраста
    int prefAgeMax;
    char prefBadHab[20];      //желаемые вредные привычки
};

long checkSize() {
    FILE * f;
    errno_t err;
    int linesCount = 0;
    err = fopen_s(&f, "database.txt", "r"); //проверка на нахождение файла и его открытие
    if (err) {
        printf("Cannot open file");
        _getch();
        exit(1);
    }
    else {
        char *tempBuffer = (char*)malloc(sizeof(char) * 1000000);
        while (!feof(f)) {
            fgets(tempBuffer, 100, f);
            linesCount++;
        }
    }
    fclose(f);
    return linesCount / 17;

}

Human* readingFromFile(int lines) {
    FILE *f;
    Human *human = (Human*)malloc(sizeof(Human)*lines);
    errno_t err;
    err = fopen_s(&f, "database.txt", "r"); //проверка на нахождение файла и его открытие
    if (err) {
        printf("Cannot open file");
        fclose(f);
        _getch();
        exit(1);
    }
    else {
        fseek(f, 0, SEEK_SET);
        for (int i = 0; i < lines && !feof(f) && human; i++)
        {
            fscanf_s(f, "%s", human[i].id, LINE);
            fscanf_s(f, "%s", human[i].surname, LINE);
            fscanf_s(f, "%s", human[i].name, LINE);
            fscanf_s(f, "%s", human[i].patronymic, LINE);
            fscanf_s(f, "%s", human[i].sex, LINE);
            fscanf_s(f, "%d", &human[i].dateOfBirth.day, LINE);
            fscanf_s(f, "%d", &human[i].dateOfBirth.month, LINE);
            fscanf_s(f, "%d", &human[i].dateOfBirth.year, LINE);
            fscanf_s(f, "%d", &human[i].height, LINE);
            fscanf_s(f, "%d", &human[i].weight, LINE);
            fscanf_s(f, "%s", human[i].city, LINE);
            fseek(f, 2, SEEK_CUR);
            fgets(human[i].interests, 100, f);
            int pos = strcspn(human[i].interests, "\n");
            human[i].interests[pos] = '\0';
            fgets(human[i].badHabits, 100, f);
            pos = strcspn(human[i].badHabits, "\n");
            human[i].badHabits[pos] = '\0';
            fgets(human[i].textMyself, 100, f);
            pos = strcspn(human[i].textMyself, "\n");
            human[i].textMyself[pos] = '\0';
            fscanf_s(f, "%d", &human[i].prefAgeMin, LINE);
            fscanf_s(f, "%d", &human[i].prefAgeMax, LINE);
            fseek(f, 2, SEEK_CUR);
            fgets(human[i].prefBadHab, 100, f);
            pos = strcspn(human[i].prefBadHab, "\n");
            human[i].prefBadHab[pos] = '\0';
        }
        if (fclose(f) == EOF)
            printf("bbooom\n");
        else
            printf("done\n");
        return human;
    }
}

void printOnConsole(Human **human, int size) {
    printf("\n%7s |%10s |%10s |%10s |%4s |%13s |%3s |%3s |%10s |%15s |%12s |%21s |%6s |%6s |%9s", "Id", "Surname", "Name", "Patronymic", "Sex", "Birthday", "H", "W", "City", "Interests", "Habbits", "SelfInfo", "MinAge", "MaxAge", "WantedHab");
    int i = 0;
    while (i != size) {
        printf("\n%7s |%10s |%10s |%10s |%4s |%3d/%3d/%5d |%3d |%3d |%10s |%15s |%12s |%21s |%6d |%6d |%9s", human[i]->id, human[i]->surname, human[i]->name, human[i]->patronymic, human[i]->sex, human[i]->dateOfBirth.day, human[i]->dateOfBirth.month, human[i]->dateOfBirth.year, human[i]->height, human[i]->weight, human[i]->city, human[i]->interests, human[i]->badHabits, human[i]->textMyself, human[i]->prefAgeMin, human[i]->prefAgeMax, human[i]->prefBadHab);
        i++;
    }
}

void loadToFile(Human **human, int lines) {
    FILE *f;
    errno_t err;
    err = fopen_s(&f, "database2.txt", "w"); //проверка на нахождение файла и его открытие
    if (err) {
        printf("Cannot open file");
        fclose(f);
        _getch();
        exit(1);
    }
    else {
        fseek(f, 0, SEEK_SET);
        for (int i = 0; i < lines && human; i++)
        {
            fprintf_s(f, "%s", human[i]->id, LINE);
            fprintf_s(f, "%s", human[i]->surname, LINE);
            fprintf_s(f, "%s", human[i]->name, LINE);
            fprintf_s(f, "%s", human[i]->patronymic, LINE);
            fprintf_s(f, "%s", human[i]->sex, LINE);
            fprintf_s(f, "%d", &human[i]->dateOfBirth.day, LINE);
            fprintf_s(f, "%d", &human[i]->dateOfBirth.month, LINE);
            fprintf_s(f, "%d", &human[i]->dateOfBirth.year, LINE);
            fprintf_s(f, "%d", &human[i]->height, LINE);
            fprintf_s(f, "%d", &human[i]->height, LINE);
            fprintf_s(f, "%d", &human[i]->weight, LINE);
            fprintf_s(f, "%s", human[i]->city, LINE);
            fseek(f, 2, SEEK_CUR);
            fputs(human[i]->interests, f);
            fputs(human[i]->badHabits, f);
            fputs(human[i]->textMyself, f);
            fprintf_s(f, "%d", &human[i]->prefAgeMin, LINE);
            fprintf_s(f, "%d", &human[i]->prefAgeMax, LINE);
            fseek(f, 2, SEEK_CUR);
            fputs(human[i]->prefBadHab, f);
        }
        fclose(f);
    }
}

int main()
{
    int size = checkSize();
    Human *human = readingFromFile(size);
    printOnConsole(&human, size);
    loadToFile(&human, size);
    _getch();
    return 0;
}

A:

У вас куча ошибок и недочётов, и поэтому непонятно, откуда может возникнуть ошибка. Предлагаю просто следить за моей мыслью, и у вас всё будет хорошо для сдачи лабораторной. :) (и код понятнее сделаем, и рабочим всё сделаем). При компиляции использовались ключи -ansi , -pedantic , -Wall и -Werror( могут и не использоваться : они всего лишь для самопроверки :D ).
Сами структуры

Посмотрите на DateOfBirth и Human. Раз вы делаете typedef, то
нужно придумать имя для вашего псевдонима, а у вас оно вообще
отсутствует (не понимаю, как ваш C-компилятор этого не заметил, если
это вообще C-компилятор).
Исправляем, назначив то же имя, как и у самой структуры :
typedef struct DateOfBirth {...} DateOfBirth;
typedef struct Human {...} Human;

Когда вы работаете с такими структурами (да и ещё с файлами, которые
с ней потенциально связаны), вам нужно (а по-моему, просто
необходимо) использовать платформонезависимые типы (char-тип, к
счастью, можно оставить). Список полей, в итоге, может быть
следующим (заголовочный файл stdint.h).
Для DateOfBirth :
/*дни не могут быть отрицательными + за границы 256 дней по смыслу не выйти*/
uint8_t day;
/*аналогично*/
uint8_t month;
/*то же самое, только для 2-х байтов*/
uint16_t year;

Для Human (аналогия с полей DateOfBirth):
char id[8]; /*3456109 не 'влезет' в ваш 'char id[7]' : '\0' неуда вмещать*/
char surname[20];
char name[20];
char patronymic[20];
char sex[2];
DateOfBirth dateOfBirth;
uint8_t height;
uint8_t weight;
char city[15];
char interests[30];
char badHabits[20];
char textMyself[30];
uint8_t prefAgeMin;
uint8_t prefAgeMax;
char prefBadHab[20];

Если вы выделяете память для такой структуры в таком положении вещей, то
вы, по факту выделяете больше, чем нужно (у вас такое есть в checkSize). Посмотрим размер "старого"
Human :
printf("%lu\n", sizeof(Human)); /*216*/

А если внимательно посчитаете, то по факту получите 212 :)
Дело всё в
выравнивании,
но не будем заострять на этом внимание. Короче говоря, можете 'обвернуть' структуры (на всякий случай DateOfBirth тоже, а то мало ли, как машина 'захочет'), ипользуя #pragma pack (push,1) и #pragma pack (pop) перед определением и после определения "алиаса" для структуры соответственно, то есть :
#pragma pack (push, 1)
typedef struct DateOfBirth {...} DateOfBirth;
#pragma pack (pop)

и
#pragma pack (push, 1)
typedef struct Human {...} Human;
#pragma pack (pop)

Этот пункт не является обязательным, поскольку pragma разнится в
зависимости от её реализации, но является желательным, если есть
такая возможность и нельзя по-другому исправить структуру.

В итоге, ваши определения могут быть следующими :
#define ID_SIZE 8
#define SURNAME_SIZE 20
#define NAME_SIZE 20
#define PATRONYMIC_SIZE 20
#define SEX_SIZE 2
#define CITY_SIZE 15
#define INTERESTS_SIZE 30
#define BADHABITS_SIZE 20
#define TEXTMYSELF_SIZE 30
#define PREFBADHAB_SIZE 20

#pragma pack (push, 1)
typedef struct DateOfBirth {
    uint8_t day;
    uint8_t month;
    uint16_t year;
} DateOfBirth;
#pragma pack (pop)

#pragma pack (push, 1)
typedef struct Human {
    char id[ID_SIZE];
    char surname[SURNAME_SIZE];
    char name[NAME_SIZE];
    char patronymic[PATRONYMIC_SIZE];
    char sex[SEX_SIZE];
    DateOfBirth dateOfBirth;
    uint8_t height;
    uint8_t weight;
    char city[CITY_SIZE];
    char interests[INTERESTS_SIZE];
    char badHabits[BADHABITS_SIZE];
    char textMyself[TEXTMYSELF_SIZE];
    uint8_t prefAgeMin;
    uint8_t prefAgeMax;
    char prefBadHab[PREFBADHAB_SIZE];
} Human;
#pragma pack (pop)

checkSize
У вас там мало того, что память выделенная не освобождается, так и слишком запутанный и непереиспользуемый код.

"сложнА-сложнААА" (c)

Предлагаю более подходящий вариант сигнатуры функции и её реализации (здесь уже "опустим" вопрос с кроссплатформенностью, ибо гораздо менее важно):
size_t get_humans_count ( const char* filename )
{
    FILE* fp;
    size_t lines_count = 0;
    char line[ MAX_LINE_SIZE ];

    fp = fopen( filename, "r" );
    if ( NULL == fp ) return 0;

    while ( fgets( line, MAX_LINE_SIZE, fp ) != NULL )
    {
        if ( 0 == is_empty(line) )
        {
            fclose(fp);
            return 0;
        }
        lines_count++;
    }

    fclose(fp);
    return lines_count / HUMAN_LINES_COUNT;
}

Реализация is_empty ( была позаимствована и немного переделана отсюда ):
static int is_empty (const char *s)
{
  while ( *s != '\0' )
  {
    if ( ! isspace( (unsigned char) *s ) ) return -1;
    s++;
  }
  return 0;
}

is_empty нужен для того, чтобы вы не могли засчитать 'пустую' строку, как актуальную для записи её в структуру.
Протестируйте сами: оставьте где-нибудь 'пустые' строки, т.е. строки, содержащие только пробельный(-е) символ(-ы). В вашей реализации это бы засчиталось, и вы бы записали в какое-нибудь поле структуры 'пустую' строку.
В данном случае поля должны идти друг за другом, а иначе функция вернёт 0 ( единственный 'минус' тут в неудобочитаемости читаемого файла, потому что описания будут 'слиты', но реализация разделения - это просто и дело "десятое", и я не буду на этом останавливаться ).
readingFromFile
Я "убил" весь день на то, чтобы правильно вывести прочитанные данные в структуру. Немного длиннее, но выглядит это всё более логично, а от такой структурированности маловероятно получить ошибку :
Human* get_humans_from ( const char* filename )
{
    FILE* fp;
    Human* humans_buffer;
    size_t humans_counter = 0;
    size_t humans_count = get_humans_count(filename);

    fp = fopen( filename, "r" );
    if ( NULL == fp || 0 == humans_count ) return NULL;

    humans_buffer = ( Human* ) malloc( sizeof(Human) * humans_count );
    if ( NULL == humans_buffer ) return NULL;

    while ( humans_counter < humans_count)
    {
        read_and_adjust_string( fp, humans_buffer[humans_counter].id );
        read_and_adjust_string( fp, humans_buffer[humans_counter].surname );
        read_and_adjust_string( fp, humans_buffer[humans_counter].name );
        read_and_adjust_string( fp, humans_buffer[humans_counter].patronymic );
        read_and_adjust_string( fp, humans_buffer[humans_counter].sex );

        humans_buffer[humans_counter].dateOfBirth.day = (uint8_t) read_and_get_ul ( fp ) ;
        humans_buffer[humans_counter].dateOfBirth.month = (uint8_t) read_and_get_ul ( fp );
        humans_buffer[humans_counter].dateOfBirth.year = (uint16_t) read_and_get_ul ( fp );
        humans_buffer[humans_counter].height = (uint8_t) read_and_get_ul ( fp );
        humans_buffer[humans_counter].weight = (uint8_t) read_and_get_ul ( fp );

        read_and_adjust_string( fp, humans_buffer[humans_counter].city );
        read_and_adjust_string( fp, humans_buffer[humans_counter].interests );
        read_and_adjust_string( fp, humans_buffer[humans_counter].badHabits );
        read_and_adjust_string( fp, humans_buffer[humans_counter].textMyself );

        humans_buffer[humans_counter].prefAgeMin = (uint8_t) read_and_get_ul ( fp );
        humans_buffer[humans_counter].prefAgeMax = (uint8_t) read_and_get_ul ( fp );

        read_and_adjust_string( fp, humans_buffer[humans_counter].prefBadHab );
        print_human_info(humans_buffer[humans_counter]);
        humans_counter++;
    }

    fclose(fp);
    return humans_buffer;
}

Участвующие функции read_and_adjust_string и read_and_get_ul имеют следующие реализации :
static void read_and_adjust_string( FILE* opened_fp, char* line )
{
    fgets( line, MAX_LINE_SIZE, opened_fp );
    line[strcspn(line, "\n")] = '\0';
}

static unsigned long int read_and_get_ul( FILE* opened_fp )
{
    char tmp_buf[MAX_LINE_SIZE] = {0};
    fgets( tmp_buf, MAX_LINE_SIZE, opened_fp );
    return strtoul( tmp_buf, NULL, 10 );
}

loadToFile
Зачем вам в аргументах 'указатель на указатель'? Этого не нужно : нам всего лишь надо прочитать значения и вывести их в файл.
void load_humans_to ( const char* filename, Human* humans_buffer, size_t humans_count )
{
    FILE* fp;
    size_t humans_counter = 0;
    if ( NULL == humans_buffer  || 0 == humans_count ) return;

    fp = fopen( filename, "w" );
    if ( NULL == fp ) return;

    while ( humans_counter < humans_count )
    {
        fprintf( fp, "%s\n", humans_buffer[humans_counter].id );
        fprintf( fp, "%s\n", humans_buffer[humans_counter].surname );
        fprintf( fp, "%s\n", humans_buffer[humans_counter].name );
        fprintf( fp, "%s\n", humans_buffer[humans_counter].patronymic );
        fprintf( fp, "%s\n", humans_buffer[humans_counter].sex );
        fprintf( fp, "%u\n", humans_buffer[humans_counter].dateOfBirth.day );
        fprintf( fp, "%u\n", humans_buffer[humans_counter].dateOfBirth.month );
        fprintf( fp, "%u\n", humans_buffer[humans_counter].dateOfBirth.year );
        fprintf( fp, "%u\n", humans_buffer[humans_counter].height );
        fprintf( fp, "%u\n", humans_buffer[humans_counter].weight );
        fprintf( fp, "%s\n", humans_buffer[humans_counter].city );
        fprintf( fp, "%s\n", humans_buffer[humans_counter].interests );
        fprintf( fp, "%s\n", humans_buffer[humans_counter].badHabits );
        fprintf( fp, "%s\n", humans_buffer[humans_counter].textMyself );
        fprintf( fp, "%u\n", humans_buffer[humans_counter].prefAgeMin );
        fprintf( fp, "%u\n", humans_buffer[humans_counter].prefAgeMax );
        fprintf( fp, "%s\n", humans_buffer[humans_counter].prefBadHab );

        humans_counter++;
    }

    fclose(fp);
}

printOnConsole (опционально)
Реализовал более понятный и приятный 'вашему соседу' код для отображения (по крайней мере, мне так удобнее):
void print_humans_info( Human* humans_buffer, size_t size )
{
    size_t counter = 0;
    while ( counter < size )
    {
        printf("Human #%lu : \n",counter);
        print_human_info( humans_buffer[counter] );
        puts("");
        counter++;
    }
}

Реализация print_human_info  следующая :
void print_human_info( Human hum )
{
    printf("\tID : %s\n", hum.id);
    printf("\tSurname : %s\n", hum.surname);
    printf("\tName : %s\n", hum.name);
    printf("\tPatronymic : %s\n", hum.patronymic);
    printf("\tSex : %s\n", hum.sex);
    printf("\tBirth day : %u\n", hum.dateOfBirth.day);
    printf("\tBirth month : %u\n", hum.dateOfBirth.month);
    printf("\tBirth year : %u\n", hum.dateOfBirth.year);
    printf("\tHeight : %u\n", hum.height);
    printf("\tWeight : %u\n", hum.weight);
    printf("\tCity : %s\n", hum.city);
    printf("\tInterests : %s\n", hum.interests);
    printf("\tBad habits : %s\n", hum.badHabits);
    printf("\tAbout : %s\n", hum.textMyself);
    printf("\tPreferable min-age : %u\n", hum.prefAgeMin);
    printf("\tPreferable max-age : %u\n", hum.prefAgeMax);
    printf("\tPreferable bad habits : %s\n", hum.prefBadHab);
}

Возможный 'main' для теста :
int main()
{
    char* src_filename = "database.txt";
    char* dst_filename = "database2.txt";
    size_t humans_count = get_humans_count(src_filename);
    Human* human_buffer = get_humans_from(src_filename);
    load_humans_to( dst_filename, human_buffer, humans_count );
    print_humans_info( human_buffer , humans_count );
    free(human_buffer);
    return 0;
}

На будущее :

Чтобы лучше представлять информацию, нужно создать ещё один
псевдоним :
#pragma pack (push, 1)
typedef struct People {
    size_t count;
    Human* humans;
} People;
#pragma pack (pop)

Таким образом вам не придется постоянно 'вытягивать' и то, и то, а
значит меньше аргументов на функции = лучшая удобочитаемость и
чистота (но это уже вам задача, если желаете).
Задавайте вопрос более конкретно. Вы даже не сказали, в каком
конкретно месте у вас возникают проблемы (у вас в коде не один
fclose). Старайтесь описывать задачу более коротко (пожалуйста).

Использованные заголовочные файлы:
stdio.h
stdint.h
stdlib.h
ctype.h
string.h


Q:

Using Jest to test a React component's method

I have a container component responsible for providing save functionality for a child form component method. I'm trying to use Jest & Enzyme (I think I need enzyme?) to test whether the child component fires the function passed from the parent component. The two methods look like so:

class Parent extends Component {
  handleSave = (someData) => (
    /* do some ajax with someData */
  )
  render() {
    return(
      <ChildComponent {...this.props} handleSave={this.handleSave} />
    )
  }
}

class ChildComponent extends Component {
  render() {
    <form onSubmit={this.props.handleSave}>
      <button type="submit">Submit</button>
    </form>
  }
}

And the test:

import React from 'react'
import ParentContainer from '../src/ParentContainer'

describe('<ParentContainer />', () => {

  it('Should fire handle save when PatientScheduler form saves', () => {
    const component = mount( <ParentContainer />)
    component.handleSave = jest.fn()
    component.find('[type="submit"]').simulate('click')
    expect(component.handleSave).toHaveBeenCalled()
  })

})

The failure message I'm getting is Expected mock function to have been called.
I feel like I'm 90% of the way there. What's wrong here? Thank you.

A:

The problem is that simulate not really fire a click event but runs wrapper.prop('click')(). Form the docs:

Common Gotchas
Currently, event simulation for the shallow renderer does not
  propagate as one would normally expect in a real environment. As a
  result, one must call .simulate() on the actual node that has the
  event handler set.
Even though the name would imply this simulates an
  actual event, .simulate() will in fact target the component's prop
  based on the event you give it. For example, .simulate('click') will
  actually get the onClick prop and call it.

So you can either run component.find('form').simulate('submit') or component.find('form').prop('onSubmit')()


Q:

How do i make PHP echo only inside div?

I am trying to create a page that displays RSS feed posts inside cards, everything is fine except only 1 card is being placed inside the div that has the flex flex-wrap class, causing the cards being placed vertically.
Screenshot of how the cards are placed
Screenshot of how the code is being created
My HTML and PHP code
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Overpass+Mono:wght@700&display=swap" rel="stylesheet">

<?php include 'rss.php';?>

My "rss.php" PHP code
<?php
$html = "";
$url = "https://phpexample1.000webhostapp.com/feed.xml";
$xml = simplexml_load_file($url);
for($i = 0; $i < 5; $i++){
    $image = $xml->channel->item[$i]->children('media', True)->content->attributes();
    $title = $xml->channel->item[$i]->title;
    $link = $xml->channel->item[$i]->link;
    $description = $xml->channel->item[$i]->description;
    $pubDate = $xml->channel->item[$i]->pubDate;

    $html .= "

  ";
    $html .= "

$title
";
    $html .= "
$description
";
    $html .= "
$pubDate

";
}
echo $html;
?>

Thanks

A:

You got too many closing /div in your code, i just indented my way but you can reorder as you like. Maybe it resolve the problem.
$url = "https://phpexample1.000webhostapp.com/feed.xml";
$xml = simplexml_load_file($url);
for($i = 0; $i < 5; $i++){
    $image = $xml->channel->item[$i]->children('media', True)->content->attributes();
    $title = $xml->channel->item[$i]->title;
    $link = $xml->channel->item[$i]->link;
    $description = $xml->channel->item[$i]->description;
    $pubDate = $xml->channel->item[$i]->pubDate;

    echo "

$title

$description

$pubDate

";
}


Q:

Is there a way to have one test function appearing as multiple unit tests in JUnit?

I have a kx q project with unit tests. This test suite produces a table with the test results and I need to integrate this with Atlassian Bamboo to see what tests failed and why. The easier way would be to dump this test result table into a csv that would be then converted to a JUnit XML output that Atlassian Bamboo plugins already understand.
To this end I think the best would be to have a Java project with a single test suite or single function that reads each line (each line in that CSV is a separate test case) of this CSV and asserts against whether the corresponding line passed or failed the test. The important thing is that each assertion is taken as a separate test within the test suite so the JUnit XML output correspond one to one to the csv file dump.
Can this be done using JUnit and how?

A:

Can this be done using JUnit

I wouldn't expect so, mostly because the behavior being described isn't strictly a unit test per se.  Perhaps I'm misunderstanding the question (correct me if that's the case), but it sounds like what you want to do is:

Repeat a single test for every line of an input file, and indicate the results individually.

That's a test of sorts, validating a file as input into the system.  But it's not testing the behavior of the code which puts it a bit outside the scope of unit tests.
Unless there's a tool which does something similar to this, I'd be inclined to simply build one.  All it really needs to do is receive the file as input, invoke a "test" over each line (which could be a unit test method, but doesn't necessarily need to be), and output results to a file of its own.  As an implementation detail that output happens to be XML in the same format that JUnit outputs its results, so that the same tools can read the results.
As unit tests alone I imagine it would necessitate treating each line of the input as a separate statically defined test (where each line of input is the "arrange" step).  Which certainly wouldn't be ideal.  I imagine writing a one-off tool to be invoked on its own would be a shorter path to the goal than trying to force JUnit into a pattern it wasn't intended for.
Unless as a concern of automated build/deploy steps it's necessary for this validation to be unit tests, a one-off tool seems more straightforward.


Q:

Why doesn't event bubbling work in detached DOM elements?

I have a parent <div> with one child <div> in memory - not attached to the current document. I want to trigger a CustomEvent on the child but listen to that event from the parent. Here is my code:
var parent = document.createElement('div');
var child = document.createElement('div');
parent.appendChild(child);
parent.addEventListener('boom', function(event) {
    console.log('parent listener', event); // <~ This never runs!
});
var event = new CustomEvent('boom', { bubbles: true });
child.dispatchEvent(event);

This code doesn't work as expected. The event listener on the parent never fires. This seems to be a contradiction of the JavaScript event system whereby events bubble up from the target. However, if I modify the final two lines of this snippet to the following, the callback fires as I would expect it to:
document.body.appendChild(parent);
child.dispatchEvent(event);

In other words, if I append my fragment as a subtree of the document before dispatching the event, then the parent event listener fires exactly as expected. Why? Is there a way to allow bubbling when using detached DOM elements?

A:

Why [doesn't bubbling work on detached elements]?

To answer your first question, I looked at the W3C "UI Events (formerly DOM Level 3 Events)" spec, and didn't see anything that addressed this issue specifically. However, the event phase portion mentions a few things that makes this behavior seem reasonable.

As the next step, the event object must complete one or more event phases. This specification defines three event phases: capture phase, target phase and bubble phase. Event objects complete these phases in the specified order using the partial propagation paths as defined below. A phase must be skipped if it is not supported, or if the event object's propagation has been stopped. For example, if the Event.bubbles attribute is set to false, the bubble phase will be skipped, and if Event.stopPropagation() has been called prior to the dispatch, all phases must be skipped.

Emphasis mine.
The spec then goes on to list the phases:

The capture phase: The event object must propagate through the target's ancestors from the Window to the target's parent. This phase is also known as the capturing phase. Event listeners registered for this phase must handle the event before it reaches its target.
The target phase: The event object must arrive at the event object's event target. This phase is also known as the at-target phase. Event listeners registered for this phase must handle the event once it has reached its target. If the event type indicates that the event must not bubble, the event object must halt after completion of this phase.
The bubble phase: The event object propagates through the target's ancestors in reverse order, starting with the target's parent and ending with the Window. This phase is also known as the bubbling phase. Event listeners registered for this phase must handle the event after it has reached its target.

Again, emphasis mine. The spec never calls out what happens with detached elements explicitly. Given that the target and bubble phases require the path to go from the element to the window, and that no path is possible on detached elements, it follows that the target and bubble event phases must be skipped because those paths are not supported.

Is there a way to allow bubbling when using detached DOM elements?

As far as I can tell, there's nothing built-in that would allow bubbling. You might be able to fake bubbling with some custom code, but that would require checking whether the element is detached every time you trigger an event.
Another thought would be to add the elements to the DOM, trigger the event, and detach the elements. As I haven't tested this, I have no idea whether it would work.


Q:

DNN 8.0 (DotNetNuke) With async controller, await behavior is not as expected

I am experimenting with an asynchronous call to an Azure Rest Api from a DNN module (this is for a client that uses the DNN platform and an older version of it namely 8.0). I need this call to retrieve the data before returning the View.
I made the controller async in order to be "await" getting the data from the azure rest api.
The behavior is unexpected. The code stops at this breakpoint(as in browser window with the blank view pops up but code after this point does not get executed) and the view is blank and never continues to the code populating the viewmodel for the page:
var result = await httpClient.GetStringAsync(url);

Sometimes result (the db user) is returned properly from the db, but the view is still blank even though the other breakpoints after await have been hit in the controller... The view seems to be returned before the await call is completed? The View window gets focus before await is completed but as a blank page.
Any suggestions about what is going on please?
In the DNN Controller class:
public async Task<ActionResult> Index() : DnnController
{
   ViewModel pageVM = new ViewModel();

   AuthenticationApi authService = new AuthenticationApi();
   var outcome = await authService.GetDbUser();  // AWAIT

   // populate the pageVM
   .................

   return View(pageVM);

}

In the Services folder, in the AuthenticationApi class:
public class AuthenticationApi
{
        public async Task<DbUser> GetDbUser()
        {
            string url = "https://mywebservicename.azurewebsites.net/api/applicants/46";

            var httpClient = new HttpClient();

            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            try
            {
                var result = await httpClient.GetStringAsync(url);

                return JsonConvert.DeserializeObject<DbUser>(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

                return null;
            }

        }
}

A:

The main response pipeline within DNN Platform is web-forms based and does not currently (even with version 9.6.2) support the usage of async/await in the main pipeline.
There is roadmap plans for this to be supported in version 10.x, however, additional changes are necessary to ensure that language features are not broken.
Some users have had success by adding this
aspnet:UseTaskFriendlySynchronizationContext

Application setting with a value of true, however, it is known to break certain features of DNN Platform such as Localization.


Q:

Cron help! Bi monthly jobs isn't working

I have a cronjob to back up some things, and it doesn't seem to be working.  You can see here it is set for 0:00 on the 1st of every other month, it should have ran this morning.
0 0 1 1/2 * ./gitbackup.sh

Here is the log - it isn't running!?
Aug 31 23:17:01 git-us CRON[22871]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Aug 31 23:20:01 git-us CRON[23349]: (smmsp) CMD (test -x /etc/init.d/sendmail && /usr/share/sendmail/sendmail cron-msp)
Aug 31 23:40:02 git-us CRON[26562]: (smmsp) CMD (test -x /etc/init.d/sendmail && /usr/share/sendmail/sendmail cron-msp)
Sep  1 00:00:01 git-us CRON[29878]: (smmsp) CMD (test -x /etc/init.d/sendmail && /usr/share/sendmail/sendmail cron-msp)
Sep  1 00:00:01 git-us CRON[29879]: (bind) CMD ( /usr/sbin/ldap2bind)

Any ideas?

A:

Turns out it was because I was running from the wrong path....doh!!


Q:

php multidimensional array json encode valid output

icant figure it out how to encode a valid json from my array
tried every posible way to encode json i had no luck
thankyou for your time
<?php
// this array is very large i used small piece as example
$listarray = array(
array(87,108,173,0,0),
array(87,108,173,0,1),
array(87,108,173,0,2),
array(87,108,173,0,3),
array(87,108,173,0,4),
array(87,108,173,0,5),
array(79,99,163,0,6),
array(79,99,163,0,7),
array(79,99,163,0,8),
array(79,99,163,0,9),
array(92,97,158,0,10),
array(92,97,158,0,11),
array(76,91,153,0,12),
array(79,99,163,0,13),
array(76,91,153,0,14),
array(92,97,158,0,15),
array(76,91,153,0,16),
array(76,91,153,0,17),
array(133,157,215,1,47),
array(133,157,215,1,48),
array(133,157,215,1,49),
array(133,157,215,1,50),
array(133,157,215,1,51),
array(133,157,215,1,52),
array(133,157,215,1,53),
array(143,168,222,1,54),
array(156,180,227,1,55),
array(156,180,227,1,56),
array(142,175,243,1,57),
array(156,180,227,1,58),
array(156,180,227,1,59),
array(156,180,227,1,60),
array(133,157,215,1,61));

for ($key = 0, $size = count($listarray); $key < $size; $key++) {
$array = array_values($listarray[$key]);
$line = $array[3]+1; //+1 start counting from 1
$loc = $array[4]+1; //+1 start counting from 1
$Name = $array[0].'_'.$array[1].'_'.$array[2];

$data = new StdClass();
$data->$line->$Name = array("$loc",);
$json = json_encode($data,JSON_PRETTY_PRINT);
echo $json."<br>";
//// echo give somthing like this and it is unusable for me
//{ "1": { "87_108_173": [ "1" ] } }
//{ "1": { "87_108_173": [ "2" ] } }
//{ "1": { "87_108_173": [ "3" ] } }
//{ "1": { "87_108_173": [ "4" ] } }
//{ "1": { "87_108_173": [ "5" ] } }
//{ "1": { "87_108_173": [ "6" ] } }
////
$fh = fopen("jsonout.json", 'w')or die("Error opening output file");
fwrite($fh, json_encode($data,JSON_PRETTY_PRINT));
fclose($fh);
    }// end of for loop
?>

// and contents of jsonout.json is not valid
//the out put needed as shoud be exactly like this
// json blew is manualy made with app and validated
{
        "1": {
            "87_108_173": [
                "1",
                "2",
                "3",
                "4",
                "5",
                "6"
            ],
            "92_97_158": [
                "11",
                "12",
                "16"
            ],
            "79_99_163": [
                "7",
                "8",
                "9",
                "14"
            ],
            "76_91_153": [
                "13",
                "15",
                "17",
                "18"
            ]
        },
        "2": {
            "156_180_227": [
                "56",
                "57",
                "59",
                "60",
                "61"
            ],
            "142_175_243": [
                "58"
            ],
            "133_157_215": [
                "48",
                "49",
                "50",
                "51",
                "52",
                "53",
                "54",
                "62"
            ],
            "143_168_222": [
                "55"
            ]
        }
    }

A:

$listarray = array(
  array(87,108,173,0,0),
  array(87,108,173,0,1),
  array(87,108,173,0,2),
  array(87,108,173,0,3),
  array(133,157,215,1,47),
array(133,157,215,1,48),
array(133,157,215,1,49),
array(133,157,215,1,50),
array(133,157,215,1,51),
array(133,157,215,1,52),
);

$resultArray = array();
foreach ($listarray as $row) {
  $ind = $row[3] + 1;
  $name = $row[0] . '_' . $row[1] . '_' . $row[2];
  $val = $row[4] + 1;

  if (!isset($resultArray[$ind])) {
    $resultArray[$ind] = array();
  }

  if (!isset($resultArray[$ind][$name])) {
    $resultArray[$ind][$name] = array();
  }

  $resultArray[$ind][$name][] = $val;
}

echo json_encode($resultArray, JSON_PRETTY_PRINT);

You are welcome ;)


Q:

Prove $f(n) = 3n^2+10n$ is in $\Theta(n^2)$

I've proven it's in $O(n^2)$ by having $n = 1$ and $c > 13$ (namely $c = 14$). How do I prove it for big theta?

A:

The inequality in the other direction is easier, since $n^2\lt 3n^2 +10n$ if $n\ge 1$.