text:
Q: Jaxb Binding with List returned in web service response I am developing a jax-ws client, I am trying to handle an ArrayList returned as a response, but i had always empty list.
Returned list is NOT empty, I am sure that WebService provider is returning data in that list, I checked that using SoapUI.
there is generated client related files:
 @XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfFact", propOrder = {
    "item"
})
public class ArrayOfFact {

    protected List<Fact> item;
 public List<Fact> getItem() {
        if (item == null) {
            item = new ArrayList<Fact>();
        }
        return this.item;
    }

}

ArrayOfFacts class generated by wsimport it's the same class generated before.
The XML response I receive in SOAPUI :
 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <ReleveResponse xmlns="http://www.test.ma/webservices/WSTestServe/">
         <ReleveResult>
            <ConversationId>conId</ConversationId>
            <Status>
               <WSStatus>OK</WSStatus>
               <WSCode>OK</WSCode>
               <WSMessage>Le traitement s'est bien déroulé!</WSMessage>
            </Status>
            <myReleveInfo>
               <NomCli>El Karkouri youssef</NomCli>
               <NbrImp>7</NbrImp>
               <Facture>
                  <Fact>
                     <RefImp>FACT-124</RefImp>
                     <MntImp>230</MntImp>
                     <LibImp>label 1</LibImp>
                     <FlgPaiObl>1</FlgPaiObl>
                  </Fact>
                  <Fact>
                     <RefImp>FACT-125</RefImp>
                     <MntImp>260</MntImp>
                     <LibImp>label 0</LibImp>
                     <FlgPaiObl>0</FlgPaiObl>
                  </Fact>
                  <Fact>
                     <RefImp>FACT-126</RefImp>
                     <MntImp>360</MntImp>
                     <LibImp>label 2</LibImp>
                     <FlgPaiObl>0</FlgPaiObl>
                  </Fact>
                  <Fact>
                     <RefImp>FACT-127</RefImp>
                     <MntImp>236</MntImp>
                     <LibImp>label 3</LibImp>
                     <FlgPaiObl>0</FlgPaiObl>
                  </Fact>
                  <Fact>
                     <RefImp>FACT-128</RefImp>
                     <MntImp>2310</MntImp>
                     <LibImp>label 4</LibImp>
                     <FlgPaiObl>1</FlgPaiObl>
                  </Fact>
                  <Fact>
                     <RefImp>FACT-129</RefImp>
                     <MntImp>2450</MntImp>
                     <LibImp>label 0</LibImp>
                     <FlgPaiObl>1</FlgPaiObl>
                  </Fact>
                  <Fact>
                     <RefImp>FACT-167</RefImp>
                     <MntImp>2380</MntImp>
                     <LibImp>label 1125</LibImp>
                     <FlgPaiObl>0</FlgPaiObl>
                  </Fact>
               </Facture>
            </myReleveInfo>
         </ReleveResult>
      </ReleveResponse>
   </soapenv:Body>
</soapenv:Envelope>

The JSON response I receive whwn I test the jax-ws client :
{
"status": "OK",
"language": "en",
"data": {
    "conversationId": {
        "name": "{http://www.test.ma/webservices/WSTestServe/}ConversationId",
        "declaredType": "java.lang.String",
        "scope": "ma.comp.company.client.testserv.AbstractBean",
        "value": "conId",
        "nil": false,
        "globalScope": false,
        "typeSubstituted": false
    },
    "status": {
        "name": "{http://www.test.ma/webservices/WSTestServe/}Status",
        "declaredType": "ma.comp.company.client.testserv.StatusBeanOut",
        "scope": "ma.comp.company.client.testserv.AbstractBeanOutOfReleveInfo",
        "value": {
            "wsstatus": "OK",
            "wscode": "OK",
            "wsmessage": "Le traitement s'est bien déroulé!"
        },
        "nil": false,
        "globalScope": false,
        "typeSubstituted": false
    },
    "myReleveInfo": {
        "nomCli": {
            "name": "{http://www.test.ma/webservices/WSTestServe/}NomCli",
            "declaredType": "java.lang.String",
            "scope": "ma.comp.company.client.testserv.ReleveInfo",
            "value": "El Karkouri youssef",
            "nil": false,
            "globalScope": false,
            "typeSubstituted": false
        },
        "nbrImp": {
            "name": "{http://www.test.ma/webservices/WSTestServe/}NbrImp",
            "declaredType": "java.lang.String",
            "scope": "ma.comp.company.client.testserv.ReleveInfo",
            "value": "7",
            "nil": false,
            "globalScope": false,
            "typeSubstituted": false
        },
        "facture": {
            "name": "{http://www.test.ma/webservices/WSTestServe/}Facture",
            "declaredType": "ma.comp.company.client.testserv.ArrayOfFact",
            "scope": "ma.comp.company.client.testserv.ReleveInfo",
            "value": {
                "item": []
            },
            "nil": false,
            "globalScope": false,
            "typeSubstituted": false
        }
    }
},
"message": null

}
Fact class:
    @XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Fact", propOrder = {
    "refImp",
    "mntImp",
    "libImp",
    "flgPaiObl"
})
public class Fact {

    @XmlElementRef(name = "RefImp", namespace = "http://www.test.ma/webservices/WSTesServe/", type = JAXBElement.class, required = false)
    protected JAXBElement<String> refImp;
    @XmlElementRef(name = "MntImp", namespace = "http://www.test.ma/webservices/WSTesServe/", type = JAXBElement.class, required = false)
    protected JAXBElement<String> mntImp;
    @XmlElementRef(name = "LibImp", namespace = "http://www.test.ma/webservices/WSTesServe/", type = JAXBElement.class, required = false)
    protected JAXBElement<String> libImp;
    @XmlElementRef(name = "FlgPaiObl", namespace = "http://www.test.ma/webservices/WSTesServe/", type = JAXBElement.class, required = false)
    protected JAXBElement<String> flgPaiObl;

    // Getters and Setters

}

A: I fixed that by adding an xml element declaration in class ObjectFactory generated by wsimport
@XmlElementDecl(namespace = "http://www.test.ma/webservices/WSTestServe/", name = "Fact", scope = ArrayOfFact.class)
public JAXBElement<Fact> createArrayOfFactItem(Fact value) {
    return new JAXBElement<Fact>(_ReleveInfoFact_QNAME, Fact.class, ArrayOfFact.class, value);
}

And the list of items should be annotated by :
@XmlElementRef(name = "Fact", namespace = "http://www.test.ma/webservices/WSTestServe/", type = JAXBElement.class, required = false)
protected List<Fact> item;


text:
Q: linuz-linux can't be found in efi-bootmanager on iMac Ive just installed a fresh new instance of arch-linux on my old iMac.
Unfortunately, the apple default efi bootloader isn't be able to load the efi-entry.
My partitions are:
#1 EFI
#2 Mac OS X
#3 Rescure Mac
#4 boot (my /boot-partition for linux)
#5 encrypted

partition 5 is my enrypted partition, which contains the lvm volume-group which contains 3 partitions (root, home and swap).
I've mounted efi (#1) on /boot/efi. In boot, there is my kernel-image vmlinuz-linux. In /boot/efi/loader/entries/arch-encrypted.conf, I've edited the file so the option "linux" has /vmlinuz-linux. Now it looks like that:
title          Arch Linux
linux          /vmlinuz-linux
initrd         /initramfs-linux.img
options        encrypteddevice=UUID=<UUID of partition #5>:lvm root=/dev/mapper/vg--base-lv--root quiet rw

But now when Im rebooting my system, arch isn't booting but an error message will get printed containing "\vmlinuz-linux can't be found".
I guess this is so because the linux-image is located on an different partition but this efi-entry points to the efi-partition where the entry is located itselv.
Can anybody help me with this please?

A: You probably answered your own question. The paths in the .conf file are relative to the root of the ESP, and no other partitions are known at this stage. vmlinuz-linux (et al.) are put in /boot by pacman, and if /boot/efi (the ESP) is mounted under /boot they are on different partitions.
You could merge the partitions so that the ESP is mounted on boot. For other solutions, see EFI System Partition.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to filter the duplicate objects inside an array I am using underscore.js plugin for this my code
I tried here jsfiddle
var basket=[{
            "basketitems":[{"items":[]}],
            "itemdetails":[{
                "amountPledged": "100",
                "bActivity": "Handloom Work",
                "bCity": "Nadia"
                },
                {
                "amountPledged": "100",
                "bActivity": "Saree Business",
                "bCity": "Nadia"
                },
                {
                "amountPledged": "100",
                "bActivity": "Saree Business",
                "bCity": "Nadia"
                }],
            "cartdetails":[],
            "paymentdetails":[],
            "userdetails":[]
            }];

var tempbasket=_.uniq(basket);
document.body.innerHTML = JSON.stringify(tempbasket);

Help me to fix this

A: For example,
basket[0].itemdetails = _.uniq(basket[0].itemdetails, JSON.stringify)

http://jsfiddle.net/g5TD9/3/
To filter by a specific field, pass a function that takes an object and returns that field:
_.uniq(itemdetails, function(x) { return x.bCity })

Docs: uniq

A: Two things are there:
1. First of all, you should do:
basket[0].itemdetails=_.uniq(basket[0].itemdetails);
document.body.innerHTML = JSON.stringify(basket);

Not:
var tempbasket=_.uniq(basket);
document.body.innerHTML = JSON.stringify(tempbasket);

2. Second thing is, as your basket[0].itemdetails is array of objects, so that _.unique will not work there. Becayse two different objects in javascript can not be equal.
Example:
var x = {a:5};
var y = {a:5};

console.log(x == y); // false;

So, this trick will not work here. You will have to do this manually. Good luck!
===== Edit =====
Here is working solution:
basket[0].itemdetails = _.unique(basket[0].itemdetails, function(item,key,a){
    return item.bActivity;
});

console.log(basket[0].itemdetails);

jsfiddle: http://jsfiddle.net/F4Q4u/3/
Enjoy JScripting!!

A: var tempbasket=_.uniq(basket[0].itemdetails.map(function(d){return JSON.stringify(d)}));

A: You can make a copy of the existing JSON and iterate over it to check the duplicates.
var basketCopy = JSON.parse( JSON.stringify( basket ) );
basketCopy[0].itemdetails = [];
_.each(basket[0].itemdetails, function(item) {
    if(!_.findWhere(basketCopy[0].itemdetails, item)) {
        basketCopy[0].itemdetails.push(item);
    }
});
console.log(basketCopy); // Your unique itemdetails list

A: I've never used underscore myself, but taking a (not so) wild guess, it checks if the first indexOf the item is the same as its actual index. Because JS treats logically identical objects as different objects, it will also treat them as different. You might have to write your own unique() function to properly deal with objects.


text:
Q: How to solve $x^2+3x+17\equiv 0\pmod{315}$? I'm trying to do this question, and I have no clue how to get started, I first tried to factor $315$ as $3^2, 5$ and $7$ and solve three sets of congruency but I again got stuck with the smaller cases, please help me with this
$$x^2+3x+17\equiv 0\pmod{315}$$

A: Hint
$$x^2+3x+17\equiv 0\pmod{5,7,9}$$
can only have $5,7$ or $9$ solutions. Try all of them.
Alternately:
$$x^2+3x+17\equiv 0\pmod{315} \Leftrightarrow \\
4x^2+12x+68 \equiv 0\pmod{315} \Leftrightarrow \\
(2x+3)^2 \equiv 256=16^2 \pmod{315}$$
You can immediatelly see that $16,-16$ are square roots of $256$, which immediately tells you that there are at least 2 solutions. Since $3,5,7$ do not divide $256$ it is easy to deduce that there must be 8 solutions, you just need to find the rest.

A: If you don't want to "try all of them" as N.S. suggests, you can do it this way.  The quadratic formula applied to  $x^2 + 3x + 17 = 0$ yields
$$ x = \dfrac{-3 \pm \sqrt{-59}}{2}$$
This will actually work modulo any odd number (it needs to be odd because you can't divide by $2$ modulo an even number): if $-59$ is a square mod $n$, it will give you solutions mod $n$ (i.e. if $y^2 \equiv -59 \mod n$,
$x \equiv 2^{-1} (-3 + y)$ will be a solution mod $n$), and if $-59$ is not a square mod $n$ there will be no solutions.
$-59 \equiv 1 \mod 5$.  That's a square, and the square roots of $1$ mod $5$ are $1$ and $4$.  So  $y \equiv 1$ or $4 \mod 5$, and correspondingly
$x \equiv 2^{-1}(-3 + 1) \equiv 4$ or $3 \mod 5$.
$-59 \equiv 4 \mod 7$.  The square roots of $4$ mod $7$ are $2$ and $5$.
So $y \equiv 2$ or $5 \mod 7$, and correspondingly $x \equiv 3$ or $1 \mod 7$.
$-59 \equiv 4 \mod 9$.  The square roots of $4$ mod $9$ are $2$ and $7$.
So  $y \equiv 2$ or $7 \mod 9$, and correspondingly $x \equiv 4$ or $2 \mod 9$.
Finally, use the Chinese Remainder Theorem with your choice of the possibilities mod $5$, mod $7$ and mod $9$.

A: It's convenient to rewrite it first as $4x^2+12x+68\equiv0$ mod $315$, and then as
$$u^2\equiv-59\mod315$$
with $u=2x+3$.  Since $-59\equiv1$ mod $5$ and $4$ mod both $7$ and $9$, we have $u\equiv\pm1$ mod $5$ and $u\equiv\pm2$ mod $7$ and mod $9$.  At this point, the Chinese Remainder Theorem can be applied systematically to find the eight different values for $u$ mod $315$. But with numbers this small, it's just as easy to find the values by playing around with combinations (and, maybe, getting lucky). Here's what I mean:
By looking at numbers of the form $63k\pm2$, we easily see $u=\pm61$ as one solution and $u=\pm191$ as another (i.e., $61\equiv191\equiv1$ mod $5$). This already gives us four out of the eight solutions mod $315$. To find the other four, we might notice that the relatively small number $16$ fits the bill, so $u\equiv\pm16$ is a solution. Test-adding $63$ gives us $u\equiv\pm79$ as another.  In total, we have solutions
$$2x+3\equiv
\begin{cases}
\pm61\\
\pm191\\
\pm331\\
\pm79\\
\end{cases}\mod315$$
where we've rewritten $16$ as $16+315=331$, for reasons that will soon be apparent. From this we get
$$2x\equiv
\begin{cases}
58\\
-64\\
188\\
-194\\
328\\
-334\\
76\\
-82
\end{cases}\mod315$$
and finally, since the numbers were all "engineered" to be even,
$$x\equiv
\begin{cases}
29\\
-32\\
94\\
-97\\
164\\
-167\\
38\\
-41
\end{cases}\mod315$$
If you like, you can make all the values positive by adding $315$ to the ones that are negative, and you can sort them in ascending order to get the set $\{29,38,94,148,164,218,274,283\}$.
The takehome message is that the theory and a small amount of computation will tell you how many solutions to expect, but to find the solutions explicitly, you have to be willing to do the extra work that's called for. There are systematic algorithms that'll let you plow through to an answer, but when the numbers involved are reasonably small you can sometimes organize things to get by with a modest amount of trial and error.

A: It probably easiest to rely on the Chinese Remainder Ther and solve in $\mod 5,\mod 7$, and $\mod 9$ first.
But in general we can solve using the quadratic formula just like "regular arithmetic" provided you have very careful not to abuse concept.
$x^2+3x + 17\equiv 0 \pmod {315}$ would mean
$x \equiv \frac {-3\pm \sqrt{9-4*17}}2 \pmod {315}$
!!!IF!!! we can assume the following:
1) There is a number we can refer to as "$\frac 12$" which is not the fraction $\frac 12$ but a residue class of an integer $a$ so that $2a \equiv 1 \pmod{315}$.  Such an integer exists if and only if $\gcd(2,315)=1$.  Which is does so we can.
2) There is an residue class of an integer $b$ so that $b^2 \equiv 9-4*17\equiv -59\equiv 256\pmod {315}$.  Now we must be careful as there may be many such $b$ and not just $2$.
1) is fine we have $\gcd(315,2)=1$ and solving for $2a\equiv 1\pmod {315}$ is just a matter of noting $1 \equiv 316 =2*158$ so $"\frac 12" \equiv 158\pmod{315}$.
2) if $b^2 \equiv 256 \pmod {315}$ then $b^2 - 256=(b-160)(b+16)\equiv 0 \pmod{315}$ and $315|(b-16)(b+16)$ which work for a variety cases.  $b\equiv 16$ or $b\equiv -16$ are obvious. but we could also have $k|b-16$ and $\frac {315}k|b+16$...
So we have $x \equiv \frac {-3+b}2 \pmod {315}$ where $b$ is such that $315|(b-16)(b+16)$. (and if $-3+b$ is odd we have $x \equiv \frac {-3+b-315}2$.
Bearing in mind $\gcd(b-16,b+16)=\gcd(2b, b+16)=\gcd(32,b+16)$ is a power of $2$ so
our solutions for $b$ are
$315|b\pm 16$ and $b\equiv \pm 16$ and so x \equiv \frac {13}2; \frac {-19}2\equiv 6+158; -9-158\equiv 164; -167$.
$5|b\pm 16; 63|b\mp 16$.
If $5|b+16$ then $b\equiv 4 \pmod 5$ and $63|b-16$ so $b\equiv 16\pmod {63}$ and so $b\equiv 79\pmod{63,5} and $b\equiv 79$ and $x\equiv \frac {76}2\equiv  38$.
if $5|b-16$ then $b\equiv 1\pmod 5$ and $b\equiv -16\equiv 47\pmod {63}$. And $47 + 3*63$ will have final digit of $6$ so $b\equiv 236\equiv -79\pmod{315}\equiv $ and so $x\equiv \frac {-82}2\equiv -41$.
Or $7|b\pm 16$ and $45|b\mp 16$.
so $b\equiv 16\equiv 2\pmod 7$ and $b\equiv -16\equiv 29\pmod {45}$
Need $29 + 45k = 2+7m$ so $(28-1) +(3+6*7)k = 7m$ so $-1 + 3k=7(m-6k-4)$. If we let $k=-2$ and $m-6k-4=m+8=-1$ or $m =-9$ and $b\equiv -61$
so $x \equiv -\frac {64}2\equiv 32$
or $b\equiv -16\equiv 5\pmod 7$ and $b \equiv 16\pmod {45}$
Need $16+45k = 5+7m$ so $11 + 45k = 7m$ so $4+(42+3)k=7(m-1)$ or $4+3k=7(m-1-6k)$ so $k=1$ and $m-1-6k=m-7=1$ so $m=8$ and $b \equiv 61\pmod{315}$.
so $x\equiv 29$.
And if $9|b\pm 16$ and $35|b\mp 16$.
If $b\equiv 16\equiv 7\pmod 9$ and $b\equiv -16\equiv 19\pmod {35}$
then $7+9k = 19+35m$ or $9k = 12+35m$ or $9(k-1-4m)=3-m$ so let $m=-6$ and $k-1+24 = 1$ so $k=-22$ and $b\equiv -191$
$x \equiv -\frac {194}2 \equiv -97$.
And if $b\equiv -16\equiv 2\pmod 9$ and $b\equiv 16\pmod {35}$ we'd have
$2+9k = 16+35m$ so $9k = 14+35m$ so 9(k-1-4m)= 5-m$ so $m=-4$ and $b\equiv -124\equiv 191$ so $x \equiv 94$
so the eight solutions are $x \equiv 164,-167, 38,-41,32,29,-97,94$


text:
Q: What is the binary to decimal conversion of something with 9 bits? A byte has 8 bits. Does the 9th bit represent 2^9 = 512? Or does it start over at 2^0 = 1?
What would the decimal conversion of a binary like 101100101 be?

A:

*Or maybe it's a flag for negatives or maybe a parity bit. Maybe it's even a extra 1 to allow numbers 0-256.

Bits don't mean anything in and of themselves, they only mean what the person who originated the data say that they mean.


text:
Q: Block all IP's except HOME IP in Nginx Netdata virtual host file on Ubuntu Server 20.04 I'm running Ubuntu Server 20.04, and have successfully set up netdata. My netdata's Nginx virtual host file looks like this:
upstream backend {
   server 127.0.0.1:19999;
   keepalive 64;
}

server {

auth_basic "Protected";
auth_basic_user_file /etc/nginx/netdata-passwords;

   server_name netdata.example.com;
   location / {
     proxy_set_header X-Forwarded-Host $host;
     proxy_set_header X-Forwarded-Server $host;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_pass http://backend;
     proxy_http_version 1.1;
     proxy_pass_request_headers on;
     proxy_set_header Connection "keep-alive";
     proxy_store off;
   }

    listen 443 ssl http2; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/netdata.example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/netdata.example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;

    ssl_trusted_certificate /etc/letsencrypt/live/netdata.example.com/chain.pem; # managed by Certbot
    ssl_stapling on; # managed by Certbot
    ssl_stapling_verify on; # managed by Certbot

}

server {
    if ($host = netdata.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

proxy_pass http://backend;
     proxy_http_version 1.1;
     proxy_pass_request_headers on;
     proxy_set_header Connection "keep-alive";
     proxy_store off;
   }
}

and my stub_status.conf virtual host file looks like this:
server {
     listen 127.0.0.1:80;
     server_name 127.0.0.1;
     location /nginx_status {
        stub_status on;
    allow 127.0.0.1;
    deny all;
     }
}

What do I need to do in my virtual host file to deny all IP addresses to netdata except my home address? Any examples would be much appreciated!


text:
Q: Grab the resource contents in CasperJS or PhantomJS I see that CasperJS has a "download" function and an "on resource received" callback but I do not see the contents of a resource in the callback, and I don't want to download the resource to the filesystem.
I want to grab the contents of the resource so that I can do something with it in my script.  Is this possible with CasperJS or PhantomJS?

A: Did not realize I could grab the source from the document object like this:
casper.start(url, function() {
    var js = this.evaluate(function() {
        return document;
    });
    this.echo(js.all[0].outerHTML);
});

More info here.

A: This problem has been in my way for the last couple of days. The proxy solution wasn't very clean in my environment so I found out where phantomjs's QTNetworking core put the resources when it caches them.
Long story short, here is my gist. You need the cache.js and mimetype.js files:
https://gist.github.com/bshamric/4717583
//for this to work, you have to call phantomjs with the cache enabled:
//usage:  phantomjs --disk-cache=true test.js

var page = require('webpage').create();
var fs = require('fs');
var cache = require('./cache');
var mimetype = require('./mimetype');

//this is the path that QTNetwork classes uses for caching files for it's http client
//the path should be the one that has 16 folders labeled 0,1,2,3,...,F
cache.cachePath = '/Users/brandon/Library/Caches/Ofi Labs/PhantomJS/data7/';

var url = 'http://google.com';
page.viewportSize = { width: 1300, height: 768 };

//when the resource is received, go ahead and include a reference to it in the cache object
page.onResourceReceived = function(response) {
  //I only cache images, but you can change this
    if(response.contentType.indexOf('image') >= 0)
    {
        cache.includeResource(response);
    }
};

//when the page is done loading, go through each cachedResource and do something with it,
//I'm just saving them to a file
page.onLoadFinished = function(status) {
    for(index in cache.cachedResources) {
        var file = cache.cachedResources[index].cacheFileNoPath;
        var ext = mimetype.ext[cache.cachedResources[index].mimetype];
        var finalFile = file.replace("."+cache.cacheExtension,"."+ext);
        fs.write('saved/'+finalFile,cache.cachedResources[index].getContents(),'b');
    }
};

page.open(url, function () {
    page.render('saved/google.pdf');
    phantom.exit();
});

Then when you call phantomjs, just make sure the cache is enabled:
phantomjs --disk-cache=true test.js
Some notes:
I wrote this for the purpose of getting the images on a page without using the proxy or taking a low res snapshot. QT uses compression on certain text file resources and you will have to deal with the decompression if you use this for text files. Also, I ran a quick test to pull in html resources and it didn't parse the http headers out of the result. But, this is useful to me, hopefully someone else will find it so, modify it if you have problems with a specific content type.

A: I've found that until the phantomjs matures a bit, according to the issue 158 http://code.google.com/p/phantomjs/issues/detail?id=158 this is a bit of a headache for them.
So you want to do it anyways? I've opted to go a bit higher to accomplish this and have grabbed PyMiProxy over at https://github.com/allfro/pymiproxy, downloaded, installed, set it up, took their example code and made this in proxy.py
from miproxy.proxy import RequestInterceptorPlugin, ResponseInterceptorPlugin, AsyncMitmProxy
from mimetools import Message
from StringIO import StringIO

class DebugInterceptor(RequestInterceptorPlugin, ResponseInterceptorPlugin):

        def do_request(self, data):
            data = data.replace('Accept-Encoding: gzip\r\n', 'Accept-Encoding:\r\n', 1);
            return data

        def do_response(self, data):
            #print '<< %s' % repr(data[:100])
            request_line, headers_alone = data.split('\r\n', 1)
            headers = Message(StringIO(headers_alone))
            print "Content type: %s" %(headers['content-type'])
            if headers['content-type'] == 'text/x-comma-separated-values':
                f = open('data.csv', 'w')
                f.write(data)
            print ''
            return data

if __name__ == '__main__':
    proxy = AsyncMitmProxy()
    proxy.register_interceptor(DebugInterceptor)
    try:
        proxy.serve_forever()
    except KeyboardInterrupt:
        proxy.server_close()

Then I fire it up
python proxy.py

Next I execute phantomjs with the proxy specified...
phantomjs --ignore-ssl-errors=yes --cookies-file=cookies.txt --proxy=127.0.0.1:8080 --web-security=no myfile.js

You may want to turn your security on or such, it was needless for me currently as I'm scraping just one source. You should now see a bunch of text flowing through your proxy console and if it lands on something with the mime type of "text/x-comma-separated-values" it'll save it as data.csv. This will also save all the headers and everything, but if you've come this far I'm sure you can figure out how to pop those off.
One other detail, I've found that I've had to disable gzip encoding, I could use zlib and decompress data in gzip from my own apache webserver, but if it comes out of IIS or such the decompression will get errors and I'm not sure about that part of it.
So my power company won't offer me an API? Fine! We do it the hard way!

A: You can use Casper.debugHTML() to print out contents of a HTML resource:
var casper = require('casper').create();

casper.start('http://google.com/', function() {
    this.debugHTML();
});

casper.run();

You can also store the HTML contents in a var using casper.getPageContent(): http://casperjs.org/api.html#casper.getPageContent (available in lastest master)


text:
Q: Is there fmemopen() in ZLIB My code uses ZLIB, and it seems that there are problems in using fmemopen() and ZLIB functions afterwards...
Is there an equivalent of fmemopen() in ZLIB? Or how can I create it if no equivalent exists?

A: No there is not. Furthermore, there is no need for such a thing, since zlib provides in-memory functions for compression and decompression.

A: no, there is no such function in ZLIB
Here is a link to (per IBM) zlib functions


text:
Q: Why isn't my checkColor function running? Can anybody please help me to figure out why my checkColor function is not running for the 2nd and subsequent clicks once the requisite for the If loop it is dependent on is deemed True (which it is, according to Log)? It works for the first click, changing the button's color, and then it should in theory move from 5 to 4, and so forth, for each Click, changing the color of each button based on the assigned number to 'row'. It logs that this is indeed the case, that the 'row' and the 'someClass' object matches what I want it to, but it's not actually running. It just runs the log, but no actual change in color to the subsequent buttons. Thanks in advance.
// var playerOne = prompt("Player One: Enter your Name - You will be Blue.")
// var playerTwo = prompt("Player One: Enter your Name - You will be Red.")

var gClass = $(".G")
var fClass = $(".F")
var eClass = $(".E")
var dClass = $(".D")
var cClass = $(".C")
var bClass = $(".B")
var aClass = $(".A")

var buttons = $("button")

var row = 5
var locRow = 5
var someClass = 0
var locClass = 1
var someClassAttr = 0
var locClassAttr = 1

function returnBackgroundColor(rowIndex,colIndex){
  // console.log($(colIndex[rowIndex]).prop("background-color"));
  // console.log(rowIndex);
  return($(colIndex[rowIndex]).prop("background-color"));
}

function changeColor(locRow, someClass){
  someClass.eq(row).css("background-color","red");
}

function checkColor(locRow ,someClass){
    for (locRow; locRow > -1; locRow--) {
      if (returnBackgroundColor(locRow, someClass) === undefined){
        return changeColor(locRow, someClass);
      }else {
        false;
      }
    }
  }

buttons.on("click", function(){
  if ($(this).attr('class') === 'G') {
    var someClass = gClass;
  }else if ($(this).attr('class') === 'F') {
    var someClass = fClass;
  }else if ($(this).attr('class') === 'E') {
    var someClass = eClass;
  }else if ($(this).attr('class') === 'D') {
    var someClass = dClass;
  }else if ($(this).attr('class') === 'C') {
    var someClass = cClass;
  }else if ($(this).attr('class') === 'B') {
    var someClass = bClass;
  }else if ($(this).attr('class') === 'A') {
    var someClass = aClass;
  }else {
    false;
  }
  someClassAttr = someClass.attr('class');
  if (locClassAttr === someClassAttr){
    locRow = locRow - 1;
    console.log(locRow, someClass);
    checkColor(locRow, someClass);
    // console.log(checkColor(locRow, someClass));
  }else {
    checkColor(row, someClass);
    var locClass = someClass;
    locClassAttr = locClass.attr('class');
    console.log(locClassAttr, someClassAttr);
  }
})


text:
Q: How can I find the name of my Network Interface I have a project that requires me to scan the local network.
I found a program on the internet that allows the local network scanner condition, but I brought the gold @ IP argument in my network program must be turned the machine alone after two minutes.
So I determined a program from my PC IP and mask can give me the class CIDR (192.168.1.123/24), but to find this result I have to give the name of the network interface that my pc is connected (ie: wlan0, eth0 or eth1) to.
Q: Is there a method to find the name of the interface without the whole list as ifconfig does?

A: Get the default route, and catch the interface column:
nicolas@host:~$ ip route list | grep default | awk '{print $5} '
wlan0

A: List the content of the directory /sys/class/net/. Each file in there corresponds to one interface. According to your question, you should find at least one file starting with eth.


text:
Q: VBA MACRO: How can I Click on button that changes classname in HTML? This is the website I am trying to reach. - > https://brokercheck.finra.org/
My vba code will allow me to get to the website, and input data in the cell box, but when I do, it doesn't really understand that there is text because the class changes when you input data manual, so when you do it with code, it doesn't change. Can anyone help please?
Set elements = html.getElementsByClassName("md-tab ng-scope ng-isolate-scope md-ink-ripple")

Set elements2 = html.getElementsByClassName("md-raised md-primary md-hue-2 md-button md-ink-ripple")

Set elements3 = html.getElementsByClassName("ng-scope selected")

Dim count As Long
Dim erow As Long count = 0

'This changes the form selection
For Each element In elements If element.className = "md-tab ng-scope ng-isolate-scope md-ink-ripple" Then element.Click
Next element

'this inputs the data on the city cell in HTML html.getElementById("acFirmLocationId").Value = "30047"

'this pushes the submit button
For Each element2 In elements2
If element2.className = "md-raised md-primary md-hue-2 md-button md-ink-ripple" Then element2.Click
Next element2

after this I get an error with the submit button because it doesn't activate the drop down list that it is embedded in the webpage.enter image description here

A: The page makes API calls to update content based on lat and lon of zipcode. You can find this in the network tab e.g. 1 , 2. These API calls return a string containing json with the listings which can be parsed with a json parser after a little string manipulation|regex. This means, in this case, you can issue xhr requests (so no need for I/O of opening browser) and then parse the json.  The total number of results is present in the responseText.
The json parser I use is Jsonconverter.bas: Download raw code from here and add to standard module called jsonConverter . You then need to go VBE > Tools > References > Add reference to Microsoft Scripting Runtime.
The following shows returning all results (all pages) for a given zipcode - both for By Firm and By Individual.

Firms:
Getting Firm results based on zip.
The API endpoint (construction):
apiUrl = "https://api.brokercheck.finra.org/firm?hl=true&json.wrf=angular.callbacks._6&lat={LAT}&lon={LON}&nrows=100&r=25&sort=score+desc&{START}&wt=json"

uses a query string where you can alter the number of results retrieved by the changing the nrows param. The limit is 100. The default is 12. If you wish to retrieve all results, you can make subsequent calls in batches of n e.g. 12 with the appropriate n cumulative offset adjustment to start param:
GET /firm?hl=true&json.wrf=angular.callbacks._7&lat=33.864146&lon=-84.114088&nrows=100&r=25&sort=score+desc&start=0&wt=json
GET /firm?hl=true&json.wrf=angular.callbacks._7&lat=33.864146&lon=-84.114088&nrows=100&r=25&sort=score+desc&start=100&wt=json

etc
In order to make less requests I would go with the max of n = 100 and alter the nrows param before a loop to collect all results, and the start (offset) param during the loop to get next batch.
Option Explicit
'Firm
Public r As Long

Public Sub GetListings()
    '<  VBE > Tools > References > Microsoft Scripting Runtime
    Dim json As Object, apiUrl As String, re As Object, s As String, latLon()
    r = 0
    Set re = CreateObject("VBScript.RegExp")
    apiUrl = "https://api.brokercheck.finra.org/firm?hl=true&json.wrf=angular.callbacks._6&lat={LAT}&lon={LON}&nrows=100&r=25&sort=score+desc&{START}&wt=json"

    Dim xhr As Object, totalResults As Long, numPages As Long

    Set xhr = CreateObject("MSXML2.XMLHTTP")

    latLon = GetLatLon("30047", xhr, re) '"30047" is the zipcode of interest and could be passed as a constant set at top of module or as a local variable changed set in a loop. over zipcodes
    apiUrl = Replace$(Replace$(apiUrl, "{LAT}", latLon(0)), "{LON}", latLon(1))
    s = GetApiResults(xhr, Replace$(apiUrl, "{START}", "start=0"), re)

    If s = "No match" Then Exit Sub

    Set json = JsonConverter.ParseJson(s)("hits")

    totalResults = json("total")

    numPages = Application.RoundUp(totalResults / 100, 0)

    Dim results(), ws As Worksheet, headers(), i As Long
    ReDim results(1 To totalResults, 1 To 3)

    Set ws = ThisWorkbook.Worksheets("Sheet1")
    headers = Array("CRD Number", "Name", "Address")
    results = GetFirmListings(results, json("hits"))

    If numPages > 1 Then
        For i = 2 To numPages
            s = GetApiResults(xhr, Replace$(apiUrl, "{START}", "start=" & (i - 1) * 100), re)
            If s = "No match" Or InStr(s, "Exceeded limit") > 0 Then Exit For
            Set json = JsonConverter.ParseJson(s)("hits")
            results = GetFirmListings(results, json("hits"))
        Next
    End If
    With ws
        .Cells(1, 1).Resize(1, UBound(headers) + 1) = headers
        .Cells(2, 1).Resize(UBound(results, 1), UBound(results, 2)) = results
    End With
End Sub

Public Function GetLatLon(ByVal zip As String, ByVal xhr As Object, ByVal re As Object) As Variant
    Dim json As Object, lat As String, lon As String
    With xhr
        .Open "GET", Replace$("https://api.brokercheck.finra.org/locations?query={ZIP}&results=1", "{ZIP}", zip), False
        .send
        Set json = JsonConverter.ParseJson(.responseText)("hits")("hits")(1)("_source")
        lat = json("latitude")
        lon = json("longitude")
        GetLatLon = Array(lat, lon)
    End With
End Function

Public Function GetApiResults(ByVal xhr As Object, ByVal apiUrl As String, ByVal re As Object) As String
    With xhr
        .Open "GET", apiUrl, False
        .send
        GetApiResults = GetJsonString(re, .responseText)
    End With
End Function

Public Function GetFirmListings(ByVal results As Variant, ByVal json As Object) As Variant
    Dim row As Object, address As Object
    Dim addressToParse As String, addressToParse2 As String
    'Crd number, name and office address

    For Each row In json
        r = r + 1
        results(r, 1) = row("_source")("firm_source_id")
        results(r, 2) = row("_source")("firm_name")
        addressToParse = Replace$(row("_source")("firm_ia_address_details"), "\""", Chr$(32))
        addressToParse2 = Replace$(row("_source")("firm_address_details"), "\""", Chr$(32))
        addressToParse = IIf(addressToParse = vbNullString, addressToParse2, addressToParse)
        If addressToParse <> vbNullString Then
            Set address = JsonConverter.ParseJson(addressToParse)("officeAddress")
            results(r, 3) = Join$(address.items, " ,")
        End If
    Next
    GetFirmListings = results
End Function

Public Function GetJsonString(ByVal re As Object, ByVal responseText As String) As String
    With re
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = "\((.*)\);" 'regex pattern to get json string
        If .Test(responseText) Then
            GetJsonString = .Execute(responseText)(0).SubMatches(0)
        Else
            GetJsonString = "No match"
        End If
    End With
End Function

Individuals:
At page = 91 there is limit exceeded.  90 requests actually yielded 9,000 results of total 11,960. It may be worth investigating whether that total is actually accurate as this may be the reason for no further results. For example, despite stating currently 11,960 results there are only 75 pages of 12 results per page i.e. only 750 of c.997 expected pages. 750 pages, at 12 results per page, gives 9,000 results which is the actual returned amount. The code below simply ceases looping if "limit exceeded" is found in the response.
I show extracting only specific items from json. There is a lot more info returned e.g. all current employments which can be more than 1. You can explore, for example, the json for the first request (first 100 listing) here.
If you are interested in a specific individual you can also use their CRD in an API call as shown at the very bottom section.
Option Explicit
'Individual
Public r As Long

Public Sub GetListings2()
    '<  VBE > Tools > References > Microsoft Scripting Runtime
    Dim json As Object, apiUrl As String, re As Object, s As String, latLon()
    r = 0
    Set re = CreateObject("VBScript.RegExp")
    apiUrl = "https://api.brokercheck.finra.org/individual?hl=true&includePrevious=false&json.wrf=angular.callbacks._d&lat={LAT}&lon={LON}&nrows=100&r=25&sort=score+desc&{START}&wt=json"
    Dim xhr As Object, totalResults As Long, numPages As Long

    Set xhr = CreateObject("MSXML2.XMLHTTP")

    latLon = GetLatLon("30047", xhr, re)
    apiUrl = Replace$(Replace$(apiUrl, "{LAT}", latLon(0)), "{LON}", latLon(1))
    s = GetApiResults(xhr, Replace$(apiUrl, "{START}", "start=0"), re)

    If s = "No match" Then Exit Sub

    Set json = JsonConverter.ParseJson(s)("hits")

    totalResults = json("total")

    numPages = Application.RoundUp(totalResults / 100, 0)

    Dim results(), ws As Worksheet, headers(), i As Long

    'example info retrieved. There is a lot more info in json
    headers = Array("CRD Number Indiv", "Name", "FINRA registered", "Disclosures", "In industry since")
    ReDim results(1 To totalResults, 1 To UBound(headers) + 1)

    Set ws = ThisWorkbook.Worksheets("Sheet1")

    results = GetIndividualListings(results, json("hits"))
    If numPages > 1 Then
        For i = 2 To numPages
            DoEvents
            s = GetApiResults(xhr, Replace$(apiUrl, "{START}", "start=" & (i - 1) * 100), re)
            If s = "No match" Or InStr(s, "Exceeded limit") > 0 Then Exit For
            Set json = JsonConverter.ParseJson(s)("hits")
            results = GetIndividualListings(results, json("hits"))
        Next
    End If
    With ws
        .Cells(1, 1).Resize(1, UBound(headers) + 1) = headers
        .Cells(2, 1).Resize(UBound(results, 1), UBound(results, 2)) = results
    End With
End Sub

Public Function GetLatLon(ByVal zip As String, ByVal xhr As Object, ByVal re As Object) As Variant
    Dim json As Object, lat As String, lon As String
    With xhr
        .Open "GET", Replace$("https://api.brokercheck.finra.org/locations?query={ZIP}&results=1", "{ZIP}", zip), False 'changed results = 10 to results = 1
        .send
        Set json = JsonConverter.ParseJson(.responseText)("hits")("hits")(1)("_source")
        lat = json("latitude")
        lon = json("longitude")
        GetLatLon = Array(lat, lon)
    End With
End Function

Public Function GetApiResults(ByVal xhr As Object, ByVal apiUrl As String, ByVal re As Object) As String
    With xhr
        .Open "GET", apiUrl, False
        .send
        GetApiResults = GetJsonString(re, .responseText)
    End With
End Function

Public Function GetIndividualListings(ByVal results As Variant, ByVal json As Object) As Variant
    Dim row As Object
      'can have numerous current employments. Alter here and below if want more info from json about the individual

    For Each row In json
        r = r + 1
        results(r, 1) = row("_source")("ind_source_id")
        results(r, 2) = Replace$(Join$(Array(row("_source")("ind_firstname"), row("_source")("ind_middlename"), row("_source")("ind_lastname")), ", "), ", , ", ", ")
        results(r, 3) = row("_source")("ind_approved_finra_registration_count")
        results(r, 4) = row("_source")("ind_bc_disclosure_fl")
        results(r, 5) = row("_source")("ind_industry_cal_date")
    Next
    GetIndividualListings = results
End Function

Public Function GetJsonString(ByVal re As Object, ByVal responseText As String) As String
    With re
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = "\((.*)\);" 'regex pattern to get json string
        If .Test(responseText) Then
            GetJsonString = .Execute(responseText)(0).SubMatches(0)
        Else
            GetJsonString = "No match"
        End If
    End With
End Function

Single individual:
Detailed info for a single individual can be gained from:
https://api.brokercheck.finra.org/individual/1614374?json.wrf=angular.callbacks._h&wt=json

A: By Whatever I understood of your problem. Maybe you can make use of Application.SendKeys. That's what I use when I need to input any information on Web.
Code: You can manipulate it as per your need.
Sub gottt()

Dim ie As Object
Dim el As Object

Set ie = CreateObject("InternetExplorer.Application")
ie.navigate "https://brokercheck.finra.org/"
ie.Visible = True

    Do While ie.Busy
        Application.Wait DateAdd("s", 1, Now)
    Loop

For Each el In ie.document.getElementsByTagName("span")
    If el.innerText = "Firm" Then el.Click
Next

Application.Wait DateAdd("s", 1, Now)

For Each el In ie.document.getElementsByTagName("input")

   If el.getAttribute("name") = "acFirmLocation" Then
        el.Focus
        Application.SendKeys ("30047"), True
        Application.Wait DateAdd("s", 1, Now)
    End If

Next

Application.Wait DateAdd("s", 1, Now)

For Each el In ie.document.getElementsByClassName("md-raised md-primary md-hue-2 md-button md-ink-ripple")
   If el.getAttribute("aria-label") = "FirmSearch" Then el.Click
Next

End Sub

Demo:


text:
Q: Can Entity Framework generate the DAL code? I know that entity framework has a database first approach. Now the question is whether it can generate the DAL (data access layer) code (not the models) for me.

A: When using a Object Relational Mapper (ORM), you don't typically have CRUD code in the traditional sense.  Rather, it abstracts those operations into more object oriented operations.
For example, you don't "insert", you add the model class to the table, then save changes.  The ORM automatically generates the SQL needed to make the Object model match the data model.
So my point is, your question displays a basic lack of understanding of how ORM's work and how they relate to data models.  You should probably do a little reading.

A: I'm not sure what you mean specifically by "DAL code", as that's a rather ambiguous term. I would consider your Entity types part of the DAL.
When you use a model-first or database-first approach, the Entity Framework tools can auto-generate a context class from your model .edmx, which will inherit from ObjectContext. It's easy to customize the generated context class with T4 templates by finding one online that already generates from a .edmx, and modifying to your liking.
Code-first development uses the DbContext, which is not typically auto-generated. Please see this post on Scott Gu's blog for more details on this.


text:
Q: Using Supersleight plugin creates border and broken image X mark in IE6 I've already asked this question on the guy's blog who created this plugin but not gotten an answer yet.
I am using the supersleight.plugin.js plugin to sort out the transparency issue in IE6. It's working just great but I seem to have an issue if I have an image AND a background image which are both transparent PNG24 images in that it creates a border around the image and the little red cross which you would normally get when you open a site with broken images in IE6
Here's the link to see what I mean.
http://bit.ly/crCY2a
You'd have to view this in IE Tester for IE6
Anyone, know of a work around for this?
Thanks

A: The script is looking for an image called x.gif (which comes with the JavaScript file) at the root of your web application. Either copy this image to the root or update the supersleight JS file accordingly.


text:
Q: customize error types of @ApiResponse() in Nestjs-swagger project I wanna create error types using ApiResponse in my swagger-nestjs project
So I created different types for different typesof errors.
For example the type for NotFoundException is :
`export class NotFoundErrorResponse {
@ApiProperty({ example: 404 })
statusCode: number;
@ApiProperty({ example: 'Title is required' })
message: string;

@ApiProperty({ example: 'ValidationError' })
error: string;

}`
and the output shown in the swagger is :
{ "statusCode": 400, "message": "Title is required", "error": "ValidationError" }
as expected.
The problem is I have to create multiple types (classes) for each one of errors in order to have different example values .
Do you have any idea about haow can I create multiple example values with just one class ?
I searched a lot but couldn't find any thing to do .thanks for your helping


text:
Q: SQL server .Net CLR culture I have a CLR .NEt dll in and SQL server. The system local settings (Region/administrative/locallanaguagesettings) are changed from en-IN to en-US. But the culture in the CLR traced with Thread.CurrentThread.CurrentCulture is still en-IN
select @@Language prints englishUS
from where does the SQL server select the culture for the CLR culture? And the final question, how can I change with a system setting the used culture in a SQL CLR assembly?

A: Try setting the UICulture and the Culture to en-US in the page directive for the page(s) .as?x
<%@ Page UICulture="en-US" Culture="en-US" %>


text:
Q: When is it appropriate to use 'the' instead of a possessive determiner? I was with someone today and we were talking about a woman, and she said:

"Wow, the husband must be so proud."

I was confused as to which was correct or more appropriate as opposed to:

"Wow, her husband must be so proud."

A: Both are grammatically correct. "The" is much less common and might have a negative connotation based on "the wife." However, the somewhat condescending "the wife" or "the husband" seems to be used in place of "my wife" or "my husband," which is different from the example you heard, where "the" is replacing "her."

A: It can be said both ways.
Let me give you an example:

That is her computer.

But you can also say it this way:

That is the computer.

Therefore:

Wow, the husband must be so proud.

That sentence is just as correct as this:

Wow, her husband must be so proud.

A: Both are valid, but would be used in slightly different contexts. The normal usage of determiners governs the choice here.
You use 'the' to signify that the determiner phrase refers to a referent already in scope. In this case, if the husband was mentioned previously (perhaps as part of a family), using the is fine:

I was talking to a couple earlier, and the wife told me she was having a baby. The husband must be so proud.

In this case "the husband" and "the wife" are in scope, since they constitute the "couple* mentioned.
If the referent is not in scope, you should use a different determiner to specify which husband you're talking about. So

I was talking to Alice earlier, and she told me she was having a baby. Her husband must be so proud.

Since "Alice" has been mentioned, the possessive determiner her suffices.
Exceptions
There are some cases where you can refer to family members with the without their being explicitly mentioned. For example, "the kids" is normally understood to refer to the speaker's own children. As others mentioned, "the wife" (or "the husband) can refer to one's spouse; this usage is condescending to the spouse.


text:
Q: How do I refer to a cell in another worksheet with a long name? As explained in this other Answer, SheetName!A1 = cell A1 in the worksheet called "SheetName" (without quotations).
Say the name for my worksheet is very long. Without shortening "SheetName" and writing out expressly "SheetName", what's a more efficient way to refer to it? Is it possible to designaet "SheetName" by "S" and then input S!A1?

A: No, that's not possible in a formula. If you have a long sheet name, wrap it in single quotes -
'this sheet name is huge'!A1

A: You can create named ranges in Excel, which are like aliases.
If you select a single cell or a range of cells, go to the text box to the left of the formula bar. By default, it will display the generic name of the currently selected cell, such as C5. However, you can type a simple name into this box and press enter to give the cell a name, and then use that name in formulas.
For example, you can go to cell A1 on Sheet1, and name it "Profits". Then on Sheet2, you can specify B3 to be =Profits*2, and then Sheet2!B3 will always have twice the value of Sheet1!A1


text:
Q: How to access a folder in sandboxed backend if the folder was opened in sandboxed frontend I develop MacOS applications that should work in sandbox:
1. Frontend application with UI where user can open a folder that should be used to save files by the backend.
2. Backend application can be run any time and should save files into the folder user specified in the frontend.
I can store access to the folder in the frontend by using security scoped bookmark and pass this bookmark to the backend, but I cannot access the folder in backend. The backend is placed inside frontend's bundle. Both applications can be in the same app group.
Does anybody know how to solve this problem?


text:
Q: How can call another phtml content file via ajax in magento 2 model popup? Please can anyone suggest me to how can call phtml file content load in model popup in magento 2...
Thanks help will be appreciated...

A: This website helpfull to you Example


text:
Q: Python program can't open txt file I'm new to python and i'm trying to make a password manager.
the problem is that my program works fine when i run it through IDLE or Pycharm
but it stops running when i run it directly from windows when it reaches the line where I import the file where i store the password.
import time

user = raw_input("Username: ")
pw = raw_input("Password: ")
if user == "PrOoOg" and pw == "aka443":
    def add_acc_func(acc, user, pw):
        database.write("\nAccount: ")
        database.write(acc)
        database.write("    Username: ")
        database.write(user)
        database.write("    Password: ")
        database.write(pw)
        database.close()

    def print_database_func():
        for lines in database.readlines():
            print lines.strip('\n')
        database.close()

    user_input = raw_input('Press "A" to add a new account\nPress "M" to modify and existing account\n'
                            'Press "D" to delete and existing account\nPress "S" to show all accounts and passwords\n')
    user_choice = user_input.lower()
    if user_choice == "a":
        database = open("source.txt", "a") #Everything worked fine when i deleted this line
        acc_to_add = raw_input("Write the name of the site or service: ").lower()
        acc_to_add_user = raw_input("Write the username or email you want to set for that account: ")
        acc_to_add_pw = raw_input("Write the password you want to set to that account: ")
        add_acc_func(acc_to_add, acc_to_add_user, acc_to_add_pw)
        print "Account added"

    if user_choice == "s":
        database = open("source.txt", "r") #Everything worked fine when i deleted this line
        print_database_func()

    raw_input("Press Enter to quit")
else:
    print ("Wrong username or password")
    time.sleep(3)

I tried to delete the lines where I import the text file and it worked.
i don't know why the code can't open the file when opened from windows and can open it when opened from IDLE or Pycharm

A: "it's just crashes when i run it from windows (rightclick ==> open with ==> python.exe)"
When you do this the working directory is C:\Windows\system32. Most likely you don't have write permissions to this directory. When running the script using the other methods the working directory is most likely the one containing the script. You need to change to a directory which you have write permissions for.
Here is an example to use the current user's Documents folder:
import os
dir = os.path.expanduser('~/Documents')
os.chdir(dir)


text:
Q: Using different version of MSBUILD.exe between Dev and Jenkins machine I have a C# project developed with VS2017.
The server on which Jenkins runs doesn't have VS installed. I have .NET 4.7 installed on the dev computer and the server.
This is what I get when I type msbuild.exe /version:
Microsoft (R) Build Engine version XXX(see below)

*

*On dev, I have 2 MSBUILD.exe:

*

*C:...\MicrosoftVisualStudio\2017\Pro\MSBuild\15.0\Bin: 15.1.1012.6693

*C:\Windows\Microsoft.NET\Framework\v4.0.30319: 4.7.2053.0

*On server: C:\Windows\Microsoft.NET\Framework\v4.0.30319: 4.7.2053.0
I assume that when I build a project in VS2017, it uses the MSBUILD.exe located in the MicrosoftVisualStudio folder.
I'm concerned now to build on the Jenkins machine with a different version of MSBUILD.exe? What would be the best approach? Copy the folder C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild to the Jenkins computer?

A: This depends on what MSBuild features you use.
The safe way to build projects developed in VS 2017 is to build using the installed VS version of MSBuild (15) from either a full VS installation or the Build Tools for Visual Studio 2017.
Even though the .NET Framework version of MSBulid will be able to build a lot of projects, it is limited to an older C# version, so you'd have to install the Microsoft.Net.Compilers NuGet package to replace the compiler. But VS 2017 introduces new MSBuild syntax features as well as build tasks which cannot be patched into the legacy version of MSBuild so its use is highly discouraged.

A: I was getting several errors using on the server this version of MSBUILD.exe: C:\Windows\Microsoft.NET\Framework\v4.0.30319: 4.7.2053.0
Here are the steps followed to builwithout error a VS2017 C# on Jenkins 2.60.2

*

*Copy C:...\MicrosoftVisualStudio\2017\Pro\MSBuild to my server

*In Jenkins/Global Tool Configuration, in the MSBUILD section

*

*Name: msbuild.exe

*Path to MSBuild: C:\MSBuild\15.0\Bin

*Default parameters: -p:FrameworkPathOverride="C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.7"

If Default parameters is empty, I was getting errors, so it is important.


text:
Q: (OLE DB) Execute SQL Task - Using output parameters I'm trying to use "Execute SQL Task" in SSIS to get a value to be stored in a user variable.
The documentation says to use '?' as a placeholder for parameters in the query but when I do I get a syntax error trying to parse the query.
So the query is like this:
SELECT ? = AVG(Score) FROM Scorecards

I've also tried adding OUTPUT after the '?'. All examples I can find for having an output parameter are similar to
EXEC ? = MyStoredProc param1, param2, ...

This isn't of any use though since I'm not using a stored proc. The use of the parameter seems similar though so why won't SSIS take it for a select statement?

A: You'll need to set the ResultSet property to Single Row, then amend your query to something like:
select avg(score) as AvgScore from ScoreCards

Then in the Result Set pane, click Add, set the Result Name to AvgScore, and your variable to Variable Name (for example, User::AvgScore).


text:
Q: Can you assign existing value to the array in c++? Is it possible to assign an existing variable to the array? Let's say if we have 5 variables a, b, c, d, e and we want to assign them to an array n[5], but I can't assign the names of variables in the array, so what do I do then?

A: Sure, you can do it like this:
T n[5] = {a, b, c, d, e};

assuming the variables are all of type T.


text:
Q: Javascript output online usernames in HTML table I made a server that checks if people are online if they logged in, and want to put that information into a html table.
<?php
session_start();
include_once '../php\connect.php';
function removeRefresh(){
    $query = connection()->prepare("UPDATE `online` SET `time` = `time`+1");
    $query->execute();
    $query = connection()->prepare("DELETE FROM `online` WHERE `time` > 5");
    $query->execute();
}
function addOrRefresh($ID){
    $query = connection()->prepare("SELECT COUNT('id') FROM `online` WHERE `ID` = :ID");
    $query->bindParam(':ID', $ID);
    $query->execute();
    $count = $query->fetchColumn();
    if($count == 0){
        $query = connection()->prepare("INSERT INTO `online`(`ID`, `time`) VALUES(:ID, 0)");
        $query->bindParam(':ID', $ID);
        $query->execute();
    }
    else{
        $query = connection()->prepare("UPDATE `online` SET `time` = 0 WHERE `ID` = :ID");
        $query->bindParam(':ID', $ID);
        $query->execute();
    }
}
$action = filter_input(INPUT_GET, 'action');
if($action == 'heartbeat'){
    removeRefresh();
    $ID = $_GET['id'];
    addOrRefresh($ID);
    $query = connection()->prepare("SELECT u.username FROM `nusers` u INNER JOIN `online` o ON o.ID = u.ID");
    $query->execute();
    $onlineUsers = $query->fetchAll(PDO::FETCH_ASSOC);
    $resultaat = "";
    foreach($onlineUsers as $user){
        $resultaat .= "
{$user['username']}

";
    }
    echo "$resultaat";
}

?>

You can register, and when you log in into the lobby, you are added into an 'online' table, that checks every second with the function 'heartbeat'.
Please excuse my poor English.
EDIT: I have systems working. I merely want to change the 'echo "$resultaat"' so that it puts the $resultaat into a tablerow.
adding  after a '}' won't work, I've tried working around that, not certain if I tried all posibilities in that retrospect. After request, I've posted the entire document.
the other javascript part is integrated into another document; containing:
   <?php
session_start();
$ID = $_SESSION['ID'];

if (isset($_POST['logout'])) {
    session_destroy();
    $query = connection()->prepare("DELETE FROM `online` WHERE `ID` = :ID");
    $query->bindParam(':ID', $ID);
    $query->execute();
}
?>

        <title>Stratego</title>
        <Link href="../layout/style.css" type="text/css" rel="stylesheet" />

        <form method='post' name='logout' action="../setup/logout.php">
            <input type='submit' name='loggout' value='Log me out'>
        </form>
        Singleplayer

    <?php echo ""; ?>

The console log is there to check if the connection is being maintained. People use their ID to login, no passwords.
This is how it looks now, with 1 person being online; named Luuk.
http://www.filedropper.com/screenproof
My goal is to get all the people that are online into a table.
I've tried
        $resultaat .= "
{$user['username']}

";
}
echo "
$resultaat
";

Just now, doesn't seem to work, any tips on how to progress?

A: I've fixed the issue;
    $resultaat = "";
foreach($onlineUsers as $user){
    $naam= $user['username']
    $resultaat .= "
$naam
";
}
echo "
$resultaat
";


text:
Q: Wifi keeps asking for password - Ubuntu 12.10 I just installed a fresh Ubuntu 12.10 and it still keeps asking me for password.
I've spent a few days of searching on net without any luck. I tried loading different drivers, using wicd instead of network-manager, re-configuring router, but still no luck.
There are many threads already about this issue, but none solved my issue. I have a USB wifi dongle Netgear WNA1000M and the driver was installed automatically. Although, when I choose a network to connect to, enter the password, it keeps prompting me for password again.
Cable connection works good.
I've run out of ideas. Can you please suggest further?
Thank you!
Lukas

A: I had this problem. I messed around with drivers and different distros but nothing worked.
I solved it by changing my router settings from n only to g/n.

A: I had a similar issue.
For me it was causes by the wlan0 power management.
Try:
sudo iwconfig wlan0 power off

if that seems to solve the issue you can turn it off permanently:
Create a file in /etc/pm/config.d . I have named it blacklist:
gksu gedit /etc/pm/config.d/blacklist

and inside the file keep:
HOOK_BLACKLIST="wireless"

How can I prevent iwconfig power management from being turned on?

A: I had this working for another hotspot (so hardware and network drivers are fine), but failed to connect to the new company WLAN. By comparing the connection information of both, I figured out that

Edit Connections > CONNECTION-NAME > /Wi-Fi Security\ > Authentication
  Was on "Tunneled TLS", needs to be "Protected EAP (PEAP)"


text:
Q: Stretched background layout using Bootstrap 3 I'm working on converting a layout to HTML/CSS using Bootstrap 3.
My question is, how can I implement the following layout in Bootstrap such that the parts highlighted in rectangles only show up in screen sizes with width 1000+ pixels? When screen sizes are below 1000px, I want the parts in the rectangles hidden.
Of particular difficulty seems the navigation bar. What do you folks suggest?

A: Well there are couple of ways to do this.
NOTE: I am just going to give an idea, NOT the whole solution.
1) You can have two divs like
HTML

CSS
.firstDiv {
   position: absolute;
   left: 0;
   width: 20%;
   opacity: 0;
}

.secDiv {
   position: absolute;
   right: 0;
   width: 20%;
   opacity: 0;
}

@media(max-screen: 1000px) {
   .firstDiv .secDiv {
      opacity: 1;
   }
}

2) You can make two images (one is full and other is croped) and set the background like
HTML

CSS
.myImage {
   background-image: url('/path/to/fullimage.png');
}

@media(max-screen: 1000px) {
   .myImage {
      background-image: url('/path/to/croppedimage.png');
   }
}


text:
Q: Elegant way to find closest value in a vector from above I need a function that takes a vector (assumed to be sorted), and a value, and returns the closest number that's [edit] greater than less than or equal to that number, preferably using an algorithm from the STL. I have come up with a solution using std::lower_bound(), but it seems kludgy and ugly:
struct ClosestCmp {
    bool operator()(const int & x, const int & y) { return x > y; }
};

// vec is assumed to be sorted
int closest(const std::vector<int> & vec, int value)
{
    std::vector<int>::const_reverse_iterator cri =
        std::lower_bound(vec.rbegin(), vec.rend(), value, ClosestCmp());
    if (cri != vec.rend()) {
        return *cri;
    }
    return -1;
}

// ...
vec.push_back(1);
vec.push_back(2);
vec.push_back(4);
vec.push_back(5);
std::cout << closest(vec, 2) << "\n"; // Should ouput "2"
std::cout << closest(vec, 3) << "\n"; // Should ouput "2"
std::cout << closest(vec, 4) << "\n"; // Should ouput "4"

Can anyone suggest a way that's more elegant, maybe using an STL algorithm without needing a comparison function or a reverse iterator? I have looked in the STL, but haven't been able to find a better solution than this.

A: Requires C++11:
template<typename InputIterator, typename ValueType>
InputIterator closest(InputIterator first, InputIterator last, ValueType value)
{
    return std::min_element(first, last, [&](ValueType x, ValueType y)
    {
        return std::abs(x - value) < std::abs(y - value);
    });
}

A: You can only use std::lower_bound and std::upper_bound with binary predicates that match the order of the container. So, you can't sort by < and then use a different binary predicate (say <= or >). So your "kludge" is actually the correct thing to do. The sorted vector in reverse is the ordering criteria you want to use to find the element less than or equal to the value. (Otherwise, if you were actually searching for the value greater than or equal to, you could just use std::lower_bound.)

A: For reminder:

*

*std::lower_bound: returns the first value that does not compare less

*std::upper_bound: returns the first value that compares strictly greater

From your description, std::lower_bound already looks like the perfect fit, what is wrong with:
int closest(std::vector<int> const& vec, int value) {
    auto const it = std::lower_bound(vec.begin(), vec.end(), value);
    if (it == vec.end()) { return -1; }

    return *it;
}

Which is used as:
int main() {
    std::vector<int> vec;
    vec.push_back(2);
    vec.push_back(4);

    std::cout << closest(vec, 2) << "\n";
    std::cout << closest(vec, 3) << "\n";
    std::cout << closest(vec, 4) << "\n";
}

Output:
2
4
4

A: For the largest which is less or equal one can use this function
int closest(std::vector<int> const& vec, int value) {
    auto const it = std::lower_bound(vec.begin(), vec.end(), value);
    if (it == vec.begin()) { return -1; }
    else return *(it - 1);
}


text:
Q: How to restrict access to pages within laravel, when user hasn't accepted terms and conditions I am currently designing a website that requires the user to agree to the terms and conditions before continuing and restricts them from accessing other pages through url if they haven't accepted the terms and conditions. What would be the best way of implementing this? I'm still fairly new to Laravel and haven't had much luck trying to implement it myself. I've looked into setting sessions which didn't work to well, and middleware wont work unless the user signs up before hand, which isn't what i want.

A: You can store authorized cookie to authenticate the visitor:
To store cookie on browser side:
$response->withCookie(cookie()->forever('authorized', 'true'));

To get the cookie value from request:
$authorized = $request->cookie('authorized');


text:
Q: ChromeCast TTML Closed Captioning with Smooth Streaming and PlayReady Hy!
I would like to create an application which supports TTML typed closed captions.
My ism/manifest file contains the TTML based closed caption, I would like to ask how can I use it?
I found this site,
https://developers.google.com/cast/docs/player
where they described the following:
Segmented TTML & WebVTT
Use Segmented TTML for Smooth Streaming and WebVTT - Web Video Text Tracks for HLS.
To enable:
protocol_.enableStream(streamIndex, true);
player_.enableCaptions(true);
But I can't find an example for my problem. Do I have to enable this after creating my host at the receiver side?
Are there any sample app for this?
UPDATE #1
Here's my code:
  window.onload = function() {

  var mediaElement = document.getElementById('video'); //video is a html video tag

  var mediamanager = new cast.receiver.MediaManager(mediaElement);

  var url = "http://playready.directtaps.net/smoothstreaming/SSWSS720H264/SuperSpeedway_720.ism/Manifest";  //Just a sample URL

  var host = new cast.player.api.Host({ 'mediaElement': mediaElement, 'url': url });

  window.player = new cast.player.api.Player(host);

  protocol = cast.player.api.CreateSmoothStreamingProtocol(host);

  var initStart = 0;

  window.player.load(protocol, initStart);

  mediamanager.loadedmetadata = function(loadinfo) {
          //onMetadataLoaded fired, set the caption
  }

  }

It doesn't work. So I decided to get the streams:
  var streamCount = protocol.getStreamCount();

And streamCount contains 0. The manifest contains the closed caption, should I use something else, not the getStreamCount()?
Thank you very much!

A: The correct approach is to listen for metadataloaded event. Once that event is fired, then you are good to get the stream count, but don't do that before that event is fired. Then you can enable the stream for the index that you want (for the language that you want, in case you have multiple ones) and then enable caption. If you want to change language, you first need to disable caption and then select a different stream index and then enable it again.

A: No samples yet.
Yes - you should enable after creating the Host and starting playback.


text:
Q: FCM delay in messaging or never receive I developed a real-time on-demand app using FCM to notify my riders of jobs. But the problem comes that these messages sometimes never arrived at the rider's app within 1 minute timespan.
I would like to understand why such latency occurs, and to use any logs from FCM side to prove issue is not with my codes and is on the FCM server side. How can I do this?


text:
Q: last element is over-written in whole arraylist? I am getting the last element copied in the whole array list.
Here MyContact contains an ID(int), name(String), Number(String, primary key).
eg. i added name = John, number = 99999 and submit it.
      and   name = Jonny, number = 99998 and submit it.
in DB i can see them properly(entries are correct)
now i want them to see in listview like
-------------
  John
  99999
-------------
  Jonny
  99998
-------------

but actual result is
-------------
  Jonny
  99998
-------------
  Jonny
  99998
-------------

code from DataBaseHelper.java
// Getting All Contacts
public List<MyContact> getAllContacts() {
        Log.d(ContactManagerUtil.TAG_ENTER, ContactManagerUtil.getInstance()
                .getMehtodName());
    List<MyContact> contactList = new ArrayList<MyContact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
    db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    cursor.moveToFirst();

    while (!cursor.isAfterLast()) {
        MyContact contact = MyContact.getInstance();
        if (cursor.getString(0) != null)
            contact.setId(Integer.parseInt(cursor.getString(0)));
        contact.setName(cursor.getString(1));
        contact.setNumber(cursor.getString(2));
        // Adding contact to list
        contactList.add(contact);
        contact = null;
        cursor.moveToNext();
    }

    Log.d(ContactManagerUtil.TAG_EXIT, contactList.toString());
    Log.d(ContactManagerUtil.TAG_EXIT, ContactManagerUtil.getInstance()
            .getMehtodName());
    cursor.close();
    db.close();

    // return contact list
    return contactList;
}

from below i am calling the getAllContactMethod.
public class ContactView extends ListActivity {
DataBaseHelper db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d("@gaurav","IN ContactView.onCreate");
    db = new DataBaseHelper(getApplicationContext());
    ArrayAdapter<MyContact> adapter = new MyContactAdapter(this,
            db.getAllContacts());
    setListAdapter(adapter);
    Log.d("@gaurav","OUT ContactView.onCreate");
}
}

Adapter is as follows
public class MyContactAdapter extends ArrayAdapter<MyContact> {

    public MyContactAdapter(Activity context, List<MyContact> obj) {
        super(context, R.layout.layout_contact_view, obj);
        contactlist = obj;
        this.context = context;
    }

    private List<MyContact> contactlist;
    private Activity context;

    static class ViewHolder {
        protected QuickContactBadge contactbadge;
        protected TextView contactname;
        protected TextView contactnumber;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            convertView = inflator.inflate(R.layout.layout_contact_view, null);
            viewHolder = new ViewHolder();
            viewHolder.contactname = (TextView) convertView
                    .findViewById(R.id.contactname);
            viewHolder.contactnumber = (TextView) convertView
                    .findViewById(R.id.contactnumber);
            viewHolder.contactbadge = (QuickContactBadge) convertView.findViewById(R.id.contactBadge);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        if(contactlist.get(position) == null){
            Log.d(ContactManagerUtil.TAG_ENTER, "In adapter getView, found: contact null");
            return null;
        }
        viewHolder.contactname.setText(contactlist.get(position).getName());
        viewHolder.contactnumber.setText(contactlist.get(position).getNumber());
        viewHolder.contactbadge.setFocusable(true);
        return convertView;
    }
}

MyContact.java
public static MyContact getInstance() {
        if (contact == null) {
            contact = new MyContact();
        }
        return contact;
    }

A: Your MyContact class looks to be a singleton (e.g., the getInstance() method):
MyContact contact = MyContact.getInstance();
...
contactList.add(contact); // Always the same instance--sad panda.

Every reference in the list refers to the same instance, which contains the values of the last item from the DB. You need to create a new instance for each list item.


text:
Q: using findstr with regex to search through CSV I was wondering if it's possible to use findstr to search through a CSV for anything matching this regular expression
^([BPXT][0-9]{6})|([a-zA-Z][a-zA-z][0-9][0-9](adm)?)$

A: I don't know which language you're talking about, but there is one obvious problem with your regex: The ^ and $ anchors require that it matches the entire string, and you seem to be planning on matching individual entries in your CSV file.
Therefore, you should use word boundary anchors instead if your regex engine supports them:
\b(?:([BPXT][0-9]{6})|([a-zA-Z]{2}[0-9]{2}(adm)?))\b

I've also added another non-capturing group around the alternation. In your regex the anchors at the start and end of the string would have been part of the alternation, which is probably not intended. Whether you really need all the other parentheses depends on what you're going to do with the match.

A: No, it is not possible to use findstr to search for matching substrings, especially those matching the complex expression you've provided.
findstr is a Windows built-in.
findstr /? shows the subset of regex that it can use:

Regular expression quick reference:
  .        Wildcard: any character
  *        Repeat: zero or more occurrences of previous character or class
  ^        Line position: beginning of line
  $        Line position: end of line
  [class]  Character class: any one character in set
  [^class] Inverse class: any one character not in set
  [x-y]    Range: any characters within the specified range
  \x       Escape: literal use of metacharacter x
  \<xyz    Word position: beginning of word
  xyz\>    Word position: end of word

This means that most of your expression is out the window.
Also, findstr can't limit its output to just the matched expression; it only identifies lines containing matches.
It is entirely unsuitable for the task described.


text:
Q: Can I switch the User-Agent header for only a single web site? I have to use a particular web site for work, but this web site checks to see whether I'm using Internet Explorer and, if not, won't allow me to log in.  I can switch my User-Agent header using the User Agent Switcher Firefox plugin and the web site works fine, but I really don't want to switch the header every time I go to the site and also don't want my User-Agent header to perpetually say I'm using IE.
I'm on Linux, so actually switching to IE unfortunately isn't an option.
Is there any way to define a particular User-Agent for a particular web site in either Firefox or Chrome?

A: For Firefox there are the extensions UAControl and ua-site-switch, which allow setting the User-Agent header on a per-site basis. Pick one of them and, as Rob W pointed out, you'll need to install User-Agent JS Fixer too.

A: There are many extensions you can use which can work by auto detecting the IE setting for the website on FF.
IE TabV2
The updated, fully supported IE Tab. Embed IE in a Firefox tab.
 IE Tab Features: FF 4+ support, IE 7-9 compatibility modes, old IE Tab settings import. IE Tab supports ICBC and alipay
IE Tab Plus
The Original IE-Tab (Works also for IE8, IE9)
An enhanced version of IE Tab with Adblock Plus in IE supported. It also allows you import settings from IE Tab and synchronize cookies between IE and Firefox.
Only IE-Tab to support FF4 and beyond

A: You can use an addon like IE-tab, which will actually use IE DLLs from within Firefox, so the page will not only think you are using IE but it will render the same.  It can be set to automatically apply when you visit specific pages, so that you get Firefox rendering on everything except the sites that require IE.

A: The extension User-Agent Switcher for Chrome has a Permanent Spoof list, where you can set specific user agents for certain domains.
Configuration

*

*Add the extension to Chrome.

*Open chrome-extension://djflhoibgkdhkhhcedjiklpkjnoahfmg/options.html.

*Click Permanent Spoof list.

*Enter the domain of the particualr website, select the desired user agent and click Add.

A: Until Firefox 25, one could set general.useragent.override.[domain] to a custom UA string. Unfortunately, this feature was removed in Firefox 25.
Now, to get per-site UA string, one could install UAControl plus User-Agent JS Fixer. The first add-on modifies the User-Agent request header per site, but not the navigator.userAgent string that is often used for UA-sniffing. The second add-on complements the first add-on by overriding navigator.userAgent.
Since I already had Greasemonkey installed, and the site I'm targetting only uses client-side User-Agent sniffing, I decided to write a small user script to change navigator.userAgent for this particular site:
// ==UserScript==
// @name        Change navigator.userAgent
// @namespace   Rob W
// @description Changes navigator.userAgent to IE on IEGallery.com
// @match       http://www.iegallery.com/*
// @run-at      document-start
// @grant       none
// @version     1
// ==/UserScript==

Object.defineProperty(navigator, 'userAgent', {
    value: 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'
});

Works like a charm in Firefox 26.0.

A: Here's what I did in FireFox:

*

*Used UserAgentSwitcher Addon to spoof myself as an iphone. Visited site I always want to load the mobile version of, and it automatically loaded the mobile version.

*Made a bookmark to the site's mobile page.

*Set UAcontrol Addon to use iphone useragent on the site.

*Turned off UserAgentSwitcher.
When I launch the site from the regular bookmark it uses the regular website. And when I launch the site from the mobile version bookmark, it uses the mobile version.
Thus... UserAccountSwitcher functionality localized to one site rather than globally.

A: I needed to switch user agent to fix low resolution images in Firefox on Android. I found a lot of  dead links to agent switchers, but this one worked in Firefox - even on Android:
User Agent Switcher:
https://addons.mozilla.org/sv-SE/firefox/addon/user-agent-string-switcher//firefox/addon/user-agent-string-switcher/


text:
Q: Change-making problem with a twist I'm trying to solve the following problem, which is a twist on the change-making problem:

Given a set $S$ of coins, and a target value $b$, construct an algorithm to find  all finite lists of coins satisfying the following properties:

*

*The first $n$ coins in the list are smaller than $k$.

*Each coin devalues, that is, the sum of coins is calculated like so:
  $$
C= \sum_{i = m}^{1} max(c_i - (l
(m - i)), 0)
$$
  Where $m$ is the length of the list of coins and $l$ is the loss rate

*$C = b$, that is, the list sums up to the target value.

To give an example, if the list of coins is $[0.5, 0.25, 0.25]$ and the loss rate $l$ is $0.15$, the sum of that list is $(0.5 - 0.15 * 2) + (0.25 - 0.15 * 1)+ (0.25- 0.15 * 0) = 0.55$.
Lists where some elements make no contribution (there are terms with $c_i - loss = 0$) should not be counted.
I need this algorithm for a real life problem, and after some attempts I couldn't crack it, so for now I'm using basically brute force to find some solutions.


text:
Q: How to create index with concatenating two columns in Procedure/Function using pl/sql I want to create index of concatenating two columns, using this query:
   declare
   t_name varchar(100) := upper('test');
   table_space varchar(100) := 'users';
   begin
   execute immediate
           'create index ' || upper('trx_cst_indx') || ' ON ' || t_name || '(' || trx_date||'_'||customer_id || ') local unusable';
   end;

Running that query gives me this error:
 PLS-00201: identifier 'TRX_DATE' must be declared
 ORA-06550: line 5, column 16:
 PL/SQL: Statement ignored
 06550. 00000 -  "line %s, column %s:\n%s"
 *Cause:    Usually a PL/SQL compilation error.

Then I use single quotation for the column names like this:
 declare
 t_name varchar(100) := upper('test_etl');
 table_space varchar(100) := 'users';
 begin
 execute immediate
           'create index ' || upper('trx_cst_indx') || ' ON ' || t_name || '(' || 'trx_date'||'_'||'customer_id' || ') local unusable';
 end;

While running the above query, I receive this error:
 Error report - ORA-00904: "TRX_DATE_CUSTOMER_ID": invalid identifier
 ORA-06512: at line 5
 00904. 00000 -  "%s: invalid identifier"
 *Cause:

I don't know what is wrong with these queries.
Would you please guide me how to create index with concatenating two columns in this mode?
Any help is really appreciated.

A: Try this:
'create index trx_cst_indx ON '| | t_name || ' (trx_date,customer_id) local unusable';


text:
Q: Cluster Validation on Remote Node I have a 3 Node always availability group:
2 Nodes are In house – Synchronous Mode.
1 Node is remote - Asynchronous Mode.
Every now and then the Remote Node loses connectivity and goes offline from the cluster.  I would like to run a validation test on that node (dr site). Will this affect the other 2 nodes which are in synchronous mode?

A:
I would like to run a validation test on that node (dr site). Will this affect the other 2 nodes which are in synchronous mode?

No not the data flow as such. You can run cluster validation of all the resources but storage with no downtime. Although few of MS blogs suggest you can run all cluster validation test but storage on WSFC without downtime, still I would suggest you to run the validation when load is relatively very less.
Please note that when you run validation of shared disks cluster manually failover the disks to each node to check the failover and availability and hence it will cause downtime apart from this all other failover tests are online. I assume your AG is one having local disks attached to each node so I do not think you have to worry about downtime but again run validation when load is relatively very less.
I would suggest you to read Validating a Cluster with Zero Downtime. Quoting from the blog

Across these dozens of tests, only a few of them will impact running cluster workloads and these are all within the storage category, so skipping this entire category is an easy way to avoid disruptive tests.  Listing All Disks and Potential Cluster Disks will not impact anything.  Validating Disk Access Latency, File System, Microsoft MPIO-based disks, and SCSI device Vital Product Data (VPD) can impact the disk's performance as tests are performed against the disk which is in use, however they will cause no downtime unless the disk latency becomes so slow that it triggers an alert.  Several tests will actually trigger failovers and move the disks and groups to different cluster nodes which will cause downtime, and these include Validating Disk Arbitration, Disk Failover, Multiple Arbitration, SCSI-3 Persistent Reservation, and Simultaneous Failover.  So if you want to test a majority of the functionality of your cluster without impacting availability, exclude these tests.


text:
Q: How can I vertically align a webfont and text of different heights Got two buttons that I want to have an icon and text in.

View all services

Get a quote

Here's the CSS
.button .flaticon-phone16,
.button .flaticon-tools6 {
font-size: 30px;
line-height:42px;
}

.button p {
display: inline;
line-height:42px;
margin: 0px;
}

.button {
font-size:15px;
font-weight:bold;
font-style:normal;
line-height: 42px;
height:42px;
width:100%;
text-decoration:none;
text-align:center;
padding: 0;
}

I removed the styling stuff from the button class. Currently they are not vertically centered, as visible in this screenshot.
Does anyone have any ideas?

A: remove the other line-hight and only add line-height with a display block on
.button p {display: block; margin: 0px; line-height: 42px; }

A: You can use display: table-cell combine with vertical-align: middle:

a {
  width: 100%;
  display: table;
}

.button .flaticon-phone16, .button .flaticon-tools6 {
    font-size: 30px;
}
.button p {
    margin: 0px;
}
.button {
    display: table-cell;
    font-size:15px;
    font-weight:bold;
    font-style:normal;
    line-height: 42px;
    height:42px;
    width:100%;
    text-decoration:none;
    text-align:center;
    padding: 0;
}

View all services

Get a quote


text:
Q: Terminating condition of Simplex Method - Stronger termination conditon My textbook states "If there are no negative values in the top row of the Simplex tableau, then we have reached optimality"
That seems intuitive enough. However, I am wondering if the following, stronger statement is also true?
"We have reached optimality if and only if there are no negative values in the top row of the Simplex tableau".

A: Your stronger statement is true if the solution is non-degenerate. (Provided that the objective function is maximize.)


text:
Q: How do I remove all metadata from a WebM file? I've tried using ffmpeg, but it seems to keep all the metadata I'm actively looking to remove.
I'm looking to remove ALL metadata, including length, bitrate, etc.
Before you say this isn't possible, yes it is, and I have multiple files that have what I'm looking to do. The files without metadata are still fully playable.
Example of what I want to do:

I've also tried exiftool but it doesn't work with WebMs.
I tried the solution here and it didn't work. The output of ffmpeg on one of the WEBMs without metadata is:

A: Try the software suite MKVToolNix. A tool in it 'mkvpropedit' can be used for your purpose. It works on webm files also as it a profile of matroska. Here is an untested example.
(Try in cmd in the target's directory)
mkvpropedit "input.webm" --tags

NOTE: It might remove other useful tags too, so create a backup.


text:
Q: Retrieve FieldSet fields throught javascript possible? I know how to get FieldSet fields from within apex through describe.
but I have the need to do it using javascript is this possible ? and if so how.
Thanks in advance
Ronen

A: I gave this a shot using JSforce, let me know if this would be an acceptable approach in your case.
https://jsforce.github.io/
You can use login methods as shown here and get the access token,I went the VF route to avoid the login call and then get the access token approach.
https://jsforce.github.io/document/#connection
I used Metdata api option to read the field set object.
https://jsforce.github.io/document/#read-metadata
  <apex:page docType="html-5.0" showHeader="false">
  <apex:includeScript value="{!URLFOR($Resource.jsforce)}" /> <!-- Static Resource or Direct Link Below -->
  <script>
        var conn = new jsforce.Connection({ accessToken: '{!$Api.Session_Id}' });
        var fullNames = [ 'Account.prao6308__test_acc_fS' ];
        conn.metadata.read('FieldSet', fullNames, function(err, metadata) {

        if (err) {
        console.error(err);
        }

        console.log('Fieldset Label: '+ metadata.label);
        console.log('Fieldset Fullname: ' + metadata.fullName);
        for (var i=0; i < metadata.displayedFields.length; i++) {
            console.log("Field "+[i]+" inside field set: " + metadata.displayedFields[i].field);
        }

        });
  </script>
</apex:page>

Ouput:


text:
Q: Runtime error using MLFlow and Spark on databricks Here is some model I created:
class SomeModel(mlflow.pyfunc.PythonModel):
    def predict(self, context, input):
        # do fancy ML stuff
        # log results
        pandas_df = pd.DataFrame(...insert predictions here...)
        spark_df = spark.createDataFrame(pandas_df)
        spark_df.write.saveAsTable('tablename', mode='append')

I'm trying to log my model in this manner by calling it later in my code:
with mlflow.start_run(run_name="SomeModel_run"):
    model = SomeModel()
    mlflow.pyfunc.log_model("somemodel", python_model=model)

Unfortunately it gives me this Error Message:
RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063.
The error is caused because of the line mlflow.pyfunc.log_model("somemodel", python_model=model), if I comment it out my model will make its predictions and log the results in my table.
Alternatively, removing the lines in my predict function where I call spark to create a dataframe and save the table, I am able to log my model.
How do I go about resolving this issue? I need my model to not only write to the table but also be logged

A: I had a similar error and I was able to resolve this by taking spark functions like "spark.createDataFrame(pandas_df)" outside of the class. If you want to read-write data using spark do it within the main function.
    class SomeModel(mlflow.pyfunc.PythonModel):
       def predict(self, context, input):
       # do fancy ML stuff
       # log results
       return predictions

    with mlflow.start_run(run_name="SomeModel_run"):
      model = SomeModel()
      pandas_df = pd.DataFrame(...insert predictions here...)
      mlflow.pyfunc.log_model("somemodel", python_model=model)


text:
Q: MVC Code First - Database not generating I am developing a MVC application using Code First Approach. I have defined my model classes in a separate class library project. I have also defined my DBContext class. I have ensured that my DBContext class has the same name as my Connection String. For some reason , I am not seeing the database created. I understand is by defining your classes and connection string, Entity framework would generate the database. I am sure with my connection string as it works fine with my other applications. Could somebody tell what the problem is
   public class Customer
    {
        public int CustomerId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }

    }
 public class TestDbContext : DbContext
    {
        public DbSet<Customer> Customer { get; set; }
    }

App.Config class
<connectionStrings>
    <add name="TestDbContext" connectionString="Data Source=XYZ-PC\MSSQLSERVER2014;Initial Catalog=SalesOrderManagement;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient" />
  </connectionStrings>

A: EF won't generate the database until you call the context. You can insure this by adding a static constructor with your selected initializer:
public class TestDbContext : DbContext
{

    static TestDbContext()
    {
        Database.SetInitializer(new DropCreateDatabaseIfModelChanges<TestDbContext>());
    }

    public DbSet<Customer> Customer { get; set; }
}


text:
Q: python pandas regex find pattern from another row I have a python pandas dataframe with the following pattern:

file_path

/home

/home/folder1

/home/folder1/file1.xlsx

/home/folder1/file2.xlsx

/home/folder2

/home/folder2/date

/home/folder2/date/dates.txt

/home/folder3

I would like to get the parent path in a new column, if there is no parent then call it "ROOT"

file_path
parent_path

/home
ROOT

/home/folder1
/home

/home/folder1/file1.xlsx
/home/folder1

/home/folder1/file2.xlsx
/home/folder1

/home/folder2
/home

/home/folder2/date
/home/folder2

/home/folder2/date/dates.txt
/home/folder2/date

/home/folder3
/home

My attempt:
import re
import pandas as pd

df = pd.DataFrame(["/home", "/home/folder1", "/home/folder1/file1.xlsx",
"/home/folder1/file1.xlsx", "/home/folder1/file2.xlsx", "/home/folder2",
"/home/folder2/date", "/home/folder2/date/dates.txt", "/home/folder3"], columns=["file_path"])

# Get list

file_paths = df.file_path.unique()

def match_parent(x, file_paths):
    x = x.split('/')
    levels = len(x)
    # Check that parent contains all elements of x and the length is 1 less

I was thinking to make a function that:

*

*For each row, compute its length and match those that are 1 length less than the current row AND,

*All previous items match (are exactly the same)
How can I do that?

A: Use pathlib.Path.parent to extract the parent, as follows:
import pandas as pd
import pathlib

df = pd.DataFrame(["/home", "/home/folder1", "/home/folder1/file1.xlsx",
                   "/home/folder1/file1.xlsx", "/home/folder1/file2.xlsx", "/home/folder2",
                   "/home/folder2/date", "/home/folder2/date/dates.txt", "/home/folder3"], columns=["file_path"])

df["parent"] = df["file_path"].apply(lambda x: pathlib.Path(x).parent)
print(df)

Output
                      file_path              parent
0                         /home                   /
1                 /home/folder1               /home
2      /home/folder1/file1.xlsx       /home/folder1
3      /home/folder1/file1.xlsx       /home/folder1
4      /home/folder1/file2.xlsx       /home/folder1
5                 /home/folder2               /home
6            /home/folder2/date       /home/folder2
7  /home/folder2/date/dates.txt  /home/folder2/date
8                 /home/folder3               /home

to match the exact output:
df["parent"] = df["file_path"].apply(lambda x: res if (res := pathlib.Path(x).parent) != pathlib.Path("/") else "ROOT")
print(df)

Output
                      file_path              parent
0                         /home                ROOT
1                 /home/folder1               /home
2      /home/folder1/file1.xlsx       /home/folder1
3      /home/folder1/file1.xlsx       /home/folder1
4      /home/folder1/file2.xlsx       /home/folder1
5                 /home/folder2               /home
6            /home/folder2/date       /home/folder2
7  /home/folder2/date/dates.txt  /home/folder2/date
8                 /home/folder3               /home


text:
Q: how to show image instead of text with link This my grid view
echo GridView::widget([
            'dataProvider' => $provider,
            'columns' => [
                'name',
            ]
        ]);

it will showing name of file with location , But i want to show if file is pdf ,pdf image will show , if file is doc doc image will show with download option, I can do code for downloading the file but i don't know how to show image and download link instead of text.

A: You can also try this way:
echo GridView::widget([
        'dataProvider' => $provider,
        'columns' => [
            'name',
            [
                'attribute' => 'url',
                'format' => 'raw',
                'value' => function ($dataProvider) {
                    return Html::img($dataProvider->url, ['class' => 'img- rounded'], ['alt' => '']);
                }
            ],
        ]
    ]);

A: Try this:
echo GridView::widget([
        'dataProvider' => $provider,
        'columns' => [
            'name',
            'imageColumn:image',
            'urlColumn:url'
        ]
    ]);


text:
Q: Wildfly is concatenating log lines I'm using WildFly 8.2.1 to run some web services. They were developed with CXF (3.1.6) and Spring (4.3.7). I use SLF4J (1.7.25) and Logback (1.2.3) as logging.
I'm facing an strange behavior in wildfly 'server.log'. It seems that the logs generated by my application are being embeeded into wildfly logs, as you can see into the example bellow:
2017-04-27 08:52:12,068 INFO  [stdout] (MSC service thread 1-8) 27.04.2017 08:52:12.068 [MSC service thread 1-8] INFO  x.y.b.s.ScheduleServletListener#contextInitialized(70) - Initializing the servlet context...
2017-04-27 08:52:12,068 INFO  [stdout] (MSC service thread 1-8) 27.04.2017 08:52:12.068 [MSC service thread 1-8] INFO  xx.yyy.blah.something.JNDIUtil#getProxyHost(145) - java:/app_proxyhost: 10.10.10.10
2017-04-27 08:52:12,068 INFO  [stdout] (MSC service thread 1-8) 27.04.2017 08:52:12.068 [MSC service thread 1-8] DEBUG xx.yyy.blah.something.ProxyUtils#setProxy(30) - ProxyHost: 10.10.10.10

I tried to disable logging subsystem and exclude logging modules, but with no effect.
So my question is, how do I avoid this situation?


text:
Q: How can I set the layout_height on an TextView I was wondering if it was possible to set, in the xml, the layout_height parameter to few dp more than the wrap_content value ?
For example wrap_content + 10 dp
Thanks for help in advance

A: Do one thing, try padding  :
use padding for that.
you can add these in your TextView . It will add 5 dp space in  left, top, right and bottom.
android:padding="5dp"

But if you want to add only top and bottom space then add:
android:paddingTop="5dp"
android:paddingBottom="5dp"

A: You can create extra space inside TextView with padding.
You can create extra space outside TextView with margin.

A: You can achieve this by using padding top attribute.
set the text view height to "wrap_content"
set padding attribute as android:paddingTop="10dp"
also set gravity as central_vertical, to align the text central_vertical inside the text view.