问:
Push an element at the end of an array
I have an array called result which I generate like this

```<code> while something
           $result[] = $row;
           array_push($result,$row['fld_ConsumptionValue'] * $energy_type_unit_price) // this won't do
    endwhile
</code>```

$result array is filled with db records. What I wanna do is to push another value I calculated like above. output is like this:

```<code>    result -> Array[6]
    [0] -> Array[34]
    [1] -> Calculated Value For 1st Record
    [2] -> Array[34]
    [3] -> Calculated Value For 2nd Record
...
...
...
</code>```

What I'm trying is to get this output

```<code> result -> Array[6]
    [0] -> Array[35]
    [1] -> Array[35]
...
...
</code>```

What am I doing wrong?

答:
This is it:</p>

```<code>while something
    // add new key to `$row`
    $row['someKey'] = $row['fld_ConsumptionValue'] * $energy_type_unit_price;
    // add `$row` to `$result`
    $result[] = $row;
endwhile
</code>```

Title: Push an element at the end of an array

Body:
I have an array called result which I generate like this

 while something
           $result[] = $row;
           array_push($result,$row['fld_ConsumptionValue'] * $energy_type_unit_price) // this won't do
    endwhile

$result array is filled with db records. What I wanna do is to push another value I calculated like above. output is like this:

    result -> Array[6]
    [0] -> Array[34]
    [1] -> Calculated Value For 1st Record
    [2] -> Array[34]
    [3] -> Calculated Value For 2nd Record
...
...
...

What I'm trying is to get this output

 result -> Array[6]
    [0] -> Array[35]
    [1] -> Array[35]
...
...

What am I doing wrong?

Body:
This is it:

while something
    // add new key to `$row`
    $row['someKey'] = $row['fld_ConsumptionValue'] * $energy_type_unit_price;
    // add `$row` to `$result`
    $result[] = $row;
endwhile


来源: stackexchange

问:
rule to run a command on newly generated files with gnumake
I am very new with make. I have a perl script that generates three latex files. I want to create a makefile that would execute the perl script and then run lualatex on the newly generates tex files. So far, I have the following:

```<code>make:
    perl diff.pl
pdf:
    make
    $(eval LIST := $(shell ls *.tex))
    lualatex $(LIST).tex
    make clean

clean:
    rm -rf *.log *.aux
</code>```

Output:

```<code>lualatex FLAT_FLAT_AVDD.tex FLAT_FLAT_VDD.tex FLAT_FLAT_VSS.tex.tex
</code>```

And I only get one pdf FLAT_FLAT_AVDD.pdf.
How can I run lualatex on all the files?
I can just declare three variables and then run make. But, how can I automate this? Is there a loop concept in make? What is a better way to achieve this with "hard-coding" the file names?

Thanks.
EDIT:
I tried to incorporate foreach.

```<code>make:
    perl diff.pl

list:
    $(eval LIST := $(shell ls *.tex))

pdf:
    make list
    $(foreach tex,$(LIST),$(lualatex $(tex)))
    make clean

clean:
    rm -rf *.log *.aux
</code>```

and then I ran, make pdf
I got the following output in terminal.

```<code>dedehog01:tislam1:243 > make pdf
make list
make[1]: Entering directory `/home/tislam1/Documents/THESIS/Script_v0.1/BOX_approach/Modified_Layout_mesh/IR_Report_mesh/flat_flat/make'
make[1]: `list' is up to date.
make[1]: Leaving directory `/home/tislam1/Documents/THESIS/Script_v0.1/BOX_approach/Modified_Layout_mesh/IR_Report_mesh/flat_flat/make'
make clean
make[1]: Entering directory `/home/tislam1/Documents/THESIS/Script_v0.1/BOX_approach/Modified_Layout_mesh/IR_Report_mesh/flat_flat/make'
rm -rf *.log *.aux
make[1]: Leaving directory `/home/tislam1/Documents/THESIS/Script_v0.1/BOX_approach/Modified_Layout_mesh/IR_Report_mesh/flat_flat/make'
</code>```

答:
Assuming you know the names of the three .tex files in advance, you can unconditionally run the perl, then update the .tex files only if the new ones actually differ from the old ones. Make will handle this fine.

```<code>tex := 1.tex 2.tex 3.tex
intermediates := ${tex:%.tex=%-new.tex}# 1-new.tex 2-new.tex 3-new.tex
pdfs := ${intermediates:%.tex=%.pdf}# 1-new.pdf etc.

.PHONY: perl
perl: ; perl diff.pl

${intermediates}: %-new.tex: %.tex | perl
    cmp -s $< $@ || mv $< $@

${pdfs}: %.pdf: %.tex
    lualatex $<

.PHONY: all
all: ${pdfs}
    : $@ Success
</code>```

Let's say the perl produces 1.tex, 2.tex and 3.tex

We unconditionally run the perl producing new copies of these three files.

Then we update 1-new.tex from 1.tex, but only if the two files differ.

Make notices any files that have changed and runs lualatex as appropriate.

This is parallel safe (a good test of any makefile). Run with -j3 to get 3 copies of lualatex running at once. You do have 4 CPUs don't you?

ContentLicense: CC BY-SA 3.0

Body:
I am very new with make. I have a perl script that generates three latex files. I want to create a makefile that would execute the perl script and then run lualatex on the newly generates tex files. So far, I have the following:

make:
    perl diff.pl
pdf:
    make
    $(eval LIST := $(shell ls *.tex))
    lualatex $(LIST).tex
    make clean

clean:
    rm -rf *.log *.aux

Output:

lualatex FLAT_FLAT_AVDD.tex FLAT_FLAT_VDD.tex FLAT_FLAT_VSS.tex.tex

And I only get one pdf FLAT_FLAT_AVDD.pdf.
How can I run lualatex on all the files?
I can just declare three variables and then run make. But, how can I automate this? Is there a loop concept in make? What is a better way to achieve this with "hard-coding" the file names?

Thanks.
EDIT:
I tried to incorporate foreach.

make:
    perl diff.pl

list:
    $(eval LIST := $(shell ls *.tex))

pdf:
    make list
    $(foreach tex,$(LIST),$(lualatex $(tex)))
    make clean

clean:
    rm -rf *.log *.aux

and then I ran, make pdf
I got the following output in terminal.

dedehog01:tislam1:243 > make pdf
make list
make[1]: Entering directory `/home/tislam1/Documents/THESIS/Script_v0.1/BOX_approach/Modified_Layout_mesh/IR_Report_mesh/flat_flat/make'
make[1]: `list' is up to date.
make[1]: Leaving directory `/home/tislam1/Documents/THESIS/Script_v0.1/BOX_approach/Modified_Layout_mesh/IR_Report_mesh/flat_flat/make'
make clean
make[1]: Entering directory `/home/tislam1/Documents/THESIS/Script_v0.1/BOX_approach/Modified_Layout_mesh/IR_Report_mesh/flat_flat/make'
rm -rf *.log *.aux
make[1]: Leaving directory `/home/tislam1/Documents/THESIS/Script_v0.1/BOX_approach/Modified_Layout_mesh/IR_Report_mesh/flat_flat/make'

Body:
Assuming you know the names of the three .tex files in advance, you can unconditionally run the perl, then update the .tex files only if the new ones actually differ from the old ones. Make will handle this fine.

tex := 1.tex 2.tex 3.tex
intermediates := ${tex:%.tex=%-new.tex}# 1-new.tex 2-new.tex 3-new.tex
pdfs := ${intermediates:%.tex=%.pdf}# 1-new.pdf etc.

.PHONY: perl
perl: ; perl diff.pl

${intermediates}: %-new.tex: %.tex | perl
    cmp -s $< $@ || mv $< $@

${pdfs}: %.pdf: %.tex
    lualatex $<

.PHONY: all
all: ${pdfs}
    : $@ Success

Let's say the perl produces 1.tex, 2.tex and 3.tex

We unconditionally run the perl producing new copies of these three files.

Then we update 1-new.tex from 1.tex, but only if the two files differ.

Make notices any files that have changed and runs lualatex as appropriate.

This is parallel safe (a good test of any makefile). Run with -j3 to get 3 copies of lualatex running at once. You do have 4 CPUs don't you?


问:
Gensim: Loss of Words/Tokens while Training
I have a corpus built out of Wikimedia Dump files stored at sentences.txt
I have a sentence say 'नीरजः हाँ माता जी! स्कूल ख़त्म होते सीधा घर आऊँगा'

Now when I try to extract the word vectors there is always one or two words which have been missed out while training (despite being included in the list to be trained upon) and I get the KeyError.
Is there any way to improve the training so that it doesn't miss out words that frequently?

Here is a proof that it does happen. tok.wordtokenize is a word tokenizer. sent.drawlist() as well as sents.drawlist() returns a list of sentences from the corpus stored inside sentences.txt.

```<code>>>> sentence = 'नीरजः हाँ माता जी! स्कूल ख़त्म होते सीधा घर आऊँगा'
>>> sentence = tok.wordtokenize(sentence) #tok.wordtokenize() is simply a word tokenizer.
>>> sentences = sent.drawlist()
>>> sentences = [tok.wordtokenize(i) for i in sentences]
>>> sentences2 = sents.drawlist()
>>> sentences2 = [tok.wordtokenize(i) for i in sentences2]
>>> sentences = sentences2 + sentences + sentence
>>> "नीरजः" in sentences #proof that the word is present inside sentences
True
>>> sentences[0:10] #list of tokenized sentences.
[['विश्व', 'भर', 'में', 'करोड़ों', 'टीवी', 'दर्शकों', 'की', 'उत्सुकता', 'भरी', 'निगाह', 'के', 'बीच', 'मिस', 'ऑस्ट्रेलिया', 'जेनिफर', 'हॉकिंस', 'को', 'मिस', 'यूनिवर्स-२००४', 'का', 'ताज', 'पहनाया', 'गया'], ['करीब', 'दो', 'घंटे', 'चले', 'कार्यक्रम', 'में', 'विभिन्न', 'देशों', 'की', '८०', 'सुंदरियों', 'के', 'बीच', '२०', 'वर्षीय', 'हॉकिंस', 'को', 'सर्वश्रेष्ठ', 'आंका', 'गया'], ['मिस', 'अमेरिका', 'शैंडी', 'फिनेजी', 'को', 'प्रथम', 'उप', 'विजेता', 'और', 'मिस', 'प्यूरेटो', 'रिको', 'अल्बा', 'रेइज', 'द्वितीय', 'उप', 'विजेता', 'चुनी', 'गई'], ['भारत', 'की', 'तनुश्री', 'दत्ता', 'अंतिम', '१०', 'प्रतिभागियों', 'में', 'ही', 'स्थान', 'बना', 'पाई'], ['हॉकिंस', 'ने', 'कहा', 'कि', 'जीत', 'के', 'बारे', 'में', 'उसने', 'सपने', 'में', 'भी', 'नहीं', 'सोचा', 'था'], ['सौंदर्य', 'की', 'यह', 'शीर्ष', 'प्रतियोगिता', 'क्विटो', 'के', 'कन्वेंशन', 'सेंटर', 'में', 'मंगलवार', 'देर', 'रात', 'शुरू', 'हुई'], ['करीब', '७५००', 'विशिष्ट', 'दर्शकों', 'की', 'मौजूदगी', 'में', 'विश्व', 'की', 'सर्वश्रेष्ठ', 'सुंदरी', 'के', 'चयन', 'की', 'कवायद', 'शुरू', 'हुई'], ['हर', 'चरण', 'के', 'बाद', 'लोगों', 'की', 'सांसे', 'थमने', 'लगतीं'], ['टीवी', 'पर', 'लुत्फ', 'उठा', 'रहे', 'दर्शक', 'अपने', 'देश', 'व', 'क्षेत्र', 'की', 'सुंदरी', 'की', 'प्रतियोगिता', 'में', 'स्थिति', 'के', 'बारे', 'में', 'व्यग्र', 'रहे'], ['फाइनल', 'में', 'पहुंचने', 'वाली', 'पांच', 'प्रतिभागियों', 'में', 'मिस', 'पेराग्वे', 'यानिना', 'गोंजालेज', 'और', 'मिस', 'त्रिनिदाद', 'व', 'टोबैगो', 'डेनियल', 'जोंस', 'भी', 'शामिल', 'थीं']]
>>> model = gensim.models.Word2Vec(sentences, size =10,  min_count=1)
>>> pred = []
>>> for word in sentence:
...         pred.append(model.wv[word].tolist())
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/home/djokester/anaconda3/lib/python3.5/site-packages/gensim/models/keyedvectors.py", line 574, in __getitem__
    return self.word_vec(words)
  File "/home/djokester/anaconda3/lib/python3.5/site-packages/gensim/models/keyedvectors.py", line 273, in word_vec
    raise KeyError("word '%s' not in vocabulary" % word)
KeyError: "word 'नीरजः' not in vocabulary"
</code>```

As you can see, I check for the word "नीरजः" inside the list of tokenized sentences. It is present in the list that I feed into the Word2Vec trainer and yet after training it is not in the vocabulary.

答:
It should never 'miss' words that were included in the tokenized corpus, and had at least min_count occurrences. So if you get a KeyError, you can be confident that the associated word-token was never supplied during training.

In your example code to reproduce, take a close look at:

```<code>sentence = "Jack and Jill went up the Hill"
sentence = [word_tokenize(i) for i in sentence]
</code>```

i in sentence will be each character of the string. It's unlikely your unshown word_tokenize() function does anything useful with the individual characters ['J', 'a', 'c', 'k', ' ', ...] - probably just leaving them as a list of letters. Then +-appending that to your other sentences makes sentences 30 items longer, rather than the single extra tokenized example you expect.

I suspect your real issue is different but related: something wrong with tokenization and composition. So check every step individually for the expected results and nested-types. (Using unique variables per step, like sentences_tokenized or sentence_tokenized instead of clobber-reusing variables like sentences and sentence, can help debug.)

Update as you suggested as edit: The issue with your latest code is that the line where you +-append is still wrong; it's appending each word in sentence as if it were its own new sentence. Looking at the results of each step – in the variable contents and lengths – should help make this clear. Also I again recommend not reusing variables for multiple steps while debugging. The line "नीरजः" in sentences #proof that the word is present inside sentences is actually proving sentences is wrong; that single word should not be an item in sentences, but in its single last list-of-tokens, sentences[-1].

Body:
I have a corpus built out of Wikimedia Dump files stored at sentences.txt
I have a sentence say 'नीरजः हाँ माता जी! स्कूल ख़त्म होते सीधा घर आऊँगा'

Now when I try to extract the word vectors there is always one or two words which have been missed out while training (despite being included in the list to be trained upon) and I get the KeyError.
Is there any way to improve the training so that it doesn't miss out words that frequently?

Here is a proof that it does happen. tok.wordtokenize is a word tokenizer. sent.drawlist() as well as sents.drawlist() returns a list of sentences from the corpus stored inside sentences.txt.

>>> sentence = 'नीरजः हाँ माता जी! स्कूल ख़त्म होते सीधा घर आऊँगा'
>>> sentence = tok.wordtokenize(sentence) #tok.wordtokenize() is simply a word tokenizer.
>>> sentences = sent.drawlist()
>>> sentences = [tok.wordtokenize(i) for i in sentences]
>>> sentences2 = sents.drawlist()
>>> sentences2 = [tok.wordtokenize(i) for i in sentences2]
>>> sentences = sentences2 + sentences + sentence
>>> "नीरजः" in sentences #proof that the word is present inside sentences
True
>>> sentences[0:10] #list of tokenized sentences.
[['विश्व', 'भर', 'में', 'करोड़ों', 'टीवी', 'दर्शकों', 'की', 'उत्सुकता', 'भरी', 'निगाह', 'के', 'बीच', 'मिस', 'ऑस्ट्रेलिया', 'जेनिफर', 'हॉकिंस', 'को', 'मिस', 'यूनिवर्स-२००४', 'का', 'ताज', 'पहनाया', 'गया'], ['करीब', 'दो', 'घंटे', 'चले', 'कार्यक्रम', 'में', 'विभिन्न', 'देशों', 'की', '८०', 'सुंदरियों', 'के', 'बीच', '२०', 'वर्षीय', 'हॉकिंस', 'को', 'सर्वश्रेष्ठ', 'आंका', 'गया'], ['मिस', 'अमेरिका', 'शैंडी', 'फिनेजी', 'को', 'प्रथम', 'उप', 'विजेता', 'और', 'मिस', 'प्यूरेटो', 'रिको', 'अल्बा', 'रेइज', 'द्वितीय', 'उप', 'विजेता', 'चुनी', 'गई'], ['भारत', 'की', 'तनुश्री', 'दत्ता', 'अंतिम', '१०', 'प्रतिभागियों', 'में', 'ही', 'स्थान', 'बना', 'पाई'], ['हॉकिंस', 'ने', 'कहा', 'कि', 'जीत', 'के', 'बारे', 'में', 'उसने', 'सपने', 'में', 'भी', 'नहीं', 'सोचा', 'था'], ['सौंदर्य', 'की', 'यह', 'शीर्ष', 'प्रतियोगिता', 'क्विटो', 'के', 'कन्वेंशन', 'सेंटर', 'में', 'मंगलवार', 'देर', 'रात', 'शुरू', 'हुई'], ['करीब', '७५००', 'विशिष्ट', 'दर्शकों', 'की', 'मौजूदगी', 'में', 'विश्व', 'की', 'सर्वश्रेष्ठ', 'सुंदरी', 'के', 'चयन', 'की', 'कवायद', 'शुरू', 'हुई'], ['हर', 'चरण', 'के', 'बाद', 'लोगों', 'की', 'सांसे', 'थमने', 'लगतीं'], ['टीवी', 'पर', 'लुत्फ', 'उठा', 'रहे', 'दर्शक', 'अपने', 'देश', 'व', 'क्षेत्र', 'की', 'सुंदरी', 'की', 'प्रतियोगिता', 'में', 'स्थिति', 'के', 'बारे', 'में', 'व्यग्र', 'रहे'], ['फाइनल', 'में', 'पहुंचने', 'वाली', 'पांच', 'प्रतिभागियों', 'में', 'मिस', 'पेराग्वे', 'यानिना', 'गोंजालेज', 'और', 'मिस', 'त्रिनिदाद', 'व', 'टोबैगो', 'डेनियल', 'जोंस', 'भी', 'शामिल', 'थीं']]
>>> model = gensim.models.Word2Vec(sentences, size =10,  min_count=1)
>>> pred = []
>>> for word in sentence:
...         pred.append(model.wv[word].tolist())
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/home/djokester/anaconda3/lib/python3.5/site-packages/gensim/models/keyedvectors.py", line 574, in __getitem__
    return self.word_vec(words)
  File "/home/djokester/anaconda3/lib/python3.5/site-packages/gensim/models/keyedvectors.py", line 273, in word_vec
    raise KeyError("word '%s' not in vocabulary" % word)
KeyError: "word 'नीरजः' not in vocabulary"

As you can see, I check for the word "नीरजः" inside the list of tokenized sentences. It is present in the list that I feed into the Word2Vec trainer and yet after training it is not in the vocabulary.

Body:
It should never 'miss' words that were included in the tokenized corpus, and had at least min_count occurrences. So if you get a KeyError, you can be confident that the associated word-token was never supplied during training.

In your example code to reproduce, take a close look at:

sentence = "Jack and Jill went up the Hill"
sentence = [word_tokenize(i) for i in sentence]

i in sentence will be each character of the string. It's unlikely your unshown word_tokenize() function does anything useful with the individual characters ['J', 'a', 'c', 'k', ' ', ...] - probably just leaving them as a list of letters. Then +-appending that to your other sentences makes sentences 30 items longer, rather than the single extra tokenized example you expect.

I suspect your real issue is different but related: something wrong with tokenization and composition. So check every step individually for the expected results and nested-types. (Using unique variables per step, like sentences_tokenized or sentence_tokenized instead of clobber-reusing variables like sentences and sentence, can help debug.)

Update as you suggested as edit: The issue with your latest code is that the line where you +-append is still wrong; it's appending each word in sentence as if it were its own new sentence. Looking at the results of each step – in the variable contents and lengths – should help make this clear. Also I again recommend not reusing variables for multiple steps while debugging. The line "नीरजः" in sentences #proof that the word is present inside sentences is actually proving sentences is wrong; that single word should not be an item in sentences, but in its single last list-of-tokens, sentences[-1].


问:
jquery-chosen multiple attribute allowing tag order same as list order
In my html i'm using chosen jquery(1.6.2) from here.
I'm facing problem while multiple selection, order of the selected tags are sorting in same order as they are in drop-down list.
I want the selected order rather than order by list.

```<code>    <select class="chosen-select" chosen multiple>
    </select>
</code>```

but still order sorting is getting done. I want to handle the order please help.

答:
```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Multiple Selected Option Value</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
var arr=[];
var selected;
$(document).ready(function() {

   $("select.country").click(function(){
   var latestSelected;
    if (selected) {
        var currentOptionsValue = $(this).val();
        latestSelected = currentOptionsValue.filter(function(element) {
        return selected.indexOf(element) < 0;
  });
}
if(!selected){
arr.push($(this).val());
}
else{
 arr.push(latestSelected);
}
selected = $(this).val();
//console.log( "latest selected option : " + latestSelected);
    });

});
function getValues(){

        alert(arr.join(','));
    }
</script>
</head>
<body>
    <form>
        <label>Country:</label>
        <select class="country" multiple="multiple" size="5">
            <option>United States</option>
            <option>India</option>
            <option>United Kingdom</option>
            <option>Brazil</option>
            <option>Germany</option>
        </select>
        <button type="button" onclick="getValues();">Get Values</button>
    </form>
</body>
</html>
</code>```

Body:
In my html i'm using chosen jquery(1.6.2) from here.
I'm facing problem while multiple selection, order of the selected tags are sorting in same order as they are in drop-down list.
I want the selected order rather than order by list.

    <select class="chosen-select" chosen multiple>
    </select>

but still order sorting is getting done. I want to handle the order please help.


问:
What's the recommended approach to store passwords/users used in deployments for Bamboo?
When creating a release of a build, the release contains all of the variables as they were set up in the system when the build was made, this includes global variables like deployment credentials (users and passwords).

A deployment for a release of a build made a week ago that's now being promoted to production is failing because the deployment credentials have been changed since last week. When rolling back the deployment this also fails for the same reason, the credentials are not up-to-date.

Is there a way to update the variables of a build or have variables that should be used only for deployment projects?

答: you can define variables at Deployment project level, not plan</p>


问:
Compare two arrays contains integers, return the difference
I want to compare 2 arrays with integers.

what I have:

```<code>function findDeletedNumber(array $arr, array $mixedArr): int {
  $diff = array_diff($arr, $mixedArr);
  if ($diff != NULL) { return($diff); }
  return 0;
}
</code>```

But the problem is that I need to return the difference as a string. Not an array. the difference is always gonna be only one value

答:
Because the returned value is always gonna be one value. You can use array_sum to sum the integers. Just substract the awnsers of summed array, and that's the difference.

```<code>findDeletedNumber(array $arr, array $mixedArr): int
{
  return array_sum($arr) - array_sum($mixedArr);
}
</code>```

Body:
I want to compare 2 arrays with integers.

what I have:

function findDeletedNumber(array $arr, array $mixedArr): int {
  $diff = array_diff($arr, $mixedArr);
  if ($diff != NULL) { return($diff); }
  return 0;
}

But the problem is that I need to return the difference as a string. Not an array. the difference is always gonna be only one value

Body:
Because the returned value is always gonna be one value. You can use array_sum to sum the integers. Just substract the awnsers of summed array, and that's the difference.

findDeletedNumber(array $arr, array $mixedArr): int
{
  return array_sum($arr) - array_sum($mixedArr);
}


问:
Rails: How to plan models and datebase?
Im pretty new to rails and I tried finding for an answer using rails with postgresql but maybe I am thinking it wrong or searching at the wrong places. So here goes

Lets say I want to do an app that tracks a user's lifestyle habits ( spending, savings, etc )

Do I do the following:

User model - email, password Lifestyle model - food, amount spent on
food, transport, amount spent on  transport, bills, amount spent on
bills, etc....

User model - email, password Lifestyle_food model - amount spent,
location, etc Lifestyle_transport model - amount spent, type of
transport, etc etc models

For the above cases, I would like to allow the user to input their daily spendings, which I think will result in thousands of entries a year per user. With regards to the model planning, I am not sure which route should I be taking that will cause the minimal problems in the future.

Situation A: will result in a table with A LOT of columns and I am not sure if that is the optimal way for searches if a user wants to pin point his or her spending habits ( through several searches of views )

Situation B: will result in A LOT of models but each has fewer columns even if they were to be very detailed.

How should I define my models and database in rails?

There doesn't seem to be much material on the internet on how the planning should be done and the considerations ( Maybe a professional is required ), but for a novice like me, how should I proceed?

答:
Even though I agree this question is completely unrelated to RoR, I'm gonna answer with my opinion - because that's what this is an opinion

User has_many:

Months

month_index:integer:index YYYYMM (201706)

daily_hash:jsonb

{ 01: { food_expenditures: [ { amount: 24453, name: 'big mac', random_keys: with_whatever }, { rinse and repeat } ], travel_expenditures : [ same ], ... }, 02: { ... } }

This would allow you to have 12 records per year * users, indexed on a integer column. So allowing user.month.find_by(month_index: 201704).daily_hash['02']['food_expenditures']

Does this present some problems? Yes, but it solves many others.

Title: Rails: How to plan models and datebase?


问:
Error in dev.off() : cannot shut down device 1 (the null device)
I am new to R programming and I got hit with this error when I tried to run the code. This simply creates a pie chart with some data. Can anyone explain to me why I am getting this error and what it means?

1) I am running windows
2) Version 3.4.0
3) I am using RGui desktop
4) R version 3.4.0

```<code># Create data for the graph.
x <- c(21, 62, 10, 53)
labels <- c("London", "New York", "Singapore", "Mumbai")

# Give the chart file a name.
png(file = "city_title_colours.jpg")

# Plot the chart with title and rainbow color pallet.
pie(x, labels, main = "City pie chart", col = rainbow(length(x)))

# Save the file.
dev.off()
</code>```

答: Turns out that the only problem with this was with where the file was trying to save to. I altered the code to save to a different directory and it worked fine</p>

Body:
I am new to R programming and I got hit with this error when I tried to run the code. This simply creates a pie chart with some data. Can anyone explain to me why I am getting this error and what it means?

1) I am running windows
2) Version 3.4.0
3) I am using RGui desktop
4) R version 3.4.0

# Create data for the graph.
x <- c(21, 62, 10, 53)
labels <- c("London", "New York", "Singapore", "Mumbai")

# Give the chart file a name.
png(file = "city_title_colours.jpg")

# Plot the chart with title and rainbow color pallet.
pie(x, labels, main = "City pie chart", col = rainbow(length(x)))

# Save the file.
dev.off()


问:
MDX - How to aggregate by date considering start and end date in a dimension
I need to calculate a measure grouping by date in a range of dates considering a start and end dates in a dimension. The objective is to count the number of students of a specific school that are actives on each day in a period.

The following SQL Code works on Data Warehouse (source of cube).

SELECT
     t.[date]
    ,count(distinct a.SKStudent) as Students
FROM DM.DimTime t
    CROSS JOIN DM.FactStudents a
    INNER JOIN DM.DimStudents m ON a.SKStudent = m.SKStudent
    INNER JOIN DM.DimSchool e ON a.SKSchool = e.SKSchool
WHERE t.[date] between '20170502' and '20170512'
    and e.SchoolCode = 123456
    and t.[date] between m.[StartDate] and m.[EndtDate]
GROUP BY t.[data]
```

<p>The result set is like the following:</p>

```+--------------+----------+
| date         | Students |
+--------------+----------+
| 2017-05-02   |    567   |
| 2017-05-03   |    567   |
| 2017-05-04   |    568   |
| 2017-05-05   |    570   |
| 2017-05-06   |    570   |
| 2017-05-07   |    570   |
| 2017-05-08   |    573   |
| 2017-05-09   |    573   |
| 2017-05-10   |    571   |
| 2017-05-11   |    568   |
| 2017-05-12   |    568   |
+--------------+----------+
```

<p>I try made the MDX code. The following is what I tried. I don't know how filter the day using the logic in CASE statement (between '???' marks):</p>

<pre class="lang-sql prettyprint-override"><code>WITH SET DateRange AS
    [Dim Time].[Date].&[20170502]:[Dim Time].[Date].&[20170512]
MEMBER StudentsByDay AS
    AGGREGATE(DateRange,
        ???CASE WHEN DateRange.CURRENTMEMBER
                    BETWEEN [Dim Students].[Start Date]
                        AND [Dim Students].[End Date]
                THEN [Measures].[Students Count]
            ELSE NULL END???)
SELECT
    NON EMPTY { [StudentsByDay] } ON COLUMNS,
    NON EMPTY { [DateRange] } ON ROWS
FROM [Education]
WHERE ( [Dim School].[School Code].&[123456] )
</code>```

答:
MDX isn't that flexible like SQL. I'd recommend to put the following condition into your FactStudents table:

```<code>t.[date] between m.[StartDate] and m.[EndtDate]
</code>```

and use like a separate measure or replace the existing one.

You need the following things:

a fact table with DateID, StudentID fields (see the code below);

a measure group related with Student and Date dims;

a measure with DistinctCount aggregation on StudentID field.

The fact code:

```<code>SELECT
     t.[date] as DateID
    ,a.[SKStudent] as StudentID
FROM DM.DimTime t
    CROSS JOIN DM.FactStudents a
    INNER JOIN DM.DimStudents m ON a.SKStudent = m.SKStudent
    INNER JOIN DM.DimSchool e ON a.SKSchool = e.SKSchool
WHERE e.SchoolCode = 123456
    and t.[date] between m.[StartDate] and m.[EndtDate]
</code>```

Body:
I need to calculate a measure grouping by date in a range of dates considering a start and end dates in a dimension. The objective is to count the number of students of a specific school that are actives on each day in a period.

The following SQL Code works on Data Warehouse (source of cube).

SELECT
     t.[date]
    ,count(distinct a.SKStudent) as Students
FROM DM.DimTime t
    CROSS JOIN DM.FactStudents a
    INNER JOIN DM.DimStudents m ON a.SKStudent = m.SKStudent
    INNER JOIN DM.DimSchool e ON a.SKSchool = e.SKSchool
WHERE t.[date] between '20170502' and '20170512'
    and e.SchoolCode = 123456
    and t.[date] between m.[StartDate] and m.[EndtDate]
GROUP BY t.[data]

The result set is like the following:

+--------------+----------+
| date         | Students |
+--------------+----------+
| 2017-05-02   |    567   |
| 2017-05-03   |    567   |
| 2017-05-04   |    568   |
| 2017-05-05   |    570   |
| 2017-05-06   |    570   |
| 2017-05-07   |    570   |
| 2017-05-08   |    573   |
| 2017-05-09   |    573   |
| 2017-05-10   |    571   |
| 2017-05-11   |    568   |
| 2017-05-12   |    568   |
+--------------+----------+

I try made the MDX code. The following is what I tried. I don't know how filter the day using the logic in CASE statement (between '???' marks):

WITH SET DateRange AS
    [Dim Time].[Date].&[20170502]:[Dim Time].[Date].&[20170512]
MEMBER StudentsByDay AS
    AGGREGATE(DateRange,
        ???CASE WHEN DateRange.CURRENTMEMBER
                    BETWEEN [Dim Students].[Start Date]
                        AND [Dim Students].[End Date]
                THEN [Measures].[Students Count]
            ELSE NULL END???)
SELECT
    NON EMPTY { [StudentsByDay] } ON COLUMNS,
    NON EMPTY { [DateRange] } ON ROWS
FROM [Education]
WHERE ( [Dim School].[School Code].&[123456] )

Body:
MDX isn't that flexible like SQL. I'd recommend to put the following condition into your FactStudents table:

t.[date] between m.[StartDate] and m.[EndtDate]

and use like a separate measure or replace the existing one.

You need the following things:

a fact table with DateID, StudentID fields (see the code below);

a measure group related with Student and Date dims;

a measure with DistinctCount aggregation on StudentID field.

The fact code:

SELECT
     t.[date] as DateID
    ,a.[SKStudent] as StudentID
FROM DM.DimTime t
    CROSS JOIN DM.FactStudents a
    INNER JOIN DM.DimStudents m ON a.SKStudent = m.SKStudent
    INNER JOIN DM.DimSchool e ON a.SKSchool = e.SKSchool
WHERE e.SchoolCode = 123456
    and t.[date] between m.[StartDate] and m.[EndtDate]


问:
Why does my code not work (diary code)?
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.</p>

```<code>import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)
</code>```

答:
it will work</p>

```<code>public static void calculator() {
    Scanner a = new Scanner(System.in);
    System.out.println("Give me the 2 numbers first: ");
    int x = a.nextInt();
    int y = a.nextInt();

    System.out.println("Now give me the operation (+,-,*,/): ");
    String choice = a.next();
    if (choice.equals("+")) {
        float result = x + y;
        System.out.println("result: " + result);
    }
    if (choice.equals("-")) {
        float result = x - y;
        System.out.println("result: " + result);
    }
    if (choice.equals("*")) {
        float result = x * y;
        System.out.println("result: " + result);
    }
    if (choice.equals("/")) {
        float result = x / y;
        System.out.println("result: " + result);
    }
    a.close();
}
</code>```

Title: Why does my code not work (diary code)?

Body:
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.

import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)

Body:
it will work

public static void calculator() {
    Scanner a = new Scanner(System.in);
    System.out.println("Give me the 2 numbers first: ");
    int x = a.nextInt();
    int y = a.nextInt();

    System.out.println("Now give me the operation (+,-,*,/): ");
    String choice = a.next();
    if (choice.equals("+")) {
        float result = x + y;
        System.out.println("result: " + result);
    }
    if (choice.equals("-")) {
        float result = x - y;
        System.out.println("result: " + result);
    }
    if (choice.equals("*")) {
        float result = x * y;
        System.out.println("result: " + result);
    }
    if (choice.equals("/")) {
        float result = x / y;
        System.out.println("result: " + result);
    }
    a.close();
}


问:
JQueryMobile HTC Android pinch zoom
I have one website with JQueryMobile which works fine for iPhone but with Android HTC looks really weird when zooming. Same thing happens in any of the demo pages of JQueryMobile site, almost half of the screen becomes blank breaking completely the site.

Is there any way of solving this or at least disable pinch zooming for Android HTC Browsers?

答:
Two ways to solve it, either disable jQueryMobile or recode the desired functionality. The goal of jQueryMobile is to provide the same functionality for a variety of mobile browsers, however that statement doesn't include performance at all - and most likely never will since the difference between different mobile devices' perfomance is geometrical; that's why you really can't have a write once, run everywhere type of library for mobile. Unless you degrade your high-end experience to feature phone level, that is. I'm willing to go as far as calling this mentality a fundamental flaw in jQueryMobile.

Also, you should know that Android is generally worse in supporting fancy animations and such than iPhoneOS. Yes, it can do the same things but not as smoothly and there's lots of weird clipping/page position jumping errors and whatnot in the animations.

ContentLicense: CC BY-SA 2.5

Title: JQueryMobile HTC Android pinch zoom


问:
Update and Change WordPress URLs in database with REGEXP
I want to change several hundred URLs to the graphics inside the posts. URLs are links to images that are on an inactive imagehost. I had backup and I loading them into a new imagehost, but I have a problem with replacement, because old links have variable, random length.

For example:
hostname.org/image/ciiidl/file_name.jpeg

Where "ciiidl" is generate random

I wrote a command in SQL, but unfortunately did not replace URLs:
UPDATE wp_posts SET post_content = REPLACE (post_content, 'https://old_hostname.org/image/[^a-zA-Z0-9]/','https://new_hostname.com/Img/')

I need to use REGEXP, but I do not know how to combine with REPLACE.

答:
I think you just need:</p>

```<code>UPDATE wp_posts
    SET post_content = concat(substring_index(post_content, '/image', 1),
                              '/Img/',
                              substring_index(post_content, '/', -1)
                             )
    WHERE post_content LIKE '%/image/%';
</code>```

Body:
I think you just need:

UPDATE wp_posts
    SET post_content = concat(substring_index(post_content, '/image', 1),
                              '/Img/',
                              substring_index(post_content, '/', -1)
                             )
    WHERE post_content LIKE '%/image/%';


问:
How to add csv MimeType to spring content-negotiation?
I'm creating a webservice method that can serve xml, json and csv output:

```<code>@GetMapping(produces = {APPLICATION_XML_VALUE, APPLICATION_JSON_VALUE, "text/csv"})
public Rsp get() {
}
</code>```

Problem: I somehow need to add the text/csv content type to my configureContentNegotiation(). But how? Because a String is not accepted, and a MediaType.TEXT_CSV does not exist (even though RFC7111 defines it as a valid mimetype.

```<code>@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer
                .favorParameter(true)
                .mediaType("json", MediaType.APPLICATION_JSON)
                .mediaType("xml", MediaType.APPLICATION_XML)
                .mediaType("csv", "text/csv"); //this is invalid
    }
}
</code>```

答:
```<code>.mediaType("csv", new MediaType("text", "csv"));
</code>```

or even configure as follows in application.properties:

```<code>spring.mvc.media-types.json=application/json
spring.mvc.media-types.xml=application/xml
spring.mvc.media-types.csv=text/csv
</code>```

Body:
I'm creating a webservice method that can serve xml, json and csv output:

@GetMapping(produces = {APPLICATION_XML_VALUE, APPLICATION_JSON_VALUE, "text/csv"})
public Rsp get() {
}

Problem: I somehow need to add the text/csv content type to my configureContentNegotiation(). But how? Because a String is not accepted, and a MediaType.TEXT_CSV does not exist (even though RFC7111 defines it as a valid mimetype.

@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer
                .favorParameter(true)
                .mediaType("json", MediaType.APPLICATION_JSON)
                .mediaType("xml", MediaType.APPLICATION_XML)
                .mediaType("csv", "text/csv"); //this is invalid
    }
}

Body:
.mediaType("csv", new MediaType("text", "csv"));

or even configure as follows in application.properties:

spring.mvc.media-types.json=application/json
spring.mvc.media-types.xml=application/xml
spring.mvc.media-types.csv=text/csv


问:
Trow error when trying to make new vue-cli webpack project
I keep getting a throw error with permission denied when trying to make a new vue-cli webpack build. It worked last night, but now all of a sudden I get these errors. Anyone know how to fix this?</p>

```<code>    /usr/local/lib/node_modules/vue-cli/node_modules/rimraf/rimraf.js:312
        throw er
        ^

Error: EACCES: permission denied, unlink
</code>```

答:
It looks like you're running this command on Linux; try using chown to give yourself permission to access all of those directories / files.

See also: GitHub - Bower - EACCES: permission denied

Body:
I keep getting a throw error with permission denied when trying to make a new vue-cli webpack build. It worked last night, but now all of a sudden I get these errors. Anyone know how to fix this?

    /usr/local/lib/node_modules/vue-cli/node_modules/rimraf/rimraf.js:312
        throw er
        ^

Error: EACCES: permission denied, unlink


问:
why there is no add method in Iterator interface
In Iterator Sun added the remove method to remove the last accessed element of the collection. Why there is no add method to add a new element to the collection? What kind of side-effects it may have to the collection or iterator?

答: Iterator have a pointer to the next element only. where as ListIterator have pointers to the previous element also(remember, it can traverse backwards).</p>


问:
Tool to automatically expand YAML merges?
I'm looking for a tool or process which can easily take a YAML file which contains anchors, aliases and merge keys and expand the aliases and merges out into a flat YAML file. There are still many commonly used YAML parses which don't fully support merging.

I'd like to be able to take advantage of merging to keep things DRY, but there are instances where this needs to then be built into a more verbose "flat" YAML file so that it can be used by other tooling which relies on incomplete YAML parsers.

Example Source YAML:

```<code>default: &DEFAULT
  URL: website.com
  mode: production
  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600

development:
  <<: *DEFAULT
  URL: website.local
  mode: dev

test:
  <<: *DEFAULT
  URL: test.website.qa
  mode: test
</code>```

Desired output YAML:

```<code>default:
  URL: website.com
  mode: production
  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600

development:
  URL: website.local
  mode: dev
  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600

test:
  URL: test.website.qa
  mode: test
  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600
</code>```

答:
If you have python installed on your system, you can do pip install ruamel.yaml.cmd¹ and then:

```<code>yaml merge-expand input.yaml output.yaml
</code>```

(replace output.yaml with - to write to stdout). This implements the merge expanding with preservation of key order and comments.

The above is actually a few lines of code that utilizes ruamel.yaml¹
so if you have Python (2.7 or 3.4+) and install that using pip install ruamel.yaml and save the following as expand.py:

```<code>import sys
from ruamel.yaml import YAML

yaml = YAML(typ='safe')
yaml.default_flow_style=False
with open(sys.argv[1]) as fp:
    data = yaml.load(fp)
with open(sys.argv[2], 'w') as fp:
    yaml.dump(data, fp)
</code>```

you can already do:

```<code>python expand.py input.yaml output.yaml
</code>```

That will get you YAML that is semantically equivalent to what you requested (in output.yaml the keys of the mappings are sorted, in this programs output they are not).

The above assumes you don't have any tags in your YAML, nor care about preserving any comments. Most of those, and the key ordering, can be preserved by using a patched version of the standard YAML() instance. Patching is necessary because the standard YAML() instance preserves the merges on round-trip as well, which is exactly what you don't want:

```<code>import sys
from ruamel.yaml import YAML, SafeConstructor

yaml = YAML()

yaml.Constructor.flatten_mapping = SafeConstructor.flatten_mapping
yaml.default_flow_style=False
yaml.allow_duplicate_keys = True
# comment out next line if you want "normal" anchors/aliases in your output
yaml.representer.ignore_aliases = lambda x: True

with open(sys.argv[1]) as fp:
    data = yaml.load(fp)
with open(sys.argv[2], 'w') as fp:
    yaml.dump(data, fp)
</code>```

with this input:

```<code>default: &DEFAULT
  URL: website.com
  mode: production
  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600  # an hour?

development:
  <<: *DEFAULT
  URL: website.local     # local web
  mode: dev

test:
  <<: *DEFAULT
  URL: test.website.qa
  mode: test
</code>```

that will give this output (note that comments on the merged in keys get duplicated):

```<code>default:
  URL: website.com
  mode: production
  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600  # an hour?

development:
  URL: website.local     # local web
  mode: dev

  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600  # an hour?

test:
  URL: test.website.qa
  mode: test
  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600  # an hour?
</code>```

The above is what the yaml merge-expand command, mentioned at the start of this answer, does.

¹ Disclaimer: I am the author of that package.

Body:
I'm looking for a tool or process which can easily take a YAML file which contains anchors, aliases and merge keys and expand the aliases and merges out into a flat YAML file. There are still many commonly used YAML parses which don't fully support merging.

I'd like to be able to take advantage of merging to keep things DRY, but there are instances where this needs to then be built into a more verbose "flat" YAML file so that it can be used by other tooling which relies on incomplete YAML parsers.

Example Source YAML:

default: &DEFAULT
  URL: website.com
  mode: production
  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600

development:
  <<: *DEFAULT
  URL: website.local
  mode: dev

test:
  <<: *DEFAULT
  URL: test.website.qa
  mode: test

Desired output YAML:

default:
  URL: website.com
  mode: production
  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600

development:
  URL: website.local
  mode: dev
  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600

test:
  URL: test.website.qa
  mode: test
  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600

Body:
If you have python installed on your system, you can do pip install ruamel.yaml.cmd¹ and then:

yaml merge-expand input.yaml output.yaml

(replace output.yaml with - to write to stdout). This implements the merge expanding with preservation of key order and comments.

The above is actually a few lines of code that utilizes ruamel.yaml¹
so if you have Python (2.7 or 3.4+) and install that using pip install ruamel.yaml and save the following as expand.py:

import sys
from ruamel.yaml import YAML

yaml = YAML(typ='safe')
yaml.default_flow_style=False
with open(sys.argv[1]) as fp:
    data = yaml.load(fp)
with open(sys.argv[2], 'w') as fp:
    yaml.dump(data, fp)

you can already do:

python expand.py input.yaml output.yaml

That will get you YAML that is semantically equivalent to what you requested (in output.yaml the keys of the mappings are sorted, in this programs output they are not).

The above assumes you don't have any tags in your YAML, nor care about preserving any comments. Most of those, and the key ordering, can be preserved by using a patched version of the standard YAML() instance. Patching is necessary because the standard YAML() instance preserves the merges on round-trip as well, which is exactly what you don't want:

import sys
from ruamel.yaml import YAML, SafeConstructor

yaml = YAML()

yaml.Constructor.flatten_mapping = SafeConstructor.flatten_mapping
yaml.default_flow_style=False
yaml.allow_duplicate_keys = True
# comment out next line if you want "normal" anchors/aliases in your output
yaml.representer.ignore_aliases = lambda x: True

with open(sys.argv[1]) as fp:
    data = yaml.load(fp)
with open(sys.argv[2], 'w') as fp:
    yaml.dump(data, fp)

with this input:

default: &DEFAULT
  URL: website.com
  mode: production
  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600  # an hour?

development:
  <<: *DEFAULT
  URL: website.local     # local web
  mode: dev

test:
  <<: *DEFAULT
  URL: test.website.qa
  mode: test

that will give this output (note that comments on the merged in keys get duplicated):

default:
  URL: website.com
  mode: production
  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600  # an hour?

development:
  URL: website.local     # local web
  mode: dev

  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600  # an hour?

test:
  URL: test.website.qa
  mode: test
  site_name: Website
  some_setting: h2i8yiuhef
  some_other_setting: 3600  # an hour?

The above is what the yaml merge-expand command, mentioned at the start of this answer, does.

¹ Disclaimer: I am the author of that package.


问:
Boost asio non-blocking IO without callbacks
Is it possible to use Boost's asio to do non-blocking IO without using async callbacks? I.e. equivalent to the O_NONBLOCK socket option.

I basically want this function:

```<code>template<typename SyncWriteStream,
         typename ConstBufferSequence>
std::size_t write_nonblock(
    SyncWriteStream & s,
    const ConstBufferSequence & buffers);
</code>```

This function will write as many bytes as it can and return immediately. It may write 0 bytes.

Is it possible?

答:
The way with s.non_blocking(true) would not work.
If you check send implementation, it uses socket_ops::sync_send, which does poll_write if send failed.

So it is still blocking on top level.

Body:
Is it possible to use Boost's asio to do non-blocking IO without using async callbacks? I.e. equivalent to the O_NONBLOCK socket option.

I basically want this function:

template<typename SyncWriteStream,
         typename ConstBufferSequence>
std::size_t write_nonblock(
    SyncWriteStream & s,
    const ConstBufferSequence & buffers);

This function will write as many bytes as it can and return immediately. It may write 0 bytes.

Is it possible?


问:
Push an element at the end of an array
I have an array called result which I generate like this

```<code> while something
           $result[] = $row;
           array_push($result,$row['fld_ConsumptionValue'] * $energy_type_unit_price) // this won't do
    endwhile
</code>```

$result array is filled with db records. What I wanna do is to push another value I calculated like above. output is like this:

```<code>    result -> Array[6]
    [0] -> Array[34]
    [1] -> Calculated Value For 1st Record
    [2] -> Array[34]
    [3] -> Calculated Value For 2nd Record
...
...
...
</code>```

What I'm trying is to get this output

```<code> result -> Array[6]
    [0] -> Array[35]
    [1] -> Array[35]
...
...
</code>```

What am I doing wrong?

答:
The simplest way to do is $array[] = $var;

In your case $result[] = $row['fld_ConsumptionValue'] * $energy_type_unit_price;

Refer http://php.net/manual/en/function.array-push.php for details

Hope it helps

Title: Push an element at the end of an array

Body:
I have an array called result which I generate like this

 while something
           $result[] = $row;
           array_push($result,$row['fld_ConsumptionValue'] * $energy_type_unit_price) // this won't do
    endwhile

$result array is filled with db records. What I wanna do is to push another value I calculated like above. output is like this:

    result -> Array[6]
    [0] -> Array[34]
    [1] -> Calculated Value For 1st Record
    [2] -> Array[34]
    [3] -> Calculated Value For 2nd Record
...
...
...

What I'm trying is to get this output

 result -> Array[6]
    [0] -> Array[35]
    [1] -> Array[35]
...
...

What am I doing wrong?


问:
Google Chrome shows gray circle cursor
Google Chrome shows a gray circle cursor when dev tools is active. Why is this happening and how do I make this stop?</p>

答: At july 2017 this option calls Add device type:

Title: Google Chrome shows gray circle cursor


问:
Lib for Android and MIDP?
Is it possible to share a Java library (in the form of a jar file) between Android and MIDP projects? If that is the case, which Java version should I compile with? The library does not use any Android or MIDP specific stuff.</p>

答: No it's impossible, since Android and J2ME use different VM. Android's one called Dalvik VM and J2ME's KVM - so they're generating different bytecodes.</p>

Title: Lib for Android and MIDP?


问:
Excel - Return row header after searching for column header and a specific value in that column
I would like an Excel formula that returns the column header (value in column A) based on 2 conditions:

Header Column Name (Country 1 in the example below)

Specific Value in that Column (Yes in the example below)
So in this case, If my Search Cell (A12) has the value "Country 1", I will get the result "Domain 5" in the Result Cell (B12).

As well, I should be able to add columns (yellow headers) without breaking the formula.

Full result table below:

Country 1: Domain 1

Country 2: Domain 3

Country 3: Domain 2

Country 4: Domain 6

Country 5: Domain 4

Country 6: Domain 5

Country 7: Domain 8

Country 8: Domain 7

I have created a google spreadsheet below with the example on the tab "Example".
What I am trying to achieve is visible on the tab "Check".
https://docs.google.com/spreadsheets/d/1FjHkCs8MoFy6w-mhcyufD1VEBX-r3Rdc98GoNcsKeC0/edit?usp=sharing

I would really appreciate if someone could give me a hand.

Simplified example

答:
In cell B7 use this formula:</p>

```<code>=INDEX($A$2:$A$4,MATCH("Yes",INDIRECT(ADDRESS(2,MATCH($A$8,$A$1:$D$1))&":"&ADDRESS(4,MATCH($A$8,$A$1:$D$1)))))
</code>```

Body:
In cell B7 use this formula:

=INDEX($A$2:$A$4,MATCH("Yes",INDIRECT(ADDRESS(2,MATCH($A$8,$A$1:$D$1))&":"&ADDRESS(4,MATCH($A$8,$A$1:$D$1)))))


问:
Hiding Empty Cells
I'm currently working on a code that hides empty cells ,but the problem is i want it to start hiding at a certain range ("A9:A12") not at the beginning of the sheet.
here is my program :

```<code>Sub EmptyRow()
'Dim s As String
po = Range("A9:A12").Count
Range("A8").Activate

For i = 1 To po
 s = i & ":" & i
 If IsEmpty(Cells(i, 1).Value) Then
     Rows(s).Select
     Selection.EntireRow.Hidden = True
End If
Next

End Sub
</code>```

The program keeps on hiding cells from the beginning, how do I set it up so it deletes from the range i want it to. Please help.

答:
Check the solution below. In case you need to change your affected area, just change the value of targetRange.

```<code>Sub EmptyRow()
Dim targetRange as Range, po as Long, i as Long
Set targetRange = Range("A9:A12")
po = targetRange.Count

With targetRange
    For i = 1 To po
        If IsEmpty(.Cells(i, 1).Value) Then
        .Rows(i).EntireRow.Hidden = True
        End If
    Next
End With

End Sub
</code>```

Title: Hiding Empty Cells

Body:
I'm currently working on a code that hides empty cells ,but the problem is i want it to start hiding at a certain range ("A9:A12") not at the beginning of the sheet.
here is my program :

Sub EmptyRow()
'Dim s As String
po = Range("A9:A12").Count
Range("A8").Activate

For i = 1 To po
 s = i & ":" & i
 If IsEmpty(Cells(i, 1).Value) Then
     Rows(s).Select
     Selection.EntireRow.Hidden = True
End If
Next

End Sub

The program keeps on hiding cells from the beginning, how do I set it up so it deletes from the range i want it to. Please help.

Body:
Check the solution below. In case you need to change your affected area, just change the value of targetRange.

Sub EmptyRow()
Dim targetRange as Range, po as Long, i as Long
Set targetRange = Range("A9:A12")
po = targetRange.Count

With targetRange
    For i = 1 To po
        If IsEmpty(.Cells(i, 1).Value) Then
        .Rows(i).EntireRow.Hidden = True
        End If
    Next
End With

End Sub


问:
How can I fix this stored card status: merchant is not authorized to use store card api in PayU payment gateway?
Why show this message how to fix this

答:
fixed showing error toast. Here commented the toast messgae.. </p>

```<code>  if (payuResponse.isResponseAvailable() && payuResponse.getResponseStatus().getCode() == PayuErrors.NO_ERROR) { // ok we are good to go
           // Toast.makeText(this, payuResponse.getResponseStatus().getResult(), Toast.LENGTH_LONG).show();
</code>```

Body: Why show this message how to fix this

Body:
fixed showing error toast. Here commented the toast messgae..

  if (payuResponse.isResponseAvailable() && payuResponse.getResponseStatus().getCode() == PayuErrors.NO_ERROR) { // ok we are good to go
           // Toast.makeText(this, payuResponse.getResponseStatus().getResult(), Toast.LENGTH_LONG).show();


答:
It's a double MATCH with an INDEX and an OFFSET:

```<code>=INDEX($A$2:$A$4,MATCH("Yes",OFFSET($A$2:$A$4,0, MATCH(A7,$B$1:$D$1,0)),0))
</code>```

Title: Excel - Return row header after searching for column header and a specific value in that column

Body:
I would like an Excel formula that returns the column header (value in column A) based on 2 conditions:

Header Column Name (Country 1 in the example below)

Specific Value in that Column (Yes in the example below)
So in this case, If my Search Cell (A12) has the value "Country 1", I will get the result "Domain 5" in the Result Cell (B12).

As well, I should be able to add columns (yellow headers) without breaking the formula.

Full result table below:

Country 1: Domain 1

Country 2: Domain 3

Country 3: Domain 2

Country 4: Domain 6

Country 5: Domain 4

Country 6: Domain 5

Country 7: Domain 8

Country 8: Domain 7

I have created a google spreadsheet below with the example on the tab "Example".
What I am trying to achieve is visible on the tab "Check".
https://docs.google.com/spreadsheets/d/1FjHkCs8MoFy6w-mhcyufD1VEBX-r3Rdc98GoNcsKeC0/edit?usp=sharing

I would really appreciate if someone could give me a hand.

Simplified example

Body:
It's a double MATCH with an INDEX and an OFFSET:

=INDEX($A$2:$A$4,MATCH("Yes",OFFSET($A$2:$A$4,0, MATCH(A7,$B$1:$D$1,0)),0))


问:
Golang gorm preloading
I'm writing my first app in golang, so sorry for newbie question, but I wasn't able to find the solution for the following problem:

I have two tables, position and attachment. Each position can have multiple attachments. Here is my model:

```<code>type Positions struct {
    Sys_id     int `gorm:"AUTO_INCREMENT" gorm:"column:sys_id" json:"sys_id,omitempty"`
    Name string `gorm:"size:120" gorm:"column:name" json:"name,omitempty"`
    OpenPositions int `gorm:"column:open_positions" json:"open_positions,omitempty"`
    ContactList string `gorm:"size:1000" gorm:"column:contact_list" json:"contact_list,omitempty"`
    Attachments []Attachment `gorm:"ForeignKey:RecordId"`
}

type Attachment struct {
    Sys_id     int `gorm:"AUTO_INCREMENT" gorm:"column:sys_id" json:"sys_id"`
    Name string `gorm:"size:255" gorm:"column: name" json:"name"`
    File string `gorm:"size:255" gorm:"column:file" json:"file"`
    RecordId int `gorm:"column:record_id" json:"record_id"`
    Table string `gorm:"size:255" gorm:"column:table" json:"table"`
    // ...
}
</code>```

I want to query the db and get positions with attachments

```<code>positions2 := []models.Positions{}
err := db.Where("open_positions > ?", 0).Preload("Attachments", "`table` = ?", "user_position").Find(&positions2)
if err != nil {
    log.WithFields(log.Fields{
        "type": "queryerr",
        "msg": err,
    }).Error("faked up query")
}
</code>```

Result of this query - I get positions correctly but the attachments are empty.

(can't preload field Attachments for models.Positions)
      level=error msg="faked up query" msg=&{0xc04200aca0 can't preload field Attachments for models.Positions 6  0xc042187e40 0xc042187d90 0xc0422cd4a0 0 {0xc042225130}  false  map[] map[] false}

Thanks in advance for help

答:
Models in your example have custom primary column names.
So, when only ForeignKey set for "has_many" association, Gorm trying to find Position's column Attachment.RecordId refers to.
By default it uses Position as prefix and Id as column name for this. But neither RecordId column has prefix Position nor Position model has column Id, so it fails.

In such case for "has_many" association you should specify both Foreign Key and Association Foreign Key.

In your example Association Foreign Key is the Position.Sys_id column and Attachment.RecordId refers to it.

So it should be fixed just by adding Association foreign key:

```<code>Attachments   []Attachment `gorm:"ForeignKey:RecordId;AssociationForeignKey:sys_id"`
</code>```

Title: Golang gorm preloading

Body:
I'm writing my first app in golang, so sorry for newbie question, but I wasn't able to find the solution for the following problem:

I have two tables, position and attachment. Each position can have multiple attachments. Here is my model:

type Positions struct {
    Sys_id     int `gorm:"AUTO_INCREMENT" gorm:"column:sys_id" json:"sys_id,omitempty"`
    Name string `gorm:"size:120" gorm:"column:name" json:"name,omitempty"`
    OpenPositions int `gorm:"column:open_positions" json:"open_positions,omitempty"`
    ContactList string `gorm:"size:1000" gorm:"column:contact_list" json:"contact_list,omitempty"`
    Attachments []Attachment `gorm:"ForeignKey:RecordId"`
}

type Attachment struct {
    Sys_id     int `gorm:"AUTO_INCREMENT" gorm:"column:sys_id" json:"sys_id"`
    Name string `gorm:"size:255" gorm:"column: name" json:"name"`
    File string `gorm:"size:255" gorm:"column:file" json:"file"`
    RecordId int `gorm:"column:record_id" json:"record_id"`
    Table string `gorm:"size:255" gorm:"column:table" json:"table"`
    // ...
}

I want to query the db and get positions with attachments

positions2 := []models.Positions{}
err := db.Where("open_positions > ?", 0).Preload("Attachments", "`table` = ?", "user_position").Find(&positions2)
if err != nil {
    log.WithFields(log.Fields{
        "type": "queryerr",
        "msg": err,
    }).Error("faked up query")
}

Result of this query - I get positions correctly but the attachments are empty.

(can't preload field Attachments for models.Positions)
      level=error msg="faked up query" msg=&{0xc04200aca0 can't preload field Attachments for models.Positions 6  0xc042187e40 0xc042187d90 0xc0422cd4a0 0 {0xc042225130}  false  map[] map[] false}

Thanks in advance for help

Body:
Models in your example have custom primary column names.
So, when only ForeignKey set for "has_many" association, Gorm trying to find Position's column Attachment.RecordId refers to.
By default it uses Position as prefix and Id as column name for this. But neither RecordId column has prefix Position nor Position model has column Id, so it fails.

In such case for "has_many" association you should specify both Foreign Key and Association Foreign Key.

In your example Association Foreign Key is the Position.Sys_id column and Attachment.RecordId refers to it.

So it should be fixed just by adding Association foreign key:

Attachments   []Attachment `gorm:"ForeignKey:RecordId;AssociationForeignKey:sys_id"`


问:
How to access data returned from Ajax post method call with index just like an array
Here is my code and it is not working to success function. Is there a possibility that I am not specifying in the right way tr and td elements

```<code>$(document).ready(function () {
    $("#search").blur(function () {
        //alert("ilir");
        $.ajax({
            type: "POST",
            data: { "barkodi": $(this).val() },
            dataType: 'json',
            success: function (data) {
                $('tr[class!="info"]').remove().after(function () {
                    $.each(function (index, data) {
                        $("tr").append(
                            $("<tr></tr>").html(
                            $("<td></td>").text(data[0].Barkodi),
                            $("<td></td>").text(data[0].Emri),
                            $("<td></td>").text(data[0].Cmimi),
                            $("<td></td>").text(data[0].Sasia))
                            );
                    });
                });
            }
        });
    });
})
</code>```

And here is my controller and action method I dont where is my bug here :(

```<code>[HttpPost]
    [AllowAnonymous]
    public JsonResult Index(string barkodi)
    {
        var produkti = _context.Produktets.SingleOrDefault(x => x.Barkodi == barkodi);

        List<ProduktetCustom> prod = new List<ProduktetCustom>();
        ProduktetCustom produkt = new ProduktetCustom()
        {
            Barkodi = produkti.Barkodi,
            Emri = produkti.Emri,
            Sasia = produkti.Sasia,
            Cmimi = produkti.Cmimi,
            Pershkrimi = produkti.Pershkrimi,
            IsDeleted = produkti.IsDeleted,
            DataModifikimit = produkti.DataModifikimit,
            DataShtimit = produkti.DataShtimit
        };

        prod.Add(produkt);
        return Json(prod,JsonRequestBehavior.AllowGet);
    }
</code>```

答:
You should use forEach function defined in Array instead of $.each.

Your code will look like this:

```<code>success: function (data) {
    $('tr[class!="info"]').remove().after(function () {
        data.forEach(function (item, index) {
            $("tr").append(
                $("<tr></tr>").html(
                    $("<td></td>").text(item.Barkodi),
                    $("<td></td>").text(item.Emri),
                    $("<td></td>").text(item.Cmimi),
                    $("<td></td>").text(item.Sasia)
                )
            );
        });
    });
}
</code>```

Body:
Here is my code and it is not working to success function. Is there a possibility that I am not specifying in the right way tr and td elements

$(document).ready(function () {
    $("#search").blur(function () {
        //alert("ilir");
        $.ajax({
            type: "POST",
            data: { "barkodi": $(this).val() },
            dataType: 'json',
            success: function (data) {
                $('tr[class!="info"]').remove().after(function () {
                    $.each(function (index, data) {
                        $("tr").append(
                            $("

").html(
                            $("	").text(data[0].Barkodi),
                            $("	").text(data[0].Emri),
                            $("	").text(data[0].Cmimi),
                            $("	").text(data[0].Sasia))
                            );
                    });
                });
            }
        });
    });
})

And here is my controller and action method I dont where is my bug here :(

[HttpPost]
    [AllowAnonymous]
    public JsonResult Index(string barkodi)
    {
        var produkti = _context.Produktets.SingleOrDefault(x => x.Barkodi == barkodi);

        List<ProduktetCustom> prod = new List<ProduktetCustom>();
        ProduktetCustom produkt = new ProduktetCustom()
        {
            Barkodi = produkti.Barkodi,
            Emri = produkti.Emri,
            Sasia = produkti.Sasia,
            Cmimi = produkti.Cmimi,
            Pershkrimi = produkti.Pershkrimi,
            IsDeleted = produkti.IsDeleted,
            DataModifikimit = produkti.DataModifikimit,
            DataShtimit = produkti.DataShtimit
        };

        prod.Add(produkt);
        return Json(prod,JsonRequestBehavior.AllowGet);
    }

Body:
You should use forEach function defined in Array instead of $.each.

Your code will look like this:

success: function (data) {
    $('tr[class!="info"]').remove().after(function () {
        data.forEach(function (item, index) {
            $("tr").append(
                $("<tr></tr>").html(
                    $("<td></td>").text(item.Barkodi),
                    $("<td></td>").text(item.Emri),
                    $("<td></td>").text(item.Cmimi),
                    $("<td></td>").text(item.Sasia)
                )
            );
        });
    });
}


问:
Incomplete output after concatenation
I am new to java and I am trying to concatenate two strings, say,

```<code>String string1 = "Paris"
String string2 = "is a great place to visit"
</code>```

I tried using concat , + and also StringBuilder, but every time I'm getting same output i.e. "Paris is".

Please help me out.

答:
Does this not work?</p>

```<code>public class Concat
{
 public static void main(String[] args)
  {
  String string1 = "Paris";
  String string2 = " is a great place to visit.";
  System.out.println(string1.concat(string2));
  }
}
</code>```

Title: Incomplete output after concatenation

Body:
I am new to java and I am trying to concatenate two strings, say,

String string1 = "Paris"
String string2 = "is a great place to visit"

I tried using concat , + and also StringBuilder, but every time I'm getting same output i.e. "Paris is".

Please help me out.

Body:
Does this not work?

public class Concat
{
 public static void main(String[] args)
  {
  String string1 = "Paris";
  String string2 = " is a great place to visit.";
  System.out.println(string1.concat(string2));
  }
}


问:
Java swing jbutton charging old image
i created a custom Java Button like this

```<code> public class GraphicPaintedButton extends JButton implements ToPaint{

    protected BufferedImage background;
    private boolean painted = false;

    public GraphicPaintedButton() {

    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if(painted){
        System.out.println("PAINTING!");
        Dimension size = getSize();
        g.drawImage(background, 0, 0,size.width, size.height,0, 0, background.getWidth(), background.getHeight(), null);
        }
    }

    @Override
    public void loadImage(String url){

        painted = true;
        URL imagePath = getClass().getResource(url);
        BufferedImage result = null;
        try {
            result = ImageIO.read(imagePath);
        } catch (IOException | IllegalArgumentException e) {
            System.err.println("Errore, immagine non trovata");
            e.printStackTrace();
        }
        background = result;
    }
    }
</code>```

Iif i load an image on the button, it calls the repaint,and it's good, the image is shown, when i load a new Image, it calls the repaint again and the new Image is shown. The problem is when i pass the mouse over the button, it calls the rapaint, but loads the old image. Why? And how did it get the old image, as the new one should have replaced it?

答:
I don't know why you want to go this extend and not simply use the icon property of the button, but...

First, I'd get rid of the painted flag, it runs the risk of allowing the paintComponent method to try and paint a null image, because the loadImage method may fail, but the painted flag is always set to true - Let's face it, you could easily end up with painted == true and background == null ... which is not a valid state

Instead, reason about the actual state you're interested in...

```<code>@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (background != null) {
        Dimension size = getSize();
        g.drawImage(background, 0, 0, size.width, size.height, 0, 0, background.getWidth(), background.getHeight(), null);
    }
}
</code>```

I would also change the loadImage method

```<code>public void loadImage(URL url) throws IOException {
    background = ImageIO.read(url);
    revalidate();
    repaint();
}
</code>```

First, don't use String, it's meaning is to ambiguous, instead, specify the lowest common parameter you're willing to deal with.

Secondly, the image is either going to load or it's not, if you're not going to deal with the exception, in any meaningful fashion, pass it back to the caller who may be in a better position to deal with it - IMHO

I don't know if this important or not, but I'd also consider overriding the getPreferredSize method...

```<code>@Override
public Dimension getPreferredSize() {
    return background == null ? new Dimension(10, 10) : new Dimension(background.getWidth(), background.getHeight());
}
</code>```

This will at least try and match the button's size to the size of the image

Title: Java swing jbutton charging old image

Body:
i created a custom Java Button like this

 public class GraphicPaintedButton extends JButton implements ToPaint{

    protected BufferedImage background;
    private boolean painted = false;

    public GraphicPaintedButton() {

    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if(painted){
        System.out.println("PAINTING!");
        Dimension size = getSize();
        g.drawImage(background, 0, 0,size.width, size.height,0, 0, background.getWidth(), background.getHeight(), null);
        }
    }

    @Override
    public void loadImage(String url){

        painted = true;
        URL imagePath = getClass().getResource(url);
        BufferedImage result = null;
        try {
            result = ImageIO.read(imagePath);
        } catch (IOException | IllegalArgumentException e) {
            System.err.println("Errore, immagine non trovata");
            e.printStackTrace();
        }
        background = result;
    }
    }

Iif i load an image on the button, it calls the repaint,and it's good, the image is shown, when i load a new Image, it calls the repaint again and the new Image is shown. The problem is when i pass the mouse over the button, it calls the rapaint, but loads the old image. Why? And how did it get the old image, as the new one should have replaced it?

Body:
I don't know why you want to go this extend and not simply use the icon property of the button, but...

First, I'd get rid of the painted flag, it runs the risk of allowing the paintComponent method to try and paint a null image, because the loadImage method may fail, but the painted flag is always set to true - Let's face it, you could easily end up with painted == true and background == null ... which is not a valid state

Instead, reason about the actual state you're interested in...

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (background != null) {
        Dimension size = getSize();
        g.drawImage(background, 0, 0, size.width, size.height, 0, 0, background.getWidth(), background.getHeight(), null);
    }
}

I would also change the loadImage method

public void loadImage(URL url) throws IOException {
    background = ImageIO.read(url);
    revalidate();
    repaint();
}

First, don't use String, it's meaning is to ambiguous, instead, specify the lowest common parameter you're willing to deal with.

Secondly, the image is either going to load or it's not, if you're not going to deal with the exception, in any meaningful fashion, pass it back to the caller who may be in a better position to deal with it - IMHO

I don't know if this important or not, but I'd also consider overriding the getPreferredSize method...

@Override
public Dimension getPreferredSize() {
    return background == null ? new Dimension(10, 10) : new Dimension(background.getWidth(), background.getHeight());
}

This will at least try and match the button's size to the size of the image


问:
How to create a query dynamically for an array of elements?
I have a basic query as follows

```<code>$query = "SELECT * FROM files WHERE (subject_code = '".$subject_code."' )";
</code>```

I have to modify this query to create a query where we have multiple subject codes fetched from an array.

```<code>$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);
</code>```

Now result holds all the required subject_codes say result[0]=SC1,result[1]=SC2 etc....

Now I want to the original query to be modified something as follows

```<code>$query = "SELECT * FROM files WHERE (subject_code = SC1 OR subject_code = SC2 .....)";
</code>```

Note that i don't know what are the values of SC1 SC2 etc.It depends on the branch and is inside $result.

How can i accomplish this?

答:
You can use Mysql In operator
Like this

```<code>SELECT * FROM files WHERE subject_code in ('SC1','SC2')";
</code>```

You can achieve ('SC1','SC2') by using implode php function,

 like this:

```<code>$subCodes = implode("','", $subject_array );
SELECT * FROM files WHERE subject_code in ('".$subCodes ."')"
</code>```

Body:
I have a basic query as follows

$query = "SELECT * FROM files WHERE (subject_code = '".$subject_code."' )";

I have to modify this query to create a query where we have multiple subject codes fetched from an array.

$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);

Now result holds all the required subject_codes say result[0]=SC1,result[1]=SC2 etc....

Now I want to the original query to be modified something as follows

$query = "SELECT * FROM files WHERE (subject_code = SC1 OR subject_code = SC2 .....)";

Note that i don't know what are the values of SC1 SC2 etc.It depends on the branch and is inside $result.

How can i accomplish this?

Body:
You can use Mysql In operator
Like this

SELECT * FROM files WHERE subject_code in ('SC1','SC2')";

You can achieve ('SC1','SC2') by using implode php function,

 like this:

$subCodes = implode("','", $subject_array );
SELECT * FROM files WHERE subject_code in ('".$subCodes ."')"


答:
You're correct; the issue is how you're adding the elements in the html() method. It accepts only a string or a function. You're also looping through the data array, but repeatedly adding only the content from the first item. You're also attempting to place content after() an element which has been removed, which won't work.

Try this:

```<code>success: function (data) {
  var html = data.map(function(o) {
    return `<tr><td>${o.Barkodi}</td><td>${o.Emri}</td><td>${o.Cmimi}</td><td>${o.Sasia}</td></tr>`;
  }).join('');
  $('table tbody').append(html);
}
</code>```

var data = [{
  Barkodi: 'Barkodi 1',
  Emri: 'Emri 1',
  Cmimi: 'Cmimi 1',
  Sasia: 'Cmimi 1',
}, {
  Barkodi: 'Barkodi 2',
  Emri: 'Emri 2',
  Cmimi: 'Cmimi 2',
  Sasia: 'Cmimi 2',
}]

var html = data.map(function(o) {
  return `<tr><td>${o.Barkodi}</td><td>${o.Emri}</td><td>${o.Cmimi}</td><td>${o.Sasia}</td></tr>`;
}).join('');
console.log(html);
$('table tbody').append(html);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table><tbody></tbody></table></code>```

Title: How to access data returned from Ajax post method call with index just like an array

Body:
You're correct; the issue is how you're adding the elements in the html() method. It accepts only a string or a function. You're also looping through the data array, but repeatedly adding only the content from the first item. You're also attempting to place content after() an element which has been removed, which won't work.

Try this:

success: function (data) {
  var html = data.map(function(o) {
    return `<tr><td>${o.Barkodi}</td><td>${o.Emri}</td><td>${o.Cmimi}</td><td>${o.Sasia}</td></tr>`;
  }).join('');
  $('table tbody').append(html);
}

var data = [{
  Barkodi: 'Barkodi 1',
  Emri: 'Emri 1',
  Cmimi: 'Cmimi 1',
  Sasia: 'Cmimi 1',
}, {
  Barkodi: 'Barkodi 2',
  Emri: 'Emri 2',
  Cmimi: 'Cmimi 2',
  Sasia: 'Cmimi 2',
}]

var html = data.map(function(o) {
  return `<tr><td>${o.Barkodi}</td><td>${o.Emri}</td><td>${o.Cmimi}</td><td>${o.Sasia}</td></tr>`;
}).join('');
console.log(html);
$('table tbody').append(html);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table><tbody></tbody></table>


问:
MongoDB Library for CodeIgniter (pecl mongodb, not mongo )
I just install php mongodb driver by "pecl install mongodb", and the phpinfo page shows mongodb module, that means the module installed successfully, but when I use the code:

```<code>"if ( ! class_exists('Mongo') && ! class_exists('MongoClient'))
{
show_error("The MongoDB PECL extension has not been installed or enabled", 500);
}"
</code>```

in the library file of codeigniter, it shows the error, then I guess maybe this is just for mongo, not for mongodb, so is there any codeingiter library for mongodb?

答:
enable both

extension=php_mongo.dll

extension=php_mongodb.dll

in php.ini file

Body:
I just install php mongodb driver by "pecl install mongodb", and the phpinfo page shows mongodb module, that means the module installed successfully, but when I use the code:

"if ( ! class_exists('Mongo') && ! class_exists('MongoClient'))
{
show_error("The MongoDB PECL extension has not been installed or enabled", 500);
}"

in the library file of codeigniter, it shows the error, then I guess maybe this is just for mongo, not for mongodb, so is there any codeingiter library for mongodb?


问:
I need to update the icons in a jqgrid tree dynamically when the cell is rendered
I want to render a jqgrid tree but he icons associated with the leaf I want to override the default values with values provided in the data. Let's say that one of the data columns is:
{name: "icon",width:1,hidden:true},
and has values such "ui-icon-alert", "ui-icon-bullet", "ui-icon-radio-off"

Is there any call back function to do this? if so how would you call it?

--UPDATE
Actually I think I found a possible answer here:TreeGrid

When I look at the data being supplied

```<code>{
"rows":[
    {"category_id":"1","name":"ELECTRONICS","price":"0.00","qty_onhand":"0","color":"","lft":"1","rgt":"44","level":"0","uiicon":""},
    {"category_id":"2","name":"TELEVISIONS","price":"0.00","qty_onhand":"0","color":"","lft":"2","rgt":"19","level":"1","uiicon":""},
    {"category_id":"3","name":"TUBE","price":"0.00","qty_onhand":"0","color":"","lft":"3","rgt":"8","level":"2","uiicon":""},
]
}
</code>```

I am not sure if this would work. But I also don't know what values lft and rgt are supposed to have. I know level determines the parent/child relationship.
Does anybody knows which is the best way?

答:
Glad to see that you find a solution in our Guriddo jqGrid.
Actually you can get more information in our new released documentation</p>

Body:
I want to render a jqgrid tree but he icons associated with the leaf I want to override the default values with values provided in the data. Let's say that one of the data columns is:
{name: "icon",width:1,hidden:true},
and has values such "ui-icon-alert", "ui-icon-bullet", "ui-icon-radio-off"

Is there any call back function to do this? if so how would you call it?

--UPDATE
Actually I think I found a possible answer here:TreeGrid

When I look at the data being supplied

{
"rows":[
    {"category_id":"1","name":"ELECTRONICS","price":"0.00","qty_onhand":"0","color":"","lft":"1","rgt":"44","level":"0","uiicon":""},
    {"category_id":"2","name":"TELEVISIONS","price":"0.00","qty_onhand":"0","color":"","lft":"2","rgt":"19","level":"1","uiicon":""},
    {"category_id":"3","name":"TUBE","price":"0.00","qty_onhand":"0","color":"","lft":"3","rgt":"8","level":"2","uiicon":""},
]
}

I am not sure if this would work. But I also don't know what values lft and rgt are supposed to have. I know level determines the parent/child relationship.
Does anybody knows which is the best way?


问:
Why has Composer installed a version of a package that seems to conflict with the requirements?
This looks like a simple issue, but I can't explain what's happening.

In composer.json for my Symfony project the twig version is specified as <2.0, to avoid breaking changes between v1 and v2.  However, Composer installs the latest Twig version (2.4.3) anyway.

```<code>php c:\php\composer\composer.phar depends -t "twig/twig"
twig/twig v2.4.3 Twig, the flexible, fast, and secure template language for PHP
|--symfony/framework-standard-edition dev-develop (requires twig/twig <2.0)
|--symfony/symfony v2.8.24 (requires twig/twig ~1.34|~2.4)
|  `--symfony/framework-standard-edition dev-develop (requires symfony/symfony 2.8.*)
`--twig/extensions v1.5.1 (requires twig/twig ~1.27|~2.0)
   `--symfony/framework-standard-edition dev-develop (requires twig/extensions ^1.3)
</code>```

Relevant chunk of composer.json:

```<code>"require": {
    "php": ">=5.3.3",
    "symfony/symfony": "2.8.*",
    "doctrine/dbal": "2.5.*",
    "doctrine/orm": "2.5.*",
    "doctrine/doctrine-bundle": "~1.2",
    "twig/twig": "<2.0",
    "twig/extensions": "^1.3",
    etc
}
</code>```

It looks to me like the requirements of the symfony/symfony and twig/extensions packages, combined with those of the project, would result in the highest possible 1.x version of Twig, 1.34.4, but that's not what happens.  Why?

EDIT:

Composer 1.4.2

Full composer.json

```<code>{
    "name": "symfony/framework-standard-edition",
    "license": "MIT",
    "type": "project",
    "description": "The \"Symfony Standard Edition\" distribution",
    "autoload": {
        "psr-0": { "": "src/", "SymfonyStandard": "app/" }
    },
    "require": {
        "php": ">=5.3.3",
        "symfony/symfony": "2.8.*",
        "doctrine/dbal": "2.5.*",
        "doctrine/orm": "2.5.*",
        "doctrine/doctrine-bundle": "~1.2",
        "twig/twig": "<2.0",
        "twig/extensions": "^1.3",
        "symfony/assetic-bundle": "^2.8",
        "symfony/swiftmailer-bundle": "~2.3",
        "symfony/monolog-bundle": "~2.4",
        "sensio/distribution-bundle": "~3.0",
        "sensio/framework-extra-bundle": "~3.0",
        "incenteev/composer-parameter-handler": "~2.0",
        "beberlei/DoctrineExtensions": "^1.0",
        "royopa/fpdf-symfony2": "^1.0",
        "liuggio/excelbundle": "^2.0",
        "patchwork/jsqueeze": "^2.0",
        "leafo/scssphp": "^0.6.5",
        "doctrine/doctrine-migrations-bundle": "^1.0",
        "ocramius/proxy-manager": "~2.0.0",
        "aws/aws-sdk-php-symfony": "^1.2"
    },
    "require-dev": {
        "sensio/generator-bundle": "~2.3",
        "symfony/phpunit-bridge": "^3.1",
        "deployer/deployer": "^3.3"
    },
    "scripts": {
        "post-root-package-install": [
            "SymfonyStandard\\Composer::hookRootPackageInstall"
        ],
        "post-install-cmd": [
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::removeSymfonyStandardFiles"
        ],
        "post-update-cmd": [
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::removeSymfonyStandardFiles"
        ]
    },
    "config": {
        "bin-dir": "bin"
    },
    "extra": {
        "symfony-app-dir": "app",
        "symfony-web-dir": "web",
        "incenteev-parameters": {
            "file": "app/config/parameters.yml"
        },
        "branch-alias": {
            "dev-master": "2.5-dev"
        }
    }
}
</code>```

EDIT 2:

Deleting composer.lock and completely updating and reinstalling gives me what I thought I should get!

答:
What version of composer are you using?

I tested that json file on a Linux Mint 17, with php 5.5 and composer 1.3.2 and the twig version installed is the right one (twig/twig - v1.34.4).

Can you try to paste your complete composer.json file?

Also, I suggest removing the composer.lock file and all the contents of the vendor folder and try the install again.

Body:
This looks like a simple issue, but I can't explain what's happening.

In composer.json for my Symfony project the twig version is specified as <2.0, to avoid breaking changes between v1 and v2.  However, Composer installs the latest Twig version (2.4.3) anyway.

php c:\php\composer\composer.phar depends -t "twig/twig"
twig/twig v2.4.3 Twig, the flexible, fast, and secure template language for PHP
|--symfony/framework-standard-edition dev-develop (requires twig/twig <2.0)
|--symfony/symfony v2.8.24 (requires twig/twig ~1.34|~2.4)
|  `--symfony/framework-standard-edition dev-develop (requires symfony/symfony 2.8.*)
`--twig/extensions v1.5.1 (requires twig/twig ~1.27|~2.0)
   `--symfony/framework-standard-edition dev-develop (requires twig/extensions ^1.3)

Relevant chunk of composer.json:

"require": {
    "php": ">=5.3.3",
    "symfony/symfony": "2.8.*",
    "doctrine/dbal": "2.5.*",
    "doctrine/orm": "2.5.*",
    "doctrine/doctrine-bundle": "~1.2",
    "twig/twig": "<2.0",
    "twig/extensions": "^1.3",
    etc
}

It looks to me like the requirements of the symfony/symfony and twig/extensions packages, combined with those of the project, would result in the highest possible 1.x version of Twig, 1.34.4, but that's not what happens.  Why?

EDIT:

Composer 1.4.2

Full composer.json

{
    "name": "symfony/framework-standard-edition",
    "license": "MIT",
    "type": "project",
    "description": "The \"Symfony Standard Edition\" distribution",
    "autoload": {
        "psr-0": { "": "src/", "SymfonyStandard": "app/" }
    },
    "require": {
        "php": ">=5.3.3",
        "symfony/symfony": "2.8.*",
        "doctrine/dbal": "2.5.*",
        "doctrine/orm": "2.5.*",
        "doctrine/doctrine-bundle": "~1.2",
        "twig/twig": "<2.0",
        "twig/extensions": "^1.3",
        "symfony/assetic-bundle": "^2.8",
        "symfony/swiftmailer-bundle": "~2.3",
        "symfony/monolog-bundle": "~2.4",
        "sensio/distribution-bundle": "~3.0",
        "sensio/framework-extra-bundle": "~3.0",
        "incenteev/composer-parameter-handler": "~2.0",
        "beberlei/DoctrineExtensions": "^1.0",
        "royopa/fpdf-symfony2": "^1.0",
        "liuggio/excelbundle": "^2.0",
        "patchwork/jsqueeze": "^2.0",
        "leafo/scssphp": "^0.6.5",
        "doctrine/doctrine-migrations-bundle": "^1.0",
        "ocramius/proxy-manager": "~2.0.0",
        "aws/aws-sdk-php-symfony": "^1.2"
    },
    "require-dev": {
        "sensio/generator-bundle": "~2.3",
        "symfony/phpunit-bridge": "^3.1",
        "deployer/deployer": "^3.3"
    },
    "scripts": {
        "post-root-package-install": [
            "SymfonyStandard\\Composer::hookRootPackageInstall"
        ],
        "post-install-cmd": [
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::removeSymfonyStandardFiles"
        ],
        "post-update-cmd": [
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::removeSymfonyStandardFiles"
        ]
    },
    "config": {
        "bin-dir": "bin"
    },
    "extra": {
        "symfony-app-dir": "app",
        "symfony-web-dir": "web",
        "incenteev-parameters": {
            "file": "app/config/parameters.yml"
        },
        "branch-alias": {
            "dev-master": "2.5-dev"
        }
    }
}

EDIT 2:

Deleting composer.lock and completely updating and reinstalling gives me what I thought I should get!


问:
How to get out of the loop, if the PHP script takes more than 53 seconds to execute
In Short: How to break the code after the code takes more than 53 seconds to execute, something like this:

```<code>while (5 < 200)
{
// do some work here, which will take around 1-6 seconds

if (code this loop is running for more than 53 seconds)
break;

}
</code>```

If you want to know, why i want to do this:

Ok, this is What I am doing: I am copying data from 7 JSON pages on the web and inserting them into my MySQL database.

The code is something like this:

```<code>$start_time = microtime(TRUE); // Helps to count PHP script execution time

connect to database
$number = get inserted number into database
while ($number > ($number+20) )

{

7 Open JSON File link like this  - "example.com/$number?api=xxxyyzz"

Use Prepared PDO statements to insert data into MySQL

}
// Code to count PHP script execution time
$end_time = microtime(TRUE);

$time_taken = $end_time - $start_time;

$time_taken = round($time_taken,5);

echo '<p>Page generated in '.$time_taken.' seconds.</p>';
</code>```

So in my case, It takes around 5.2 seconds to complete one whole loop of adding all data. But some JSON files are empty, so it takes only 1.4 second to complete 1 loop, if they are empty.

So like that, I want to complete millions of loops (add Data from millions of JSON files). So if my code runs for 24/7, it will take me 1 month to complete my task.

But after the code runs for 90 seconds, i get this error:

I am using a CRON job to do the task. And looks like server gives the same error to CRON job.

So, I want to do the CRON job to run every 1 minute, so I do not get timed out error.

But I am afraid of this: What If the script added data in half rows  and 1 mintue gets over, and it do not add data into other half rows. Then after the starting on the new minute, the code start from the next $number.

So, If i can break; out of the loop after 53 seconds (If the code starts another loop at 52 seconds, then break at the end of it, that will be around 58-59 seconds).

I mean,  i will put the break; code just before the loop end (before }). So i do not exit the loop, while the data got inserted into half of the rows.

答:
I guess that your PHP's max_execution_time is equal to 90 seconds, you can  specify max_execution_time by set_time_limit, but I don't think it is a  good approach for this.

Have a try pcntl or pthreads, it would save you a lot of time.

Body:
In Short: How to break the code after the code takes more than 53 seconds to execute, something like this:

while (5 < 200)
{
// do some work here, which will take around 1-6 seconds

if (code this loop is running for more than 53 seconds)
break;

}

If you want to know, why i want to do this:

Ok, this is What I am doing: I am copying data from 7 JSON pages on the web and inserting them into my MySQL database.

The code is something like this:

$start_time = microtime(TRUE); // Helps to count PHP script execution time

connect to database
$number = get inserted number into database
while ($number > ($number+20) )

{

7 Open JSON File link like this  - "example.com/$number?api=xxxyyzz"

Use Prepared PDO statements to insert data into MySQL

}
// Code to count PHP script execution time
$end_time = microtime(TRUE);

$time_taken = $end_time - $start_time;

$time_taken = round($time_taken,5);

echo '
Page generated in '.$time_taken.' seconds.
';

So in my case, It takes around 5.2 seconds to complete one whole loop of adding all data. But some JSON files are empty, so it takes only 1.4 second to complete 1 loop, if they are empty.

So like that, I want to complete millions of loops (add Data from millions of JSON files). So if my code runs for 24/7, it will take me 1 month to complete my task.

But after the code runs for 90 seconds, i get this error:

I am using a CRON job to do the task. And looks like server gives the same error to CRON job.

So, I want to do the CRON job to run every 1 minute, so I do not get timed out error.

But I am afraid of this: What If the script added data in half rows  and 1 mintue gets over, and it do not add data into other half rows. Then after the starting on the new minute, the code start from the next $number.

So, If i can break; out of the loop after 53 seconds (If the code starts another loop at 52 seconds, then break at the end of it, that will be around 58-59 seconds).

I mean,  i will put the break; code just before the loop end (before }). So i do not exit the loop, while the data got inserted into half of the rows.