text:
Q: If both $f(z)$ and $−\overline{f(z)}$ are analytic, what can you say about $f(z)$? Prove your claim. I am struggling with this question. If both $f(z)$ and its negative conjugate $-\overline{f(z)}$ are analytic, what can you say about $f(z)$? Prove your claim.
I know that the sum on difference of two analytic functions is analytic but I can't see how that will help. Does anyone know how to approach this question or a theorem that would lead to an argument. Please provide at least a start to the argument so I may understand your approach well enough.

A:
I know that the sum on difference of two analytic functions is analytic

Perfect! So, what can we tell about the difference $f(z)-(-\overline{f(z)})$? You say you know it's analytic. Here is one more thing we can tell: It is real-valued, since it's equal to $2\operatorname{Re}(f(z))$.
An analytic function that always takes real values, and thus has constant imaginary part, must be constant. So $f$ has constant real part, which means that $f$ itself must be constant.

A: If $f(z)$ and $-\overline{f(z)}$ are both analytic, then $f(z) - \overline{f(z)} = 2i \Im(f(z))$ is analytic ($\Im(h)$ being imaginary part of $h$), and thus the imaginary part of $f(z)$ is analytic.
The imaginary part of $f(z)$ is a real-valued analytic function. Any real-valued analytic function must be constant. For suppose $g$ is a real-valued analytic function and $g'(z) \neq 0$. Then consider a sufficiently small real $\delta$. Then $g(z + i \frac{h}{g'(z)}) = g(z) + ih + o(h)$, which is not a real number.
Thus, the imaginary part of $f(z)$ is constant. Then the real part of $f(z)$ is also a real-valued analytic function, hence is constant. Then $f$ is constant.

A: Here's another approach: Complex functions are complex differentiable iff they are real differentiable and their Jacobian is of the form
$$\mathrm Df=\begin{pmatrix}a&-b\\b&a\end{pmatrix}$$
That's essentially the content of the criterion for complex differentiability using the Cauchy-Riemann equations (it requires that $f$ be real differentiable and that its partial derivatives satisfy the CR-equations, which is the same as saying that the Jacobian has the above form). Now the function $g:z\mapsto -\bar z$ is also real differentiable with Jacobian
$$\mathrm Dg=\begin{pmatrix}-1&0\\0&1\end{pmatrix}.$$
Now the chain rule says that $g\circ f$ is also real differentiable with Jacobian
$$\mathrm D(g\circ f)=\mathrm Dg(f)\mathrm Df=\begin{pmatrix}-1&0\\0&1\end{pmatrix}\begin{pmatrix}a&-b\\b&a\end{pmatrix}=\begin{pmatrix}-a&b\\b&a\end{pmatrix}.$$
By assumption, $g\circ f$ is analytic, so this Jacobian must also satisfy that the diagonal elements are equal, while the off-diagonal elements differ by sign, which gives us $-a=a$ and $b=-b$. But that means $a=b=0$, so our function has vanishing derivative, and is thus constant (on connected sets).


text:
Q: can not use mount.cifs: mount error(2): No such file or directory The command mount.cifs is found not being able to run in a gentoo system with systemd
ae429-1105 etc # mount -t cifs //file.abc.edu.au/user /home/directory/path -o credentials=/etc/user,rw,iocharset=utf8,file_mode=0777,dir_mode=0777
mount error(2): No such file or directory
Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)

It has been confirmed that the existence and accessibility of the mountpoint  /home/directory/path and credential file /etc/user. Also the relevant modules and services has been enabled, i.e.,
 ae429-1105 etc # lsmod |egrep 'fuse|cifs'
 fuse                   72589  5
 cifs                  312131  0

and
ae429-1105 etc # systemctl -t service -a |grep Samba
nmbd.service                         loaded active   running Samba NetBIOS                     name server
smbd.service                         loaded active   running Samba SMB/CIFS     server
winbindd.service                     loaded inactive dead    Samba Winbind daemon

This problem has been identified by many users, e.g. one example . ALSO NOTE that the same command executed in my Ubuntu/debian system is able to mount successfully.
Other information in the problematic machine:
ae429-1105 etc # mount.cifs --version
mount.cifs version: 6.1

the version of mount.cifs installed in debian/ubuntu is 6.0

A: Can you use nodfs option? ie for your -o options input pass the input as below.
-o credentials=/etc/user,rw,iocharset=utf8,file_mode=0777,dir_mode=0777,nodfs

i.e appended ,nodfs
It worked for me.

A: I ran into this on Ubuntu 18.04. The problem was I needed the keyutils package to do Kerberos authentication (sec=krb5 mount option), which was not installed along with cifs-utils (which provided mount.cifs). I'm not sure if the package name is the same on Gentoo or not.
(Thanks to https://forum.zentyal.org/index.php?topic=18601.0 for the solution.)

A: You might need to change the sec parameter: this setting made it work on my setup:
mount.cifs ... -o sec=ntlm

Relevant extract of man mount.cifs:

sec= Security mode. Allowed values are:

*

*none - attempt to connection as a null user (no name)

*krb5 - Use Kerberos version 5 authentication

*krb5i - Use Kerberos authentication and forcibly enable packet signing

*ntlm - Use NTLM password hashing

*ntlmi - Use NTLM password hashing and force packet signing

*ntlmv2 - Use NTLMv2 password hashing

*ntlmv2i - Use NTLMv2 password hashing and force packet signing

*ntlmssp - Use NTLMv2 password hashing encapsulated in Raw NTLMSSP message

*ntlmsspi - Use NTLMv2 password hashing encapsulated in Raw NTLMSSP message, and force packet signing
The default in mainline kernel versions prior to v3.8 was sec=ntlm. In v3.8, the default was changed to sec=ntlmssp.
If the server requires signing during protocol negotiation, then it may be enabled automatically. Packet signing may also be enabled automatically if it's enabled in /proc/fs/cifs/SecurityFlags.

A: You might need to provide the vers= option to the mount command to force version 3.0 if you're trying to mount a share from a newer version of Windows. One of our fileservers was recently upgraded to 2012R2 and that's when my mount stopped working. Setting it to vers=3.0 fixed the issue. Like most Samba/CIFS errors the "No such file or directory" message isn't much help.
As an example:
# mount -t cifs //win2012r2/someshare -o cred=/home/foo/.cifs_user,vers=3.0 /mnt/tmp

..where I have my domain, username and password contained in the .cifs_user file:
user=MyUser
password=MyPassword
domain=MyDomain

Apparently, smbmount uses a newer version of the SMB protocol by default since it worked without issue or any special options.
Notice below that the default protocol version is 1.0.
From the mount.cifs man page:
vers=arg
       SMB protocol version. Allowed values are:

       · 1.0 - The classic CIFS/SMBv1 protocol.

       · 2.0 - The SMBv2.002 protocol. This was initially introduced in Windows Vista Service Pack 1, and Windows Server 2008. Note  that  the  initial  release
         version of Windows Vista spoke a slightly different dialect (2.000) that is not supported.

       · 2.1 - The SMBv2.1 protocol that was introduced in Microsoft Windows 7 and Windows Server 2008R2.

       · 3.0 - The SMBv3.0 protocol that was introduced in Microsoft Windows 8 and Windows Server 2012.

       · 3.02 or 3.0.2 - The SMBv3.0.2 protocol that was introduced in Microsoft Windows 8.1 and Windows Server 2012R2.

       · 3.1.1 or 3.11 - The SMBv3.1.1 protocol that was introduced in Microsoft Windows 10 and Windows Server 2016.

       · 3 - The SMBv3.0 protocol version and above.

       · default - Tries to negotiate the highest SMB2+ version supported by both the client and server.

       If no dialect is specified on mount vers=default is used.  To check Dialect refer to /proc/fs/cifs/DebugData

       Note too that while this option governs the protocol version used, not all features of each version are available.

       The default since v4.13.5 is for the client and server to negotiate the highest possible version greater than or equal to 2.1. In kernels prior to v4.13,
       the default was 1.0. For kernels between v4.13 and v4.13.5 the default is 3.0.

A: I wanted to add another source of this problem I encountered today.
Once you change the user id of a unix user, the smb user created via smbpasswd may not able to authenticate for the samba share anymore resulting in the same error.
So if you changed your unix user id via usermod -u 1000 my_user then you may run into problems. The fix for me was to delete and re-add the smb user afterwards:

smbpasswd -x my_user
smbpasswd -a my_user

A: Try to install the package keyutils:
sudo apt-get install keyutils

Not sure exactly why this helps, maybe someone else has an answer here. But at least it did the trick for me: with keyutils the cifs mount worked just fine.

A: I was running into this same "mount error(2): No such file or directory" error using mount.cifs on a CentOS 7 VM. I never determined exactly why the error was being generated when using the default ntlm security (and the variants), but I did discover that using Kerberos authentication worked around the problem. So my final working command line looked like this:
mount.cifs -v -o domain=MYCODOMAIN,sec=krb5 //winserver/sharename /mnt/mymountpoint

whereas this command that gave the "no such file or directory" error was:
mount.cifs -v -o username=myusername,domain=MYCODOMAIN //winserver/sharename /mnt/mymountpoint

To use Kerberos, I installed "krb5-workstation" package and configured it.

A: Add a $ to the end, like this //winserver/sharename$
mount.cifs -v -o username=myusername,domain=MYCODOMAIN //winserver/sharename$ /mnt/mymountpoint

A: With me it worked by putting "vers = 1.0" as before -> credentials = / root / .dbx.credentials, vers = 1.0, uid = 1001, gid = 100, rw

A: Could you have just upgraded the linux kernel?
Are you on a corporate network?
If so - try disabling IPv6 in /etc/sysctl.conf
to do this open it with sudo nano /etc/sysctl.conf and add the following:
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1

And then run sudo sysctl -p
Remount and try again.
This worked for me when I upgraded LTS all the way from 16.04 through 18.04 to 20.04, and I had this problem.

A: Apparently samba throws this entirely un-helpful error in an astoundingly wide range of cases. In my case, the issue was an option configured for the share in the server's smb.conf (vfs objects = vfs_fruit) which the server didn't like, even though testparm didn't complain about it.

A: This error could mean a variety of things. Scenario I saw was that Samba on the server had been updated, but the service was not restarted. This caused it to have errors loading shared modules. Restarting Samba on the server resolved. So: check the server logs and consider restarting Samba.

A: One solution might be to manually install keyutils since it is not a (hard) dependency of cifs-utils anymore.
Information why keyutils are not installed anymore can be found here:
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=822841
And a launchpad bug report can be found here: https://bugs.launchpad.net/ubuntu/+source/cifs-utils/+bug/1772148

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaScript: setInterval() doesn't produce expected output Please take a look at my code below, I don't know why it produce expected output. I think the way I used setInterval() and setTimeout is wrong. Somehow the process doesn't go by 1 order from top to bottom. It seems like there are 3 threads run in parallel. How can I fix it? Thank you.

(function() {
  var nums = [1, 2, 3];
  nums.forEach(
    (e) => {
      console.log(e);
      var frame = 0;
      let loop = setInterval(function() {
        if (frame === 3)
          clearInterval(loop);
        console.log(e + " frame " + frame);
        frame++;
      }, 1000);
      let wait = setTimeout(function() {
        console.log(e + " 2 second passed");
      }, 2000);
    }
  )
})();

Expected output:
1
1 frame 0
1 frame 1
1 frame 2
1 2 seconds passed
2
2 frame 0
2 frame 1
2 frame 2
2 2 seconds passed
3
3 frame 0
3 frame 1
3 frame 2
3 2 seconds passed

Actual output:
1
2
3
1 frame 0
2 frame 0
3 frame 0
1 frame 1
1 2 second passed
2 frame 1
2 2 second passed
3 frame 1
3 2 second passed
1 frame 2
2 frame 2
3 frame 2
1 frame 3
2 frame 3
3 frame 3

A: Because Javascript is asynchronous, you need some way of waiting for each of the intervals and the timeout to complete before running the next.
One way of doing this is by using async/await and wrapping the intervals and timeout in a promise.

(async function() {
  var nums = [1, 2, 3];
  for (const e of nums) {
    console.log(e);
    let frame = 0;
    await new Promise(resolve => {
      let loop = setInterval(function() {
        if (frame === 3) {
          clearInterval(loop);
          resolve();
        } else {
          console.log(e + " frame " + frame);
          frame++;
        }

      }, 100);
    })
    await new Promise(resolve => {
      let wait = setTimeout(function() {
        console.log(e + " 2 second passed");
        resolve();
      }, 200);
    })
  }
})();

A: No idea what you going to accomplished with this code. but please try with below approach. you can console log what you asked. Do changes as your favor,

let nums = [1, 2, 3];
const timesecs = 1000;

const timeOut = (num) => {
  setTimeout(
    () => {
      console.log(num);
      nums.forEach(
        (item, index) => {
          console.log(num + " frame " + index);
        }
      )
      //console.log(`${num} ${num+1} seconds passed`);
      console.log(`${num} 2 seconds passed`);
    },
    num * timesecs
  )
}

nums.forEach((num) => {
  timeOut(num);
});

A: Javascript doesn't work this way. You need to understand the concept of ASYNC operations and callbacks first. Aysnc operations, like setTimeout and setInterval, do not wait for their callback functions to finish before moving to the next line of the code. They just move the execution cursor to the next line. Your setInterval function will finish its callback execution after 1000 milliseconds.
There are new functionalities are added like await and async function. You may want to look into them to achieve what you want.
The for loop you are running should be inside the interval rather than what you are doing.

(function () {
        var nums = [1, 2, 3];
  var ind = 0;
  let loop = setInterval(function(){
   if(ind === 2){
    clearInterval(loop);
   }
   console.log(nums[ind]);
   nums.forEach(e => {
    console.log(nums[ind] + " frame " + e);
   });
   console.log(nums[ind] + " 2 seconds passed");
   ind++;
  }, 2000);
})();

A: You have a forEach loop that will loop 3 times. On the first iteration, it will:

*

*console.log the frame (1)

*create an interval that will execute in 1 second

*create a timeout that will execute in 2 seconds

Then the second iteration of the loop happens immediately after the first iteration so it will again:

*

*console.log the frame (2)

*create another new second interval that will execute in 1 second

*create another new second timeout that will execute in 2 seconds

Finally the third iteration will occur, immediately and it will:

*

*console.log the frame (3)

*create another third new interval that will execute in 1 second

*create another third new timeout that will execute in 2 seconds

Next, all three of your newly created intervals will execute about 1 second after the loop finishes. Each interval will execute very slightly behind the previous interval. And each one contains a "closure" around the variable frame (i.e. when they were created, they all "captured" frame when it was set to 0 so they all console.log(0).
On the next second, each of the 3 intervals will attempt to run again (now each with frame === 1), and the 3 timeouts will also attempt to run. Note that each timeout also has formed a "closure", locking in the value of e at the time it was created. You end up getting a bit of staggering of intervals executing, mixed with timeouts executing.
The 3 timeouts only ever happen once each.
The remainder of the output is the set of 3 intervals successively executing, with a 2 second gap between each set.

You could achieve your output by just using one interval (with no loop), set to fire every second and print something. I'm not sure of the requirements regarding how many seconds apart you need these statements to be printed, so I cannot produce the exact code that you need but here's something that produces your desired output with my best guess at the timing:
var num = 1;
var frame = 0;
var loop = setInterval( function() {
  if (frame === 0) {
    console.log(num);
  }
  if (frame >= 0 && frame <= 2) {
    console.log(num + " frame " + frame);
  }

  if (frame === 4) {
    console.log(num + " 2 seconds passed");
    num++;
    frame = -1;
  }
  if (num > 3) {
    clearInterval(loop);
  }
  frame++;
}, 1000);


text:
Q: How to create cron jobs in firebase programmatically I have a unique problem here. I actually need to schedule a task to send emails to eligible users at specific times. I have checked and found out that scheduling cron jobs can solve the problem. However, in my case, I need to schedule these tasks programmatically based on when specific users meet certain conditions.
Here is my scenario

*

*I am running a referral campaign in my application where users who refer up to 5 persons get a discounted subscription

*After the user has referred 5 persons, the cost of subscription is slashed as long as he pays within 24 hours. Otherwise the cost returns to the original value

*I'm using firebase cloud functions to send eligible users reminder email reminders at certain times to make payment before the 24 hours elapses
Now the problem

*

*I want to send reminder emails at specific times say as soon as he refers 5 persons, when his time is remaining say 3 hours etc.

*If I just schedule a function regardless of the user, I may have to set cron jobs at regular intervals say 1 minute to always check if the users in my db are eligible and then send emails to them. This pose serious issue such that cloud functions are ran whether or not there are eligible users.

*Another problem is that with the above implementation, I cannot send emails to users at specific/exact times unless I schedule tasks for like every 1 second which will of course sky rocket price as cloud functions will be called around a whooping 86400 times (86400 seconds) a day
My proposed solution

*

*I just need a way to schedule cron tasks dynamically so that I can schedule a job for particular users. This will solve many problems like sending the emails at particular times, prevent cloud functions from running when not necessary, ability to set different email send times for different users etc

*I plan using http triggers with a request parameter of the user ID for scheduling tasks so that firebase can use this ID to assign tasks to only specific users, i.e each eligible user will have his own http trigger
Please is there a way to achieve this or any other good solution for my case?

A: Instead of trying to dynamically creating scheduled function, consider having a single function that runs on a fixed schedule, and then implementing your timing logic inside of that function.
So instead of saying "I need to schedule a function that runs 3 hours from now and send a message to these 5 people", think of it as a task that you can write into a database: "at x:yz send an email to these 5 people", and then have a periodic Cloud Function that checks what tasks it needs to execute.
Also see Delay Google Cloud Function, How to use scheduler for Firebase Cloud Functions with Realtime Database/Analytics triggers?
Alternatively you can use Cloud Scheduler to create a task for the specific action you want to perform, and then have it post to Cloud Functions via PubSub.
As an even newer alternative: Use a separate scheduler service that has an API to create schedules, like Cloud Tasks. Doug wrote a great article about that in How to schedule a Cloud Function to run in the future with Cloud Tasks (to build a Firestore document TTL).


text:
Q: What is required to store these values in conceptual order when parsing and building an AST? I am working on a programming language, say we are focusing on type definitions, and say the type definitions are specified in a certain order. Say, too, we have "macros" which are lazily evaluated and we essentially inject the appropriate code where the macro is. Ignore for this question the idea of processing the macros first, then processing the rest, think of them as processed in order they are encountered. Then for example, we might have this in a file/module:
INSERT z
type a
type b
INSERT x
type c
type d
INSERT y

MACRO y {
  type p
  type q
  INSERT w
}

MACRO z {
  type t
  type v
}

MACRO x {
  type h
  type i
}

MACRO w {
  type l
  type m
  type n
}

The resulting AST should look something like this:
[
  { type: 't' },
  { type: 'v' },
  { type: 'a' },
  { type: 'b' },
  { type: 'h' },
  { type: 'i' },
  { type: 'c' },
  { type: 'd' },
  { type: 'p' },
  { type: 'q' },
  { type: 'l' },
  { type: 'm' },
  { type: 'n' },
]

// or more concisely visualized as:
t v a b h i c d p q l m n

That is, it is in the order you would conceptually expect.
The naive algorithm would do this though:
a b c d p q t v h i l m n

That is, it would do something like this to start parsing:
WAIT z
a
b
WAIT x
c
d
WAIT y

It would insert placeholders for the things it hasn't encountered yet, and come back to them to fill them in later. But it would have an array and simply push them into the array as it encountered each next one, resulting in that second ordering.
push('a')
push('b')
push('c')
push('d')
push('h')
push('i')
...

My question is, how would you "insert these in conceptual order" (as opposed to discovery order)?
At first I was thinking, maybe use a SortedSet, and have the key be the index, and use a decimal for the later encountered ones or something like that (kind of like how you might sort items by a position property in a database, as items are drag-n-drop ordered haphazardly). But I have a hard time taking that spark of a thought further.
Then I was thinking to keep a pointer to the WAIT objects, and when the macro was encountered, you would find the index of the WAIT, and insert all the items into the array starting at that array index. But that seems less than ideal, having to move all the subsequent items in the array every time you encounter the macro results...
Are there any other magic tricks than these two ways for doing it? How would you solve this problem and create a sorted list or even a sorted hash table, where the values are in the value you would conceptually expect them to be (the first example)?
Maybe a third approach would be to sort them after everything is parsed and use some sort of special index keys? I'm not sure.

A: One idea is to create a nested array. When an INSERT is encountered, don't attempt to insert the macro definition, but insert a nested object (array) that initially is empty, and log that object reference in a map keyed by the macro name.
When eventually the MACRO instruction is encountered, populate that array which you find in that map. If no such entry exists yet, then create it.
If an INSERT occurs when the mentioned macro already has such array reference then use that one.
For the example this leads to a structure which evolves as follows:
After processing INSERT z:
result: [
  { macro: array1 }
]

macros: {
  z: array1  // same reference as above; array is currently empty
}

After INSERT x:
result: [
  { macro: array1 },
  { type: "a" },
  { type: "b" },
  { macro: array2 }
]

macros: {
  z: array1,
  x: array2
}

After INSERT y:
result: [
  { macro: array1 },
  { type: "a" },
  { type: "b" },
  { macro: array2 },
  { type: "c" },
  { type: "d" },
  { macro: array3 }
]

macros: {
  z: array1,
  x: array2,
  y: array3
}

During the recursive processing of macro y, the deeper result (marked with an accent) looks like this when INSERT w is processed:
result': [
  { type: "p" },
  { type: "q" },
  { macro: array4 }
]

result: [
  { macro: array1 },
  { type: "a" },
  { type: "b" },
  { macro: array2 },
  { type: "c" },
  { type: "d" },
  { macro: array3 }
]

macros: {
  z: array1,
  x: array2,
  y: array3
  w: array4
}

Once all the macro definitions have been processed, these arrayX objects get populated, and that can be seen via the macros map, and (as they are the same arrrays) via the result array. The results array will eventually look like this:
result [
  { macro: [
            { type: "t" },
            { type": "v" }
           ]
  },
  { type: "a" },
  { type: "b" },
  { macro: [
            { type: "h" },
            { type: "i" }
           ]
  },
  { type: "c" },
  { type: "d" },
  { macro: [
            { type: "p" },
            { type: "q" },
            { macro: [
                      { type: "l" },
                      { type: "m" },
                      { type: "n" }
                     ]
            }
           ]
  }
]

It is not visible in this presentation, but if a macro is inserted multiple times, the corresponding array is not duplicated. The result will then just have duplicate references to the same array.
It then remains to flatten that nested structure, but that is just a matter of a depth-first traversal.
Here is a JavaScript solution that does all this:

function parse(input) {
    function graph() {
        const result = [];
        while (true) {
            const instruction = iterator.next().value;
            if (instruction === undefined || instruction == "}") return result;
            const arg = iterator.next().value;
            switch (instruction) {
            case "type":
                result.push({type: arg});
                break;
            case "INSERT":
                macros[arg] ??= []; // Create the macro array as empty (temporarily) if it doesn't exist
                result.push({macro: macros[arg]});
                break;
            case "MACRO":
                const token = iterator.next().value;
                if (token != "{") throw "Syntax error: expected '{', got " + token;
                if (macros[arg]?.length) throw "Duplicate definition of macro " + arg;
                macros[arg] ??= []; // Only create macro array if it wasn't referenced before
                macros[arg].push(...graph()); // Recursion to populate macro array
                break;
            default:
                throw "unexpected token";
            }
        }
    }

    function* values(nodes) {
        for (let node of nodes) {
            if (node.type) yield node;
            else if (node.macro) yield* values(node.macro);
        }
    }

    const macros = {}; // Map of macro definitions
    const iterator = input.match(/\S+/g)[Symbol.iterator]();
    const result = graph();
    return Array.from(values(result));
}

// Demo
let input = `
INSERT z
type a
type b
INSERT x
type c
type d
INSERT y

MACRO y {
  type p
  type q
  INSERT w
}

MACRO z {
  type t
  type v
}

MACRO x {
  type h
  type i
}

MACRO w {
  type l
  type m
  type n
}
`;

console.log(parse(input));

Be aware that this language can create cycles, and if you do, the above values() iterator will keep yielding values, so that the Array.from call will never finish.


text:
Q: Form committee of $2$ out of $5$ women and $3$ out of $6$ man with additional requirements. What is the number of ways of forming a committee that consists of $2$ out of $5$ women Ms. A, B, C, D, E, and $3$ out of $6$ man, Mr. A, B, C, D, E, F.
There are two additional requirements:

*

*Mr. A refuses to serve on committee if Mr. B is a member

*Mr. B only serve wants to serve if Ms. C is the member of the committee

A: *

*all committees: ${6 \choose 3} * {5 \choose 2}$

*remove the committees with both A and B: $4*{5 \choose 2}$

*remove the committees with B and not C: ${5 \choose 2} *4$

*inclusion/exclusion: add the committees with A, B, not C. (You subtracted twice and have to compensate): $4*{4 \choose 2}$

A: As @ астон вілла олоф мэллбэрг mentioned, this question is an application of simple combinatorics.
The number of ways of choosing  women from 5 women is $5\choose2$ while number of ways of choosing 3 men from 6 men is  $6\choose3$. So, The total number of ways are $5\choose2$$\times$$6\choose3$.


text:
Q: Postman interceptor proxy iPhone can't see GET requests I can't see certain GET requests from iPhone using Postman interceptor proxy.
I'm trying to see certain requests sent from an app on an iPhone in postman app. I've followed the guide on the postman website here.

*

*This works great for POST requests

*But I'm not able to see any GET requests.
I just want to check that this is normal. I did note that in the guide to using the postman built-in proxy that

Note: for the Postman native apps, request captures over HTTPS will not work if the website has HSTS enabled. Most websites have this check in place.

I'd like to know why this would block certain GET requests but allow other POST requests. Both URL endpoints are https:// if that helps.
Thanks in advance.


text:
Q: Get error with try/catch in Sequencial async functions I have a sequence of async functions that can be resolved or rejected. This functions must be executed in the correct sequence and depend one on other. So, i used 3 async functions and a try catch block. The problem is that when I reject some of the promises in the async functions, the catch block dont get the error sended on the reject callback. How can I get the error sended on reject? (code bellow)
Or should I use promise chaining? I would like to avoid this...
const methods = {

methodOne: async output => {

    return new Promise( (resolve, reject) => {

        if(error)
            reject(error) // want to get this error in try/catch block
        else
            resolve()

        })

    })

},

methodTwo: async () => {

    return new Promise( (resolve, reject) => {

        if(error)
            reject(error)
        else
            resolve('output')

        })

    })

},

methodThree: async () => {

    return new Promise( (resolve, reject) => {

        if(error)
            reject(error)
        else
            resolve()

        })

    })

},

runMethods: async () => {

    return new Promise( async (resolve, reject) => {

        try {

            await methods.methodOne()
            const output = await methods.methodTwo()
            await methods.methodThree(output)
            resolve()

        } catch(error) {

            console.log(error)
            reject(error)

        }

    })

}

}

A: You don't need the try/catch. You should use the promise .catch when awaiting for the methods.
You also don't need to return new Promise (...).
If your promise is rejected, it will go in the .catch of that promise, wich is different from regular catch.
You could just return nested promises.
runMethods: () => {
    return methods.methodOne()
            .then(() => methods.methodTwo())
            .then(output  => methods.methodThree(output))
}

A: I usually come at it this way.

const methods = {

    methodOne: () => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log('method1')
                resolve()
            },1000)

        }).catch(e=>console.log(e))
    },
    methodTwo: () => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log('method2')
                resolve()
            }, 1000)
        }).catch(e => console.log(e))

    },
    methodThree: () => {
        return new Promise((resolve, reject) => {

            setTimeout(() => {
                console.log('method3')
                reject('whoops something happened')
            }, 1000)
        }).catch(e => console.log(e))
},

    runMethods: () => {
        let run = new Promise(resolve=>resolve(true))
        run
            .then(result1 => methods.methodOne())
            .then(result2 => methods.methodTwo())
            .then(result3 => methods.methodThree())
            .catch(e=>console.log(e))
    }
}

methods.runMethods()


text:
Q: How to determine true/false sharing misses in cache coherence? I have a question regarding True/False sharing miss in Cache coherence.
Xl and X2 are in the block B. The block B is initially in the private caches of processors Pl and P2. The system uses MSI protocol. The following sequence of events are given

*

*P2 writes Xl,

*P2 reads X2,

*Pl reads X2,

*P2 writes Xl,

*P1 writes X2,

*P2 reads X2.

I figured out that (3) will be false sharing miss, as (1) invalidated the copy of B in P1 even though there was no change in value of X2. And (6) should be True sharing miss as (5) updated X2 and it needs to be communicated to P2.
How to categorise others ( as True/False sharing miss) ? A good explanation for each categorisation is appreciated.
I am really confused with True sharing miss concept. False sharing miss is so easy to understand.
If more information required, please comment.

A: I am not familiar with your terminology.  In false sharing, the meaning of false is incorrect, rather than a boolean or logical fallacy.  Typically, to analyze it, you look at the state the block will be in after each op; and the transactions for achieving that state. For example, assuming MESI cache protocol:
op#  P1   P2   Trans
 0    I    I   0          -- assume invalid to start
 1    I    M   R+I
 2    I    M   0
 3    S    S   r
 4    I    M   X
 5    M    I   r+I
 6    S    S   r

The transactions are R=system Read, I=Invalidate, r=local Read.  If you are an arm-type, think system = outer, local = inner.  So we see 1*Read + 3*cacheread + 2*Invalidate; or, condensed, 3 system, 3 local.
Now, if we assume X1 & X2 were in separate blocks
op#   P1     P2       Trans
 0    I,I    I,I
 1    I,I    M,I      R+I
 2    I,I    M,S      R
 3    I,S    M,S      r
 4    I,S    M,S      0
 5    I,M    M,I      R+I
 6    I,S    M,S      r

we see 3*Read 2*cread 2*Invalidate; or 5 system, 2 local.
From that, it appears that placing X1, X2 into separate blocks will not appreciably improve this workload.  Even if the Invalidate + Read were collapsed,


text:
Q: How can I calculate the centroid of polygon? What is the way to calculate the centroid of polygon? I have a concave polygon of 16 points, and I want know the centroid of that.
thanks

A: II.  SOLVE THE PROBLEM
Why doesn't a simple mean give the position of a centroid in a polygon? leads to formulas.
Frown.  I want to know how to set up and solve the problem. A solution can always be converted to a formula. The reverse --figuring out how a problem was solved by looking at the formula-- is very hard.  So I will solve problem from scratch.
A working demonstration of the method below can be found here.  The linked document is a Geogebra worksheet; feel free to download it, examine the code, and use it as you see fit.
A. Observation
The centroid of triangle $\Delta ABC$ is the simple average of its vertices:
$\;\;\;D = (A+ B + C)/3$.  What? Point order does not matter here: take the vertices A,B,C, in any order, they are the same triangle.  To prove the formula is correct, I might Integrate the triangle area; Find the balance point of figure ABC; or, with compass and straightedge, draw the intersection of the medians.  I say, the point is the same in every case.
B. Procedure
I will convert the problem into one I know how to solve:
Proposition: Find the centroid of a set of weighted points.

*

*Chop Jerome up into mutually exclusive triangles.

*Say there are m triangles. For each triangle $\;\Delta_k, \;k =1, 2, \ldots, m,\;$ find the centroid $C_k$, and the area (weight) $w_k$.  The set of weighted points is then $[\frac{w_k C_k}{J}],$ where J is the area of Jerome.

*Solution:  Add 'em up.
I say, the resulting point is the centroid of the polygon.
I have a general solution (I can always carry out this procedure). But it's messy: I don't have a triangulation rule. Now what? A good way to generalize is to start with a case I can solve.
C. Case: Jerome is Convex
It is commonly known that, given a convex polygon $P$, we may choose any vertex, $V,$ draw segments from $V$ to every non-adjacent vertex, and $P$ is correctly triangulated.
I will also use the following formulas:
 -Let any two sides of $\Delta ABC$ be vectors ${\rm  u =(u_1, u_2),\;\; v= (v_1, v_2)}.\;$  Then
 $\;\;\;{\rm Area}_{\Delta ABC} = \tfrac{1}{2}|{\rm  u \times  v}|,\;\;\;\;\;$where (the determinant) ${\rm u \times v}={\rm u_1 v_2-u_2 v_1}$.
-Let sides $AB, AC$ of $\Delta ABC$ be vectors ${\rm  u, v}.\;$  Then the centroid D= (A+B+C)/3 can be written
 $\;\;\;D = A + \tfrac{1}{3}|{\rm  u +  v}|.$
I have gathered what I need.
D. Solution

*

*Let the counterclockwise path of my n-gon be given, in order, by
$\;\;[A_i] = A_1, A_2, \ldots, A_n$ For covenience, I choose $V=A_1$.

*Draw the n-1 vectors from A_1 to the other vertices:
$\;\;[{\rm a_i}] = (A_{k+1}-A_1),\;\; k = 1, 2, \ldots n\!-\!1$

*I have n-2 adjacent triangles with centroids
$\;\;[C_i] = A_1 + \tfrac{1}{3}{\rm (a_k+a_{k+1})},\;\; k = 1, 2, \ldots n\!-\!2$
And areas (weights)
$\;\;[w_i] = \tfrac{1}{2}{\rm (a_k\times a_{k+1})},\;\; k = 1, 2, \ldots n\!-\!2$
(I dropped the absolute value: counter-clockwise, ${\rm u \times v}$ is positive.) Then
Total area = $\sum_{k=1}^{n-2} w_k$ and

*The centroid $C_J$  of Jerome is the sum of weighted triangle 'roids, divided by total area:
$\;\;C_J= {\large \frac{\sum_{k=1}^{n-2} w_k C_k}{\sum_{k=1}^{n-2} w_k}}$,

which can be written
$$(2)\;\;C_J= A_1+{\large \frac{1}{3} \frac{\sum_{k=1}^{n-2} ({\rm a_k+ a_{k+1}})({\rm a_k \times  a_{k+1}})}{\sum_{k=1}^{n-2} ({\rm a_k \times  a_{k+1}})}
}$$
I say, that this is in fact the complete solution: the determinants give signed areas: +/- according as the direction of rotation from $A_k$ to $A_{k+1}$, about $A_1$ is positive or negative, preserving measure in either case.
Being the thing to be done.

A: I. CONSIDERATIONS.
(In 2 parts.  The formulas are at the end of each.)
Case: Point List
I have sixteen marbles of equal mass.  Let us agree they all lie in one plane.
Q1: What is the center of mass of the set of marbles?
The center of mass of a sphere is its center.  So let the coordinates of the marble centers be:
$\;\;\;\;\;Pts = A_1, A_2.... A_{16}. $
To find the centroid C, average them:
$(1)\;\;\;\;\;C =(A_1+A_2+....+A_{16})/16.  $

Case: Polygon
Now, using (Pts) as the vertices, I cut out a 16-sided polygon, Jerome.
Q2: What is the center of mass of Jerome?
This is not the same question.  How can I ask it correctly? Consider (1) above.  What has changed? I see two problems:

*

*There are many concave polygons through 16 given points.  Which did I cut out? I must uniquely identify the region (area) I want to measure. Here are two ways:
a) Break up Jerome into distinct, convex regions. If a set of points
are the vertices of a convex polygon, that polygon is unique. Each
convex region of Jerome is uniquely determined by its vertices.
b) Arrange Pts so that the order (A1 -> A2 -> A3 .... ->An) follows the perimeter in a single direction, without leaps or self-intersections.  A unique perimeter is a unique polygon.
Both ways allow me to draw the figure.  Note that the simple average (mean) does not distinguish order; it can't give the correct answer.

*Jerome is a plane figure:  Its mass is proportional to area.  But "the mean of coordinates" is not the same thing as "proportional to area".  Area of what? Again, the mean can't, in general, give an answer.
I now have a unique definition of the task.  I have also discarded the simple average where it can't apply, without knowing the answer or doing any math. Going a bit further, it seems that the mean could be right if the vertices are equally distributed about a common center (this hunch turns out to be correct; e.g. regular polygons).
Now to solve the problem...
(A correct formula is given here: Why doesn't a simple mean give the position of a centroid in a polygon? , but I want to know how to obtain that formula.)


text:
Q: find all the values of a and b so that the system has a) no solution b) 1 solution c) exactly 3 solutions and 4) infinitely many solutions $$\begin{cases}
&x  &- &y &+ &2z &= 4 \\
&3x &- &2y &+ &9z &= 14 \\
&2x &- &4y &+ &az &= b
\end{cases}
$$
I know that $a$ and $b$ has to either equal to something or not in order to satisfy the $4$ conditions stated above.
my matrices looked like
$$
        \begin{bmatrix}
        1 & -1 & 2 \\
        0 & 1 & 3 \\
        0 & 0 & a+12 \\
        \end{bmatrix}
\begin{bmatrix}
        x & \\
        y &\\
        z &  \\
        \end{bmatrix}=
\begin{bmatrix}
        6 &  \\
        2 & \\
        b+8 & \\
        \end{bmatrix}
$$

A: Apply Gaussian Elimination to the reduced matrix.
$$
\pmatrix{1 & -1 & 2 &  4\\3 & -2 & 9 & 14\\2 & -4 & a & b} \to
\pmatrix{1 & -1 & 2 &  4\\0 &  1 & 3 &  2\\0 & -2 & a-4 & b-8} \to
\pmatrix{1 & -1 & 2 &  4\\0 &  1 & 3 &  2\\0 &  0 & a+2 & b+4}
$$
So

*

*if you want a unique solution, $\frac{b+4}{a+2}$ must be defined, i.e. $a \neq -2$.

*if you want infinite number of solutions, $a=-2$ and $b = -4$ removes the last equation.

*if you want no solutions, $a=-2$ and $b \neq -4$.


text:
Q: Get the count of newly published product (today) in WooCommerce I have a WooCommerce site where products are considered as trade/deal. Therefore, when someone take a trade (buy a product), it become out of stock.
How to display the number of products that has been published today (the new ones)?
ex: 4 New Trades (products) Published Today

A: The custom function below will return with a SQL query the newly published products count (made in the 24 hours):
function get_new_products_count(){
    global $wpdb;

    // 24 hours ago
    $is_24h_ago = date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s")." -1day"));

    // The SQL query
    $result = $wpdb->get_col( "
        SELECT COUNT(p.ID)
        FROM {$wpdb->prefix}posts as p
        WHERE p.post_type LIKE '%product%'
        AND p.post_status LIKE 'publish'
        AND p.post_date > '$is_24h_ago'
    " );

    return reset($result);
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and working

Usage example (in any php file):
$count = get_new_products_count();
$message = sprintf( __( '%s new trades have been published…' ), $count );
echo '
'.$message.'
';

will display something like:


text:
Q: Нахождение максимального и минимального значения в массиве Найти минимальное и максимальное значение в массиве. Сохранить максимум и минимум в отдельной переменной.
Реализованный алгоритм:
    String gg = "-65649 -28979 -7098 60269 -20815 -13380 -78850 -7601 -62340 -1522 16584 57888 58337 58659 58809 29382 132 -56100 -14701 74564 11098 -79380 28418 -31457 50295 -44985 40248 -52332 25183 5280 71982 39533 56300 -15116 19802 -44514 51503 20952 27884 69163 -60570 -35531 47052 77766 -56872 25861 27149 23260 49761 -67551 17824 -19140 -66932 -33758 29402 63363 1257 -10350 -68969 -53559 74929 -76987 65973 51230 -12104 5776 -73284 -40600 -53272 34600 -51436 -33843 79068 75615 -36076 -57803 21476 71072 45456 -8762 -76479 -16719 52097 -63411 29523 1499 79951 -49220 71149 -69018 -22780 66078 -66005 -36806 37309 1891 48969 44025 41291 75697 -1374 69854 -38146 -2305 65469 5778 19891 6946 -3150 -14652 78183 371 48628 50281 16959 -1849 -28220 16910 28931 -37071 27892 -73848 -50992 41887 -30655 66317 -36222 -61685 30342 -74930 -65987 -51032 74923 -24134 26663 60392 61644 -33446 -12661 -21506 31901 -14478 58864 530 -44197 -4176 78680 7583 -67265 27612 50512 40627 33764 79520 2514 -76891 65837 46292 -58576 16180 51361 -44564 45148 46285 11302 -8189 26677 -7054 38365 -65983 51440 -9734 -462 30305 70795 35341 -53870 69476 -37075 -41136 17089 -66562 79490 -29147 -67042 2005 -26038 78795 -31702 -4615 14975 -60340 30821 -19876 65944 -37876 51934 12622 35070 10300 26638 6510 -79434 -53823 -43184 71361 61518 -17055 60838 -55557 21808 -2073 -42119 21299 48779 -29162 -56695 -57258 -30367 -8397 18127 64608 11262 -31052 -35267 -2793 11072 -63332 -70170 -33858 26967 36467 52652 27532 62644 -70532 18894 44162 -7588 -267 68605 -65779 77659 -53514 35519 46439 -2676 58824 69181 46957 -29573 7308 31566 61689 56256 76298 -21104 -12672 -67034 -11274 33470 39932 -54806 6122 -12536 -72162 15589 -73641 52000 -71998 6091 40606 -57778 3751 67092 57741 -29809 -15584 36566 -40628 -48626 -73007 46679 62939 68682 22935 59237 -32421 -69736 72202 36304 43733 32134 61497 -30145 -60401 69334 65444 -54042 41335";
    String[] mas = gg.split(" ");

    int[] mas_int = new int[mas.length];
    int counter = 0;

    for (String str : mas) {
        try {
            mas_int[counter] = Integer.parseInt(str);
        } catch (Exception error) {
            System.out.println("str = " + str);
        }
        counter++;
    }

    System.out.println("Колличество символов: " + mas_int.length);
    int max = mas_int[0], min = mas_int[1];

    for (int i = 0, j = 1; j < 300; i += 1, j += 1) {
        if (mas_int[i] >= mas_int[j]) {
            max = mas_int[i];
        }
        if (mas_int[i] < mas_int[j]) {
            min = mas_int[i];
        }
        if (mas_int[j] > mas_int[i]) {
            max = mas_int[j];
        }
        if (mas_int[j] < mas_int[i]) {
            min = mas_int[j];
        }

    }
    System.out.println("Максимум " + max + "\nМинимум " + min);
}

При выполнении кода выводит не правильные значения.

A: Можно так - отсортировать и взять первое и последнее значение массива
Arrays.sort(arrInt);
int min = arrInt[0];
int max = arrInt[arrInt.length-1];

A: Ошибка в цикле:
for (int i = 0; i < mas_int.length; i++) {
    if (max <= mas_int[i]) {
        max = mas_int[i];
    }
    if (min >= mas_int[i]) {
        min = mas_int[i];
    }


text:
Q: Ubuntu UFW: how to add ipv6 tcp/udp rule? For example, what is the ipv6 only equivalence of ufw allow 22/tcp?
UFW documentation does not list valid protocol names, and I could not figure out the protocol name for tcpv6.

A: To allow IPv6 through the firewall, first perquisite is to add to
/etc/default/ufw the following line:
IPV6= yes

From now on, the syntax for ufw allow is exactly the same,
with IPv6 addresses used instead of IPv4.
For example, to allow all link-local addresses :
ufw allow from fe80::/64


text:
Q: Error in the execution of a video in ubuntu in Ubuntu, I downloaded a video, with the format avi, and when I open the file video, it gets an error, and it doesn't execute.
The error is, why it doesn't define the flux type.

What is this error?
Thank you.


text:
Q: How to enumerate installed metro applications (native API) Is there some native Windows API to enumerate installed metro applicatons?
I was able to find only examples which use .net like this one. There is also Package Query API which I am using in my application to get info about concrete application, but there is no way to enumerate applications with this API.


text:
Q: OpenShift, Tomcat7 and JDBC Realm I am trying to deploy JaveEE Tomcat7 based application to OpenShift. Whole configuration is based on Tomcat 7 (JBoss EWS 2.0) catridge. Up to now I'd developed my application locally and all worked fine including JDBCRealm based user's authentication.
Project spec, pom.xml attached at the end of the post:

*

*entirely maven based

*tomcat used via artifact org.apache.tomcat.maven
But now I need to make my app available in web, so I decided to go to OpenShift, where I created Tomcat7 application (which is also maven based). Deployment was successful but I am having trouble with JDBCRealm now, which worked locally. The problem is that tomcat fails to find MySQL driver to open realm connection. I'd solved this problem with org.apache.tomcat.maven by specifying my context.xml and adding mysql dependency. Howeever maven-war-plugin which seems to not have an option to inject the dependency. So i am stucked with an error like this:
mar 30, 2013 8:59:08 AM org.apache.catalina.realm.JDBCRealm authenticate
SEVERE: Exception performing authentication
java.sql.SQLException: com.mysql.jdbc.Driver
    at org.apache.catalina.realm.JDBCRealm.open(JDBCRealm.java:706)
    at org.apache.catalina.realm.JDBCRealm.authenticate(JDBCRealm.java:352)
    at org.apache.catalina.authenticator.BasicAuthenticator.authenticate(BasicAuthenticator.java:158)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:544)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:188)
    at org.apache.catalina.realm.JDBCRealm.open(JDBCRealm.java:702)
    ... 14 more

and pom.xml like this, which does not do the job:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>majekwms</groupId>
    <artifactId>majekwms</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>majekwms</name>

    <developers>
        <developer>
            <id>kornicameister</id>
            <email>kornicameister@gmail.com</email>
            <name>Tomasz Trębski</name>
        </developer>
    </developers>

    <repositories>
        <repository>
            <id>eap</id>
            <url>http://maven.repository.redhat.com/techpreview/all</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>eap</id>
            <url>http://maven.repository.redhat.com/techpreview/all</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
    <properties>
        <maven.compiler.source>1.6</maven.compiler.source>
        <maven.compiler.target>1.6</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <json-simple.version>1.1.1</json-simple.version>

        <jdk.version>1.7</jdk.version>
        <log4j.version>1.2.17</log4j.version>
        <mysql.version>5.1.9</mysql.version>
        <tomcat.maven.version>2.0</tomcat.maven.version>
        <maven.compiler.version>3.0</maven.compiler.version>
        <junit.version>4.11</junit.version>
        <hibernate.version>4.2.0.CR1</hibernate.version>
        <hibernate-annotations.version>3.5.6-Final</hibernate-annotations.version>
        <hibernate-common-annotations.version>3.3.0.ga</hibernate-common-annotations.version>
        <gson.version>2.2.2</gson.version>
        <slf4j-log4j12.version>1.7.2</slf4j-log4j12.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.jboss.spec</groupId>
            <artifactId>jboss-javaee-6.0</artifactId>
            <version>3.0.0.Final-redhat-1</version>
            <type>pom</type>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j-log4j12.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <!--json-->
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>${json-simple.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>${gson.version}</version>
        </dependency>
        <!--json-->

        <!--hibernate-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-ehcache</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>${hibernate-annotations.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0.2</version>
        </dependency>
        <!--hibernate-->

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-servlet-api</artifactId>
            <version>7.0.21</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <profiles>
        <profile>
            <!-- When built in OpenShift the 'openshift' profile will be used when
                invoking mvn. -->
            <!-- Use this profile for any OpenShift specific customization your app
                will need. -->
            <!-- By default that is to put the resulting archive into the 'webapps'
                folder. -->
            <!-- http://maven.apache.org/guides/mini/guide-building-for-different-environments.html -->
            <id>openshift</id>
            <build>
                <finalName>majekwms</finalName>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-compiler-plugin</artifactId>
                        <version>${maven.compiler.version}</version>
                        <configuration>
                            <source>${jdk.version}</source>
                            <target>${jdk.version}</target>
                            <encoding>${project.build.sourceEncoding}</encoding>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.tomcat.maven</groupId>
                        <artifactId>tomcat7-maven-plugin</artifactId>
                        <version>${tomcat.maven.version}</version>
                        <configuration>
                            <url>http://127.6.35.1:8080/MajekWMS/</url>
                            <mode>both</mode>
                            <path>/MajekWMS</path>
                            <uriEncoding>UTF-8</uriEncoding>
                            <contextReloadable>true</contextReloadable>
                            <contextFile>src/main/tomcat/context.xml</contextFile>
                        </configuration>
                        <dependencies>
                            <dependency>
                                <groupId>mysql</groupId>
                                <artifactId>mysql-connector-java</artifactId>
                                <version>${mysql.version}</version>
                            </dependency>
                        </dependencies>
                    </plugin>
                    <plugin>
                        <artifactId>maven-war-plugin</artifactId>
                        <version>2.1.1</version>
                        <configuration>
                            <attachClasses>true</attachClasses>
                            <classesClassifier>classes</classesClassifier>
                            <containerConfigXML>src/main/tomcat/context.xml</containerConfigXML>
                            <outputDirectory>webapps</outputDirectory>
                            <warName>ROOT</warName>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

And of course my context.xml, which seems to be detected and tomcat tries to read configuration from it, but since mysql driver is missing it fails with SQLException:
<?xml version="1.0" encoding="UTF-8"?>
<Context
        className="org.apache.catalina.core.StandardContext"
        reloadable="true"
        antiJARLocking="true"
        swallowOutput="true">
    <Realm connectionName="user_name_here"
           connectionPassword="pass_here"
           connectionURL="jdbc:mysql://localhost:3306/majekwms?useUnicode=true&characterEncoding=utf8"
           roleNameCol="role"
           userCredCol="secPassword"
           userNameCol="login"
           userRoleTable="userRole"
           userTable="user"
           driverName="com.mysql.jdbc.Driver"
           digest="md5"
           className="org.apache.catalina.realm.JDBCRealm"/>
</Context>

A: Thank you for posting on our forums: https://www.openshift.com/forums/openshift/openshift-tomcat7-and-jdbc-realm#comment-28951
Here's a forum thread that covers this topic: https://www.openshift.com/kb/kb-e1040-using-your-own-jar-files-in-a-java-applica...
Can you please take a look at it and see if it helps? Then, if you are still unable to connect, please let us know.

A: Giving that in openshift you can deploy only one webapp, you must edit global context.xml and server.xml to configure a DataSource.
Also you need to add database jar driver somewhere where you have write permissions and tomcat can find it.
here you can show how.


text:
Q: How can I create and update two different models in the same page in ruby on rails? I have two models, Group and Type.
Group:
------
group_code, group_name

Type:
-----
group_code, type_code, type_name, use_in_location, type_summary

group_code is the foreign_key to types.
Each Group has multiple Types. I want to create a form for Group and Type in a same page. So When I click edit of the Group table, it will also show the Type fields to edit in the same page.
How can I achieve this? Do I need to create separate controllers, views for both group and types? Please somebody suggest with an examples.
Thanks

A: You should check railscasts.com episode on nested forms. Episode 1 and Episode 2


text:
Q: Zabbix file last modify date check problem I added to my zabbix (4.2.5) this ITEM
vfs.file.time[/home/PATH_TO_FILE/MY.log,modify]

And I receive this error "Cannot obtain file information: [13] Permission denied"
But if i log on VM to test and launch command
zabbix_agentd -t "vfs.file.time[/home/PATH_TO_FILE/MY.log,modify]"

agent return "[u|1595559607]" correct data.
So I tryed to run agent command as zabbix user....
runuser -l zabbix -c 'zabbix_agentd -t "vfs.file.time[/home/PATH_TO_FILE/MY.log,modify]"'

runuser: warning: cannot change directory to /var/lib/zabbix: File o directory not exists
This account is currently not available.
becouse zabbix agent user is
zabbix:x:997:995:Zabbix Monitoring System:/var/lib/zabbix:/sbin/nologin

Zabbix agent is latest 5.x
How can I solve it?

A: *

*which user are you logged in as, and which user is Zabbix Agent running as?

*which permission has the file, and the container folders?

*you can't use  runas -l zabbix because user is locked, you should use

*

*from the zabbix server (or proxy): zabbix_get -s ip/hostname -k vfs.file.time[/home/PATH_TO_FILE/MY.log,modify]

*from the monitored host: su - zabbix -s /bin/sh -c 'zabbix_agentd -t "vfs.file.time[/home/PATH_TO_FILE/MY.log,modify]"'


text:
Q: CanCan 2.0 + Paperclip expiring_url I set some files using Paperclip expiring_url. Those are working fine.
I try using CanCan 2.0 to allow expiring_url only to signed members using the following code
# /app/models/ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new  # guest user
    can :read, :movies
    cannot :read, :movies, :expiring_url

    if user.persisted?
      can :read, :movies, :expiring_url
    end

  end
end

My MoviesController.rb has load_and_authorize_resource still all users are being able to download the movie.
expiring_url is not an attribute of Movie and I can see that is the reason why is not working. I'm not sure how can specify the paperclip expiring_url object associated to this in order to make it work.
Any idea how to do this?

A: Cancan apparently requires the conditions to be actual database columns, according to the statement on this page:

It is important to only use database columns for these conditions

This isn't a limitation in paperclip, it's cancan (which I love quite a bit, don't get me wrong).

A: I use CanCan 1.6.x, but under Defining Abilities in the 2.0 docs,  Ryan says

The current_user is passed in allowing you to define permissions based on user attributes.

so if you have a current_user would not something like below work for you?
if user
  can :read, :movies, :expiring_url
else
  can :read, :movies
end

Can you provide more info about what "expiring_url" is? I just realized the above probably won't work for you either since expiring_url doesn't sound like a model.


text:
Q: Why current directory doesn't change in makefile? I'm trying to run a simple script- clone a git repository into a certain directory, then cd to this directory in order to execute an installation script.
This script is in a Makefile.
But the cd seems not to be working. It doesn't find my installation script.
I added a pwd after the cd in the script, and it shows me the directory from where I'm executing the script, not the directory where I cd into.
What's the problem?
git clone http://somerepo ~/some_dir
cd ~/some_dir/
pwd
python myscript.py install

=>
pwd: /hereIsPathToDirectoryFromWhichIRunTheScript

python: can't open file 'setup.py': [Errno 2] No such file or directory

It also doesn't work with ./setup.py.
If I enter the absolute path ~/some_dir/setup.py the script fails later because it's trying to access resources in the same folder.

A: You're using a makefile. Makefiles aren't scripts, each line is executed in a new shell. Meaning when you change the environment in line (such as cd), that change is not propagated to the next line.
The solution is that when you want to preserve the environment between commands, you run all the commands in the same line. All the commands will then be executed in the same shell, and the environment is preserved.
For example:
target:
    git clone http://somerepo ~/some_dir
    cd ~/some_dir/ && python myscript.py install

A: since GNU  make version 3.82  you can add .ONESHELL: on the top of your Makefile and then cd folder will do the trick as you expect.
Read the docs

A: A script is run in a subshell, which means it has its own $PWD. Once it exits you get the "old" $PWD. If you want to keep the $PWD you need to source (aka. .) the script instead of running it. This won't work in a Makefile, however, because each command is run in a separate subshell:
$ pwd
/home/user
$ cat test.sh
cd /
$ cat Makefile
test:
    . ./test.sh && pwd
    pwd
$ make test
. ./test.sh && pwd
/
pwd
/home/user


text:
Q: Can't get xpi to work in TorBrowser I created a small little HelloWorld extension and was able to get it to work in Firefox 31 (which TorBrowser is based on). However I'm unable to get it to work in TorBrowser. Any idea why that might be and how I can fix? This is my main.js
var contextMenu = require("sdk/context-menu");
var menuItem = contextMenu.Item({
    label: "Log Selection",
    context: contextMenu.SelectionContext(),
    contentScript: 'self.on("click", function () {' +
        '  var text = window.getSelection().toString();' +
        '  self.postMessage(text);' +
        '});',
    onMessage: function (selectionText) {
    console.log(selectionText);
}
});

The context menu item shows up in FF but not TB.

A: Had to add "permissions": {"private-browsing": true} to the package.json
https://tor.stackexchange.com/questions/6293/sidebar-for-custom-addon-broken-in-tbb


text:
Q: What are the most commonly used words for use in identifiers? Naming variables, methods, and classes is hard.  Having a good vocabulary to choose from can make things easier, and choosing commonly used words can make your programs more easily understood by other programmers.
For example:

*

*Naming classes after common patterns (Builder, Factory, Observer, Iterator)

*Built-in classes  (Executor)

*Action verbs  (get, set, build, connect, execute)
Are there any compiled lists of the most commonly used words in programs to aid in name construction?
Some lists I have found so far:

*

*http://source-code-wordle.de/

A: For java: link
For c++: link
For c#: link
Googling "reserved words in [insert language here]" will get you the same thing for just about any language.


text:
Q: Definition of bit masks in objective-c I am learning Objective-c and I can't understand what are BitMasks, can anyone help me to understand it please? And I also don't know what is the function of this operator << is.

A: Objective C is an existing of C, and it uses the same bitwise operators. Lets take UIRemoteNotificationType as an example:
UIRemoteNotificationTypeNone    = 0,
UIRemoteNotificationTypeBadge   = 1 << 0,
UIRemoteNotificationTypeSound   = 1 << 1,
UIRemoteNotificationTypeAlert   = 1 << 2,
UIRemoteNotificationTypeNewsstandContentAvailability = 1 << 3,

The << is the shift left operator and its function is obvious once you look at the binary form:
1 << 0 = 1 (decimal) = 0000001 (binary)
1 << 1 = 2 (decimal) = 0000010 (binary)
1 << 2 = 4 (decimal) = 0000100 (binary)
1 << 3 = 8 (decimal) = 0001000 (binary)

It shifts a specific pattern (the left operand) to the left, the 'length' of the shift is determined by the right operand. It works with other numbers than 1; 3 << 2 = 12 because 0000011 (binary) shifted two places is 0001100. Translated to normal mathematics, a << b = a * 2^b.
The specific use of this pattern is that it is very easy to check if a certain option is set. Suppose I want my application to send notifications with badges and alerts. I pass the value UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert to the API, which is
UIRemoteNotificationTypeBadge = 0000001
UIRemoteNotificationTypeAlert = 0000100
                        total = 0000101 |

(the | is the bitwise OR operator; for every bit, the result is 1 if one or both of the corresponding bit of the operands is 1).
The API can then check if the badge property is present with the & operator:
                        total = 0000101
UIRemoteNotificationTypeBadge = 0000001
                       result = 0000001 &

(the & is the bitwise AND operator; for every bit, the result is 1 if both of the corresponding bit of the operands is 1).
The result is non-zero, so the badge property is present. Let's do the same with the sound property:
                        total = 0000101
UIRemoteNotificationTypeSound = 0000010
                       result = 0000000 &

The result is zero, so the badge property is not present.


text:
Q: This is a code that I followed in a YouTube video and it doesn't work I followed this YouTube tutorial code up to 11:55 in it and did exactly everything but I'm getting two errors:

The name 'Move' does not exist in the current context and method must have a return type.

This is the code for blend tree to move the character with animation:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private Animator _animator;

    // Start is called before the first frame update
    void Start()
    {
        _animator = GetComponent<Animator>();

    }

    // Update is called once per frame
    void Update()
    {
        if (_animator == null) return;

        var x = Input.GetAxis("Horizontal");
        var y = Input.GetAxis("Vertical");

        Move(x, y);
    }
    private Move(float x, float y)
    {
        _animator.SetFloat("VelX", x);
        _animator.SetFloat("VelY", y);
    }

}

A: Change this line
private Move(float x, float y)

to look like
private void Move(float x, float y)

The problem is that you haven't specified a return type for the method.


text:
Q: How to set engine in the PHP Openssl Extension? I am using the PHP Openssl Extension by calling openssl_sign() in my code.
My Openssl is configured to use 3 different engines (configuration located in '/etc/ssl/openssl.cnf')
My default engine is set to my custom engine and when I am calling RSA Sign from Command Line (openssl rsautl -sign) it does use my custom engine.
But when using the PHP Openssl Extension it only calls the "regular" Openssl Engine.
I do I force the Extension to use my custom engine ?


text:
Q: Virtal Assistant throwing 'Sorry it looks like something went wrong' I have created a virtual assistant using the Microsoft virtual assistant template. When testing in the emulator whatever message i send i am getting a 'something went wrong reply.'
I am new to the entire bot framework ecosystem and it is becoming very difficult to proceed.
In the log what i can see is:
    [11:26:32]Emulator listening on http://localhost:65233
[11:26:32]ngrok not configured (only needed when connecting to remotely hosted bots)
[11:26:32]Connecting to bots hosted remotely
[11:26:32]Edit ngrok settings
[11:26:32]POST201directline.startConversation
[11:26:39]<-messageapplication/vnd.microsoft.card.adaptive
[11:26:39]POST200conversations.replyToActivity
[11:26:54]->messagehi
[11:26:55]<-traceThe given key 'en' was not present in the dictiona...
[11:26:55]POST200conversations.replyToActivity
[11:26:55]<-trace at System.Collections.Generic.Dictionary`2.get_...
[11:26:55]POST200conversations.replyToActivity
[11:26:55]<-messageSorry, it looks like something went wrong.
[11:26:55]POST200conversations.replyToActivity
[11:26:55]POST200directline.postActivity
[11:27:48]->messagehello
[11:27:48]<-traceThe given key 'en' was not present in the dictiona...
[11:27:48]POST200conversations.replyToActivity
[11:27:48]<-trace at System.Collections.Generic.Dictionary`2.get_...
[11:27:48]POST200conversations.replyToActivity
[11:27:48]<-messageSorry, it looks like something went wrong.
[11:27:48]POST200conversations.replyToActivity
[11:27:48]POST200directline.postActivity

From what I understood the 'en' is not present in dictionary and I am not sure what is means. I checked in the Responses folder and could not see an en file not sure if that is the issue:

My emulator screenshot is attached:

Any help would be useful.

A: I believe the issue you are experiencing is a problem on the following lines inside MainDialog.cs:
var locale = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
var cognitiveModels = _services.CognitiveModelSets[locale];

This tries to use the locale (retrieved from the current thread as per this documentation) as the key to access the cognitive models in your cognitivemodels.json file.
Inside your cognitivemodels.json file it should look like:
{
  "cognitiveModels": {
    // This line below here is what could be missing/incorrect in yours
    "en": {
      "dispatchModel": {
        "type": "dispatch",
        "region": "westus",
        ...
      },
      "knowledgebases": [
        {
          "id": "chitchat",
          "name": "chitchat",
          ...
        },
        {
          "id": "faq",
          "name": "faq",
          ...
        },
      ],
      "languageModels": [
        {
          "id": "general",
          "name": "msag-test-va-boten_general",
          "region": "westus",
          ...
        }
      ]
    }
  },
  "defaultLocale": "en-us"
}

The en key insides the cognitiveModels object is what the code is trying to use to retrieve your cognitive models, thus if the locale pulled out in the code doesn't match the locale keys in your cognitivemodels.json then you will get the dictionary key error.
EDIT
The issue the OP has was a failed deploy. The steps we took were to:

*

*Checked the deploy_log.txt inside the Deployment folder for errors.

*

*If this case it was empty - not a good sign.

*Checked the deploy_cognitive_models_log.txt inside the Deployment folder for errors.

*

*There was an error present Error: Cannot find module 'C:\Users\dip_chatterjee\AppData\Roaming\npm\node_modules\botdispatch\bin\dispatch.js.

*

*To fix this error we reinstalled all of the required npm packages as per step 5 of this guide then ran the deploy script as per this guide.


text:
Q: Whether the set $A$ , $ A=\{y\in R : y= \lim_{n\rightarrow \infty} f(x_{n}) \text{ where } x_n \text{ diverges to } +\infty \}$ is connected Let  $f: \mathbb R \rightarrow \mathbb R$ be  continuous  function  and  $A\subset \mathbb R$ be  defined  by  $$ A=\{y\in R : y= \lim_{n\rightarrow \infty} f(x_{n}) \text{ where } x_n \text{ diverges to } +\infty \}$$
Then $A$  is
A. Connected
B. Compact
C. Singleton
D. None  of  the  above
Now by taking $f(x)=\sin(x)$ I see C. do not hold but A. and B. do. But  how to ensure that what must be correct for all continuous functions or  not  and what special role the divergence of that sequence $x_n$ plays there?

A: To see that $A$ must be connected:
Let $a$ and $b$ be elements of $A$ with $a < b$ and let $c$ be some real number in between them (so $c \in (a,b)$).  We need to show that $c\in A$.  To do that we'll show that there are arbitrarily large values $z$ such that $f(z)=c$. Choose $\epsilon > 0 $ so that $a<a+\epsilon<c<b-\epsilon<b$.  By definition of $A$ we can find arbitrarily large $x$ and $y$ such that $|f(x)-a|<\epsilon$ and $|f(y)-b|<\epsilon$.
Choose your cut off $M$. (we want to find $z>M$ such that $f(z) = c$).  But choose $x$ and $y$ as above, requiring that both be larger than $M$. Then $f(x)<c<f(y)$ so the intermediate value theorem guarantees the existence of the $z$ we want.

A: As has been sort of said, $x\sin(x)$ is a counterexample to (B) and to (C).
But (A) is true. (And this is really awful notation, using "A" for a certain set and also for a condition that set may or may not satisfy).
It's enough to show that if $a,c\in A$ and $a<b<c$ then $b\in A$. Say $x_n\to\infty$, $f(x_n)\to a$, $z_n\to\infty$ and $f(z_n)\to c$.
For each positive integer $k$ there exist $n$ and $m$ such that $x_n>k$, $z_m>k$, $f(x_n)<b$ and $f(z_m)>b$. The intermediate value theorem shows that there exists $y_k$ between $x_n$ and $z_m$ such that $f(y_k)=b$. And $y_k\to\infty$, since $x_n>k$ and $z_m>k$.


text:
Q: is provisioning storage in VMAX difficult? is provisioning storage in VMAX difficult? I am not getting any sort of training from my manager .There's going to be requests fro the clients in provisioning storage to their hosts (cluster, stand alone) .
I have gone through few doc but there's not much information there.I request guys here to help me with a proper link ,if not the explanation ,on how to provision storage from VMAX.
I know many people here would have worked on VMAX and allocated storage. Please guide me as i am in desperate need.
Any link related to that will be greatly appreciated.
thanks!!

A: I hope this isn't too late, but provisioning storage is pretty easy on the VMAX.  A quick guide can be found here.  In short, you'll need to create:

*

*A storage group that groups your devices

*A port group that groups your directors and ports

*An initiator group that contains your hosts and WWNs

*And a masking view, which ties your three groups together


text:
Q: using-declaration for overloaded inherited function template leads to "ambiguous call to overloaded function" I have a base class template C that implements multiple overloads of a function c(), of which one is a function template, and a sub class D that inherits from C and re-implements the function template.
D::c() causes all overloads of C::c() to be hidden in D. As I want the overloads that are not re-implemented by D to not be hidden, D makes them available via using C<D>::c;
This works fine if all overloads of c() are non templated functions: The base implementations are available to users of D for overloads that D does not re-implement, but for overloads that D re-implements, the implementation from C becomes unavailable to users of D and the implementation from D is used instead.
However if the re-implemented function is a function template, then the same approach leads to a compiler error in MSVC.
"ambiguous call to overloaded function
could be 'void D::c<int>(FT)
or       'void C::c<int>(FT)'"

Apparently with templates the C implementation stays available to D users and conflicts with the re-implementation in D.
template<typename T>
class C
{
public:
    void c(void){}
    template<typename FT> void c(FT param){}
};

class D : public C<D>
{
public:
    using C<D>::c;
    template<typename FT> void c(FT param){}
};

int main()
{
    D d;
    d.c<int>(1);
}

clang and G++ both compile this code just fine, while MSVC 11, 12, 14 and 15 all fail to compile it.
A simplified version of the code in which C is not a template, but an ordinary class, still fails to compile in MSVC 11 and 12, but compiles fine in MSVC 14 and 15.
With the usual approach not working is there any better approach in C++03 for re-implementing an inherited overloaded function template than to abstain from using using C<D>::c and instead adding re-implementations for all overloads, of which some do nothing more than only calling their base implementation?
Note:
I can't use C++11 or any newer standards.


text:
Q: Creating text files in every sub-directory I have a directory hierarchy named, for example, abc and a text file names.txt. I need to choose several lines from the text file and then create new files with sample text, say "Hello world", in every sub-directory of the abc, where every chosen line from the names.txt is the name for one of the new files. I have to do it in one line using xargs or -exec. I've tried something like this but it doesn't seem to work:
find abc -type d -exec sh -c 'grep ^'A' names.txt | xargs -I% sh -c 'echo 'Hello world' | tee {}/%'' \;

How to do this the right way?

A: Let's start with what you need to for one directory:
awk '/^A/ { print "Hello world" >$0 }' names.txt

This would read the file called names.txt and write the string Hello world to each filename given by a complete line of input from that file, if the input line starts with a capital A.
With a small modification, we can get it to output to a file under a specific directory, $dirname:
awk -v dir="$dirname" '/^A/ { print "Hello world" >(dir "/" $0) }' names.txt

We may then use find to call this for each subdirectory (including the start directory):
find abc -type d -exec awk -v dir={} '/^A/ { print "Hello world" >(dir "/" $0) }' names.txt \;


text:
Q: Usar las propiedades de una lista anidada en un hashmap para guardar resultados Estoy intentando guardar los datos de un formulario dinámico en un mapa cuyo valor es una lista de objetos, el problema está en que cuando llego al método POST correspondiente, en el mapa, las entryKey están todas bien con sus objetos correspondientes pero cuando miro el valor table del mapa las que deberían estar rellenas aparecen como null.
El mapa es el siguiente, lo inicializo antes de procesar los datos:
private Map<String, List<FilterForm>> filtros = new LinkedHashMap<String, List<FilterForm>>();

public CustomSearchForm() {
        this.filtros.put("datos_personales", new ArrayList<FilterForm>());
        this.filtros.put("datos_institucion", new ArrayList<FilterForm>());

}

Antes de recger los datos seteo las listas con todos los campos.
public void setDefaultFilters(SearchService ss) {
        SearchType type = (SearchType) ss.findTypeById(searchType);
        this.searchTypeName = type.getName();
        FilterForm filterForm = null;
        SearchTable table = (SearchTable) ss.findTableByAlias(searchTable, searchType);
        List<FilterForm> filters = new ArrayList<FilterForm>();
        for (SearchField field : table.getFields()) {
            filterForm = new FilterForm(field.getName(), field.getAlias(), field.getF_type().getName());
            filters.add(filterForm);
        }
        if (searchTypeName.equals(Constantes.SEARCH_TYPE_PERSONAS)) {
            switch (searchTable) {
            case "Datos personales":
                this.filtros.get("datos_personales").addAll(filters);
                break;
            case "Formas de contacto":
                this.filtros.get("p_formas_contacto").addAll(filters);
                break;
            case "Instituciones":
                this.filtros.get("p_instituciones").addAll(filters);
                break;
            case "Relaciones":
                this.filtros.get("p_relaciones").addAll(filters);
                break;
            case "Patronos":
                this.filtros.get("p_patronos").addAll(filters);
                break;
            case "Candidatura":
                this.filtros.get("p_candidatura").addAll(filters);
                break;
            }
        } else if (searchTypeName.equals(Constantes.SEARCH_TYPE_INSTITUCIONES)) {
            switch (searchTable) {
            case "Datos de la institución":
                this.filtros.get("datos_institucion").addAll(filters);
                break;
            case "Candidatura":
                this.filtros.get("i_candidatura").addAll(filters);
                break;
            case "Formas de contacto":
                this.filtros.get("i_formas_contacto").addAll(filters);
                break;
            case "Patronos":
                this.filtros.get("i_patronos").addAll(filters);
                break;
            case "Empleados":
                this.filtros.get("i_empleados").addAll(filters);
                break;
            }
        }
    }

Y recojo los datos de la siguiente forma:

    <select th:id="'accion_'+${f.key}+'_'+${status.index}" onchange="cambioCombo(this);" th:if="${ff.tipoCampo != 'Booleano'}" class="form-control select2me" form="customSearch"
        placeholder="Acción"
        th:field="*{filtros[__${f.key}__][__${status.index}__].accion}">
        <option th:each="a : ${customSearch.ACCIONES}" th:value="${a}"
                th:text="${a}"></option>
    </select>

    <input th:id="'valueField_'+${f.key}+'_'+${status.index}" th:if="${ff.tipoCampo == 'Numero' or ff.tipoCampo == 'Texto' or ff.tipoCampo == 'Tabla'}" form="customSearch"
        type="text" class="form-control" placeholder="Valor"
        th:field="*{filtros[__${f.key}__][__${status.index}__].value}" />

        <input form="searchForm"
            class="form-control input-lg date" th:id="'valueFieldDate_'+${f.key}+'_'+${status.index}"
            th:field="*{filtros[__${f.key}__][__${status.index}__].value}"
            th:name="'valueField_'+${f.key}+'_'+${status.index}" type="text" placeholder="Fecha" />

La variable f sale de iterar el hashmap correspondiente y la variable status de iterar la lista dentro de dicho mapa.


text:
Q: How to display imenu content in speedbar I would like to display imenu content in Emacs Speedbar. Best as a flat list (like in with imenus) (not a tree-like structure).
In speedbar - Display menu I have only the following options:

*

*Files

*Quick Buffers

*Buffers

*Info

*Eieio

*Analyze (only after calling semantic-speedbar-analysis)

A: I wrote this for myself so there is no documentation, but all you should have to do is put it somewhere in your load-path and:
(require 'sb-imenu)
Start speedbar and choose the sb-imenu display.


text:
Q: PHP switch statement POST or GET I'm starting to learn PHP and I want to make a switch statement with a <select> option. The idea is that you select a brand like Volvo, and when you've selected Volvo the types will come up in a second  box. After this you will be able to select a color and materials but let's start with the first select box.
HTML:

Brand: <form action="?" method="post"><select name="brand">
<option value="Volvo">Volvo</option>
<option value="BMW">BWM</option>
<option value="porche">Porche</option></select>
<input type="submit value="submit"">
</form>

Type: <?php echo $type; ?>

PHP:
switch($brand) {
    case 'Volvo':
        $type = '<?php echo $typeVolvo; ?>';
    break;
    case 'BMW':
        $type = '<?php echo $typeBMW; ?>';
    break;
    case 'porche':
        $type = '<?php echo $typePorche; ?>';
    break;
    default:
        $type = 'Select a brand';
}

I've also tried switch($_GET['serie']) or with POST but I can't seem to find the right solution for this one. $typePorche is also included underneath this code.

A: <option> tags needs value attribute, not name. And on the PHP side, you need to use $_POST['brand']

A: Also you can directly code like bwlow to avoid switch case

Brand: <form action="?" method="post"><select name="brand">
            <option value="Volvo">Volvo</option>
            <option value="BMW">BWM</option>
            <option value="porche">Porche</option></select>
            <input type="submit value="submit"">
            </form>

            <?php
                if(isset($_POST['brand'])) {
                    $type = $_POST['brand'];
                }
            ?>


text:
Q: Additional colour transparency categories in ggalluvial I'm trying to reproduce a mobility flow diagram and don't really know how to add additional colour transparency to the fill argument based on axis2 categories. Or whether that's even the way to go about solving this problem!
Any suggestions would be greatly appreciated, thanks!
What I'm trying to achieve:
Mobility flow diagram
What I have:
My mobility flow diagram example
Code for my mobility flow diagram example:
library(ggplot2)
library(ggalluvial)

oclass <- c("1st", "1st", "1st", "2nd", "2nd", "2nd", "3rd", "3rd", "3rd")
dclass <- c("1st", "2nd", "3rd", "1st", "2nd", "3rd", "1st", "2nd", "3rd")
Freq  <- c(700, 200, 100, 200, 600, 200, 50, 250, 700)

odclass <- data.frame(oclass, dclass, Freq)

ggplot(odclass, aes(y = Freq, axis1 = oclass, axis2 = dclass)) +
       geom_alluvium(aes(fill = oclass), width = 1/6, reverse = TRUE) +
       geom_stratum(width = 1/6, alpha = 0, reverse = TRUE, color = "black") +
       geom_text(aes(label = after_stat(stratum)), stat = "stratum", reverse = TRUE, size=5) +
       scale_fill_manual(values = c("darkcyan", "darkgoldenrod2", "mediumorchid")) +
       theme_minimal() +
       theme(axis.title.y = element_blank(), axis.text.y= element_blank(), legend.position = "none",
             plot.title = element_text(hjust=0.5, size=18), axis.text.x = element_blank())

A: It's pretty easy to add what you're after. You just need to map alpha to dclass and then set the values you want using scale_alpha_manual().
library(tidyverse)
library(ggalluvial)
#> Warning: package 'ggalluvial' was built under R version 4.0.4

oclass <- c("1st", "1st", "1st", "2nd", "2nd", "2nd", "3rd", "3rd", "3rd")
dclass <- c("1st", "2nd", "3rd", "1st", "2nd", "3rd", "1st", "2nd", "3rd")
Freq  <- c(700, 200, 100, 200, 600, 200, 50, 250, 700)

odclass <- data.frame(oclass, dclass, Freq)

ggplot(odclass, aes(y = Freq, axis1 = oclass, axis2 = dclass)) +
  geom_alluvium(aes(fill = oclass, alpha = dclass), width = 1/6, reverse = TRUE) +
  geom_stratum(width = 1/6, alpha = 0, reverse = TRUE, color = "black") +
  geom_text(aes(label = after_stat(stratum)), stat = "stratum", reverse = TRUE, size=5) +
  scale_fill_manual(values = c("darkcyan", "darkgoldenrod2", "mediumorchid")) +
  scale_alpha_manual(values = c(0.9, 0.7, 0.5)) +
  theme_minimal() +
  theme(axis.title.y = element_blank(), axis.text.y= element_blank(), legend.position = "none",
        plot.title = element_text(hjust=0.5, size=18), axis.text.x = element_blank())
#> Warning in to_lodes_form(data = data, axes = axis_ind, discern =
#> params$discern): Some strata appear at multiple axes.
#> Warning in to_lodes_form(data = data, axes = axis_ind, discern =
#> params$discern): Some strata appear at multiple axes.

#> Warning in to_lodes_form(data = data, axes = axis_ind, discern =
#> params$discern): Some strata appear at multiple axes.

Created on 2021-03-29 by the reprex package (v1.0.0)


text:
Q: Searching by multi-select facets in Spree using SQL I'd like to filter products by their properties using facets, or in other words, to select multiple values across multiple properties at once.
I've decided to build the query manually, however the following SQL produces less results than I would expect. How do I change it to include all the products?
SELECT COUNT(DISTINCT "spree_products"."id") FROM "spree_products"
  LEFT OUTER JOIN "spree_product_properties" ON "spree_product_properties"."product_id" = "spree_products"."id"
  WHERE
    ("spree_product_properties"."value" in ('lacoste', 'fred perry') AND "spree_product_properties"."property_id" = 161337574)
    AND
    ("spree_product_properties"."value" in ('socks', 'shirts') AND "spree_product_properties"."property_id" = 905834903)

A: When working with the spree framework for analytics projects, I use existing LookML template in Looker. This way I don't write manual queries and Looker knows the schema against which it generates queries.
My template for spree covers the basic spree installation.
If you plan on integrating Spree with other 3rd party tools, then you will just need to extend the model.


text:
Q: What kind of unit tests should be written for a call to a database update function? I'm dealing with a lot of functions like the one below and I'm unsure of what kind of unit tests should be written for them.
public void UpdateEmployeeClockIn(int employeeId)
{
var sql = string.format("Update Employee set ClockIn = GETUTCDATE() where employeeId={0}", employeeId);

db.ExecuteNonQuery(sql);
}

I'm thinking I could refactor this method into one that maybe returns a sql statement and I could run a few tests on the sql statement to make sure there is a correct where clause etc. Any ideas? I keep running into code like this where I simply do not know how or what to test for.

A: It depends on the layer of abstraction between this code and the database.
If an abstraction there is, and you can actually put a mock instead of the object which actually accesses a real database, then your unit tests may check that the correct SQL query is sent to the mock when the method is called with an arbitrary argument, say 123. Given the actual code and the fact that unit testing is white box testing, there is nothing else here to test. Things could be different if you were sanitizing your inputs, for instance by checking that employeeId cannot be negative or zero.
If there are no abstractions, you can't write unit tests for this method without refactoring it first. You can write automated tests, but those would be integration, system, functional or acceptance tests, not unit tests. In this case, you'll run:

*

*A similar test which passes an ID of an existing employee, and checks that the database entry was changed.

*A test which uses an ID which doesn't exist.

*A test which runs on a database set in read-only mode, or an unreachable database (both cases are especially important if you have a cluster).

Note that:

*

*While in the actual piece of code, SQL Injection is impossible, this is still a wrong way to use the database. When you use parametrized queries, the database engine can cache the execution plan. In your case, you are virtually preventing it from doing this.

*You're not sanitizing your inputs. This could be intentional, if you want to let your database return an error on invalid values, but usually, it indicates that the developer simply forgot to do it. This could make it easier to perform DOS attacks against your database.

*You are not catching any exception. Is it intentional? It may be: for instance, you may prefer passing the exception up the stack in order for the business layer or presentation layer to deal with it. However, there are cases, where you have to deal with some exceptions right now. For instance, if accessing a cluster, you may have to deal with read-only instances or plain connection loss; instead of simply showing the error to the user, the method could handle the exception gracefully by retrying the query or doing what makes sense to do in a specific situation.

A: In addition to @Arseni's answer.
Your method depends on the database. Even db variable is an interface you still passing query which depends on the database type or database version etc.
Unit tests are tests which are separated from any IO operations (File system, Web service or database). Because unit tests are tests which developer need to run every 1 minute and execution time of tests need to be very short (seconds). While tests with involved IO operation takes longer time.
Tests which depend on IO operations have place to be, but they called "Integration tests".
So if your method is part of Data layer then you can write integration test where you can run another SELECT query and assert that ClockIn column isn't NULL after updating.
But if your method is part of Business logic then for proper unit testing you need abstract this method to the interface for example. Then while testing a method which will use UpdateEmployeeClockIn you can assert that UpdateEmployeeClockIn method was called with correct parameter.
Your method have another case which can make your testing almost impossible. You using system's datetime function ClockIn = GETUTCDATE(). Function GETUTCDATE() always return different value. You cannot create expected value against which your result can be asserted.
Because you using time from database then I suggest move time method to the dedicated function in your interface. Which can be mocked up and return defined expected value for the testing
public interface IDataService
{
    void UpdateEmployeeClockIn(int employeeId, DateTime timeIn);
    DateTime GetCurrentTime();
}

Then in your Business logic layer
public class EmployerManager
{
    private readonly IDataService _dataService;

    public Employer(IDataService dataService)
    {
        _dataService = dataService;
    }

    public void UpdateClockinWithCurrentTime(int employerId)
    {
        DateTime currentTime = _dataService.GetCurrentTime();
        _dataService.UpdateEmployeeClockIn(employerId, currentTime);
    }
}

In this case you can write unit tests for the method UpdateClockinWithCurrentTime where you can tests through mock of IDataService that UpdateEmployeeClockIn was executed with correct parameters.


text:
Q: Tokenization of unbalanced dataset I'm working with a dataset of emails' content which I want to transform with doc2vec. This is a labeled dataset (spam/not-spam) and it is unbalanced (90-10 ratio).
My question is: when tokenizing the emails' content, should I first oversample (using SMOTE), or is it ok to use the dataset as is?

A: Try both, pick which works better.
(Separately: avoid using the known-labels as the document-identifiers in Doc2Vec, as in practice that turns the dataset into just two giant documents – far too few for training doc-vectors of any useful dimensionality – instead of the many varied documents that are needed for an interesting/useful high-dimensional doc-vector set.)