Even or Odd Number using underscore js

Question: var data =[{
    "_id" : 500,
    "bank_name" : "THE WEST BENGAL STATE COOPERATIVE BANK",
    "ifsc" : "WBSC0TUCB01",
    "micr" : "700093255",
    "branch_name" : "MAHINAGAR",
    "address" : "PO-MALANCHA-MAHINAGAR  VILL-MAHINAGAR",
    "contact" : "24379149",
    "city" : "KOLKATA",
    "district" : "24 PGS NORTH",
    "state" : "WEST BENGAL",
    "createdAt" :"2017-12-20T12:53:22.072",
    "updatedAt" :"2017-12-20T12:53:22.072"
},
{
    "_id" : 572,
    "bank_name" : "THE WEST BENGAL STATE COOPERATIVE BANK",
    "ifsc" : "WBSC0MUCB01",
    "micr" : null,
    "branch_name" : "KOLKATA MAHILA COOP BANK",
    "address" : "8D,KRISHNA LAHA LANE,BOWBAZAR",
    "contact" : "0",
    "city" : "KOLKATA",
    "district" : "KOLKATA",
    "state" : "WEST BENGAL",
    "createdAt" :"2017-12-20T12:53:22.082",
    "updatedAt" :"2017-12-20T12:53:22.082"
},
{
    "_id" : 587,
    "bank_name" : "THE WEST BENGAL STATE COOPERATIVE BANK",
    "ifsc" : "WBSC0MCCB18",
    "micr" : "742806512",
    "branch_name" : "MURSHIDABAD DIST CENTRAL COOP BANK",
    "address" : "VILL AND PO SAKTIPUR",
    "contact" : "251116",
    "city" : "KOLKATA",
    "district" : "MURSHIDABAD",
    "state" : "WEST BENGAL",
    "createdAt" :"2017-12-20T12:53:22.084",
    "updatedAt" :"2017-12-20T12:53:22.084"
},
{
    "_id" : 1,
    "bank_name" : "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc" : "SDCB0000099",
    "micr" : "395244002",
    "branch_name" : "MAIN BRANCH",
    "address" : "KANPITH, NEAR CHAUTAPOOL, PINCODE : 395003",
    "contact" : "2597730",
    "city" : "SURAT",
    "district" : "SURAT",
    "state" : "GUJARAT",
    "createdAt" :"2017-12-20T12:53:21.915",
    "updatedAt" :"2017-12-20T12:53:21.915"
},
{
    "_id" : 2,
    "bank_name" : "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc" : "SDCB0000085",
    "micr" : "395244039",
    "branch_name" : "ANAND MAHAL ROAD",
    "address" : "GROUND FLOOR, SHOP NO 1,2,3, MANISHA APARTMENT, NEAR SNEH SANKUL WADI, ANAND MAHAL ROAD, PIN - 395005",
    "contact" : "0",
    "city" : "SURAT",
    "district" : "SURAT",
    "state" : "GUJARAT",
    "createdAt" :"2017-12-20T12:53:21.929",
    "updatedAt" :"2017-12-20T12:53:21.929"
},
{
    "_id" : 4,
    "bank_name" : "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc" : "SDCB0000083",
    "micr" : "395244038",
    "branch_name" : "BHESTAN",
    "address" : "RAM NAGAR SOCIETY, SURAT-NAVSARI MAIN ROAD, BHESTAN, TA - CHORIYASI, PINCODE-395023",
    "contact" : "0",
    "city" : "SURAT",
    "district" : "SURAT",
    "state" : "GUJARAT",
    "createdAt" :"2017-12-20T12:53:21.931",
    "updatedAt" :"2017-12-20T12:53:21.931"
},
{
    "_id" : 5,
    "bank_name" : "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc" : "SDCB0000082",
    "micr" : "395244037",
    "branch_name" : "UDHANA",
    "address" : "THE UDHANA UDHYOG NAGAR SANGH LTD, SHOP NO 1,2,3,4 SEVEN SQUARE GROUND FLOOR, UDHANA, CHORIYASI, SURAT",
    "contact" : "0",
    "city" : "SURAT",
    "district" : "SURAT",
    "state" : "GUJARAT",
    "createdAt" :"2017-12-20T12:53:21.931",
    "updatedAt" :"2017-12-20T12:53:21.931"
},
{
    "_id" : 1,
    "bank_name" : "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc" : "SDCB0000099",
    "micr" : "395244002",
    "branch_name" : "MAIN BRANCH",
    "address" : "KANPITH, NEAR CHAUTAPOOL, PINCODE : 395003",
    "contact" : "2597730",
    "city" : "SURAT",
    "district" : "SURAT",
    "state" : "GUJARAT",
    "createdAt" :"2017-12-20T12:53:21.915",
    "updatedAt" :"2017-12-20T12:53:21.915"
},
{
    "_id" : 2,
    "bank_name" : "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc" : "SDCB0000085",
    "micr" : "395244039",
    "branch_name" : "ANAND MAHAL ROAD",
    "address" : "GROUND FLOOR, SHOP NO 1,2,3, MANISHA APARTMENT, NEAR SNEH SANKUL WADI, ANAND MAHAL ROAD, PIN - 395005",
    "contact" : "0",
    "city" : "SURAT",
    "district" : "SURAT",
    "state" : "GUJARAT",
    "createdAt" :"2017-12-20T12:53:21.929",
    "updatedAt" :"2017-12-20T12:53:21.929"
},
{
    "_id" : 3,
    "bank_name" : "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc" : "SDCB0000084",
    "micr" : "NA",
    "branch_name" : "KAPURA",
    "address" : "HOUSE NO - 135, AT AND POST - KAPURA, TALUKA - VYARA, PIN - 394655",
    "contact" : "0",
    "city" : "VYARA",
    "district" : "TAPI",
    "state" : "GUJARAT",
    "createdAt" :"2017-12-20T12:53:21.931",
    "updatedAt" :"2017-12-20T12:53:21.931"
},
{
    "_id" : 4,
    "bank_name" : "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc" : "SDCB0000083",
    "micr" : "395244038",
    "branch_name" : "BHESTAN",
    "address" : "RAM NAGAR SOCIETY, SURAT-NAVSARI MAIN ROAD, BHESTAN, TA - CHORIYASI, PINCODE-395023",
    "contact" : "0",
    "city" : "SURAT",
    "district" : "SURAT",
    "state" : "GUJARAT",
    "createdAt" :"2017-12-20T12:53:21.931",
    "updatedAt" :"2017-12-20T12:53:21.931"
}];

here is my data. I want to find index of all array and from that I need to find even or odd index..
Answer: You can use below code:
 var data [.... From Question ....];

 var allIndex = _.keys(data)
 var evens = _.filter(allIndex, function(num){ return num % 2 == 0; });
 var olds = _.filter(allIndex, function(num){ return num % 2 != 0; });

Output :
 allIndex: [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ]

 evens: [ "0", "2", "4", "6", "8", "10" ]

 olds: [ "1", "3", "5", "7", "9" ]

For sum
 var sum = 0;
 _.each(allIndex, function (item) {
    sum += parseInt(item);
 });

Output :
 sum: 55

If you don't use parseInt() method then it will concatenate values
jsfiddle
Comment: Even I want to make addition of all index value..can u help?
Comment: count total index increament by last index
Comment: var sum = 0;
 _.each(_.keys(data), function (item) {
    sum += parseInt(item);
 });
(13) ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
0
:
"0"
1
:
"1"
2
:
"2"
3
:
"3"
4
:
"4"
5
:
"5"
6
:
"6"
7
:
"7"
8
:
"8"
9
:
"9"
10
:
"10"
11
:
"11"
12
:
"12"
length
:
13
__proto__
:
Array(0) this is showing in console
Comment: Unable to understand what is your question. Please provide JSFIDDLE. I updated my jsfiddle to http://jsfiddle.net/kqvcyp90/8093/
Answer:

var data = [{
    "_id": 500,
    "bank_name": "THE WEST BENGAL STATE COOPERATIVE BANK",
    "ifsc": "WBSC0TUCB01",
    "micr": "700093255",
    "branch_name": "MAHINAGAR",
    "address": "PO-MALANCHA-MAHINAGAR  VILL-MAHINAGAR",
    "contact": "24379149",
    "city": "KOLKATA",
    "district": "24 PGS NORTH",
    "state": "WEST BENGAL",
    "createdAt": "2017-12-20T12:53:22.072",
    "updatedAt": "2017-12-20T12:53:22.072"
  },
  {
    "_id": 572,
    "bank_name": "THE WEST BENGAL STATE COOPERATIVE BANK",
    "ifsc": "WBSC0MUCB01",
    "micr": null,
    "branch_name": "KOLKATA MAHILA COOP BANK",
    "address": "8D,KRISHNA LAHA LANE,BOWBAZAR",
    "contact": "0",
    "city": "KOLKATA",
    "district": "KOLKATA",
    "state": "WEST BENGAL",
    "createdAt": "2017-12-20T12:53:22.082",
    "updatedAt": "2017-12-20T12:53:22.082"
  },
  {
    "_id": 587,
    "bank_name": "THE WEST BENGAL STATE COOPERATIVE BANK",
    "ifsc": "WBSC0MCCB18",
    "micr": "742806512",
    "branch_name": "MURSHIDABAD DIST CENTRAL COOP BANK",
    "address": "VILL AND PO SAKTIPUR",
    "contact": "251116",
    "city": "KOLKATA",
    "district": "MURSHIDABAD",
    "state": "WEST BENGAL",
    "createdAt": "2017-12-20T12:53:22.084",
    "updatedAt": "2017-12-20T12:53:22.084"
  },
  {
    "_id": 1,
    "bank_name": "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc": "SDCB0000099",
    "micr": "395244002",
    "branch_name": "MAIN BRANCH",
    "address": "KANPITH, NEAR CHAUTAPOOL, PINCODE : 395003",
    "contact": "2597730",
    "city": "SURAT",
    "district": "SURAT",
    "state": "GUJARAT",
    "createdAt": "2017-12-20T12:53:21.915",
    "updatedAt": "2017-12-20T12:53:21.915"
  },
  {
    "_id": 2,
    "bank_name": "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc": "SDCB0000085",
    "micr": "395244039",
    "branch_name": "ANAND MAHAL ROAD",
    "address": "GROUND FLOOR, SHOP NO 1,2,3, MANISHA APARTMENT, NEAR SNEH SANKUL WADI, ANAND MAHAL ROAD, PIN - 395005",
    "contact": "0",
    "city": "SURAT",
    "district": "SURAT",
    "state": "GUJARAT",
    "createdAt": "2017-12-20T12:53:21.929",
    "updatedAt": "2017-12-20T12:53:21.929"
  },
  {
    "_id": 4,
    "bank_name": "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc": "SDCB0000083",
    "micr": "395244038",
    "branch_name": "BHESTAN",
    "address": "RAM NAGAR SOCIETY, SURAT-NAVSARI MAIN ROAD, BHESTAN, TA - CHORIYASI, PINCODE-395023",
    "contact": "0",
    "city": "SURAT",
    "district": "SURAT",
    "state": "GUJARAT",
    "createdAt": "2017-12-20T12:53:21.931",
    "updatedAt": "2017-12-20T12:53:21.931"
  },
  {
    "_id": 5,
    "bank_name": "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc": "SDCB0000082",
    "micr": "395244037",
    "branch_name": "UDHANA",
    "address": "THE UDHANA UDHYOG NAGAR SANGH LTD, SHOP NO 1,2,3,4 SEVEN SQUARE GROUND FLOOR, UDHANA, CHORIYASI, SURAT",
    "contact": "0",
    "city": "SURAT",
    "district": "SURAT",
    "state": "GUJARAT",
    "createdAt": "2017-12-20T12:53:21.931",
    "updatedAt": "2017-12-20T12:53:21.931"
  },
  {
    "_id": 1,
    "bank_name": "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc": "SDCB0000099",
    "micr": "395244002",
    "branch_name": "MAIN BRANCH",
    "address": "KANPITH, NEAR CHAUTAPOOL, PINCODE : 395003",
    "contact": "2597730",
    "city": "SURAT",
    "district": "SURAT",
    "state": "GUJARAT",
    "createdAt": "2017-12-20T12:53:21.915",
    "updatedAt": "2017-12-20T12:53:21.915"
  },
  {
    "_id": 2,
    "bank_name": "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc": "SDCB0000085",
    "micr": "395244039",
    "branch_name": "ANAND MAHAL ROAD",
    "address": "GROUND FLOOR, SHOP NO 1,2,3, MANISHA APARTMENT, NEAR SNEH SANKUL WADI, ANAND MAHAL ROAD, PIN - 395005",
    "contact": "0",
    "city": "SURAT",
    "district": "SURAT",
    "state": "GUJARAT",
    "createdAt": "2017-12-20T12:53:21.929",
    "updatedAt": "2017-12-20T12:53:21.929"
  },
  {
    "_id": 3,
    "bank_name": "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc": "SDCB0000084",
    "micr": "NA",
    "branch_name": "KAPURA",
    "address": "HOUSE NO - 135, AT AND POST - KAPURA, TALUKA - VYARA, PIN - 394655",
    "contact": "0",
    "city": "VYARA",
    "district": "TAPI",
    "state": "GUJARAT",
    "createdAt": "2017-12-20T12:53:21.931",
    "updatedAt": "2017-12-20T12:53:21.931"
  },
  {
    "_id": 4,
    "bank_name": "THE SURAT DISTRICT COOPERATIVE BANK LIMITED",
    "ifsc": "SDCB0000083",
    "micr": "395244038",
    "branch_name": "BHESTAN",
    "address": "RAM NAGAR SOCIETY, SURAT-NAVSARI MAIN ROAD, BHESTAN, TA - CHORIYASI, PINCODE-395023",
    "contact": "0",
    "city": "SURAT",
    "district": "SURAT",
    "state": "GUJARAT",
    "createdAt": "2017-12-20T12:53:21.931",
    "updatedAt": "2017-12-20T12:53:21.931"
  }
];

function test() {
  var indexs = _.keys(data)
  var evenIndex = _.filter(indexs, function(num) {
    return num % 2 == 0;
  });
  var oldIndex = _.filter(indexs, function(num) {
    return num % 2 != 0;
  });

  var sum = 0;
  _.each(indexs, function(item) {
    sum += parseInt(item);
  });

  log("Indexs", indexs);
  log("Even Indexs", evenIndex);
  log("Old Indexs", oldIndex);
  log("Sum", sum);
}

// log func
function log(name, msg) {
  if (_.isUndefined(msg)) {
    msg = name;
    name = null;
  }
  if (_.isObject(msg)) {
    msg = JSON.stringify(msg, null, 2);
  }
  msg = (name ? name + ': ' : '') + msg;
  $('#content').append($('

').html(msg));
}

test();

Even or Odd Number using underscore js


stp - avoid links with packet loss

Question: We have a set of devices connected in a ring, that are using stp (using https://github.com/mstpd/mstpd at the moment) to avoid issues with the loop. What we have seen, is that while stp can adapt the network when a link is fully broken, it ignores a situation where one of the links sees high packet loss.
Is this something stp supports? that is, to consider the packet loss in network links in the cost associated to a given interface and adapt the network based on that? If not, are there any good alternatives?
The way we ran into that, is because there were some usb to eth adapters that failed in some cases after rebooting or after a manual reconnection of the eth cable. While the issue is likely some driver/os related issue, it showed very well that stp still chooses the partially failing link, ending in a permanent 50% packet loss instead of the 0% of avoiding that link.
Comment: STP was never designed to deal with poor quality links.  That's not its purpose.
Answer:
What we have seen, is that while stp can adapt the network when a link is fully broken, it ignores a situation where one of the links sees high packet loss. Is this something stp supports?

Link quality is nothing STP cares about nor is designed to handle.
STP runs between switches. If more than just a very few packets are lost the link's bad and needs to be fixed.
The only way to avoid those bad links would be some monitoring and shutting down the port at a certain error rate. Since links are normally practically error-free, that's nothing you'd commonly find in a switch.
As a workaround, you could use port priorities to have STP avoid a known-bad link while still keeping it as a fail-over.
Comment: the confusion I have, is that STP adapts to a cable being disconnected by using the other links. So it kind of cares about keeping the network working in the event of part of a link becoming unavailable. If one has redundancy in a network to make sure to keep things up, then I wonder if a physical failure is always a perfect full disconnect (which we happened to be hit during early testing due to those adapters issues).
Comment: @eglasius xSTP just uses a link-up/link-down type detection - no quality monitoring whatsoever. Yes, if your cabling is OK then a failure is most likely a clean disconnect (cable disconnection, transceiver failure, switch offline, ...). If you need quality monitoring you'd have to add it to your stack. However: for a decent network you should never use rings but connect your devices to a decent, central switch (or a hierarchical structure of switches).
Comment: in the network(s) in our context the devices in the network are all part of a bigger standardized system that need to talk to each other. 3 devices in this version, with potentially a couple more later on. A single switch is being viewed as a single point of failure, so its really 2 switches in diff physical locations + 2 * [device count] cables vs. [device count] cables for the ring. The main point against so far is its not adapting to lossy links. When you say never to use rings, are there other concerns in mind?
Comment: Viewing a decent switch as SPOF but at the same time trying to use some kind of workaround for substandard cabling is - strange... With standard Ethernet, rings generally don't behave very well (unless you're using the appropriate Ethernet options). You might want to check the [relevant discussions](https://networkengineering.stackexchange.com/search?q=ring) on [Network Engineering](https://networkengineering.stackexchange.com).

stp - avoid links with packet loss


Data recovery options for unix file systems

Question: What popular and tried data recovery options are there?
I know of these (none of which have GUIs afaik):

foremost - Forensics application to recover data
scalpel - A Frugal, High Performance File Carver
ext3grep - Tool to help recover deleted files on ext3 filesystems
e2undel - Undelete utility for the ext2 file system

Do you know of any that have desktop frontends? It's a tool you don't get to use much, reading manuals and searching for correct flags is not efficient.
Answer: I've had excellent results with TestDisk. No gui, but the next best thing ... console menus! And an excellent wiki for use cases.
Many an accidentally deleted thumbdrive has been rescued.
Comment: +1 for mentioning a program I almost forgot about! Thanks for remembering me!
Answer: I don't think you'll find GUI frontends for these. Ext3grep is your best option for recovering files though: I used it for the first time a couple of weeks ago and was easily[1] able to recover all the pictures I had deleted.
Compared to a couple of years back, ext3grep has made life a lot easier. It takes some time, but it does the job and does it pretty well.
[1] Easily is relative to what it used to be, before ext3grep.
Answer: Not exactly for Unix file systems (it does not depend on file systems at all) but I can recommend PhotoRec. You'll probably find it in testdisk package


Help me to find the second limit

Question:
Let $(x_n)_{n \ge 1}$ with $x_1>4$ and $x_{n+1}=3+\frac{4}{x_n}, n \ge 1$.
Prove that  $\lim_{n\to \infty} x_n=4$ and find  $\lim_{n\to \infty}( \frac{x_{2n+1}+x_{2n}}{8})^n$.

I proved that $\lim_{n\to \infty} x_n=4$, and for the second limit I wrote $$\left(\frac{x_{2n}+x_{2n+1}}{8}\right)^n=\exp\left\{n\ln\left(\frac{x_{2n}+x_{2n+1}}{8}\right)\right\},$$ but I don't understand how to calculate this. Please help!
Comment: The limit is 1. See below my answer.
Answer: Sketch of proof : step 1:  $ \ln(1-x)=-x-x^2-\cdots -x^n+ o(x^n)\ $, so you have to determine the limit of $$ n(x_{2n}+x_{2n+1}-8)$$
Step 2 : From a certain point $N$, $x_n\in[3,5]$ so (with $f(x):=3+\frac{4}{x}$)
$$|x_{n+1}-x_{n}|=|f(x_{n})-f(x_{n-1})|\leq \sup_{c\in[3,5]}|f'(c)||x_{n}-x_{n-1}|< C |x_{n}-x_{n-1}|< 2 C^{n-N}$$
 with $0<C<1$, for $n>N$. So, for $2n>N$,
$$ |x_{2n+1}-x_{2n}|\leq 2 C^{2n-N} $$
 sept 3: from the particular form of that equation, it is easy to prove that the subsequence $x_{2n}$ is decreasing to $4$  (since $x_0>4$) and $x_{2n+1}$ is increasing to $4$ (and $x_p>0$ or all $p$).
So, $x_{2n+1}\leq  4\leq x_{2n}$ and
$$ |x_{2n}+x_{2n+1}-8 |\leq |x_{2n+1}-4|+|x_{2n}-4|=|x_{2n+1}-x_{2n}|\leq 2 C^{2n-N}$$
so
$$\lim_{n\rightarrow \infty}n(x_{2n}+x_{2n+1}-8) =0$$
You can conclude.
Comment: @Surb thanks :)
Comment: @Surb Because of $x_{2n+1}\leq  4\leq x_{2n}$ we have $$ |x_{2n+1}-4|+|x_{2n}-4|=|x_{2n+1}-x_{2n}|$$ (draw a picture)
Comment: Yes, sure ! Good job :-) (+1)
Comment: @Surb The same demonstration works for $$\lim_{n\to \infty}( \frac{x_{2n+1}+x_{2n}}{8})^{n^k}$$ for some $k>0$ fixed, so there was some room to torture students a bit more :)
Comment: To be honest, I didn't think about using mean value theorem (and you really nicely solve this problem, I really like it). But without more indication, I hope that you recognize that your first *hint* was not enough :-) I think that here the real trick was the mean value theorem. As a futur hint, something as : Taylor + Mean Value Theorem  would have been perfect (and not only Taylor) :-) Anyway, good job ! :-)
Comment: @Surb yes, I agree, it was not a complete hint, but the point was to put the OP on the start of a road : the point was to focus on the speed of the convergence of the sequence (and not losing time with $\ln$ or $\exp$), which is, I think, quite classical for this type of sequences.

Help me to find the second limit


LoadRunner AccessViolationException when invoking web.url in C#

Question: What's the correct syntax to invoke a HTTP Get using the LoadRunner API (VUGEN 18.104.22.168) in C#? The following generates an AccessViolationException:
LoadRunner.WebApi web = new LoadRunner.WebApi();
web.url("GoToMyService", "http://path/to/my/service/", new string[0], "LAST");

Exception thrown by call to web.url:
Error: Action.cs(25): System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
   at LoadRunner.WebApiClass.url(String name, String urladdr, Object options, Object extrares)
   at Script.VuserClass.Action() in h:\Personal\_projects\LoadTest\Action.cs:line 25

Comment: Oh man, I thought this was going to be about porting the classic game.  :(
Answer: One option, which isn't really in the spirit of LoadRunner, is to skip using the LoadRunner API and just use the System.Net APIs:
WebResponse response = HttpWebRequest.Create("http://path/to/my/service/").GetResponse();

Answer: You are engaging in an ethically problematic activity for a performance tester:  You do not point a loaded gun at something that you do not own, manage or control.  LoadRunner is a loaded gun and I am ~~~assuming~~ you don't work for google.   So, just don't
Comment: Don't worry. Worth being clear that I'm not actually running load tests against google.com. In my example code I just replaced the URL for the service I'm developing with something more generic. I have removed my reference to google.com anyway :-)


How to get the completion time of a task in Outlook

Question: I've written a VBA macro that exports in excel all completed (ticked)  mails from a mailbox based upon the TaskCompletedDate property. However TaskCompletedDate shows only the date portion of the DateTime value. Is there a way to getthe time value as well?
I'm using Outlook 2010.
Comment: Does this answer help? http://stackoverflow.com/a/10259285/2258
Comment: Not really, because the Flag Completed Date can be manually changed by the user and I need to access the system completion time for reporting purposes.
Comment: I've added an answer to stackoverflow.com/a/10259285/2258
Answer: Documentation reads that it returns Date type, so you can't get exact time I'm affraid, unless you save it on your own in the first place.
Answer: You cannot do that - Outlook only stores the date (in the UTC time zone). You can see the data on the MAPI level in OutlookSpy (I am its author - select the task, click IMessage button).
Answer: yes you can get the time as well. For this first go to your outlook express mailbox. Then right click on the column header and select "View Settings". Now in the pop-up window click "Format Columns". Now select the "Flag Completed Date" column on the left hand side and then from the format drop down select the 1st, 2nd or 3rd option. Click ok and come out of settings.
Now whenever you extract the info from the taskcompleteddate property you will get the time as well.
I am too late to answer... i have joined recently. But I hope this will help someone else who might be looking for it.
Regards,
Premanshu
Comment: "outlook express"? No matter what setting you use in the view, the data is simply not there. Outlook does not preserve the time portion. Look at the data in OutlookSpy or MFCMAPI.


How should you determine the probability returned by a flat uniform prior function

Question: I am currently doing an analysis that involves fitting a model to a 1D graph.
Following the example on the emcee documentation, I started with Maximum likelihood estimation and am now looking at using MCMC and Bayesian statistics to constrain nuisance parameters in my function.
This is all fine.
The part that I am on before being able to use MCMC is that I need to have a posterior function, which is given by the product of my likelihood function and a prior. The only part I am missing is the prior.
Based on doing background reading into this, I am starting just with the very simple example of using a flat, uniform prior, like they have in the emcee documentation (fitting a model to data tutorial is what I am referencing).
Now, I understand that for a flat uniform prior, every value within your defined range has equal probability of being chosen assigned to it and that for such a function, that probability is given by p(x) = 1/(b-a), where a, b are the min and max values of your chosen range and that, outside your range the probability is zero.
So, in the emcee example they are trying to constrain the slope of a line which they define by parameter, m. They state the range is, [a,b] = [-5.0,0.5] and therefore the probability of each parameter within that range is 1/(0.5--5.0) = 1/5.5. This all makes sense.
However, in their code block demonstrating this, which I will paste below from their page, where they then take the log of the prior and therefore, log of the probability within the function, they return the values 0, for probabilities of values within the range of the uniform function and -infinity, for values outside the range of the function.
<code>def log_prior(theta):
m, b, log_f = theta
if -5.0 < m < 0.5 and 0.0 < b < 10.0 and -10.0 < log_f < 1.0:
    return 0.0
return -np.inf
</code>
Where 0.0 is log of the probability within the function range and - infinity is log of the probability outside the function range.
For the -infinity value, this makes sense and based on some reading, I understand that while log(0) is undefined, it is common to assign a value of -infinity to it. However, a value of zero for values within the range would imply that they took the log of 1, for values within the range.
What I don't understand is why they would take the log of 1 and not the log of 1/5.5, which is the probability assigned to each possible value in the function range. Taking the log of 1 would be the log of the total probability within the function but I can't seem to find any explanations of their reasoning anywhere.
Therefore, I was wondering the correct way to do this and whether, you should always take the log of 1 for a uniform flat prior? and if so, what is the point of determining the probability of values within the function (i.e. the 1/5.5 value in this example), if you don't use it in your prior?
I have attached the link to the emcee docs page I am using below.
Following on from this, while they have given the example for the probability of the m parameter they are trying to constrain from the fit, they are actually trying to constrain three nuisance parameters (total: m , b and f as defined in the docs). If the best approach is to return a probability of 1/(b-a), how would you do when combining multiple parameter constraints? is it just the same as a joint probability distribution when you take the product of the probabilities (or sum if you're doing log)? this is what makes sense to me but I cannot find examples of anyone explicitly giving the value for multiple constraints so I ask incase there is another approach.
Many thanks,
https://emcee.readthedocs.io/en/stable/tutorials/line/
An additional question, if anyone should know is, when doing log prior and if your parameters are outside the function range, therefore assigned a value of - infinity, when going to add this to your likelihood function to get the posterior (as we are in log space), wouldn't you always get a value of -infinity? because your likelihood value is small in comparison ? Maybe this is a naive question based on my currently limited understanding but any guidance would be appreciated.
Comment: Thank you for your response - I did read the part of the "calculated up to a constant" but I (mis)interpreted this as referring to the removal of the Bayesian evidence term as opposed to the 1/5.5. vs 1 factor. I appreciate you tagging relevant threads
Comment: The posterior is calculated up to a constant; see the [documentation](https://emcee.readthedocs.io/en/stable/tutorials/line/#marginalization-uncertainty-estimation). The log(5.5) is incorporated into the constant.
Comment: This has been explained many times on CV but one more explanation doesn't hurt. Some related threads: [1](https://stats.stackexchange.com/q/97515/237901), [2](https://stats.stackexchange.com/q/182525/237901), [3](https://stats.stackexchange.com/q/275641/237901).
Comment: That's true -- that constant includes the evidence but it can include other components as convenient for computational purposes (as long as those are constant in the parameters).
Comment: @dipetkov that all makes sense, thank you for explaining and clarifying for me!
Comment: Perhaps you benefit from having a peek at my [tutorial](https://www.amazon.com/dp/B0BTNVFR65). You can read most of it online under "Read Sample."
Comment: @RomkeBontekoe Thank you very much! I will check it out
Answer: There is a more formal answer to your question, but I won't give it here. In broader terms, though:

What I don't understand is why they would take the log of 1 and not the log of 1/5.5, which is the probability assigned to each possible value in the function range. Taking the log of 1 would be the log of the total probability within the function but I can't seem to find any explanations of their reasoning anywhere.

It doesn't (usually) matter.
When you're using MCMC to estimate the posterior distribution, it's not actually necessary to have a function that outputs the value of the posterior density, $P(\theta | x)$. All you need is to output a value that's proportional to this, usually written as $\propto P(\theta | x)$. This is good, because to actually calculate $P(\theta | x)$ you need to also calculate the normalising constant, and this is expensive to do, but because it's a constant, it doesn't affect the proportional value.
For this reason, it doesn't actually matter if you shift the prior density up or down by a constant amount (e.g. $1$ vs $\frac{1}{5.5}$), since everything remains in proportion.

An additional question, if anyone should know is, when doing log prior and if your parameters are outside the function range, therefore assigned a value of - infinity, when going to add this to your likelihood function to get the posterior (as we are in log space), wouldn't you always get a value of -infinity? because your likelihood value is small in comparison ? Maybe this is a naive question based on my currently limited understanding but any guidance would be appreciated.

Correct. If the prior says a value of $\theta$ has a probability of 0 (it's impossible), it should also have a probability of 0 (also impossible) in the posterior, since no amount of data can make the impossible possible.
Edit: It's also worth looking at what people actually mean when they say "up to a constant" when talking about the posterior, e.g. here.
Comment: Thank you so much for your response, that all makes a lot of sense and I appreciate you taking the time to answer!


Using Cereal to serialize templated polymorphic types in a library

Question: I have a templated base class:
template<typename T>
class A {
    public:
    T a;

    template<class Archive>
    void serialize(Archive & ar) {
        ar(a);
    }
};

and a templated class that derives from it:
template<typename T>
class B : public A<T> {
    public:
    T b;

    template<class Archive>
    void serialize(Archive & ar) {
        ar(cereal::base_class<A<T>>(this));
        ar(b);
    }
};

It is used in another serialized class:
template<typename T>
class C {

    template<class Archive>
    void serialize(Archive & ar)
    {
        ar(collection);
    }

    std::vector<std::shared_ptr<A<T>>> collection;
};

This code and the code that uses it is compiled into a static lib
From my understanding of the cereal docs I need to add
CEREAL_REGISTER_TYPE(A<double>)
CEREAL_REGISTER_TYPE(A<float>)

CEREAL_REGISTER_TYPE(B<double>)
CEREAL_REGISTER_TYPE(B<float>)

etc for each type that will be used, in the header files for each class
This compiles. But has a run time error of

Trying to save an unregistered polymorphic type (B). Make sure
  your type is registered with CEREAL_REGISTER_TYPE and that the archive
  you are using was included (and registered with
  CEREAL_REGISTER_ARCHIVE) prior to calling CEREAL_REGISTER_TYPE. If
  your type is already registered and you still see this error, you may
  need to use CEREAL_REGISTER_DYNAMIC_INIT.

From the docs I think I need to add CEREAL_FORCE_DYNAMIC_INIT(libname) in the headers and CEREAL_REGISTER_DYNAMIC_INIT in the CPP file, but there is no cpp file. Or a suitable CPP file to place this in.
Adding CEREAL_REGISTER_POLYMORPHIC_RELATION makes no difference as expected as B's serialization function is calling the base calss A with cereal::base_class
Is there a way to use Cereal to serialize templated classes?
Comment: Sorry, transcription error, missed the .
Comment: The types in your examples don't seem to be polymorphic... are they actually representative of your real code?  If so, that is an odd error
Comment: [Have you followed the documentation](http://uscilab.github.io/cereal/polymorphism.html)? Have you used `CEREAL_REGISTER_POLYMORPHIC_RELATION` (if it's needed; I'm totally unfamiliar with cereal)? I agree with xaxxon that the code you posted isn't polymorphic.
Comment: According to the [docs](http://uscilab.github.io/cereal/assets/doxygen/polymorphic_8hpp.html#a0479821f6a987e08e7d3f765cda02d91) CEREAL_REGISTER_POLYMORPHIC_RELATION is only required if the subclass does not call the base class with cereal::base_class. Which I am doing.
Comment: Updated to show polymorphic usage.
Answer: Issue came down to the order of the included headers and where they were included, plus a small amount of RTFM carefully.
In base class header needed:
#include <cereal/types/polymorphic.hpp>
#include <cereal/archives/portable_binary.hpp>

plus any other types I want to serialize to.
Then in subclasses add CEREAL_REGISTER_TYPE for each supported type.
The key, as noted in the documentation, is that the type of archive is included BEFORE CEREAL_REGISTER_TYPE. They do not have to be in the same file as the class declaration. Just include headers before registering types.


How to compare lists of different types

Question: I have two lists. One list has 6 elements, another one has 3 elements. I need compare both the lists and retain only that information in the aList which matches bList.
public class AClass{

    String cname;
    int cid;
    int aid;
}

public class BClass{
    String cname;
    int sc_id;
    int aid;
}

And the two lists:
List<AClass> aList;
List<BClass> bList;

For example, aList has 1,2,3,4,5,6 and bList has 1,4,5. The comparison has to be done so that aList has 1,4,5 in it.
I've tried the below code. But doesn't work.
aList.retainAll(bList);

Kindly help!
Comment: When you say `aList has 1,2,3,4,5,6` what exactly do you mean? Because your classes contain more than just a single integer.
Comment: What do you want to compare?
Comment: Have you tried mapping all objects in ```bList``` to an ```AClass``` object? Then compare ```aList``` against this new list that you've created.
Comment: @OHGODSPIDERS aList 1,2,3,4,5,6 refers to cid. Both the lists have a common field. cid of aList is same as sc_id of bList
Comment: @MuratKaragöz i want to compare the ids(cid of aList with sc_id of bList) in both the lists, and retain only the information that matches.
Answer: Basically the idea is to compare every element of aList with every element of bList while comparing sc_id == e.cid. You can use streams for that. Looks like this
aList = aList.stream().filter(e -> bList.stream().anyMatch(b -> b.sc_id == e.cid)).collect(Collectors.toList());

Answer: Get the ids you want to keep first, then filter against them.
Set<Integer> keepIds = bList.stream().map(BClass:getId).collect(toSet());
List<AClass> filtered = aList.stream
                             .filter(a -> keepIds.contains(a.getId()))
                             .collect(toList());

Answer: List<Integer> a = List.of(1,2,3,4,5);
List<Integer> b = List.of(1,4,6);
List<Integer> collect = a.stream().filter(b::contains).collect(Collectors.toList());
System.out.println(collect);

Comment: He does not have a List of Integers.

How to compare lists of different types


Circles- finding radii of smallest and largest circle

Question: If $r_1$ and $r_2$ are the radii of smallest and largest circle which passes through $(5,6)$ and touches the circle $(x-2)^2+y^2=4$.
Then $r_1r_2$ = ??
Answer: Let $A=(5,6)$ and $C=(2,0)$ (center of the given circle). Then the radius of the smaller circle touching the given circle and passing through $A$ will be $(AC-2)/2$ (where $2$ is the radius of the given circle). Likewise the radius of the bigger circle will be $(AC+2)/2$. Thus
$$r_1r_2=(AC^2-4)/4=\frac{[(5-2)^2+(6-0)^2]-4}{4}=41/4.$$
Comment: That sounds so much easier than what i had thought of it. Thanks sir!


How do I calculate the percentage of Calculax in a vat after one hour?

Question: I have a problem that states:
A container has 250 gallons of solution that had 4% Calculax (per volume). Solution with 6% Calculax is pumped into the container at a rate of 10 gal/min and the mixture is pumped out at the same rate. What is the percentage of Calculax in the vat after an hour?
I am having difficulty trying to figure out how to start, especially the equation for it. Any help is appreciated. Thank you in advance!
Answer: There are $250\cdot4\%=10$ gallons of Calculax in the container initially. Every minute we add $10\cdot6\%=0.6$ gallons of Calculax every minute. After $1$ hour there are $10+0.6\cdot60$ gallons of Calculax in the container.
There are $250$ gallons of solution in the container initially. Every minute we add $10$ gallons of solution every minute. After $1$ hour there are $250+10\cdot60$ gallons of solution in the container.
Now divide the number of gallons of Calculax in the container by the number of gallons of solution in the container to get the fraction of Calculax. Then multiply by $100$ to get the percentage of Calculax in the solution. I'll leave the calculations to you.


How to decode and inspect an HTTP payload when it is a zip

Question: So I'm pretty new at all this. I am trying to reverse engineer a web application.
When I submit a form, it sends a POST with a request payload that looks something similar to this:
encoding=UTF8&zip=1&size=136240&html=DwQgIg_a_whole_lot_more_gibberish_not_worth_posting
Anyways, from inspecting the captured traffic from Chrome developer tools, I noticed it is encoded and sent as a zipped up html?
How would I go about reversing this to see what the content is actually being sent to the server?
Answer: What you want to do is this:
1) Get the name of the zip file
 2) Get the path of the zip file (likely the root directory or the current path the form is at)
 3) Generate the URL (http://site_name.com/path/to/folder/zip_file.zip)
 4) Download it using a too such as wget (typing the URL into the browser may work too)
I used this technique to download all the files that get downloaded to the OTA updates on iOS devices (used burp suit to intercept the zip file name where the server was on my computer which my iDevice was connected to).
Please note: the name of the zip file you have given does not end in .zip. this may mean it doesn't have a extension; you may have to add .zip to the file manually; or it may have another ending such as .tar, .tar.gz etc.


Facets and Apache Solr in Drupal 7 - Clicking Facets results in no results being show

Question: I'm having a bit of an issue with Facets and Apache Solr, I'm not sure whether the fault lies with Solr or the Facets API.
I am using Solr as my search engine and I get results being shown when searches are performed, also shown are the amount of matches in specified fields/facets.
E.g. I search for 'content' - there are numerous values for 'content' within different categories such as 'category1', 'category2'
The search result shows as:
<code>category1(5)
category2(7)
</code>
Implying there are 5 results in the facet category1, and 7 results in the facet category2, these are also links, however upon clicking these links the search shows as "no results found". Odd behaviour, has anyone experienced anything like this before? if so any pointers on where to look in order to resolve the issue?
I'm hoping this question is quite clear, if not just ask and I'll try provide some more details.
Thanks, Dan.
Answer: This is very odd behaviour, can you ensure you are:

running the latest version of apachesolr (3.6.1)
running the latest version of the apachesolr module (7.x-1.1) OR search_api module (7.x-1.3)
are running the latest schema.xml and solrconfig.xml (hopefully the 3.x version)

Also, try dropping and re-creating the entire index, this normally addresses more problems.
Answer: There are a large number of similar issues in the relevant issue queues for both Apache Solr and Search API Solr, because this could be a result of any number of errors. Here are some basic tips:

Make sure you're using at least version 3.6.0 of Apache Solr (there are some outstanding bugs with Solr 1.4.x)
Make sure you're using the correct schema.xml, solrconfig.xml, and other configuration files with Solr (see the installation instructions, and remember to delete your sites' index and reindex your content if you've modified those files)
Check the Tomcat logs for your query; there should be a line for each query which includes the text "hits=123" where 123 is the number of results (if Solr is in fact returning results, your problem is specific to Drupal)
If you're presenting results using views and you have an exposed fulltext search filter, make sure it's set as optional and not as input required
Answer: I would start by looking at how the url for the solr query is being built and testing it directly against the solr engine to see if it returns any results. I guess once you see the query built for the link you will understand why it returns 0 results. Happy hunting :)


Multiple imputation for non-parametric tests on small sample?

Question: I am new to multiple imputation, so apologies if the question is naive. I have been exploring multiple imputation for use on a small data set where there are just a couple of data points. I would like to run Wilcoxon signed-rank tests using the pooled imputations. However, SPSS doesn't provide pooled test statistics for non-parametrics because "Rubin's rules... don't address nonparametric tests". Consequently, SPSS calculates the statistics for each imputation, but not as a group. So I was wondering how useable this output is (e.g., should I report the statistic range) or is this indicative of a fundamental issue in trying to use multiple imputation with non-parametric tests. Because of these complexities and the small amount of missing data, I considered mean substitution instead but I appreciate that this approach is not optimal - although the overall findings remain the same either way.
Any advice would be greatly appreciated.
Comment: I think the jist is that Rubin's rules for pooling estimates rely on the approximate normality of the multiply imputed test statistics ($T_i, i = 1, 2, \ldots, m$). If we don't know the distribution of $T_i$ we don't know that $\sum_{i=1}^m T_i$ will follow anything like a normal.
Answer: Not a naive question at all. I'm not an expert, but I think this is actually a rather difficult question.
As you may be aware, Rubin's Rules assume that the full-data estimate, $\hat{\theta}_{full}$, would be normally distributed. Then from the $M$ imputed estimates, $\hat{\theta}_{1}, \ldots, \hat{\theta}_{M}$, we average them to find the point estimate $\hat{\theta}_{imp}$ and also combine the within- and between- variances to estimate the variance of $\hat{\theta}_{imp}$, $\hat{\text{V}}[\hat{\theta}_{imp}]$. Then we can use traditional methods for normally distributed values to find confidence intervals and perform tests. If the estimates $\hat{\theta}_{i}$ are not normally distributed then this will not work.
My understanding is that the Wilcoxon signed-rank test statistic, $W$, is asymptotically normally distributed. So in contrast to the SPSS manual, I think you could pool the estimates if you had a large sample. Although if it isn't supported by SPSS you'd probably have to program the calculations yourself.
But, it sounds like your sample isn't nearly large enough to consider this. $W$ is not close to normally distributed in small samples. An alternative you could consider would be pooling the p-values from the imputed datasets themselves. I don't know enough to offer guidance on it, but you can read about the procedure in section 5.3.2 of Flexible Imputation of Missing Data, https://stefvanbuuren.name/fimd/sec-multiparameter.html#sec:chi. The basic idea is to transform the imputed p-values to be approximately normally distributed, pool those transformed values, then transform back to find the final p-value. You can see some sample code in this answer, How to get pooled p-values on tests done in multiple imputed datasets?
Of course, if the amount of missing data is very small, you could consider using a complete-case analysis instead. The results would probably be very similar.


PdfStamper changes size of MemoryStream

Question: Have a PDF on disk that is 498kb.  I'm reading this into a MemoryStream which reports the size as 508978 when viewed in the debugger.  Then using a reader and stamper, the output MemoryStream has a size of 15.  When the stream is output to disk the PDF is unreadable.
MemoryStream inputStream = new MemoryStream();
MemoryStream outputStream = new MemoryStream();

FileStream fs = File.OpenRead(@"e:\O1.pdf");
inputStream.SetLength(fs.Length);
fs.Read(inputStream.GetBuffer(), 0, (int)fs.Length);
inputStream.Seek(0, SeekOrigin.Begin);

PdfReader reader = new PdfReader(inputStream);
PdfStamper stamper = new PdfStamper(reader, outputStream);
stamper.Writer.CloseStream = false;

AcroFields fields = reader.AcroFields;
foreach (String key in fields.Fields.Keys)
{
if (String.Equals(key, @"ReportID")) { stamper.AcroFields.SetField(@"ReportID", "Fred Bloggs");   }
}

stamper.Close();
Byte[] bytes = (Byte[])outputStream.ToArray();
File.WriteAllBytes(@"e:\O2.pdf", bytes);

Comment: 1) The source of `ConvertFileToStream()` is missing. 2) You compute the length of the output stream before doing anything with the stamper; look at the length after stamping and closing the stamper; you may need `stamper.CloseStream = false`.
Comment: Taking into account your edit: Yes, your code definitively misses a `stamper.Close()` call or a `using` construct implicitly causing Close to be called. As you lateron try to use `outputStream` as a stream, you need to set `stamper.CloseStream = false` before that.
Comment: @mkl - Not understanding you here.  You say I'm missing a stamper.Close() which I get, however then you say I need a stamper.CloseStream=false before that.  Is this Java syntax as it does not exist in C#.
Comment: Sorry. No, it's not Java, it's .Net only, but the CloseStream property is not directly in the PdfStamper but in its associated writer; thus, you will want to do `stamper.Writer.CloseStream = false`...
Answer: Your code snippet is incomplete, which makes it hard to answer your question.
You make people guess your question.
First guess:
You have a PDF of 10 KB, when reading it with PdfReader, you suddenly use 100 KB. You are surprised. How can this be?
The answer is simple: the PDF of 10 KB is compressed. When PdfReader starts working with it, it creates objects (requiring memory) and it decompresses data (requires more memory).
Second guess:
You have a PdfReader object and you use it to create a PdfStamper object. You forget to close the stamper. Suddenly you have a very small file of which PDF viewer tell you: this isn't a real PDF. How come?
You've made a mistake that many people who don't read the documentation make. The file you're manipulating with PdfStamper isn't fully written until you close the stamper.
Third guess:
You have a PdfReader object and you use it to create a PdfStamper object. You don't do anything with the stamper, you just close it. You're surprised the resulting PDF has a different size than the original one.

The size is smaller: iText sometimes throws away unused object, and it reorders objects in different ways. This is typical for PDF libraries.
The size is bigger: even if you didn't add anything, file size can grow, for instance when the original document is fully compressed (PDF 1.5 and higher). By default, PdfStamper won't create a compressed xref-stream (unless you instruct PdfStamper to compress the xref).

If none of these answers apply, I suggest that you rephrase your question. If not, you'll risk that moderators close it.
Comment: Where do I close the stamper?  It must be before I try to write from the stream, anywhere else makes no sense.
Comment: I assume the question is rhetorical as the question contains the answer.
Comment: If I close the stamper then I get a runtime about the outputStream being closed.  I also tried closing the reader (r.Close();) but this makes no difference - if I close the stamper I get a runtime and if I don't then the PDF file is 1kb and unreadable.  Appreciate this is 100% pilot error so any help would be greatly received.
Comment: "You don't do anything with the stamper,".  Sorry, I just snipped out the code that used the stamper as I know it worked.  It just loops thru the acrofields and stamps real data into them.
Comment: You corrected the code after I wrote my answer ;-) When I see your code, I stumble over choices I don't understand: why do you create the PDF in memory before writing it to a file; if you have a reason, why aren't you using MemoryStream.ToArray,... These choices are outside the scope of iText; these are pure C# design choices. This makes that I can't answer your question. In cases like this, I always suggest using Occam's Razor to cut away everything that is irrelevant and to end up with a pure iText question. Now your code is too convoluted. There are too many places where it can go wrong.
Comment: Thanks for the info.  I'm don't need to write a file at all, it's just easier whilst testing to see if the output is correct.  I will actually be storing the resultant PDF in a Byte[] in the database.  My problem remains though that if I close the stamper I get a runtime error whilst trying to write the file using FileStream, if I don;t close the stamper I just get an empty/unreadable PDF on disk.  I will distil the code down completely and post back.  The problem is not with the stamper it's my use of it.
Comment: I have updated the code above which now works, although I had to convert the outputStream to a Byte[] in order for the file O2.PDF to be readable.
Comment: Thanks for the feedback! Glad you now have a working solution!

PdfStamper changes size of MemoryStream


Como passar uma variável como parâmetro para o "getElementById"

Question: Preciso colorir vários canvas, o code abaixo colore um deles
var canvas1 = document.getElementById("a1");
var ctx1 = canvas1.getContext('2d');
ctx1.fillStyle = cor; //aqui vai a cor html
ctx1.fillRect(0, 0, 300, 300);

Posso automatizar a cor através de um array tipo arrcor = [#F95201,#AB31AA,#E70078...], algo como:
ctx1.fillStyle = arrcor[i];

Mas eu preciso que cada cor dessa vá para um canvas diferente de acordo com o ID, algo como id="a1", id="a2", id="a3"... Por isso, preciso automatizar essa mudança, tentei passar uma variável dentro, tipo:
rolln = "a" + i;
var canvas1 = document.getElementById(rolln);
var ctx1 = canvas1.getContext('2d');
ctx1.fillStyle = cor; //aqui vai a cor html
ctx1.fillRect(0, 0, 300, 300);

ou

var canvas1 = document.getElementById("a" + i);
var ctx1 = canvas1.getContext('2d');
ctx1.fillStyle = cor; //aqui vai a cor html
ctx1.fillRect(0, 0, 300, 300);

Mas não funciona, como eu faço para ele ir mudando o id, de acordo com o i (contador) dentro do laço já que o getElementById aceita somente uma string como parâmetro?
Comment: Deveria funcionar. Veja o exemplo no SO em ingles https://stackoverflow.com/questions/22068387/can-i-use-a-string-variable-in-document-getelementbyid . Seu canvas está na DOM? Pode ser isso...
Comment: dib, deveria funcionar já que `"a" + i` aqui é uma string tanto quanto `"a1"`. Veja se no console mostra erro, pq se `document.getElementById("a" + i)` não encontrar nada, dará um erro na linha `var ctx1 = canvas1.getContext('2d');`.
Comment: Exato, esse erro mesmo.
Answer: Você pode colocar a associação dentro de um array de objetos, como por exemplo:
var arrayCores = [
     {"nome_elemento": "a1", "cor": "#FFFFFF"},
     {"nome_elemento": "a2", "cor": "#AB31AA"}
];

for (var i in arrayCores){
   var canvas1 = document.getElementById(arrayCores[i]["nome_elemento"]);
   var ctx1 = canvas1.getContext('2d');
   ctx1.fillStyle = arrayCores[i]["cor"];
   ctx1.fillRect(0, 0, 300, 300);
}

Comment: Obrigado pelo seu raciocínio, o ponto é que os id's não mudam, serão sempre a1, a2, a3..., mas as cores sim, elas serão repassadas por um cálculo.
Comment: Desculpe pela demora, mas no caso bastaria você fazer com que o arrayCores fosse populado depois de saber qual cor fosse para cada elemento


Delphi / Rad Studio 10.4 - TSimpleDataSet: cannot expand Connection and DataSet property

Question: when I use a TSimpleDataSet, the IDE cannot allow me to expand Connection and DataSet property.
See the image below. I don't have the arrow to expand properties but only on Connection and DataSet.

Please give me support!
Answer: Your project needs to contain a TSqlConnection component before you can set the Connection property of a TSimpleDataSet.
Do this:

Start a new VCL project.

Add a TSqlConnection and a TSqlQuery to the form.

Configure the TSqlConnection to access a Sqlite database on your system.

Set the SqlConnection of SqlQuery1 to SqlConnection1.

Now ...

Add a TSimpleDataSet to the form.

Set the Connection property of SimpleDataSet1 to SqlConnection1.  This answers your first point.

Notice that you still can't change the DataSet property of SimpleDataSet1.  That's working as designed, because it is only supposed to use this internally-created dataset.

Open the DataSet property of SimpleDataSet1 and set its CommandText property to do a SELECT query against one of the tables in the Sqlite databaase.

Set SimpleDataSet1.DataSet.Active to True.  That'h how you use TSimpleDataSet's DataSet property.

Next, see https://docwiki.embarcadero.com/RADStudio/Sydney/en/Using_TSimpleDataSet and https://docwiki.embarcadero.com/Libraries/Sydney/en/SimpleDS.TSimpleDataSet.
Comment: Thank you very much for your response.
Unfortunately even following your guide still doesn't work.

Could it be a RadStudio configuration problem?
Comment: Well, if you make the effort to explain exacly what "still doesn't work", perhaps that will solve it.  But just saying it doesn't work doesn't convey any useful infornation whatsoever.  And no, I don't think it's a configuration problem.
Comment: The problem is simple: when I try to expand Connecton and DataSet property, the arrows is missing and i cannot expand to see properties.

I try the same project in another PC and it works perfectly. In my company only my pc have this problem, in the other 4 PC it works.

Thank you very much
Comment: Have you tried re-installing Delphi on your machine?
Comment: No because we use a lot of components and packages, so I would try to solve with current installation. :(
The last way will be the re-installation!


After Intsall SSL on magento site

Question: I installed SSL certificate for my magento store and set system config to:

Use Secure URLs in Frontend:yes
Use Secure URLs in Admin:yes

however when I review the page source some links have http:// instead of https://
I cleaned up the cache, but was not able to solve this issue, can any one help me?
Answer: You will need to fix your theme's templates, styles and extensions.
Search in projectroot for href="http:// or src="http:// and replace by href="// and src="//
also make sure external resources support ssl

After Intsall SSL on magento site


evaluating an ineuality

Question: Is it possible to find $\beta>1,0<\epsilon<1$ such that the following inequality is true for large enough $n$:
$4\pi^2 \beta\big( 2(n-1)^{-\frac{1}{2}(\epsilon+1)}n^{\frac{3}{2}}+\frac{1}{2}\frac{n}{n-1}\sqrt{(\gamma-1)(n-1)^{1-\epsilon}\ln n}+\frac{n^2}{2(n-1)}\big)<\exp(\frac{C(n-1)^\epsilon}{n})$
I encountered this problem when I am doing a research problem on deriving certain nice probabilistic bound by choosing approapriate values of parameters. However, here is where I am getting stuck at. Could someone help me out?
Many thanks.
Answer: Since $\epsilon < 1, \frac{(n-1)^\epsilon}n \to 0$ as $n \to \infty$. Therefore the RHS of your inequality will converge to $1$.
The LHS has three terms all of which are positive, and for which the last obviously diverges to $\infty$ as $n \to \infty$. Therefore the entire left-hand side diverges to $\infty$ as $n \to \infty$.
So no, you cannot find an $\epsilon < 1$ or $\beta > 0$ for which your inequality holds for large $n$.

evaluating an ineuality


Reverse loop through a GridView and retrieve the last records, VB.Net

Question: I know how to loop through a GridView and extract each row using the for each loop as below, but I was looking for a easy way to loop through the datagrid and say extract the last 20 rows? Is it possible to go through in reverse order in vb.net?
For Each row As GridViewRow In InventHistoryGridView.Rows

Next row

Comment: well you can do a for next loop starting from Rows.Count and down to 0 with -1 increment. As usual in these cases the question is anyway: why do you loop against/through the UI Control (Grid) and not on the original datasource?
Comment: The data is brought back from numerous tables and just displayed in a Gridview so can't really loop through the Orginal data as suggested.
Answer: Rows is just a representation of the Rows collection in a GridView
For i = ((Rows.Count - 1) - 20) To Rows.Count -1
   'do some cool stuff
Next

Unless you specifically have to start from the last row and head backwards, in which you do as Davide Piras suggested in his comment, displayed below.
For i = Rows.Count -1 To ((Rows.Count - 1) - 20) Step -1
    'do some cool stuff
Next

Comment: You could put Rows.Count - 21, but writing it out like that more explains what you're doing.


File to media migration: use node title for media title

Question: I have my files migrated from D7 to D8 (using d7_file source plugin to an entity:file destination).
I then migrated those files to media (using file_entity source plugin to an entity:media destination), based off this post.
However, the images in my Drupal 7 nodes of which I'm migrating never had alt text. Therefore, I would like to use the Drupal 7 node title as both (a) the Media title and (b) its image alt text.
My files to media migration looks like this (a portion of it):
source:
  plugin: file_entity
  type: image
  constants:
    bundle: 'image'
process:
  mid: fid
  bundle: 'constants/bundle'
  langcode:
    plugin: default_value
    source: language
    default_value: "und"
  # name: filename
  uid:
    plugin: default_value
    default_value: 1
  status: status
  created: timestamp
  changed: timestamp
  field_media_image/target_id: fid
  # field_media_image/alt: field_file_image_alt_text/0/value
destination:
  plugin: entity:media

The commented out lines are what I'd like to use the node title (name and field_media_image/alt), but I'm not sure how to pull in the original Drupal 7 node title. Any suggestions are appreciated.
Answer: Without knowing your content model, you can't answer this question directly, but what you'll need to do is query your node title for every fid entry for your source file entities table. You can do that in many places (e.g. source/process plugin) with your existing source plugin being a good place.
Using your custom file_entity source plugin as an example, you'll need to update the query() method so  its DB query joins the node table based on how you're content is modeled (e.g. entity/paragraph references) then selects the title column so it's included in the row data. You can follow that up with updating the fields() method so your source plugin will provide the title field you need.
Comment: Thanks. Seems like modifying my source plugin is the best option, but a bit over my head. My D7 node type is Business with an image `field_logo`. I'm using Image media in D8 (with `field_media_image`). I'll do some research from here. Thanks again.
Comment: Is that essentially what this source plugin is doing? https://github.com/geerlingguy/drupal-8-example-pix_migrate/blob/master/src/Plugin/migrate/source/PixImage.php
Comment: It's roughly similar in that it's joining 2 tables to provide one set of migration fields. In your case, you're starting with the `file_managed` table (to pull in all files) then attaching other tables to find associated node data.


Beta Bernoulli - distribution of p conditional on successes

Question: I have a Beta-Bernoulli process $\textbf{X}=\{X_1, X_2...X_n\}$, $\textbf{p}=\{p_1, p_2...p_n\}$ where:
$$X_i \sim Bernoulli(p_i)$$
$$p_i \sim Beta(\alpha,\beta)$$
where $\alpha$ and $\beta$ are known.
Is there an analytical solution for distribution of $p'$ for the subset of trials that were successful:
$f_{p'|X_i=1}$
It's easier to illustrate in a simulation setting.
That is, given sequence $\textbf{X}$, let $\textbf{X'}$ be the subset of $\textbf{X'}$ containing successes only: $$\textbf{X}'=\{X_i|X_i = 1\} = \{1,1,1...1\}$$
What is the distribution of $p$ that generated $\textbf{X'}$?
For example, below is the result from a simulation. The blue line is the distribution of $p$ from all trials ($p\sim Beta(2,2)$). Orange line is the conditional distribution of $p$ from successes only. Green line is the distribution of $p$ from failures only. So, the overall distribution of $p$ is a mixture of the two.
Answer: I suppose this is supposed to be a Bayesian question
If the prior for $p$ is $\operatorname{Beta}(\alpha, \beta)$ with density proportional to $p^{\alpha-1}(1-p)^{\beta-1}$ and you then observe $k$ successes and $n-k$ failures in $\mathbf{X}$ with likelihood proportional to $p^k(1-p)^{n-k}$
then the posterior density for $p$ given $\mathbf{X}$  is proportional to $p^{\alpha-1+ k}(1-p)^{\beta-1+ n-k}$ so the posterior distribution for $p$ is  $\operatorname{Beta}(\alpha+k, \beta+n-k)$
If $\mathbf{X}$ is a single observation and is a success then this mean the posterior distribution for $p$ is  $\operatorname{Beta}(\alpha+1, \beta)$

I now believe you think you are asking a different question, where different values of $p$ are drawn from $\operatorname{Beta}(\alpha, \beta)$ giving $p_1, p_2, \ldots, p_n$, and then each $X_i$ is drawn from  $\operatorname{Bernoulli}(p_i)$; you want to know the distribution of those $p_i$ corresponding to $X_i=1$.
This is equivalent to the final line of my initial answer on a single successful observation: the distribution in question is $\operatorname{Beta}(\alpha+1, \beta)$
To try and convince you, here are a couple of simulations in R of $10^6$ initial draws, first with $\alpha=2, \beta=2$ and then with $\alpha=2, \beta=8$, drawing the simulated densities for the successful cases (black) and comparing this with the theoretical densities for $\operatorname{Beta}(\alpha+1, \beta)$.  They are a very close match
set.seed(2021)

positives <- function(samplesize, alpha, beta){
  p <- rbeta(samplesize, alpha, beta)
  X <- rbinom(samplesize, 1, p)
  success <- (X == 1)
  psuccess <- p[success]
  plot(density(psuccess, from=0, to=1))
  curve(dbeta(x, alpha+1, beta), col="red", from=0, to=1, add=TRUE)
  c(mean(success))
  }

positives(10^6, alpha=1, beta=2)

and the chart above, starting with $p\sim \operatorname{Beta}(1,2)$, shows a $\operatorname{Beta}(2,2)$ distribution for the $p_i$ corresponding to $X_i=1$.

and the chart above, starting with $p\sim \operatorname{Beta}(2,2)$, shows a $\operatorname{Beta}(3,2)$ distribution for the $p_i$ corresponding to $X_i=1$. Then
positives(10^6, alpha=2, beta=8)

and the chart above, starting with $p\sim \operatorname{Beta}(2,8)$, shows a $\operatorname{Beta}(3,8)$ distribution for the $p_i$ corresponding to $X_i=1$.
Comment: Sorry if the question was unclear. I'm not trying to estimate the distribution of $p$ (the parameters $\alpha$ and $\beta$ are already known). I'm trying to estimate the distribution of $p'$ that generated all the successful trials. I updated the question for clarification.
Comment: @parasu You said "$X_i \sim Bernoulli(p)$" which suggested to me that $p$ was the parameter for all the trials
Comment: I understand the confusion now. For every $X_i$ there's a $p_i$ from which $X_i$ is sampled. I updated the post to clarify this.
Comment: @parasu That is in effect the same question worded a different way, but with the same answer.  I have now illustrated this
Comment: you're absolutely right. I just checked this as well. It makes sense that it can be reduced to a single draw. Thank you!


MySQL ADD CONSTRAINT 18+

Question: I need to know how do I ADD CONSTRAINT to a field and make sure that they are 18+ the field is age.
I can see how the following works, by joining the ID and the lastname to make the PersonID, but how do I get it to work to make sure a persons birthdate is 18 or over
ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName);

I know how to check the DOB
SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(dob, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(dob, '00-%m-%d')) AS age FROM `members`

but how do I put that into an ADD CONSTRAINT.
Comment: It would be as simple as adding a constraint `check (age >= 18)` in almost any other DBMS. But MySQL has not implemented `check` constraints so you'll have to enforce this through your insert/update statements or with triggers.
Comment: And it would be a bit more complicated if you stored the birthdate and not the age (as you should because birthdate doesn't change. What do you plan to do, update the `age` column once a year? Or every day?
Answer: Anything other than simple constraints (like foreign key references) is generally done with triggers in a DBMS.
You'll need a before trigger on the insert and update actions, to ensure you fail if either of those two try to set the age to something below 18.
If you want to simply enforce the column being a specific minimum value, you can just modify it in the insert or update trigger:
new.colname = 18

or leave it as it was in the update trigger:
new.colname = old.colname

To force a failure, you can raise a signal within the trigger.

As an aside, it's rather unusual to store an age in the database (if this is indeed what you're doing) since this is obviously something that will need to be updated every year. A more sensible approach would be to store the birthdate which doesn't change, and simply get the age as a calculated field.
Comment: I think OP indicated that "birthdate" was being stored, not age. (Or, maybe I inferred that from the question because that's what I expected.)  The check for "age at least 18" could easily be performed on value assigned to `birthdate` column.... `NEW.birthdate <= NOW() - INTERVAL 18 YEAR`.
Comment: @spencer7593, yeah, I originally thought that but then re-read it. OP talks of adding a constraint to a field and specifically names that field as `age`.  Still, it's just an aside, I'll change it to "*if* you're doing X, Y may be better".
Comment: I know but this is a college thing
Answer: Generally speaking, it's considered best practice to implement "business logic" such as this in the application, rather than in the database. Database constraints should generally only be used as a precaution to ensure that invalid data cannot enter your database: for instance, they can be used to ensure that foreign keys refer to valid objects, that required values are not inappropriately empty or zero, and so on. Under normal operation, it should be impossible to cause a constraint to be violated from the "front end" of your application.
One of the primary reasons for this is that it is often difficult to convert database errors (e.g, invalid value for column 'age', or something of the sort) into errors which can be usefully displayed to users (e.g, a dialog box saying "you must be 18 years old to continue"). Additionally, it is often difficult or even impossible to permit exceptions to database constraints, or to allow existing violations to be "grandfathered in" when a new constraint is introduced.
So… don't do this. Check the user's age in the section of your application which handles creating users (e.g, your registration script), and/or any other sections which would allow their age to be changed; or in the object which represents a user in your application.

MySQL ADD CONSTRAINT 18+


React: state variable is unchanged, setState is not triggering

Question: Here is my code. The confirm state variable on line 34 will not change. Calling setConfirm from handleSubmit does not change it. I've attempted deliberately toggling it in dev tools, no effect. I've tried deliberately setting it to true in the code, and placing {confirm &&
TEST
} at the top of the contact form. It doesn't render the h1, even when deliberately set to true. But {true &&
TEST
} works just fine. It's as if the confirm variable doesn't even exist. Can someone shed some light on why this might be happening?
import { useState, useEffect } from 'react'
import styles from "./ContactAndBooking.module.css"

const ContactAndBooking = () => {
    // Contact form values
    const [contact, setContact] = useState({
        name: null,
        email: null,
        phone: null,
        reason: null,
        message: null
    })

    // Booking form values
    const [booking, setBooking] = useState({
        name: null,
        email: null,
        phone: null,
        date: null,
        time: null,
        description: null
    })

    // Store today's date, calendar selection minimum
    const [minDate, setMinDate] = useState()

    // Display contact form or booking form, switch on button press
    const [typeContact, setTypeContact] = useState("contact")

    // Flag invalid form values for validation alerts
    const [validFlag, setValidFlag] = useState(true)

    // Successful message confirmation flag
    const [confirm, setConfirm] = useState(false)

    // Keep track of today's date, booking calendar selection minimum
    useEffect(()=> {
        let today = new Date
        let dd = today.getDate()
        let mm = today.getMonth() + 1
        let yyyy = today.getFullYear()

        if (dd < 10)
            dd = '0' + dd
        if (mm < 10)
            mm = '0' + mm

        today = yyyy + '-' + mm + '-' + dd
        setMinDate(today)
    })

    // Validate form values
    const validate = () => {
        // Track and return form validity, switch to false if any field fails
        let isValid = true

        // Check validity of contact form values
        if (typeContact === "contact"){
            // If no name, trigger invalid flag
            if (!contact.name){
                isValid = false
            }
            // If no email or email does not match regex, trigger invalid flag
            if (!contact.email || !contact.email.match(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)){
                isValid = false
            }
            // If phone number length is neither 10 nor 11 digits long, trigger invalid flag
            if (!contact.phone || ![10,11].includes(contact.phone.split('-').join('').split('').length) || contact.phone.split('-').join('').split('').some(e => !'0123456789'.includes(e))){
                isValid = false
            }
            // If no reason for contact is given, trigger invalid flag
            if (!contact.reason){
                isValid = false
            }
            // If message field is blank, trigger invalid flag
            if (!contact.message){
                isValid = false
            }
        }
        // Check validity of booking form values
        else if (typeContact === "booking"){
            // If no name, trigger invalid flag
            if (!booking.name){
                isValid = false
            }
            // If no email or email does not match regex, trigger invalid flag
            if (!booking.email || !booking.email.match(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)){
                isValid = false
            }
            // If phone number length is neither 10 nor 11 digits long, trigger invalid flag
            if (!booking.phone || ![10,11].includes(booking.phone.split('-').join('').split('').length)|| booking.phone.split('-').join('').split('').some(e => !'0123456789'.includes(e))){
                isValid = false
            }
            // If no booking date is selected, trigger invalid flag
            if (!booking.date){
                isValid = false
            }
            // If no booking time is selected, trigger invalid flag
            if (!booking.time){
                isValid = false
            }
            // If no booking description is given, trigger invalid flag
            if (!booking.description){
                isValid = false
            }
        }

        // set form validation alert flag on validation failure
        !isValid ? setValidFlag(false) : setValidFlag(true)

        return isValid
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        setValidFlag(true)
        if (validate()){
            console.log("CONFIRMATION TRIGGERING...") // TESTING
            // Trigger confirmation window
            setConfirm(true) // NOT TRIGGERING
            console.log("CONFIRMATION TRIGGERED") // TESTING
            if (typeContact === "contact"){
                // To be replaced with Axios request
                console.log(contact)
            }
            else if (typeContact === "booking"){
                // To be replaced with Axios request
                console.log(booking)
            }
        }
        // set form validation alert flag on validation failure
        else {
            setValidFlag(false)
            console.log("SUBMISSION INVALID")
        }
    }

    // Contact form view
    const contactWindow = () => {
        return (
            <form onSubmit={e => handleSubmit(e)}>
                {confirm &&
TEST
}
                Name:
                <input
                    className={styles.input}
                    name="name"
                    type="text"
                    onChange={e => setContact({...contact, name: e.target.value})}
                />
                Please enter your name.
                Email:
                <input
                    className={styles.input}
                    name="email"
                    type="email"
                    onChange={e => setContact({...contact, email: e.target.value})}
                />

                    Please enter a valid email address.

                Phone:
                <input
                    className={styles.input}
                    name="phone"
                    type="text"
                    onChange={e => setContact({...contact, phone: e.target.value})}
                />
                 !'0123456789'.includes(e)))
                    ? styles.warning
                    : styles.warningHidden
                }>Please enter a valid phone number.}
                <select
                    className={styles.select}
                    onChange={e => setContact({...contact, reason: e.target.value})}
                    defaultValue="Reason for contact"
                >
                    <option className={styles.option} value="Reason for contact" disabled>Reason for contact</option>
                    <option className={styles.option} value="Business Inquiry">Business Inquiry</option>
                    <option className={styles.option} value="Ticket Sales">Ticket Sales</option>
                    <option className={styles.option} value="Other">Other</option>
                </select>
                Please select a reason for contact.
                <textarea
                    className={`${styles.textarea} ${styles.textareaContact}`}
                    placeholder="How can I help you?"
                    onChange={e => setContact({...contact, message: e.target.value})}
                />
                Please enter your message.
                <button className={styles.submit} role="submit">Submit</button>
            </form>
        )
    }

    // Booking form view
    const bookingWindow = () => {
        return (
            <form onSubmit={handleSubmit}>
                Name:
                <input
                    className={styles.input}
                    name="name"
                    type="text"
                    onChange={e => setBooking({...booking, name: e.target.value})}
                />
                Please enter your name.
                Email:
                <input
                    className={styles.input}
                    name="email"
                    type="email"
                    onChange={e => setBooking({...booking, email: e.target.value})}
                />

                    Please enter a valid email address.

                Phone:
                <input
                    className={styles.input}
                    name="phone"
                    type="text"
                    onChange={e => setBooking({...booking, phone: e.target.value})}
                />
                 !'0123456789'.includes(e)))
                    ? styles.warning
                    : styles.warningHidden
                }>
                    Please enter a valid phone number.

                Select Date:
                <input
                    className={styles.datetime}
                    type="date"
                    name="date"
                    min={minDate}
                    onChange={e => setBooking({...booking, date: e.target.value})}
                />
                Please select a date for your event.
                Select Time:
                <input
                    className={styles.datetime}
                    type="time"
                    name="time"
                    onChange={e => setBooking({...booking, time: e.target.value})}
                />
                Please select a time for your event.
                <textarea
                    className={`${styles.textarea} ${styles.textareaBooking}`}
                    placeholder="Please give a brief description of your event."
                    onChange={e => setBooking({...booking, description: e.target.value})}
                />
                Please describe your event.
                <button className={styles.submit} role="submit">Submit</button>
            </form>
        )
    }

    // Message confirmation window, triggered on successful validation and submission
    const confirmWindow = () => {
        return (

                <h1 className={`${styles.confirmText} ${styles.confirmThankYou}`}>Thanks for the message!

                <h3 className={`${styles.confirmText} ${styles.confirmSubThankYou}`}>I'll get back to you ASAP.

                <button className={styles.confirmOkay} onClick={setConfirm(false)}>Okay</button>

        )
    }

    return (

            <button
                role="button"
                className={`${styles.toggle} ${styles.toggleContact}`}
                onClick={() => {
                    setTypeContact("contact")
                    setValidFlag(true)
                }}
            >
                CONTACT
            </button>
            <button
                role="button"
                className={`${styles.toggle} ${styles.toggleBooking}`}
                onClick={() => {
                    setTypeContact("booking")
                    setValidFlag(true)
                }}
            >
                BOOKING
            </button>

            {typeContact === "contact" && contactWindow()}
            {typeContact === "booking" && bookingWindow()}
            {confirm && confirmWindow()}

    )
}

export default ContactAndBooking

Answer: try changing line 273 from
<button className={styles.confirmOkay} onClick={setConfirm(false)}>Okay</button>

to
<button className={styles.confirmOkay} onClick={() => setConfirm(false)}>Okay</button>

then it appears to be working
Answer: When you call setConfirm(false) in your onClick event, what you are actually saying is to run the setConfirm state update as soon as the page loads. What you want to do is create an arrow function in the onClick so that you are passing reference to a function that will be ran once the button is clicked.
<button className={styles.confirmOkay} onClick={() => setConfirm(false)}>Okay</button>
If you wanted to do more than just call setConfirm, you can create another function and call setConfirm inside of that, then you can just pass the new function as reference so that every time the button is clicked the setConfirm function gets called.
const handleConfirmUpdate = () => {
   // do some stuff in here if you'd like
   setConfirm(true);
}

<button className={styles.confirmOkay} onClick={handleConfirmUpdate}>Okay</button>
Notice that we are not calling the function, but rather passing a reference.
Comment: Makes sense. What should I do about calling setConfirm(true) from another handler function? I'm trying to call it from handleSubmit, but it has no effect. I've also tried setting it with useCallback on the condition that validFlag is true, and still not effect.
Comment: You can call setConfirm(true) in another handler, just make sure your handler is either inside a arrow function in the onClick or passed as a reference. One thing you can do is to create a useEffect() hook with confirm as the dependency and see if it's changing or not (I bet that it is). Also I noticed that your useEffect for calculating min date is being called every re-render. Add a empty dependency to it as it looks like that's something you'd want to run once on component mount.


show images in disorder by the ng-repeat in angularjs

Question: you can see part of my code:

<ion-infinite-scroll ng-if="comment.loadMore" on-infinite="loadMoreComments()">
</ion-infinite-scroll>

when the 'comments' contains less  data ,all looks normal.But when there are lots of data in the array(maybe 100 or more),the images will be showed in disorder.For example, the image should be  in the  third "li" will be showed in the fourth "li".Could anyone tell me why,please!
PS. I use the ionic.bundle.js,but I dont know it will cause something wrong or not. And when the event of ion-infinite-scroll be tiggered,I will push the new data into the "comments" array.
Comment: I didn't find your code, may you send again?
Comment: I have just edit my text.Now you can read the code,please^_^
Comment: Sorry man, but i think that it's not enough... Can you put more information?
Answer: Tracking by $index is not a good idea. Can you track by commentItem.id (or another unique identifier on the commentItem) instead? I'm not sure if that will solve the problem but looking at that code snippet, that's the first thing I would try.


Como faço para pegar os dados de um select option enviar para um email o valor selecionado

Question: HTML:
<form action="orcamento.php" method="POST">

          <input type="text" class="form-control ajust_18" name="nome_do_projeto" placeholder="NOME DO PROJETO">

          <input type="text" class="form-control ajust_18" name="descreva_o_projeto" placeholder="DESCREVA O PROJETO">

          <input type="text" class="form-control ajust_18" name="qual_seu_orcamento" placeholder="QUAL SEU ORÇAMENTO">

          <input type="text" class="form-control ajust_18" name="quantos_metros_tem_seu_projeto" placeholder="QUANTOS METROS TEM SEU PROJETO?">

          CASA COMPLETA
          <select class="ajsta_rl" name="departamento1">
            <option value="Decoraração Completa">Decoração Completa</option>
            <option value="Doecoraçã Parcial">Decoração Parcial</option>
            <option value="Nada a Mudar">Nada a mudar</option>
          </select>

          COZINHA
          <select class="ajsta_rl" name="departamento2">
            <option value="Decoração Completa">Decoração Complea</option>
            <option value="Decoração Parcial">Decoração Parcial</option>
            <option value="Parede Única">Parede Única</option>
            <option value="Formato em L">Formato em L</option>
            <option value="Formato em U">Formato em U</option>
            <option value="Nada a Mudar">Nada a Mudar</option>
          </select>

          SALA DE ESTAR
          <select class="ajsta_rl" name="departamento3">
            <option value="Decoração Completa">Decoraração Completa</option>
            <option value="Decoração Parcial">Decoraração Parcial</option>
            <option value="Nada a Mudar">Nada a Mudar</option>
          </select>

          BANHEIROS
          <select class="ajsta_rl" name="departamento4">
            <option value="Decoração Completa">Decoração Completa</option>
            <option value="Decoração Parcial">Decoração Parcial</option>
            <option value="Moderno">Moderno</option>
            <option value="Campestre">Campestre</option>
            <option value="Clássico">Clássico</option>
            <option value="Rustíco">Rustíco</option>
            <option value="Nada a Mudar">Nada a Mudar</option>
          </select>

          QUARTOS
          <select class="ajsta_rl" name="departamento5">
            <option value="Decoração Parcial">Decoração Completa</option>
            <option value="Decoração Parcial">Dcoração Parcial</option>
            <option value="Nada a Mudar">Nada a Mudar</option>
          </select>

          COMERCIAL ESCRITÓRIO
          <select class="ajsta_rl" name="departamento6">
            <option value="Decoração Completa">Decoração Completa</option>
            <option value="Decoração Parcial">Dcoração Parcial</option>
            <option value="Nada a Mudar">Nada a Mudar</option>
          </select>

          <input type="text" class="form-control ajust_18" name="nome_completo" id="nome_completo" placeholder="NOME COMPLETO">

          <input type="text" class="form-control ajust_18" name="cidade" id="cidade" placeholder="CIDADE">

          <input type="text" class="form-control ajust_18" name="estado" id="estado" placeholder="ESTADO [ UF ] ">

          <input type="text" class="form-control ajust_18" name="telefone" id="telefone" placeholder="TLEFONE">

          <input type="email" class="form-control ajust_18" name="mail" id="mail" placeholder="E-MAIL">

          <input type="submit" value="Receba uma cotação" class="btn btn-primary">

</form>

Código PHP:
<?php
 //variaveis

 $equipe = 'Lucilene Bredoff';
 $quebra_linha = "\n\r";

 $departamento1 =    $_POST['casa_completa'];
 $departamento2 =    $_POST['cozinha'];
 $departamento3 =    $_POST['sala_de_estar'];
 $departamento4 =    $_POST['banheiros'];
 $departamento5 =    $_POST['quartos'];
 $departamento6 =    $_POST['comercial_escritorio'];

$emailremetente     = trim($_POST['email']);
$emaildestinatario  = 'firstname.lastname@example.com'; // Digite seu e-mail aqui, lembrando que o e-mail deve estar em seu servidor web
 //$email_to = 'email@example.com';  email para envio.
 $nome_do_projeto                     = $_POST["nome_do_projeto"];
 $descreva_o_projeto                  = $_POST["descreva_o_projeto"];
 $qual_seu_orcamento                  = $_POST["qual_seu_orcamento"];
 $quantos_mentros_tem_seu_projeto     = $_POST["quantos_metros_tem_seu_projeto"];
 $nome_completo                       = $_POST["nome_completo"];
 $cidade                              = $_POST["cidade"];
 $estado                              = $_POST["estado"];
 $telefone                            = $_POST["telefone"];
 $mail                                = $_POST["mail"];

 //$headers = "MIME-Version: 1.1".$quebra_linha;
 //$headers .= "Content-type: text/html; charset=utf-8".$quebra_linha;
 $headers .= "Nome do Projeto: $nome_do_projeto".$quebra_linha;
 $headers .= "Remetente: $mail".$quebra_linha;
 $headers .= "From: $emailremetente\r\n"; // remetente
 $headers .= "Return-Path: $emaildestinatario \r\n"; // return-path
 //$headers .= "From: $emailremetente;".$quebra_linha;
 //$headers .= "Reply-To:".$departamento .$quebra_linha;
 //$headers .= "Retrun-Path:".$emaildestinatario .$quebra_linha;

$corpo     = "Projetos Online - Lucilene Bredoff\n";
$corpo    .= "Nome Do Projeto : "                  .$nome_do_projeto . "\n";
$corpo    .= "Descreva O Projeto : "               .$descreva_o_projeto. "\n";
$corpo    .= "Qual Seu Orçamento : "               .$qual_seu_orcamento. "\n";
$corpo    .= "Quantos Metros Tem Seu Projeto : "   .$quantos_mentros_tem_seu_projeto. "\n";
$corpo    .= "Nome Completo: "                     .$nome_completo. "\n";
$corpo    .= "Cidade: "                            .$cidade. "\n";
$corpo    .= "Estado: "                            .$estado. "\n";
$corpo    .= "Telefone :"                          .$telefone. "\n";
$corpo    .= "E-mail : "                           .$mail . "\n";

$status = mail($departamento1,$departamento2,$departamento3,$departamento4,$departamento5,$departamento6,$nome_do_projeto,$headers,$corpo); //enviando o email.

if ($status) {
  echo "";
}
else {
  echo "";
}
?>

Comment: Olá Diogo, esplique melhor sua dúvida, não coloque apenas código. E verifique também a formatação dos códigos.
Comment: É a mesma coisa de enviar um *input*: `$derpatamento1 = $_POST['derpatamento1'];`
Comment: Eu ja tentei passar desta forma mas o    $status = mail($departamento1,$departamento2,$departamento3,$departamento4,$departamento5,$departamento6,$nome_do_projeto,$headers,$corpo); //enviando o email. da erro nesta linha  e não envia o e-mail.
Comment: @DavidAlves O que preciso e pegar os itens que estão no select passados pelo option  como exemplo   Decoração completa    e enviar para um e-mail
Comment: Acontece que, no seu código, você está utilizando `$departamento1 = $_POST['casa_completa'];`, porém não existe um campo com o atributo `name="casa_completa"`
Comment: O correto é `$departamento1 = $_POST['departamento1'];`
Comment: usei esta modificação mas continuo tendo erro de retorno na linha $status = mail($departamento1,$departamento2,$departamento3,$departamento4,$departamento5,$departamento6,$nome_do_projeto,$headers,$corpo); //enviando o email.
Comment: @DiogoCunha Qual o erro?
Comment: Apresenta a mensagem Warning: mail()expect at most 5 parameters, 9 given in /home/lucilenebredoff/public_html/orcamento.php on line 54

Retornando o else que passei informando do preenchimento dos campos
Answer:

<?php
 //variaveis

 $equipe = 'Lucilene Bredoff';
 $quebra_linha = "\n\r";

 $departamento1 =    $_POST['departamento1'];
 $departamento2 =    $_POST['departamento2'];
 $departamento3 =    $_POST['departamento3'];
 $departamento4 =    $_POST['departamento4'];
 $departamento5 =    $_POST['departamento5'];

$emailremetente     = trim($_POST['email']);
$emaildestinatario  = 'firstname.lastname@example.com'; // Digite seu e-mail aqui, lembrando que o e-mail deve estar em seu servidor web
 //$email_to = 'email@example.com';  email para envio.
 $nome_do_projeto                     = $_POST["nome_do_projeto"];
 $descreva_o_projeto                  = $_POST["descreva_o_projeto"];
 $qual_seu_orcamento                  = $_POST["qual_seu_orcamento"];
 $quantos_mentros_tem_seu_projeto     = $_POST["quantos_metros_tem_seu_projeto"];
 $nome_completo                       = $_POST["nome_completo"];
 $cidade                              = $_POST["cidade"];
 $estado                              = $_POST["estado"];
 $telefone                            = $_POST["telefone"];
 $mail                                = $_POST["mail"];

 //$headers = "MIME-Version: 1.1".$quebra_linha;
 //$headers .= "Content-type: text/html; charset=utf-8".$quebra_linha;
 $headers .= "Nome do Projeto: $nome_do_projeto".$quebra_linha;
 $headers .= "Remetente: $mail".$quebra_linha;
 $headers .= "From: $emailremetente\r\n"; // remetente
 $headers .= "Return-Path: $emaildestinatario \r\n"; // return-path
 //$headers .= "From: $emailremetente;".$quebra_linha;
 //$headers .= "Reply-To:".$departamento .$quebra_linha;
 //$headers .= "Retrun-Path:".$emaildestinatario .$quebra_linha;

$corpo     = "Projetos Online - Lucilene Bredoff\n";
$corpo    .= "Nome Do Projeto : "                  .$nome_do_projeto . "\n";
$corpo    .= "Descreva O Projeto : "               .$descreva_o_projeto. "\n";
$corpo    .= "Qual Seu Orçamento : "               .$qual_seu_orcamento. "\n";
$corpo    .= "Quantos Metros Tem Seu Projeto : "   .$quantos_mentros_tem_seu_projeto. "\n";
$corpo    .= "Nome Completo: "                     .$nome_completo. "\n";
$corpo    .= "Cidade: "                            .$cidade. "\n";
$corpo    .= "Estado: "                            .$estado. "\n";
$corpo    .= "Telefone :"                          .$telefone. "\n";
$corpo    .= "E-mail : "                           .$mail . "\n";
$corpo    .= "Casa Completa:"                      .$departamento1. "\n";
$corpo    .= "Cozinha: "                           .$departamento2. "\n";
$corpo    .= "Sala de Estar: "                     .$departamento3. "\n";
$corpo    .= "Banheiros: "                         .$departamento4. "\n";
$corpo    .= "Quartos: "                           .$departamento5. "\n";
$corpo    .= "Comercial Escritório: "              .$departamento6. "\n";

$status = mail($emaildestinatario,$nome_do_projeto,$headers,$corpo); //enviando o email.

if ($status) {
  echo "";
}
else {
  echo "";
}
?>

Consegui resolver, agradeço a todos que ajudaram


In oracle database how do we maintain same surrogate key (sequence value) on both tables simultaneously

Question: In our data warehouse,  we have a requirement to load 2 tables which are at the same grain. Volume in both tables is exactly same. During the insert, i need to load same surrogate key (sequence) simultaneously. Are there any ways to achieve this?
Comment: Can you load one table first, and then - once you're done - "copy" rows from that table to the second table, simply reusing the key value? Or, depending on how you load data, if it is "one row into table 1, then one row into table 2" (which is a bad option, row-by-row is slow-by-slow, but table 1 could use sequence.nextval while table 2 would use sequence.currval (basically, the same value).
Comment: loading one table first and then loading the second is time consuming.We want to load the tables in parallel but maintain same key value. is there any way to achieve this using same sequence?
Comment: I don't think so. Once you use sequence.nextval, it is consumed and table 2 can't reuse it.
Comment: @Littlefoot Table 2 can use `sequence.currval` though
Comment: That's what I said 21 minutes ago, @Matthew :), but not - unless I'm wrong - in two bulk parallel loading sessions.
Comment: @Littlefoot sorry, missed that at the end of your 1st comment.
Comment: No problem at all, @Matthew
Comment: sequence.currval doesn't seem to be a possible option since its a set based processing not one row at a time.
Answer: There are too many unknowns about your ETL process, so I apologize if this is way off.  It's too long for a comment though.
You can insert into multiple tables at the same time using the INSERT ALL command.  Like this:
create sequence matt_s;
create table etl1 ( id number, other_data VARCHAR2(30));
create table etl2 ( id number, other_data VARCHAR2(30));

insert all
  into etl1 (id, other_data) values ( matt_s.nextval, other_data )
  into etl2 (id, other_data) values ( matt_s.nextval, other_data )
select /* dummy source data */
       to_char(rownum) other_data
from   dual src
connect by rownum <= 50;

Every row in the source query will be inserted into both tables and share common values for the id column.
Comment: I will try this method. Thank you!


Accessing Event Object from JavaScript Function

Question: I have something similar to the following:

   Content...

When doSomethingElse() is called, I don't want doSomething() to be called as well.
Searching the web, I found references to event.stopPropagation() and event.cancelBubble(), which prevent the event from bubbling up to parent elements.
Two questions:

How can I get the event object from doSomethingElse()?
Is it necessary to use both event.stopPropagation() and event.cancelBubble(), or has the industry settled on a standard for this?
Comment: You might consider using event delegation to simplify things:
e.g., [this](http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/)
Answer: 1.) You can just pass the event in as the first parameter of the function:

   Content...

(Note: the same works in jQuery event bindings)
Example Fiddle

2.) I've started to see a lax in people using cancelBubble and instead switch over to stopPropagation entirely (the prior being used mostly for legacy IE support). Also, the MDN Docs say to use stopPropagation instead since cancelBubble is both "non-standard" and "deprecated" (source).
(Note: stopPropagation alone does not stop default events. For that, you'll want to call event.preventDefault() (source).
Comment: I had no idea I could just add `event` as a parameter like that. Where did it come from? I'll try it.
Comment: It's always passed through as the first parameter after an event is fired. Since it's JavaScript, you can completely ignore it as a parameter and all will be well lol.
Answer: you should define `doSomethingElse' as follows:
var doSomethingElse = function(e){
    // e: event object ... so ...
    e.stopPropagation(); // enough
};

you should also pass the event object in your call: doSomethingElse(event)
event.stopPropagation() works on all browsers, as for IE, works as expected on IE9 and later.


Rota resulta em 404 Not Found

Question: Estava seguindo o tutorial de inicialização do CodeIgniter quando me deparei com um problema com rotas.
o arquivo de rotas está com as seguintes rotas:
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

$route['news/create'] = 'news/create';
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';

Um exemplo de controller poderia ser o Pages:
class Pages extends CI_Controller
{
    public function view($page = 'home')
    {
        if ( ! file_exists(APPPATH . 'views/pages/' . $page . '.php'))
            show_404();

        $data['title'] = ucfirst($page);

        $this->load->view('templates/header', $data);
        $this->load->view('pages/'.$page, $data);
        $this->load->view('templates/footer', $data);
    }
}

Quando chamado pelo default_controller ele é executado normalmente, mas quando tento entrar em uma rota diferente é exibido um Not Found do Apache.
Já verifiquei se todas classes estão com os arquivos iniciados em letra maiúscula, o módulo rewrite está ativo, e no config.php só alterei o:
$config['base_url'] = 'http://estudo.local/ci/';

O .htaccess:
<IfModule authz_core_module>
    Require all denied
</IfModule>
<IfModule !authz_core_module>
    Deny from all
</IfModule>

Qual seria o problema?
Comment: Coloquei ele na pergunta, não alterei nada nele pois no tutorial não dizia nada sobre ele então confiei por seu um tutorial oficial.
Comment: Como está o arquivo .htaccess?
Comment: Não esqueceu de colocar ele?
Answer: Coloca o arquivo .htaccess da seguinte forma:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]

Rota resulta em 404 Not Found