text:
Q: Are these two sequences the same? I was browsing OEIS and came across the largely composite numbers, A067128, defined as the natural numbers that have at least as many divisors as all smaller natural numbers. (They are of course related to the highly composite numbers.)
A comment on the OEIS page asks whether the largely composite numbers are the same as A034287, the numbers $n$ such that the product of the divisors of $n$ is larger than for all smaller natural numbers. In reply, another comment says that the two sequences are the same for all terms less than $10^{150}$, of which there are 105834.
My questions are:

*

*Are these two sequences the same, or do they differ at some point after the 105834th term?

*If they do differ, is there a nice way to see why the two sequences should be the same for such a large range of initial values?

A: Begun actual work on the thing. The product of divisors has, of course, the same prime factors as the original number. What I did not know is that, if the original exponent is $a$ and the number of divisors of the number is $d(n),$ then the new exponent of that prime (in the product of divisors) is
$$ a \, d(n) / 2.  $$
This gives the first hint of how a large number of divisors tends to give a large product of divisors, in a tightly controlled manner. Put another way, if the original number is $n$ and the product of all divisors is $P,$ then
$$ P = n^{d(n)/2} $$
Therefore, if $n$ has at least as many divisors as all smaller numbers, then $P$ is guaranteed strictly larger than all previous values for $P.$ So, we have that A067128 is contained in A034287, maybe strictly, or maybe the sequences are equal.
THEOREM a largely composite number has a product of divisors that is strictly larger than such products for all smaller numbers.
Approaches for the other direction: if the assumption is that $n$ sets a new record for product of divisors, we are saying that, for all $m < n,$
$$  d(n) > \left( \frac{\log m}{\log n} \right) d(m).  $$
We do have explicit upper bounds on the size of $d(n)$ due to Nicolas and Robin; the important thing is how very small these bounds are. It is possible that numbers setting new divisor product records are so frequent that, when $m$ is the previous element in that list, that $  \left( \frac{\log m}{\log n} \right) d(m) > d(m) - 1.  $ That would do it; maybe it is true. I will, at least, experiment with that. OH, WELL. The conjectured inequality does not appear to be true, or even true for sufficently large numbers. On the other hand, we appear to get the promising $  \left( \frac{\log m}{\log n} \right) d(m) > d(m) - 3.  $ Worth playing with this computer conjecture, because $d(m)$ is even unless $m$ itself is a square.  NOPE. The $3$ does not hold up either. Here are the smallest numbers where the difference exceeds 2.0. The way this is going, I think either finding a number on one list but not the other, or a proof the lists are the same, would be a fair amount of effort.
7560 =  ( 3,  3,  1,  1  )  prod    =  ( 96,  96,  32,  32,  )   number of divisors  64 prev  60 57.2759  diff  2.7241
131040 =  ( 5,  2,  1,  1,  1  )  prod    =  ( 360,  144,  72,  72,  72,  )   number of divisors  144 prev  144 141.958  diff  2.04152
196560 =  ( 4,  3,  1,  1,  1  )  prod    =  ( 320,  240,  80,  80,  80,  )   number of divisors  160 prev  160 157.807  diff  2.1929
262080 =  ( 6,  2,  1,  1,  1  )  prod    =  ( 504,  168,  84,  84,  84,  )   number of divisors  168 prev  168 165.751  diff  2.24945
327600 =  ( 4,  2,  2,  1,  1  )  prod    =  ( 360,  180,  180,  90,  90,  )   number of divisors  180 prev  180 177.632  diff  2.36778
655200 =  ( 5,  2,  2,  1,  1  )  prod    =  ( 540,  216,  216,  108,  108,  )   number of divisors  216 prev  216 213.306  diff  2.69428
831600 =  ( 4,  3,  2,  1,  1  )  prod    =  ( 480,  360,  240,  120,  120,  )   number of divisors  240 prev  240 237.48  diff  2.51955
942480 =  ( 4,  2,  1,  1,  1,  1  )  prod    =  ( 480,  240,  120,  120,  120,  120,  )   number of divisors  240 prev  240 237.816  diff  2.18367
1330560 =  ( 7,  3,  1,  1,  1  )  prod    =  ( 896,  384,  128,  128,  128,  )   number of divisors  256 prev  256 252.23  diff  3.76961
1663200 =  ( 5,  3,  2,  1,  1  )  prod    =  ( 720,  432,  288,  144,  144,  )   number of divisors  288 prev  288 285.123  diff  2.87715

Sample, just the exponents, not the primes themselves:
2 =  (  1 )  prod    =  (  1 )   number of divisors  2
3 =  (  1 )  prod    =  (  1 )   number of divisors  2
4 =  ( 2,  )  prod    =  ( 3,  )   number of divisors  3
6 =  ( 1,  1  )  prod    =  ( 2,  2,  )   number of divisors  4
8 =  ( 3,  )  prod    =  ( 6,  )   number of divisors  4
10 =  ( 1,  1  )  prod    =  ( 2,  2,  )   number of divisors  4
12 =  ( 2,  1  )  prod    =  ( 6,  3,  )   number of divisors  6
18 =  ( 1,  2,  )  prod    =  ( 3,  6,  )   number of divisors  6
20 =  ( 2,  1  )  prod    =  ( 6,  3,  )   number of divisors  6
24 =  ( 3,  1  )  prod    =  ( 12,  4,  )   number of divisors  8
30 =  ( 1,  1,  1  )  prod    =  ( 4,  4,  4,  )   number of divisors  8
36 =  ( 2,  2,  )  prod    =  ( 9,  9,  )   number of divisors  9
48 =  ( 4,  1  )  prod    =  ( 20,  5,  )   number of divisors  10
60 =  ( 2,  1,  1  )  prod    =  ( 12,  6,  6,  )   number of divisors  12
72 =  ( 3,  2,  )  prod    =  ( 18,  12,  )   number of divisors  12
84 =  ( 2,  1,  1  )  prod    =  ( 12,  6,  6,  )   number of divisors  12
90 =  ( 1,  2,  1  )  prod    =  ( 6,  12,  6,  )   number of divisors  12
96 =  ( 5,  1  )  prod    =  ( 30,  6,  )   number of divisors  12
108 =  ( 2,  3,  )  prod    =  ( 12,  18,  )   number of divisors  12
120 =  ( 3,  1,  1  )  prod    =  ( 24,  8,  8,  )   number of divisors  16
168 =  ( 3,  1,  1  )  prod    =  ( 24,  8,  8,  )   number of divisors  16
180 =  ( 2,  2,  1  )  prod    =  ( 18,  18,  9,  )   number of divisors  18
240 =  ( 4,  1,  1  )  prod    =  ( 40,  10,  10,  )   number of divisors  20
336 =  ( 4,  1,  1  )  prod    =  ( 40,  10,  10,  )   number of divisors  20
360 =  ( 3,  2,  1  )  prod    =  ( 36,  24,  12,  )   number of divisors  24
420 =  ( 2,  1,  1,  1  )  prod    =  ( 24,  12,  12,  12,  )   number of divisors  24
480 =  ( 5,  1,  1  )  prod    =  ( 60,  12,  12,  )   number of divisors  24
504 =  ( 3,  2,  1  )  prod    =  ( 36,  24,  12,  )   number of divisors  24
540 =  ( 2,  3,  1  )  prod    =  ( 24,  36,  12,  )   number of divisors  24
600 =  ( 3,  1,  2,  )  prod    =  ( 36,  12,  24,  )   number of divisors  24
630 =  ( 1,  2,  1,  1  )  prod    =  ( 12,  24,  12,  12,  )   number of divisors  24
660 =  ( 2,  1,  1,  1  )  prod    =  ( 24,  12,  12,  12,  )   number of divisors  24
672 =  ( 5,  1,  1  )  prod    =  ( 60,  12,  12,  )   number of divisors  24
720 =  ( 4,  2,  1  )  prod    =  ( 60,  30,  15,  )   number of divisors  30
840 =  ( 3,  1,  1,  1  )  prod    =  ( 48,  16,  16,  16,  )   number of divisors  32
1080 =  ( 3,  3,  1  )  prod    =  ( 48,  48,  16,  )   number of divisors  32
1260 =  ( 2,  2,  1,  1  )  prod    =  ( 36,  36,  18,  18,  )   number of divisors  36
1440 =  ( 5,  2,  1  )  prod    =  ( 90,  36,  18,  )   number of divisors  36
1680 =  ( 4,  1,  1,  1  )  prod    =  ( 80,  20,  20,  20,  )   number of divisors  40
2160 =  ( 4,  3,  1  )  prod    =  ( 80,  60,  20,  )   number of divisors  40
2520 =  ( 3,  2,  1,  1  )  prod    =  ( 72,  48,  24,  24,  )   number of divisors  48
3360 =  ( 5,  1,  1,  1  )  prod    =  ( 120,  24,  24,  24,  )   number of divisors  48
3780 =  ( 2,  3,  1,  1  )  prod    =  ( 48,  72,  24,  24,  )   number of divisors  48
3960 =  ( 3,  2,  1,  1  )  prod    =  ( 72,  48,  24,  24,  )   number of divisors  48
4200 =  ( 3,  1,  2,  1  )  prod    =  ( 72,  24,  48,  24,  )   number of divisors  48
4320 =  ( 5,  3,  1  )  prod    =  ( 120,  72,  24,  )   number of divisors  48
4620 =  ( 2,  1,  1,  1,  1  )  prod    =  ( 48,  24,  24,  24,  24,  )   number of divisors  48
4680 =  ( 3,  2,  1,  1  )  prod    =  ( 72,  48,  24,  24,  )   number of divisors  48
5040 =  ( 4,  2,  1,  1  )  prod    =  ( 120,  60,  30,  30,  )   number of divisors  60
7560 =  ( 3,  3,  1,  1  )  prod    =  ( 96,  96,  32,  32,  )   number of divisors  64
9240 =  ( 3,  1,  1,  1,  1  )  prod    =  ( 96,  32,  32,  32,  32,  )   number of divisors  64
10080 =  ( 5,  2,  1,  1  )  prod    =  ( 180,  72,  36,  36,  )   number of divisors  72
12600 =  ( 3,  2,  2,  1  )  prod    =  ( 108,  72,  72,  36,  )   number of divisors  72
13860 =  ( 2,  2,  1,  1,  1  )  prod    =  ( 72,  72,  36,  36,  36,  )   number of divisors  72
15120 =  ( 4,  3,  1,  1  )  prod    =  ( 160,  120,  40,  40,  )   number of divisors  80
18480 =  ( 4,  1,  1,  1,  1  )  prod    =  ( 160,  40,  40,  40,  40,  )   number of divisors  80
20160 =  ( 6,  2,  1,  1  )  prod    =  ( 252,  84,  42,  42,  )   number of divisors  84
25200 =  ( 4,  2,  2,  1  )  prod    =  ( 180,  90,  90,  45,  )   number of divisors  90
27720 =  ( 3,  2,  1,  1,  1  )  prod    =  ( 144,  96,  48,  48,  48,  )   number of divisors  96
30240 =  ( 5,  3,  1,  1  )  prod    =  ( 240,  144,  48,  48,  )   number of divisors  96
32760 =  ( 3,  2,  1,  1,  1  )  prod    =  ( 144,  96,  48,  48,  48,  )   number of divisors  96
36960 =  ( 5,  1,  1,  1,  1  )  prod    =  ( 240,  48,  48,  48,  48,  )   number of divisors  96
37800 =  ( 3,  3,  2,  1  )  prod    =  ( 144,  144,  96,  48,  )   number of divisors  96
40320 =  ( 7,  2,  1,  1  )  prod    =  ( 336,  96,  48,  48,  )   number of divisors  96
41580 =  ( 2,  3,  1,  1,  1  )  prod    =  ( 96,  144,  48,  48,  48,  )   number of divisors  96
42840 =  ( 3,  2,  1,  1,  1  )  prod    =  ( 144,  96,  48,  48,  48,  )   number of divisors  96
43680 =  ( 5,  1,  1,  1,  1  )  prod    =  ( 240,  48,  48,  48,  48,  )   number of divisors  96

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=


text:
Q: Difference between checking hash map and iterating through keys in hash map I have a list of words with a corresponding score for each word. And I'm combing through and matching each individual word in a big block of text in a .txt file with words in the list of words. The .txt file can have up to 10,000 lines of text.
When I first did this, I used a very brute force and naive method to match the words on my word list with my .txt file. Although I used a hash map, I did not use the hash map correctly, and might as well have used it as a list. So the code was written in the following manner:
for(int i=0; i<words.length; i++){
    for(int j=0; j<wordListType.size(); j++){
        Map<String, Integer> hmap = wordListType.get(j).getMap();
        for(Map.Entry<String, Integer> entry : hmap.entrySet()){
            if(words[i].contains(entry.getKey())){
                foo();
            }
        }
    }
}

words is a String[] with individual words from the text file. wordListType is an ArrayList of a class that contains a hash map of the keywords that I'm searching for. It's an ArrayList because there are multiple types of word lists. And the getMap() is my own helper method inside the WordList class.
Afterwards, I figured out my code was inefficient, and I was not using my hash map to its full strength. So I changed the code to the following:
for(int i=0; i<words.length; i++){
    for(int j=0; j<wordListType.size(); j++){
        Map<String, Integer> hmap = wordListType.get(j).getMap();
        Integer val = null;
        if((val = hmap.get(words[i])) != null){
            foo();
        }
    }
}

This way I'm not going through each and every key in hmap like I do with the first method, and I use the O(1) HashMap.get() method instead.
However, the second, efficient method is not producing the results that I want.
I'm not quite sure why the words are being matched differently though. From what I can see, they should both provide the exact same answers, except my latter code should do so much faster. Instead the first method of iterating through all the keys of the hash map is actually producing the results that I want (and I checked this manually), while the second method does not.
There are NO null values in my hash map, which I have tested for. I've looked up the implementation of hash map, so I don't quite understand why this is not working. Am I missing something here or is there something else that is unrelated that is affecting my results? Any help is much appreciated.

A: If I get it correctly words[i] is a String. In the first solution you are matching every word that has the map key as substring. The second case you do exact matching.
This one:
words[i].contains(entry.getKey())

Will match every word that has entry.getKey() a ssubstring. I.e it will match alabala for the string ala
Over here:
(val = hmap.get(words[k])) != null

Which is better written:
hmap.contains(words[k])

You check if the map contains key that exactly matches the given word. In this case ala will not match for the word alabala.

A: The two if conditions you use do not test the same thing. Lets take an example where words[i] is "tested" and your map contains the key "test" :
if(words[i].contains(entry.getKey())) {

This condition checks if your Word[i] contains your map key, meaning that the if block will be evaluated.
if((val = hmap.get(words[k])) != null){

This condition checks if your map contains the string word[k] ("tested"), which will evaluate to false as it contains only "test".
I believe that for your use case, the second implentation gives the result you are looking for.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to access localhost asp.net core web api from outside I have react native app.i want get data from the asp.net core web API .I want to  to access localhost asp.net core web API from outside(from react native app)

A: You can use many 3rd party library for HTTP request such as axios, fetch even XMLHttpRequest as you want to access core web API. You can use the following approaches it doesn't matter what's your endpoint.
 fetch('https://jsonplaceholder.typicode.com/posts/1', {
         method: 'GET'
      })
      .then((response) => response.json())
      .then((responseJson) => {
         console.log(responseJson);
         this.setState({
            data: responseJson
         })
      })
      .catch((error) => {
         console.error(error);
      });

using XMLHttpRequest
var xhr = new XMLHttpRequest()
    xhr.addEventListener('load', () => {
      console.log(xhr.responseText)
    })
    xhr.open('GET', 'https://dog.ceo/api/breeds/list/all')
    xhr.send()

using axios
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
  });


text:
Q: Filtering date between two dates in javascript I was trying to filter the data between two dates.
But i am not able to achieve
Where the Detaileddata is my array having set of data. In which I have the date as
date = {01.07.2020,02.07.2020,03.07.2020,.....18.08.2020}
where date has the values in the format [DD.MM.YYYY],
But the result i am able to acheive is only the data having 01.07.2020 and 18.08.2020. But I want to display the data between the 01.07.2020 and 18.08.2020
Typescript part
     var startDate = "01.07.2020";
     var endDate = "18.08.2020";
     this.Detaileddata = this.Detaileddata.filter((item) => {
       return (item.date >= startDate && item.date <= endDate);
     })
     console.log("result"+this.detaileddata);

A: The better way always to use library like date-fns or moment.js. Using vanilla approach. You can convert date in timestamp. I am assuming you are getting these date:

var startDate = "01.07.2020";
var endDate = "18.08.2020";

const detailedData = [{date:"01.07.2020"},{date:"20.07.2020"},{date:"25.07.2020"},{date:"01.08.2020"},{date:"18.08.2020"},{date:"01.09.2020"},{date:"01.10.2020"}]

const filteredDate = detailedData.filter(item => {
        let itemDate = item.date.split('.').reverse().join("-")
        let startDateModified = startDate.split('.').reverse().join("-")
        let endDateModified = endDate.split('.').reverse().join("-")
       return (new Date(itemDate).getTime() >= new Date(startDateModified).getTime() && new Date(itemDate).getTime() <= new Date(endDateModified).getTime());
     })
console.log("result",filteredDate);


text:
Q: Is it safe to cast a IDispatch* into an IUnknown*, without using QueryInterface, for interprocess COM objects? When dealing with interprocess COM objects, is it safe to cast a IDispatch* into an IUnknown*, without using QueryInterface ?
Here our IDispatch object comes from an other process OtherProcess.exe.
And a colleague of mine says that I should call QueryInterface on the IDispatch so as to get an IUnknown.
Currently I'm doing:
void CComThrowDispatch::CheckCOMAvailabilty() const
{
    IUnknown * pIUnknown = m_spDispatchDriver.p;
    // is this line above a problem ?
    // m_spDispatchDriver is an ATL CComDispatchDriver
    // it handles an object instanciated in another process.
    // m_spDispatchDriver.p is of type IDispatch*

    if (pIUnknown == nullptr) return;
    bool bComObjectReachable = ::CoIsHandlerConnected(pIUnknown) == TRUE;
    if (bComObjectReachable == false)
    {
        throw MyException;
    }
}

My problem with his suggestion: I am dealing with cases (access violations) when the OtherProcess.exe has crashed or has been killed. It seems calling any functions like Invoke on the IDispatch that encapsulates any objects from this no longer exisiting OtherProcess.exe provokes these access violations (EDIT: comments and answers reveals that this latest assumption was completely false!).
That's why I'm trying to protect the application testing ::CoIsHandlerConnected(pIUnknown); which takes an IUnknown as parameter.
But by calling QueryInterface on the IDispatch, like my colleague advises me to do, I am afraid to fall back in the same problem I am trying to solve: This IDispatch handles an object that no longer exists, and QueryInterface to an  IUnknown would just be Undefined Behaviour all the same (EDIT again, this assumption is also false).
Am I really wrong when I just do the cast ?
What is the common way to deal with dead interprocess COM objects ?
This is the begining of the definition of IDispatch in OAIdl.h, which is declared as deriving from IUnknown.
MIDL_INTERFACE("00020400-0000-0000-C000-000000000046")
IDispatch : public IUnknown
{
public:
    virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(
        /* [out] */ __RPC__out UINT *pctinfo) = 0;

A: In order to detect whether the object is remote CoIsHandlerConnected would QueryInterface the argument anyway (for IProxyManager etc), so it does not matter whether you provide the pointer you already have, or you additionally query for IUnknown. Your QueryInterface call has not effect on the status of the remote object: whether the object is remote or not, whether remote object is dead or not - CoIsHandlerConnected has the same result for you regardless of your additional QueryInterface. Hence, there is no need to do it.
Then another note is that it is still safe to call IDispatch::Invoke if remote object is dead (out-of-process server crashed etc). The proxy simply returns error code without undefined behavior. That is, it looks like you don't need CoIsHandlerConnected at all, and if you experience access violations in context of client process, then you probably have other issues to resolve first.

A: Casting IDispatch to IUnknown in C++ (like static_cast<IUnknown*>(pDispatch)) yields exactly the same pointer value, because IDispatch derives from IUnknown. OTOH, doing QueryInterface for IID_IUnknown on pDispatch may return a different pointer, but it's still a legit operation. In fact, this is how to get the identity of a COM object, say, to check if two interfaces are implemented by the same COM object (a hard COM rule which always work inside the same COM apartment).
That said, the proxy COM object implemented by the COM marshaller may be caching interfaces, so the call to IDispatch::QueryInterface may return S_OK and a valid IUnknown identity of the proxy, despite the remote server already went down. That is, such operation might not be causing an instant IPC call.
In your case, to test if the COM server is still alive and well, I'd simply call IDispatch::GetTypeInfoCount on the proxy object you already have. That would actually cause an IPC call (or a round-trip over the wire, if the server runs on a different host).
In case the remote server has crashed or is unavailable, you'd likely receive a CO_E_OBJNOTCONNECTED error (could perhaps be a different error code, but certainly not S_OK).
Note though, doing an extra IPC call just to check if the server is available might be a costly operation, depending on your scenario.

A: No, you should always you QueryInterface.
Just because you've com an IUnknown interface it doesn't mean you can directly cast it to IDispatch. COM may have given you a proxy to the underlying object, which means that the pointer has nothing to do with IDispatch.
Likewise, an implementation may wrap an object that implements IDispatch and when you call QueryInterface it delegates to this object. Or you may have a pointer to a COM objects that delegates to an outer IUnknown.
So, basically, never directly cast, even if you think it'll work, because things may change over time. Calling QueryInterface is rarely a performance bottleneck and therefore not worth avoiding.


text:
Q: Sysrq magic key functionality check The first time my laptop froze, I used the Alt+SysRq REISUB and it worked.
Next time it happened - it didn't work.
I edited the 10-magic-sysrq.conf file's line kernel.sysrq = 176 (changed it to value 1).
I want to be sure that next time my laptop will freeze, the combination will work.. how do I check that Sysrq works?
(Shift + Alt (or) Alt Gr + SysRq didn't work, with and without Fn)
I run Ubuntu 14.04

A: Press your key combination while tail-ing your /var/log/syslog file. In my case, if I press Alt-SysRq-m (memory dump, see the list here) you should have some message appearing. In my case:
Feb  5 16:04:14 pern kernel: [281437.665719] SysRq : This sysrq operation is disabled.
Feb  5 16:04:22 pern kernel: [281445.815216] SysRq : This sysrq operation is disabled.

So I know that the kernel is receiving the message. If it's authorized, you should have a complete memory statistics in output.

A: This might damage your system!
I am not an expert. This might be entirely unsafe. But what I did, was:

*

*Boot the computer - so that nothing very important would be working in the background.

*Go to another TTY. E.g. to go to tty4 you can press Ctrl+Alt+F4. You don't need to log in.

*Simply press the Magic SysRq keys you wish to test.

*You should now see the normal SysRq output. If there are any errors you can memorize or take a photo of them.


text:
Q: Update a row in nedb I have the following data in nedb.
["UserId":"1446943507761","UserName":"xxx","link":"xxx.html","taskDone":"false","id":14,"_id":"fdaaTWSxloQZdYlT"]
["UserId":"1446943507761","UserName":"xxx","link":"xxx.html","taskDone":"false","id":1,"_id":"fzh2cedAXxT76GwB"]
["UserId":"1446943507761","UserName":"xxx","link":"xxx.html","taskDone":"false","id":0,"_id":"k4loE7XR5gioQk54"]

I am trying to update row with id 0 and set the value of taskDone to true. I use the following query to set the value to true
db.taskmap.update({ _id: "k4loE7XR5gioQk54", UserName:"xxx" }, { $set: { taskDone: "true"} }, function (err, numReplaced) {
    console.log("replaced---->" + numReplaced);
  });

It updates the value but it updates as a new row. It basically inserts a new row with same values except for the taskdone value as true. It does not delete the existing data. Hence in the final data table after update i get tow rows for id 0 with all values same except for the taskDone. I am not sure if i am doing anything wrong. It will be helpful if anybody can tell me a correct way of updating the value.

A: You should call db.loadDatabase(); again at the end of db.update(); to see, that no second row with the same _id: appears instead the specific doc gets directly updated.
Edit:
It appears that sometimes when you do db.update() the document that should be updated appears twice instead on the database. It happened to me when I was updating an entry in a list of servers, multiple entries with the modified values were appearing on the database. So to avoid this simply do the following. (I took the same code that was suggested as the answer)
db.update(
           { _id: "k4loE7XR5gioQk54", UserName:"xxx" },
           { $set: { taskDone: "true"} },
           {},// this argument was missing
           function (err, numReplaced) {
             console.log("replaced---->" + numReplaced);

             db.loadDatabase();
           }
           );

Doing this prevents this from happening. I tested it multiple times and the issue disappeared.

A: update wants four arguments
var Datastore = require('nedb');
var db = new Datastore();

db.insert(
[
  {
    "UserId":"1446943507761",
    "UserName":"xxx",
    "link":"xxx.html",
    "taskDone":"false",
    "id":14,
    "_id":"fdaaTWSxloQZdYlT"
  },
 {
    "UserId":"1446943507761",
    "UserName":"xxx",
    "link":"xxx.html",
    "taskDone":"false",
    "id":1,
    "_id":"fzh2cedAXxT76GwB"
 },
 {
    "UserId":"1446943507761",
    "UserName":"xxx",
    "link":"xxx.html",
    "taskDone":"false",
    "id":0,
    "_id":"k4loE7XR5gioQk54"
  }],
  function (err, newDocs) {
    // empty here
  }
  );
db.update(
           { _id: "k4loE7XR5gioQk54", UserName:"xxx" },
           { $set: { taskDone: "true"} },
           {},// this argument was missing
           function (err, numReplaced) {
             console.log("replaced---->" + numReplaced);
           }
           );
// should give the correct result now
db.find({}).exec(function (err, docs) {console.log(docs);});


text:
Q: How do you handle objects that need custom behavior, and need to exist as an entity in the database? For a simple example, assume your application sends out notifications to users when various events happen.  So in the database I might have the following tables:
TABLE Event
    EventId uniqueidentifier
    EventName varchar

TABLE User
    UserId uniqueidentifier
    Name varchar

TABLE EventSubscription
    EventUserId
    EventId
    UserId

The events themselves are generated by the program.  So there are hard-coded points in the application where an event instance is generated, and it needs to notify all the subscribed users.
So, the application itself doesn't edit the Event table, except during initial installation, and during an update where a new Event might be created.
At some point, when an event is generated, the application needs to lookup the Event and get a list of Users.  What's the best way to link the event in the source code to the event in the database?
Option 1:
Store the EventName in the program as a fixed constant, and look it up by name.
Option 2:
Store the EventId in the program as a static Guid, and look it up by ID.
Extra Credit
In other similar circumstances I may want to include custom behavior with the event type.  That is, I'll want subclasses of my Event entity class with different behaviors, and when I lookup an event, I want it to return an instance of my subclass.
For instance:
class Event
{
    public Guid Id { get;  }
    public Guid EventName { get;  }
    public ReadOnlyCollection<EventSubscription> EventSubscriptions { get; }
    public void NotifySubscribers()
    {
        foreach(var eventSubscription in EventSubscriptions)
        {
            eventSubscription.Notify();
        }
        this.OnSubscribersNotified();
    }
    public virtual void OnSubscribersNotified() {}
}

class WakingEvent : Event
{
    private readonly IWaker waker;
    public WakingEvent(IWaker waker)
    {
        if(waker == null) throw new ArgumentNullException("waker");
        this.waker = waker;
    }

    public override void OnSubscribersNotified()
    {
        this.waker.Wake();
        base.OnSubscribersNotified();
    }
}

So, that means I need to map WakingEvent to whatever key I'm using to look it up in the database.  Let's say that's the EventId.  Where do I store this relationship?  Does it go in the event repository class?  Should the WakingEvent know declare its own ID in a static member or method?
...and then, is this all backwards?  If all events have a subclass, then instead of retrieving events by ID, should I be asking my repository for the WakingEvent like this:
public T GetEvent<T>() where T : Event
{
    ... // what goes here?
}

I can't be the first one to tackle this.  What's the best practice?

A: No this is a common subsystem of larger applications, I call it Alerts and Notifications. The Event and Subscriber entities you mentioned are a starting point.

Here we have a simple diagram for the core of the system. You have an EventType, which just describes the various events that can be raised by the system. A subscription (which may have hanging off of it various subscription types, e.g. Email, SMS, etc.). When an event is generated, the system looks at that event's type and generates an alert for each subscription.
The tricky part is like you said, how to create a hierarchy of events. Event Type is what is known in the Object Modeling world as a Descriptor. Descriptors have an inherent knowledge of how to generate the type of object they are describing. That is, they act as object factories. We used an ORM trick where we stored the fully qualified name of the Event subclasses in the EventType table for each type. Thus when we had an instance of an EventType, it would return subclass of the Event via Reflection.
Most O/RMs support mapping a hierarchy of classes to a database (at least in the .NET world).
There is a lot more that could be said about implementing an alert and notification system. But I'll leave the discussion open for you to ask any follow-up questions.

A: I assume data in Event is truly static, not dynamic. If that's the case an enum could represent the event types. Have both the name and ID match that of the database if possible. At least 1 should match.
enum EventType
{
    Waking = 1, //it would be nice if both enum's name/int matched DB name/ID
    Sleeping,
    FooBar
}

To get the Event object pass an enum to a factory method.
IEvent getImp(EventType type)
{
    IEvent imp = null;

    switch (type)
    {
        case EventType.Waking:
            imp = new WakingEvent();
            break;
        case EventType.Sleeping:
            imp = new SleepingEvent();
            break;
        case EventType.FooBar:
            imp = new FooBarEvent();
            break;
    }
    return imp;
}

It may feel "wrong" because everything is hard-coded into the app. But this is assuming the behavior cannot be data driven. Random complex behavior cannot be defined as data unless the data itself is imperative code.


text:
Q: How to wait until jQuery effects have finished? How can I wait until an animation is finished in jQuery?
function foo() {
  $("#element").fadeOut();
}

I need the .fadeOut() to complete before foo() returns because the calling code expects the DOM to be free of #element.

A: All jQuery animation functions have a complete callback. Because they are asyncronous you can't wait for them, you have to use callbacks.
function foo() {
    $("#element").fadeOut(function() {
        // finished
    });
}

A: jQuery defines fadeout as: .fadeOut( [duration ] [, complete ] ), so using a callback should just work fine.

complete Type: Function() A function to call once the animation is
  complete, called once per matched element.

A: Use a callback function for this
function foo() {
  $("#element").fadeOut('slow', function(){
     // called when the element finishes fading out
  });
}

A: You can't prevent foo from returning before the animation finishes. You need to use the callback or promise/deferred pattern. Here's how a callback could work:
function bar() {
    foo(function() {
        // stuff to execute after foo()
    });
}

function foo(callback) {
    $("#element").fadeOut('speed', callback);
}

A: $('#element').fadeOut(1000, function() {
  // after 1 second do something

});


text:
Q: Pushing checkbox values from one array to another I have very little experience with JavaScript however I am attempting to write a function which pushes checkbox values from one array to another. I have written the following code, however it doesn't appear to work. Any help is appreciated.
var pages = document.forms['frm_list'].elements[ 'pages[]' ];
var selected = document.forms['frm_list'].elements[ 'selectedPages[]' ];
console.log(pages);
console.log(selected);

// using reference to sports obtained above
    for (var i=0, len=pages.length; i<len; i++) {
        pages[i].onclick = addPage;
    }

function addPage() {
    if ( this.checked ) {
        console.log(this);
        selected.push(pages);
        alert( this.value );
    } else {
        alert( this.value );
    }
}


text:
Q: What is the correct syntax for DELETE TOP statement? I want do delete only 1 row of the table "trader_inventory" where the "item_id" is 14 and "trader_id" is 1.
This is the code I've tried:
DELETE TOP 1
FROM trader_inventory
WHERE item_id = 14 AND trader_id = 1;

I also tried this to see if its only working with 1 condition:
DELETE TOP 1
FROM trader_inventory
WHERE item_id = 14;

I also tried with brackets at "TOP (1)"
SQL says Syntax-error at '1 FROM trader_inventory WHERE item_id = 14'
I can't explain why it's not working. I am trying to find a solution for 2 hours now. I hope someone can help me.
I saw that some people write their table names in []-brackets but that didn't work for me. SQL marked it as wrong.

A: In MySQL, you would use:
DELETE FROM trader_inventory
    WHERE item_id = 14 AND trader_id = 1
    LIMIT 1;

Here is a db<>fiddle.
There is no SELECT TOP in MySQL.  If you were using SQL Server (as suggested by the use of TOP), you can use a subquery (or CTE):
DELETE ti
    FROM (SELECT TOP (1) ti.*
          FROM trader_inventory ti
          WHERE item_id = 14 AND trader_id = 1
         ) ti;

Note:  SELECT TOP is usually used with an ORDER BY so the results are consistent.  This deletes an arbitrary row.  And if you run it on a table with the same rows, different rows could be chosen.


text:
Q: Microsoft Visio Page settings I used to use Visio years ago (2003 version), recently installed it again(2016 version) to make some technical drawings. But it has been frustrating to say the least.
What i wish is that the "page"  starts @ 0,0 meaning that the left top most pixel is 0.0 (like in paint). So that when i place my Rectangle @ 0,0 it ends up in the top right corner touching both borders...instead i get this :

Is there a way to adjust this?
And will the grid also adjust to start there? so i won't get this weird half grid row in front of it? like so:

I honestly don't get it that there is no default template for something as simple as this :|

A: What I wish is that the "page" starts @ 0,0 meaning that the left top most pixel is 0.0

Change the position of the ruler zero point
By default, the zero point is the lower-left corner of the drawing
  page. Do any of the following:

*

*To change the position of the zero point on both rulers, hold down the CTRL key and, from the intersection of the two rulers, drag
  to where you want the new zero point.

*To change the position on one ruler, hold down the CTRL key and drag from the ruler.

*To return the zero point to the lower-left corner of the page, double-click the intersection of the two rulers.

Source Change the ruler measurement units in Visio - Visio

And will the grid also adjust to start there?

Change the origin of the grid
The grid origin is set to the same position as the ruler zero point.
  If you move the ruler zero point, the grid origin also moves. You can,
  however, set the grid origin independently from the ruler zero point.

*

*On the View tab, in the Show group, click the Ruler & Grid Dialog Box Launcher.

*Under Grid origin, enter x (horizontal) and y (vertical) coordinates for the point from which you want the grid to originate,
  and then click OK.

Source Show, hide, or change the grid in Visio - Visio


text:
Q: Normalizing nested responses in ngrx I am fairly new to ngrx and I am not sure what the best practices are regarding normalizing nested objects.
Let say the store is defined as follow:
export interface User {
   id: string;
   name: string;
   surname: string;
}

export interface Transaction {
    id: string;
    amount: number;
    owners: []
}

export interface TransactionState {
    ids: string[];
    entities: { [id: string]: Transaction }
}

export interface UserState {
   ids: string[],
   entities: { [id: string]: User }
}

export interface CapitalState {
  transactions: TransactionState;
  users: UserState;
}

The first way I thought of implementing this is, is in the effect where the data is normalized and then two actions are dispatched to update the users and the transactions
@Effect()
transactions$ = this.actions$.pipe(
   ofType(fromTransactionsActions.TransactionsActionTypes.LoadTransactions),
   concatMap((action: fromTransactionsActions.LoadTransactions) =>
      this.transactionsService.loadTransactions(action.payload).pipe(
         map((tranactions: TransactionView) => {
             //Normalize Data
             return [ //Dispatch Transactions Load Success
                      //Dispatch Users Load Success];
         }),
         catchError(error => of(new fromTransactionsActions.TransactionsLoadFailure("")))
        ))
    )

The second is to dispatch the normalized data in one Transaction Load Success action and then to update the state from there.
export function reducer(state = initialState, action: TransactionsActions): CapitalState {
    switch (action.type) {
        case TransactionsActionTypes.AllotShareCapitalSuccess:
            return {
                ...state,
                transactions: { ...state.transactions, ...action.payload.entities.transactions },
                users: { ...state.users, ...action.payload.entities.users },
                error: ''
            };

I am not sure if these are best practices or if I am missing something. Are any of these good ways to do this? Are there better ways?


text:
Q: Fail to send message from popup.js in Chrome extension to background.js I hope to send message from popup.js to background.js. When I click the button, the message will send to the background.js, and it will open a new tab for my specify website. I have check the popup.js and background.js and found that both of them are ok, only just can't send the message from popup.js to background.js.
popup.js
window.onload=function()
{
     document.getElementById("submit").onclick=function()
  {
     chrome.extension.sendMessage({command:"start"});
  }
}

background.js
chrome.extension.onMessage.addListener(
    function(request,sender,sendResponse)
    {
        switch(request.command)
        {
            case "command":
                openTab();
            break;
        }

        return true;
    }
);

var openTab=function()
{
    chrome.windows.create
    (
        {
            url:"http://www.baidu.com",
            tabId:1
        }

    );
};

A: There's a little error in your code: in the function you use to receive the message in the background.js script you are using the switch statement on the variable request.command, but then, inside it, you're checking for case "command", when you should check for case "start" instead, because you're sending a message which is {command: "start"}.
The message is received, but checked against a string that doesn't match, and obviously your openTab() function will never be called.
To solve this issue you can either:

*

*Change the message you're sending from popup.js, like this:
chrome.runtime.sendMessage({command: "command"});

*Or change the case statement in your background.js script:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    switch(request.command) {
        case "start":
            openTab();
            break;
    }

    return true;
});

Anyway, I strongly recommend you to use the chrome.runtime API instead of chrome.extension, which is outdated.


text:
Q: Why is LB_GETITEMDATA returning 0? I'm trying to create a program that suspends and resumes processes, it creates a listbox with text strings of all the running processes on the system, but when I click the suspend button to suspend a process I try to send WM_GETITEMDATA for the currently selected item in the listbox but the value returns 0. I expected the return value to be a string with the text of the lParam of LB_ADDSTRING.
I think this has something to do with the scope of the function I use LB_ADDSTRING in because when I use LB_GETITEMDATA right after LB_ADDSTRING it properly returns the value of the lParam of LB_ADDSTRING. Since I am unsure of where my error lies I'm adding the full source code to the bottom of my question. Here is the function I use to add strings to the listbox:
void RefreshList()
{
    SendMessage (hlist, LB_RESETCONTENT, 0, 0);
    HANDLE hSnapShot3 = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
    PROCESSENTRY32 pEntry3;
    pEntry3.dwSize = sizeof (pEntry3);
    BOOL hRes3 = Process32First(hSnapShot3, &pEntry3);
    int listitem = 0;
    while (hRes3)
    {

        SendMessage (hlist, LB_ADDSTRING, 0, (LPARAM)pEntry3.szExeFile);
        SendMessage (hlist, LB_SETITEMDATA, listitem, (LPARAM)pEntry3.szExeFile);
        SendMessage(hlist, LB_GETITEMDATA, listitem, NULL);
        MessageBox(0,0,0,0);
        listitem++;
        hRes3 = Process32Next(hSnapShot3, &pEntry3);
    }
    CloseHandle(hSnapShot3);
}

Here is the part of the windows procedure where I catch clicks to my context menu and try to send the message LB_GETITEMDATA:
    case WM_COMMAND:
        if (HIWORD(wParam) == 0 && LOWORD(wParam) == 1)
        {
        selection = SendMessage(hlist, LB_GETCURSEL, 0, 0);
        LRESULT selectionname = SendMessage(hlist, LB_GETITEMDATA, selection, NULL);
        }

here is the full code
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <process.h>
#include <Tlhelp32.h>
#include <winbase.h>
#include <string.h>
#include <stdio.h>
#include <windowsx.h>
#define list1 1
#define button1 2
int selection;
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK ProcessListProc (HWND, UINT, WPARAM, LPARAM);
char szClassName[ ] = "mainwindowclass";
HWND hlist;
HWND hwnd;
void RefreshList()
{
    SendMessage (hlist, LB_RESETCONTENT, 0, 0);
    HANDLE hSnapShot3 = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
    PROCESSENTRY32 pEntry3;
    pEntry3.dwSize = sizeof (pEntry3);
    BOOL hRes3 = Process32First(hSnapShot3, &pEntry3);
    int listitem = 0;
    while (hRes3)
    {

        SendMessage (hlist, LB_ADDSTRING, 0, (LPARAM)pEntry3.szExeFile);
        SendMessage (hlist, LB_SETITEMDATA, listitem, (LPARAM)pEntry3.szExeFile);
        SendMessage(hlist, LB_GETITEMDATA, listitem, NULL);
        MessageBox(0,0,0,0);
        listitem++;
        hRes3 = Process32Next(hSnapShot3, &pEntry3);
    }
    CloseHandle(hSnapShot3);
}

int SuspendProcess(TCHAR processname)
{
    int doublePID = 0;
    DWORD pidtoacton;
    DWORD Result;
    HANDLE hSnapShot3 = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
    PROCESSENTRY32 pEntry3;
    pEntry3.dwSize = sizeof (pEntry3);
    BOOL hRes3 = Process32First(hSnapShot3, &pEntry3);
    while (hRes3)
    {
            if (processname == pEntry3.szExeFile);
            {
                if (doublePID != 0)
                {
                    MessageBox (NULL, "2 processes of the same type detected, support not yet implimented!", NULL, MB_OK);
                }
            pidtoacton = pEntry3.th32ProcessID;
            doublePID++;
            }
    hRes3 = Process32Next(hSnapShot3, &pEntry3);
    }
    HANDLE tsnap = CreateToolhelp32Snapshot (TH32CS_SNAPTHREAD, 0);
    THREADENTRY32 tentry;
    tentry.dwSize = sizeof (tentry);
    BOOL CRec = Thread32First(tsnap, &tentry);
    while (CRec)
    {
        if (tentry.th32OwnerProcessID == pidtoacton)
     {
         HANDLE handletoacton = OpenThread(2, 0, tentry.th32ThreadID);
         Result = SuspendThread(handletoacton);
         if (Result == -1)
         {
             MessageBox (NULL, "An unknown error has occured when attempting to suspend a thread in the process", NULL, MB_OK);
         }
     }
     CRec = Thread32Next(tsnap, &tentry);
    }
    CloseHandle(tsnap);
}

    MSG messages;
int WINAPI WinMain (HINSTANCE hThisInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR lpszArgument,
                    int nCmdShow)
{
          /* Here messages to the application are saved */
    WNDCLASSEX wincl;        /* Data structure for the windowclass */
    MSG messages2;

    /* The Window structure */
    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = szClassName;
    wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
    wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
    wincl.cbSize = sizeof (WNDCLASSEX);

    /* Use default icon and mouse-pointer */
    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;                 /* No menu */
    wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
    wincl.cbWndExtra = 0;                      /* structure or the window instance */
    /* Use Windows's default colour as the background of the window */
    wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;

    /* Register the window class, and if it fails quit the program */
    if (!RegisterClassEx (&wincl))
        return 0;
    /* Register the window class, and if it fails quit the program */

    /* The class is registered, let's create the program*/
    hwnd = CreateWindowEx (
               0,                   /* Extended possibilites for variation */
               szClassName,         /* Classname */
               "Process suspender",       /* Title Text */
               WS_OVERLAPPEDWINDOW, /* default window */
               CW_USEDEFAULT,       /* Windows decides the position */
               CW_USEDEFAULT,       /* where the window ends up on the screen */
               350,                 /* The programs width */
               650,                 /* and height in pixels */
               HWND_DESKTOP,        /* The window is a child-window to desktop */
               NULL,                /* No menu */
               hThisInstance,       /* Program Instance handler */
               NULL                 /* No Window Creation data */
           );

    hlist = CreateWindowEx (0,TEXT("listbox"),NULL,WS_CHILD|WS_VISIBLE|LBS_NOTIFY|LBS_STANDARD|LBS_HASSTRINGS,10,15,320,500,hwnd,(HMENU)list1,NULL,NULL);
    RefreshList();

    HWND hWndButton = CreateWindowEx(NULL,
                                     TEXT("button"),
                                     TEXT("refresh"),
                                     WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON,
                                     130,
                                     535,
                                     80,
                                     30,
                                     hwnd,
                                     (HMENU)button1,
                                     NULL,
                                     NULL);

    /* Make the window visible on the screen */
    ShowWindow (hwnd, nCmdShow);

    /* Run the message loop. It will run until GetMessage() returns 0 */
    while (GetMessage (&messages, NULL, 0, 0))
    {
        /* Translate virtual-key messages into character messages */
        TranslateMessage(&messages);
        /* Send message to WindowProcedure */
        DispatchMessage(&messages);
    }

    /* The program return-value is 0 - The value that PostQuitMessage() gave */
    return messages.wParam;
}

/*  This function is called by the Windows function DispatchMessage()  */

LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)                  /* handle the messages */
    {
    case WM_CONTEXTMENU:
    {
        if ((HWND)wParam == hlist)
        {
         INPUT clickin;
         clickin.type = 0;
         clickin.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
         clickin.mi.dx = 0;
         clickin.mi.dy = 0;
         clickin.mi.mouseData = 0;
         clickin.mi.time = 0;
         clickin.mi.dwExtraInfo = 0;
         SendInput(1,&clickin,sizeof(clickin));
         clickin.mi.dwFlags = MOUSEEVENTF_LEFTUP;
         SendInput(1,&clickin,sizeof(clickin));
         GetMessage (&messages, NULL, 0, 0);
         TranslateMessage(&messages);
         DispatchMessage(&messages);
         int xPos = GET_X_LPARAM(lParam);
         int yPos = GET_Y_LPARAM(lParam);
         HMENU rightclickmenu = CreatePopupMenu();
         InsertMenu(rightclickmenu, 1, MF_BYCOMMAND | MF_STRING | MF_ENABLED, 1, "Suspend");
         InsertMenu(rightclickmenu, 0, MF_BYCOMMAND | MF_STRING | MF_ENABLED, 0, "Resume");
         TrackPopupMenu(rightclickmenu, TPM_TOPALIGN | TPM_LEFTALIGN, xPos, yPos, 0, hwnd, NULL);
        }
        break;
    }
    case WM_DESTROY:
        PostQuitMessage (0);       /* send a WM_QUIT to the message queue */
        break;
    case WM_COMMAND:
        if (HIWORD(wParam) == 0 && LOWORD(wParam) == 1)
        {
        selection = SendMessage(hlist, LB_GETCURSEL, 0, 0);
        LRESULT selectionname = SendMessage(hlist, LB_GETITEMDATA, selection, NULL);
        }
        switch (wParam)
        {
        case button1:
            RefreshList();
            break;
        }
    default:
        return DefWindowProc (hwnd, message, wParam, lParam);
    }
    return 0;
}

A: As @JonathanPotter mentions in his comment, you need to use LB_GETTEXT to retrieve the text of an item.
If you were going to use LB_SETITEMDATA to store, say, the process-id for each item, it is good practice to always use the index returned by the LB_ADDSTRING and not assume that the index will always increment by one, this will work for sorted and unsorted list boxes:
listitem = SendMessage(hlist, LB_ADDSTRING, 0, (LPARAM)pEntry3.szExeFile);
SendMessage(hlist, LB_SETITEMDATA, listitem, (LPARAM)pEntry3.th32ProcessID);


text:
Q: Gradle - run mongoDB scripts In our gradle script we run some mysql scripts with gradle using jdbc.
My question: is there any similar way to execute scripts for mongo through gradle?
Here  is how we execute mysql scripts thorugh gradle:
def props = [user: mySqlLoginName, password: mySqlPassword, allowMultiQueries: 'true'] as Properties
def driver = 'com.mysql.jdbc.Driver'
def sql = Sql.newInstance(mySqlUrl, props, driver)
File allModification = file("src/main/database/updateScript.sql")
String fileContents = allModification.text
println "\nUpdating mySql"
sql.execute fileContents

thanks!

A: If the code above is really outside a task declaration, it means that you are running this query for every single Gradle invocation, which is probably not what you want. Anyway, the code is using Groovy's Sql class and no particular Gradle features. Likewise, you can use any Mongo client library to access Mongo in a similar way.
You'll need to declare a dependency on the Mongo client library in a buildscript block. This will allow Gradle to download the dependency and make it available to the build script. For details on how to declare a buildscript block, see the Gradle User Guide.


text:
Q: Background: url() não vai Quero adicionar uma imagem na minha pagina, ja tentei de duas formas, com background: url(img/menina.png); e background-image: url(img/menina.png);
A foto esta na pagina correta, a foto esta no formato correto, o css esta linkado com o html
<link rel="stylesheet" href="css/master.css" />

<title>Criativa</title>

.header {
width: 150px;;
background: url(img/menina.png);
background-image: url(img/menina.png);
background-position: center;
background-size: cover;
}

A: Acredito que você precisa colocar valores no width e height quer permitam que a imagem apareça, como no exemplo que adicionei experimente remover o atributo height ela some.

.header {
width: 150px;
height: 150px;
background-image: url(https://www.conversion.com.br/wp-content/uploads/2019/06/google-icone.png);
background-position: center;
background-size: cover;
}


text:
Q: How to use s2_mask() function in R to mask clouds in Sentinel 2 image? I want to use the toolbox sen2r to process Sentinel 2 L2A data in R. I have already manually downloaded the images in .SAFE format.
I have used the s2_translate() to convert .SAFE format to geotif:
in_dir <- "D:/data/s2"
out_dir <-"D:/s2_geotifs"

## translate .safe to geotif

s2_example <- file.path(
  in_dir,
  "S2B_MSIL2A_20200525T104619_N0214_R051_T31UFT_20200525T133932.SAFE")

s2_raster_dir <- s2_translate(s2_example,
                              format="GTiff",
                              outdir = out_dir)

This results is a raster brick with 11 layers, all corresponding to the optical bands of sentinel 2 as far as i can see.
Now i want to apply the s2_mask function (specifically to band 4 and 8 because i want to make NDVI) but the documentation for the code says you need the SCL product as input. The SCL product are bands with the classified cloud pixels used for masking. If i load the .SAFE image into SNAP e.g. i can see the SCL products. However i cannot find the SCL in my s2_translate() output, or in the original .SAFE for that matter.
According to the documentation the input should be as follows:

So the issue is that i cannot find the SCL product anywhere. I have applied s2_translate as required.

A: By default, s2_translate only generates BOA output. I think you need to explicitly generate also the SCL file from the SAFE using again s2_translate, using something on the lines:
s2_translate(s2_example,
             prod_type = "SCL",
             format="GTiff",
             outdir = out_dir)

see documentation here:
http://sen2r.ranghetti.info/reference/s2_translate.html
http://sen2r.ranghetti.info/reference/safe_shortname.html


text:
Q: wpdb update query not working I've made an email script that should update as soon as wp_mail has result. For some reason my value won't update. Have I missed something? I am receiving the mail so the wp_mail works.
Cheers!
$email_result = wp_mail( $to, $subject, $message, $headers );

if( $email_result ){//wp_mail() processed the request successfully
    global $wpdb;
    $table_name = $wpdb->prefix . "wpsc_coupon_codes";
    $coupon_id = $ereminder->ID;

$ereminders = $wpdb->query( $wpdb->prepare("
    UPDATE *
    FROM $table_name
    SET reminder = 1
    WHERE ID = $coupon_id
") );

}

A: try this
UPDATE  $table_name
SET reminer = 1
WHERE ID = $coupon_id

A: We could use $wpdb->update, like this:
 global $wpdb;
 $table_name = $wpdb->prefix.'your_table_name';
 $data_update = array('row_name_1' => $row_data_1 ,'row_name_2' => $row_data_2);
 $data_where = array('row_name' => $row_data);
 $wpdb->update($table_name , $data_update, $data_where);

A: You may change instead of (UPDATE * FROM)
$ereminders = $wpdb->query($wpdb->prepare("UPDATE $table_name SET reminer='1' WHERE ID=$coupon_id"));

and use no break.
Thank you.

A: Example of mine that is working:
$result = $wpdb->update(
    $wpdb->prefix .'sae_calendar',
    array(
        'year' => $year,
        'quarter' => $quarter,
        'start_date' => $start_date,
        'end_date' => $end_date,
        'reservation_start_date' => $reservation_start_date,
        'reservation_end_date' => $reservation_end_date
    ),
    array(
        "id" => $id
    )
);

A: Try This:
$wpdb->update( $table_name, array( 'reminder' => 1),array('ID'=>$coupon_id));

A: <?php
  global $wpdb;
    if(isset($_POST['progress'])){
    $table=t_test;
    $data=array('client_development'=>$_POST['Progress']);
    $where=array('p_id'=>$_SESSION['id']);
    $format=("%d");
    $whereFormat=("%d");
    $result4=$wpdb->UPDATE($table,$data,$where,$format,$whereFormat);
  }
?>
<form method="post">
  <input type="text" name="Progress">
  <input type="submit" name="progress" value="Prog%">
</form>
<?php
if(isset($_POST['progress'])){
$table=t_test;
    $data=array('client_development'=>$_POST['Progress']);
    $where=array('p_id'=>$_SESSION['id']);
    $format=("%d");
    $whereFormat=("%d");
    $result4=$wpdb->UPDATE($table,$data,$where,$format,$whereFormat);
}
?>
<form method="post">
  <input type="text" name="Progress">
  <input type="submit" name="progress" value="Prog%">
</form>


text:
Q: Trigger Duplicate CSV am trying to upload a CSV file / insert a bulk of records using the import wizard. In short I would like to keep the latest record, in case if duplicates are found. Duplicates record are a combination of First name, Last name and title
For example if my CSV file looks like the following:
James,Wistler,34,New York,Married
James,Wistler,34,London,Married
....
....

James,Wistler,34,New York,Divorced
This should only keep in my org: James,Wistler,34,New York,Divorced
I have been trying to write a trigger before an update / insert but so far no success Here is my trigger code: (The code is not yet finished (only filering with Firstname), I am having a problem deleting found duplicate in my CSV ) Any hints. Thanks for reading!
trigger CheckDuplicateInsert on Customer__c(before insert,before update){

Map <String, Customer__c> customerFirstName = new Map<String,Customer__c>();
list <Customer__c> CustomerList = Trigger.new;

for (Customer__c newCustomer : CustomerList)
{
    if ((newCustomer.First_Name__c != null) && System.Trigger.isInsert )
    {
        if (customerFirstName.containsKey(newCustomer.First_Name__c) )
        //remove the duplicate from the map
        customerFirstName.remove(newCustomer.First_Name__c);
        //end of the if clause
    // add this stage we dont have any duplicate, so lets add a new customer
    customerFirstName.put(newCustomer.First_Name__c , newCustomer);
    }
    else if ((System.Trigger.oldMap.get(newCustomer.id)!= null)&&newCustomer.First_Name__c !=System.Trigger.oldMap.get(newCustomer.id).First_Name__c )
    {//field is being updated, lets mark it with UPDATED for tracking
    newCustomer.First_Name__c=newCustomer.First_Name__c+'UPDATED';
    customerFirstName.put(newCustomer.First_Name__c , newCustomer);
    }

 }

for (Customer__c customer : [SELECT First_Name__c FROM Customer__c WHERE First_Name__c IN  :customerFirstName.KeySet()])
{
    if (customer.First_Name__c!=null)
    {
        Customer__c newCustomer=customerFirstName.get(customer.First_Name__c);
        newCustomer.First_Name__c=Customer.First_Name__c+'EXIST_DB';
    }
}
}

A: Purely non-SF solution would be to sort them & deduplicate in Excel for example ;)

Good news - you don't need a trigger. Bad news - you might have to ditch the import wizard and start using Data Loader. The solution is pretty long and looks scary but once you get the hang of it it should start to make more sense and be easier to maintain in future than writing code.
You can download the Data Loader in setup area of your Production org and here's some basic info about the tool.
Anyway.

*

*I'd make a new text field on your Contact, call it "unique key" or something and mark it as External Id. If you have never used ext. ids - Jeff Douglas has a good post about them.

*You might have to populate the field on your existing data before proceeding. Easiest would be to export all Contacts where it's blank (from a report for example), fill it in with some Excel formulas and import back.

*If you want, you can even write a workflow rule to handle the generation of the unique key. This might help you when Mrs. Jane Doe gets married and becomes Jane Bloggs and also will make previous point easier (you'd just import Contacts without changes, just "touching" them and the workflow will fire). Something like

*

*condition: ISBLANK(Unique_key__c) || ISCHANGED(FirstName) || ISCHANGED(LastName) || ISCHANGED(Title)

*new value: Title + FirstName + ' ' + LastName

*Almost there. Fire Data Loader and prepare an upsert job (because we want to insert some records and when duplicate is found - update them instead).

*My only concern is what happens when what's effectively same row will appear more than once in 1 "batch" of records sent to SF like in your example. Upsert will not know which value is valid (it's like setting x = 7; and x = 5; in same save to DB) and will decide to fail these rows. So you might have to tweak the amount of records in a batch in Data Loader's settings.


text:
Q: vector, matrix multiplication and sum I'm going around in circles with all the options in numpy/scipy. Dot product, multiply, matmul, tensordot, einsum etc.
I want to multiply a 1d vector with a 2d matrix (which will be sparse csr) and sum the result so I have a 1d vector
eg
oneDarray = np.array([1, 2, 3])
matrix = np.array([[1,2,3],[4,5,6],[7,8,9]])

# multiple and sum the oneDarray against the rows of the matrix
#          eg 1*1 + 1*2 + 1*3 = 6, 2*4 + 2*5 + 2*6 = 30, 3*7 + 3*8 + 3*9 = 42
so output we be [6,30,53]

# multiple and sum the oneDarray against the columns of the matrix
#          eg 1*1 + 1*4 + 1*7 = 28, 2*2 + 2*5 + 2*8 = 30, 3*3 + 3*6 + 3*9 = 486
so output we be [28,30,486]

Any help would be greatly appreciated.

A: # 1*1 + 1*2 + 1*3 = 6, 2*4 + 2*5 + 2*6 = 30, 3*7 + 3*8 + 3*9 = 42

1*1 + 1*2 + 1*3 = 6
2*4 + 2*5 + 2*6 = 30,
3*7 + 3*8 + 3*9 = 42

1*(1 + 2 + 3) = 6,
2*(4 + 5 + 6) = 30,
3*(7 + 8 + 9) = 42

So this can calculated in several ways:
In [92]: oneDarray*(matrix.sum(axis=1))
Out[92]: array([ 6, 30, 72])

In [93]: np.einsum('i,ij->i', oneDarray, matrix)
Out[93]: array([ 6, 30, 72])

In [94]: (oneDarray[:,None]*matrix).sum(axis=1)
Out[94]: array([ 6, 30, 72])

It doesn't fit the usual dot (matrix) product, which would have an einsum expression like ij,j->i (wrong index is summed).
The other expression is (your values are wrong, except the middle one):
In [95]: matrix.sum(axis=0)*oneDarray
Out[95]: array([12, 30, 54])

If the matrix is sparse csr:
In [96]: M = sparse.csr_matrix(matrix)
In [97]: M
Out[97]:
<3x3 sparse matrix of type '<class 'numpy.int64'>'
    with 9 stored elements in Compressed Sparse Row format>
In [98]: M.sum(axis=1)
Out[98]:
matrix([[ 6],
        [15],
        [24]])
In [99]: M.sum(axis=1).A1*oneDarray
Out[99]: array([ 6, 30, 72])

The sum is a (3,1) np.matrix.  A1 flattens it into a 1d ndarray, making the element wise multiplication easier.
In [103]: M.sum(axis=0)
Out[103]: matrix([[12, 15, 18]], dtype=int64)
In [104]: M.sum(axis=0).A1*oneDarray
Out[104]: array([12, 30, 54], dtype=int64)
In [116]: np.multiply(M.sum(0), oneDarray)
Out[116]: matrix([[12, 30, 54]], dtype=int64)

A: Well you have some calculation error in your question.The first one will result in [6, 30, 72] and the second part will result in [12, 30, 54]. If I understand correctly, the first one can be solved with
np.sum(oneDarray * matrix.T, axis=0)

and the second part with
np.sum(np.multiply(matrix, oneDarray), axis=0)


text:
Q: Tagging / Entity extraction using an entity list I'm looking for a good solution to extract entities from a text.
In my case, entities are movie titles (so they could be quite long strings) and I have them stored in a database.
What could be a good way to do this ? Is there any already developed software to perform this kind of task ?
I've seen nltk, but what I need is way less complex: Given a (huge) list of strings, identify them in the input text.
Thanks!


text:
Q: How can we clear kendo UI Grid for angular 2 when we change paging of grid We had prepared one demo of Kendo UI Grid binding with angular 2.
We had used Custom paging with pagesize of 250 in this demo.
When we move to the next page in Grid, the memory usage increses every time.
At some point scrolling gets slower and application also gets crashed.
So is there any way to clear grid data when i move to next or pervious page?
Or any other way to get better performance in grid with large amount of pagesize more then 500.
we have also tried this.gridData.next([])  to clear grid data. But .next() funtion is not supporting for Observable.
Can please provide demo for it.
Following is the code we are using to bind grid and custom paging.
Code in app.module.ts file.
public query(config: any): void {
    this.getTask(config)
        .subscribe(x => super.next(x));

}
private getTask(config: any): Observable<GridDataResult> {
    let params = new URLSearchParams();
    params.set('Skip', config.skip);
    params.set('Take', config.take);

    this.http.get(`${this.TaskCount_URL}`)
        .map(response => response.json())
        .subscribe(result => this.total = result);

    return this.http.get(`${this.TaskDetail_URL}`, { search: params })
        .map(this.extractData)
        .map(response => (<GridDataResult>{
            data: response,
            total: this.total
        }));
}

Code in app.Component.ts file
public onNextClick(event: any) {
    this.skip = this.skip + 1000;
    this.gridData = this.service;
    this.service.query({ skip: this.skip, take: this.pageSize, sort: this.sort });
}

A: Change your query function slightly.
From this.
public query(config: any): void {
    this.getTask(config)
        .subscribe(x => super.next(x));

}

To this.
public query(config: any): void {
    super.next(data: [], total: 0);
    this.getTask(config)
        .subscribe(x => super.next(x));
}

This will set the grid to nothing while its waiting for the next page of data.
The other caveat is to make sure you never send an error to the Behaviour Subject. If you do, it will stop processing anything else. Best practice is probably along the lines for this.
public query(config: any): void {
    super.next(data: [], total: 0);
    this.getTask(config)
        .subscribe(
            x => super.next(x),
            err => {
                //notify user of error some other way.
                alert("Error retrieving grid data");
                super.next(data: [], total: 0);
            }
        );
}


text:
Q: Strip Specific Word in VBA for each chart So I loop through each chart using the following code:
Sub LoopThroughCharts()

Dim sht As Worksheet
Dim CurrentSheet As Worksheet
Dim cht As ChartObject

Application.ScreenUpdating = False
Application.EnableEvents = False

Set CurrentSheet = ActiveSheet

For Each sht In ActiveWorkbook.Worksheets
  For Each cht In sht.ChartObjects
    cht.Activate

    'Do something with the chart...
    ActiveChart.Legend.Select
    Selection.Left = 108.499
    Selection.Width = 405.5
    Selection.Height = 36.248
    Selection.Top = 201.85
    Selection.Left = 63.499
    Selection.Top = 330.85
    ActiveChart.PlotArea.Select
    Selection.Height = 246.69
    Selection.Width = 445.028

  Next cht
Next sht

CurrentSheet.Activate
Application.EnableEvents = True

This makes each chart a specific size and I was thinking that I can modify the following vba code to strip the word "Test: out of Test: abc the legend and then the resulting legend would be abc. I think that I can modify the following code, but I am not sure how to to do this. :
For i = ActiveChart.SeriesCollection.Count To 1 Step -1
If ActiveChart.Legend(i)= "Test: *" Then
ActiveChart.Legend(i) **what I think needs to be modified**
End If
Next i

A: In order to strip a specific word, you can

*

*Replace the prefix using the function Replace()

*Take the sub string using the function Mid()
Here's the demo code
Sub stripDemo()
    Dim str As String
    str = "Test: my legend"
    Debug.Print Replace(str, "Test: ", "")
    Debug.Print Mid(str, 7, Len(str) - 6)
End Sub

EDIT
So when the code is applied to chart, it becomes :
For Each sht In ActiveWorkbook.Worksheets
  For Each cht In sht.ChartObjects
    cht.Activate
    ' iterate the series collection
    ' replace the prefixe "Tests: " with ""
    For Each sr In ActiveChart.SeriesCollection
      If Len(sr.Name) > 6 And Left(sr.Name, 6) = "Test: " Then
        sr.Name = Replace(sr.Name, "Test: ", "")
      End If
    Next sr
  Next cht
Next sht


text:
Q: Can we use { to declare e variable variable? I have a piece of code which I a trying to shorten using variable variable, wanted to check if this is a valid code.
Original code:
$town = ( $_POST['town'] ) ;
$county = ($_POST['county'] ) ;

// Update town user meta
if ( !empty( $town ) )
    update_user_meta( $user_id, 'town', $town);

// Delete town user meta
else
    delete_user_meta( $user_id, 'town' );

//Update county user meta
if ( !empty( $county ) )
    update_user_meta( $user_id, 'county', $county);

// Delete county user meta
else
    delete_user_meta( $user_id, 'county' );

Shortened code :
$fields = array("town","county");
foreach ($fields as $field) {
${$field} = $_POST[$field];
    if ( !empty( $field ) ) { update_user_meta( $user_id, "$field", ${$field}); } else { delete_user_meta( $user_id, "$field" ); }
}

Without the shortened code, we can accommodate more variables, which is the goal.
Thanks for your time.
EDIT
Special thanks to all the negative voters. My last post here got 7 negative votes, here its 2 only so far. Com'n guys, break my last record.
On a more serious note, there must be a stricter policy by Stackoverflow about negative voting and there must be a scrutiny on such votes by other people - I feel, random mass negative votes like these can be highly demoralizing.

A: You already have an array you can use:
foreach( $_POST as $field => $value ){
  if ( !empty( $value ) ) update_user_meta( $user_id, $field, $value);
}

However, you need to run validation on the POST data and make sure you guard against sql injection

A: You are probably looking for something like
foreach($_POST as $key => $value){
   if ( !empty( $value) ) { update_user_meta( $user_id, $key, $value); }
   else { delete_user_meta( $user_id, $key); }
}

Or something along those lines.
EDIT: But if you really need to define a list of fields you could do
$fields = array("town","county");

foreach($fields as $field){
       if ( !empty($_POST[$field]) ) { update_user_meta( $user_id, $field, $_POST[$field]); }
       else { delete_user_meta( $user_id, $field ); }
}


text:
Q: Adding attributes to CSV-file using PyQGIS I am new to PyQGIS and I want to add one more field in my existed table. Here is my code:
pointLayer = QgsVectorLayer(uri, 'my_layer', 'delimitedtext')
pointLayer.dataProvider().addAttributes([QgsField("new1", QVariant.Double)])
pointLayer.updateFields()

However, there's no difference if I print the names of the field before and after adding attributes respectively.

I don't know how to fix the problem and the code does not have any error.

A: TLDR: you can't if using "delimitedtext" option to open CSV, you can if using "ogr" to open the layer. The 2nd choice restrict what you can do when opening compared to the 1st option and you will be limited by what ogr can do (see driver info behind QGIS scene https://gdal.org/drivers/vector/csv.html#creation-issues). Last option: do not choose CSV to add fields as it can't keep types in columns when you reopen. Choose another format and export to CSV if you really have the requirements
Option 1:
Proof to show you can't edit using "delimitedtext" layer by running below code after selecting your CSV layer:
layer = iface.activeLayer()
cap = layer.dataProvider().capabilities()
if cap & QgsVectorDataProvider.AddAttributes:
    print('Allows addition of new attributes (fields)')
else:
    print('Do not allows addition of new attributes (fields)')

You can also use a version to summarize all capabilities by running
layer = iface.activeLayer()
print(layer.dataProvider().capabilitiesString())

For a shp, it will return Add Features, Delete Features, Change Attribute Values, Add Attributes, Delete Attributes, Rename Attributes, Create Spatial Index, Create Attribute Indexes, Fast Access to Features at ID, Change Geometries
For a delimited txt, it will return Create Spatial Index, Fast Access to Features at ID, Curved Geometries. In 2nd case, as Add Attributes is missing you interpret it's not possible.
You can test other properties related to the provider capabilities using list from https://qgis.org/api/classQgsVectorDataProvider.html#a1a360c9e78933697b9f9be334cfcaf7a
Option 2:
If you really want to edit using ogr, the recipe below works
pointLayer = QgsVectorLayer('/tmp/test1.csv|layername=test1|option:X_POSSIBLE_NAMES=X|option:Y_POSSIBLE_NAMES=Y', 'my_layer', 'ogr')
pointLayer.dataProvider().addAttributes([QgsField("new1", QVariant.Double)])
pointLayer.updateFields()

Content of file test1.csv
point_id,X,Y,ele,time,Ds,len
"371",0.6644, 45.89,486,2020/04/07 09:58:07,0,0
"372",1.2697,44.38,486.2,2020/04/07 09:58:08,8.544,8.54


text:
Q: Check status of Meteor.js sync with server meteor.js uses magic (ie: websockets) to sync the local db with the server. I have been searching for, but sofar have not been able to find, a way to see the status of the synchronisation. I would like the be able to check if a update for instance has been synced to the server. How could I do that?
thanks,
Paul

A: The callback associated with an insert/update/remove will be invoked with an error as its first argument. If error is defined, the server failed to make the modification. If it isn't defined, the modification succeeded.
Comments.update(commentId, {$set: {message: newMessage}}, function(error) {
  if (error) {
    console.log('it failed!');
  } else {
    console.log('it worked!');
  }
});


text:
Q: how to: mustache if else statement How do we write the following in mustache?
I want to check if a variable exists, if it does, I want to check if that variable equals another variable. so
This would be the PHP equivalent
if ($example && $example == $type) {
}

A: Alternatively mustache shortcodes use the # symbol for 'if' so assuming your shortcode is {{example}} then
{{#example}}
    Start condition if example exists
{{/example}}

And ^ works the same way for 'if does not exist'
{{ ^example}}
    Start condition if example does not exist
{{/example}}

NOTE - If using mustache conditions you must must remember to close the condition the same way you would an HTML attribute.

A: If you're using mustache the goal is to perform this type of logic in the controller, and not in the template. As per How do I accomplish an if/else in mustache.js? You would want to do this type of check in the controller and generate a boolean that you can use the in the template

A: You can attach a closure to the mustache data and put this logic into that closure, something like:
var md = {};
md['my_condition'] = function(){
  return (this['some_attr'] && this['some_attr'] == 'expected_val');
}

and then use the md object as data to the mustache template.


text:
Q: Search in struct, delivering index of array? What's needed to get this code running?
Hi, I already have this part of code. It searches in an array of struct and delivers - if found - the index of that item:
    for index in 0 ..< gSteering.count {
        if gSteering[index].Ext == fileExtension.uppercaseString {
            priority = index
            break
        }
    }

I'm sure, that there is are shoreter and more elegant way in SWIFT using library functions. Any hints?

A: Something like
let priority = gSteering.indexOf() {
    $0.Ext == fileExtension.uppercaseString
}

P.S. And if you want priority to default to maxint in case if item is not found:
let priority = gSteering.indexOf() {
    $0.Ext == fileExtension.uppercaseString
} ?? Int.max

A: Here's one I could come up with:
if let index = (gSteering.map{ $0.Ext }).indexOf(fileExtension.uppercaseString)
{
    priority = index
}
else
{
    // Not found.
}

And here's another one:
let priority = gSteering.indexOf { $0.Ext == fileExtension.uppercaseString }

And here's one to get the object directly instead of the index:
// This will give you an array with all the results that match.
let priorityObj = gSteering.filter { $0.Ext == fileExtension.uppercaseString }


text:
Q: If I "use" a BinaryWriter, do I also need to call Close? - F# I understand that if I am working with a BinaryWriter, and I declare it with "use" instead of "let," it will automatically call the "Dispose" method when I am done with it. Does this Dispose also call "Close" on the BinaryWriter, or do I need to call Close as well, to ensure that the underlying streams are also closed?
use byteWriter = new BinaryWriter(new MemoryStream(bytes))
[1;2;3] |> List.iter(fun s -> byteWriter.Write(int16(s)))
byteWriter.Close()   // is this needed?

A: The documentation for BinaryWriter.Close states:

This implementation of Close calls the Dispose method passing a true
  value.

so no it should not be needed since Dispose will be called when exiting the scope of the use.
If you look at the source for BinaryWriter you can see that Close and Dispose both just call Dispose(true).


text:
Q: load svg with Cairo I want to load a SVG file with the Cairo library, do apply some transformations to it.
Then I want to display my svg with a glTexture.
But I just find functions which create svg file and not load svg.

A: Cairo itself cannot read SVG files. You need something like librsvg to render SVGs to a Cairo surface.
From a quick look at their API documentation, it looks like you need rsvg_handle_new_from_file() to load a file and something like rsvg_handle_render_cairo() or rsvg_handle_get_pixbuf() to draw the SVG to a Cairo context / to turn the SVG into a GdkPixbuf.


text:
Q: Convertir parametros de un array javascript Necesito una funcion que me cambie los parametros que acepta un arreglo el acepta 'abbreviation' y 'description' tiene que leer  'optionStringValue' y 'optionStringText'
Tengo un Select2 que me deberia de cargar todos los meses del año pero no los carga porque el array que tengo acepta otros parametros que no acepta el LoadDataSelect que tengo
este el codigo que tengo
eso me deberia de cargar los meses
pLoadDataSelect($('#select_mes'),fGetArrayMonth(),{
                'optionStringValue' : 1,
                'optionStringText' : 1,
                'functionData' : fDataSelectCountBudget
            });

De este arreglo
function fGetArrayMonth() {

    var array = [];

    array.push({
        'code' : 1,
        'abbreviation' : 'ene',
        'description' : 'ENERO'
    });
    array.push({
        'code' : 2,
        'abbreviation' : 'feb',
        'description' : 'FEBRERO'
    });
    array.push({
        'code' : 3,
        'abbreviation' : 'mar',
        'description' : 'MARZO'
    });
    array.push({
        'code' : 4,
        'abbreviation' : 'abr',
        'description' : 'ABRIL'
    });
    array.push({
        'code' : 5,
        'abbreviation' : 'may',
        'description' : 'MAYO'
    });
    array.push({
        'code' : 6,
        'abbreviation' : 'jun',
        'description' : 'JUNIO'
    });
    array.push({
        'code' : 7,
        'abbreviation' : 'jul',
        'description' : 'JULIO'
    });
    array.push({
        'code' : 8,
        'abbreviation' : 'ago',
        'description' : 'AGOSTO'
    });
    array.push({
        'code' : 9,
        'abbreviation' : 'sep',
        'description' : 'SEPTIEMBRE'
    });
    array.push({
        'code' : 10,
        'abbreviation' : 'oct',
        'description' : 'OCTUBRE'
    });
    array.push({
        'code' : 11,
        'abbreviation' : 'nov',
        'description' : 'NOVIEMBRE'
    });
    array.push({
        'code' : 12,
        'abbreviation' : 'dic',
        'description' : 'DICIEMBRE'
    });

    return array;

}


text:
Q: TextMate: Bundle to wrap selected text with php commenting I am new to TextMate, and so far I am loving it!
Prior to TextMate, I was using Dreamweaver.
Dreamweaver has a nice feature where you select your text, and wrap it with php commenting. <?php /* */?>. This was especially useful for temporarily wrapping large blocks of code which already contained html commenting.
E.g. >
<?php /*

My Paragraph

[...]

My Paragraph

*/ ?>

Is there already a bundle for this?
I think this would be a good and maybe even standard bundle!

A: If you haven't already figured this out, there is.  Command+/ will comment selected text in any language you are programming in.


text:
Q: linux shell script using djvused program not working I want to write a script that renames the pages of a DJVU file recursively.
From http://djvu.sourceforge.net/doc/man/djvused.html I know that the command to do that on a single page (say call page 5 of the bundle with name 6) is
djvused file.djvu -e 'select 5; set-page-title 6; save'

But then I have troubles when trying to do it recursively, namely running the script
./for.sh

which is given by
for (( i=12; i<=823; i++ ))
do
 djvused file.djvu -e 'select $i; set-page-title $((i-10)); save'
done

The error I get is due to the program being unable to understand $i as a number, instead of an expression. I think this is related to my small knowledge of shell scripts and djvused.
Could anyone tell me how to modify it so that it works?

A: You should quote it properly with double-quotes. Using single quotes would not allow variables to be expanded and remain as literal form.
for (( i=12; i<=823; i++ ))
do
 djvused file.djvu -e "select $i; set-page-title $((i-10)); save"
done

As noted about single quotes:

Enclosing characters in single quotes (''') preserves the literal
  value of each character within the quotes. A single quote may not
  occur between single quotes, even when preceded by a backslash.

Whereas on double quotes:

Enclosing characters in double quotes ('"') preserves the literal
  value of all characters within the quotes, with the exception of '$',
  '', '\', and, when history expansion is enabled, '!'. The characters
  '$' and '' retain their special meaning within double quotes


text:
Q: SQL Math prob involving averaging values (but not how you think!) I'm very new to SQL and having trouble getting a SQL query to work.
I have a list of responses that contain the numbers 1 through 4 Example:
Question 1 contains the data Q1: 1,2,1,3,4,1,2,3,4,2
What I need to do is count how many 1's and 2's there are, total them and then average the number. Such as in the above example have a count that there are 6 1's and 2's total and divide that by the total number for a average.  6/10 = .6 (oh gosh I hope that made sense)
I have been trying this code but it is summing the numbers and then dividing by the total.
Select avg(q1) as avg
From db
Where q1 between 1 and 2
And call = 55817

Such as in the above example it's doing this: 1+2+1+1+2+2=9/10 = .9 when again I need it to just "count" how many 1's and 2's there are.

A: For an SQLite specific solution, try this:
SELECT AVG(q1 IN (1, 2)) AS youravg
FROM db
WHERE call = 55817

See it working online: sqlfiddle
For a more standard SQL solution, you might prefer this:
SELECT AVG(CASE WHEN q1 IN (1, 2) THEN 1 ELSE 0 END) AS youravg
FROM db
WHERE call = 55817

A: Why not do a SELECT with 1 and 2 then use the COUNT function?
COUNT


text:
Q: Using imshow with basemap: mismatch between colours and map borders I am trying to plot some grib data using basemap
and imshow instead of contourf. When I plot it with contourf I get the proper boundaries and colours, but when I do it with imshow there is a mismatch between the image and the map.
Plot with contourf using contourf. Plot with imshow using imwshow
I am using an lcc projection. In the documentation I see some examples using a cylindrical projection, but I also get the mismatch in this case.
The relevant code is below.
m = Basemap(llcrnrlon=-55, llcrnrlat=55.8, urcrnrlon=80, urcrnrlat=80, lat_1=72, lat_0=72., lon_0=-36, resolution='h', projection='lcc')
x, y = m(lons, lats)

data = data - 273.15
import matplotlib as mpl
cmap = mpl.cm.RdBu_r
norm = mpl.colors.Normalize(vmin=-55, vmax=15)
minVal = min(data.flatten())
maxVal = max(data.flatten())
clev = np.arange(minVal,maxVal,0.01)
#using contourf
CS_tmp = m.contourf(x,y,data,clev,cmap=plt.cm.coolwarm)
#using imshow
CS_tmp = m.imshow(data2,cmap=cmap) #,extent=extent)

My question is, what sort of transformation should I apply
to the data? I tried to follow this tutorial
https://basemaptutorial.readthedocs.io/en/latest/utilities.html#interp
which makes reference to transform_scalar, which will only work
for cylindrical projections.
It suggest to use interp for a non-cyl projection
"When the input matrix is not regular in longitude-latitude (i.e. is not a cylindric projection), this method can't be used properly, since the longitude-latitude grid won't be regular. See the interp example for a solution."
I tried following the example there, but this didn't work
and I am still seeing the mismatch
x2 = np.linspace(x[0][0],x[0][-1],x.shape[1]*2)
y2 = np.linspace(y[0][0],y[-1][0],y.shape[0]*2)
x2, y2 = np.meshgrid(x2, y2)
data_trans = interp(data,  x[0], y[:, 0], x2, y2,order=1)

Could anyone tell me what would the adequate transformation here?
Thanks for any help
Carlos

A: I think the problem is that the imshow plot fits into the whole figure window in your plot because matplotlib can't obtain any coordinate information from your array.
If you would use another projection it would be possible to set the boundaries correctly but as you use a polar based projection the extent of the coordinates goes up to 80° in Latitude and Longitude.
So you have to add nan's to your data2 array.
Code could look like this:
# take a raw array of zeros along longitude axes
base_nan_array = np.zeros(len(x))

# find out how many rows must be added
n_lat_rows =len(y) - data2.shape[1]

# fill up nan array
nan_array = np.array([base_nan_array,]*n_lat_rows)

# append to data (you have to find the direction of append on your own bc. no test data is avail.)
np.append([data2, nan_array], axis=0)

This will make your array cover the whole extend of your basemap.


text:
Q: How to implement the swipe view in android project? I am new to android.I tried many ways but I cannot able to understood how to implement a swipe view in my android project.
I have a six tabs:

1.Home
2.Video
3.Audio
4.Gallery
5.Blog
6.More

I referred android docs about swipe view.I cannot able to understood how to implement the swipe view in android project.anybody can help me with these.Thanks in advance.

A: Here lots of url to make this view you can follow any one:
http://just-another-blog.net/programming/how-to-implement-horizontal-view-swiping-with-tabs/
http://developer.android.com/training/implementing-navigation/lateral.html#swipe-tabs
How do I implement swiping between tabs on Android?
I hope it will work for you.


text:
Q: LAN Huge File Transfer How to send a Huge file more than 8GB to Several clients on a Local Area Network., At the same time., like File Multicast..,
.
No Intermediate software.,
No Permission Required at Client or Receiver

A: I've used UDPcast.

UDPcast is a file transfer tool that can send data simultaneously to many destinations on a LAN. This can for instance be used to install entire classrooms of PC's at once. The advantage of UDPcast over using other methods (nfs, ftp, whatever) is that UDPcast uses UDP's multicast abilities: it won't take longer to install 15 machines than it would to install just 2.
From https://www.udpcast.linux.lu/index.html

It's an old software program (2006), but it still worked fine for me.
I've never set it up in a perfect way, so 1 or 2 transmissions usually failed, but it saved time during my classes sending a large ISO file to my students at once.

Basic usage
udp-sender -f outfile
  Starts the sender program. The program waits for
  connections from the receivers. As soon as a key is pressed on either
  one of the receivers or on one of the senders, the data transfer will
  start.
udp-receiver -f outfile
  Starts the receiver program. It automatically
  locates (via broadcast) any sender on the local net, and connects to
  it.
From https://www.udpcast.linux.lu/cmdlinedoc.html


text:
Q: Not able to create a JNDI object in grails How do I do a lookup in grails?   A jndi lookup should be simple enough, but I find confusing information about context.xml, adding "grails.naming.entries" in Config.xml, creating a jndi-lookup bean in resources.groovy - all of the combinations I've tried so far have been fruitless. It is able to take the JNDI if we give it in context.xml of tomcat. So if i deploy the war inside tomcat i do not get any exception.
my config.groovy
grails.naming.entries = [
    "java:comp/env/bonitaDS": [
            type: 'javax.sql.DataSource',
            auth: 'Container',
            description: 'Main datasource',
            url: "jdbc:mysql://localhost/bonita?useUnicode=yes&characterEncoding=UTF-8",
            username: "",
            password: "",
            driverClassName: "com.mysql.jdbc.Driver",//"com.mysql.jdbc.jdbc2.optional.MysqlXADataSource",
            maxActive: "8",
            maxIdle: "4"
    ],

    "java:comp/env/bonitaSequenceManagerDS": [
            type: 'javax.sql.DataSource',
            auth: 'Container',
            description: 'Main datasource',
            url: 'jdbc:mysql://localhost/bonita?useUnicode=yes&characterEncoding=UTF-8',
            username: "root",
            password: "root",
            driverClassName: 'com.mysql.jdbc.Driver',
            maxConnectionsPerPartition: "2",
            minConnectionsPerPartition: "1",
            partitionCount: "1",
            acquireIncrement: "5",
            statementsCacheSize: "100",
            releaseHelperThreads: "3"
    ],

    "java:comp/UserTransaction": [
            type: 'com.atomikos.icatch.jta.UserTransactionFactory'
    ]
]

My context.xml file inside conf folder of tomcat
<Resource name="bonitaSequenceManagerDS"
          auth="Container"
          type="javax.sql.DataSource"
          maxActive="17"
          minIdle="5"
          maxWait="10000"
          initialSize="3"
          maxPoolSize="15"
          minPoolSize="3"
          maxConnectionAge="0"
          maxIdleTime="1800"
          maxIdleTimeExcessConnections="120"
          idleConnectionTestPeriod="30"
          acquireIncrement="3"
          validationQuery="SELECT 1"
          validationInterval="30000"
          testConnectionOnCheckout="true"
          removeAbandoned="true"
          logAbandoned="true"
          username=""
          password=""
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/bonita?dontTrackOpenResources=true&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true"/>

<Resource name="bonitaDS"
          auth="Container"
          type="javax.sql.DataSource"
          factory="bitronix.tm.resource.ResourceObjectFactory"
          uniqueName="jdbc/bonitaDSXA" />

The error:

org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'transactionManager' defined in file
  [C:\bonita-home\server\platform\conf\services\cfg-bonita-transaction-api-impl.xml]:
  Invocation of init method failed; nested exception is
  javax.naming.NameNotFou ion: Name [java:comp/UserTransaction] not
  bound; 2 bindings:
  [java:comp/env/bonitaDS,java:comp/env/bonitaSequenceManagerDS] (Use
  --stacktrace to see the full trace)

I get the following startup exception when running the test-app and also
 get the same exception during run time when using run-app using
Grails 2.4.2

A: This is how we do it in Datasource.groovy
dataSource {

   jndiName = "java:comp/env/jdbc/bonitaSequenceManagerDS"
}


text:
Q: send 300K records as API response in Ruby and Sinatra My application has an end point for POST request. When ever the request is made for this POST request end point, it queries and fetches records from Mysql table (table containing 3.5 million records) and selects around 300K records.
It reads this 300k records and sends this data to the client as API response in JSON format.
This request and response takes around 15 minutes to send back 300K records as JSON response. Which is very slow in performance and really not acceptable by the clients.
Is there any quick way to send out 300K records as Json format in API response.?

A: You can try to add the oj gem to your project.


text:
Q: clojure storing vs. using a sequence in expression Helo, In an effort to learn clojure, I have taken an interest in clojure.core functions that act on sequences.  Recently, I noticed some odd behaviour and would like an explaination of the difference between the folling expressions:
What I'm trying to do is this:
user=> (reduce + (take-while (partial > 1000) (iterate inc 1)))
499500

However, when I store (iterate inc 1) with def a get an error:
user=> (def a (iterate inc 1))
#'user/a
user=> (reduce + (take-while (partial > 1000) (a)))
java.lang.ClassCastException: clojure.lang.Cons cannot be cast to clojure.lang.IFn (NO_SOURCE_FILE:0)

Could someone please explain what the difference between storing iterate inc 1 and using it directly in the expression? I know that a is a lazy sequence but am missing something...
Thank you very much for your time.

A: You should be doing
(reduce + (take-while (partial > 1000) a))

(a) attempts to call a, but it's not a function.


text:
Q: How to store multiple numpy 2d matrices - with different sizes - into one numpy matrix? In short:
I need to load multiple 2d numpy matrices - with different sizes - into one numpy matrix. First, I tried to load them as the 3rd dimension of the matrix but due to the various sizes it wasn't possible. It would be great if you could direct me how to do it, or even any other convenient solution.
More description:
I'm reading arrays from multiple csv files and loading them into numpy arrays. This is easy when the number of csv files are known and the arrays are at the same size. Whereas, I need to do this for any number of files at different sizes. So I thought I could use numpy's structured arrays, but I can't do it.

A: I think Numpy is going to require mathematically consistent matrices... which means all rows/columns in a 2D matrix have to have the same number of elements.  Likewise, if you try to make a 3-dimensional matrix, each 2D matrix will have to have the same dimensions.
However, you could use a regular Python array of numpy matrices.  If you do that, then you can dynamically add/remove individual matrices, and they can have varying dimensions.


text:
Q: He's likely to succeed According to the book of Michael Swan Practical English Usage:

Be +likely is often followed by infinitive. (Probable cannot be used in this way).

*

*I am likely to be busy tomorrow.

*Are you likely to be staying in this evening.

*Do you think it is likely to rain?

*He is unlikely to agree.

  It is not used as a preparatory subject in this structure.

*

*He's likely to succeed. (NOT It is likely for him to succeed.)

Could you please clarify about the last two line?
I think we are not allowed to use this format:

'it is likely ... to ..'

but:

'The Environment Agency has warned that it is likely to be an ongoing problem.'

As we know, 'It is likely to rain' is grammatically correct, but we used 'it' as a subject in above sentence. And it is the opposition of Michael Swan book.
Thanks.

A: In your example, 'it' is a regular pronoun, referring to some subject introduced earlier (such as 'air pollution').
So the sentence is perfectly grammatical.

(...some sentence introducing the topic of air pollution.)  The Environment Agency has warned that air pollution is likely to be an ongoing problem.