text:
Q: Why this error appeared "No module named fsspec " and before it was working well I am using pandas to read from gcs buckets and after making the required transformation and want to save it as parquet i got this error No module named fsspec, I solved it by just installing fsspec,gcsfs libraries but I just want to know why this error appeared and before it was running well.
I installed two libraries (fsspec,gcsfs) and works well but I want to know what the reason behind this error


text:
Q: Mapping an object in Hibernate that has 2 lists causing problems I'm trying to save an object that has 2 similar lists using a hbm.xml file. Below is my model object and HBM:
public class MyClass {

...

    private List<MyType> list;

    private List<MyType> otherList;

...

}

My HMB for this section is as follows:
    <list name="list" cascade="all-delete-orphan"
        lazy="false">
        <key column="USER_ID" />
        <list-index column="index" />
        <one-to-many class="path.to.MyType" />
    </list>

    <list name="otherList" cascade="all-delete-orphan"
        lazy="false">
        <key column="USER_ID" />
        <list-index column="index" />
        <one-to-many class="path.to.MyType" />
    </list>

However, when this object gets populated from the database, whatever I expect to be in 'list' is also showing up in 'otherList'. I imagine I'm missing a simple configuration change to allow hibernate to store these 2 lists properly, but I can't figure it out.
Any help?

A: The <list>s contain the same content because you are telling Hibernate to map the same class (path.to.MyType) using the same <key column="USER_ID"> in both instances. Are you sure you haven't made an error in the Hibernate mapping?
Conceptually, what Hibernate will do to materialize these collections is issue a query like
SELECT m.* from MyType m where m.USER_ID = this.USER_ID

If you tell Hibernate to use the same query to map both list and otherList, how can it return different results for the same query?

redpajama_set_name: RedPajamaStackExchange


text:
Q: function pointer - ambiguous symbol error MyClass is a singleton class (There will only ever be one of these in my whole program).
What I want to do is follows.

*

*Add data to my class using AddData, get a function pointer returned that I can then pass to 'another' function in a dll.

*Then this 'other' function calls my call back function

My class is like so.
typedef void (*DataReceivedCallback)(int, int);

class MyClass
{
    MyClass();
    ~MyClass();

    void AddData(int sourceId, DataReceivedCallback &callback);
    static void MyCallBackFunction(int var1, int var2);
};

void MyClass::AddData(int sourceId, DataReceivedCallback &callback)
{
    callback = &MyCallBackFunction;

}
void MyClass::MyCallBackFunction(int var1, int var2 )
{
    //do something blah blah
}

I can then do:
int main()
{
     DataReceivedCallback callback;
     MyClass->GetInstance()->AddData(1, callback);
     callback(1,100);
}

When I step through this I see that I do actually step into the callback MyCallBackFunction which is what I want :)
What I then want to do now is pass this 'callback' defined in main to a dll function that will call back into my callback function.
I have the code for the dll so I want to modify one if its functions so that it accepts my callback function parameter.
I am doing this in the dll function signature:
void * someDllFunction( int var1, int var2, DataReceivedCallback& callback)
{
   callback(2, 200);
}

But I get the error:
error C2872: 'DataReceivedCallback' : ambiguous symbol
How can I solve this?
Does this have to do with only being allowed to use c-style parameters across dll boundaries??

A: typedef void (*DataReceivedCallback)(int, int);

should be,
typedef void (MyClass::*DataReceivedCallback)(int, int);

Because, MyCallBackFunction is a non-static member method of MyClass. So it cannot have regular function signature.
Also change assignment to,
callback = &MyClass::MyCallBackFunction;

Demo.

A: You got your types wrong. DataReceivedCallback, alias void(*)(int, int), is a function pointer, but &MyClass::MyCallBackFunction is a pointer-to-member-function (PTMF). Those two are entirely unrelated and incompatible types!
You cannot treat a member function as a free function.
Since you only have one single instance of your class (Note: "one instance", not "one class"; you always only have one class), why bother with member functions at all? Just make the function global (inside a namespace) and you're done. Though perhaps I'm misunderstanding your requirements.
Another note: You don't need to pass function pointers by reference to the DLL function, just pass them by value. They're just pointers, so they're light-weight.

A: The thing you are missing is how to declare a pointer to member function and how to invoke the member function via that pointer, below is a working example based on your example:
class MyClass;
//standard way to declare a pointer to member function should be - className::*memberFunName(para list)
typedef void (MyClass::*DataReceivedCallback)(int, int);

class MyClass
{
public:
    void AddData(int sourceId, DataReceivedCallback &callback);
    void MyCallBackFunction(int var1, int var2);
};

void MyClass::AddData(int sourceId, DataReceivedCallback &callback)
{
    callback = &MyClass::MyCallBackFunction;

}
void MyClass::MyCallBackFunction(int var1, int var2 )
{
    //do something blah blah
    int tem = var1 + var2; //tem = 3 here
}

int main()
{
    MyClass obj;
    DataReceivedCallback callback;
    obj.AddData(1, callback);
    (obj.*callback)(1,2); //standard way to call the member function via function pointer
}


text:
Q: How to decipher ChicagoBoss Post param I'm a newbie in ChicagoBoss web framework. I have a server which receives a POST request from another server where POST params is of the form:
<<"clientId=STRING_FOR_CLIENT_ID&userId=STRING_FOR_USER_ID&sessionToken=STRING_FOR_SESSION_TOKEN">>
All I have to do is to add clientSecret=CLIENT_SECRET_STRING to this POST params in my server and resend it to the server outside to retrieve access_token.
It would be great if someone suggest some basic code how this can be done.

A: Are you making the client secret string from the original post data? Anyway, if you can use ibrowse, then:
%% send form data as iolist
Data = <<"clientId=STRING_FOR_CLIENT_ID&userId=STRING_FOR_USER_ID&sessionToken=STRING_FOR_SESSION_TOKEN">>,
ibrowse:send_req("http://httpbin.org/post",
             [], post,
             [Data, <<"&clientSecret=CLIENT_SECRET_STRING">>]).


text:
Q: basic rules logarithm of exponential I am looking for proof of the basic rules of logarithm. I can prove all basic rules except this $$\log_ab^y=y\log_ab$$
how to get this rule using definition of logarithm.

A: Just check that
$$
a^{y \log_{a}(b)}
=
a^{\log_{a}(b) y}
=
\left(a^{\log_{a}(b)}\right)^{y}
=
b^{y}.
$$

A: If $\log_ab=m\iff a^m=b$
So, $\log_ab^y=n\iff a^n=b^y=(a^m)^y=a^{my}\implies n=my$ if $a\ne0,1$
So, $\log_ab^y=n=my=y\log_ab$

A: Assuming you know, or have proven that $\log_a(xy) = \log_a x + \log_z y$
We use this to prove:
$$\log_ab^y= \log_a \underbrace{(b \cdot b \cdot ...\cdot b)}_{\large y \; times}$$
$$\iff \log_a b^y = \underbrace{\log_a b + \log_a b + \cdots + \log_z b}_{\large y \;\;times}$$
$$ \iff \log_ab^y = y\log_z b$$
Else: by definition only
$$a^{y \log_{a}(b)}= a^{\log_{a}(b) y}=\left(a^{\log_{a}(b)}\right)^{y}=b^{y}.$$

A: $b=a^{\log_a(b)}$ so $$b^y=(a^{\log_a(b)})^y$$ and by $$(p^m)^n=p^{m\cdot n}$$ you get $$b^y=a^{y\cdot\log_a(b)}$$ taking $\log_a$ on both sides gives:
$$\log_a(b^y)=\log_a(a^{y\cdot\log_a(b)}$$ which by the definition $\log_p(p^m)=m$ goes to:
$$\log_a(b^y)=y\cdot\log_a(b)$$
QED


text:
Q: can't open file or find the folder I can't seem to find the folder called invoice and not sure whether my code is correct or not
I tried to change the write to write and read but it still hasn't created the file in the folder for me...
$invoice = "------------------------------------\n";
$invoice .= "Level 1 Monthly Subscriptionplan Information\n";
$invoice .=  $level1."\n";
$invoice .= "Subscriptionplan:".$row['subscriptionplan']."\n";
$invoice .= "Enrollment Date:".$row['subscriptionplandate']."\n";
$invoice .= "Monthly Fees:".$row['feesmonthly']."\n";
$invoice .= "Payment Status:".$row['paid']."\n";
$invoice .= "Expiry Date:".$row['expirydate']."\n";
$invoice .= "Payment Due Date:".$row['paidbydate']."\n";

$myfile='invoice/level1monthly/'.$_SESSION['u_uid'].'.txt';
$fh = fopen($myfile, 'w+') or die("can't open file");
fwrite($fh, $invoice);
fclose($fh);

I expect it to create a folder called invoice in my root directory of my live server

Level 3 Monthly Subscriptionplan Information

Subscriptionplan:
Enrollment Date:
Monthly Fees:0
Payment Status:
Expiry Date:
Payment Due Date:

I have done the following code but can't get it to change to append
$invoice .= "Level 1 Monthly Subscriptionplan Information\n";
                                $invoice .=  $level1."\n";
                                $invoice .= "Subscriptionplan:".$row['subscriptionplan']."\n";
                                $invoice .= "Enrollment Date:".$row['subscriptionplandate']."\n";
                                $invoice .= "Monthly Fees:".$row['feesmonthly']."\n";
                                $invoice .= "Payment Status:".$row['paid']."\n";
                                $invoice .= "Expiry Date:".$row['expirydate']."\n";
                                $invoice .= "Payment Due Date:".$row['paidbydate']."\n";
                                $myfile='invoice/level1monthly'.$_SESSION['u_uid'].'.txt';
                                $fh = fopen($myfile, 'a+') or die("can't open file");
                                fwrite($fh, $invoice);
                                fclose($fh);
                                  } else {

                                  $invoice = "------------------------------------\n";
                                $invoice .= "Level 1 Monthly Subscriptionplan Information\n";
                                $invoice .=  $level1."\n";
                                $invoice .= "Subscriptionplan:".$row['subscriptionplan']."\n";
                                $invoice .= "Enrollment Date:".$row['subscriptionplandate']."\n";
                                $invoice .= "Monthly Fees:".$row['feesmonthly']."\n";
                                $invoice .= "Payment Status:".$row['paid']."\n";
                                $invoice .= "Expiry Date:".$row['expirydate']."\n";
                                $invoice .= "Payment Due Date:".$row['paidbydate']."\n";
                                $myfile='invoice/level1monthly'.$_SESSION['u_uid'].'.txt';
                                $fh = fopen($myfile, 'w+') or die("can't open file");
                                fwrite($fh, $invoice);
                                fclose($fh);
                                  }

This is my updated code... Will this work in terms of creating a new file if it doesn't exist and then append it?
$myfile='invoice/level1monthly'.$_SESSION['u_uid'].'.txt';

                                  if(file_exists($myfile)) {
                                     $invoice = "------------------------------------\n";
                                $invoice .= "Level 1 Monthly Subscriptionplan Information\n";
                                $invoice .=  $level1."\n";
                                $invoice .= "Subscriptionplan:".$row['subscriptionplan']."\n";
                                $invoice .= "Enrollment Date:".$row['subscriptionplandate']."\n";
                                $invoice .= "Monthly Fees:".$row['feesmonthly']."\n";
                                $invoice .= "Payment Status:".$row['paid']."\n";
                                $invoice .= "Expiry Date:".$row['expirydate']."\n";
                                $invoice .= "Payment Due Date:".$row['paidbydate']."\n";

                                $fh = fopen($myfile, 'a+') or die("can't open file");
                                fwrite($fh, $invoice);
                                fclose($fh);
                                  } else {

                                  $invoice = "------------------------------------\n";
                                $invoice .= "Level 1 Monthly Subscriptionplan Information\n";
                                $invoice .=  $level1."\n";
                                $invoice .= "Subscriptionplan:".$row['subscriptionplan']."\n";
                                $invoice .= "Enrollment Date:".$row['subscriptionplandate']."\n";
                                $invoice .= "Monthly Fees:".$row['feesmonthly']."\n";
                                $invoice .= "Payment Status:".$row['paid']."\n";
                                $invoice .= "Expiry Date:".$row['expirydate']."\n";
                                $invoice .= "Payment Due Date:".$row['paidbydate']."\n";
                                $myfile='invoice/level1monthly'.$_SESSION['u_uid'].'.txt';
                                $fh = fopen($myfile, 'w+') or die("can't open file");
                                fwrite($fh, $invoice);
                                fclose($fh);
                                  }

A: If the directory is not already created, you will need to manually create it or use mkdir():
$dir = __DIR__.'/invoice/level1monthly/';
# If directory doesn't exist
if(!is_dir($dir))
    # Create it recursively and use folder permission 0755
    mkdir($dir, 1, 0755);

You may as well use file_put_contents() as well, it's more straight forward, in my opinion:
$invoice = "------------------------------------\n";
$invoice .= "Level 1 Monthly Subscriptionplan Information\n";
$invoice .=  $level1."\n";
$invoice .= "Subscriptionplan:".$row['subscriptionplan']."\n";
$invoice .= "Enrollment Date:".$row['subscriptionplandate']."\n";
$invoice .= "Monthly Fees:".$row['feesmonthly']."\n";
$invoice .= "Payment Status:".$row['paid']."\n";
$invoice .= "Expiry Date:".$row['expirydate']."\n";
$invoice .= "Payment Due Date:".$row['paidbydate']."\n";
# I am assuming this script is happening in the root.
$dir = __DIR__.'/invoice/level1monthly/';
if(!is_dir($dir))
    mkdir($dir, 1, 0755);
# Append
$myfile = $dir.$_SESSION['u_uid'].'.txt';
# Put contents
file_put_contents($myfile, $invoice);

echo is_file($myfile);


text:
Q: SSH to remote server refused if done via GitLab CI We have a RHEL 7 remote server where I created a dummy user called gitlabci.

*

*While SSH'd into the remote server, I generated a public-private key pair (for use when grabbing files from GitLab)

*

*Uploaded the public key as a deploy key for use later when we get our CI set up

*Generated another public-private key pair in my local machine (for use when SSH'ing into the remote server from the GitLab Runner)

*

*Added the public key to the remote server's authorized_keys

*Added the private key to the project's CI environment variables
The idea is when the CI runs, the GitLab runner will SSH into the remote server as the gitlabci user I created then fetch the branch into the web directory using the deploy keys.
I thought I have set up the keys properly but whenever the runner tries to SSH, the connection gets refused.
$ which ssh-agent || ( apt-get update -y && apt-get install openssh-client git -y )
...
$ eval $(ssh-agent -s)
Agent pid 457
$ echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
Identity added: (stdin) (GitLab CI)
$ mkdir -p ~/.ssh
$ chmod 700 ~/.ssh
$ [[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
$ ssh gitlabci@random.server.com
Pseudo-terminal will not be allocated because stdin is not a terminal.
ssh: connect to host random.server.com port 22: Connection refused
ERROR: Job failed: exit code 1

When I tried to SSH into the remote server via GitBash on my local machine using the key pair I generated it did work.
$ ssh -i ~/.ssh/gitlabci gitlabci@random.server.com
Last login: Mon Nov  4 13:49:59 2019 from machine01.work.server.com

A: ssh: connect to host random.server.com port 22: Connection refused

"Connection refused" means that the ssh client transmitted a connection request to the named host and port, and it received in response a so-called "reset" packet, indicating that the remote server was refusing to accept the connection.
If you can connect to random.server.com from one host but get connection refused from another host, a few possible explanations come to mind:

*

*You might have an entry in your .ssh/config file which substitutes a different name or address for random.server.com. For example, an entry like the following would cause ssh to connect to random2.server.com when you request random.server.com:
Host random.server.com
    Hostname random2.server.com

*The IP address lookup for "random.server.com" is returning the wrong address somehow, so ssh is trying to connect to the wrong server. For example, someone might have added an entry to /etc/hosts for that hostname.

*Some firewall or other packet inspection software is interfering with the connection attempt by responding with a fake reset packet.


text:
Q: Is CHMOD 775 safe to use? I know it's not good to use CHMOD 777, but is 775 as dangerous? Does it provide a backdoor to hackers as easily as 777?

A: The difference between 777 and 775 is the writable attribute for the world-group. The big risk with 777 is that any user on your server can edit the file. 775 does not have this risk.
Don't erroneously assume that the "world writable" flag means everyone can write to the file - only the users on that server can. So on a private server, this poses less risk.
One of the biggest risks is that any script on the server now can write to the file - one "weak" script (known or discovered exploits) can compromise the entire server. If the file is 775, and the webserver-user (usually wwwrun with apache) is in the file's group, it can also write to the file. In this case 775 poses the same risks as 777...


text:
Q: How to set "capped" after collection is created? I am attempting to set a capped parameter to my collection within my mongoose.Schema that did not include capped at first.
Any help welcome.
My Schema:
    const mongoose = require('mongoose')

    var Schema = mongoose.Schema;
    var userSchema = new Schema({
        name:  { type: String, required: true },
        email: { type: String },
        password: { type: String },
        isAdmin: {type: Boolean, default: false},
        avatar: { type: String },
        joinDate: { type: Date, default: Date.now() },
    },{ autoCreate: true, capped : 1024})

userSchema.set('timestamps', true);
const Users = mongoose.model('Users', userSchema)
module.exports = Users;

I get following error:
Error: A non-capped collection exists with the name: users
To use this collection as a capped collection, please first convert it.

A: Seems like you have already created a users collection in your database. So to convert it into a capped run below command either in mongoshell or robomongo
db.runCommand( { convertToCapped: 'users', size: 1024 } )


text:
Q: Find out database entries that are incorrectly encoded I have about a million database values, and I need to flag the items that are not properly encoded. Here are two examples:
# INCORRECT
Academy Award-nominee Gary Busey ("Under Siege," "The Firm") stars in a story of three young surfers searching for meaning as their lives change in the '60s and '70s. This largely autobiographical film from director John Milius ("Conan The Barbarian") features truly spectacular surfing scenes. Also starring Jan-Michael Vincent ("The Winds of War"), real- life mother and son Barbara Hale ("Perry Mason") and William Katt ("The Greatest American Hero") and Patti D'Arbanville ("Miami Vice").

# CORRECT
The Bowery Boys form a unit of their own --- to go to war.

# CORRECT
В древнем русском городе Ростове родился в поповской семье сын. Назвали его родители Алешей. А когда он вырос и стал богатырем, то совершил такие подвиги, что стал героем русских былин Алешей Поповичем. Только подвиги его начались с конфуза…

# INCORRECT
Wenn jemand weiÃ, was es heiÃt, anders zu sein â dann ist das Flöckchen. Sein schneeweiÃes Fell unterscheidet ihn von all den anderen Gorillas seit dem Tag seiner Geburt. Weit entfernt von seiner Heimat lebt Schneeflöckchen im Zoo von Barcelona. Dort ist er die allergröÃte Attraktion und sehr beliebt â bei jedem, nur nicht bei den Gorillas. Im Gegensatz zu seiner Freundin Paula, ein aufgewecktes kleines Mädchen, können die Gorillas im Zoo ganz und gar nicht erkennen, was so faszinierend an diesem schneeweiÃen Sonderling sein soll. Aber Schneeflöckchen hat einen Plan. Zusammen mit seinem Freund Ailur, ein im Geiste buddhistischer schwarzer Panther, der sich im falschen Körper glaubt, flieht der kleine weiÃe Gorilla aus dem Zoo und begibt sich auf die abenteuerlichste und gefährlichste Reise seines Lebens. Eine mächtige Hexe in der GroÃstadt soll ihm seinen sehnlichsten Wunsch erfüllen: normal zu sein. Doch Paula versucht ihn aufzuhalten. SchlieÃlich ist er ihr bester Freund und er soll so bleiben, wie er ist!

What would be a good method for determining which rows are incorrectly encoded?


text:
Q: Haskell libssh2 module throws ERROR_KNOWN_HOSTS I am trying to ssh to my local machine using libssh2-hs module. The command i used is,
runhaskell ssh-client.hs command sk localhost 22 ls

And it throws,
ssh-client.hs: ERROR_KNOWN_HOSTS

When i run ssh client as,
ssh sk@localhost

it goes through successfully.
This error message is inadequate.. (or) is there any other haskell ssh library, i can use.
I deleted all host fingerprints in /home/sk/.ssh/known_hosts and it throws Authentication failure. And surprisingly, the cli tool is not having any traces of taking a password/privat key argument.


text:
Q: Inheriting Custom Operators in Python? If I have class A that defines __cmp__, and class B that extends class A, it seems like I have to redefine __cmp__ in class B.  Is this correct?
Is there a better workaround than implementing a method "cmp" in class A and calling it from the separate implementations of __cmp__ in class A and class B?
Thanks,
-aj

UPDATE:  The issue seems to be my lack of Python 3 exposure.  As I read it, __cmp__ should no longer be used:  http://docs.python.org/dev/3.0/whatsnew/3.0.html#ordering-comparisons
Instead, I've re-implemented my classes using the new ordering comparison operators:  http://docs.python.org/dev/3.0/reference/datamodel.html#object.lt

A: Assuming you have a class called "A", and that class has a definition for __ cmp __.
And let's assume you extend class A:
class B(A):

So to retrieve __ cmp __ from class A from within class B one would use:
A.__cmp__ from within class B
Is my guess.


text:
Q: SQL Server query coding in master detail table I have two tables master and detail
Master table has columns:
id primary
mmrec
billno
billdate
billtype
name
address
amount

Details table has columns:
id primary
purchrecno - master>mmrec
itemcode
itemqty
amount
transtype (There will always be 4 types for this )
taxtype

Besides there is a tax table which has
taxcode primary
taxdesc
percent

What I want to achieve is a summary report, which will have four rows as per billtyp
There will be two sets of columns having twice as many columns as taxtype that were used in a particular period. One set will display base amount (this will be sum of amount for a particular type of tax) another set will have sum of tax (tax is calculated using percent from tax table on amount so that base amount  + tax amount equals to amount ( in details table)
obviously Master table will provide id to select details table transaction and provide
date for the details table transaction
tax table will provide tax information, and percent for tax calculation.
What I have conceived is there will 4 union for each transtype.
But somehow or other could not work out properly.
And I need your help in coding this query.
I am open to using a stored procedure or view but would prefer a query will get me 4 rows.
Thanks


text:
Q: WKWebView: How to handle BLOB URL I have my WKWebView when I click on a file to download it. I have a popup writing:

No application configured to open the URL blob:https// ...

I tried to register a custom URL scheme blob to WKWebView, the application crash saying that this scheme is already supported by default.
However, when I click on the file, the delegate is not called:
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void)`

So I can't even know when a blob url is clicked to try to download the file by injecting JavaScript.
My application is for macOS.

A: Note that this is a really roundabout hack.  Scan all href and replace any blob urls detected with datauri.
EDIT: updated to show it running
function blobToDataURL(blob, callback) {
    var a = new FileReader();
    a.onload = function(e) {callback(e.target.result);}
    a.readAsDataURL(blob);
}
// not sure what elements you are going to intercept:
document.querySelectorAll('a').forEach(async (el)=>{
   const url = el.getAttribute('href');
   if( url.indexOf('blob:')===0 ) {
       let blob = await fetch(url).then(r => r.blob());
       blobToDataURL(blob, datauri => el.setAttribute('href',datauri));
   }
});

b=new Blob([new Int8Array([1,2,3,4,5,6,7,8,9,10]).buffer]);
test.href=URL.createObjectURL(b);
b=new Blob([new Int8Array([31,32,33,34,35]).buffer]);
test1.href=URL.createObjectURL(b);
b=new Blob([new Int8Array([51,52,53,54]).buffer]);
test2.href=URL.createObjectURL(b);

function blobToDataURL(blob, callback) {
    var a = new FileReader();
    a.onload = function(e) {callback(e.target.result);}
    a.readAsDataURL(blob);
}

document.addEventListener('click', function(event) {
  event.preventDefault();
  if ( event.target.matches('a[href^="blob:"]') )
     (async el=>{
       const url = el.href;
       const blob = await fetch(url).then(r => r.blob());
       blobToDataURL(blob, datauri => el.href=datauri);
     })(event.target);
});

// not sure what elements you are going to intercept:
/*document.querySelectorAll('a').forEach(async (el)=>{
   const url = el.href;
   if( url.indexOf('blob:')===0 ) {
       let blob = await fetch(url).then(r => r.blob());
       blobToDataURL(blob, datauri => el.href=datauri);
   }
});*/
test
test
test

Example of data uri conversion on click:

b=new Blob([new Int8Array([1,2,3,4,5,6,7,8,9,10]).buffer]);
test.href=URL.createObjectURL(b);
b=new Blob([new Int8Array([31,32,33,34,35]).buffer]);
test1.href=URL.createObjectURL(b);
b=new Blob([new Int8Array([51,52,53,54]).buffer]);
test2.href=URL.createObjectURL(b);

function blobToDataURL(blob, callback) {
    var a = new FileReader();
    a.onload = function(e) {callback(e.target.result);}
    a.readAsDataURL(blob);
}

document.addEventListener('click', function(event) {
  if ( event.target.matches('a[href^="blob:"]') ) {
     event.preventDefault();
     (async el=>{
       const url = el.href;
       const blob = await fetch(url).then(r => r.blob());
       blobToDataURL(blob, datauri => window.open(el.href=datauri,el.target||'_self'));
     })(event.target);
   }
});

// not sure what elements you are going to intercept:
/*document.querySelectorAll('a').forEach(async (el)=>{
   const url = el.href;
   if( url.indexOf('blob:')===0 ) {
       let blob = await fetch(url).then(r => r.blob());
       blobToDataURL(blob, datauri => el.href=datauri);
   }
});*/
test
test
test


text:
Q: How do I find the coordinates of 10 points spaced equally on a circle? I am not extremely good at math but I am working with computer graphics and I need to find a way to cut a circle equally in to 10 sections. To do this I need to define 10 points on the circle and my basic geometry skills have failed me.
I can so far find the point on the circle using this:
$$x^2 + y^2 = r^2$$

A: Using degrees, your points are $$(r\times\cos(36^{\circ}x+18^{\circ}),r\times\sin(36^{\circ}x+18^{\circ}))\\\text{with }x=\{0,1,2,3,4,5,6,7,8,9\}$$
I don't know the technical way to express this.
What this does is give you the $(x,y)$ coordinates of a radius $r$ long from $(0,0)$ at the angles $\{18^{\circ},54^{\circ},90^{\circ},\dots,342^{\circ}\}$


text:
Q: Reverse spectral theorem proof
Let $T$ be a linear transformation in a finite inner product space $V$ , let $l_1,...l_k$ be different scalars , and let $P_1 \not=0,....,P_k \not=0$ linear transformations in $V$ that satisfies the following conditions:

*

*$T= l_1P_1+...+l_kP_k$

*$I=P_1+...+P_k$

*for all $i \not = j$ $P_i P_j =0$

*for all $i$ $P_i^2=P_i$

*for all $i$ $P_i^*=P_i$.

the first condition in $T$ is called "The spectral theorem of $T$ ".
let $T$ be a linear transformation in $T$ in a finite inner product space $V$ , and let $l_1P_1+...+l_kP_k$ be a spectral decomposition of $T$. prove that: $\{l_1,...,l_k\}$ is the set of all eigenvalues of $T$; $P_1,...,P_k$ are orthographic projection to the eigen
subspace that belong to $l_1,...,l_k$ accordingly ; $T$ is normal when $F= \Bbb C$ and $T$ is symmetric when $F= \Bbb R$

I saw this post which is the same as mine but I am still confused a bit because of the solution provided by my professor, this is his solution:
First we will prove that $P_i$ is an orthonormal projection, let $V_i = \{v | P_i v =v \}$ and $W_i = \{v | P_i v =0 \}$  then $V_i \cap W_i = \{0\}$ (this is my first question , why is that? what do $W_i$ and $V_i$ represent here? why did he define them this way?) . for all $v \in V$ : $v= P_i v +(v- P_i v)$.
since $P_i^2 =P$ then $P_i(P_iv)=P_iv$ therefore $ P_iv \in V_i$ (why is $ P_iv \in V_i$?)  also $P_i (v-P_iv)=0$ so $(v-P_iv) \in W_i$ (I guess this is because $T(v)=0 \iff v=0$?)
from our conclusions here we get $V= V_i \oplus W_i$.
let $w \in W_i$ be any vector and let $v \in V_i$ then
$(v,w)=(P_iv,w)=(v,P_i^*w)=(v,P_iw)=(v,0)=0 $ (is this because of the standard inner product and the last condition? (#5)) , therefore because of this and dimension consideration we get $W_i = V_i^\perp$ finally we get that $P_i$ is an orthogonal projection on $V_i$.
for all $j \not = i$ and for all $v \in V_j$ we get $P_iv = P_u P_jv = 0(v)=0$ (third condition)  so $V_j \subseteq W_i$ and $V_i \perp V_j$ and $V_i \cap V_j = \{0\}$.
let $v \in V$ then $v=Iv= (P_1+...+P_k)v = P_1v +...+ P_kv$ (second condition) and from here we get $V+ V_1+V_2+...+V_k$ from $V_i \cap V_j = \{0\}$ and $V+ V_1+V_2+...+V_k$ we conclude that $V= V_1 \oplus ... \oplus V_k$
according to the first condition for all $0 \not = v \in V_i$ we get $Tv= (l_1P_1+...+l_kP_k)v=l_iP_iv=l_iv$ because $P_jv=0$ for $j \not i$ ( there exists a vector $v \not = 0 $ because $P_i \not = 0$) therefore $v$ is an eigenvector of $T$ that belongs to the eigenvalue $l_i$ , if we define the space $U_i$ of the eigenvalue $l_i$ then we get $V_i \subseteq U_i$ , also let $v \in U_i$.
$V= V_1 \oplus ... \oplus V_k$ so we can define $v=v_1+...+v_k$ , $v_t \in V_t$ for $1 \leq t \leq k$. so $Tv= l_iv=...=l_iv_k$ but $Tv=l_1 v_1 +...+ l_k v_k$ so $(l_i-l_1)v_1 +...+ (l_i - l_k)v_k=0$ and because of the uniqueness of a direct sum we conclude that for all $j$ $(l_i - l_j) v_j =0$ if $j \not = i$ then $l_j \not = l_i$ so we conclude that $v_j =0$ and $v=v_i$ meaning $v \in V_i$. that way we showed that $U_i \subseteq V_i$ and $V_i = U_i$.
lastly given for $i=1,...,k$ $T^*= (\sum l_i P_i)^* = \sum \bar l_i P_i^* = \sum \bar l_i P_i^*$ if we are in the real number field we get $\bar l_i = l_i$ and then $T^*=T$ so $T$ is symmetric.
and in complex field $TT^*=T^*T=\sum|l_i|^2 P_i$ because $P_i^2=P_i$ and $P_iP_j=0$ so it is normal.
Hopefully my translations of his solution are correct.. I am aware that his solution is detailed but appreciate any further explanations for to make it simpler and more understandable or any other (not so advanced please) way is acceptable. hopefully his solution can help someone else on the forum though.

A: You have a lot of questions here, but your comment seems to indicate you are mainly interested in the first two, so I'll answer those in the meantime. Feel free to let me know if you have follow-up questions and I can edit this to address those as well.

*

*The idea behind defining $V_i$ and $W_i$ as they are is that condition (4) implies that the eigenvalues of each $P_i$, should they exist, are either $0$ or $1$ (do you see why?). As such, we are interested in the set of vectors that are fixed by $P_i$ (corresponding to eigenvalue $1$; this is $V_i$), and the set of vectors that are zeroed out by $P_i$ (corresponding to eigenvalue $0$; this is $W_i$).

*Since $P_i^2=P_i$ for all $v$, we know that $P_i(P_i v)=P_i v$, and as such $P_i v$ is fixed by $P_i$, which is precisely the definition of being in $V_i$. Similarly, $P_i(v-P_i(v))=P_i v-P_i^2 v = P_iv-P_iv=0$, so $v-P_iv$ is zeroed out by $P_i$, which is precisely the definition of being in $W_i$. The upshot of this analysis is that we now know any vector in $V$ can be written as the sum of a vector in $V_i$ and a vector in $W_i$.
Hope this helps!
EDIT: For your next question:

*Yes, exactly. We have $(v,w)=(P_iv,w)$ because $P_iv=v$ by the definition of $V_i$, $(P_iv,w)=(v,P_i^*w)$ by the definition of the adjoint, $(v,P_i^*w)=(v,P_i w)$ by condition (5), and $(v,P_i w)=(v,0)=0$ because $P_iw=0$ by the definition of $W_i$.

EDIT 2:

*I'm going to assume that you understand the proof that $V=V_1\oplus\dots\oplus V_k$, as it is very similar to the work before involving $V_i$ and $W_i$. The thing to note is that since all of the $V_i$'s are orthogonal and each $P_i$ is an orthogonal projection, if we pick $v\in V_i$ for some $i$, all of the terms in $Tv$ are going to be zero except for $l_iP_iv$, which will equal $l_i v$ since $P_iv=v$. Therefore $v$ is an eigenvector of $T$ with corresponding eigenvalue $l_i$. Doing this for each $V_i$, we construct a list of $k$ linearly independent eigenvectors with corresponding eigenvalues $l_1,\dots,l_k$ and eigenspaces that span $V$. Since the eigenspaces span $V$, we know we have found all possible eigenvalues.


text:
Q: Precision/recall curve and accuracy/threshold interpretation I am running a logisitc regression and trying to interpret the predictive power it generates. How should I interpret the precision/recall curve and the accuracy as a function of threshold?
My precision/recall curve looks very strange with the immediate dip.

A: At the left end of your precision/recall curve, you classify everything as "negative". So you have $TP=FP=0$. No matter how many true positives $P$ you have (assuming $P>0$), your recall is
$$ \frac{TP}{P}=\frac{0}{P}=0. $$
On the other hand, your precision is
$$ \frac{TP}{TP+FP}=\frac{0}{0+0}=\frac{0}{0}, $$
which is undefined, but your software may simply set it to (or plot it as) one.
Very much related: Why is accuracy not the best measure for assessing classification models? and Classification probability threshold. So, in reply to your question "How should I interpret the precision/recall curve and the accuracy as a function of threshold?", my answer would be "don't".


text:
Q: Color manipulation when radio button is checked I'm trying to dynamically change the color of text when the slider radio
button is checked or unchecked. My goal is for the text to change color when the slider is active or not. Here is a link to my code.
HTML:

              <input id="togggle_repl_beef" class="checkbox-toggle" data-type="date" type="checkbox"></input>

              Fade this text when off
               Fade this text when on

CSS:
/* The switch - the box around the slider */
.switch {
}

/* Hide default HTML checkbox */
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* Rounded sliders */
.slider {
  position: relative;
  display: block;
  cursor: pointer;
  height: 20px;
  width: 40px;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  display: block;
  content: "";
  height: 10px;
  width: 10px;
  left: 4px;
  bottom: 4.5px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #235b96;
}

input:focus + .slider {
  box-shadow: 0 0 1px rgba(0, 0, 0, 0.123);
}

input:checked + .slider:before {
  -webkit-transform: translateX(22px);
  -ms-transform: translateX(22px);
  transform: translateX(22px);
}

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
.toggle-text {
  text-transform: uppercase;
  font-weight: 700;
  overflow: hidden;
  line-height: 2;
  color: #235b96;
  letter-spacing: 1.2px;
  font-size: 11px;
}

.switch {
  display: flex;
  flex-direction: row;
}

.off {
  order: 1;
}

.slider {
  margin: 0 5px;
  order: 2;
}

.on {
  order: 3;
}

input:checked ~ .on {
  color: red;
}

input:not(:checked) ~ .off {
  color: red;
}

A:

/* The switch - the box around the slider */
.switch {
}

/* Hide default HTML checkbox */
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* Rounded sliders */
.slider {
  position: relative;
  display: block;
  cursor: pointer;
  height: 20px;
  width: 40px;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  display: block;
  content: "";
  height: 10px;
  width: 10px;
  left: 4px;
  bottom: 4.5px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #235b96;
}

input:focus + .slider {
  box-shadow: 0 0 1px rgba(0, 0, 0, 0.123);
}

input:checked + .slider:before {
  -webkit-transform: translateX(22px);
  -ms-transform: translateX(22px);
  transform: translateX(22px);
}

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
.toggle-text {
  text-transform: uppercase;
  font-weight: 700;
  overflow: hidden;
  line-height: 2;
  color: #235b96;
  letter-spacing: 1.2px;
  font-size: 11px;
}

.switch {
  display: flex;
  flex-direction: row;
}

.off {
  order: 1;
}

.slider {
  margin: 0 5px;
  order: 2;
}

.on {
  order: 3;
}

input:checked ~ .on {
  color: red;
}

input:not(:checked) ~ .off {
  color: red;
}

     <input id="togggle_repl_beef" class="checkbox-toggle" data-type="date" type="checkbox"></input>

     Fade this text when off
      Fade this text when on


text:
Q: Can DSolve give results in parametric form? Can DSolve give results in parametric form?
For example the cycloid equation is:
DSolve[{(x'[t])^2 == r/x[t] - 1}, x[t], t]

And the solution is usually given in parametric form:
$$x=r \,(t- Sin[t]) \quad y=r\,(1- Cos[t])$$
but Mathematica (10) give a resolt in terms of InverseFunction
So I wonder can DSolve give result in parametric form?

A: This is more an extended comment as a solution.  For convenience, begin from the ODE in the form given in the Wikipedia reference cited in the question.
y'[x]^2 == 2 r/y[x] - 1

The OP wishes DSolve to provide the parametric answer,
{y[t] -> r - r Cos[t], x[t] -> r (t - Sin[t])}

However, this result is not unique.  For instance, replacing t by a t, where a is any real constant, also is a valid parametric solution.  And, there are infinitely more equivalent parametric solutions.  Obtaining the desired solution requires specifying an additional relationship.
Here is a simple illustration.  Rewrite the ODE in terms of a parameter t.
y'[t]^2 == x'[t]^2 (2 r/y[t] - 1)

This ODE cannot, of course, be solved without a second relationship among x, y, and t.  For instance, specify
x'[t] == y[t]

(Other second equations are possible but yield different parametric representations.)  Now solve the set of ODEs, impose the boundary conditions that x and y vanish at t == 0, and simplify
FullSimplify[First@DSolve[{y'[t]^2 == x'[t]^2 (2 r/y[t] - 1), x'[t] == y[t],
    x[0] == 0}, {x[t], y[t]}, t] /. C[1] -> 0]

(* {y[t] -> r - r Cos[t], x[t] -> r (t - Sin[t])} *)

as desired.  This example is meant to show that DSolve is capable with assistance of producing parametric solutions.  It is not, however, capable of producing any particular parametric solution that someone might desire without very particular assistance.


text:
Q: Change default behaviour of legend in Amchart 5 I'm trying to make this chart (https://www.amcharts.com/demos/reversed-value-axis/) in angular and need help in changing default behaviour of legend like if i click on any legend only that axis should be show other will hide unlike now if we click on any legend, that will hide.
is there any possible way to do it?
Default Chart
If click on one legend

A: Yes, of course...
To do that, you need a collection of all your series. You also need hide() and appear() methods.
Here is a possible implementation:

am5.ready(() => {

  let root = am5.Root.new("chartdiv");

  root.setThemes([
    am5themes_Animated.new(root)
  ]);

  let chart = root.container.children.push(am5xy.XYChart.new(root, {
    layout: root.verticalLayout
  }));

  let data = [
    {
      year: "1930",
      italy: 1,
      germany: 5,
      uk: 3
    },
    {
      year: "1934",
      italy: 1,
      germany: 2,
      uk: 6
    },
    {
      year: "1938",
      italy: 2,
      germany: 3,
      uk: 1
    },
    {
      year: "1950",
      italy: 3,
      germany: 4,
      uk: 1
    },
    {
      year: "1954",
      italy: 5,
      germany: 1,
      uk: 2
    },
    {
      year: "1958",
      italy: 3,
      germany: 2,
      uk: 1
    },
    {
      year: "1962",
      italy: 1,
      germany: 2,
      uk: 3
    },
    {
      year: "1966",
      italy: 2,
      germany: 1,
      uk: 5
    },
    {
      year: "1970",
      italy: 3,
      germany: 5,
      uk: 2
    },
    {
      year: "1974",
      italy: 4,
      germany: 3,
      uk: 6
    },
    {
      year: "1978",
      italy: 1,
      germany: 2,
      uk: 4
    }
  ];

  let xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {
    categoryField: "year",
    renderer: am5xy.AxisRendererX.new(root, {})
  }));

  xAxis.data.setAll(data);

  let yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
    renderer: am5xy.AxisRendererY.new(root, {
      inversed: true
    })
  }));

  function createSeries(name, field) {
    let series = chart.series.push(am5xy.LineSeries.new(root, {
      name,
      xAxis,
      yAxis,
      categoryXField: "year",
      valueYField: field
    }));

    series.bullets.push(() => {
      return am5.Bullet.new(root, {
        sprite: am5.Circle.new(root, {
          radius: 5,
          fill: series.get("fill")
        })
      });
    });

    series.data.setAll(data);

    return series;
  }

  // The interesting part starts here!

  let allSeries = [];

  allSeries.push(createSeries("Italy", "italy"));
  allSeries.push(createSeries("Germany", "germany"));
  allSeries.push(createSeries("UK", "uk"));

  let legend = chart.children.push(am5.Legend.new(root, {
    centerX: am5.p50,
    x: am5.p50
  }));

  legend.itemContainers.template.events.on("click", () => {
    for (let series of allSeries) {
      series.hide();
    }
  });

  legend.data.setAll(chart.series.values);

  document.getElementById("reset").addEventListener("click", () => {
    for (let series of allSeries) {
      series.appear();
    }
  });

});
#chartdiv {
  width: 100%;
  height: 350px;
}

#reset {
  width: 50%;
  display: block;
  margin: auto;
  cursor: pointer;
}

<button type="button" id="reset">Reset</button>


text:
Q: Java: Read certificates from windows store It is possible to write a Java program to read one certificate (getting private and public key) stored in windows certificate store ?
Thanks

A: If you are on Java 6, you can use the MSCAPI keystore to read it. Just open your keystore like this,
      KeyStore msCertStore = KeyStore.getInstance("Windows-MY", "SunMSCAPI");


text:
Q: I want to exclude empty category from Mage::getModel in Magento 1.9 $allCats = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('is_active','1')
->addAttributeToFilter('include_in_menu','1')
->addAttributeToFilter('parent_id',array('eq' => $parentId))
->addAttributeToSort('position', 'asc');

Currently, this code showing all category including empty category I want to remove empty category from collection

A: Try this one:
$categories = Mage::getModel('catalog/category')->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('level', 2)
    ->addAttributeToSelect('is_active', 1)
    ->setLoadProductCount(true);

foreach ($categories as $category) {
    echo $category->getProductCount();
}

A:
You can remove empty categories from category collection

foreach($allCats as $key => $category) {
    if ($category->getProductCount() === 0) {
        $allCats->removeItemByKey($category->getId());
    }
}

I hope this will help


text:
Q: Background Width jQuery Specification Not Working I created a web page where the background of my page changes depending on the hour. I want the background image to always be the full width of the page, so I am trying to set it to be 100%, but it doesn't seem to be working. Is there some part of the code that's written incorrectly? Do I need to implement something else?

body {
  margin-left: 5%;
  margin-right: 5%;
}
#demo {
  color: white;
}
#txt {
  color: white;
  float: left;
  font-family: OpenSans;
  font-size: 90px;
  margin: 20px;
}
#weather {
  color: white;
  float: right;
  font-family: OpenSans;
  font-size: 40px;
  margin: 20px;
}
<!DOCTYPE html>

    <title>Blooming Time And Temperature</title>
    <link href="css/format.css" rel="stylesheet"/>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">

A: You could try removing the margin attributes on the body tag in your CSS, and set background-size: cover on the body tag there. Then in your changeBackground function, you mightn't need the .width(100%); method, since the width shouldn't change when you swap out the background images?

A: If you are putting the background image on the body and you have this css property, it won't do.
body {
  margin-left: 5%;
  margin-right: 5%;
}

Make the property
body {
    margin:0;
}


text:
Q: How do I make imageView move infinitely from side to side of the screen? [android animation] Here is my xml code:
<?xml version="1.0" encoding="utf-8"?>

android:repeatCount="infinite">
    <translate  xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromXDelta="10"
        android:toXDelta="500"
        android:fillAfter="true"
        android:duration="1000"
        >
    </translate>

    <translate xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromXDelta="500"
        android:toXDelta="10"
        android:duration="1000"
        android:fillBefore="true"
        android:startOffset="2000"
        >
    </translate>

here is java code:
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.page1);
    cloud2 = (ImageView) findViewById(R.id.cloud2);
    Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.clouds_animation);
    cloud2.startAnimation(animation);
    animation.setRepeatCount(Animation.INFINITE);

I have tried already

*

*to put "repeatCount=infinite" into both translate, but no result

*to put programatically setrepeatCount in java code.

What am i doing wrong?

A: instead of doing 2 animations in xml file, i solved this problem this way:
   TranslateAnimation cloud_moving = new TranslateAnimation(
            Animation.ABSOLUTE, 1450,
            Animation.ABSOLUTE, 10,
            Animation.ABSOLUTE, 0,
            Animation.ABSOLUTE, 0
    );

    cloud_moving.setDuration(6000);
    cloud_moving.setFillAfter(true);
    cloud_moving.setStartOffset(1000);
    cloud_moving.setRepeatCount(Animation.INFINITE);
    cloud_moving.setRepeatMode(Animation.REVERSE);
    cloud2.startAnimation(cloud_moving);

apparently, xml equivalent animation does not work as well as just source code, coding it up works better!
from the docs: if you set repeat count to infinite AND set repeat mode to reverse - it will "mirror" itself, i.e. the image will move from one side to another, and don't forget to set fill after to true - the image will stay where it stays after animation is complete...


text:
Q: Wifi doesn't work on Lenovo B590 with Broadcom BCM4313 My son bougt a laptop.  I installed Ubuntu 12.04. First wifi worked fine now it keeps searching but can't connect. I tried some solutions but I think I need help.
lspci -nn | grep
028002:00.0 Network controller [0280]: Broadcom Corporation BCM4313 802.11b/g/n Wireless LAN Controller [14e4:4727] (rev 01)
These are the data.
Thanks!

A: Please get a temporary wired ethernet connection and open a terminal and do:
sudo apt-get install linux-firmware-nonfree

Reboot and you should be all set.


text:
Q: Why this javascript regex doesn't work? I'm doing a small javascript method, which receive a list of point, and I've to read those points to create a Polygon in a google map.
I receive those point on the form:
(lat, long), (lat, long),(lat, long)
So I've done the following regex:
\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)

I've tested it with RegexPal and the exact data I receive:
(25.774252, -80.190262),(18.466465, -66.118292),(32.321384, -64.75737),(25.774252, -80.190262)

and it works, so why when I've this code in my javascript, I receive null in the result?
var polygons="(25.774252, -80.190262),(18.466465, -66.118292),(32.321384, -64.75737),(25.774252, -80.190262)";
var reg = new RegExp("/\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g");
var result = polygons.match(reg);

I've no javascript error when executing(with debug mode of google chrome). This code is hosted in a javascript function which is in a included JS file. This method is called in the OnLoad method.
I've searched a lot, but I can't find why this isn't working. Thank you very much!

A: Use a regex literal [MDN]:
var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;

You are making two errors when you use RegExp [MDN]:

*

*The "delimiters" / are should not be part of the expression

*If you define an expression as string, you have to escape the backslash, because it is the escape character in strings

Furthermore, modifiers are passed as second argument to the function.
So if you wanted to use RegExp (which you don't have to in this case), the equivalent would be:
var reg = new RegExp("\\(\\s*([0-9.-]+)\\s*,\\s([0-9.-]+)\\s*\\)", "g");

(and I think now you see why regex literals are more convenient)

I always find it helpful to copy and past a RegExp expression in the console and see its output. Taking your original expression, we get:
/(s*([0-9.-]+)s*,s([0-9.-]+)s*)/g

which means that the expressions tries to match /, s and g literally and the parens () are still treated as special characters.

Update: .match() returns an array:
["(25.774252, -80.190262)", "(18.466465, -66.118292)", ... ]

which does not seem to be very useful.
You have to use .exec() [MDN] to extract the numbers:
["(25.774252, -80.190262)", "25.774252", "-80.190262"]

This has to be called repeatedly until the whole strings was processed.
Example:
var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
var result, points = [];

while((result = reg.exec(polygons)) !== null) {
    points.push([+result[1], +result[2]]);
}

This creates an array of arrays and the unary plus (+) will convert the strings into numbers:
[
    [25.774252, -80.190262],
    [18.466465, -66.118292],
    ...
]

Of course if you want the values as strings and not as numbers, you can just omit the +.


text:
Q: htaccess blocking requests to /? I am getting a ton of bots or something hitting my site for URLs like: www.website.com/?how-much-does-a-ventolin-inhaler-cost-in-canada
I have no idea what they are, it doesn't resolve on anything to my site but it causing significant mysql overhead as my index has some heavy queries.
I can't seem to figure out how to stop these via htaccess because of the question mark...
I was thinking something like this:
RewriteEngine On
RewriteCond %{REQUEST_URI} /\?^
RewriteRule .*$ - [F,L]

But no dice.

A: All values found after the "?" in the URL are called query string parameters. Does your entire website not use query string parameters? You may want to be careful before removing every request with a query string parameter, because that's a pretty common way of using the internet.
If you really want to strip them, the following code would work.
RewriteEngine On
RewriteCond %{QUERY_STRING} !=""
RewriteRule . - [F,L]

However, this just blocks all requests to your page that contain query parameters. Anyone could easily spam your page without any query parameters if they knew it caused an issue that would lead to a denial of service for you.
This whole issue sounds like there's a more systemic issue beneath - it shouldn't be causing you significant overhead for people who hit your default page.

A: I would guess that you publish webstats or some similar information like top URLs, top referers, etc. As the symptoms suggests you are being targeted by search engine poisoning.


text:
Q: How to run MPI on VS Code or Visual Studio? I have a need to run MPI on Windows 10, so I tried to install the library on Visual Studio, but each time I create a new project it requires repeating the process from the beginning, meaning I have to add dependencies all over again.
The first question is it possible to install the MPI once and for all and the second is if it's possible to run it on VS Code instead of Studio.

A: So I managed to do it via this guide
https://learn.microsoft.com/en-us/cpp/build/vcpkg?view=msvc-160
Seems to work now without needing each time to add dependencies, does not run on Vscode though, says some error with the .json I don't know what exactly but I can run in Visual Studio so it's okay for now.


text:
Q: remote validation is behind one step in mvc Is anyone else getting this issue?
Remote validation on unobtrusive in mvc is behind by one step.
I am trying to validate a field and if the field is valid, a checkmark appears beside it. Everything is working except for remote.
Please see image (gif) attached.
In this gif, I have two forms with a blur listener. I check if valid/invalid. If the field is valid, the checkmark appears else, should disappear.
I got it working for confirm email but not the 'Field Two Remote validation'. The checkmark disappears once I focus then blur
Anyone else experiencing this? If I do a reverse which is I enter the email confirmation first, I get the same issue
code to make the checkmark show:
$.fn.addCheckIconTextBox = function (options) {
    var settings = $.extend({
        // These are the defaults.
        id: "#" + $(this).attr('id')
    }, options);
    if ($(settings.id).length > 0) {
        $(settings.id).blur(function (e) {
            console.log("isvalid " + $('form').validate().element(settings.id));
            if ($(settings.id).val() !== '') {
                if ($(settings.id).hasClass('input-validation-error')) {
                    $(settings.id).next('.helper').attr('class', 'ico helper');
                } else {
                    $(settings.id).next('.helper').attr('class', 'ico helper pass');
                }
            } else {
                $(settings.id).next('.helper').attr('class', 'ico helper');
            }
        });
    }
};

A: answer is based on: Trouble Attaching Call Back to Unobtrusive Validation Show Error
/**add/remove form icon when valid/invalid only when svg.helper is beside it**/
v.settings.highlight = function (element, errorClass, validClass) {
    var elId = $(element).attr('id');
    var checkIconEl = $('#' + elId).next('.helper');
    checkIconEl.attr('class', 'ico helper');
    originalHighlight.call(v, element, errorClass, validClass);
}
v.settings.unhighlight = function (element, errorClass, validClass) {
    var elId = $(element).attr('id');
    var checkIconEl = $('#' + elId).next('.helper');
    checkIconEl.attr('class', 'ico helper pass');
    originalUnHighlight.call(v, element, errorClass, validClass);
}


text:
Q: Best Way to Render HTML in WinForms application? I have a WinForms application, running on .net 3.5. This Application generates HTML on the fly, which includes the complete document, and also an inline-CSS-Stylesheet (inside the head element).
I am using the WebBrowser control and setting browser.DocumentText to my generated HTML, but that does not seem to properly apply styles on the body element (I've set background-color to #000000 in the CSS, but the background is still white).
I wonder if a) there are some alternatives to render relatively simple HTML in C# (i.e. a completely managed HTML renderer) or b) what would be the best way to render HTML using the WebBrowser control, including correct handling of inline-css and without using a temporary file on the hard drive.
Edit: The CSS-not-applying issue was a separate problem. I've put my actual CSS in a CDATA block, which seems to cause it not to apply correctly. That is now fixed, but the question itself still stands.

A: Stayed with the built-in WebBrowser. The HtmlRenderer from the other answer is great, but renders an image.

A: For managed HTML renderer see HtmlRenderer on GitHub.

A: Your could look into using a view engine.
Most view engines can work in a stand-alone api manner
for example NHaml and nvelocity both can be used stand alone
http://code.google.com/p/nhaml/
http://www.castleproject.org/others/nvelocity/index.html
And i assume Spark can be as well
http://dev.dejardin.org/

A: I have developed what you were asking for: a "completely managed HTML renderer", which will "render relatively simple HTML in C#". It supports a subset of CSS, which you can "specify in a inline CSS stylesheet (inside the head element)".
For details, see the ModelText HTML control.


text:
Q: Displaying isolated points using pm3d Gnuplot I am plotting 3D histograms using pm3d in Gnuplot. Data is provided below. The sequence of steps in Gnuplot are:
set view map
splot 'test.dat' u 1:2:(log($3)) with pm3d t " ", 'test.dat' u 1:2:(log($3)) t " "

as you can see in this figure:

some data points are not plotted with pm3d, I think because the lack of coordination with neighboring points. I wonder if there is a way to explicitly plot these non-well coordinated points in Gnuplot using pm3d.
Note: The "plot with images" doesn't work in my case, because the data set I have is much more larger than this simple example and the plot looks like fragmented squares.
Thanks.
Data:
   1           1           1
   1           2           0
   1           3           0
   1           4           0
   1           5           0
   1           6           0
   1           7           0
   1           8           0

   2           1           0
   2           2           0
   2           3           1
   2           4           2
   2           5           3
   2           6           0
   2           7           0
   2           8           0

   3           1           0
   3           2           0
   3           3           2
   3           4          10
   3           5          15
   3           6           2
   3           7           0
   3           8           0

   4           1           0
   4           2           0
   4           3           0
   4           4           5
   4           5           2
   4           6           1
   4           7           0
   4           8           0

   5           1           0
   5           2           0
   5           3           0
   5           4           3
   5           5           2
   5           6           0
   5           7           0
   5           8           0

   6           1           0
   6           2           0
   6           3           0
   6           4           2
   6           5           0
   6           6           0
   6           7           1
   6           8           0

   7           1           0
   7           2           0
   7           3           0
   7           4           0
   7           5           0
   7           6           0
   7           7           0
   7           8           0

   8           1           0
   8           2           0
   8           3           0
   8           4           0
   8           5           0
   8           6           0
   8           7           1.1
   8           8           0


text:
Q: mysterious margin for nav dots I have created a very simple dot navigation on my site banner HERE. The HTML code i have used is as follows:

Now for the
 element i have the following code:
.banner ul.carousel-dots li {
    height: 13px;
    width: 13px;
    display: inline-block;
    background: url(../img/res/carousel-dots.png) 0 0 no-repeat;
    margin: 0;
    cursor: pointer;
}

Now even though i have margin: 0; in my style, i get a margin between the left and right, i don't know where are these spaces coming from , i would want the dots to be touching each other , side to side. So whats causing this mysterious margin ?

A: white space between inline-block elements?
The space is actually created by the "enter" between your elements.
How to remove the space between inline-block elements?
In the question above there are a lot of different answers how to remove it.
I set the parent element font-size to 0.

ul {
  font-size: 0;
}
ul.carousel-dots li {
  height: 13px;
  width: 13px;
  display: inline-block;
  /*background: url(../img/res/carousel-dots.png) 0 0 no-repeat;*/
  background-color: black;
  border-radius: 50%;
  margin: 0;
  cursor: pointer;
}

A: Ok, the answer is a bit tricky, if you want it fixed, you have to remove the space between the
 and the next

So, this:

Should become this:

The reason of this issue is the fact that when using inline-block, spaces are also considered inline characters, leaving space in between.
PS: There are also other ways to remove the space, by using word-spacing or other such things, but I find the simplest solution to be always the best, plus on html you should always try to minimize your code before shipping, so a few lines of code less is always better than a few more


text:
Q: JS, jQuery: How do you make a chained jQuery animation NOT wait until the previous animation is done? As you may know, if you chain jQuery animations together using the "complete" parameter, each animation happens in succession only after the previous is complete.
I have a chain, like this:
$('#foobar').load(url, function(){
    $(this).fadeIn(time, function(){
        $(this).scrollTop(position, time, function() {
            $(this).css({'color':'#58e'})
        });
    });
});

This chain will execute something like this: first load content, then fade in, then scroll to the top, then finally change the css color.
What I want is this: first load the content, then fade in and scroll to the top at the same time, then finally change the color after fadeIn and scrollTop are both done.
Let's say the scrollTop animation takes twice as long than the fadeIn animation. What simple piece of code would I add to my code so that the scrollTop callback in fadeIn DOESN'T wait for the fadeIn animation to complete. The css() animation will wait for the scrollTop animation to complete, like normal.
So the only change (whatever it might be) would affect the callback within fadeIn where scrollTop is called. I'm guessing it might have to do with manipulating the queue?
Thanks for the help!
EDIT: Here's the solution as hinted by Andrew:
First, my original code which loads each custom function in order:
show_loader(0, function() {
    close_box($target_close, '/', '#' + $target_close.attr('id') + ' .post_wrap', function() {
        open_box($target_open, event.value, '.wide-col', function() {
            hide_loader(function() {
                scroll_to_content($target_open);
            });
            $target_close = $target_open;
        });
    });
});

Now I want close_box and open_box to execute asynchronously (at the same time), so I changed it to this:
show_loader(0, function() {
    close_box($target_close, '/', '#' + $target_close.attr('id') + ' .post_wrap');
    open_box($target_open, event.value, '.wide-col', function() {
        hide_loader(function() {
            scroll_to_content($target_open);
        });
        $target_close = $target_open;
    });
});

Now close_box and open_box animations happen at the "same time".

A: Move the code that animates scrollTop outside of the callback to the fadeIn function:
$('#foobar').load(url, function() {
    $(this).fadeIn(time);
    $(this).scrollTop(position, time, function() {
        $(this).css({'color':'#58e'});
    });
});


text:
Q: What will the values of the registers be after this code segment executes Need help understanding what the values of the registers be after this code finish executing
   mov dword ptr [ebp-4], 1
   cmp dword ptr [ebp-4], 0
   jnz loc_40101C
   mov eax, [ebp-4]
   xor eax, 2
   mov [ebp-4], eax
   jmp loc_401025
loc_40101C:
   mov ecx, [ebp-4]
   xor ecx, 3
   mov [ebp-4], ecx
loc_401025:
   mov ebx, [ebp-4]
   xor ebx, 5
   mov [ebp-4], ebx

From my current understanding, the code jumps to loc_40101C because the cmp instruction above did not return with a zero flag. So, instructions below jnz are ignored and will be skipped to loc_40101C.
Now at loc_40101C, the value 1 gets moved to ecx. ecx then gets XOR'd with 3 resulting in the value of 2. The code then finishes executing resulting in ecx having a value of 2.
My question is, would any value be assigned to eax and ebx after this code finishes executing?


text:
Q: Deleting and Re-adding iOS app breaks Hot Questions widget I deleted and re-installed the app to get out of this bug. That killed my Hot Questions widget (it just showed the title, with no posts). I then tried to reproduce it. The second time, I tapped a 'hot question' while the app was deleted (the widget sticks around when the app is deleted.), and got an error message, before the widget changed to look like the screenshot below. Reinstalling the app doesn't fix it, I had to restart my device to get it back.
iOS 8.2, iPhone 4s, Beta App v1.2.2.200

A: I've not been able replicate this.  The facts that it says "com.stackexchange.ent.zapho..." instead of "Hot Questions" and worked after reboot suggests that there was an OS level problem when reloading the widget. I've seen other erratic behavior on development builds too.  I don't think there's really anything we can do from a development perspective.


text:
Q: Run macro on change within target range | Change (ByVal Target As Range) I'm working with the Worksheet_Change(ByVal Target As Range) event.
I wanted to run a macro if either on of cells A1 or A2 are changed.
So the target range is set to [A1, A2]
Then, if A1 is changed, I want to clear A2, or the other way around (A2 is changed: clear A1).
Now the problem:
If A1 value is changed. the macro clears A2. That's seen as a change in A2, so it clears A1, which is a change, etc...
I'm sure it's something simple, but I can't see how I can have cell A1 be changed without triggering the change macro if A2 is being cleared.
Anyone who has experience in this?

A: You can accomplish this by toggling events off and on, like the following:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Intersect(Target, Me.Range("A1:A2")) Is Nothing Then Exit Sub

    On Error GoTo SafeExit
    Application.EnableEvents = False

    If Target.Address = "$A$1" Then
        Me.Range("A2").Clear
    ElseIf Target.Address = "$A$2" Then
        Me.Range("A1").Clear
    End If

SafeExit:
    Application.EnableEvents = True
End Sub

A: There are a few edge cases here, around changing more than one cell eg via copy pasting a range (possibly include other cells too).
Here's a version thats more robust in those cases
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range
    Set rng = Intersect(Target, Me.Range("A1:A2"))
    If rng Is Nothing Then Exit Sub

    On Error GoTo SafeExit
    Application.EnableEvents = False

    Select Case rng.Address(0, 0)
        ' If both changed, what now? Default to clearing A2
        Case "A1", "A1:A2"
            If Not IsEmpty(Me.Cells(1, 1)) Then
                Me.Cells(2, 1).Clear
            End If
        Case "A2"
            If Not IsEmpty(Me.Cells(2, 1)) Then
                Me.Cells(1, 1).Clear
            End If
    End Select

SafeExit:
    Application.EnableEvents = True
End Sub


text:
Q: Toast is shown every time when device is rotate In my Android app I use AAC.
Here my activity:
public class AddTraderActivity extends AppCompatActivity {
    AddTraderViewModel addTraderViewModel;
    private static final String TAG = AddTraderActivity.class.getName();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AddTraderActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.add_trader_activity);
        binding.setHandler(this);
        init();
    }

    private void init() {
        ViewModelProvider viewViewModelProvider = ViewModelProviders.of(this);
        addTraderViewModel = viewViewModelProvider.get(AddTraderViewModel.class);
        Observer<String> () {

            @Override
            public void onChanged (String message){
                Debug.d(TAG, "onChanged: message = " + message);
                Toast.makeText(AddTraderActivity.this, message, Toast.LENGTH_LONG).show();
            }
        });
    }

    public void onClickStart() {
        EditText baseEditText = findViewById(R.id.baseEditText);
        EditText quoteEditText = findViewById(R.id.quoteEditText);
        addTraderViewModel.doClickStart(baseEditText.getText().toString(), quoteEditText.getText().toString());
    }
}

Here my ViewModel:
public class AddTraderViewModel extends AndroidViewModel {
    private MutableLiveData<String> messageLiveData = new MutableLiveData<>();

    private static final String TAG = AddTraderViewModel.class.getName();

    public AddTraderViewModel(@NonNull Application application) {
        super(application);
    }

    public void doClickStart(String base, String quote) {
        Debug.d(TAG, "doClickStart: ");
        if (base.trim().isEmpty() || quote.trim().isEmpty()) {
            String message = getApplication().getApplicationContext().getString(R.string.please_input_all_fields);
            messageLiveData.setValue(message);
            return;
        }
    }

    public LiveData<String> getMessageLiveData() {
        return messageLiveData;
    }
}

So when I click on button on Activity call method onClickStart()
If any fields is empty the show toast. In the activity call method:
onChanged (String message)

Nice. It's work fine.
But the problem is, when I rotate the device in the activity method onChanged(String message) is called AGAIN and as result show toast. This happened on every rotation.
Why?

A: This is the expected behaviour. If you want to avoid this you must set message = "" and keep an empty check before showing the toast.
A better way to use it is something like Event Wrapper or SingleLiveEvent
Highly recommend you to read this article. This explains why you are facing this and what are your options in detail.


text:
Q: Bitbucket and a small development house I am in the process of finally rolling Mercurial as our version control system at work. This is a huge deal for everyone as, shockingly, they have never used a VCS. After months of putting the bug in management's ears, they finally saw the light and now realise how much better it is than working with a network of shared folders!
In the process of rolling this out, I am thinking of different strategies to manage our stuff and I am leaning towards using Bitbucket as our "central" repository.  The projects in Bitbucket will solely be private projects and everyone will push and pull from there.
I am open to different suggestions, but has anyone got a similar setup? If so, what caveats have you encountered?

A: I use Bitbucket for private repository hosting and one of my clients uses private repository hosting on GitHub. Another company I work with uses private repository hosting of subversion on Jira's servers.
Offsite storage of your data, if it's not the only place you have it, can reduce your risk when it comes to disaster recovery. Since you will have physical copies of the source on dev machines, and git and mercurial both keep the entire development history in the local copies, this is now a very viable solution. Unless you have gigabytes of data in a single project, and a sluggish network connection, I highly recommend this option. It's low cost, gives developers a lot of portability and flexibility, and it gives you automatic redundancy.
Depending on your level of paranoia, you may be concerned that having a third party storing your code may expose security risks, but I think that in practice this is no worse than having developers with laptops that can be used off your corporate network. Github and Bitbucket both use SSH to transfer data, so man-in-the-middle attacks have relatively low-probability of occurrence.

A: I am not a BitBucket user, but I'd suggest reading their terms and conditions with a fine tooth comb.  You need to be really sure about their terms of service, data protection and security/privacy if you're going to be storing your companies private projects on there.
I assume you've looked into having a Mecurial 'central/master' hosted on an internal machine?

A: We did something similar with ProjectLocker at my old job. Honestly, it comes down to a cost/benefit analysis - are you willing to give up the flexibility and costs of running your own Hq/Git/SVN server for the price you will be paying to BitBucket? If yes, then go for it. We never really had an uptime issue, and it was a good experience.

A: We are not BitBucket users (as a company). We run several legacy systems inhouse (CVS, SVN) and our main repository is a git system with sync'ed caches in outlying offices.
From a manager's perspective I would advise against putting your company's intellectual property on somebody else's servers, unless you don't have adequate IT facilities in-house. This code is your company's lifeblood. This should not be about money, but about protecting your IP.

A: I'd say it definitely comes down to a cost analysis of which is cheaper; running your own server (or a VM instance) or sticking it elsewhere.
Also, if the company already has network shared folders set up, you might want to consider using Git, because you could turn that network shared folder into your 'remote' repository, with something like git init --bare, and the network share permissions would already be in place for the users. Then each user could just add the shared folder as a remote with git remote add origin file:///some/shared/folder  (that might not be the exact syntax for a file referenced share, I'd google it for the exact syntax).
I do basically this at home to manage my personal projects; I have a NAS drive on my home lan that has my 'remote' repos on it, then I can get to them from my various PCs and laptops across a Windows mapped drive letter.

A: I join the other programmers on this one: Think hard about giving away your code.
For me it would only be an option to outsource the VCS if you really don't have the manpower and/or knowledge to host your own repository (mean: including backups and maintenance). If you already have shared network folders with regular backups, you could start using them and get the backup without additional cost.

A: I've used BitBucket for a little while and I've found it is a pretty good service. I don't think there will be any issues with privacy or security.
That being said, if you feel uncomfortable hosting your company's code on someone else's servers, you can set up a mercurial repository to be accessed over ssh on one of your company's servers. See http://mercurial.selenic.com/wiki/SharedSSH and http://blog.mixu.net/2010/10/04/setting-up-private-ssh-based-mercurial-repo-hosting-on-centos/.

A: Bitbucket is good for open source project.
If this project will be proprietary, I'd suggest hosting your own code. It is not that expensive to host it yourself, if you already have an IT setup. Just find a fair server and deploy your code.
mercurial is easy to configure.
good luck and enjoy.
Mercurial is really nice. Miss it :(

A: Well for a company I would prefer make sure that the authoritative repo of the project be on a private server, even if you have an always-up-to-date clone on bitbucket, just to be sure.
I would recommand installing Rhodecode on a private local server machine (for quick access), then have a script update bitbucket regularly, if you want. Keep several clones at different places anyway, you never know.


text:
Q: Why does my heroku application data keep resetting its data? I have a Heroku application that edits and creates json files, I have noticed that after a few hours the data stored in the json files have been reset back to the default, more specifically the last state that I pushed. I am not totally sure about files it creates, I am testing that as I speak/type. The json files are of a normal/reasonable size, and the site could be totally inactive, and upon reloading the site its clear the json file has been reset.
I am using get_file_contents() and set_file_contents() as well as fopen(), fwrite(), and fclose()
There aren't any errors in the PHP, and like I previously mentioned, the site has been completely inactive when this happens.
So WHY TF do my files keep getting reset ?!?!?

A: https://help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted

The Heroku filesystem is ephemeral - that means that any changes to
the filesystem whilst the dyno is running only last until that dyno is
shut down or restarted. Each dyno boots with a clean copy of the
filesystem from the most recent deploy. This is similar to how many
container based systems, such as Docker, operate.
In addition, under normal operations dynos will restart every day in a process known as "Cycling".

This is expected. If you are using Heroku Dynos and need to store files, the recommended approach is to use something like AWS S3 or Digital Ocean Spaces


text:
Q: How to keep current view in ViewFlipper when changing orientation Is there any good way of keeping the current view in the ViewFlipper while sill being able to load the layout-port folder? Maybe with onRetainNonConfigurationInstance()? If so, how would I go about implementing it? I tried someones solution of putting:
android:configChanges="orientation|keyboardHidden"

in the Manifest.
The problem with that is that Android then ignores my layout-port folder which rearranges the input field and buttons.
--Update--
Here is the code I have with hooked82's code added. I added the parts that are throwing the error:
public class AtriumMain extends Activity {
    Login login = new Login();

    String username, password;
    EditText user, pass, serverName, propertyID;

    Context context;
    CharSequence text;
    int duration, settingsClicks, doneClicks;

    final int WRONG_SETTINGS_DIALOG = 0;
    final int SET_SETTINGS_DIALOG = 1;

    LayoutInflater inflater;

    View failed_login, wrong_settings, card1, card2, set_settings;
    Button loginButton, settingsButton, doneButton, checkServer, yes_button, no_button, ok_button;
    ImageView failed_login_image, wrong_settings_image, set_settings_image;
    TextView failed_login_errorText, wrong_settings_errorText, set_settings_errorText;
    Boolean correctSettings;
    ViewFlipper flipper;
    Resources res;
    Application app;
    OutputStreamWriter settings_outstream;
    InputStream settings_instream;
    Toast failed_login_errorMessage;
    Dialog wrong_settings_errorMessage, set_settings_errorMessage;
    Builder test;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null)
        {
            int flipperPosition = savedInstanceState.getInt("CARD_NUMBER");
            flipper.setDisplayedChild(flipperPosition);
        }

        setContentView(R.layout.login);

        context = getApplicationContext();
        res = getResources();
        app = ((AtriumApplication)this.getApplication());

        inflater = getLayoutInflater();
        failed_login = inflater.inflate(R.layout.failed_login, (ViewGroup) findViewById(R.id.failed_login));
        wrong_settings = inflater.inflate(R.layout.wrong_settings, (ViewGroup) findViewById(R.id.wrong_settings));
        set_settings = inflater.inflate(R.layout.set_settings, (ViewGroup) findViewById(R.id.set_settings));

        loginButton = (Button)findViewById(R.id.login);
        settingsButton = (Button)findViewById(R.id.settings);
        doneButton = (Button)findViewById(R.id.done);
        checkServer = (Button)findViewById(R.id.check_server);

        //((Button)findViewById(R.id.login)).setOnClickListener(mAddListener);

        user = (EditText)findViewById(R.id.username);
        pass = (EditText)findViewById(R.id.password);

        serverName = (EditText)findViewById(R.id.serverName);
        propertyID = (EditText)findViewById(R.id.propertyId);

        flipper=(ViewFlipper)findViewById(R.id.cards);

        failed_login_image = (ImageView) failed_login.findViewById(R.id.failed_login_image);
        failed_login_image.setImageResource(R.drawable.warning2);

        failed_login_errorText = (TextView) failed_login.findViewById(R.id.text);
        failed_login_errorText.setText(res.getString(R.string.failed_login));

        failed_login_errorMessage = new Toast(context);
        failed_login_errorMessage.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        failed_login_errorMessage.setDuration(Toast.LENGTH_LONG);
        failed_login_errorMessage.setView(failed_login);

        loginButton.setOnClickListener(loginListener);
        settingsButton.setOnClickListener(settingsListener);
        doneButton.setOnClickListener(doneListener);
        checkServer.setOnClickListener(checkServerListener);

        settingsClicks = 0;
        doneClicks = 0;

        if ((((AtriumApplication)app).getCorrectSettings()))
        {
            doneButton.getBackground().setColorFilter(new LightingColorFilter(0xFF0000FF, 0xFF000010));
        }
        else
        {
            doneButton.getBackground().setColorFilter(new LightingColorFilter(0xFFFF1010, 0xFFAA0000));
            showDialog(SET_SETTINGS_DIALOG);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState)
    {
        int position = flipper.getDisplayedChild();
        savedInstanceState.putInt("CARD_NUMBER", position);
    }

And here is the Logcat output from around where the error happened:
08-20 11:23:52.730: VERBOSE/WindowManager(293): Preventing status bar from hiding by policy
08-20 11:23:52.740: VERBOSE/WindowManager(293): Preventing status bar from hiding by policy
08-20 11:23:52.760: VERBOSE/WindowManager(293): Preventing status bar from hiding by policy
08-20 11:23:52.770: VERBOSE/WindowManager(293): Preventing status bar from hiding by policy
08-20 11:23:52.790: VERBOSE/WindowManager(293): Preventing status bar from hiding by policy
08-20 11:23:52.810: VERBOSE/WindowManager(293): Preventing status bar from hiding by policy
08-20 11:23:52.820: VERBOSE/WindowManager(293): Preventing status bar from hiding by policy
08-20 11:23:52.830: INFO/SurfaceFlinger(223): id=6705 Removed Starting com.szymon.atrium idx=4 Map Size=5
08-20 11:23:52.830: VERBOSE/WindowManager(293): Preventing status bar from hiding by policy
08-20 11:23:52.830: INFO/SurfaceFlinger(223): id=6705 Removed Starting com.szymon.atrium idx=-2 Map Size=5
08-20 11:23:52.840: VERBOSE/WindowManager(293): Preventing status bar from hiding by policy
08-20 11:23:52.860: VERBOSE/WindowManager(293): Preventing status bar from hiding by policy
08-20 11:23:52.870: VERBOSE/WindowManager(293): Preventing status bar from hiding by policy
08-20 11:23:52.890: VERBOSE/WindowManager(293): Preventing status bar from hiding by policy
08-20 11:23:54.010: DEBUG/HierarchicalStateMachine(293): handleMessage: E msg.what=83
08-20 11:23:54.010: DEBUG/HierarchicalStateMachine(293): processMsg: ConnectedState
08-20 11:23:54.010: DEBUG/WifiStateMachine(293): ConnectedState{ what=83 when=-4ms arg1=936 }
08-20 11:23:54.030: DEBUG/HierarchicalStateMachine(293): handleMessage: X
08-20 11:23:57.030: DEBUG/HierarchicalStateMachine(293): handleMessage: E msg.what=83
08-20 11:23:57.030: DEBUG/HierarchicalStateMachine(293): processMsg: ConnectedState
08-20 11:23:57.030: DEBUG/WifiStateMachine(293): ConnectedState{ what=83 when=-4ms arg1=936 }
08-20 11:23:57.050: DEBUG/HierarchicalStateMachine(293): handleMessage: X
08-20 11:23:57.480: DEBUG/dalvikvm(30999): GC_EXPLICIT freed 1181K, 30% free 14894K/21255K, paused 3ms+3ms
08-20 11:24:00.000: DEBUG/KeyguardUpdateMonitor(293): received broadcast android.intent.action.TIME_TICK
08-20 11:24:00.000: DEBUG/KeyguardUpdateMonitor(293): handleTimeUpdate
08-20 11:24:00.050: DEBUG/HierarchicalStateMachine(293): handleMessage: E msg.what=83
08-20 11:24:00.050: DEBUG/HierarchicalStateMachine(293): processMsg: ConnectedState
08-20 11:24:00.050: DEBUG/WifiStateMachine(293): ConnectedState{ what=83 when=-3ms arg1=936 }
08-20 11:24:00.070: DEBUG/HierarchicalStateMachine(293): handleMessage: X
08-20 11:24:01.070: INFO/OrientationDebug(293): [pwm] in MyOrientationListener.onOrientationChanged() rotation=1  mFancyRotationAnimation=0   now call mWindowManager.setRotation()
08-20 11:24:01.070: INFO/OrientationDebug(293): [wms] in setRotation() rotation=1 alwaysSendConfiguration=false animFlags=0
08-20 11:24:01.070: INFO/OrientationDebug(293): [wms] in setRotation() now call setRotationUnchecked()
08-20 11:24:01.070: INFO/OrientationDebug(293): [pwm] rotationForOrientationLw(), orientation=-1 lastRotation=2 userRotation=3
08-20 11:24:01.070: INFO/OrientationDebug(293): [pwm] useSensorForOrientationLp(), return true #2
08-20 11:24:01.070: INFO/OrientationDebug(293): [pwm] in rotationForOrientationLw(), return #13
08-20 11:24:01.070: VERBOSE/WindowOrientationListener(293): > Orientation changed!  rotation=1
08-20 11:24:01.070: VERBOSE/WindowOrientationListener(293): Result: rotation=1, confidence=[0.0, 1.0, 0.0, 0.0], timeDeltaMS=54.104
08-20 11:24:01.240: INFO/SurfaceFlinger(223): id=6709(1638) createSurface 0x14c93c for pid 0 (1280x800),2 flag=0, FreezeSurface
08-20 11:24:01.280: INFO/OrientationDebug(293): [wms] in setRotationUncheckedLocked(), Setting rotation to 1   The rotation is came from PWM.rotationForOrientationLw()
08-20 11:24:01.280: DEBUG/SurfaceFlinger(223): mCurrentState.orientation:1 mDrawingState.orientation:2
08-20 11:24:01.280: DEBUG/TvoutSystem(293): bool android::TvoutSystem::TvoutSetRotation(int)
08-20 11:24:01.280: DEBUG/TvoutSystem(293): bool android::TvoutSystem::TvoutGetCableStatus()
08-20 11:24:01.280: DEBUG/TvoutService(230): virtual bool android::TvoutService::TvoutGetCableStatus()
08-20 11:24:01.280: DEBUG/TvoutService(Java)(293): TvoutGetCableStatus() : false
08-20 11:24:01.280: INFO/WindowManager(293): Setting rotation to 1, animFlags=0
08-20 11:24:01.280: INFO/ActivityManager(293): Config changed: { scale=1.0 imsi=0/0 loc=en_US touch=3 keys=1/1/2 nav=1/2 orien=P layout=0x10000014 uiMode=0x11 seq=291 FlipFont=0}
08-20 11:24:01.290: VERBOSE/WindowManager(293): Preventing status bar from hiding by policy
08-20 11:24:01.320: VERBOSE/WindowOrientationListener(293): > Orientation changed!  rotation=1
08-20 11:24:01.320: VERBOSE/WindowOrientationListener(293): Result: rotation=1, confidence=[0.0, 1.0, 0.0, 0.0], timeDeltaMS=54.104
08-20 11:24:01.320: INFO/WindowManager(293): Putting input method here!
08-20 11:24:01.320: DEBUG/WindowManager(293):     w.mAttrs.token=ActivityRecord{41811888 com.szymon.atrium/.AtriumMain}
08-20 11:24:01.320: DEBUG/WindowManager(293):     w.mToken=AppWindowToken{427877c0  token=ActivityRecord{41811888 com.szymon.atrium/.AtriumMain}}
08-20 11:24:01.320: DEBUG/WindowManager(293):     token=AppWindowToken{427877c0 token=ActivityRecord{41811888 com.szymon.atrium/.AtriumMain}}
08-20 11:24:01.320: INFO/SurfaceFlinger(223): id=6707 Removed com.szymon.atrium/com.szymon.atrium.AtriumMain idx=2 Map Size=5
08-20 11:24:01.320: INFO/WindowManager(293): Placing input method @5
08-20 11:24:01.330: INFO/SurfaceFlinger(223): id=6707 Removed com.szymon.atrium/com.szymon.atrium.AtriumMain idx=-2 Map Size=5
08-20 11:24:01.330: ERROR/TelephonyManager(22015): Hidden constructor called more than once per process!
08-20 11:24:01.330: INFO/WindowManager(293): Placing input method @1
08-20 11:24:01.340: DEBUG/MiniModeAppsPanel(430): ACTION_CONFIGURATION_CHANGED
08-20 11:24:02.140: VERBOSE/WindowOrientationListener(293): rotation : 1   Angle: 90   tilt: 2
08-20 11:24:03.070: DEBUG/HierarchicalStateMachine(293): handleMessage: E msg.what=83
08-20 11:24:03.070: DEBUG/HierarchicalStateMachine(293): processMsg: ConnectedState
08-20 11:24:03.070: DEBUG/WifiStateMachine(293): ConnectedState{ what=83 when=-4ms arg1=936 }
08-20 11:24:03.070: DEBUG/HierarchicalStateMachine(293): handleMessage: X
08-20 11:24:03.070: WARN/WindowManager(293): Window freeze timeout expired.
08-20 11:24:03.070: WARN/WindowManager(293): Force clearing orientation change: Window{407d1208 InputMethod paused=false}
08-20 11:24:03.390: WARN/InputConnectionWrapper.ICC(439): Timed out waiting on IInputContextCallback
08-20 11:24:03.420: WARN/Resources(439): Converting to boolean: TypedValue{t=0x3/d=0x15 "true" a=-1}
08-20 11:24:03.430: WARN/Resources(439): Converting to boolean: TypedValue{t=0x3/d=0x15 "true" a=-1}
08-20 11:24:03.590: VERBOSE/WindowOrientationListener(293): rotation : 1   Angle: 90   tilt: 0
08-20 11:24:05.070: VERBOSE/WindowOrientationListener(293): rotation : 1   Angle: 90   tilt: -2
08-20 11:24:05.430: WARN/InputConnectionWrapper.ICC(439): Timed out waiting on IInputContextCallback
08-20 11:24:05.450: ERROR/TabletStatusBar(430): closing mini mode apps panel
08-20 11:24:05.490: DEBUG/dalvikvm(439): GC_FOR_ALLOC freed 1756K, 38% free 10279K/16391K, paused 27ms
08-20 11:24:06.080: DEBUG/HierarchicalStateMachine(293): handleMessage: E msg.what=83
08-20 11:24:06.080: DEBUG/HierarchicalStateMachine(293): processMsg: ConnectedState
08-20 11:24:06.080: DEBUG/WifiStateMachine(293): ConnectedState{ what=83 when=-4ms arg1=936 }
08-20 11:24:06.090: DEBUG/HierarchicalStateMachine(293): handleMessage: X
08-20 11:24:06.290: WARN/WindowManager(293): App freeze timeout expired.
08-20 11:24:06.290: WARN/WindowManager(293): Force clearing freeze: AppWindowToken{427877c0 token=ActivityRecord{41811888 com.szymon.atrium/.AtriumMain}}
08-20 11:24:06.300: INFO/SurfaceFlinger(223): id=6710(1639) createSurface for pid 0 (800x2560),-1 flag=131072, BlackSurface
08-20 11:24:06.300: INFO/SurfaceFlinger(223): id=6711(1640) createSurface for pid 0 (1600x1280),-1 flag=131072, BlackSurface
08-20 11:24:06.300: INFO/SurfaceFlinger(223): id=6712(1641) createSurface for pid 0 (800x2560),-1 flag=131072, BlackSurface
08-20 11:24:06.310: INFO/SurfaceFlinger(223): id=6713(1642) createSurface for pid 0 (1600x1280),-1 flag=131072, BlackSurface
08-20 11:24:06.370: DEBUG/dalvikvm(15392): GC_CONCURRENT freed 458K, 37% free 7282K/11399K, paused 7ms+8ms
08-20 11:24:06.370: DEBUG/dalvikvm(20484): GC_EXPLICIT freed 9K, 5% free 6215K/6531K, paused 3ms+2ms
08-20 11:24:06.560: VERBOSE/WindowOrientationListener(293): rotation : 1   Angle: 90   tilt: -3
08-20 11:24:06.740: INFO/SurfaceFlinger(223): id=6709 Removed FreezeSurface idx=9 Map Size=4
08-20 11:24:06.740: INFO/SurfaceFlinger(223): id=6710 Removed BlackSurface idx=5 Map Size=4
08-20 11:24:06.740: INFO/SurfaceFlinger(223): id=6711 Removed BlackSurface idx=5 Map Size=4
08-20 11:24:06.750: INFO/SurfaceFlinger(223): id=6712 Removed BlackSurface idx=5 Map Size=4
08-20 11:24:06.750: INFO/SurfaceFlinger(223): id=6712 Removed BlackSurface idx=-2 Map Size=4
08-20 11:24:06.750: INFO/SurfaceFlinger(223): id=6711 Removed BlackSurface idx=-2 Map Size=4
08-20 11:24:06.750: INFO/SurfaceFlinger(223): id=6710 Removed BlackSurface idx=-2 Map Size=4
08-20 11:24:06.750: INFO/SurfaceFlinger(223): id=6709 Removed FreezeSurface idx=-2 Map Size=4
08-20 11:24:06.750: INFO/SurfaceFlinger(223): id=6713 Removed BlackSurface idx=5 Map Size=4
08-20 11:24:06.750: INFO/OrientationDebug(293): [pwm] rotationForOrientationLw(), orientation=-1 lastRotation=1 userRotation=3
08-20 11:24:06.750: INFO/OrientationDebug(293): [pwm] useSensorForOrientationLp(), return true #2
08-20 11:24:06.750: INFO/OrientationDebug(293): [pwm] in rotationForOrientationLw(), return #13
08-20 11:24:06.760: INFO/SurfaceFlinger(223): id=6713 Removed BlackSurface idx=-2 Map Size=4
08-20 11:24:08.030: VERBOSE/WindowOrientationListener(293): rotation : 1   Angle: 90   tilt: -3
08-20 11:24:08.460: DEBUG/dalvikvm(293): GC_EXPLICIT freed 1140K, 16% free 116574K/137223K, paused 13ms+19ms
08-20 11:24:09.090: DEBUG/HierarchicalStateMachine(293): handleMessage: E msg.what=83
08-20 11:24:09.090: DEBUG/HierarchicalStateMachine(293): processMsg: ConnectedState
08-20 11:24:09.090: DEBUG/WifiStateMachine(293): ConnectedState{ what=83 when=-4ms arg1=936 }
08-20 11:24:09.110: DEBUG/HierarchicalStateMachine(293): handleMessage: X
08-20 11:24:09.500: VERBOSE/WindowOrientationListener(293): rotation : 1   Angle: 91   tilt: 2
08-20 11:24:11.380: DEBUG/dalvikvm(20510): GC_EXPLICIT freed 20K, 5% free 6220K/6531K, paused 2ms+9ms
08-20 11:24:12.120: DEBUG/HierarchicalStateMachine(293): handleMessage: E msg.what=83
08-20 11:24:12.120: DEBUG/HierarchicalStateMachine(293): processMsg: ConnectedState
08-20 11:24:12.120: DEBUG/WifiStateMachine(293): ConnectedState{ what=83 when=-4ms arg1=936 }
08-20 11:24:12.130: DEBUG/HierarchicalStateMachine(293): handleMessage: X

I hope this helps.

A: Try saving which tab you're on in the ViewFlipper when your screen orientation changes by overriding onSaveInstanceState
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    int position = flipper.getDisplayedChild();
    savedInstanceState.putInt("TAB_NUMBER", position);
}

Then in your onCreate, try the following
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        int flipperPosition = savedInstanceState.getInt("TAB_NUMBER");
        flipper.setDisplayedChild(flipperPosition);
    }
}

Make sure that you call the setDisplayedChild() method on flipper only after you have initialized flipper, by doing something like, for example,
flipper = (ViewFlipper) findViewById(R.id.flipper);
in your onCreate() method. Not doing so might result in a crash.

A: There is no other way than saving your application state by yourself and loading it after screen orientation change. You can override an onRetainNonConfigurationInstance() method or if you use API 11 or newer use pair of setRetainInstance(boolean) and getLastNonConfigurationInstance()
Here is also an answer whether to use retaining instance or saving it.
There is also possibility that you will inflate your new port-layout by yourself but I think it's not a good idea.


text:
Q: Can I remove a specific $post from $posts if I know the ID of the $post? If my query returns $posts which contain 3 posts with ids of 1,2 and 3, can I somehow remove the $post with id of 2 so that when I loop through $posts I only output the posts with id of 1 and 3?

A: after fetching to $posts, you can filter
$posts = $posts->filter(function ($value, $key) {
    return $value->id != 2;
});

see this:
https://laravel.com/docs/5.7/collections#method-filter

A: Using blade:
@foreach($posts as $post)
   @if(!$post->id == 2 )
     {{$post->title}}
   @endif
@endforeach


text:
Q: Wordpress, all pages with thumbnail Can we get a list (or ID) of only those pages of a wordpress website for which we have set a Featured Image?
Thanks

A: This will grab all pages with a featured image and store it in a variable.
$loop = new WP_Query( array( 'post_type' => 'page', 'meta_key' => '_thumbnail_id' ) );


text:
Q: Angular/Ionic CORS error with Authorization header I am building an Ionic app (angular 4) and i want to consume an API which is build with C# on an IIS 10.
When at first did a POST request like that:
this.http.post(my_url, my_credentials, { headers = new HttpHeaders({
    'Content-Type': 'application/x-www-form-urlencoded',
  })
});

i got a cors error 404 message:
Failed to load https://some_url/api/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

After some research i added on web.config
access-control-allow-origin: *

and that solved the CORS issues.
After that i retrieve my access token and wanted to use it for others requests
so i made another post request with authorization header :
this.http.post(my_url, my_body, { headers = new HttpHeaders({
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Bearer ' + token
  })
});

and then i got the same error as previous.
So, to sum up those requests are on the same app. The first request work great but the second no.
What's the extra configuration has to put on the server tou accept the extra Authorization header?

A: try to add to web.config:
Access-Control-Allow-Methods: POST, GET (..and more Methods that you need.)
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept

I'm not sure if it will work, but you can give it a try :P

A: You might want to add proxy.conf.json to redirect your app URL's to your appropriate server URL's. The following article might help:
https://juristr.com/blog/2016/11/configure-proxy-api-angular-cli/

A: I use, and works for an asp.net core backend
const headers = new HttpHeaders()
   .set('Content-Type', 'application/json')
   .set('Accept', 'application/json')
   .set('Authorization', 'Bearer ' + token);

this.http.post(my_url, my_credentials, headers)

Don't remember if this is valid for http, I think it is only valid foy httpClient