问:
Trying to Understand an Implementation of Hash#merge with Procs
trying to understand this problem here. I am creating my own verison of the hash#merge called hash#my_merge that can take in a proc. I'm trying to understand what does do:

```<code>self.each do |k,v|
  newhash[k]=hash[k] ? prc.call(k,v,hash[k]): v
end
</code>```

Its look like a ternary operation but newhash[k]=hash[k] isn't a true/false statement? The prompt and the rest of the question is as follows:

```<code>class Hash
# Hash#merge takes a proc that accepts three arguments: a key and the two
# corresponding values in the hashes being merged. Hash#merge then sets that
# key to the return value of the proc in a new hash. If no proc is given,
# Hash#merge simply merges the two hashes.
#
# Write a method with the functionality of Hash#merge. Your Hash#my_merge
method
# should optionally take a proc as an argument and return a new hash. If a
proc
# is not given, your method should provide default merging behavior. Do not
use
# Hash#merge in your method.

  def my_merge(hash, &prc)
    prc ||=Proc.new{|k,oldval,newval|}
    newhash=Hash.new

    self.each do |k,v|
      newhash[k]=hash[k] ? prc.call(k,v,hash[k]): v
    end

    hash.each do |k,v|
      newhash[k]=v if newhash[k].nil?
    end
    newhash
  end
end
</code>```

Any help would be greatly appreciated. Thanks!

答:
While your core problem is one of operator precedence when using a ternary in that fashion, the real issue is an over-complication of the actual solution.

If you're just getting started with Ruby do your best to avoid things like ternary statements to keep your code as simple and obvious as possible. For example, what does the following do:

```<code>a = nil

a = true ? :yes : :no
</code>```

If you think the answer is "a is assigned :yes" then you're reading it correctly. If you think "a is assigned true" then you're forgetting that the ternary ? has a higher precedence than = for assignment so it happens first.

The same wouldn't be true if you looked at it this way:

```<code>if (a = true)
  :yes
else
  :no
end
</code>```

Or the alternative interpretation laid clear:

```<code>a =
  if (true)
    :yes
  else
    :no
  end
</code>```

Where the outcome of those two is immediately apparent with even a basic understanding of programming. This can also be handy if it's really late at night and you're trying to fix a bug and you can't figure out your own code because you've made it too convoluted.

That being said, a reworked solution looks like this:

```<code>class Hash
  def my_merge(hash)
    # Figure out all the keys that might show up in this merge in advance.
    keys = (self.keys + hash.keys).uniq
    newhash = { }

    # Try all possible keys and evaluate what the result should be
    keys.each do |k|
      newhash[k] =
        if (block_given?)
          yield(k, self[k], hash[k])
        elsif (self.has_key?(k))
          self[k]
        else
          hash[k]
        end
    end

    newhash
  end
end
</code>```

You can leverage the way if actually returns values in Ruby to make short work of this problem and keep the inner logic pretty clear.

One thing to note is when you use Hash.new you probably mean { } instead. The formal declaration is reserved for things like Hash.new(0) or Hash.new { |h,k| h[k] = [ ] } where the first sets a static default and the second is a computed default. If you're not setting a default, don't use the explicit initializer. It just adds noise.

You can also make better use of the built-in features of Ruby that allow significantly minimizing the amount of temporary variables you need, plus the amount of work you actually have to do to effect a transform like this. For example, a little tidying up and you get this:

```<code>class Hash
  def my_merge(hash)
    (self.keys + hash.keys).uniq.map do |k|
      [
        k,
        if (block_given?)
          yield(k, self[k], hash[k])
        elsif (self.has_key?(k))
          self[k]
        else
          hash[k]
        end
      ]
    end.to_h
  end
end
</code>```

That's pretty lean and the biggest chunk of code there is your merge implmentation, as it should be, not all the set-up and clean-up code.

Body:
trying to understand this problem here. I am creating my own verison of the hash#merge called hash#my_merge that can take in a proc. I'm trying to understand what does do:

self.each do |k,v|
  newhash[k]=hash[k] ? prc.call(k,v,hash[k]): v
end

Its look like a ternary operation but newhash[k]=hash[k] isn't a true/false statement? The prompt and the rest of the question is as follows:

class Hash
# Hash#merge takes a proc that accepts three arguments: a key and the two
# corresponding values in the hashes being merged. Hash#merge then sets that
# key to the return value of the proc in a new hash. If no proc is given,
# Hash#merge simply merges the two hashes.
#
# Write a method with the functionality of Hash#merge. Your Hash#my_merge
method
# should optionally take a proc as an argument and return a new hash. If a
proc
# is not given, your method should provide default merging behavior. Do not
use
# Hash#merge in your method.

  def my_merge(hash, &prc)
    prc ||=Proc.new{|k,oldval,newval|}
    newhash=Hash.new

    self.each do |k,v|
      newhash[k]=hash[k] ? prc.call(k,v,hash[k]): v
    end

    hash.each do |k,v|
      newhash[k]=v if newhash[k].nil?
    end
    newhash
  end
end

Any help would be greatly appreciated. Thanks!

Body:
While your core problem is one of operator precedence when using a ternary in that fashion, the real issue is an over-complication of the actual solution.

If you're just getting started with Ruby do your best to avoid things like ternary statements to keep your code as simple and obvious as possible. For example, what does the following do:

a = nil

a = true ? :yes : :no

If you think the answer is "a is assigned :yes" then you're reading it correctly. If you think "a is assigned true" then you're forgetting that the ternary ? has a higher precedence than = for assignment so it happens first.

The same wouldn't be true if you looked at it this way:

if (a = true)
  :yes
else
  :no
end

Or the alternative interpretation laid clear:

a =
  if (true)
    :yes
  else
    :no
  end

Where the outcome of those two is immediately apparent with even a basic understanding of programming. This can also be handy if it's really late at night and you're trying to fix a bug and you can't figure out your own code because you've made it too convoluted.

That being said, a reworked solution looks like this:

class Hash
  def my_merge(hash)
    # Figure out all the keys that might show up in this merge in advance.
    keys = (self.keys + hash.keys).uniq
    newhash = { }

    # Try all possible keys and evaluate what the result should be
    keys.each do |k|
      newhash[k] =
        if (block_given?)
          yield(k, self[k], hash[k])
        elsif (self.has_key?(k))
          self[k]
        else
          hash[k]
        end
    end

    newhash
  end
end

You can leverage the way if actually returns values in Ruby to make short work of this problem and keep the inner logic pretty clear.

One thing to note is when you use Hash.new you probably mean { } instead. The formal declaration is reserved for things like Hash.new(0) or Hash.new { |h,k| h[k] = [ ] } where the first sets a static default and the second is a computed default. If you're not setting a default, don't use the explicit initializer. It just adds noise.

You can also make better use of the built-in features of Ruby that allow significantly minimizing the amount of temporary variables you need, plus the amount of work you actually have to do to effect a transform like this. For example, a little tidying up and you get this:

class Hash
  def my_merge(hash)
    (self.keys + hash.keys).uniq.map do |k|
      [
        k,
        if (block_given?)
          yield(k, self[k], hash[k])
        elsif (self.has_key?(k))
          self[k]
        else
          hash[k]
        end
      ]
    end.to_h
  end
end

That's pretty lean and the biggest chunk of code there is your merge implmentation, as it should be, not all the set-up and clean-up code.


来源: stackexchange

问:
python linear regression predict by date
I want to predict a value at a date in the future with simple linear regression, but I can't due to the date format.

This is the dataframe I have:

```<code>data_df =
date          value
2016-01-15    1555
2016-01-16    1678
2016-01-17    1789
...

y = np.asarray(data_df['value'])
X = data_df[['date']]
X_train, X_test, y_train, y_test = train_test_split
(X,y,train_size=.7,random_state=42)

model = LinearRegression() #create linear regression object
model.fit(X_train, y_train) #train model on train data
model.score(X_train, y_train) #check score

print (‘Coefficient: \n’, model.coef_)
print (‘Intercept: \n’, model.intercept_)
coefs = zip(model.coef_, X.columns)
model.__dict__
print "sl = %.1f + " % model.intercept_ + \
     " + ".join("%.1f %s" % coef for coef in coefs) #linear model
</code>```

I tried to convert the date unsuccessfully

```<code>data_df['conv_date'] = data_df.date.apply(lambda x: x.toordinal())

data_df['conv_date'] = pd.to_datetime(data_df.date, format="%Y-%M-%D")
</code>```

答:
When using

```<code>dt.datetime.toordinal
</code>```

be careful that it only converts dates values and does not take into account minutes, seconds etc..  For a complete answer on generating ordinals from full datetime objects you can use something like:

```<code>df['Datetime column'].apply(lambda x: time.mktime(x.timetuple()))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to predict a value at a date in the future with simple linear regression, but I can't due to the date format.

This is the dataframe I have:

data_df =
date          value
2016-01-15    1555
2016-01-16    1678
2016-01-17    1789
...

y = np.asarray(data_df['value'])
X = data_df[['date']]
X_train, X_test, y_train, y_test = train_test_split
(X,y,train_size=.7,random_state=42)

model = LinearRegression() #create linear regression object
model.fit(X_train, y_train) #train model on train data
model.score(X_train, y_train) #check score

print (‘Coefficient: \n’, model.coef_)
print (‘Intercept: \n’, model.intercept_)
coefs = zip(model.coef_, X.columns)
model.__dict__
print "sl = %.1f + " % model.intercept_ + \
     " + ".join("%.1f %s" % coef for coef in coefs) #linear model

I tried to convert the date unsuccessfully

data_df['conv_date'] = data_df.date.apply(lambda x: x.toordinal())

data_df['conv_date'] = pd.to_datetime(data_df.date, format="%Y-%M-%D")

Body:
When using

dt.datetime.toordinal

be careful that it only converts dates values and does not take into account minutes, seconds etc..  For a complete answer on generating ordinals from full datetime objects you can use something like:

df['Datetime column'].apply(lambda x: time.mktime(x.timetuple()))

ContentLicense: CC BY-SA 4.0


问:
ApplicationData.Current.LocalFolder GetFile synchronous
I need to create a database / check for its existance at my program start.

```<code>public async Task CopyDatabaseIfNotExists(string dbPath)
{
    var nExpectedFolder = IsolatedStorageFile.GetUserStoreForApplication();

            try
            {
                await ApplicationData.Current.LocalFolder.GetFileAsync(dbPath); //nExpectedFolder.GetFileAsync(dbPath);/// ApplicationData.Current.LocalFolder.GetFileAsync("preinstalledDB.db");
                // No exception means it exists
                return;
            }
            catch (System.IO.FileNotFoundException)
            {
                // The file obviously doesn't exist
            }

        (... some other stuff)
</code>```

My application can't and shouldn't be run before this test has been completed.

Therefore I wanted to change my calls to be synchronous.

However, I only see

```<code>ApplicationData.Current.LocalFolder.GetFileAsync
</code>```

.GetFile doesn't exist.

What would be the way to make the call synchronous?

答:
You can use the .NET APIs from System.IO to read files synchronously. You can get the StorageFolder.Path property from the LocalFolder and pass the path name to .NET.

The FileStream constructor takes a path and a mode and from there you can read and write synchronously or asynchronously.

Body:
I need to create a database / check for its existance at my program start.

public async Task CopyDatabaseIfNotExists(string dbPath)
{
    var nExpectedFolder = IsolatedStorageFile.GetUserStoreForApplication();

            try
            {
                await ApplicationData.Current.LocalFolder.GetFileAsync(dbPath); //nExpectedFolder.GetFileAsync(dbPath);/// ApplicationData.Current.LocalFolder.GetFileAsync("preinstalledDB.db");
                // No exception means it exists
                return;
            }
            catch (System.IO.FileNotFoundException)
            {
                // The file obviously doesn't exist
            }

        (... some other stuff)

My application can't and shouldn't be run before this test has been completed.

Therefore I wanted to change my calls to be synchronous.

However, I only see

ApplicationData.Current.LocalFolder.GetFileAsync

.GetFile doesn't exist.

What would be the way to make the call synchronous?


问:
Another way to improve code
Thank you all for the help with my previous question. It really helped!. My code is now this...

```<code>def intro():
    """This is the function that starts the program"""

    msg = input("Enter the message you wish to encrypt: ") # This ask the user to input a message to encrypt
    return msg

def shift(msg):
    """This function is the meat of the program. Shifting the message"""

    alpha = ['a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] # Letters that the user can input
    rotate = int(input("The level of the encryption?: ")) #Tells how to shift letters, if message is "a" and inputs level 2, it becomes "c"
    text = "" #puts the tex between quotes
    for ch in msg:
        if ch == " " or ch == ".":
            pass #If user inputs a blank or period it wont casue an error
        else:
            index = alpha.index(ch) # index becomes message and the ASCII
            newindex = (index + rotate) % len(alpha) #ASCII will shift by the rotate value and becomes newindex
            new= alpha[newindex]#new message becomes new
            text += new #the encrypted message is now text
    return text

def start():
    """Fuction that puts everything together and starts the program"""
    while True:
        msg = intro()
        if msg == '999':
            print("Farewell. We will see each other again soon, I guarantee it")
            break # If the user inputs "999" the program will end
       deep web shift(msg)
        print("Your encryptions is: " + text)#Output of the program

print("Hello there. Welcome to my deep web encryption services, Please press '999' if you wish to leave")#Tells the user what to do
print("Encryption level can be any numeric value")
start()
</code>```

Here is my other question if possible to answer. I know ascii for lowercase and uppercase are different. Is there a way I can shift uppercase letters. like, make " Hello" shift by 2 to make"Jgnnq".Also if a user inputs something invalid it will keep it. An example being "hell@" shift by 2 will become "jgnn@"

答:
str.maketrans and str.translate are designed around problems like these: mapping one set of character onto another.

```<code>from string import ascii_lowercase, ascii_uppercase
from itertools import chain

alphabets = [ascii_lowercase, ascii_uppercase]

def shift(msg, rotate, alphabets):
    paired_letters = (zip(alphabet, alphabet[rotate:]+alphabet[:rotate]) for alphabet in alphabets)
    trans = str.maketrans(dict(chain.from_iterable(paired_letters)))
    return msg.translate(trans)

print(shift('helL@', 2, alphabets))
</code>```

will print

```<code>jgnN@
</code>```

Title: Another way to improve code

Body:
Thank you all for the help with my previous question. It really helped!. My code is now this...

def intro():
    """This is the function that starts the program"""

    msg = input("Enter the message you wish to encrypt: ") # This ask the user to input a message to encrypt
    return msg

def shift(msg):
    """This function is the meat of the program. Shifting the message"""

    alpha = ['a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] # Letters that the user can input
    rotate = int(input("The level of the encryption?: ")) #Tells how to shift letters, if message is "a" and inputs level 2, it becomes "c"
    text = "" #puts the tex between quotes
    for ch in msg:
        if ch == " " or ch == ".":
            pass #If user inputs a blank or period it wont casue an error
        else:
            index = alpha.index(ch) # index becomes message and the ASCII
            newindex = (index + rotate) % len(alpha) #ASCII will shift by the rotate value and becomes newindex
            new= alpha[newindex]#new message becomes new
            text += new #the encrypted message is now text
    return text

def start():
    """Fuction that puts everything together and starts the program"""
    while True:
        msg = intro()
        if msg == '999':
            print("Farewell. We will see each other again soon, I guarantee it")
            break # If the user inputs "999" the program will end
       deep web shift(msg)
        print("Your encryptions is: " + text)#Output of the program

print("Hello there. Welcome to my deep web encryption services, Please press '999' if you wish to leave")#Tells the user what to do
print("Encryption level can be any numeric value")
start()

Here is my other question if possible to answer. I know ascii for lowercase and uppercase are different. Is there a way I can shift uppercase letters. like, make " Hello" shift by 2 to make"Jgnnq".Also if a user inputs something invalid it will keep it. An example being "hell@" shift by 2 will become "jgnn@"

Body:
str.maketrans and str.translate are designed around problems like these: mapping one set of character onto another.

from string import ascii_lowercase, ascii_uppercase
from itertools import chain

alphabets = [ascii_lowercase, ascii_uppercase]

def shift(msg, rotate, alphabets):
    paired_letters = (zip(alphabet, alphabet[rotate:]+alphabet[:rotate]) for alphabet in alphabets)
    trans = str.maketrans(dict(chain.from_iterable(paired_letters)))
    return msg.translate(trans)

print(shift('helL@', 2, alphabets))

will print

jgnN@


问:
Installing APK from email attachment

Whenever i send a .apk file via email as an attachment and then open the .apk-file in my phone from my email-account, i get a parsing error.

However if i put the .apk on my website and provide a URL to it, it works like a charm.

A bug? Just me? Am i doing it wrong?

Thanks

答:
That on new Android versions works very well, because, if the attachment is and apk then appear an install button. (on GMail native app)

But for older Android versions you will need and app like Email install
this one : http://www.appbrain.com/app/email-installer/com.best.app.attachment

ContentLicense: CC BY-SA 2.5

Title: Installing APK from email attachment


问:
Assign Repeated Statement to a Variable
Below is the working stored procedure.  How can I assign the repeated code under the case statement to a variable and use it so I can reduce the number of coding lines?  The purpose of the procedure is to update the table with start_date and end_date for each CASE statement.  Thank you for your help and advise.</p>

```<code>BEGIN
    UPDATE period x
    SET start_date = CASE
        when return_period = 'L3M' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -2 Month))
        when return_period = 'YTD' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL 1-MONTH((select max(monthend_date) from returns y
            WHERE x.account_id=y.account_id)) Month))
        when return_period = '1YR_CUM' or return_period = '1YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -11 Month))
        when return_period = '2YR_CUM' or return_period = '2YR_ANN' then
            last_day(date_add((select max(monthend_date) from eturns y WHERE x.account_id=y.account_id),INTERVAL -23 Month))
        when return_period = '3YR_CUM' or return_period = '3YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -35 Month))
        when return_period = '4YR_CUM' or return_period = '4YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -47 Month))
        when return_period = '5YR_CUM' or return_period = '5YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -59 Month))
        when return_period = '6YR_CUM' or return_period = '6YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -71 Month))
        when return_period = '7YR_CUM' or return_period = '7YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -83 Month))
        when return_period = '8YR_CUM' or return_period = '8YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -95 Month))
        when return_period = '9YR_CUM' or return_period = '9YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -107 Month))
        when return_period = '10YR_CUM' or return_period = '10YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -119 Month))
        when return_period = '11YR_CUM' or return_period = '11YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -131 Month))
        when return_period = '12YR_CUM' or return_period = '12YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -143 Month))
        when return_period = '13YR_CUM' or return_period = '13YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -155 Month))
        when return_period = '14YR_CUM' or return_period = '14YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -167 Month))
        when return_period = '15YR_CUM' or return_period = '15YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -179 Month))
        when return_period = 'SI_CUM' or return_period = 'SI_ANN' then
            (select min(monthend_date) from returns y WHERE x.account_id=y.account_id)
        END
        ,
        end_date=(select max(monthend_date) from returns y WHERE x.account_id=y.account_id)
        ;
END
</code>```

答:
This is your repeating expression:

```<code>last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL {months} MONTH))
</code>```

The only difference is the value in {months}.
First I would write the expression a bit shorter:

```<code>last_day((select max(monthend_date) from returns y WHERE x.account_id=y.account_id) + INTERVAL {months} MONTH)
</code>```

Then I would use CASE only for the {month} part:

```<code>UPDATE period x
SET start_date = last_day((select max(monthend_date) from returns y WHERE x.account_id=y.account_id) + INTERVAL
        CASE
            when return_period = 'L3M' then -2
            when return_period = 'YTD' then -1
            when return_period = '1YR_CUM' or return_period = '1YR_ANN' then -11
            when return_period = '2YR_CUM' or return_period = '2YR_ANN' then -23
            when return_period = '3YR_CUM' or return_period = '3YR_ANN' then -35
            when return_period = '4YR_CUM' or return_period = '4YR_ANN' then -47
            # [...]
        END
    MONTH),
    end_date=(select max(monthend_date) from returns y WHERE x.account_id=y.account_id);
</code>```

You can also write it this way:

```<code>UPDATE period x
SET start_date = last_day((select max(monthend_date) from returns y WHERE x.account_id=y.account_id) + INTERVAL
        CASE return_period
            when 'L3M'     then -2
            when 'YTD'     then -1
            when '1YR_CUM' then -11
            when '1YR_ANN' then -11
            when '2YR_CUM' then -23
            when '2YR_ANN' then -23
            when '3YR_CUM' then -35
            when '3YR_ANN' then -35
            when '4YR_CUM' then -47
            when '4YR_ANN' then -47
            # [...]
        END
    MONTH),
    end_date=(select max(monthend_date) from returns y WHERE x.account_id=y.account_id);
</code>```

Title: Assign Repeated Statement to a Variable

Body:
Below is the working stored procedure.  How can I assign the repeated code under the case statement to a variable and use it so I can reduce the number of coding lines?  The purpose of the procedure is to update the table with start_date and end_date for each CASE statement.  Thank you for your help and advise.

BEGIN
    UPDATE period x
    SET start_date = CASE
        when return_period = 'L3M' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -2 Month))
        when return_period = 'YTD' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL 1-MONTH((select max(monthend_date) from returns y
            WHERE x.account_id=y.account_id)) Month))
        when return_period = '1YR_CUM' or return_period = '1YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -11 Month))
        when return_period = '2YR_CUM' or return_period = '2YR_ANN' then
            last_day(date_add((select max(monthend_date) from eturns y WHERE x.account_id=y.account_id),INTERVAL -23 Month))
        when return_period = '3YR_CUM' or return_period = '3YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -35 Month))
        when return_period = '4YR_CUM' or return_period = '4YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -47 Month))
        when return_period = '5YR_CUM' or return_period = '5YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -59 Month))
        when return_period = '6YR_CUM' or return_period = '6YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -71 Month))
        when return_period = '7YR_CUM' or return_period = '7YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -83 Month))
        when return_period = '8YR_CUM' or return_period = '8YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -95 Month))
        when return_period = '9YR_CUM' or return_period = '9YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -107 Month))
        when return_period = '10YR_CUM' or return_period = '10YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -119 Month))
        when return_period = '11YR_CUM' or return_period = '11YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -131 Month))
        when return_period = '12YR_CUM' or return_period = '12YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -143 Month))
        when return_period = '13YR_CUM' or return_period = '13YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -155 Month))
        when return_period = '14YR_CUM' or return_period = '14YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -167 Month))
        when return_period = '15YR_CUM' or return_period = '15YR_ANN' then
            last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL -179 Month))
        when return_period = 'SI_CUM' or return_period = 'SI_ANN' then
            (select min(monthend_date) from returns y WHERE x.account_id=y.account_id)
        END
        ,
        end_date=(select max(monthend_date) from returns y WHERE x.account_id=y.account_id)
        ;
END

Body:
This is your repeating expression:

last_day(date_add((select max(monthend_date) from returns y WHERE x.account_id=y.account_id),INTERVAL {months} MONTH))

The only difference is the value in {months}.
First I would write the expression a bit shorter:

last_day((select max(monthend_date) from returns y WHERE x.account_id=y.account_id) + INTERVAL {months} MONTH)

Then I would use CASE only for the {month} part:

UPDATE period x
SET start_date = last_day((select max(monthend_date) from returns y WHERE x.account_id=y.account_id) + INTERVAL
        CASE
            when return_period = 'L3M' then -2
            when return_period = 'YTD' then -1
            when return_period = '1YR_CUM' or return_period = '1YR_ANN' then -11
            when return_period = '2YR_CUM' or return_period = '2YR_ANN' then -23
            when return_period = '3YR_CUM' or return_period = '3YR_ANN' then -35
            when return_period = '4YR_CUM' or return_period = '4YR_ANN' then -47
            # [...]
        END
    MONTH),
    end_date=(select max(monthend_date) from returns y WHERE x.account_id=y.account_id);

You can also write it this way:

UPDATE period x
SET start_date = last_day((select max(monthend_date) from returns y WHERE x.account_id=y.account_id) + INTERVAL
        CASE return_period
            when 'L3M'     then -2
            when 'YTD'     then -1
            when '1YR_CUM' then -11
            when '1YR_ANN' then -11
            when '2YR_CUM' then -23
            when '2YR_ANN' then -23
            when '3YR_CUM' then -35
            when '3YR_ANN' then -35
            when '4YR_CUM' then -47
            when '4YR_ANN' then -47
            # [...]
        END
    MONTH),
    end_date=(select max(monthend_date) from returns y WHERE x.account_id=y.account_id);


问:
Debugging sidekiq worker memory leak with jemalloc
So, I've got a memory leak in my Sidekiq worker. I have a worker server with one queue for this worker task only, that gets to about 10G RSS in a week.

I tried to reproduce it locally with only 1 worker thread and voila - I get from 200M to 1G in one night, processing 1 task/min. Naturally, I want to know what's leaking, so I'm also logging RSS, heap_live_slots and heap_free_slots. When I plot results I can see steady RSS growth while live and free slots fluctuate randomly but in well defined and constant boundaries, while their sum remains constant.

At this point I come to the conclusion that the leak likely occurs not in Ruby code, but rather in some native extension. So I reinstall ruby with Jemalloc support via RVM:
rvm reinstall 2.4.2 --with-jemalloc

Then I set up MALLOC_CONF:

export
 MALLOC_CONF='prof_leak:true,lg_prof_sample:0,prof_final:true,stats_print:true'

And fire up Sidekiq. Freshly started Sidekiq with 1 worker thread is worth about 200M RSS, but when I press Ctrl+C and look at stats output of jemalloc I see something completely different:

```<code>Arenas: 32
Quantum size: 16
Page size: 4096
Maximum thread-cached size class: 32768
Allocated: 34056, active: 61440, metadata: 2949272, resident: 2981888, mapped: 6352896, retained: 2035712
</code>```

What? 6M mapped? This cannot be true. So I start irb and do the following:

```<code>2.4.2 :001 > arr = []
 => []
2.4.2 :002 > loop do
2.4.2 :003 >   arr << 'a'*10000000
2.4.2 :004?>   sleep 1
2.4.2 :005?> end
</code>```

After waiting until irb process climbs to about 1G RSS I stop the process... and see exactly same numbers. Maybe visualizing the call graph will help me understand what's going on?

```<code>jeprof --show_bytes --pdf `which ruby` jeprof.10536.0.f.heap > ruby.pdf

Using local file /home/mhi/.rvm/rubies/ruby-2.4.2/bin/ruby.
Using local file jeprof.10536.0.f.heap.
No nodes to print
</code>```

So something is clearly wrong, and that's what I need help figuring out.

Here's full output from jemalloc stat: https://pastebin.com/RiMLtqA6

UPD.

So I've updated all the native-extension related gems, here's output of
bundle exec ruby -e 'puts Gem.loaded_specs.values.select{ |i| !i.extensions.empty? }.map{ |i| "#{i.name} #{i.version}" }':

```<code>io-console 0.4.6
nokogiri 1.8.1
bcrypt 3.1.11
debug_inspector 0.0.3
binding_of_caller 0.7.2
json 2.1.0
capybara-webkit 1.14.0
damerau-levenshtein 1.3.0
unf_ext 0.0.7.4
eventmachine 1.2.5
ffi 1.9.18
kgio 2.11.0
msgpack 1.1.0
mysql2 0.4.9
rainbow 2.2.2
raindrops 0.18.0
rbtrace 0.4.8
stackprof 0.2.10
therubyracer 0.12.3
unicode 0.4.4.4
unicorn 5.3.0
</code>```

Same result: RSS, Memory slots

答:
Ruby 2.4.2 has a known issue with jemalloc.

the issue was closed about a month ago, but I don't know if the package you're using is patched... Actually,  I don't think the patch was released yet. It's likely all the jemalloc stat data is irrelevant.

Also, this seems like an X-Y question (you're asking about jemalloc, while you probably want a solution to the memory "leak").

Before assuming a memory leak in native code (though a distinct possibility), I would consider how the task's scope might affect the garbage collector and try to minimize both the scope and any long-life variables.

For example, if  your task is a Proc, it might be bound to the global scope, which means that some variables might live forever...

Try enclosing the task in a function and make sure that none of the variables are referenced once the task is done.

Body:
So, I've got a memory leak in my Sidekiq worker. I have a worker server with one queue for this worker task only, that gets to about 10G RSS in a week.

I tried to reproduce it locally with only 1 worker thread and voila - I get from 200M to 1G in one night, processing 1 task/min. Naturally, I want to know what's leaking, so I'm also logging RSS, heap_live_slots and heap_free_slots. When I plot results I can see steady RSS growth while live and free slots fluctuate randomly but in well defined and constant boundaries, while their sum remains constant.

At this point I come to the conclusion that the leak likely occurs not in Ruby code, but rather in some native extension. So I reinstall ruby with Jemalloc support via RVM:
rvm reinstall 2.4.2 --with-jemalloc

Then I set up MALLOC_CONF:

export
 MALLOC_CONF='prof_leak:true,lg_prof_sample:0,prof_final:true,stats_print:true'

And fire up Sidekiq. Freshly started Sidekiq with 1 worker thread is worth about 200M RSS, but when I press Ctrl+C and look at stats output of jemalloc I see something completely different:

Arenas: 32
Quantum size: 16
Page size: 4096
Maximum thread-cached size class: 32768
Allocated: 34056, active: 61440, metadata: 2949272, resident: 2981888, mapped: 6352896, retained: 2035712

What? 6M mapped? This cannot be true. So I start irb and do the following:

2.4.2 :001 > arr = []
 => []
2.4.2 :002 > loop do
2.4.2 :003 >   arr << 'a'*10000000
2.4.2 :004?>   sleep 1
2.4.2 :005?> end

After waiting until irb process climbs to about 1G RSS I stop the process... and see exactly same numbers. Maybe visualizing the call graph will help me understand what's going on?

jeprof --show_bytes --pdf `which ruby` jeprof.10536.0.f.heap > ruby.pdf

Using local file /home/mhi/.rvm/rubies/ruby-2.4.2/bin/ruby.
Using local file jeprof.10536.0.f.heap.
No nodes to print

So something is clearly wrong, and that's what I need help figuring out.

Here's full output from jemalloc stat: https://pastebin.com/RiMLtqA6

UPD.

So I've updated all the native-extension related gems, here's output of
bundle exec ruby -e 'puts Gem.loaded_specs.values.select{ |i| !i.extensions.empty? }.map{ |i| "#{i.name} #{i.version}" }':

io-console 0.4.6
nokogiri 1.8.1
bcrypt 3.1.11
debug_inspector 0.0.3
binding_of_caller 0.7.2
json 2.1.0
capybara-webkit 1.14.0
damerau-levenshtein 1.3.0
unf_ext 0.0.7.4
eventmachine 1.2.5
ffi 1.9.18
kgio 2.11.0
msgpack 1.1.0
mysql2 0.4.9
rainbow 2.2.2
raindrops 0.18.0
rbtrace 0.4.8
stackprof 0.2.10
therubyracer 0.12.3
unicode 0.4.4.4
unicorn 5.3.0

Same result: RSS, Memory slots


问:
How to publish a post on wordpress, the post is already published on Blogger.com
I have a blog

, I want to share/post some of the articles from this blog to my WordPress website. Is there anyway?

答:
You can achieve that by Javascript and Blogger JSON API.

The following example shows the last post title from your blogger blog

```<code><div id="content"></div>

<script>
    function get(json) {

        document.getElementById('content').innerHTML = "<h2>" + json.feed.entry[0].title.$t + "</h2>";
    }
</script>

<script src="your-blog-url/feeds/posts/default?alt=json-in-script&callback=get"></script>
</code>```

Body:
You can achieve that by Javascript and Blogger JSON API.

The following example shows the last post title from your blogger blog

<div id="content"></div>

<script>
    function get(json) {

        document.getElementById('content').innerHTML = "<h2>" + json.feed.entry[0].title.$t + "</h2>";
    }
</script>

<script src="your-blog-url/feeds/posts/default?alt=json-in-script&callback=get"></script>


问:
Figuring out labeling for classes when using sklearn MLP.predict_proba() function
I am creating a Neural Net with labeled classes that are a list of binary values and there are 1167 classes. I want to utilize the MLP.predict_proba() to output the top 5 classes based on prediction probabilities but the output is a np array with probabilities for each class labeled just by index values i.e.

enter image description here

I want to figure out what classes are linked to these probabilities and the predict function correctly outputs the binary list that represents the class that it was predicted to. Is there anyway for me to manually label the classes to these unique binary lists? I basically have labeled classes and my neural net is able to output the correct binary list for its predictions just when I use predict_proba() it gives me just probabilities with no clear indication of what classes these probabilities are for. Thanks!

答:
Use the classes_ of the mlp after fitting. As per the documentation:

classes_ : array or list of array of shape (n_classes,) Class labels
  for each output.

It will print out the classes learnt from the dataset (mostly in alphabetical order).

The predict_proba() will be outputing the values in the same order.


问:
Installer to execute multiple .msi files
I have developed several applications and their executable are in .msi format.

Now I need to develop a single installer which when installed should install all of my developed application( 8 to 10 msi files)

Is there any way to achieve this using Wix Setup Project or something else.

答:
Use Wix's bundle, and chain multiple

http://wixtoolset.org/documentation/manual/v3/bundle/
http://wixtoolset.org/documentation/manual/v3/xsd/wix/chain.html


问:
XMLEncoder not writing object data when class fields are private
I have a class with private fields and public methods. My methods follow the get/set naming convention. When my fields are private and I try to write my object data to an XML file, I get an empty XML file, but when I change them to public, the XML contains all the necessary data. What do you think is causing this?</p>

```<code>public class ClassData {

private String name;
private ArrayList<String> methods;

public ClassData()
{
    methods = new ArrayList<>();
}

public void setName(String cName)
{
    name = cName;
}

public String getName()
{
    return name;
}

public void setMethods(String mName)
{
    methods.add(mName);
}

public ArrayList<String> getMethods()
{
    return methods;
}

}

String fileName = cObj.getName() + ".xml";

XMLEncoder enc=null;

try{
    enc=new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fileName)));
}catch(FileNotFoundException fileNotFound){
    System.out.println("Unable to save file.");
}

enc.writeObject(cObj);
enc.close();
</code>```

答:
This is because your methods do not have a "Setter" to make it an accessible "property". Change method setMethods(String mName) to addMethod(String mName) to add individual method and add a setter setMethods that sets same time as that of methods and things work. Sample below:

```<code>import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;

public class ClassData {

    private String name;
    private ArrayList<String> methods;

    public ClassData() {
        methods = new ArrayList<>();
    }

    public void setName(String cName) {
        name = cName;
    }

    public String getName() {
        return name;
    }

    public void addMethod(String mName) {
        methods.add(mName);
    }
    public void setMethods(ArrayList<String> m)
    {
        methods.addAll(m);
    }

    public ArrayList<String> getMethods() {
        return methods;
    }

    public static void main(String[] args) {
        ClassData cObj = new ClassData();
        cObj.setName("This_is_name");
        cObj.addMethod("m1");
        String fileName = cObj.getName() + ".xml";

        XMLEncoder enc = null;

        try {
            enc = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fileName)));
        } catch (FileNotFoundException fileNotFound) {
            System.out.println("Unable to save file.");
        }

        enc.writeObject(cObj);
        enc.close();

    }

}
</code>```

Body:
I have a class with private fields and public methods. My methods follow the get/set naming convention. When my fields are private and I try to write my object data to an XML file, I get an empty XML file, but when I change them to public, the XML contains all the necessary data. What do you think is causing this?

public class ClassData {

private String name;
private ArrayList<String> methods;

public ClassData()
{
    methods = new ArrayList<>();
}

public void setName(String cName)
{
    name = cName;
}

public String getName()
{
    return name;
}

public void setMethods(String mName)
{
    methods.add(mName);
}

public ArrayList<String> getMethods()
{
    return methods;
}

}

String fileName = cObj.getName() + ".xml";

XMLEncoder enc=null;

try{
    enc=new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fileName)));
}catch(FileNotFoundException fileNotFound){
    System.out.println("Unable to save file.");
}

enc.writeObject(cObj);
enc.close();

Body:
This is because your methods do not have a "Setter" to make it an accessible "property". Change method setMethods(String mName) to addMethod(String mName) to add individual method and add a setter setMethods that sets same time as that of methods and things work. Sample below:

import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;

public class ClassData {

    private String name;
    private ArrayList<String> methods;

    public ClassData() {
        methods = new ArrayList<>();
    }

    public void setName(String cName) {
        name = cName;
    }

    public String getName() {
        return name;
    }

    public void addMethod(String mName) {
        methods.add(mName);
    }
    public void setMethods(ArrayList<String> m)
    {
        methods.addAll(m);
    }

    public ArrayList<String> getMethods() {
        return methods;
    }

    public static void main(String[] args) {
        ClassData cObj = new ClassData();
        cObj.setName("This_is_name");
        cObj.addMethod("m1");
        String fileName = cObj.getName() + ".xml";

        XMLEncoder enc = null;

        try {
            enc = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fileName)));
        } catch (FileNotFoundException fileNotFound) {
            System.out.println("Unable to save file.");
        }

        enc.writeObject(cObj);
        enc.close();

    }

}


问:
asp.net access user control in vb class
i have a usercontrol named filebox (which wraps a fileupload and some related stuff)

in a certain .net class i have need to use this type as a ctype

but i cant seem to call ctype(aobject,filebox)

or either ctype(aobject,Controls_filebox) (which is the correct name)

how can i convert an object to this type?

thanks a million!

答:
You need to add the class' namespace.

It's probably in the ASP namespace; you can check in the Object Browser.

You can change the namespace by adding Class="My.Namespace.Filebox" in the <%@ Control directive.

Title: asp.net access user control in vb class


问:
CDPATH configured but not working
I've been trying to configure the CDPATH variable to include some directories with long absolute paths, placed on an external drive, but despite telling me the directory is included, the 'cd' command doesn't change directory either way

I used the following commands:

$ export CDPATH=/media/user/01/workspace/rubystudies

then

$ echo $CDPATH, which returned to me the following:

/media/user/01/workspace/rubystudies

However, when I try cd rubystudies or cd /rubystudies it says

bash: cd: /rubystudies: No such file or directory

What exactly am I doing wrong? Is this really how I use cd after configuring CDPATH?

答:
Below is the documentation for the CDPATH setting:

The search path for the cd command.  This is a colon-separated
  list of directories in which the shell looks for destination
  directories specified by the cd command.  A sample value is ".:~:/usr".

So, the CDPATH setting isn't simply a colon separated list of bookmarks.  It is more similar to the PATH setting in that it looks inside of each of the listed directories for the directory passed to the cd command.

If you want to properly use the setting here, I would try:

```<code>export CDPATH='.:/media/user/01/workspace'
</code>```

... which would allow you to execute cd rubystudies/ as you need.

I use the CDPATH to hold . (the current working directory) and a directory with all of my projects so that I can switch to any one of them from anywhere. You may also want to include your home directory for quick access to the sub-directories it contains.

Title: CDPATH configured but not working

Body:
Below is the documentation for the CDPATH setting:

The search path for the cd command.  This is a colon-separated
  list of directories in which the shell looks for destination
  directories specified by the cd command.  A sample value is ".:~:/usr".

So, the CDPATH setting isn't simply a colon separated list of bookmarks.  It is more similar to the PATH setting in that it looks inside of each of the listed directories for the directory passed to the cd command.

If you want to properly use the setting here, I would try:

export CDPATH='.:/media/user/01/workspace'

... which would allow you to execute cd rubystudies/ as you need.

I use the CDPATH to hold . (the current working directory) and a directory with all of my projects so that I can switch to any one of them from anywhere. You may also want to include your home directory for quick access to the sub-directories it contains.


问:
Autocomplete in a ComboBox Using Access 2017
I want to make Autocomplete in a ComboBox using Access 2017. So I used this code... But there are some errors, like:

"The name 'da' does not exist in the current context".

Please help me to fix this error.

```<code>    private void Autocomplete()
    {
        string query;
        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Neth1.accdb");
        //opening connection
        con.Open();
        try
        {
            //initialize a new instance of sqlcommand
            OleDbCommand cmd = new OleDbCommand();
            //set a connection used by this instance of sqlcommand
            cmd.Connection = con;
            //set the sql statement to execute at the data source
            cmd.CommandText = query;

            OleDbDataAdapter da = new OleDbDataAdapter();
            //set the sql statement or stored procedure to execute at the data source
            da.SelectCommand = cmd;
            //initialize a new instance of DataTable
            DataTable dt = new DataTable();
            //add or resfresh rows in the certain range in the datatable to match those in the data source.
            da.Fill(dt);

            foreach (DataRow r in dt.Rows)
            {
                //getting all rows in the specific field|Column
                var rw = r.Field<string>("IMEI");

                //Set the properties of a combobox to make it auto suggest.
                comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
                comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
                //adding all rows into the combobox
                comboBox1.AutoCompleteCustomSource.Add(rw);

            }
        }
        catch (Exception ex)
        {
            //catching error
            MessageBox.Show(ex.Message);
        }
        //release all resources used by the component
          da.Dispose();
        //clossing connection
        con.Close();
    }
</code>```

答:
Your OleDbDataAdapter is declare inside the try block, it doesn't exist outside of it, hence the error you're seeing.

The query string presented here is empty.

When you deal with OleDb objects, it's common practice to make use
of using blocks, which take care of disposing the disposable objects you create.

What you rally don't want, is to set those controls properties inside a foreach loop.

It is also more efficient to fill the ComboBox AutoCompleteCustomSource using AddRage(), instead of adding objects one by one.

This is how I propose to edit your code:

```<code>// You can set these properties in the Form designer
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
// [...]

string query = "SELECT [Some Field] FROM [Some Table] WHERE [Some Condition]";
List<string> data = new List<string>();

try {
    using (var con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Neth1.accdb"))
    {
        con.Open();
        using (var cmd = new OleDbCommand(query, con))
        using (var reader = cmd.ExecuteReader()) {
            if (reader.HasRows) {
                while (reader.Read()) {
                   data.Add((string)reader["IMEI"]);
                }
            }
        }
    }
}
catch {
    // Notify, log, whatever fits
}
 comboBox1.AutoCompleteCustomSource.Clear();
 comboBox1.AutoCompleteCustomSource.AddRange(data.ToArray());
 data.Clear();
</code>```

Body:
I want to make Autocomplete in a ComboBox using Access 2017. So I used this code... But there are some errors, like:

"The name 'da' does not exist in the current context".

Please help me to fix this error.

    private void Autocomplete()
    {
        string query;
        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Neth1.accdb");
        //opening connection
        con.Open();
        try
        {
            //initialize a new instance of sqlcommand
            OleDbCommand cmd = new OleDbCommand();
            //set a connection used by this instance of sqlcommand
            cmd.Connection = con;
            //set the sql statement to execute at the data source
            cmd.CommandText = query;

            OleDbDataAdapter da = new OleDbDataAdapter();
            //set the sql statement or stored procedure to execute at the data source
            da.SelectCommand = cmd;
            //initialize a new instance of DataTable
            DataTable dt = new DataTable();
            //add or resfresh rows in the certain range in the datatable to match those in the data source.
            da.Fill(dt);

            foreach (DataRow r in dt.Rows)
            {
                //getting all rows in the specific field|Column
                var rw = r.Field<string>("IMEI");

                //Set the properties of a combobox to make it auto suggest.
                comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
                comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
                //adding all rows into the combobox
                comboBox1.AutoCompleteCustomSource.Add(rw);

            }
        }
        catch (Exception ex)
        {
            //catching error
            MessageBox.Show(ex.Message);
        }
        //release all resources used by the component
          da.Dispose();
        //clossing connection
        con.Close();
    }

Body:
Your OleDbDataAdapter is declare inside the try block, it doesn't exist outside of it, hence the error you're seeing.

The query string presented here is empty.

When you deal with OleDb objects, it's common practice to make use
of using blocks, which take care of disposing the disposable objects you create.

What you rally don't want, is to set those controls properties inside a foreach loop.

It is also more efficient to fill the ComboBox AutoCompleteCustomSource using AddRage(), instead of adding objects one by one.

This is how I propose to edit your code:

// You can set these properties in the Form designer
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
// [...]

string query = "SELECT [Some Field] FROM [Some Table] WHERE [Some Condition]";
List<string> data = new List<string>();

try {
    using (var con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Neth1.accdb"))
    {
        con.Open();
        using (var cmd = new OleDbCommand(query, con))
        using (var reader = cmd.ExecuteReader()) {
            if (reader.HasRows) {
                while (reader.Read()) {
                   data.Add((string)reader["IMEI"]);
                }
            }
        }
    }
}
catch {
    // Notify, log, whatever fits
}
 comboBox1.AutoCompleteCustomSource.Clear();
 comboBox1.AutoCompleteCustomSource.AddRange(data.ToArray());
 data.Clear();


问:
What exactly is a reference variable in Java? How does it differ from other variables?
I have been studying Inheritance in Java and the writer makes the statement "it is the type of object being referred to (not the type of reference variable) that determines which version of an overridden method will be executed."
This statement is awfully confusing.</p>

答:
A reference variable looks like this :

```<code>Coordinate cords; //Cords is the ref. var
</code>```

Inside of that reference variable is an address inside of your computer's RAM which stores the attributes of that object. Since we did not instantiate (actually make an object of) the address of the aforementioned cords object is null

Reference variables hold addresses to reserved parts of memory.

```<code>cords = new Coordinate(0.0,0.0,0.0);
</code>```

Now inside of the RAM of the computer is a reserved space that holds three floating type variables. Upon instantiation, a reference variable holds the address. So what can we do with addresses in Java?

Nothing of use. Java memory address are useless, and you can not see them(Though they look something like 0xFFFFFFF)

For a visual representation click here

Body:
A reference variable looks like this :

Coordinate cords; //Cords is the ref. var

Inside of that reference variable is an address inside of your computer's RAM which stores the attributes of that object. Since we did not instantiate (actually make an object of) the address of the aforementioned cords object is null

Reference variables hold addresses to reserved parts of memory.

cords = new Coordinate(0.0,0.0,0.0);

Now inside of the RAM of the computer is a reserved space that holds three floating type variables. Upon instantiation, a reference variable holds the address. So what can we do with addresses in Java?

Nothing of use. Java memory address are useless, and you can not see them(Though they look something like 0xFFFFFFF)

For a visual representation click here


问:
explain arguments meaning in res = cv2.bitwise_and(img,img,mask = mask)
I am trying to extract blue colour of an input image. For that I create a blue HSV colour boundary and threshold HSV image by using the command

```<code>mask_img = cv2.inRange(hsv, lower_blue, upper_blue)
</code>```

After that I used a bitwise_and on the input image and the threshold image by using

```<code>res = cv2.bitwise_and(img, img, mask = mask_img)
</code>```

Where img is the input image. I got this code from opencv. But I didn't understand why are three arguments used in bitwise_and and what actually each arguments mean? Why the same image is used at src1 and src2 ?

And also what is the use of mask keyword here? Please help me to find out the answer

答: Regarding using img twice, my guess is that we don't really care what img[i] and img[i] is, as it's just img[i] for binary. What matters is that, as mentioned by Mohammed Awney, when the mask is 0, we make img[i] be 0, otherwise we leave the pixel alone. This is a way to make certain pixels in img black, according to our mask.</p>

Body:
I am trying to extract blue colour of an input image. For that I create a blue HSV colour boundary and threshold HSV image by using the command

mask_img = cv2.inRange(hsv, lower_blue, upper_blue)

After that I used a bitwise_and on the input image and the threshold image by using

res = cv2.bitwise_and(img, img, mask = mask_img)

Where img is the input image. I got this code from opencv. But I didn't understand why are three arguments used in bitwise_and and what actually each arguments mean? Why the same image is used at src1 and src2 ?

And also what is the use of mask keyword here? Please help me to find out the answer


问:
SimpleFacets.lamba and NumberFormatException Errors on Enum FieldType in Solr
Has anyone ever tried sorting on a enum field? I've got a field defined as an enum with a custom enumConfig.xml file that has about 1000 different values. If I try to make a range query on this enum field or sort by it, I get this exception:

```<code>Invalid shift value in prefixCoded bytes (is encoded value really an INT?).
</code>```

The values in the config file have both numbers and characters in them, if it's relevant/important...

It gives me a nasty exception if I try to facet on the field, too:

```<code>"msg": "Exception during facet.field: ORBIT",
"trace": "org.apache.solr.common.SolrException: Exception during
facet.field: ORBIT\n\tat org.apache.solr.request.SimpleFacets.lambda$getFacetFieldCounts$0(SimpleFacets.java:766)
</code>```

Says it's a NumberFormatException ...?

Although I only get that exception if I specify "facet.limit=-1", it works for small values.

答: Turns out weird errors like that can occur if you make changes to the enum config file, even if you reindex. I had to completely delete my collection to get it to work.</p>

Body:
Has anyone ever tried sorting on a enum field? I've got a field defined as an enum with a custom enumConfig.xml file that has about 1000 different values. If I try to make a range query on this enum field or sort by it, I get this exception:

Invalid shift value in prefixCoded bytes (is encoded value really an INT?).

The values in the config file have both numbers and characters in them, if it's relevant/important...

It gives me a nasty exception if I try to facet on the field, too:

"msg": "Exception during facet.field: ORBIT",
"trace": "org.apache.solr.common.SolrException: Exception during
facet.field: ORBIT\n\tat org.apache.solr.request.SimpleFacets.lambda$getFacetFieldCounts$0(SimpleFacets.java:766)

Says it's a NumberFormatException ...?

Although I only get that exception if I specify "facet.limit=-1", it works for small values.


答:
Your OleDbDataAdapter da = new OleDbDataAdapter(); is within try { } scope and

da.Dispose(); is outside of that scope, try to place this line within try { } scope or move OleDbDataAdapter da = new OleDbDataAdapter(); outside of try { }scope.

Title: Autocomplete in a ComboBox Using Access 2017


问:
Oracle stored procedure help
HI am new to stored procedure.
Am using a dynamic sql with

```<code>select * from table into var
</code>```

var is a variable.the var contains more than one value ,when i try to run the proc with inputs i get an error:

```<code>ORA-01422: exact fetch returns more than requested number of rows
</code>```

Is there a way such that the variable can hold more than one row using dynamic sql.

答:
You have to bulk collect the result set into a table of type if you're going to select multiple rows.

```<code>declare
    type record_type is table of <table_name>;
    var_records record_type;

begin

    select *
    bulk collect into var_records
    from <table_name>;

end;
/
</code>```

See also my answer to PL SQL how to select all columns

Title: Oracle stored procedure help

Body:
HI am new to stored procedure.
Am using a dynamic sql with

select * from table into var

var is a variable.the var contains more than one value ,when i try to run the proc with inputs i get an error:

ORA-01422: exact fetch returns more than requested number of rows

Is there a way such that the variable can hold more than one row using dynamic sql.

Body:
You have to bulk collect the result set into a table of type if you're going to select multiple rows.

declare
    type record_type is table of <table_name>;
    var_records record_type;

begin

    select *
    bulk collect into var_records
    from <table_name>;

end;
/

See also my answer to PL SQL how to select all columns


问:
Rails: How can I ignore fixtures for single test
I have two tests. The results of each depend upon the user count.

At the moment, I have no user fixtures. The second test introduces a user in its setup method. The first test would fail if there were users in the db.

But I want to introduce users in users.yml. As such, the first test will fail because of the existing users. Is there any way I can instruct this test to ignore fixtures/users.yml?

```<code>require 'test_helper'

class UsersSignupTestWithoutExistingUsers < ActionDispatch::IntegrationTest
  test "Signup page is accessible" do
    get new_user_registration_path
    assert_response :success
  end
end

class UsersSignupTestWithExistingUsers < ActionDispatch::IntegrationTest
  def setup
    post user_registration_path, params: {user: {
      email:                 "user@test.com",
      password:              "password",
      password_confirmation: "password"
    }}
  end

  test "Signup page will redirect" do
    get new_user_registration_path
    assert_response :redirect
  end
end
</code>```

答: In the test that requires no users in the DB you can stub the method that looks in the DB for users so that it returns an empty set for that test.</p>

Body:
I have two tests. The results of each depend upon the user count.

At the moment, I have no user fixtures. The second test introduces a user in its setup method. The first test would fail if there were users in the db.

But I want to introduce users in users.yml. As such, the first test will fail because of the existing users. Is there any way I can instruct this test to ignore fixtures/users.yml?

require 'test_helper'

class UsersSignupTestWithoutExistingUsers < ActionDispatch::IntegrationTest
  test "Signup page is accessible" do
    get new_user_registration_path
    assert_response :success
  end
end

class UsersSignupTestWithExistingUsers < ActionDispatch::IntegrationTest
  def setup
    post user_registration_path, params: {user: {
      email:                 "user@test.com",
      password:              "password",
      password_confirmation: "password"
    }}
  end

  test "Signup page will redirect" do
    get new_user_registration_path
    assert_response :redirect
  end
end


问:
How to stop labels from moving up when navigation bar disappears?
The layout in Xcode:

Output, in an iPhone 5s simulator once the navigation bar is removed:

Initially, at the start of this view, the navigation bar is required, but when I hit the record button, the navigation bar is to disappear, which it does. However, in doing so, it moves the timer labels up with it. How do I stop autolayout from moving the labels up?

Thanks.

答: Solved by grouping the elements I wanted (bottom views) into a stacked view, then by setting a constraint to the bottom, whilst leaving a constraint on the top element to the top. </p>


问:
UIWebview won't zoom even after setting scalesPageToFit to YES
I have a UIWebview that is loaded as a subview when a user selects a tab on a UISegmentedControl. For some reason, I can not get it to allow pinch/zooming.
I set the following code in the viewDidLoad: method, so it should work.

```<code>self.myWebView = [[[UIWebView alloc] initWithFrame:self.view.frame] autorelease];
self.myWebView.backgroundColor = [UIColor whiteColor];
self.myWebView.scalesPageToFit = YES;
self.myWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
self.myWebView.delegate = self;
[self.view addSubview: myWebView];
</code>```

I tried loading a UIWebView from a NIB and creating it programmatically with no avail. Is there something I'm missing? What could be causing the webview to ignore pinching and zooming?

Thanks!

答:
I solved this with setting a view port:

```<code><meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.5; user-scalable=1"/>
</code>```

Good luck

Body:
I have a UIWebview that is loaded as a subview when a user selects a tab on a UISegmentedControl. For some reason, I can not get it to allow pinch/zooming.
I set the following code in the viewDidLoad: method, so it should work.

self.myWebView = [[[UIWebView alloc] initWithFrame:self.view.frame] autorelease];
self.myWebView.backgroundColor = [UIColor whiteColor];
self.myWebView.scalesPageToFit = YES;
self.myWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
self.myWebView.delegate = self;
[self.view addSubview: myWebView];

I tried loading a UIWebView from a NIB and creating it programmatically with no avail. Is there something I'm missing? What could be causing the webview to ignore pinching and zooming?

Thanks!

Body:
I solved this with setting a view port:

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.5; user-scalable=1"/>

Good luck


问:
Tensorflow variable images size within single batch
I am currently implementing FCN in tensorflow that enables variable input image size.

I have images of really various image sizes, but unfortunately I am not able to start the training with batch size different than 1.

I am using the feed dict in a following way:

```<code>feed_dict = {fcn.images: image_batch,
             fcn.labels: labels_batch,
             fcn.dropout_keep: dropout}
result = sess.run(list(tf_ops), feed_dict=feed_dict)
</code>```

I have already tried:

Creating image_batch and labels_batch as numpy array, this however does not work since numpy arrays does not support variable certain dimensions.

Creating image_batch and labels_batch as list of numpy arrays. Here seems that tensorflow is trying to call numpy.array(image_batch).

Going with tf.pack(), this unfortunately does not support different image sizes as well

My question is:
Is there a way how to solve this problem?

Thank you in advance for any suggestions and advices.

答:
So we can close this - quoting Olivier Moindrot above:

You have to pad or resize all your images to the same size before batching them.

Note that after Olivier's answer, there was a new tf.image.decode_and_crop_jpeg op added that can make it a bit easier to do this.

Body:
I am currently implementing FCN in tensorflow that enables variable input image size.

I have images of really various image sizes, but unfortunately I am not able to start the training with batch size different than 1.

I am using the feed dict in a following way:

feed_dict = {fcn.images: image_batch,
             fcn.labels: labels_batch,
             fcn.dropout_keep: dropout}
result = sess.run(list(tf_ops), feed_dict=feed_dict)

I have already tried:

Creating image_batch and labels_batch as numpy array, this however does not work since numpy arrays does not support variable certain dimensions.

Creating image_batch and labels_batch as list of numpy arrays. Here seems that tensorflow is trying to call numpy.array(image_batch).

Going with tf.pack(), this unfortunately does not support different image sizes as well

My question is:
Is there a way how to solve this problem?

Thank you in advance for any suggestions and advices.


问:
How to find the index of a missing element?
Let's say you have the following lists:

```<code>fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]
</code>```

How would I write a loop that identifies that the "pear" element is missing in the
"fruits" list's 2nd index?

I do know the first step begins with:

```<code>for element in fruit_types:
    if element not in fruits:
</code>```

But I am completely lost where else to go from here.

答:
The above set differences work. But in case you wanted code that only checks if one of the two lists has missing elements (In your style). You could use the enumerate function.

```<code>fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]

def find_missing_index():
    for index, element in enumerate(fruit_types):
        if element not in fruits:
            print(fruit_types[index], index)

def main():
    find_missing_index()

if __name__ == '__main__':
    main()
</code>```

No doubt you wanted the set difference code however which there are plenty of examples from others.

For added performance, it would be wise to convert fruits to a set in advance.

```<code>fset = set(fruits)
for index, element in enumerate(fruit_types):
    if element not in fset:
        print(fruit_types[index], index)
</code>```

This reduces the membership test to constant, O(1) lookup.

Body:
Let's say you have the following lists:

fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]

How would I write a loop that identifies that the "pear" element is missing in the
"fruits" list's 2nd index?

I do know the first step begins with:

for element in fruit_types:
    if element not in fruits:

But I am completely lost where else to go from here.

Body:
The above set differences work. But in case you wanted code that only checks if one of the two lists has missing elements (In your style). You could use the enumerate function.

fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]

def find_missing_index():
    for index, element in enumerate(fruit_types):
        if element not in fruits:
            print(fruit_types[index], index)

def main():
    find_missing_index()

if __name__ == '__main__':
    main()

No doubt you wanted the set difference code however which there are plenty of examples from others.

For added performance, it would be wise to convert fruits to a set in advance.

fset = set(fruits)
for index, element in enumerate(fruit_types):
    if element not in fset:
        print(fruit_types[index], index)

This reduces the membership test to constant, O(1) lookup.


问:
How to check which values have overlapping keys in a dictionary?
I have a dictionary:

```<code>{0: [1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [0, 9, 4, 6, 7], 2: [8, 9, 3, 6, 0], 3: [8, 9, 2, 0], 4: [8, 0, 1, 6, 7], 5: [0, 9], 6: [8, 0, 2, 4, 1], 7: [8, 0, 4, 1], 8: [0, 2, 3, 4, 6, 7], 9: [0, 1, 2, 3, 5]}
</code>```

And then I take an input which references one of the keys:

```<code>flag = 0
user = input("Enter an integer for a user ID: ")
if isinstance(user, float):
    flag = 1
if user.isdigit() and int(user) >= 0 and int(user) <= (len(network)-1) and flag == 0:
    return(user)
else:
    while user.isdigit() == False or int(user) < 0 or int(user) > (len(network)-1):
        user = input("Enter an integer for a user ID: ")
</code>```

So now I need to help to understand to find the values with overlapping keys, for example, if the user chooses 4 the code would output:

```<code>"For user with ID 4 we recommend the user with ID 2"
"That is because users 4 and 2 have 3 common friends and user 4 does not have more common friends with anyone else."
</code>```

Also the users cannot know each other.  So even though 4 has more in common with 0, they know each other and therefore do not work.

Thanks!

答:
Approach:

Function matchMaker(id, d) which accepts the id and d

Loop through key-value pairs in d

Checks if key is not same as the id

Checks if id's know each other

Finds the common friends between id and every other id; appends to list l2

If match exists finds all and returns the list matches else []

Code

```<code>d={0: [1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [0, 9, 4, 6, 7], 2: [8, 9, 3, 6, 0], 3: [8, 9, 2, 0], 4: [8, 0, 1, 6, 7], 5: [0, 9], 6: [8, 0, 2, 4, 1], 7: [8, 0, 4, 1], 8: [0, 2, 3, 4, 6, 7], 9: [0, 1, 2, 3, 5]}

def matchMaker(id, d):
    l2=[]
    for k,v in d.items():
        if k!=id:
            if id not in v:
                f = set(d[id]).intersection(v)
                l2.append([len(f), k])        # append f if you want the suggestions
    matches=[]
    if l2:
        match_count = max(l2)[0]
        matchid = max(l2)[1]
        matches = [matchid]

        for item in l2:
            if item[1] not in matches:
                if match_count == item[0]:
                    matches.append(item[1])
    return matches

id=5
all_matches = matchMaker(id,d)

print(all_matches)
</code>```

To obtain the integer value of id, use all_matches[0], all_matches[1] etc.

Output

```<code># matches for id = 5
[3, 1, 2]

# matches for id = 4
[2]
</code>```

Body:
I have a dictionary:

{0: [1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [0, 9, 4, 6, 7], 2: [8, 9, 3, 6, 0], 3: [8, 9, 2, 0], 4: [8, 0, 1, 6, 7], 5: [0, 9], 6: [8, 0, 2, 4, 1], 7: [8, 0, 4, 1], 8: [0, 2, 3, 4, 6, 7], 9: [0, 1, 2, 3, 5]}

And then I take an input which references one of the keys:

flag = 0
user = input("Enter an integer for a user ID: ")
if isinstance(user, float):
    flag = 1
if user.isdigit() and int(user) >= 0 and int(user) <= (len(network)-1) and flag == 0:
    return(user)
else:
    while user.isdigit() == False or int(user) < 0 or int(user) > (len(network)-1):
        user = input("Enter an integer for a user ID: ")

So now I need to help to understand to find the values with overlapping keys, for example, if the user chooses 4 the code would output:

"For user with ID 4 we recommend the user with ID 2"
"That is because users 4 and 2 have 3 common friends and user 4 does not have more common friends with anyone else."

Also the users cannot know each other.  So even though 4 has more in common with 0, they know each other and therefore do not work.

Thanks!

Body:
Approach:

Function matchMaker(id, d) which accepts the id and d

Loop through key-value pairs in d

Checks if key is not same as the id

Checks if id's know each other

Finds the common friends between id and every other id; appends to list l2

If match exists finds all and returns the list matches else []

Code

d={0: [1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [0, 9, 4, 6, 7], 2: [8, 9, 3, 6, 0], 3: [8, 9, 2, 0], 4: [8, 0, 1, 6, 7], 5: [0, 9], 6: [8, 0, 2, 4, 1], 7: [8, 0, 4, 1], 8: [0, 2, 3, 4, 6, 7], 9: [0, 1, 2, 3, 5]}

def matchMaker(id, d):
    l2=[]
    for k,v in d.items():
        if k!=id:
            if id not in v:
                f = set(d[id]).intersection(v)
                l2.append([len(f), k])        # append f if you want the suggestions
    matches=[]
    if l2:
        match_count = max(l2)[0]
        matchid = max(l2)[1]
        matches = [matchid]

        for item in l2:
            if item[1] not in matches:
                if match_count == item[0]:
                    matches.append(item[1])
    return matches

id=5
all_matches = matchMaker(id,d)

print(all_matches)

To obtain the integer value of id, use all_matches[0], all_matches[1] etc.

Output

# matches for id = 5
[3, 1, 2]

# matches for id = 4
[2]


问:
The proper way of using IsolationForest to detect outliers of high-dim dataset
I use the following simple IsolationForest algorithm to detect the outliers of given dataset X of 20K samples and 16 features, I run the following

```<code>train_X, tesy_X, train_y, test_y = train_test_split(X, y, train_size=.8)

clf = IsolationForest()
clf.fit(X)   # Notice I am using the entire dataset X when fitting!!
print (clf.predict(X))
</code>```

I get the result:

[ 1  1  1 -1  ... 1  1  1  -1  1]

This question is: Is it logically correct to use the entire dataset X when fitting into IsolationForest or only train_X?

答:
Yes, it is logically correct to ultimately train on the entire dataset.

With that in mind, you could measure the test set performance against the training set's performance.  This could tell you if the test set is from a similar distribution as your training set.

If the test set scores anomalous as compared to the training set, then you can expect future data to be similar.  In this case, I would like more data to have a more complete view of what is 'normal'.

If the test set scores similarly to the training set, I would be more comfortable with the final Isolation Forest trained on all data.

Perhaps you could use sklearn TimeSeriesSplit CV in this fashion to get a sense for how much data is enough for your problem?

Since this is unlabeled data to the anomaly detector, the more data the better when defining 'normal'.

Body:
I use the following simple IsolationForest algorithm to detect the outliers of given dataset X of 20K samples and 16 features, I run the following

train_X, tesy_X, train_y, test_y = train_test_split(X, y, train_size=.8)

clf = IsolationForest()
clf.fit(X)   # Notice I am using the entire dataset X when fitting!!
print (clf.predict(X))

I get the result:

[ 1  1  1 -1  ... 1  1  1  -1  1]

This question is: Is it logically correct to use the entire dataset X when fitting into IsolationForest or only train_X?


问:
Search for the original date - MYSQL
I need to find the original date of a pedimento (CUSTOMS document)
I have 2 tables DS_551 (The details table) and DS_701 the rectified pedimentos table.

And the structure of the tables are similar to this

DS_551

Patente

Pedimento

Aduana

Fecha Pago

Value

DS_701

Patente

Pedimento

Aduana

Fecha Pago

PatenteAnterior

PedimentoAnterior

AduanaAnterior

FechaAnterior

And i need to find the original date per example:

Format: (Patente-Pedimento-Aduana)

Original pedimento: 4020-8000001-400

1st rectification: 4020-8009005-400

2nd rectification: 4020-9001003-400

In all the cases i would have on my table (DS_551) only the last rectification in this case the 2nd (4020-9001003-400) but i need to update the row with the original pedimento date a.k.a fecha (4020-8000001-400)

on my table DS_701 the rows are similar to this

```<code>Patente|Pedimento|Aduana|Fecha Pago|PatenteAnterior|PedimentoAnterior|AduanaAnterior|FechaAnterior|
4020|9001003|400|2017-11-17|4020|8009005|400|2017-10-17|
4020|8009005|400|2017-10-17|4020|8000001|400|2016-01-01|
</code>```

In the example above the 1st row references to the data of the 2nd rectification and the previus document (the 1st rectification) and the 2nd row references to the data of the 1st rectification and the original document in the tables the word at the end "Anterior" references to the previus document data, so only having the data 4020|9001003|400 i need to find the date (fecha) of the document 4020|8000001|400

```<code>SELECT * FROM DS_551 WHERE CONCAT(Patente, Pedimento, Aduana) IN (SELECT CONCAT(Patente, Pedimento, Aduana) FROM DS_701)
</code>```

the above query returns the list of the documents that i need to find the original date or the documents that have an rectification.

given the above list of documents how i can loop over each item to find the original date of them?? each document can have infinite number of rectifications.

I'm doing this on a stored procedure on MYSQL

Fiddle: http://sqlfiddle.com/#!9/64f0a5/12

答:
This is the question:

how i can ... find the original date...??

For '4020' as the search string, the "original date" from the given data is 2016-01-01

This query, will return the "original date" for '4020'

```<code>  set @patente := '4020';
  select
      min(lafecha)
  from (
        select  Patente, Pedimento, Aduana, `FechaPago` lafecha
        from  DS_701
        where Patente = @patente
        union
        select  PatenteAnterior, PedimentoAnterior, FechaAnterior, FechaAnterior
        from DS_701
        where PatenteAnterior = @patente
        ) d1
</code>```

The result is:

```<code>| min(lafecha) |
|--------------|
|   2016-01-01 |
</code>```

We can take it a step further:

```<code>set @patente := '4020';
select
*
from DS_701
where Patente = @patente
and coalesce(FechaAnterior,FechaPago) =
     (select
          min(lafecha)
      from (
            select  Patente, Pedimento, Aduana, `FechaPago` lafecha
            from  DS_701
            where Patente = @patente
            union
            select  PatenteAnterior, PedimentoAnterior, FechaAnterior, FechaAnterior
            from DS_701
            where PatenteAnterior = @patente
            ) d1
     )
;
</code>```

Which returns the "original" row:

```<code>| ID | Patente | Pedimento | Aduana |  FechaPago | PatenteAnterior | PedimentoAnterior | AduanaAnterior | FechaAnterior |
|----|---------|-----------|--------|------------|-----------------|-------------------|----------------|---------------|
|  2 |    4020 |   8009005 |    400 | 2017-10-17 |            4020 |           8000001 |            400 |    2016-01-01 |
</code>```

See: http://sqlfiddle.com/#!9/64f0a5/52

Title: Search for the original date - MYSQL

Body:
I need to find the original date of a pedimento (CUSTOMS document)
I have 2 tables DS_551 (The details table) and DS_701 the rectified pedimentos table.

And the structure of the tables are similar to this

DS_551

Patente

Pedimento

Aduana

Fecha Pago

Value

DS_701

Patente

Pedimento

Aduana

Fecha Pago

PatenteAnterior

PedimentoAnterior

AduanaAnterior

FechaAnterior

And i need to find the original date per example:

Format: (Patente-Pedimento-Aduana)

Original pedimento: 4020-8000001-400

1st rectification: 4020-8009005-400

2nd rectification: 4020-9001003-400

In all the cases i would have on my table (DS_551) only the last rectification in this case the 2nd (4020-9001003-400) but i need to update the row with the original pedimento date a.k.a fecha (4020-8000001-400)

on my table DS_701 the rows are similar to this

Patente|Pedimento|Aduana|Fecha Pago|PatenteAnterior|PedimentoAnterior|AduanaAnterior|FechaAnterior|
4020|9001003|400|2017-11-17|4020|8009005|400|2017-10-17|
4020|8009005|400|2017-10-17|4020|8000001|400|2016-01-01|

In the example above the 1st row references to the data of the 2nd rectification and the previus document (the 1st rectification) and the 2nd row references to the data of the 1st rectification and the original document in the tables the word at the end "Anterior" references to the previus document data, so only having the data 4020|9001003|400 i need to find the date (fecha) of the document 4020|8000001|400

SELECT * FROM DS_551 WHERE CONCAT(Patente, Pedimento, Aduana) IN (SELECT CONCAT(Patente, Pedimento, Aduana) FROM DS_701)

the above query returns the list of the documents that i need to find the original date or the documents that have an rectification.

given the above list of documents how i can loop over each item to find the original date of them?? each document can have infinite number of rectifications.

I'm doing this on a stored procedure on MYSQL

Fiddle: http://sqlfiddle.com/#!9/64f0a5/12

Body:
This is the question:

how i can ... find the original date...??

For '4020' as the search string, the "original date" from the given data is 2016-01-01

This query, will return the "original date" for '4020'

  set @patente := '4020';
  select
      min(lafecha)
  from (
        select  Patente, Pedimento, Aduana, `FechaPago` lafecha
        from  DS_701
        where Patente = @patente
        union
        select  PatenteAnterior, PedimentoAnterior, FechaAnterior, FechaAnterior
        from DS_701
        where PatenteAnterior = @patente
        ) d1

The result is:

| min(lafecha) |
|--------------|
|   2016-01-01 |

We can take it a step further:

set @patente := '4020';
select
*
from DS_701
where Patente = @patente
and coalesce(FechaAnterior,FechaPago) =
     (select
          min(lafecha)
      from (
            select  Patente, Pedimento, Aduana, `FechaPago` lafecha
            from  DS_701
            where Patente = @patente
            union
            select  PatenteAnterior, PedimentoAnterior, FechaAnterior, FechaAnterior
            from DS_701
            where PatenteAnterior = @patente
            ) d1
     )
;

Which returns the "original" row:

| ID | Patente | Pedimento | Aduana |  FechaPago | PatenteAnterior | PedimentoAnterior | AduanaAnterior | FechaAnterior |
|----|---------|-----------|--------|------------|-----------------|-------------------|----------------|---------------|
|  2 |    4020 |   8009005 |    400 | 2017-10-17 |            4020 |           8000001 |            400 |    2016-01-01 |

See: http://sqlfiddle.com/#!9/64f0a5/52


问:
Is it possible to simplify SQL Query
I take need to take count depend on different values. I am using this one. Can I simplify that.

```<code>SELECT
[FC].[Name] AS [JobCategory],
(SELECT COUNT(*)
  FROM [dbo].[JobCandidateHire] AS [JCH]
  LEFT JOIN [dbo].[Job] AS [J] ON [J].[ID]=[JCH].[JobID]
  LEFT JOIN [dbo].[Candidate] AS [C] ON [C].[ID]=[JCH].[CandidateID]
  LEFT JOIN [dbo].[JobCandidateHireLevel] AS [JCHL] ON [JCHL].[ID]=[JCH].[JobCandidateHireLevelID]
  WHERE [JCHL].[LevelType]=5 AND [J].[FunctionalCategoryID] =[FC].[ID]  AND [C].[EthnicityID]=5 AND [C].[GenderID]=2
) AS [HMale],
(SELECT COUNT(*)
  FROM [dbo].[JobCandidateHire] AS [JCH]
  LEFT JOIN [dbo].[Job] AS [J] ON [J].[ID]=[JCH].[JobID]
  LEFT JOIN [dbo].[Candidate] AS [C] ON [C].[ID]=[JCH].[CandidateID]
  LEFT JOIN [dbo].[JobCandidateHireLevel] AS [JCHL] ON [JCHL].[ID]=[JCH].[JobCandidateHireLevelID]
  WHERE [JCHL].[LevelType]=5 AND [J].[FunctionalCategoryID] =[FC].[ID] AND [C].[EthnicityID]=2 AND [C].[GenderID]=3
) AS [AmericanIndianFemale],
(SELECT COUNT(*)
  FROM [dbo].[JobCandidateHire] AS [JCH]
  LEFT JOIN [dbo].[Job] AS [J] ON [J].[ID]=[JCH].[JobID]
  LEFT JOIN [dbo].[Candidate] AS [C] ON [C].[ID]=[JCH].[CandidateID]
  LEFT JOIN [dbo].[JobCandidateHireLevel] AS [JCHL] ON [JCHL].[ID]=[JCH].[JobCandidateHireLevelID]
  WHERE [JCHL].[LevelType]=5 AND [J].[FunctionalCategoryID] =[FC].[ID] AND [C].[EthnicityID]=7 AND [C].[GenderID]=3
) AS [TwoMoreRaceFemale],
(SELECT COUNT(*)
  FROM [dbo].[JobCandidateHire] AS [JCH]
  LEFT JOIN [dbo].[Job] AS [J] ON [J].[ID]=[JCH].[JobID]
  LEFT JOIN [dbo].[Candidate] AS [C] ON [C].[ID]=[JCH].[CandidateID]
  LEFT JOIN [dbo].[JobCandidateHireLevel] AS [JCHL] ON [JCHL].[ID]=[JCH].[JobCandidateHireLevelID]
  WHERE [JCHL].[LevelType]=5 AND [J].[FunctionalCategoryID] = [FC].[ID]
) AS [CategoryTotal],
[FC].[IsArchived]
FROM [dbo].[FunctionalCategory] AS [FC]
</code>```

Here the join is same for sub query, just where condition is different.

答:
The query below works syntactically, but without any schema or sample data provided it is the best estimate of a simpler query.</p>

```<code>select fc.name as JobCateogry
, sum(case when jchl.LevelType = 5 and c.EthnicityID = 5 and c.GenderID = 2 then 1 else 0 end) as HMale
, sum(case when jchl.LevelType = 5 and c.EthnicityID = 2 and c.GenderID = 3 then 1 else 0 end) as AmericanIndianFemale
, sum(case when jchl.LevelType = 5 and c.EthnicityID = 7 and c.GenderID = 3 then 1 else 0 end) as TwoMoreRaceFemale
, count(*) as CategoryTotal
, fc.IsArchived
from dbo.FunctionalCategory as fc
left join dbo.Job as j on fc.ID = j.FunctionalCategoryID
left join dbo.JobCandidateHire as jch on j.ID = jch.JobID
left join dbo.Candidate as c on c.id = jch.CandidateID
left join dbo.JobCandidateHireLevel as jchl on jchl.ID = jch.JobCandidateHireLevelID
group by fc.name
, fc.IsArchived
</code>```

Title: Is it possible to simplify SQL Query

Body:
I take need to take count depend on different values. I am using this one. Can I simplify that.

SELECT
[FC].[Name] AS [JobCategory],
(SELECT COUNT(*)
  FROM [dbo].[JobCandidateHire] AS [JCH]
  LEFT JOIN [dbo].[Job] AS [J] ON [J].[ID]=[JCH].[JobID]
  LEFT JOIN [dbo].[Candidate] AS [C] ON [C].[ID]=[JCH].[CandidateID]
  LEFT JOIN [dbo].[JobCandidateHireLevel] AS [JCHL] ON [JCHL].[ID]=[JCH].[JobCandidateHireLevelID]
  WHERE [JCHL].[LevelType]=5 AND [J].[FunctionalCategoryID] =[FC].[ID]  AND [C].[EthnicityID]=5 AND [C].[GenderID]=2
) AS [HMale],
(SELECT COUNT(*)
  FROM [dbo].[JobCandidateHire] AS [JCH]
  LEFT JOIN [dbo].[Job] AS [J] ON [J].[ID]=[JCH].[JobID]
  LEFT JOIN [dbo].[Candidate] AS [C] ON [C].[ID]=[JCH].[CandidateID]
  LEFT JOIN [dbo].[JobCandidateHireLevel] AS [JCHL] ON [JCHL].[ID]=[JCH].[JobCandidateHireLevelID]
  WHERE [JCHL].[LevelType]=5 AND [J].[FunctionalCategoryID] =[FC].[ID] AND [C].[EthnicityID]=2 AND [C].[GenderID]=3
) AS [AmericanIndianFemale],
(SELECT COUNT(*)
  FROM [dbo].[JobCandidateHire] AS [JCH]
  LEFT JOIN [dbo].[Job] AS [J] ON [J].[ID]=[JCH].[JobID]
  LEFT JOIN [dbo].[Candidate] AS [C] ON [C].[ID]=[JCH].[CandidateID]
  LEFT JOIN [dbo].[JobCandidateHireLevel] AS [JCHL] ON [JCHL].[ID]=[JCH].[JobCandidateHireLevelID]
  WHERE [JCHL].[LevelType]=5 AND [J].[FunctionalCategoryID] =[FC].[ID] AND [C].[EthnicityID]=7 AND [C].[GenderID]=3
) AS [TwoMoreRaceFemale],
(SELECT COUNT(*)
  FROM [dbo].[JobCandidateHire] AS [JCH]
  LEFT JOIN [dbo].[Job] AS [J] ON [J].[ID]=[JCH].[JobID]
  LEFT JOIN [dbo].[Candidate] AS [C] ON [C].[ID]=[JCH].[CandidateID]
  LEFT JOIN [dbo].[JobCandidateHireLevel] AS [JCHL] ON [JCHL].[ID]=[JCH].[JobCandidateHireLevelID]
  WHERE [JCHL].[LevelType]=5 AND [J].[FunctionalCategoryID] = [FC].[ID]
) AS [CategoryTotal],
[FC].[IsArchived]
FROM [dbo].[FunctionalCategory] AS [FC]

Here the join is same for sub query, just where condition is different.

Body:
The query below works syntactically, but without any schema or sample data provided it is the best estimate of a simpler query.

select fc.name as JobCateogry
, sum(case when jchl.LevelType = 5 and c.EthnicityID = 5 and c.GenderID = 2 then 1 else 0 end) as HMale
, sum(case when jchl.LevelType = 5 and c.EthnicityID = 2 and c.GenderID = 3 then 1 else 0 end) as AmericanIndianFemale
, sum(case when jchl.LevelType = 5 and c.EthnicityID = 7 and c.GenderID = 3 then 1 else 0 end) as TwoMoreRaceFemale
, count(*) as CategoryTotal
, fc.IsArchived
from dbo.FunctionalCategory as fc
left join dbo.Job as j on fc.ID = j.FunctionalCategoryID
left join dbo.JobCandidateHire as jch on j.ID = jch.JobID
left join dbo.Candidate as c on c.id = jch.CandidateID
left join dbo.JobCandidateHireLevel as jchl on jchl.ID = jch.JobCandidateHireLevelID
group by fc.name
, fc.IsArchived


问:
Why does creating a 2x8 R8 texture from a 16 byte buffer fail in webgl2?
When I try to create a 2x8 R8 texture in webgl2, I get an error. This doesn't happen for a 4x8 texture. If I double the size of the input buffer compared to what I expect, the 2x8 succeeds.

Does webgl2 have a 'column alignment' of 4 when creating/reading textures?

Here is some code that reproduces the issue. I tested it on Windows in both Chrome and Firefox:

function test_read(w) {
    let gl = document.createElement('canvas').getContext('webgl2');
    let h = 8;
    let data = new Uint8Array(w*h);
    data[5] = 5;

    let texture = gl.createTexture();
    let frameBuffer = gl.createFramebuffer();
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, w, h, 0, gl.RED, gl.UNSIGNED_BYTE, data);
    if (gl.getError() !== gl.NO_ERROR) {
        return 'bad w=' + w;
    }
    return 'good w=' + w;
}

console.log(test_read(4)); // good w=4
console.log(test_read(2)); // bad w=2```

The error code coming out is 0x502 (INVALID_OPERATION). A similar issue happens when reading textures that were created by expanding the buffer: it seems to expect a 'column alignment' of 4.

答:
You need to set gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)

The default UNPACK_ALIGNMENT is 4 which means WebGL expects every row of pixel to be a multiple of 4 bytes. Since you're using R8 (1 byte pixel) and a width of 2 your rows are only 2 bytes long. When you change the width to 4 it starts working.

function test_read(w) {
    let gl = document.createElement('canvas').getContext('webgl2');
    let h = 8;
    let data = new Uint8Array(w*h);
    data[5] = 5;

    // ---=== ADDED ===---
    gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);

    let texture = gl.createTexture();
    let frameBuffer = gl.createFramebuffer();
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, w, h, 0, gl.RED, gl.UNSIGNED_BYTE, data);
    if (gl.getError() !== gl.NO_ERROR) {
        return 'bad w=' + w;
    }
    return 'good w=' + w;
}

console.log(test_read(4)); // good w=4
console.log(test_read(2)); // bad w=2```

Body:
When I try to create a 2x8 R8 texture in webgl2, I get an error. This doesn't happen for a 4x8 texture. If I double the size of the input buffer compared to what I expect, the 2x8 succeeds.

Does webgl2 have a 'column alignment' of 4 when creating/reading textures?

Here is some code that reproduces the issue. I tested it on Windows in both Chrome and Firefox:

function test_read(w) {
    let gl = document.createElement('canvas').getContext('webgl2');
    let h = 8;
    let data = new Uint8Array(w*h);
    data[5] = 5;

    let texture = gl.createTexture();
    let frameBuffer = gl.createFramebuffer();
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, w, h, 0, gl.RED, gl.UNSIGNED_BYTE, data);
    if (gl.getError() !== gl.NO_ERROR) {
        return 'bad w=' + w;
    }
    return 'good w=' + w;
}

console.log(test_read(4)); // good w=4
console.log(test_read(2)); // bad w=2

The error code coming out is 0x502 (INVALID_OPERATION). A similar issue happens when reading textures that were created by expanding the buffer: it seems to expect a 'column alignment' of 4.


问:
How to add calendar in a "form_for"
I am new in Rails, currently, I am working on my form (using 'form_for'), for some reason, I have to use form_for, can not use *sematic_form_for*, please don't ask me to use that.

My question is if I stick to use form_for, is there any way to implement a calendar selection field for date selection. (I know there is 'select_date' and 'date_select' helper, but they are drop down menus)

```<code>=form_for :myobject do |form|
  =form.??? /how to add a calender selection here??
</code>```

答:
I'd recommend using date_select so that users who do not or cannot effectively use JavaScript can still interact with your form.

That said, for those users who do have JavaScript enabled, the jQuery UI Datepicker is very slick and can integrate with Rails.

This blog post contains some details about integrating with Rails, and though it uses formtastic, it can be adapted.

Title: How to add calendar in a "form_for"

Body:
I am new in Rails, currently, I am working on my form (using 'form_for'), for some reason, I have to use form_for, can not use *sematic_form_for*, please don't ask me to use that.

My question is if I stick to use form_for, is there any way to implement a calendar selection field for date selection. (I know there is 'select_date' and 'date_select' helper, but they are drop down menus)

=form_for :myobject do |form|
  =form.??? /how to add a calender selection here??


问:
Making zoom on hover jquery
I want to know if there is a way with jquery to make the zoom effects like on this page http://chobanifoodservice.com/
As you can see, the image doesn't change its size, it zooms it while staying in the same size. Thanks in advance</p>

答:
You can accomplish this in CSS quite well.  Doing this only in jQuery becomes a lot more messy (in my opinion).

.zoom {
  display:inline-block;
  overflow:hidden;
  border:1px solid black;
}

.zoom img {
  transition:.1s ease-in-out;
}

.zoom:hover img {
  transform: scale(1.05);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="zoom">
  <img src="http://neil.computer/stack/food.jpg" />
</div></code>```

Title: Making zoom on hover jquery

Body:
You can accomplish this in CSS quite well.  Doing this only in jQuery becomes a lot more messy (in my opinion).

.zoom {
  display:inline-block;
  overflow:hidden;
  border:1px solid black;
}

.zoom img {
  transition:.1s ease-in-out;
}

.zoom:hover img {
  transform: scale(1.05);
}

<div class="zoom">
  <img src="http://neil.computer/stack/food.jpg" />
</div>