text:
Q: Not getting proper output I'm having trouble getting this program to output things in the correct format. The setw function doesn't seem to do what I want it to do. Also, the averages, lows and highs are giving me the wrong answer. The program is supposed to read in a file and process them to find the highest temp, the lowest temp and the average of all temps for that day. Each day has the same values as the previous day.
Can someone point out what I'm doing wrong?
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <fstream>
#include <string>

double averageTemp(double total, int number);
double lowTemp(double valueLow);
double highTemp(double valueHigh);
double high = 0;
double low = 0;

int main()
{
    std::string dummy = "";
    int day, time = 0;

    double input1[10][50], input5[10][50], input25[10][50];
    /*
    Keeps track of the data:
        Dimension 1: stores the input for each time of the day.
    */

    double m1[10][3], m5[10][3], m25[10][3];
    /*
    Process data:
        Dimension 1:
            Index 1: Keeps track of day
        Dimension 2:
            Index 1: Average temp
            Index 2: Low temp
             Index 3: High temp
    */

   std::ifstream datain;
   std::ofstream dataout;

    datain.open("curiosity234X.dat");
    dataout.open("output.dat");

    for (unsigned int i = 0; i < 4; i++)
    {
        getline(datain, dummy);
    }

    int dayCount = 0, loopDay;

    while (datain >> day >> dummy >> dummy >> input1[day][time]
                  >> input5[day][time] >> input25[day][time])
    {
                  while (dayCount == 0)
                  {
                        loopDay = day - 1;
                        dayCount++;
                  }

     m1[day][0] = averageTemp(input1[day][time], time);
     m1[day][1] = lowTemp(input1[day][time]);
     m1[day][2] = highTemp(input1[day][time]);

     m5[day][0] = averageTemp(input5[day][time], time);
     m5[day][1] = lowTemp(input5[day][time]);
     m5[day][2] = highTemp(input5[day][time]);

     m25[day][0] = averageTemp(input25[day][time], time);
     m25[day][1] = lowTemp(input25[day][time]);
     m25[day][2] = highTemp(input25[day][time]);

     time++;
    }

    dataout << std::setw(5) << std::fixed;
    dataout << "Average" << "Low" << "High" << std::endl
            << "Temp" << "Temp" << "Temp" <<std::endl
            << "1 meter" << ".5 meters" << ".25 meters" << std::endl;

    std::cout << std::setw(5) << std::fixed;
    std::cout << "Average" << "Low" << "High" << std::endl
              << "Temp" << "Temp" << "Temp" <<std::endl
             << "1 meter" << ".5 meters" << ".25 meters" << std::endl;

    for (unsigned int i = loopDay; i < day; i++)
    {
        dataout << std::fixed << std::setprecision(1) << std::setw(5);
        dataout
                << m1[day][0] << m1[day][1] << m1[day][2]
            << m5[day][0] << m5[day][1] << m5[day][2]
                << m25[day][0] << m25[day][1] << m25[day][2]
                << std::endl;

        std::cout << std::fixed << std::setprecision(1) << std::setw(5);
        std::cout
                  << m1[day][0] << m1[day][1] << m1[day][2]
          << m5[day][0] << m5[day][1] << m5[day][2]
              << m25[day][0] << m25[day][1] << m25[day][2]
                  << std::endl;
    }

    std::cout << std::endl << std::endl << std::endl
              << "The output.dat file has been written and transmitted."
              << std::endl;

    _getch();
    return 0;
}

double lowTemp(double valueLow)
{
    if (valueLow < low)
    {
        ::low = valueLow;

        return valueLow;
    } else
    {
        return low;
    }
}

double highTemp(double valueHigh)
{
    if (valueHigh > high)
    {
        ::high = valueHigh;

        return valueHigh;
    } else
    {
        return high;
    }
}

double averageTemp(double total, int number)
{
    double average = total/double(number);

    return average;
}

A: *

*Please check this loop:
for (unsigned int i = loopDay; i < day; i++) { ... }
the i variable isn't used inside the loop body, so you're doing the same thing n-times. I think you should change m1[day][...] with m1[i][...] (same for m5 and m25).

*About the loopDay variable:
while (dayCount == 0)
{
  loopDay = day - 1;
  dayCount++;
}

I suppose what you mean is:
if (dayCount == 0)
  loopDay = day;

++dayCount;

In this way loopDay stores the first day seen (the first day you'll print in the for loop). Considering that dayCount isn't referenced in other points of the source code you could get rid of it and write:
if (time == 0)
  loopDay = day;

*Now you have to change the the upper limit in the for loop: the last day you have seen must be included so < day must be <= day.
There are other things to change but this is a starting point.


text:
Q: What is the best set of Authorized networks setting for PostgreSQL as it is missing App Engine authorization setting The option to authorize all apps belonging to the same project is missing in Google Cloud SQL - PostgreSQL. The documentation provide examples for authorization using the network setting 0.0.0.0/0 which simply allows all IPv4 connections.
As we do not know when the App Engine authorization feature would be available for PostgreSQL, what is the next best setting to allow the IP range of App engine instances? I am lost as they are dynamically allocated and ephemeral.
Specs
App Engine Flex (1 aspnetcore + 1 custom service on dotnet core)
Cloud SQL - PostgreSQL
Both belong to the same GCP project

A: The way to go in this case is to follow the documentation steps:
add 0.0.0.0/0 as the network and configure SSL access from the App Engine Flexible to the Cloud SQL PostgreSQL instance. The crucial part here is to adjust the PostgreSQL instance details, namely the SSL connections configuration. You need to allow only SSL connections to reach your instance, this way the GAE Flex instances (and only them, as having the SSL certificate) will be able to reach the instance with the database, even having dynamically allocated IPs.
To allow SSL connections only in your PostgreSQL instance:

*

*Go to Cloud Console, choose the SQL section

*Click on your PostgreSQL instance to view its details

*Click the Allow only SSL connections button in the SSL tab

redpajama_set_name: RedPajamaStackExchange


text:
Q: In unity, how to make default cylinder top or bottom face forward specific target position here is my code:
[ExecuteInEditMode]
public class TestCylinderLookAt : MonoBehaviourExt
{
    private GameObject target;

    void Start()
    {
        target = GameObject.Find("TargetSphere");
    }

    // Update is called once per frame
    void Update()
    {
        transform.LookAt(target.transform.position);
    }
}
#endif

and here is my try:

I don't expect cylinder side to forward target, I expect cylinder top or bottom face forward target, how should i do?

A: You could apply a local-space rotation of 90 degrees in your cylinder after you perform the LookAt() operation, as the following:
void Update()
{
    transform.LookAt(target.transform.position);
    transform.Rotate(90, 0, 0, Space.Self);
}

A: You have two options:
Option 1: Make your own cylinder
If you model your own cylinder, you can have the Z axis oriented any way you like.
Option 2: Reparenting
Create an empty game object as a child of the cylinder, set its position to (0,0,0), then reorder the hierarchy so that the empty object is now the parent of the cylinder. Rotate the cylinder so that its top faces its parent's Z axis.
Remember to adjust any scripts and references such that they target the parent object instead of the model.


text:
Q: Proving the uniform convergence of $\sin(\frac{x}{n}) e^{-x^2}$ How might one show that $\left(\sin(\frac{x}{n})e^{-x^2}\right)_n$ converges uniformly? I tried finding the supremum by setting the 1st derivative to $0$, but that gives a hard-to-solve equation. There must therefore be a looser bound, but I am not seeing it. Thanks.

A: Notice that $xe^{-x^2}$ is uniformly bounded, say by some constant $M$.  Then $$\biggr|\sin\left(\frac{x}{n}\right)e^{-x^2}\biggr|\leq \biggr|\frac{x}{n}e^{-x^2}\biggr|\leq \frac{M}{n}.$$
As $\frac{1}{n}$ converges and this no longer depends on $x$ we have uniform convergence.


text:
Q: SSL Error on upgrade to WSO2 IS 5.1 with apache http server We are in process of upgrading WSO2 IS 5.0 SP1 to WSo2 5.1. The communication with WSO2 IS happens via a Apache HTTP server 2.2. This Communication works fine with WSO2 IS 5.0 SP1. But when we upgrade to 5.1 we get the following error message on the browser.
Proxy Error

The proxy server could not handle the request GET /services/EntitlementService.
Reason: Error during SSL Handshake with remote server

Update:
On inspecting the apache log we get the following error
[Fri Jan 29 11:34:59 2016] [debug] mod_proxy_http.c(1974): proxy: HTTP: serving URL https://[IP]:9443/services/EntitlementService?wsdl
[Fri Jan 29 11:34:59 2016] [debug] proxy_util.c(2018): proxy: HTTPS: has acquired connection for ([IP])
[Fri Jan 29 11:34:59 2016] [debug] proxy_util.c(2074): proxy: connecting https://[IP]:9443/services/EntitlementService?wsdl to [IP]:9443
[Fri Jan 29 11:34:59 2016] [debug] proxy_util.c(2200): proxy: connected /services/EntitlementService?wsdl to [IP]:9443
[Fri Jan 29 11:34:59 2016] [debug] proxy_util.c(2451): proxy: HTTPS: fam 2 socket created to connect to [IP]
[Fri Jan 29 11:34:59 2016] [debug] proxy_util.c(2583): proxy: HTTPS: connection complete to [IP]:9443 ([IP])
[Fri Jan 29 11:34:59 2016] [info] [client [IP]] Connection to child 0 established (server [HOSTNAME]:443)
[Fri Jan 29 11:34:59 2016] [info] Seeding PRNG with 136 bytes of entropy
[Fri Jan 29 11:34:59 2016] [debug] ssl_engine_kernel.c(1871): OpenSSL: Handshake: start
[Fri Jan 29 11:34:59 2016] [debug] ssl_engine_kernel.c(1879): OpenSSL: Loop: before/connect initialization
[Fri Jan 29 11:34:59 2016] [debug] ssl_engine_kernel.c(1879): OpenSSL: Loop: SSLv2/v3 write client hello A
[Fri Jan 29 11:34:59 2016] [debug] ssl_engine_io.c(1947): OpenSSL: I/O error, 7 bytes expected to read on BIO#33bb678 [mem: a59cd0]
[Fri Jan 29 11:34:59 2016] [debug] ssl_engine_kernel.c(1908): OpenSSL: Exit: error in SSLv2/v3 read server hello A
[Fri Jan 29 11:34:59 2016] [info] [client [IP]] SSL Proxy connect failed
[Fri Jan 29 11:34:59 2016] [info] [client [IP]] Connection closed to child 0 with abortive shutdown (server [HOSTNAME]:443)
[Fri Jan 29 11:34:59 2016] [error] (502)Unknown error: proxy: pass request body failed to [IP]:9443 ([IP])
[Fri Jan 29 11:34:59 2016] [error] [client [IP]] proxy: Error during SSL Handshake with remote server returned by /services/EntitlementService
[Fri Jan 29 11:34:59 2016] [error] proxy: pass request body failed to [IP]:9443 ([IP]) from [IP] ()
[Fri Jan 29 11:34:59 2016] [debug] proxy_util.c(2036): proxy: HTTPS: has released connection for ([IP])
[Fri Jan 29 11:34:59 2016] [debug] ssl_engine_kernel.c(1889): OpenSSL: Write: SSL negotiation finished successfully
[Fri Jan 29 11:34:59 2016] [info] [client [IP]] Connection closed to child 63 with standard shutdown (server [HOSTNAME]:443)

Kindly advice.


text:
Q: How can I get email.utils.make_msgid to pick from address domain instead of local hostname in Python I am trying to get the message-id to pick the domain portion of the from address and not sure how to do it. I can hardcode it but I would like it pick up whatever the domain portion of the from address
message = MIMEMultipart("alternative")
message['From'] = email.utils.formataddr(('User1', 'aniga@domain.com')) # header address
message['Date'] = email.utils.formatdate(timeval=None, localtime=False, usegmt=False)
message['Message-ID'] = email.utils.make_msgid("".join(random.choice("0123456789ABCDEF") for i in range(16)), domain=pickfrom from address domain
message['Subject'] = 'Testing from Python'
message['To'] = email.utils.formataddr((recpient, recpient@example.com))

A: There is no built-in support for doing that; if you want to extract the domain part from the From: address, you have to do that separately.
There should be no need for you to pick the idstring yourself, by the way; let Python take care of that.
You'll probably also want to upgrade to use the Python 3.6+ updated EmailMessage API for new code.
from email.message import EmailMessage
import email.utils

message = EmailMessage()
message['From'] = email.utils.formataddr(('User1', 'aniga@domain.com'))
message['Date'] = email.utils.formatdate(timeval=None, localtime=False, usegmt=False)
# Notice change here
message['Message-ID'] = email.utils.make_msgid(domain=message['From'].groups[0].addresses[0].domain)
message['Subject'] = 'Testing from Python'
# Trivial typo + syntax edit here
message['To'] = email.utils.formataddr(('recipient', 'recipient@example.com'))

If what you have isn't a formataddr it won't have a groups attribute; if you simply have a str containing the sender's address, a quick and dirty heuristic is to simply split on @ and take everything up through the first > or whitespace character as probably the domain name.  But this has a number of pesky corner cases you really want to avoid - it's better to parse the From: header (again, if necessary) and be reasonably sure that you really get it properly parsed.


text:
Q: Working directory of azure load testing service? We have uploaded a shell script file as a parameter to Azure load test service and trying to access it in OS process sampler in our jmeter script.
What is the working directory which we have to mention to pick the file which we have uploaded ?
We always get error file not found in directory /


text:
Q: Visual Tree (graph) generating I'm trying to find a piece of software or some API / technology that would allow me to do the following....
I'm looking to generate a family tree based on input I was to feed into a piece of software. I'd like each child of the tree to be clickable and for me to embed it into a website somehow.

A: I think AT&T's graphviz is a great tool for displaying trees.
This link suggests that it's possible to associate a URL with a node: "...Note that URL tags are respected, to allow clickable PDF objects..."

A: Have a look at Ryan Schmidt's Canviz parser for Graphviz output. It takes the xdot output you'd get from running Graphviz on a server and renders it using pure Javascript.


text:
Q: pandas groupby ignoring NAs I have a DataFrame which has a lot of NAs.  pandas's groupby operation is ignoring any combinations with NA in it.  Is there a way to include NAs in groups?  If not, what are the alternatives to pandas groupby?  I really don't want to fill in NAs because the fact that something is missing is useful information.
Edit: I noticed that my question is exactly the same issue reported in groupby columns with NaN (missing) values
Has there been any developments technology to get around this issue?

A: I will use some kind of non-NA representation for NA only for groupby, which can't be confused with proper data (e.g. -999999 or 'missing')
df.fillna(-999999).groupby(...)

As inplace argument has default value False your original dataframe will not be affected.


text:
Q: PHP variable is not assigned I'm working on a laravel project.
now I want to access one of my column which is data
The data colmn contains an array of stuff like message, klant_address, reactionPlacer and more.
foreach(Auth::user()->unreadNotifications as $notfiy) {
 {{ $notify->data['klant_address'] }} //This gives an error "variable is not assigned"
}

but if i store it first to a variable it does'nt gives an error like this
foreach(Auth::user()->unreadNotifications as $notfiy) {
$klantAddress = $notify->data['klant_address']
echo $klantAddress
}

Now comes the weirdest part of all
if i do
dd($notify->data['klant_address']) <-- this does gives me the signle string return

and
foreach(Auth::user()->unreadNotifications as $notfiy) {
{{ $notfiy->data['messages'] }} <--- This does output
}

does work.
I hope someone can help me or at least explain why this is happened. Because I'm so confused for it.
thanks in advance.

Error Page

Database Table

A: Looks more like JSON to me. (Look at the last image)
Try this:
{{ $notify->data->klant_address ?? '' }}

If that doesn't work, try {{ json_encode($notify->data)->klant_address ?? '' }}
(Thrown in ternaries to help with nulls etc.)


text:
Q: APNS certificate issue for free and paid version I have two Applications in iTunes. A free version and a paid version. The paid version does not have advertisement. The two versions have different App Ids.
I have set up APNS for one of the App Ids. How can I handle notifications for both Apps?

A: Each application requires its own certificate (since each App Id has its own push certificates).
Therefore, your server will have to hold a different certificate for each App, and maintain a separate connection with the APNs server for each App (since you use the certificate to open the connection).
This means that when one of your apps sends a device token to your server, you have to know which app sent the device token, and mark it accordingly in your DB (in order to know which connection to the APNs server to use when pushing a notification to that device).


text:
Q: Cythonizing and importing cythonized files in profiler/cmd-line not working since Python 3.6.2 I've been using the Spyder profiler quite a lot to profile my script. Today I updated to Anaconda 4.4 with Python 3.62 and Spyder 3.2.1, all running on 64bit.
My cythonized functions, can be imported in the Spyder editor and the IPython console easily. Running my script in the editor or using the IPython console works as expected.
But when I try to profile my script in the Spyder profiler OR try to run it in cmd python "path/to/my/file/script.py", I get an ModuleNotFoundError.
Before updating to Python 3.6.2 it was working fine. The only way I can use my Cython functions now is to use pyximport, which I like for debugging but not for ready-to-use functions...
Another problem since the upgrade is that I can't run my Cython setup.py script anymore. It finished without generating any file and the command line shows no response like Code generated (or whatever it was) when invoking setup.py.
Has there been any change in Python/Cython implementation concerning importing Cython files? Or perhaps is there perhaps any package that I forgot to update/install? I followed the complete Cython install routine after the update, but no change...
edit: oh and btw... __init__.py is added in the relevant path and all relevant paths are also permanently added to sys.path.
Thanks for help in advance!


text:
Q: How to go about finding how many years between 1 and 2000 were leap years? Question:
Assuming x represents the value of the year. If x is divisible by 4, then the year is determined as being leap. But, if x is divisible by 100, then, the year would be determined as not being leap, unless it would be divisible 400, which would then imply it being leap. How many years between 1 and 2000 would be leap?
Here is what I got:
Number of years divisible by 4 = $\frac{1996-4}{4}+1$ = 499
Number of years divisible by 100 = $\frac{1900-100}{100}+1$ = 19
Number of years divisible by 400 = $\frac{1600-400}{400}+1$ = 4
Number of years between 1 and 2000 would be leap = 499 - 19 + 4 = 484
Could anyone assist me into reformatting/ presenting my answers into a more mathematically proper presentation?

A: Prior to the Gregorian calendar, a leap year would occur once every four years. In this case we have
$$j(x)=\left\lfloor\frac{x}{4}\right\rfloor$$
Once the Gregorian calendar was adopted, which occurred in 1582, we have that every 400 years contains 97 leap years. Hence
$$g(x)=\left\lfloor\frac{97x}{400}\right\rfloor$$
In this case we also have to account for the 12 leap years that occurred prior to 1582. Kudos to egreg for pointing this out.
$$g(x)=\left\lfloor\frac{97x}{400}\right\rfloor+12$$
Since 4 AD was not a leap year, we must substract one from the end result in both scenarios
$$j(x)=\left\lfloor\frac{x}{4}\right\rfloor-1$$
$$g(x)=\left\lfloor\frac{97x}{400}\right\rfloor+11$$
Ultimately what you're looking for is this
$$f(x)=\left\{\begin{array}{ll}
0, & x\lt 4 \\
\left\lfloor\frac x4\right\rfloor-1, & 4\le x\lt 1582 \\
\left\lfloor\frac{97x}{400}\right\rfloor+11, & x\ge 1582
\end{array}\right.$$
Where $x$ is an integer that represents a given year in the common era. Since we seek the total number of leap years between 1 and 2000, we have
$$f(1999)=495$$
And we're done. I hope this helps you understand.

A: For a moment, let's gloss over the finer points of how leap years are determined, and find the number of multiple of $4$'s there are between $4$ and $1996$:
\begin{align}
1996-4 &= 1992 \\
1992 \div 4 &= 498 \, .
\end{align}
$498$ is not quite right because of what's called the Fence Post Problem. How many multiple of $4$'s are there between $4$ and $8?$ Not one but two! So there are actually $499$ multiple of $4$'s between $4$ and $1996$. Now let's try to think about the multiples of $100$ that are not multiples of $400$. There are $19$ multiples of $100$ in the range: $100,200,300,\ldots,1900$. Of those $19$, four of them are multiples of $400$. So there are $15$ exceptions that we have to deal with. We are left with
$$
499-15=484
$$
leap years.

This answer is technically incorrect because $4$ AD was not a leap year, as k170 has pointed out. So we are left with $483$ leap years (unless someone points out some other idiosyncrasy about the calendar system!).

A: Another way to get the answer summarizes as
$${2000\over4}-{2000\over100}+{2000\over400}-1$$
That is, start by including year 2000 and assume for the moment that every fourth year is a leap year. That gives the $2000/4$. Next assume you throw away the leap day from every century mark. That gives the $-2000/100$. Then remember that there is a leap year in every fourth century mark. That gives the $2000/400$. And finally, remember that you don't want to include the year 2000. That gives the $-1$.
Remark: As k170 points out, the Julian calendar omitted leap day in the year 4, so there's an argument for subtracting another $1$ from the answer. However, the Julian calendar otherwise included leap days every four years, not skipping century marks, so there is an argument for adding back another dozen to the answer, since the Gregorian calendar, whose main innovation was the skipping of leap day in three out of every four century marks, wasn't invented until the sixteenth century. The reason for saying "a dozen or so" instead of something more precise is that the exact answer is geopolitically dependent: Different countries adopted the Gregorian calendar in different centuries. (See egreg's comment below k170's answer, which I only just now noticed.)


text:
Q: Y axis text cutoff when make html to pdf using html2pdf library? I am using Html2pdf to export my webpage to pdf. My chart looks great on web, but upon exporting to pdf some highchart text cut off from the last pdf page. The charts on other pages are working perfect.
Screenshots of an original chart and its pdf display.

And my code is
document.getElementById("download-btn").addEventListener("click",function(){
        var downloadFile = document.querySelector(".downloadpage");
        console.log("downloadFile");
        console.log(downloadFile);
    console.log(window);
    var opt = {
            margin: 0.1,
            filename: 'Report.pdf',
            image: { type: 'jpeg', quality: 0.98 },
            html2canvas: { scale: 2 },
            jsPDF: { unit: 'in', format: [14.7, 16.5], orientation: 'landscape' },
        pagebreak: { mode: ['avoid-all', 'css', 'legacy'] }

        };
    html2pdf().from(downloadFile).set(opt).save();
    })
window.onload= function(){

}

What can I do to make this work?
There is any property from the library to fix it ?


text:
Q: ColdFusion: Invalid XML Control Char (hex) I'm trying to create an xml object using <cfxml>. I formatted all the data with XMLFormat().
In XML there are some invalid characters like '»'. I added this chars to the xml doctype as follow:
<!ENTITY raquo "»">

The HTML text is not very well formatted, but most of it works with my code. But in some texts there are some control chars. I'm getting the following error:
An invalid XML character (Unicode: 0x13) was found in the element content of the document.
I tried to add the unicode to the doctype and I tried this solution. Both didn't work...

A: Here's valid cfscript code which cleans up our XML, there are two methods, one which clears higher international characters, and one which clears only lower ASCII character which was breaking our XML, if you find more characters, just expand filter rules.
<cfscript>
    function cleanHighAscii(text){
        var buffer = createObject("java", "java.lang.StringBuffer").init();
        var pattern = createObject("java", "java.util.regex.Pattern").compile(javaCast( "string", "[^\x00-\x7F]" ));
        var matcher = pattern.Matcher(javaCast( "string", text));

        while(matcher.find()){
            var value = matcher.group();
            var asciiValue = asc(value);

            if ((asciiValue == 8220) OR (asciiValue == 8221))
                value = """";
            else if ((asciiValue == 8216) || (asciiValue == 8217))
                value = "'";
            else if (asciiValue == 8230)
                value = "...";
            else
                value = "&###asciiValue#;";

            matcher.AppendReplacement(buffer, javaCast( "string", value ));
        }

        matcher.AppendTail(buffer);
        return buffer.ToString();
    }

    function removeSubAscii(text){

        return rereplaceNoCase(text, "\x1A","&###26#;", "all");
    }

    function XMLSafe(text){
        text = cleanHighAscii(text);
        text = removeSubAscii(text);
        return text;
    }
</cfscript>

Other posisbilty is to user CF10 funciton encodeForXML():
https://learn.adobe.com/wiki/display/coldfusionen/EncodeForXML
Or use ESAPI which comes with CF10 directly or add ESAPI jars to your older CF from OWASP site https://www.owasp.org/index.php/ESAPI_Overview :
var esapi = createObject("java", "org.owasp.esapi.ESAPI");
var esapiEncoder = esapi.encoder();
return esapiEncoder.encodeForXML(text);

A: Try using » instead of ». For example, this CFML:
<cfxml variable="x"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE doc
[
    <!ENTITY raquo "»">
]>
<doc>
    Hello, » !
</doc>
</cfxml>

<cfdump var="#x#">

A: Pass your XML string through this method, and this will solve your problem.
It allows only valid characters to be sent in the input, if you want to replace invalids with some other character, you can modify the below method to do that
public String stripNonValidXMLCharacters(String in) {
    StringBuffer out = new StringBuffer(); // Used to hold the output.
    char current; // Used to reference the current character.

    if (in == null || ("".equals(in))) return ""; // vacancy test.
    for (int i = 0; i < in.length(); i++) {
        current = in.charAt(i);
        if ((current == 0x9) ||
            (current == 0xA) ||
            (current == 0xD) ||
            ((current >= 0x20) && (current <= 0xD7FF)) ||
            ((current >= 0xE000) && (current <= 0xFFFD)) ||
            ((current >= 0x10000) && (current <= 0x10FFFF)))
            out.append(current);
    }
    return out.toString();
}


text:
Q: Post load scripts for Postgresql database We successfully migrated data to an Azure Virtual Machine that contains a Postgresqldb with Azure Data Factory. We now need to run on this database some post-loading scripts, like creating views, create indexes and so on.
For a normal SQL-DB I would put the scripts into a Stored Procedure and trigger them in Azure Data Factory.
What is the best way to trigger these scripts for the PostgreSQL also from Azure Data Factory?

A: ADF stored proc acitivity does not support PostgresSQL , I think you should use Azure function as a workaround . You can always invoke the azure function from ADF .


text:
Q: MEF unable to oversrite DirectoryCatalog file. Access Denied I'm having issues with MEF where I have a DirectoryCatalog and in a later stage want to overwrite the assembly and "refresh" the catalog.
The problem i'm running into is that the file simply is "in use" and I can't overwrite the file. Normaly you are able to overwrite a .Net assembly.
I quess MEF has it in use, but how does this match with Recompilation?!
Here is my code example. Even with local variables the file is still in use.
I've also tried to have the assembly in both application and plugins folder but then the app folder version is used and therefor overwriting does not make a difference.
public RecompilationExample()
{
    DirectoryInfo dir = new DirectoryInfo(".\\plugin");

    if (!dir.Exists)
        dir.Create();

    DirectoryCatalog d;
    CompositionContainer c;

    d = new DirectoryCatalog(".\\plugin");
    d.Changed += new EventHandler<ComposablePartCatalogChangeEventArgs>(d_Changed);

    c = new CompositionContainer(d);
    c.ExportsChanged += new EventHandler<ExportsChangeEventArgs>(c_ExportsChanged);
    c.ComposeParts(this);
}

A:
Normaly you are able to overwrite a .Net assembly.

As far as I know, no. A loaded .NET assembly cannot be overwritten. You also can't unload a loaded assembly (except by unloading the entire AppDomain it is hosted in).
What you can do instead is to use shadow copying, i.e. copying the assembly and then loading the copy. You can enable this with the AppDomainSetup.ShadowCopyFiles property. This is typically used in ASP.NET and allows you to overwrite the original file, but not in a way that influences the running process - until you restart it.
See also this other answer I wrote in response to a similar question. Long story short: You can use DirectoryCatalog.Refresh to add new assemblies on the fly, but not to replace or remove them. When you need to replace assemblies, the best solution is to restart your process.


text:
Q: Ruby on Rails rake test:units error I have a problem about product_text.rb
I'm newbie in RoR, this example is from Agile Web Development from Sam Ruby and Dave Thomas.
my product_test.rb looks like this
#---
# Excerpted from "Agile Web Development with Rails",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
#---
#---
# Excerpted from "Agile Web Development with Rails, 4rd Ed.",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
#---
require 'test_helper'

class ProductTest < ActiveSupport::TestCase
  test "product attributes must not be empty" do
    product = Product.new
    assert product.invalid?
    assert product.errors[:title].any?
    assert product.errors[:description].any?
    assert product.errors[:price].any?
    assert product.errors[:image_url].any?
  end

  test "product price must be positive" do
    product = Product.new(:title       => "My Book Title",
                          :description => "yyy",
                          :image_url   => "zzz.jpg")
    product.price = -1
    assert product.invalid?
    assert_equal "must be greater than or equal to 0.01",
      product.errors[:price].join('; ')

    product.price = 0
    assert product.invalid?
    assert_equal "must be greater than or equal to 0.01",
      product.errors[:price].join('; ')

    product.price = 1
    assert product.valid?
  end

  def new_product(image_url)
    Product.new(:title       => "My Book Title",
                :description => "yyy",
                :price       => 1,
                :image_url   => image_url)
  end

  test "image url" do
    ok = %w{ fred.gif fred.jpg fred.png FRED.JPG FRED.Jpg
             http://a.b.c/x/y/z/fred.gif }
    bad = %w{ fred.doc fred.gif/more fred.gif.more }

    ok.each do |name|
      assert new_product(name).valid?, "#{name} shouldn't be invalid"
    end

    bad.each do |name|
      assert new_product(name).invalid?, "#{name} shouldn't be valid"
    end
  end

  test "product is not valid without a unique title" do
    product = Product.new(:title       => products(:ruby).title,
                          :description => "yyy",
                          :price       => 1,
                          :image_url   => "fred.gif")

    assert !product.save
    assert_equal "has already been taken", product.errors[:title].join('; ')
  end

  test "product is not valid without a unique title - i18n" do
    product = Product.new(:title       => products(:ruby).title,
                          :description => "yyy",
                          :price       => 1,
                          :image_url   => "fred.gif")

    assert !product.save
    assert_equal I18n.translate('activerecord.errors.messages.taken'),
                 product.errors[:title].join('; ')
  end

end

and the output from the console:
juldou-programming@juldou-programming-laptop:~/work/depot$ rake --trace  test:units
(in /home/juldou-programming/work/depot)
** Invoke test:units (first_time)
** Invoke test:prepare (first_time)
** Invoke db:test:prepare (first_time)
** Invoke db:abort_if_pending_migrations (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:abort_if_pending_migrations
** Execute db:test:prepare
** Invoke db:test:load (first_time)
** Invoke db:test:purge (first_time)
** Invoke environment
** Execute db:test:purge
** Execute db:test:load
** Invoke db:schema:load (first_time)
** Invoke environment
** Execute db:schema:load
** Execute test:prepare
** Execute test:units
Loaded suite /usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader
Started
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
..EE.
Finished in 0.075767 seconds.

  1) Error:
test_product_is_not_valid_without_a_unique_title(ProductTest):
StandardError: No fixture with name 'ruby' found for table 'products'
    /test/unit/product_test.rb:69:in `test_product_is_not_valid_without_a_unique_title'

  2) Error:
test_product_is_not_valid_without_a_unique_title_-_i18n(ProductTest):
StandardError: No fixture with name 'ruby' found for table 'products'
    /test/unit/product_test.rb:79:in `test_product_is_not_valid_without_a_unique_title_-_i18n'

5 tests, 19 assertions, 0 failures, 2 errors
rake aborted!
Command failed with status (1): [/usr/bin/ruby1.8 -I"lib:test" "/usr/lib/ru...]
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:995
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:1010:in `call'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:1010:in `sh'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:1094:in `sh'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:1029:in `ruby'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:1094:in `ruby'
/usr/lib/ruby/gems/1.8/gems/railties-3.0.7/lib/rails/test_unit/testing.rake:26
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:1112:in `verbose'
/usr/lib/ruby/gems/1.8/gems/railties-3.0.7/lib/rails/test_unit/testing.rake:11
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:636:in `call'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:636:in `execute'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:631:in `each'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:631:in `execute'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:597:in `invoke_with_call_chain'
/usr/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:590:in `invoke_with_call_chain'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:583:in `invoke'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2051:in `invoke_task'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2029:in `each'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2023:in `top_level'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2001:in `run'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:1998:in `run'
/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/bin/rake:31
/usr/bin/rake:19:in `load'
/usr/bin/rake:19

Thank you

A: I think you missed this in products.yml
ruby:
    title: Programming Ruby 1.9
    description:
        Ruby is the fastest growing and most exciting dynamic language out there.
        If you need to get working programs delivered fast, you should add Ruby to
        your toolbox.
    price: 49.50
    image_url: ruby.jpg


text:
Q: Why does my code create a .txt file, but doesn't write information in it? Pretty self explanatory title. Why is my program not writing text into the .txt file? Here's the code:
package juego;
import java.io.*;
/**
*
* @author Administrador
*/
public class Archivo
{
    public void crearArchivo()
    {
    try
    {
        FileWriter fw = new FileWriter("ReglasDelTablero.txt");
        PrintWriter pw = new PrintWriter(fw);

        pw.println("<7,0> , <0,0>");
        pw.println("<4,1> , <7,2> | <2,7> , <5,5> | <1,2> , <7,4> | <0,4> , <2,5>");
        pw.println("<7,7> , <3,6> | <6,4> , <3,5> | <4,0> , <2,1> | <2,4> , <0,3>");
    }
    catch(IOException e)
    {
        System.out.println("error");
    }
}
}

A: You have to close the writers so the changes show up in the text file. The finally block ensures that this happens even when an error occurs.
try {
    FileWriter fw = new FileWriter("ReglasDelTablero.txt");
    PrintWriter pw = new PrintWriter(fw);

    //...
} catch (IOException e) {
    //...
} finally {
    pw.close();
    fw.close();
}

Alternatively you could also use a try-with-resources statement, which will automatically close the writers:
try (FileWriter fw = new FileWriter("ReglasDelTablero.txt");
    PrintWriter pw = new PrintWriter(fw);)
{
    //...
} catch (IOException e) {
    //...
}

A: Try this
package juego;
import java.io.*;
/**
*
* @author Administrador
*/
public class Archivo
{
    public void crearArchivo()
    {
      PrintWriter pw = null;
    try
    {
        pw = new PrintWriter(new FileWriter("ReglasDelTablero.txt"));//onle line chain

        pw.println("<7,0> , <0,0>");
        pw.println("<4,1> , <7,2> | <2,7> , <5,5> | <1,2> , <7,4> | <0,4> , <2,5>");
        pw.println("<7,7> , <3,6> | <6,4> , <3,5> | <4,0> , <2,1> | <2,4> , <0,3>");
    }
    catch(IOException e)
    {
        System.out.println("error");
    }finally{

         if(pw!=null){
                try{ pw.close();...catch
         }

   }

try-catch rsources is fine for some cases but this is the old way and works better when you have more than 1 exception in a block


text:
Q: System.Net.Http reference properties path not showing NuGet packages path I have a solution with a number of projects.
I have changed system.Net.http to use the NuGet version, and most projects, when i select the "System.Net.Http" reference in the references node of solution explorer, it shows the path as "X:\myPath\packages\System.Net.Http.4.3.4\lib etc..."

However, i have a couple of projects when removing reference to System.Net.Http then going to NuGet Package Manager and installing it, when you click reference in the reference node, the path shows as "C:\Program Files etc.... Microsoft.NET.Build.Extensions\net461\"

I have opened the project file, and the "HintPath" is correct, however the path that shows in the reference Properties is incorrect.

When i look at Object Browser, it confirms this project is actually calling the framework version of System.Http.Net (so, even though i have installed NuGet version, and the HintPath is pointing to our packages folder, its still referencing the framework version)
Does anyone know why the path isnt matching and how I can fix this (so my project is using NuGet version instead of framework version to match the other projects in my solution?
Just incase it helps, here are all the references in the problem project:

A: I have a theory: it's a hack implemented in Visual Studio in order to workaround an issue with the package System.Net.Http.
There are issues with this package and it seems we should not use it anymore. The version of the System.Net.Http library included in the .NET Framework is better starting from 4.7.2 if I understand correctly.
See:

*

*https://github.com/dotnet/corefx/issues/11100

*https://github.com/dotnet/corefx/issues/17522#issuecomment-338418610

*https://github.com/dotnet/corefx/issues/29622
I'm currently moving projects to .NET Framework 4.8 and I'm removing all System.Net.Http packages.


text:
Q: Framework7 vue components not showing up when I run in an emulator. Only the default Cordova page showing I am using framework7 with vue.js and Cordova to build a mobile app, but whenever I try to run the app in an emulator all I get is the default Cordova page with the icon, and none of my components from framework7 appear. I have no idea why it's doing this. the emulator is running android 9. These are some of the files.
index.html (I havent made any changes)
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta http-equiv="Content-Security-Policy" content="default-src * 'self' 'unsafe-inline' 'unsafe-eval' data: gap: content:">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui, viewport-fit=cover">

  <meta name="theme-color" content="#007aff">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">
  <title>Easy Dine</title>

  <% if (process.env.TARGET === 'cordova') { %>

  <% } %>

app.vue (I havent made any changes)
<template>
<f7-app :params="f7params" >

  <f7-panel left cover theme-dark>
    <f7-view>
      <f7-page>
        <f7-navbar title="Left Panel"></f7-navbar>
        <f7-block>
          <f7-button fill raised login-screen-open="#my-login-screen">Login Screen</f7-button>
        </f7-block>
      </f7-page>
    </f7-view>
  </f7-panel>

  <f7-panel right reveal theme-dark>
    <f7-view>
      <f7-page>
        <f7-navbar title="Right Panel"></f7-navbar>
        <f7-block>Right panel content goes here</f7-block>
      </f7-page>
    </f7-view>
  </f7-panel>

  <f7-views tabs class="safe-areas">

    <f7-toolbar tabbar labels bottom>
      <f7-link tab-link="#view-home" tab-link-active icon-ios="f7:house_fill" icon-aurora="f7:house_fill" icon-md="material:home" text="Home"></f7-link>
      <f7-link tab-link="#view-catalog" icon-ios="f7:square_list_fill" icon-aurora="f7:square_list_fill" icon-md="material:view_list" text="Catalog"></f7-link>
      <f7-link tab-link="#view-settings" icon-ios="f7:gear" icon-aurora="f7:gear" icon-md="material:settings" text="Settings"></f7-link>
    </f7-toolbar>

    <f7-view id="view-home" main tab tab-active url="/"></f7-view>

    <f7-view id="view-catalog" name="catalog" tab url="/catalog/"></f7-view>

    <f7-view id="view-settings" name="settings" tab url="/settings/"></f7-view>

  </f7-views>

  <f7-popup id="my-popup">
    <f7-view>
      <f7-page>
        <f7-navbar title="Popup">
          <f7-nav-right>
            <f7-link popup-close>Close</f7-link>
          </f7-nav-right>
        </f7-navbar>
        <f7-block>

Popup content goes here.

        </f7-block>
      </f7-page>
    </f7-view>
  </f7-popup>

  <f7-login-screen id="my-login-screen">
    <f7-view>
      <f7-page login-screen>
        <f7-login-screen-title>Login</f7-login-screen-title>
        <f7-list form>
          <f7-list-input
            type="text"
            name="username"
            placeholder="Your username"
            :value="username"
            @input="username = $event.target.value"
          ></f7-list-input>
          <f7-list-input
            type="password"
            name="password"
            placeholder="Your password"
            :value="password"
            @input="password = $event.target.value"
          ></f7-list-input>
        </f7-list>
        <f7-list>
          <f7-list-button title="Sign In" login-screen-close @click="alertLoginData"></f7-list-button>
          <f7-block-footer>
            Some text about login information.
Click "Sign In" to close Login Screen
          </f7-block-footer>
        </f7-list>
      </f7-page>
    </f7-view>
  </f7-login-screen>
</f7-app>
</template>

catalog.vue (the only file i've changed)
<template>
  <f7-page name="catalog">
    <f7-navbar title="Catalog"></f7-navbar>
    <f7-block strong inset>
          <f7-button @click="scanCode" fill raised >Scan New Code</f7-button>
    </f7-block>
  </f7-page>
</template>

here's an image of what I get on the  emulator

here's an image of what is supposed to show

A: It worked after I ran the command
npm run build-prod-cordova-android


text:
Q: method sort not sorting last nested array JavaScript somehow arr[i].sort() not sorting last nested array and i getting bad result.
tryed FOR and WHILE, different operators, nothing helped. what im doing wrong?
it have return biggest numbers in array.

function largestOfFour(arr) {
  var i = 0;
  while (i != arr.length) {
    arr[i] = arr[i].sort().pop();
    i++;
  }
  return arr;
}

largestOfFour([
  [4, 5, 8, 1, 3],
  [13, 27, 18, 26],
  [32, 35, 37, 39],
  [1000, 1001, 817, 1]
]);

A: By default sort() orders the elements as strings, not numbers, and "1001" < "817". If you want a numeric sort you need to provide a comparison function that performs numeric ordering.

function largestOfFour(arr) {
  var i = 0;
  while (i != arr.length) {
    arr[i] = arr[i].sort(function(a, b) {
        return a - b;
    }).pop();
    i++;
  }
  return arr;
}

console.log(largestOfFour([
  [4, 5, 8, 1, 3],
  [13, 27, 18, 26],
  [32, 35, 37, 39],
  [1000, 1001, 817, 1]
]));

A: Not the cause of the problem you are seeing (which @Barmar answered), but you can use Array.map with Math.max.apply to get the max number of each list:

function largestOfFour(arr) {
   return arr.map(function(list) {
      return Math.max.apply(null, list);
   });
}

console.log(largestOfFour([
  [4, 5, 8, 1, 3],
  [13, 27, 18, 26],
  [32, 35, 37, 39],
  [1000, 1001, 817, 1]
]));

Or a bit more concise with ES6:
const largestOfFour = arr => arr.map(list => Math.max(...list))

A: The problem is in sort defaults - it sorts the array as strings - so "8..." > "1..."
Try following:
function cmp(a,b){
  return a-b;
}

function largestOfFour(arr) {
  var i = 0;
  while (i != arr.length) {
    arr[i] = arr[i].sort(cmp).pop();
    i++;
  }
  return arr;
}

largestOfFour([
  [4, 5, 8, 1, 3],
  [13, 27, 18, 26],
  [32, 35, 37, 39],
  [1000, 1001, 817, 1]
]);

Output:  [ 8, 27, 39, 1001 ]


text:
Q: SSD split into two drives I recently installed a 250GB SSD. I copied my Windows C drive over to my SSD F drive.
The computer now boots to the F drive SSD but my SSD seems to be split up as my F drive is showing it has 149gb storage and I have a new D drive with 77GB storage on it.
How do I combine the disks together?
See images below:


text:
Q: Quantifying coherence with density matrices I'm aware that the coherence of a statistical ensemble can be measured by looking at the off-diagonal elements of its density matrix, which is computed as the weighted sum of the density matrices of all the possible quantum states that it could be in. However, I recently thought about what would happen if we summed a statistical ensemble of density matrices, each with significant magnitudes of its off-diagonal terms, and the off-diagonal terms interfered destructively to produce zero coherence. Is this a problem with using ensemble density matrices to determine how coherent a system is? Or if there is destructive interference in the way mentioned above, does that really mean that the system is incoherent?
For example, say that a system has a $50 \%$ chance of being in the pure state $\frac1{\sqrt2}\left(|1\rangle+|2\rangle\right)$, with density matrix $\begin{pmatrix}\frac12&\frac12\\\frac12&\frac12\end{pmatrix}$, and a $50\%$ chance of being in the pure state $\frac1{\sqrt2}\left(|1\rangle-|2\rangle\right)$, with density matrix $\begin{pmatrix}\frac12&-\frac12\\-\frac12&\frac12\end{pmatrix}$. Both of these two options exhibit nonzero coherence, and yet the weighted sum of their density matrices is $\begin{pmatrix}\frac12&0\\0&\frac12\end{pmatrix}$, which implies zero coherence.

A: Are you familiar with von Neumann entropy? It is a standard way of capturing coherence. It is given by:
$$
S = -\text{Tr }(\rho\ln\rho)
$$
Intuitively, a pure state is maximally coherent and the normalised identity is maximally incoherent. This is captured by the entropy as it is minimal, $S=0$, on pure states and maximal on the normalised identity, $S=\ln d$ ($d$ the dimension of the Hilbert space).
More generally, $S$ is concave, so this translates how convex combinations of density states increase decoherence. In particular, a convex combination of pure state will typically have a positive entropy even if individually it is null. This captures the phenomenon you observed with off diagonal entries.
Hope this helps.

A: The non-diagonal elements for the density matrices that you write for $(|1\rangle\pm|2\rangle)/\sqrt{2}$ are simply the result of a basis transformation. If we worked in the same basis in which your last density matrix is written (i.e., $(|1\rangle\pm|2\rangle)/\sqrt{2}$), they would have forms
$$
\begin{pmatrix}1&0\\0&0\end{pmatrix}\text{ and }
\begin{pmatrix}0&0\\0&1\end{pmatrix}
$$
Both correspond to a pure state, and this does not change when we transform them to basis $|1\rangle,|2\rangle$.
When you assemble a system that has 50% probability to be in one of these states, you make an implicit assumption that the coherence is zero. Indeed, there are other possibilities - e.g., state $|1\rangle$ corresponds to 50% probability to be in either of $(|1\rangle\pm|2\rangle)/\sqrt{2}$, and so does state $|1\rangle$. However, if we assume that the density matrix is either in  $|+\rangle=(|1\rangle+|2\rangle)/\sqrt{2}$ or in $|-\rangle=(|1\rangle-|2\rangle)/\sqrt{2}$, then our density matrix is already specified as lacking coherence
$$
\rho=0.5|+\rangle\langle +|+0.5|-\rangle\langle -| = 0.5\begin{pmatrix}1&0\\0&1\end{pmatrix},
$$
and no basis transformation can cure that.
That the sum in different bases is the same is the result of the equal probabilities that you chose - this makes density matrix proportional to the identity matrix, which does not change under basis transformations.


text:
Q: iOS Notifications push server with php I have something wrong with my notifications but i can't see where is the problem. I have an app that generates the token successfully, at first I was able to send a notification from my localhost to the device, but after i restored the device and and tested with the new device token to push a simple notification i couldn't get get it to work even though I didn't made any changes to php code nor my app code, here is my php code :
        require_once 'ApnsPHP/Autoload.php';
        // Instantiate a new ApnsPHP_Push object
        $push = new ApnsPHP_Push(
            ApnsPHP_Abstract::ENVIRONMENT_SANDBOX,
            'server_certificates_bundle_sandbox.pem'
        );

        // Set the Root Certificate Autority to verify the Apple remote peer
        $push->setRootCertificationAuthority('entrust_root_certification_authority.pem');
        // Connect to the Apple Push Notification Service
        $push->connect();

        //  Instantiate a new Message with a single recipient
        $message = new ApnsPHP_Message($token);
        // Set a simple welcome text
        $message->setText("GELLLOOOOOO");
        // Play the default sound
        $message->setSound();
        // Add the message to the message queue
        $push->add($message);
        $push->send();
        $push->disconnect();
        // Examine the error message container
        $aErrorQueue = $push->getErrors();
        var_dump($aErrorQueue);

I think it have something to do with certificates but i'm not sure where is the issues since it was working before and there is nothing in $aErrorQueue , just an empty array.


text:
Q: Javascript Help me make this so it's DRY I would like to make this code DRY. I know I am repeating myself here and there must be a way to condense this code. The code is working and does what i want but I am trying to learn how to configure my code better. Can you please help?
http://codepen.io/anon/pen/GpMKLX

        <button id="btn_1"> Pick</button>

        <button id="btn_2"> Pick</button>

        <button id="btn_3"> Pick</button>

        <button id="btn_4"> Pick</button>

var btnOne = document.getElementById("btn_1");
var btnTwo = document.getElementById("btn_2");
var btnThree = document.getElementById("btn_3");
var btnFour = document.getElementById("btn_4");

var divOne = document.getElementById("divNum_1");
var divTwo = document.getElementById("divNum_2");
var divThree = document.getElementById("divNum_3");
var divFour = document.getElementById("divNum_4");

function randomNum() {
    var num = Math.random() * 10;
    num = Math.floor(num);
    return num;
}

btnOne.onclick = function () {
    divOne.innerHTML = randomNum();
}

btnTwo.onclick = function () {
    divTwo.innerHTML = randomNum();
}

btnThree.onclick = function () {
    divThree.innerHTML = randomNum();
}

btnFour.onclick = function () {
    divFour.innerHTML = randomNum();
}

A: function addOnclick(index)
{
    //Get the button
    var button = document.getElementById( "btn_" + index );

    //Add listener
    button.addEventListener(
        "click",
        function () {
            document.getElementById( "divNum_" + index ).innerHTML = randomNum();
        }
    );
}

//Now call it
for ( var i = 1; i < 5; i++ ) addOnclick( i );

Working JSFiddle

A: var buttons = document.querySelectorAll("div button");
var divs    = document.querySelectorAll("div.num_wrapper > div");

if( buttons.length != divs.length ) throw "different number of buttons vs divs";

for(var i=0; i<buttons.length;i++) {
    buttons[i].onclick = function() {
        divs[i].textContent = Math.floor( Math.random() * 10 );
    }
}

*

*Repeated calls to getElementbyId replaced with querySelectorAll

*textContent used instead of the semi-standard innerHTML, it's also XSS-safe

*Elimination of randomNum

A: Without resorting to requiring unique IDs with matching number suffixes, this can be done with classes attached to the parts.  It can be done without classes also, using relative elements, but the classes make it clearer in my example.
I'll use your same CSS and basically the same structure as you, but with classes in place of the IDs being used.
The page structure is as described in my earlier comment:

"a div of class 'num_wrapper' which encloses exactly one div of class 'num_content' and a sibling button of class 'num_pick'"

This gets all of the _num_pick_ buttons, then loops through them and attaches a click event handler to each.
The handler function uses this for the button that was clicked, gets the parent, then finds the num_content div within (querySelector can be used on any Node, not just document.querySelector!) and sets its textContent.

var buttons = document.querySelectorAll("button.num_pick");
for (var i=0; i<buttons.length; i++) {
    buttons[i].addEventListener("click", function(e) {
        var cont = this.parentElement.querySelector("div.num_content")
        cont.textContent = Math.floor( Math.random() * 10 );
    });
}
.wrapper {
 width:448px;
 margin:0 auto;
}
.num_wrapper {
 margin:0 5px;
 width:100px;
 height:100px;
 float:left;
 border:1px solid #333;
 background-color:#ccc;
 position:relative;
 font-family:Arial;
 font-size:60px;
 text-align:center;
}
button {
 width:100%;
 position:absolute;
 top:72px;
 left:0;
 font-size:20px;
 text-align:center;
}

        <button class="num_pick"> Pick </button>

        <button class="num_pick"> Pick </button>

        <button class="num_pick"> Pick </button>

        <button class="num_pick"> Pick </button>

This works for as many repeated num_wrapper divs as you want, without having to change/update numbers in each id.


text:
Q: iMacros/Javascript - How to expose text area of recaptcha V2 when in iframe? I have a situation where I need to use 2Captcha to solve recaptcha for the site , but the recaptcha is unusually in its own frame. My normal .js I use in imacros for firefox fails to expose the "text area" to paste the token result into.
How can this be overcome ?Presumably I just need to reference the frame but I am unsure how to do this as I am just starting with javascript and use a script that I paid a coder for . I have asked him but I dont think he is sure , or too busy perhaps !
The code below normally works to expose the text area to input the recaptcha token..
macro += "URL GOTO=javascript:((function(){var<SP>k=document.querySelector('[src^=\"https://www.google.com/recaptcha/api2/anchor?\"]').src.split('k=')[1].split('&')[0];document.getElementById('g-recaptcha-response').style.display='';document.getElementById('g-recaptcha-response').textContent=k;}))();" + "\n";

Any help would be greatly appreciated as this is has been a problem for a long time


text:
Q: The OLE DB provider "SQLNCLI" for linked server X reported a change in schema version between compile time X and run time X for table [tablename] The below error starts happening once a week at the same time every week.
The OLE DB provider "SQLNCLI" for linked server X reported a change in schema version between compile time X and run time X for table [tablename].
[SqlException (0x80131904): The OLE DB provider "SQLNCLI" for linked server "ABCDEF" reported a change in schema version between compile time ("175385004624084") and run time ("175393583420554") for table ""ABCDEF"."dbo"."TheViewOnLinkedServer"".]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1950890
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4846875
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392
   System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +33
   System.Data.SqlClient.SqlDataReader.get_MetaData() +83
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +297
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +954
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +162
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
   System.Data.SqlClient.SqlCommand.ExecuteReader() +89
   XXXX.XXXX.Data.SqlHelper.ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, String commandText, SqlParameter[] commandParameters, SqlConnectionOwnership connectionOwnership) in E:\WorkingFolderVSSNET\Lesa\Databases\Lesa.Net.Data\Lesa.Net.Data\SQLHelper.cs:671
   XXXX.XXXX.Data.SqlHelper.ExecuteReader(SqlConnection connection, CommandType commandType, String commandText, SqlParameter[] commandParameters) in E:\WorkingFolderVSSNET\Lesa\Databases\Lesa.Net.Data\Lesa.Net.Data\SQLHelper.cs:803
   XXXX.XXXX.XXXXX.XXXX.GetAttTypes(String ID, String App) +279

[ApplicationException: Error in GetAttTypes]
   XXXX.XXXX.XXXX.XXXX.XXXXXXX(String ID, String App) +507
   XXXX.XXXX.XXXX.XXXXX.XXXXX.Load(Int32 XXXX) +14717

[Exception: Error in XXXXXX.Load( XXXXX=XXXXXX) at XXXXX- for.]
   XXXX.XXX.XXX.XXXXXX.XXXXXX..ctor(String XXXXX, String XXXXX) +312
   XXXXXXX.XXXXXXXX.Page_Load(Object sender, EventArgs e) +2481
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
   System.Web.UI.Control.OnLoad(EventArgs e) +99
   System.Web.UI.Control.LoadRecursive() +50
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627

To fix the problem I just run the alter statement for the view without any changes.
The view selects from another view on a linked server and does list the column names (doesn't select by *).
I am not able to duplicate the problem after it has been fixed yet because I can't figure out what could be causing it. I have tried rebuilding indexes to see if that is causing it but it doesn't seem to.
Any ideas on how to troubleshoot this or what the cause could be?

A: Are you using a synonym? The few cases I have seen people complaining of this, this fix worked - http://support.microsoft.com/kb/2498818 - What version/build are you on?

A: We have linked server connections from one SQL server to another and on multiple servers.  Get this error msg everyday and been researching for the past two yrs with no definitive answer. Even placed (paid) support call to Microsoft with no resolution due to they couldn't absolutely pinpoint during testing.
Since we setup our data pulls to utilize SQL Sever Agent, we set to retry a few time if a failure occurs.
I think the problem lies within the db engine and those at Microsoft SQL product group programming the product would be the only ones who could come up with a valid reason.
FYI, our company uses several SQL instances on several servers with versions 2005 and 2008.
Good luck
There is also another post relating to the issue and response from Microsoft.  Seems like it could be related to rebuilding indexes and stats.  You may want to try running before these occur:

Posted by Microsoft on 6/8/2010 at 8:54 PM
We fixed the bug related to the schema version error when using
  synonyms in a local view to reference a remote table. The fix will be
  in the first CTP (CTP0) of the coming release (SQL Server 11 Codename
  Denali). We are currently also considering backporting it to earlier
  versions but the decision has not been made yet.
Thanks for your patience.
Regards,
Joachim Hammer Program Manager SQL Server


text:
Q: Why is my toast working with so many different contexts? I'm working in my activity4.java and the code is:
public class Activity4 extends Activity {
Spinner spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_4);
    spinner=findViewById(R.id.spinner);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            if(Activity4.this==adapterView.getContext())
            Toast.makeText(adapterView.getContext(),adapterView.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
}
}

I used adapterView.getContext() as context in the above code. But even if I replace it with getApplicationContext() like
Toast.makeText(getApplicationContext(),adapterView.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
or if I write getBaseContext() like this,
Toast.makeText(getBaseContext(),adapterView.getSelectedItem().toString(),Toast.LENGTH_LONG).show();

The toast seems to work just fine. Why is it so?

A: This is the implementation of the makeText() method in Toast.java:
/**
 * Make a standard toast that just contains a text view.
 *
 * @param context  The context to use.  Usually your {@link android.app.Application}
 *                 or {@link android.app.Activity} object.
 * @param text     The text to show.  Can be formatted text.
 * @param duration How long to display the message.  Either {@link #LENGTH_SHORT} or
 *                 {@link #LENGTH_LONG}
 *
 */
public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
    return makeText(context, null, text, duration);
}

As you can see in the comments for @param context explains that it usually is the application's context or the activity's context.
But the documentation:

This method takes three parameters: the application Context, the text
  message, and the duration for the toast

states that the context must be the application Context.
Well it seems that Toast just needs a context.
If possible we must use application Context to avoid unexpected results.
Although I haven't seen any yet.


text:
Q: bash variables and regex comparison Let x='abc.xyz' and y='abc:xyz' so that the following holds true (prints "matches" and "diff"):
[[ "${x}" =~ abc".xyz" ]] && echo "matches"
[[ "${y}" =~ abc".xyz" ]] || echo "diff"

Now, literal l=".xyz" can be extracted and tests still work (note double quotes around l refs):
[[ "${x}" =~ abc"${l}" ]] && echo "matches"
[[ "${y}" =~ abc"${l}" ]] || echo "diff"

And the problem: if we try further r="abc\"${l}\"" or r="abc${l}", the first test never prints "matches":
[[ "${x}" =~ ${r} ]] && echo "matches"
[[ "${y}" =~ ${r} ]] || echo "diff"

What should be the proper form of r to pass both tests?

A: The shell removes normally all unquoted " from the command line (they control
only if arguments should be splitted or not), but there
is special handling after =~. The quotes work here like escapes,
everything between the quotes are handled as raw characters matching only
itself (beside the variable substitution with $ that still work).
There is only one evaluation of the pattern, therefore quotes
hidden in variables are considered as regular quotes, and do
not trigger the special quote syntax.
You need to escape the . (or any other active) character in $l
and the quote syntax does not work in variables.
If $l is always equal to .xyz, you can use r="abc\\${l}" to get the correct match.
It is equal to r='abc\.xyz'.


text:
Q: Document stuck in printing queue My sister still has Win XP. She tried to print a document on her USB printer and now it's stuck in the printing queue. I tried the following:

*

*Restart the computer

*Restart the printer

*Delete the entry from the printing queue

*From the printing queue choose Printer\Cancel All Documents

*Right click the print job and choose Pause

The status of the printing job now reads "Deleting - Paused - Printing".
Nothing I do seems to get rid of this stuck printing job.
What should I do?

A: The usual answer for this is to go into the Windows services tab and stop then restart the printer spooler.

A: The advice on this site saved me more than once:

Pull up your Run box (Windows Key+R)
  type in cmd and hit Enter. This will
  bring you to the MS DOS prompt. There
  type in the following:
net stop spooler
You should get a message saying the
  spooler stopped successfully. Now we
  need to clean out the spool folder.
  This is where windows keeps jobs that
  haven't been printed yet.
Call up your Run box again (Windows
  Key+R) and type in the following:
%SYSTEMROOT%\system32\spool\PRINTERS
This should open a new explorer
  window. You are likely to see bunch of
  files in there – some of which may be
  classified as "Shockwave Objects" by
  windows. They are actually not
  Shockwave files but whatever. We don't
  care because we will be deleting them.
  Just remove everything you can see
  that folder and then close the window.
  If you can't delete some of the files,
  it means that you didn't stop the
  spooler properly. Go back and try it
  again.
This deletes all the jobs on the
  queue, so you might need to re-send
  some of the documents that got stuck
  there waiting. Once the folder is
  empty go back to your DOS prompt and
  type in:
net start spooler
Your printer queue should be clean
  now. If it's not, you probably did
  something wrong.

A: Although the answers here seem valid, I solved the problem even before I read them.
My solution\workaround was after marking the printing job to delete, I disconnected the printer from the electricity, restarted the computer and then reconnected the printer to the electricity.
I guess that when the computer restarted without the printer it was able to remove the printing job from the queue.


text:
Q: how to plot after combining rows dplyr I'm using the babynames dataset by Hadley Wickham. I'm trying to plot a graph showing the top popular boys name in 1950 using dplyr. So far I can show to the top names by:
malebabynames1950<-filter(babynames, year==1950, gender=="M")
totalboys1950<-malebabynames1950 %>% group_by(name, gender, year) %>% summarise(count=sum(count))
head(arrange(totalboys1950, desc(count)))

which shows:
    name gender  year count
    <chr>  <chr> <int> <int>
1   James      M  1950 86266
2  Robert      M  1950 83590
3    John      M  1950 79447
4 Michael      M  1950 65185
5   David      M  1950 60761
6 William      M  1950 60722

but I cannot figure out how to plot names vs count. Any ideas? Thanks!

A: Use ggplot with geom_bar. By default, geom_bar uses stat="count" so you don't have to group and summarize before plotting. If you want to use your grouped dataframe for plotting, use geom_bar(stat="identity")


text:
Q: Multiple Processes of "Java Web Start Launcher" showing up in the Task Manager when uninstalling Java A few days ago, I planned to uninstall Java because I don't need it anymore. I use an uninstaller named 'Revo Uninstaller' to do a thorough uninstallation of older versions of Java.
I was able to uninstall Java 7 Update 67 using Revo Uninstaller. Revo Uninstaller wasn't able to uninstall Java 8 Update 30-something and I don't know why. It was showing some error about "Windows Installer" so I just used the Control Panel's uninstallation tool. The Control Panel was able to uninstall it but after that, a number of processes named "Java Web Start Launcher" suddenly appeared on the Task Manager. There were many! I decided to shut down the computer because I needed to sleep.
The next day, I woke up and tried to uninstall another old version named "Java 8 Update 40" by using Revo Uninstaller. The uninstallation took a while then I noticed that my PC started running slow. So I went to the Task Manager and I saw that "Java Web Start Launcher" appearing again and again. It kept on creating a lot of them. Every time I scroll down, I see more and more processes of it. So I went to a task manager alternative named "Process Explorer" and tried to kill the Process Tree. It didn't work. It just kept on creating more. They took a lot of my CPU usage. My computer went slow so I held down the power button of my laptop to shut down my PC.
I'd like to know why this is happening. I don't want to uninstall Java 8 Update 40 and the last one named Java 8 Update 45 in the fear of this might happen again.
Could this be fixed? Is there a way to uninstall these Java versions without having another problem like this? Could I uninstall them manually? Like deleting some files in the Program Files folder in the C: drive or maybe removing some registry entries?
Thanks, I hope for an immediate answer.
I'm running Windows 8.1.

A: Recently I experienced it similarly. I changed (not upgraded yet?) Windows7 to Windows10 and installed many Java related packages (like eclipse, Java SE runtime 32/64 etc.) Suddenly, the blue circle next to the cursor kept on spinning while I was not doing anything. So many Java(TM) Web Start Launcher processes running according to Task Manager. Even though they took 0~1% CPU time each, and they caused CPU and memory usage to reach 100%.
If this is your case, the following may help you, as it did me;
(Please bear with me that the following steps are based on Windows 10.)

*

*Windows Key + R

*Type msconfig and run it.

*Go to the Service tab

*Check Hide all Microsoft Services

*Click Disable all

*Go to the Startup tab

*Disable all items

*Optionally, in an administrative command prompt, run the following;

Dism /online /cleanup-image /restorehealth

*Reboot

After this work, my computer has been running fine for last two days. Then I went back to the msconfig and I turned on the services I really need such as OneDrive and Dropbox stuff. (a debtor)<><

A: I had the same problem about three weeks ago and tried multiple solutions I found on the web. The solution that worked was:

*

*Delete my Java folder (right-click on the folder and select Delete).    Then, all four versions of Java and the folder were (and still are) gone.

*Run RKill and then MalwareBytes... no problems detected.

*Run CCleaner and it removed some Java registry entries.

*Shut down my laptop and then restart it.

*Run CCleaner again (out of curiosity) and it deleted more Java registry entries.

*Ran AVG scan... no problems detected.

Result: My laptop immediately ran normal speed and still does.
Thoughts:  I suspect the problem was caused by an unsuccessful installation of Java.  I had three versions of Java listed on my install/uninstall program listing and four in my Java folder.  The latest version was in the folder but not in the program listing.  I have not reinstalled Java yet, but my local computer repair technician thinks that should be alright to do.
More details on the original problem: Hundreds of copies of Web Start Launcher would launch after I would get on the web (per Task Manager), and that brought my laptop to a crawl.  When I tried to uninstall Java, Java attempted to install and locked up the laptop with hundreds of copies of Java Web Start Launcher.

A: Using the Java Uninstaller is the recommended way to remove the problematic version.
As far as killing the multiple processes created by said defunct version of Java, while you may encounter windows error messages, if you continue to attempt to kill the process several times, it may eventually shut down the out of control processes.
The other thing you can do is to disable the "Java SE Auto Updater" item, located under the Startup Tab in System Configuration. If you see it there and it is checked, then uncheck it and before you close the 'System Configuration' window, click on the "Services" tab and scroll through the list to look for any "Java" items. If you find any, uncheck them too & click the "Apply" button, which will apply both actions. Click OK, and close the System Configuration window, after which you will be prompted to restart your computer. You should save any work you have open and then click OK to restart your computer.
If you're having trouble performing the above tasks for any reason, including that your computer is running slow because of the out of control process, reboot your computer into Safe Mode and then try the above steps to disable the rogue Java Startup entry.
If you absolutely need Java for some reason, the best thing to do after uninstalling the bad version, is to install the previously working version that did not cause this error and to set its security levels to maximum. But do not let it start with windows nor have it set to automatically update. The best advice here is to use it only as "On-Demand." Also, if you're browsers flag any Java plug-ins as "unsafe"-------you should listen to that warning and do not enable that unsafe plug-in.
If on the other hand, you're absolutely sure that you do not need Java and would like it and it's remnants gone from your system, you should definitely use the Java uninstaller.
As for further cleaning methods (i.e. scanning the registry to remove whats left of Java), this can be done-------but you must be careful!
Unless you actually know what you are doing, editing the registry without proper knowledge could be disastrous and could cause all types of system stability issues, including an un-bootable computer. This includes using the "Registry" cleaning function of CCleaner!
As a general rule of thumb, especially if you're just an average user with little to no knowledge of Windows Internals, it is highly recommended that you leave such editing to trained professionals only!
If you knew how to build an automobile engine, you probably wouldn't need to take your car to a mechanic, should you encounter any issues with it, but for those of us whom don't know the first thing about auto-mechanics, we usually concede to the fact that we're going to have to take the car into the shop for it's needed repairs, whether we like it or not. Well, the same thing can be said for computers.
Eating humble pie once in a while is a good thing for the soul and it might actually save you from future heartache as well. Take the advice of professionals and don't try this at home unless you are one!

A: I had this issue, saying that I am unsure of the causation of the actual problem.. I came here to try and identify what went on, but have had no such luck.
Anyways, I fixed the machine via the following:
1) Boot in to safe mode: This prevents the wild and wacky processes from launching and prevents system slow down.
2) Recommendation: It may be worth carrying out a health check on the machine. So running a scan of MalwareBytes (google it) and HitmanPro (google it) to identify any malware and rootkits is recommended.
2) Uninstall all versions of Java in control panel where visible
3) Download CCleaner
4) Uninstall all versions of Java in CCLeaner where visible
5) Delete the Java folder in program files
6) Using CCleaner click the registry tab and "Scan for Issues". When I did this, I found numerous corruptions and unused extensions (naturally as we have just removed java from the machine).
Oh Of course, feel free to reinstall Java after the end of this process :).

A: I gathered from the previous two answers that the gist of the remedy was to remove Java and its registry entries. Using the Control Panel I was unable to uninstall Java so followed the instructions to remove the Java directory and run CCLeaner. That seems to have solved the problem. I did notice however, that when re-installing Java it told me it would remove an older version of Java. I suspect that the older version is the cause. Running fine now - Thanks.


text:
Q: Fetch events from EKEventStore and show in tableView in Swift iOS8 I'm trying to create a small application that will fetch all events and will show them in a tableView.
My specific questions are:

*

*Is my fetchEvents() method is implemented correctly?

*Where should I call the fetchEvent() method in order to show the list when the app opens (is it in viewDidLoad?) and to refresh it after the addition/edit of a new event?

Thanks!
This is my code for the MasterViewController.swift file:
import UIKit
import EventKitUI

class MasterViewController: UITableViewController , EKEventEditViewDelegate{

var objects = NSMutableArray()
let eventStore =  EKEventStore()

override func awakeFromNib() {
    super.awakeFromNib()
}

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.
    self.navigationItem.leftBarButtonItem = self.editButtonItem()

    let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
    self.navigationItem.rightBarButtonItem = addButton

    //self.fetchEvents()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func insertNewObject(sender: AnyObject) {

    let controller = EKEventEditViewController()

    eventStore.requestAccessToEntityType(EKEntityType(), completion: {granted, error in })
    controller.eventStore = eventStore

    controller.editViewDelegate = self
    self.presentModalViewController(controller, animated: true)

    let indexPath = NSIndexPath(forRow: 0, inSection: 0)
    self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}

func eventEditViewController(controller: EKEventEditViewController!, didCompleteWithAction action: EKEventEditViewAction) {
    self.dismissModalViewControllerAnimated(true)
}

func fetchEvents() -> NSMutableArray {

    eventStore.requestAccessToEntityType(EKEntityType(), completion: {granted, error in })

    let endDate = NSDate(timeIntervalSinceNow: 604800*10);   //This is 10 weeks in seconds
    let predicate = self.eventStore.predicateForEventsWithStartDate(NSDate(), endDate: NSDate(), calendars: nil)

    var events = NSMutableArray(array: self.eventStore.eventsMatchingPredicate(predicate))

    return events

    /*
    var indexes = NSMutableIndexSet(index: 5)

    indexes.addIndex(4)

    objects.insertObjects(events, atIndexes: indexes) */

    // Create the start date components

   /* NSDateComponents *oneDayAgoComponents = [[NSDateComponents alloc] init];
    oneDayAgoComponents.day = -1;

    let oneDayAgo = currentCalendar.date dateByAddingComponents:oneDayAgoComponents*/

}

// #pragma mark - Segues

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showDetail" {
        let indexPath = self.tableView.indexPathForSelectedRow()
        let object = objects[indexPath.row] as NSDate
        (segue.destinationViewController as DetailViewController).detailItem = object
    }
}

// #pragma mark - Table View

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return objects.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    let object = objects[indexPath.row] as NSDate
    cell.textLabel.text = object.description
    return cell
}

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return false if you do not want the specified item to be editable.
    return true
}

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        objects.removeObjectAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}
}

A: First off, You should be doing the rest of the work in your fetchEvents function inside the callback for eventStore.requestAccessToEntityType:
func fetchEvents() -> NSMutableArray {
    eventStore.requestAccessToEntityType(EKEntityType()) completion: {
        granted, error in
        ... the rest of the code ...
    })
}

of course now that it's async, you'll need to return the data in a callback instead of returning it:
func fetchEvents(completed: (NSMutableArray) -> ()) {
    eventStore.requestAccessToEntityType(EKEntityType()) completion: {
        granted, error in
        let endDate = NSDate(timeIntervalSinceNow: 604800*10);   //This is 10 weeks in seconds
        let predicate = self.eventStore.predicateForEventsWithStartDate(NSDate(), endDate: NSDate(), calendars: nil)
        let events = NSMutableArray(array: self.eventStore.eventsMatchingPredicate(predicate))
        completed(events)
    })
}

But now you have another problem... you're using self in the closure, thereby capturing a reference, which can lead to a "reference cycle". In this particular case, I'm pretty sure that won't happen because requestAccessToEntityType() won't keep a reference to your closure (I'm pretty sure), but it's a good idea to use [weak self] whenever you you use self inside a callback function:
once you've done that, self is an optional though, so you need to make sure it's not nil…
func fetchEvents(completed: (NSMutableArray) -> ()) {
    eventStore.requestAccessToEntityType(EKEntityType()) completion: { [weak self]
        granted, error in
        if let strongSelf = self {
            let endDate = NSDate(timeIntervalSinceNow: 604800*10);   //This is 10 weeks in seconds
            let predicate = strongSelf.eventStore.predicateForEventsWithStartDate(NSDate(), endDate: NSDate(), calendars: nil)
            let events = NSMutableArray(array: strongSelf.eventStore.eventsMatchingPredicate(predicate))
            completed(events)
        }
    })
}

but looking a little closer, we never use self just self.eventStore, so we can capture a weak reference to that directly instead:
func fetchEvents(completed: (NSMutableArray) -> ()) {
    eventStore.requestAccessToEntityType(EKEntityType()) completion: { [weak weakEventStore = self.eventStore]
        granted, error in
        if let eventStore = weakEventStore {
            let endDate = NSDate(timeIntervalSinceNow: 604800*10);   //This is 10 weeks in seconds
            let predicate = eventStore.predicateForEventsWithStartDate(NSDate(), endDate: NSDate(), calendars: nil)
            let events = NSMutableArray(array: eventStore.eventsMatchingPredicate(predicate))
            completed(events)
        }
    })
}

finally, you really ought to check for errors instead of ignoring them, (granted could be false, meaning the user didn't give you access, or there could have been an error (so you need to check if error is nil (if error { /* handle failure */ })
PS - I have working code which uses event kit on github which you may find useful.


text:
Q: ionic2:,how can I scroll to the last element with code in .ts file? following code is html segment:
<ion-scroll scrollX="true" style="height: 4rem;overflow: scroll; white-space: nowrap;" no-padding *ngIf="treeId" class="bg-style">
        <div *ngFor="let p of progressArray; let i = index;" class="tree-progress">
            <button ion-button clear [color]="getTextColor(i)" class="tree-progress-item">
                {{ p }}
            </button>
            <ion-icon class="tree-progress-arrow" name="ios-arrow-forward-outline" color="arrowColor" *ngIf="checkLast(i)"></ion-icon>
        </div>
</ion-scroll>

well,  scroll horizontal, I want to control Scroll scroll to the last position(last element) when array progressArray added automatically. But I can't find any method the api provided.
Then I used a javascript library https://github.com/flesler/jquery.scrollTo in my project.
First I download this library with npm
npm install jquery.scrollto --save

Then I import 'jquery.scrollto'
Then I did like this:
ionViewDidLoad() {
    var mainScroll = document.getElementsByClassName('scroll-content')[0];
    var last = mainScroll.firstElementChild.lastElementChild;
    $('.scroll-zoom-wrapper').scrollTo(last, 200);
}

it does't work.Please help me solve this problem, or have examples ready so I can refer to.
Thanks all!

A: I solved this problem like this:
ionViewDidLoad() {
    var mainScroll = document.getElementsByClassName('tree-progress-item');
    var length = mainScroll.length;
    console.log('mainScroll-->' + mainScroll + " length-->" + length);
    if (length > 0) {
        var last = mainScroll[length - 1];
        last.scrollIntoView(true);
    }
}


text:
Q: Get all include folders from cmake executable How can I get all include directories of my executable?
I want to introduce cppcheck and I need to forward all include directories to cppcheck (also the include directories of the interface imported libraries).
So for example I have
add_executable(my_exe main.cpp)
target_link_libraries(my_exe PRIVATE RapidJSON::RapidJSON)

How can I get all corresponding include directories of my_exe, including the RapidJSON ones (e.g. ~/.conan/data/RapidJSON/1.1.0/a/b/package/x/include)?
I tried following without success :-(
get_target_property(ALL_INCLUDES my_exe INTERFACE_INCLUDE_DIRECTORIES) # NOTFOUND
get_target_property(ALL_INCLUDES my_exe INCLUDE_DIRECTORIES) # empty

add_executable(my_exe main.cpp)
target_link_libraries(my_exe PRIVATE RapidJSON::RapidJSON)

# the following line should be adapted so that the variable cppcheck_includes also contains the RapidJSON include directories

set(cppcheck_includes           ${CMAKE_SOURCE_DIR}/includes)

add_custom_target(cppcheck
        COMMAND cppcheck
        --enable=all
        --std=c++11
        --library=/usr/share/cppcheck/cfg/std.cfg
        --check-config
        ${cppcheck_includes}
        main.cpp
)

I expect that there is no warning, but there is a warning:
Include file: <rapidjson/document.h> not found.

A: In my case I just created a target which runs Cppcheck and uses the compilation database of my project as input - see https://github.com/firewave/mame_regtest/blob/master/cppcheck.cmake.
To generate the compilation database you simply need to add
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

to your CMakeLists.txt.
You could also use the integrated support in CMake but I have no experience with that yet.

A: Recent versions of CMake support easy integration of cppcheck. Starting with CMake v3.10 cppcheck can be invoked as CMake target by setting the CMAKE_<LANG>_CPPCHECK variable.
Minimal example CMakeLists.txt that should work on Linux when cppcheck is installed:
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
project(StaticChecker)

# find installed cppcheck executable on system
find_program(CMAKE_CXX_CPPCHECK NAMES cppcheck)
if(CMAKE_CXX_CPPCHECK)
    list(APPEND CMAKE_CXX_CPPCHECK "--enable=all")
    list(APPEND CMAKE_CXX_CPPCHECK "--std=c++11")
endif()

add_library(some_library lib.cpp)

The static analyzer is automatically invoked within the default cmake build target.


text:
Q: How to exit after certain days from `strategy.entry` I can't seem to figure out the syntax for exit a trade from a certain time interval from the trade entry. Any help would be greatly appreciated.
if (crossover(delta, 0))
    strategy.entry("Long", strategy.long, comment="Long")
    strategy.exit("Exit", "Long", when = 15)

The code above I want to exit the long position after 15 days. But it doesn't seem to work.

A: I figured it out one solution. I created another if statement but offset by 15 days to trigger. I also set the crossover to a variable. See code:
buy = (crossover(delta, 0))

if (buy)
    strategy.entry("Long", strategy.long, comment="Long")
if (buy[15])
    strategy.close("Long")

A: Try barssince
// Example - Buy when the price closes below 22

myEntry = close  < 22

strategy.entry(id= "sample", long = strategy.long, when= myEntry)

// Close 10 bar periods after the condition that triggered the entry

strategy.close(id = "sample", when = barssince(myEntry) >= 10)


text:
Q: What sort of RAM do I need for a Toshiba Satellite 310CDS? I was thinking of upgrading my legacy notebook with some RAM.
This is a Toshiba Satellite 310CDS, and I'd like to put the maximum possible RAM module into it, to max-out the ram in that machine.
I do this only for hobbyist purposes, as this laptop is almost twelve years old, I don't do reasonable work on it any more. But since it's otherwise in perfect working order, I was thinking of maxing out the RAM, to run NetBSD more easily on it (surely not faster, though, since this laptop has only a 199MHz CPU)
OK, here comes the question:
What RAM module do I need (part number, etc) to max-out the RAM in that laptop?
I bought an SODIMM module one, and it fitted into the slot, but it wasn't recognized by the hardware.

A: Sure go for it, revive the thing and put it to good use, I had an old IBM Thinkpad lying around, maxed out it's RAM and it's sitting here with me with Ubuntu working perfect :)

A: You might not find it overly easy to find RAM cheaply that is compatible with a laptop as old as that. IIRC those machines take EDO SODIMMS and have 32Mb built-in and you have one slot that you can add up to 128Mb in taking it up to 160Mb. If you can find compatible RAM at a reasonable price such a machine should boot lubuntu or puppy linux well enough and run fine for simple tasks (I'd not want to browse modern web sites in a modern browser on something like that, or try run OO.o on it, but for email, text/code editing, or just as a dumb terminal via VNC or similar the machine could be useful.

A: I did the same thing with my Toshiba Satellite 1900-603 but had trouble locating the second memory slot so I posted a question and later found the answer. Perhaps my experience may help you. Good luck with it.


text:
Q: How to implement a custom oracle sequence? The oracle sequence is designed to return auto-increasing numbers. I am wondering that can I implement a customized sequence that returns from values pool I putted in, so I can tell the sequence what are expected to return.
Anyway to implement this? or alternative, like adding trigger, or oracle functions or anything else?
Or even to use a table the save values, but how to do is best performance, like oralce  sequence
I have this, but not sure is it the best one.
create table your_table(
   gap_from int,
   gap_to int
);

insert into your_table values(99999, 9998888);
insert into your_table values(2, 7);
insert into your_table values(200, 10000);
insert into your_table values(10001, 300000);

create table2 as  select
          gap_from,
          1 + nvl(sum(gap_to - gap_from + 1) over (order by gap_from rows between unbounded preceding and 1 preceding), 0) as seq_from,
          sum(gap_to - gap_from + 1) over (order by gap_from) as seq_to
        from your_table;

create sequence your_new_seq;

create or replace function get_PK_inside_gap return number as
  new_seq_val number;
  PK_inside_gap number;
begin
  select your_new_seq.nextval into new_seq_val from dual;
  execute immediate '
    select
      new_seq_val + gap_from - seq_from
    from
      (select :1 as new_seq_val from dual)
      join (
       table2
      ) on new_seq_val between seq_from and seq_to'
  into PK_inside_gap using new_seq_val;
  return PK_inside_gap;
end;

A: To return only values from range 5 to 10:
 create sequence seq1 start with 5 maxvalue 10;

To return only values from 100000 to 999990, in jumps of 10:
 create sequence seq2 start with 100000 maxvalue 999990 increment 10;

A: Create a table with the entries you want, then pin the table in memory for good performance. When the values get 'used' you can update them to set a status flag.
In your query from that in memory pinned table, the query can  select the smallest entry that is not 'used'. Or you can make the query select on other criteria as you mentioned you want that flexibility.

A: You can create usual sequence and modify its result according to your gap list.
create table your_table(
   gap_from int,
   gap_to int
);

insert into your_table values(99999, 9998888);
insert into your_table values(2, 7);
insert into your_table values(200, 10000);
insert into your_table values(10001, 300000);

create sequence your_new_seq;

create or replace function get_PK_inside_gap return number as
  new_seq_val number;
  PK_inside_gap number;
begin
  select your_new_seq.nextval into new_seq_val from dual;
  execute immediate '
    select
      new_seq_val + gap_from - seq_from
    from
      (select :1 as new_seq_val from dual)
      join (
        select
          gap_from,
          1 + nvl(sum(gap_to - gap_from + 1) over (order by gap_from rows between unbounded preceding and 1 preceding), 0) as seq_from,
          sum(gap_to - gap_from + 1) over (order by gap_from) as seq_to
        from your_table
      ) on new_seq_val between seq_from and seq_to'
  into PK_inside_gap using new_seq_val;
  return PK_inside_gap;
end;

Now call get_PK_inside_gap to get your sequence of not used PK: 2,3,4,5,6,7,200,201,...

A: dude  i think this might help you,usually once you create sequence you can't assign start with parameter,so better drop that sequence and recreated it;
create or replace
procedure SEQ_alter(start_with in number,end_with in number,seq_name varchar2)
   as
   sql_qury varchar2(148);
   drop_qury varchar2(148);
   begin
   drop_qury:='drop sequence '||seq_name ;
   execute immediate drop_qury;
   sql_qury:='create sequence '||seq_name|| ' start with '|| to_number(start_with ) ||' maxvalue '|| to_number(end_with);

   execute immediate sql_qury;
   end;


text:
Q: jQuery: adding tooltips to parts of text in a textarea, and removing them when user starts editing it I am planning on building a tool that will provide suggestions to the user on his text, similar to a spellchecker.
I would like to:

*

*highlight problematic text

*remove the highlighting when the user starts editing it.

How would I do this in jquery? Highlighting problematic text looks easy, even adding tooltips with a lib like qtip2, but how would I remove that highlighting as soon as the user starts to edit the text?

A: If you just want to remove something assign a handler to textarea's change, focus, mousedown, keydown events