text:
Q: Unexpected Response Code 400 with Volley I'm attempting to use the google URL shortener API with Volley and I keep getting the response BasicNetwork.performRequest: Unexpected response code 400. I'm using the POST request to shorten a url. My other POST on the same view is working as well. I've tried all different types of configurations with no luck and this works on my iOS app. Any idea what I'm doing wrong here? My LogCat gives me next to nothing . Code here :
public void ShortenURL() {
        String endpoint = "https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyA32UQwEvxZNPClTsjZWzm6wO1xNGlkH-U";
        final String toShorten = mShortenEditText.getText().toString();

        RequestQueue queue = Volley.newRequestQueue(getActivity());

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, endpoint,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //messageContentEditText.setText("");
                        Toast.makeText(getActivity(), "URL Shortened", Toast.LENGTH_LONG).show();
                        //parse response and display new URL in edittext
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show();
                        error.printStackTrace();
                        System.out.println(error.networkResponse.toString());
                    }
                }) {
            //adding parameters to the request
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("longUrl", "http://wwww.espn.com/newyorkjets/joshmccown");
                //params.put("key", "AIzaSyA32UQwEvxZNPClTsjZWzm6wO1xNGlkH-U");
                return params;
            }

            @Override
            public Map<String, String> getHeaders () throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                //headers.put("Accept","application/json");
                return headers;
            }

        };
        queue.add(stringRequest);
    }

Logcat:
11-16 11:56:47.643 1446-1658/com.a2.reach1 D/NetworkSecurityConfig: No Network Security Config specified, using platform default
11-16 11:56:48.710 1446-1658/com.a2.reach1 E/Volley: [321] BasicNetwork.performRequest: Unexpected response code 400 for https://www.googleapis.com/urlshortener/v1/url
11-16 11:56:48.717 1446-1446/com.a2.reach1 W/System.err: com.android.volley.ServerError
11-16 11:56:48.717 1446-1446/com.a2.reach1 W/System.err:     at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:163)
11-16 11:56:48.717 1446-1446/com.a2.reach1 W/System.err:     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
11-16 11:56:48.717 1446-1446/com.a2.reach1 I/System.out: com.android.volley.NetworkResponse@df41f55
11-16 11:56:48.802 1446-1503/com.a2.reach1 D/EGL_emulation: eglMakeCurrent: 0xa12fcf60: ver 2 0 (tinfo 0xa12f9670)
11-16 11:56:48.917 1446-1503/com.a2.reach1 D/EGL_emulation: eglMakeCurrent: 0xa12fcf60: ver 2 0 (tinfo 0xa12f9670)
11-16 11:57:12.221 1446-1453/com.a2.reach1 W/art: Suspending all threads took: 7.226ms

This was from Hurl.it
Alt-Svc: hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303338; quic=51303337; quic=51303335,quic=":443"; ma=2592000; v="41,39,38,37,35"
Cache-Control: private, max-age=0
Content-Encoding: gzip
Content-Type: application/json; charset=UTF-8
Date: Fri, 17 Nov 2017 04:15:06 GMT
Expires: Fri, 17 Nov 2017 04:15:06 GMT
Server: GSE
Transfer-Encoding: chunked
Vary: Origin, X-Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Xss-Protection: 1; mode=block

{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}


text:
Q: Remote Desktop Services roaming profile leaving local copy after logoff I have a Windows 2008 Remote Desktop Server and a GPO redirecting Remote Desktop Services profiles to a netapp share. This works with one caveat. I am getting a local profile written as well as the roaming profile. An actual full local profile, not a cached copy.
I have already tried deleting the registry key and local profile directories manually. They just reappear on login.

A: Enable the "Delete cached copies of roaming profiles" setting in the GPO that is applied to the RDS server. The setting can be found at:
Computer Configuration|Policies|Administrative Templates|System|User Profiles

redpajama_set_name: RedPajamaStackExchange


text:
Q: Not able to log a fetch's result I'm currently working with nodejs, I created a server side function that returns and prints data from a database.
app.get('/renderMainDashboard', (req,res)=>{ //DASHBOARD DATA
    con.connect(err => {
        if (!err){
            con.query("SELECT * FROM owners", (err, data, fields) =>{
                console.log(data); //IT LOGS THE DATA INTO DE VS TERMINAL
                return data;
            })
        }
    });
});

I need this function to be called from the client side, so there is a class that makes the fetch inside the constructor:
export default class{
    constructor() {
        this.title = "Dashboard";

        fetch('http://localhost:5600/renderMainDashboard') //DEFAULT GET ()
        .then(response => response.json())
        .then(finalResponse => {console.log('Datos recibidos desde el server', finalResponse);});
        //DOESN'T LOG 'Datos recibidos...' TO WEB CONSOLE
       //.then(console.log('Response from then statement'); //IT DOES THE LOG
    }
//----
}

The function actually works, when I try to do the fetch it is still working but I need to log the response. As you may see, there is a then statement with a console.log('Datos recibidos...') but it is not working. Any idea of what I may be doing wrong?
Actual output of the DB:
[
  TextRow {
    id: 1,
    firstName: 'Andres',
    lastName: 'Gonzalez',
    email: 'androsogt@gmail.com',
    personalKey: 'androso+1234-',
    phoneNumber: '35006115'
  },
  TextRow {
    id: 2,
    firstName: 'Pedro',
    lastName: 'Contreras',
    email: 'sirpedro@gmail.com',
    personalKey: 'holamundo',
    phoneNumber: '41508886'
  },
  TextRow {
    id: 3,
    firstName: 'Yuhana',
    lastName: 'Melgar',
    email: 'melgar.keyla@gmail.com',
    personalKey: 'COD2002',
    phoneNumber: '37578639'
  }
]

A: You don't end your request by sending a response. See this example:
app.get('/', function (req, res) {
  res.send('hello world')
})

You should use res.send() method to end your request and send back data.
Why it doesn't log? Because response.json() returns a rejected promise as there's no response (timeout) and hence, second .then doesn't get called.

A: Your express get /renderMainDashboard handler is not sending anything back to the client.
Try replacing:
return data;

with:
res.status(200).json(data); // provided that data is a valid JSON object


text:
Q: How can I send raw binary ping data through a websocket using websocket-client python package? So I'm using the Websocket-Client Python Package to get some information and from time to time I need to send a ping to the server so he know I'm alive the problem is that when I create the function that reads the message and then sends the ping back, the recieved ping and the sent ping are different:
This is the message I'm recieving and sending (the logs are obtained using the enableTrace flag to True in the WebsocketApp class).
++Rcv raw: b'\x81\x0b{"type":6}\x1e'
++Rcv decoded: fin=1 opcode=1 data=b'{"type":6}\x1e'
++Sent raw: b'\x81\x8bbr\xa1\xe3\x19P\xd5\x9a\x12\x17\x83\xd9T\x0f\xbf'
++Sent decoded: fin=1 opcode=1 data=b'{"type":6}\x1e'

I want to send the same raw b'\x81\x0b{"type":6}\x1e' bits through the websocket but as you can see it encodes it in some way and the server disconects me.
This is the code I'm using:
if _message["type"] == 6: #Filter the message with the type 6 (6 means ping from the server)
    wsapp.send('{"type":6}' + '\x1e') #Send back a pong message (6 also is a pong if the client sends it)

I know there is a function in the websocket class from this package (websocket.send_binary(binary_message)) but it sends the same data to the server as if I was sending it with the normal send function.
I've also seen that every time I send that same string ('{"type":6}' + '\x1e') there is a different raw message sent to the websocket.
Thank you!


text:
Q: ssl taking too much time on nginx server I have a website in nginx, php-fpm, and use lets encrypt centbot for the ssl
Here is a check that checks response time for my website:
SEE THE SCREENSHOT
here is the full config of virtualhost for that website:
fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=WORDPRESS:300m inactive=90m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

server {

        listen 80;
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name example.com www.example.com;

        root      /var/www/example.com/public_html;
        index     index.html index.htm index.php;

        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

        #Force redirect http to https
        if ($scheme != "https") {
                return 301 https://$host$request_uri;
        }

        location / {

            #wp perma directive
            try_files $uri $uri/ /index.php?$args;

        }

        # Pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        location ~ \.php$ {
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

                fastcgi_cache_bypass $skip_cache;
                fastcgi_no_cache $skip_cache;
                fastcgi_cache WORDPRESS;
                fastcgi_cache_valid 90m;
                include fastcgi_params;
        }

        #DHPARAM
        ssl_dhparam /etc/ssl/certs/dhparam.pem;
        location ~ /.well-known/acme-challenge/ {
                root /var/www/example.com/public_html;
                allow all;
        }

        ## SSL
        ssl_session_cache shared:SSL:20m;
        ssl_session_timeout 10m;

        ssl_prefer_server_ciphers On;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS;

        ssl_stapling on;
        ssl_stapling_verify on;
        resolver 8.8.8.8 8.8.4.4 valid=300s;
        resolver_timeout 10s;

        #Gzip Settings
        gzip on;
        gzip_vary on;
        gzip_proxied any;
        gzip_comp_level 2;
        gzip_buffers 16 8k;
        gzip_http_version 1.1;
        gzip_min_length 5000;
        gzip_types text/xml text/css text/javascript;
}

do these rules have anything to do with it? is there some sort of ssl cache I can implement to make ti faster?
SSL
ssl_session_cache shared:SSL:20m;
ssl_session_timeout 10m;

ssl_prefer_server_ciphers On;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS;

ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 10s;


text:
Q: SQL not finding a result when using WHERE Here's my SQL:
$query = mysqli_query($db, "SELECT * FROM chat WHERE to = '0' ORDER BY id DESC LIMIT 0,30");

And my table looks like this:

Why does it not find it? If I remove the WHERE to = '0' it works fine.


text:
Q: Spring Security SpEL error in @Query of Spring Data JPA for new Role:Ordinal parameter not bound : 3 Original query which works fine:
 String authorizeQuery = " and e.id in (select emp.id from Employee emp, Employee loggedIn where " +
            " 1 = ?#{hasAuthority('ADMIN') ? 1: 0} or 1 = ?#{hasAuthority('OPERATOR') ? 1: 0} or (loggedIn.oauthUser.id = ?#{principal.id} " +
            " and loggedIn.id in (emp.id, emp.lead.id, emp.team.leader.id)))";

I tried to add another role: SUPER_ADMIN in authentication like below:
String authorizeQuery = " and e.id in (select emp.id from Employee emp, Employee loggedIn where " +
            " 1 = ?#{hasAuthority('ADMIN') ? 1: 0} or 1 = ?#{hasAuthority('OPERATOR') ? 1: 0} or 1 = ?#{hasAuthority('SUPER_ADMIN') ? 1: 0} or (loggedIn.oauthUser.id = ?#{principal.id} " +
            " and loggedIn.id in (emp.id, emp.lead.id, emp.team.leader.id)))";

authorizedQuery is being used here:
@Query("select e from MyModel e " +
          " where " +
          " e.isActive=1 and "+
          " (:fieldOne is null or e.fieldOne = :fieldOne) and " +
          " (:fieldTwo is null or e.fieldTwo= :fieldTwo) " + authorizeQuery)
   Page<MyModel> searchAllMyModel(@Param("fieldOne") String fieldOne,
                                    @Param("fieldTwo") String fieldTwo, Pageable pageRequest);

When I request with this change, I get this error:

org.springframework.dao.InvalidDataAccessResourceUsageException: Ordinal parameter not bound : 3; nested exception is org.hibernate.QueryException: Ordinal parameter not bound : 3

I have that role present in my associated Table.


text:
Q: How to clear the text after deleting a message having scenario like this.
i have list of comments to one post when i delete a comment that is deleting and getting success message.but here that is not removing until and unless refresh the page.
used $route.reload()
this is not solution
Thanks in advance

A: suppose your comments array is $scope.commentsArray=['comment 1', comment 2];
By comment id or any identity that a particular comment have by which you can find out the index of that comment(which you want to delete) in array like this:
var a = $scope.commentsArray.indexOf("comment1");

After that Just splice this comment form your array and make a hard copy in the scope like this:
$scope.commentsArray = $scope.commentsArray.splice(index, 1);

after doing this  definitively changes will reflect on your view .. thanks it will help you

A: If your comments are coming from server than you should call get request for your comments again after getting success from deleting your comment.
Hope this helps....


text:
Q: Sailed back safe See this problem:

*

*How about the ship then?

*It sailed back _____.
A. safe
B. safely
C. safety

The answer is A. Although it's understandable, I still wondered why B isn't the answer?

A: In my opinion, B is a much better answer.
It's true that we can say He came back safe and sound (he was safe and well when he arrived), but sailed refers to the ship's journey, not just its arrival, so an adverb seems more appropriate.

A:
It sailed back safe.

= the ship sailed back and the ship was safe. (It is quite possible that the ship was badly damaged and the journey was far from safe. It was only when it arrived that the ship and crew could be said to be safe.)

It sailed back safely.

= the ship sailed back in a safe manner. This implies that all due caution was observed.
Compare
He arrived drunk - he arrived and he was drunk.
He arrived drunkenly - he arrived in a manner that suggested he had been drinking, although he could have been ill, dizzy, etc.


text:
Q: How to exclude folders when using TFS in vscode? I am using Visual Studio Team Services extension in VS code for check in. https://marketplace.visualstudio.com/items?itemName=ms-vsts.team
I am now trying to check in change in angular project, but I am annoyed by excluded 16000 files which are from node_modules:

How can I exclude those files from source control? In Visual Studio I used .tfignore file, how about vscode?

A: I had the same problem creating a dotnet core 2 cli react project using visual studio code and TFVC. I created a .tfignore file in the root (same place as the .gitignore).
Then I copied the content in the .gitignore file into .tfignore file, save and done...

A: So I followed everything that the others mentioned, but was missing the following, for .tfignore to skip the files:
Place the following in you Visual Studio Code's settings.json file.
"tfvc.restrictWorkspace": true

settings.json location:
File - Preferences - Settings (top right-hand corner(Open Settings (JSON)))
That I found the answer here.


text:
Q: What is the smallest number of subsets in such a subdivision? Given any $30$ points in the plane, what is the smallest number of
subsets in a subdivision of the set of $30$ points into subsets such
that all the points in each subset are on the boundary of the convex
hull of the subset? and how about $60$ points? Thanks a lot.

A: I am going to assume that the points are no three on a line. I think that only makes things harder anyway.
For 30 points (or even 25) 5 subsets can be required. I don't know if 5 subsets are always sufficient, but 6 are. For 60 points (or even 57) 9 subsets can be required however 11 are sufficient for any configuration of 60 points.
It is known that for any $N$ there is a set of $2^{N-2}$ points in the plane so that no $N$ are the vertices of a convex $N$-gon. So discard 7 points from a heptagon free set of 32  to get 25 points with no convex heptagons. Similarly, discard 7 points from 64 to get a set of 57 points with no convex octagons.
There is the conjecture that $2^{N-2}+1$ points are enough to force a convex $N$-gon but that is only known for $N=$3,4,5,6. So with 30 points there may be no heptagons but there will be hexagons until we have used up all but 16 points.  Thus we are assured that, even with a greedy strategy, it can't be worse then using  3 hexagons, then a pentagon, a square, and a triangle for a total of 6. If it is also true that any set of 33 points contains the vertices of a convex heptagon, then one gets a bound of 11 subsets for 60 points (4 7-gons, 3 hexagons, a square and then, perhaps, 2 more subsets for the last 4 points.) Even without that conjectured result, we can still say that 11 subsets suffice because we can use 5 hexagons getting down to 30 points left and then we already said that 6 more are enough.
I am assuming that the convex subsets need not have disjoint interiors. I don't think there is an advantage to considering shared vertices. It may be that there are reasons to know that less subsets suffice.

A: Consider the general problem of $n$ points (no three on a line). It is
known that some $N$ of these points are in convex position if
$n=4^N$. Thus for $n$ points we can find $\log_4 n$ points in convex
position. After removing them, we can find $\log_4(n-\log_4 n)$ points
in convex position, etc. It takes about $n/(\log n)$ steps (does someone
know a more accurate estimate?) to remove all the points by this
procedure, so we get an upper bound on the number of subsets which is
on the order of $n/(\log n)$. Can this be improved?


text:
Q: Prevent Excel from saving UDF path to formula cells I'm using a custom Add-in which adds functions to Excel, like UDF1(param1, param2).

(1) example call in cell:
=UDF1(param1, param2)

When saving workbook1, which implements UDF(), Excel silently adds the path to the Add-in to each call of UDF(). This can be seen when uninstalling the Add-in and reopening workbook1.

Excel asks to update external references, I click "don't update".
(2) new cell content: ='\...\user\Desktop\Addin1'!UDF1(param1, param2)

How to prevent Excel from saving the path to the Add-in when saving the workbook?
I would like the new cell content (2) to match the original content (1).
(This is particularly annoying when different people are using the same Add-in, respectively installed in a different location of their computers, as it requires deleting the '\......!' path from each cell each time the workbook is opened by another user.)
Edit: Remove AddIn path from UDF in Excel formula and http://www.jkp-ads.com/Articles/FixLinks2UDF.asp is not what I'm looking for, as the suggested "solutions" are workarounds.

A: You researched very well the issue*, and you found the answer that you did not like: what you want to do is not possible.
That is the way Excel refers to UDFs (similarly, when you refer to cells in open vs. not-open workbooks).
You need a workaround, either of those proposed in the links you provide, or perhaps something alternative.
.* It is not the typical case.

A: As always, there is a way of using user defined functions (UDF) from an addin.
Let us have a function in an excel Addin-File B.xlam in a Module we have
Public Function Volume(a as Double, b as Double, c as Double)
    Volume = a * b * c
End Function

This File has the Workbook.IsAddin-Property set to true and is stored in the same directory as the consuming Excel Sheet A.xlsm. This Excel Sheet has a VBA-Reference to file B.xlam. If You then use the Function Volume in any Cell of A.xlsm, the function is delegated to VBA and VBA also looks, if the Function Volume exists in the referenced File B.xlam.

So far so good. If in the workbook-view of Excel, refereces are shown (in the data-ribbon), then change the reference from B.xlam to the file A.xlsm itself. So finally there is no direct Excel-Reference from A.xlsm to B.xlam. The only reference exists is a VBA-Reference.
Now, if the Addin-File B.xlam is loaded before the File A.xlsm the reference always refers to the open file. Otherwise VBA looks for the original path and if that does not exist, it looks in the workbook-path.
So this way the UDF may be referenced via VBA and the addin may sit anywhere, if loaded bevore the consuming file or in the same directory of the consuming Excel-file.


text:
Q: how to use background-image and hover I've got the following:
table.inactiveTable thead {
    background: #efe;
    background: -moz-linear-gradient(top,#efe,#ded);
    background: -webkit-gradient(linear,0% 0,0% 100%,from(#efe),to(#ded));
    filter: progid:DXImageTransform.Microsoft.gradient(gradientType=0,startColorstr=#efe,endColorstr=#ded);
    height: 40px;
}

table.inactiveTable th:hover {
    background: -moz-linear-gradient(top,#efe,#F8FFB5);
    background: -webkit-gradient(linear,0% 0,0% 100%,from(#efe),to(#F8FFB5));
    filter: progid:DXImageTransform.Microsoft.gradient(gradientType=0,startColorstr=#efe,endColorstr=#F8FFB5);
    cursor : pointer;
}

then, in runtime i add asc class for that element, the style is the follows:
.asc, .asc:hover{
    background-image: url(arrow_up.png);
    background-repeat: no-repeat;
    background-position : left;
}

It works - i mean there's the correct image in the background. But it disappeads on hover event - th:hover works.
I mean: this is what i see when i add asc class:

and this is what i get when i hober over this element:

How can i make them work together - i mean to make inage stay while changing the gradient colours?
My goal is to be able to add a background image for the specific (table column header) element on click event, but not to loose this image on hover.
added:
html:

            id
            bccu
...

A: Add-
.inactiveTable th.asc, .inactiveTable th.asc:hover{
    background: url(arrow_up.png) no-repeat left top;
}

It will work


text:
Q: $3\times 3$ real matrix similar to a specific matrix I have a $3\times 3$ real matrix $A$ with one real eigenvalue $\lambda$ and two complex ones. Is it true that there is a real matrix $P$ such that $P^{-1}AP$ is of the form $\begin{pmatrix}\lambda & 0 & 0\\ 0 & a & -b\\ 0 &b &a\end{pmatrix}$?
If this is true, how can I prove it?
Thanks!

A: If $A$ has eigenvalues $\lambda, a+bi, a-bi$
then there exist a $P$ such that
$A = P\begin{bmatrix} \lambda\\&a+bi\\&&a-bi\end{bmatrix}P^{-1}$
$\begin{bmatrix} \lambda\\&a &b\\&-b&a\end{bmatrix} = \begin{bmatrix} 1\\&\frac{1}{\sqrt2}1&\frac{1}{\sqrt2}i\\&\frac{1}{\sqrt2}i&\frac{1}{\sqrt2}1\end{bmatrix}\begin{bmatrix} \lambda\\&a+bi\\&&a-bi\end{bmatrix}\begin{bmatrix} 1\\&\frac 1{\sqrt2}&-\frac 1{\sqrt2}i\\&-\frac 1{\sqrt2}i&\frac1{\sqrt2}\end{bmatrix}$
$A = P\begin{bmatrix} 1\\&\frac 1{\sqrt2}&-\frac 1{\sqrt2}i\\&-\frac 1{\sqrt2}i&\frac1{\sqrt2}\end{bmatrix}\begin{bmatrix} \lambda\\&a &b\\&-b&a\end{bmatrix}\begin{bmatrix} 1\\&\frac{1}{\sqrt2}1&\frac{1}{\sqrt2}i\\&\frac{1}{\sqrt2}i&\frac{1}{\sqrt2}1\end{bmatrix}P^{-1}$


text:
Q: How can I modify vmlinux.lds to break up a built-in.o? So I'm working with ucLinux under the NXP LPC1788 processor (ARM-CortexM3, no MMU).  The ucLinux port was orignally done by Emcraft Systems.
The 1788 has 512KiB of onboard flash (called eNVM) which is faster to access than the rest of memory connected via the external memory controller.  Emcraft's linker script has a portion where you can relocate critical parts of the kernel to this eNVM area.  I'm using 80K for the bootloader so I have 432K free to stuff with as much kernel as I can.
So the linker script, vmlinux.lds.S, has a portion that begins like this:
#ifdef CONFIG_KERNEL_IN_ENVM
_envm_loc = .;

.envm  ENVM_PHYS_OFFSET + CONFIG_KERNEL_IN_ENVM_OFFSET * 1024 : {
    _envm_start = .;

#if CONFIG_KERNEL_IN_ENVM_SIZE>0
    __exception_text_start = .;
    *(.exception.text*)
    *(.exception.rodata*)
    __exception_text_end = .;
    SCHED_TEXT
    LOCK_TEXT
    KPROBES_TEXT

    usr/built-in.o(.text)
    usr/built-in.o(.rodata*)
    init/built-in.o(.text)
    init/built-in.o(.rodata*)
    mm/built-in.o(.text)
    mm/built-in.o(.rodata*)

...and so on.  As you can see, entire subdirectories are being pulled in via their built-in.o object file.
As I get closer and closer to the end of the flash space, I'd like to have a bit more control over what gets linked here.  drivers/built-in.o, for example, won't fit in the free space but if I could get drivers/usb and drivers/input here, that would help a lot.
If I modify the linker script to have just those portions, like this:
    drivers/usb/built-in.o(.text)
    drivers/usb/built-in.o(.rodata*)
    drivers/input/built-in.o(.text)
    drivers/input/built-in.o(.rodata*)

then I get duplicate symbol errors when drivers/built-in.o gets linked.  I can't see where that happens exactly, so that's part of the problem I think.
So the question: Is there a way to link individual built-in.o files to different regions without linking the master .o built at the top of the directory?
I've put the whole linker file at http://pastebin.com/qcj6rHme if anyone wants to take a look.
Thanks!

A: If you're going to link usb and input directly, drivers/built-in.o should not include them.  Modifying Kbuild to build the subdirs but not include them is a bit tricky; those two elements will have to filtered out of obj-y where drivers/built-in.o is generated -- if they aren't included in obj-y they won't get built at all.


text:
Q: Inserir PHP em div com Jquery (.html) Eu tenho uma div que vai receber o conteúdo, tenho um menu vertical, que vai definir o conteúdo que o fulano vai ver. O problema está que ele faz o .load() do arquivo, mas ele carrega até onde aparece

Tentei pelo .html(), e colocar um include .php, ele até faz, mas dá o mesmo problema. Não lê as informações depois do PHP. Tentei escrever a página dentro do .html(), mas também não funciona, fiz as correções de aspas duplas com barra invertida (\") e não funcionou.
Nos bibliotecas oficiais não consegui uma resposta se o caso for com Banco de Dados e PHP. mas não consigo compreender, por que não funciona.
Meu código é um pouco grande, pois são vários links e os conteúdos são extensos, fiz um exemplo reduzido, porque acho que o problema é de conceito, não de sintaxe.

*

*O problema não está no PHP e MySQL, porque se eu abro a página somente, fora do jQuery, funciona tranquila, pega todos os dados.

*O banco jQuery e a conexão com MySQL já estão sendo feitas e funcionam, não coloquei para não encher de código inútil.
jQuery:

HTML
  Link 1
  Link 2

Este conteúdo é para ser alterado, conforme o usuário vá clicando no link... O link 1 funciona normal, pois não tem php, o link 2 funciona até aparecer o PHP...

O PHP (link2.php)
  <?php
$query = @mysql_query("SELECT * FROM dados;");
while($linha = @mysql_fetch_array($query)) { ?>

<?php echo $linha['nome']. " - ". $linha['sobrenome']; ?>
Veja a foto

<?php } ?>

A:
TL;DR - Inclua os arquivos php que definem a conexão em link2.php. O  .load() do jQuery só irá funcionar quando você puder fazer uma requisição direta para link2.php e receber o fragmento html desejado.

Você está confundindo duas coisas. A interpretação de comandos PHP server-side (include)  com funcionalidades ajax client-side.
O método loaddo jQuery espera que o link2.php retorne uma página ou fragmento html. No caso o link2.php sozinho não produz nada, apenas falha silenciosamente (@) devido a falta de uma conexão ativa.
Request 1 -> Pagina 1 -> Request 2 -> link2.php (sem conexão) = Falha silenciosa

O que você precisa fazer é criar uma página link2.php que funcione sozinha (ou seja, retorne resultados quando um request for feito diretamente pelo navegador). Para isso você deve incluir código para conectar no banco e tudo o que for necessário para imprimir os resultados.
Veja que essa funcionalidade é bem diferente de um require ou include; esses fazem tudo do lado do servidor:
Request 1 ->
    Pagina 1, cria conexões etc
        include 'link2.php'
            usa conexão "definida" na página 1
<- Servidor interpreta o conjunto e navegador recebe uma resposta HTML unificada

Nesse caso não existe um segundo request, o conteúdo de link2.php é interpretado junto com o conteúdo da página atual pelo servidor como se fosse mais um pedaço de código PHP no corpo da página. O navegador não tem ciência de que esses são dois arquivos separados.

A: Tente usar um aplicativo como o firebug para debugar a transação e verificar se está recebendo os dados corretamente durante a requisição feita com o jQuery.
Tente o exemplo a seguir:

A:     //menu.php
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>

            Abrir Tela 1
            Abrir Tela 2

    //page1.php

Pagina Link 1

    //page2.php

Pagina Link 2

<?php
    $conexao = new PDO("mysql:dbname=generics;host=localhost", "root", "senha");
    $tables  = $conexao->prepare("show tables");
    $tables->execute();
    print_r($tables->fetchAll());
?>

A página menu chama a page1.php e a page2.php sendo que a page2.php tem uma conexão com o banco de dados com a classe PDO, cuidado em colocar @, porque, omite erros e a classe mysql já é obsoleta nas novas versões do PHP, logo serão retiradas, trabalhe com mysqli ou PDO (PDO acredito ser melhor pela padronização de codificação, servindo a mesma para diversões tipos de bancos) ...


text:
Q: Slot type AMAZON.NUMBER won't handle larger number My intent schema uses an AMAZON.NUMBER slot:
{
  "intents": [
    {
      "intent": "MyIntent",
      "slots": [
        {
          "name": "Foo",
          "type": "AMAZON.NUMBER"
        }
      ]
    }
  ]
}

Smaller numbers like "two thousand" show up properly in the IntentRequest...
{
  "version": "1.0",
  "request": {
    "Intent": {
      "name": "MyIntent",
      "slots": {
        "Foo": {
          "name": "Foo",
          "value": "2000"
        }
      }
    },
    "type": "IntentRequest"
  }
}

Unfortunately, it doesn't seem to handle expressions such as "four point five million":
{
  "version": "1.0",
  "request": {
    "Intent": {
      "name": "MyIntent",
      "slots": {
        "Foo": {
          "name": "Foo",
          "value": "?"
        }
      }
    },
    "type": "IntentRequest"
  }
}

Do I need to use an AMAZON.LITERAL slot and feed the value into my own number expression parser? Or is there a better way?

A: The AMAZON.NUMBER slot type will not handle well sequences of numbers (e.g. a telephone or bank account number) and in my experience it will not handle decimals or numbers that have any "utterance" between them. On top of that,  AMAZON.LITERAL is deprecated so it may be difficult to capture this kind of numbers using the current API. Sorry.


text:
Q: finding joint pdf Suppose the continuous random variable
$Y = X + V$,
where $X$ & $V$ are continuous random variables with parameters ($\mu_x,\sigma_x$) & ($\mu_y,\sigma_y$).
How should I go about finding the joint pdf $f_{\mathbf{x,y}}(x,y)$?
I am seeking a generalized method for the above question, independent of the nature of the random variables.

A: In general, the mean and variance do not determine the distribution (and even if they're Gaussian, it does not determine the joint distribution - you need the covariance (which is zero if they're independent)) - you actually need the joint distribution of $X$ and $V$ to solve this problem.
A simple way to do these sort of problems is to simply integrate:
$F(x,y) = P(X \leq x \text{ and } Y \leq y) = P(X \leq x \text{ and } X+V \leq y)$, then write this down as a 2 dimensional integral in the $X,V$ space, then take the second mixed partial.
Alternatively, note that the mapping $(X,V) \to (X, X+V)$ has Jacobian determinant $J=det([1, 1;0,1]) = 1$.
Thus, you can write the PDF of $(X,Y)$ by noting $V=X-Y$ as $f_{XY}(x,y) = f_{XV}(X, Y-X)/|J|$ using the Jacobian rule for PDF transformations (See proposition 1.11.1 in these notes or similar).
Possibly related: A useful thing to note is that when you add independent random variables, you convolve their densities (if some of them are mixed type or discrete, you can write their densities out with delta functions to do this).


text:
Q: Android: Write to /sys/ directory I'm developing an application that is not intended to be released as a standard app. It'll be run on a single rooted device.
I require the ability to write to a file in the /sys/ directory. The file in question is owned by root and has -rw-rw-rw- permissions.
I am aware that there may be restrictions on the VM my code runs within that prohibit writing to this area of the file system, but I have observed another application apparently do this.
Is this possible? How might it be achieved? It doesn't matter if the phone needs to be rooted (the dev one I'm using is).

I've looked into simply using a FileWriter to write to the file, causing the following error on .flush():
java.io.IOException: Invalid argument
at org.apache.harmony.luni.platform.OSFileSystem.writeImpl(Native Method)

I've also tried executing a shell command from Java, both with and without "su". Which returned "request rejected" and "Permission Denied" respectively.
Process process = Runtime.getRuntime().exec("echo 'hello' > /sys/file");

Lastly I've tried using the NDK and JNI in case C some how magically managed to write to this file. When attempting to fflush to this file I receive an EOF (meaning an error has occured).

All suggestions greatly welcome!

A: The method Runtime.getRuntime().exec(String) simply treats the input string as a file name of an executable. It won't accept your echo command.
You should use the Runtime.getRuntime().exec(String[]) instead, like:
String[] cmd = { "/system/bin/sh", "-c", "echo xxx > /sys/somefile", };
Runtime.getRuntime().exec(cmd);
Alternatively, to write something to a sys file, you should use java.io.PrintWriter class.
Please refer to http://www.netmite.com/android/mydroid/frameworks/base/core/java/android/os/Debug.java and search for 'startNativeTracing()' for an example.
Of cause, all of above can only work if the sys file is writable for your application.

A: i think you're going to have to share the actual code and tell us what you're really trying to do. "Invalid argument" corresponds to write(2) failing with EINVAL, which happens when you're trying to write to something unsuitable. not a permissions thing; a type thing. this file isn't a regular file, is it?

A: You have to modify your manifest so your program asks for root user acess.
http://developer.android.com/reference/android/Manifest.permission.html
public static final String FACTORY_TEST
Since: API Level 1
Run as a manufacturer test application, running as the root user. Only available when the device is running in manufacturer test mode.
Constant Value: "android.permission.FACTORY_TEST"


text:
Q: A word for decorations added to letters Is there a word for the artistic decorations that are often added to letters in some type-faces / fonts (e.g. caligraphy, etc.)
I'm thinking like a serif, but as far as I know, (I'm open to correction) a serif is a specific tail that's added to some letters, whereas I'm looking for a word that encapsulates all the different types of decorative strokes or flourishes that can be added to letters.

A: The word you are looking for is swash, which is a term of art in typesetting. The OED's 1989 definition for this is:

*Printing Applied to old-style capital letters having flourished strokes designed to fill up unsightly gaps between adjacent letters.

Most italic faces, for example, use a sloped roman by default for their capitals, reserving the swash versions for the true italic capitals as non-default alternates.
Robert Bringhurst defines swash rather better than the OED does in his  Elements of Typographic Style:

Swash A letterform reveling in luxury. Some swash letters carry extra flourishes; others simply occupy an abnormally large ration of space. Swash letters are usually cursive and swash typefaces therefore usually italic. True italic capitals (as distinct from sloped roman capitals) are usually swash.

Here, also from Bringhurst, is an illustration of the difference. Compare his lines 3.1 and 4.1:

Here from the Cooper Italic Pro face is another illustration of swash alternates:

Notice how the line that reads:

Dusted off. Whittled into shape.

occurs twice. The first time it uses true italic (cursive, with swash) capitals for the D and the W, and the second time it uses false italic (sloped roman) capitals for those two letters. The difference between italic and roman is NOT the slope or slant; rather, it's the letterforms themselves.
(As you see, the Georgia face we use does not have true italic capitals. Alas.)
Bringhurst further observes that:

Herman Zapf's Zapf Renaissance italic and Robert Slimbach's Poetica are faces in which the swash can be extended to the lower case.

Here is a demo of Zapf Rennaisance swash italics:

But for super-swash, nothing can beat Herman Zapf's Zapfino, a script face not an italic one. Here's a demo:

And here is another:

Whereas here is a Poetica demo:


text:
Q: Sharing sqlite database between two iphone applications I want to share my sqlite database between two iphone applications
In one application i am reading and writing into that database and in another
I am reading that data
Can we do this in iphone? And if yes How?
Appreciate any help...
Thanks,
Bhagyashree Dayama

A: iPhone Apps are sandboxed.. In simple terms If you create/Install a App, a folder will be created where all your files will be stored. In your case you will have your DB inside that folder.. Your app cannot access anything outside its folder. The same way Another App cannot access your Apps files..
So the answer for your question will be NO..

A: No. There is no way to access files outside your applications sandbox.

A: As everybody saying my answer is also NO..
but you can achieve the database sharing having a common database at the server and then syncing it on the both local applications.


text:
Q: Run different tasks differs only with one file I have a complicated .grunt file which a lot of things. Among them is concat. It looks in the following way
concat: {
  libraries : {
    src : [many files],
    dest: 'libraries.js'
  },
  ... a lot of similar things,
  myCode : {
    src : [
      'config.js',               // this is the main problem
      ... a lot of files
    ],
    dest: 'myCode.js'
  },
}

So the main problem is that I have my preproduction environment and real environment. And I want different config to be included for each of them (let's say config_dev.js and config_prod.js).
The way I currently handle it is by creating different code_ parts:
  myCode_prod : {
    src : [
      'config_prod.js',               // this is the main problem
      ... a lot of files
    ],
    dest: 'myCode.js'
  },
  myCode_dev : {
    src : [
      'config_dev.js',               // this is the main problem
      ... a lot of files
    ],
    dest: 'myCode.js'
  }

And then register 2 different tasks:
grunt.registerTask('default', [
    // my other tasks
    'concat:libraries',
    'concat:otherthings',
    'concat:myCode_prod'
]);

and
grunt.registerTask('default', [
    // my other tasks
    'concat:libraries',
    'concat:otherthings',
    'concat:myCode_dev'
]);

It works nice and correct, but the problem is that myCode_dev differs only in one file and a lot of other files (like 20 and they are adding/changing every week). And here is the problem: sometimes I forget to include/copy all of them and the problems starts.
So is there a way to do it in a different way?
P.S. I know that the title is bad, but can not find a better one. So please change it as you wish.

A: I think what you need is to separate dev from dist early on. On this project I have a similar approach that might prove useful. The main idea is to register two tasks and pick a default one (you'd still have to have a look on the tasks that contain dev and dist variations - in this case uglify and compass, to understand it fully):
// Compile production files
grunt.registerTask('dist', [
    'jshint',
    'jasmine',
    'uglify:dist',
    'compass:dist'
]);

// Compile developer friendly environment
grunt.registerTask('dev', [
    'jshint',
    'jasmine',
    'uglify:dev',
    'compass:dev'
]);

// Default task(s).
grunt.registerTask('default', 'dev');

The last line means that dev would run by default, when you run the command grunt by itself. If you'd like to to a build for production, you'd have to be specific, like: grunt:dist.
Note that this project is grunt watch-centric, which I believe is the best workflow. The watch task, if configured smartly, will only parse/compile certain files when the files being watched are changed. In that way CSS files are not compiled/concatenated/minified when changes are only done to javascript files, only javascript files. It's all there in that project, feel free to explore it. Cheers!


text:
Q: Not able to connect the Google Cloud Load Balancer generated using ingress-nginx on Browser after adding the LB IP in my windows hosts file I am new to Kubernetes in GCE-GKE, I was trying to build and deploy the nodeJS app in GCE-GKE cluster using the skaffold.Yaml. I can see image got build and also deployed withoutr any issue but when I tried to access GET the index.ts file on browser, I can't. I really don't understand what might have gone wrong or I may have missed something at LB or ingress-nginx.
Below id the skaffold.yaml
apiVersion: skaffold/v2alpha3
kind: Config
deploy:
  kubectl:
    manifests:
      - ./infra/k8s/*
build:
  # local:
  #   push: false
  googleCloudBuild:
    projectId: xxxxxxxxxxxx
  artifacts:
    - image: us.gcr.io/xxxxxxxxxxx/auth
      context: auth
      docker:
        dockerfile: Dockerfile
      sync:
        manual:
          - src: 'src/**/*.ts'
            dest: .

Below is ingress-srv.yaml
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: 'true'
spec:
  rules:
    - host: ticketing.dev
      http:
        paths:
          - path: /api/users/?(.*)
            backend:
              serviceName: auth-srv
              servicePort: 3000

Below is auth-depl.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: auth-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: auth
  template:
    metadata:
      labels:
        app: auth
    spec:
      containers:
        - name: auth
          image: us.gcr.io/xxxxxxxxxxxxx/auth
---
apiVersion: v1
kind: Service
metadata:
  name: auth-srv
spec:
  selector:
    app: auth
  ports:
    - name: auth
      protocol: TCP
      port: 3000
      targetPort: 3000

Below is package.json
{
  "name": "auth",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "ts-node-dev --poll src/index.ts"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/express": "^4.17.6",
    "express": "^4.17.1",
    "nodemon": "^2.0.4",
    "typescript": "^3.9.5"
  },
  "devDependencies": {
    "ts-node-dev": "^1.0.0-pre.44"
  }
}

Below is index.ts
import express from 'express';
import { json } from 'body-parser';

const app = express();
app.use(json());
// /api/users/currentuser
app.get('/users', (req, res) => {
  res.send('Hello');
});

app.listen(3000, () => {
  console.log('Great');
  console.log('listening on port 3000!!!!!');
});

Below is docker file
FROM node:alpine

WORKDIR /app
COPY package.json .
RUN npm install
COPY . .

CMD ["npm", "start"]

A: Which tools you use to manage domain configuraion?
Step 1: As far as i know, after you init nginx on your k8s cluster, you need add a DNS record to map a domain (or subdomain) in your domain (ticketing.dev) to external IP or external DNS of your k8s cluster which nginx have regenerated for you (i use an A record normally).
Step 2: After that, when you have deployed your application, you need to set the domain of your app (domain name you specify in your ingress yaml file) is a CNAME record of the above (A) record.
You can verify your domain verify cation by use nslookup command.
If you do not use proxy for your domain, both of above domain (A and CNAME record) will be resolve to the same your externall IP of your k8s cluster.
The purpose of 2 above steps is that you let the DNS server know where (which IP) to resolve when the DNS server get a req ask about any your subdomain (domain). That why you can use nslookup command to verify your configuration.
Below is the tools i have used to manage DNS of our domain:
https://www.namecheap.com/support/knowledgebase/article.aspx/9607/2210/how-to-set-up-dns-records-for-your-domain-in-cloudflare-account
example


text:
Q: global variable within a function i am trying to tell one function to remove the button lb from the screen using place.forget() but i am getting an error because i have defined the button lb as a global variable within another function and so each time it tries to recall it it doesn't 'see' the global variable. I know why it's giving me the error i'm just unsure of how to correct it, any help would be greatly appreciated.
def page4():
    master.title('Page 4')
    #draw
    c19.grid(pady=slpady)
    c19.grid(row=sly,column=slx1)
    c20.grid(row=sly,column=slx2)
    c21.grid(row=sly,column=slx3)
    c22.grid(row=sly,column=slx4)
    c23.grid(row=sly,column=slx5)
    c24.grid(row=sly,column=slx6)
    rec.grid(row=rec_y, column=rec_x,columnspan=3)
    clear_4.grid(row=clear_y, column=clear_x,columnspan=3)
    #hide
    c1.grid_remove()
    c2.grid_remove()
    c3.grid_remove()
    c4.grid_remove()
    c5.grid_remove()
    c6.grid_remove()
    c7.grid_remove()
    c8.grid_remove()
    c9.grid_remove()
    c10.grid_remove()
    c11.grid_remove()
    c12.grid_remove()
    c13.grid_remove()
    c14.grid_remove()
    c15.grid_remove()
    c16.grid_remove()
    c17.grid_remove()
    c18.grid_remove()
    new_show.grid_remove()
    save_show.grid_remove()
    load_show.grid_remove()
    pre_1.grid_remove()
    pre_2.grid_remove()
    pre_3.grid_remove()
    pre_4.grid_remove()
    clear_1.grid_remove()
    clear_2.grid_remove()
    clear_3.grid_remove()
    lb.place_forget()

#Presets
def presets():
    master.title('Presets')
    pre_1.grid(row=1,column=1,padx=ppadx, pady=ppady)
    pre_2.grid(row=1,column=2,padx=ppadx, pady=ppady)
    pre_3.grid(row=2,column=1,padx=ppadx, pady=ppady)
    pre_4.grid(row=2,column=2,padx=ppadx, pady=ppady)
    global lb
    lb=Button(master,width=20,height=5,text='LOCK',bg='burlywood1',command=lockscreen)
    lb.place(x=450,y=580)

the error im getting is:
Exception in Tkinter callback Traceback (most recent call last):
    File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
        return self.func(*args)
    File "C:\Users\Josh Bailey\Desktop\pi_dmx\pi_dmx512py2.py", line 412, in page4
        lb.place_forget() NameError: global name 'lb' is not defined

A: Initialize lb before you start any of the functions.

A: I have solved it by moving the global lb and the lb=Button(master,width=20,height=5,text='LOCK',bg='burlywood1',command=lockscreen) to the top of my code so that it was out of any function and then had to rearrange the rest of my code so that the function being called by that button ( lockscreen) sat above the preset function. Thanks for the help!


text:
Q: Constructor initializer does not allow me to use 'this' Compiler Error
    Keyword 'this' is not available in the current context
delegate void CallBack(int i);
class A
{
    public A(CallBack cb) { }
}
class B : A
{
    public B() : base(new CallBack(this.f)){}

    private void f(int i) { }
}

Why is this error ?
As a solution I thought of providing a parameterless protected ctor in A() and have
class B : A
{
     public B() : base()   // inherit the new A() ctor
     {
          base.cb = new CallBack(this.f); //this is allowed here
     }
     //...
}

A: It's because "this" hasn't been created until the base class constructor has run.
In your 2nd example the base constructor has finished, and now "this" has meaning.

A: In the first example the B instance is not initialized yet. In the second, it is.

A: Since the object is not yet (fully) constructed, that is the base constructor was not yet run, this is not available there.

A: You should use a abstract/virtual method.
abstract class A {
    A() {
        this.Initialize();
    }

    abstract void Initialize() { }
}

class B : A {
    string Text;

    B() { }

    override void Initialize() {
        this.Text = "Hello world";
    }
}


text:
Q: Make Excel PivotTable connect to multiple Access DBs to look up data I need a good advise here.
I am trying to make an Excel reporting dashboard that is using PivotTable / Sliders, so people can filter on data. However, I have 8 Access DBs from a hundred megs to 1.x GB where my data is in - meaning that I cannot combine them as there is a limit of 2 GB in Access.
What I would like to do, is to make my Excel PivotTable look up data in all 8 of the Access DBs. For instance, I want to look up manufacturer = 'ABC', then it should return all data from the 8 DBs where manufacturer = 'ABC'.
I have been reading/looking at linking the 8 DBs in Access (in a master "lookup" Access DB) and then using a SQL query Union All to combine them. However, I do not know if this is actually possible (I have not made it work yet), or if there is a better way. All these files are stored on a shared drive.
** EDIT
The data is stored in CSV files to start off with.
All the DBs contain the same amount of tables and headers.


text:
Q: Is this retirement wish appropriate to a senior lady? A retirement wish on retirement card from an new employee to a senior lady that does not have a lot of connection at work. Does it look appropriate?

All the best for your amazing retirement! Enjoy the new chapter in life, enjoy the years ahead!

The background is:
a guy's words to a senior lady;
a new employee to a lady that does not have a lot of connection at work.
my concerns were:
not to be over excited;
not to be rude;
and be polite and natural.
Does it look appropriate?

A: Sounds great to me: Friendly, cheerful, and sincere without leaving the false impression that you two were very close friends.


text:
Q: R-PropTest in Java I have a 2X2 Matrix and am doing prop_test in R and then take the P value from the result.
Now, I want to do the same thing in Java i.e., computing the P value.
One way is to use https://commons.apache.org/proper/commons-math/javadocs/api-3.1/org/apache/commons/math3/stat/inference/ChiSquareTest.html and compute the P-value
But, chi-square test does not use a Yates' continuity correction which can result in differences between R's approach and ChiSquareTest approach.
I would like to know any other ways to get the P-Value using Yates' continuity correction


text:
Q: How to pass parameters from specific view to _Layout.cshtml? I have a tool site, and the site layout was arranged like below. Black square has the main content, and when you go to a specific tool now I want to display the related tools on the right side.

Now to avoid Col-md duplication on every page I arranged the Layout page like this

                    @RenderBody()

                //Related tools widget

So inside above code the  I want to display this related tools widget. But there is a condition. When you go to a specific tool, that specific tool should not be displayed in that widget. So I created a partial view, and now I don't know where to call it.
How to achieve that?
Is my structure all right? Instead of using col-md on the layout shall I use them on a specific view like the one below?

               //Content goes here

               @RenderSection("RelatedTools", required:true)

A: Since you have using @RenderSection("RelatedTools", required:true),you need to add @section RelatedTools {} in your each view:
Layout:

                    @RenderBody()

                @RenderSection("RelatedTools", required:true)

View:

Welcome

Learn about building Web apps with ASP.NET Core.

@section RelatedTools {

RelatedTools

}

So that the html in @section RelatedTools will in the right side,and the html outside @section RelatedTools will in the left side.
Result:


text:
Q: Retagging accountability request When I do a manual retag, I'll often find other tags that look "off" and investigate further. These tangent tags usually lead to handfuls of questions that need retagging as well. If after a thorough search, the desired tag doesn't exist, then I'll create it.
During my retagging session this past Saturday, I ended up creating quite a few new tags in that process. Having created this many is abnormal, but so it goes.
John Saunders approached me directly by e-mail shortly thereafter. He noticed I had created these tags, and suggested that (a) some of them may not be appropriate, and (b) I get some feedback on Meta to improve the process for the future. I agreed completely.
So, here are the tags I created, with an explanation of either their current status, my thought process (or lack thereof), etc. Note: all the new tags are linkified for convenience, even though they don't show up with an underline. Also, between the time I got the list of tags from John and going back to analyze, some of the tags' statuses had changed.

*

*[dual-boot] - This was a retag of a handful of questions marked with [dualboot]. Not much to say here, as I think it was straight-forward.

*[event-notification] - I don't see any questions with this tag now, though I remember creating it. I had run into several questions that mentioned event notification, so at that point I figured there should be a tag for it as people were using that terminology.

*[monitor-refresh-rate] - There was a single question about programmatically changing the refresh rate of the display, however that question seems to have disappeared and I can't find it under any tag now.

*[display-properties] - I put this on question 245102. There was no existing [display-settings] either, and I thought using the word 'properties' was more appropriate to find that particular question. I'm really not sure how else to describe that question with a tag.

*[device-disconnection] - This was used by 544875, where the question-asker needed to respond to an event when an external hard drive was disconnected from the system. I did my best on that question, as it was somewhat vague.

*[virtual-driver] - No questions are currently tagged with this. 540267 was asked by the same user as 544875, and I took the language used verbatim without thinking, transposing [virtual] [driver] into [virtual-driver]. I made a 2nd edit within the 5 minute window and changed [virtual-driver] to [virtual-drive], but the new tag remained.

*[virtual-desktop] - 509733 deals with errors in a class that creates a virtual desktop in C#. Now that I go back and read the question more thoroughly, it really doesn't have too much to do with virtual desktops, and is more of a newbie/fix-my-compiler-errors question. I'm on the fence as to whether [virtual-desktop] should be kept or discarded at this point.

*[libsvn] - A single question (1564797) deals with this SVN library. There is also [libsvm], but that is something completely different (I thought it might have been a typo, but it's not).

*[getexitcodeprocess] - 1763686. Brainfart. I've already removed this one and put [exit-code] on it (and merged [exitcode] (3) and [exit-status] (1) into [exit-code] (29) while I was at it).

*[disk-space] - This was created as the anticipated target for a merge with [diskspace] (50) which I discovered in my retagging. I haven't gone through those questions at all to see if it's a valid merge, but with 50 questions on it, it most likely is, or is pretty darn close.

*[virtual-file] - 2157682 was interested in finding a way of executing a program that didn't physically exist in a file on the disk. Honestly I was at a bit of a loss as to how to tag this question, even though I knew what it was asking.

*[file-indexing] - I put this on 2238606, and I thought it was pretty straight-forward at the time. Now that I look back there is also [indexingservice], which may be more appropriate, or at least supplementary.
That's it. I really appreciate John contacting me about this (and also the way he did it, too). I truly want what's best for the site, and the feedback I get here should help me become a more productive member of the community.
EDIT: Thank you all for the feedback. I was expecting a lot more constructive criticism, but if everyone is content with what I'm doing, then I will happily continue. As I said, I welcome any/all feedback (not limited just to retagging) so send me an e-mail if you think it's appropriate. There's a direct e-mail link on my website. Thanks!

A: Thanks, Jon, for bringing this to meta. I appreciate your hard work, and your willingness to discuss this with the community.
I noticed these tags while using the "Questions with newly-created tags" link that 10k users have access to. I'll occasionally use this tool to correct misspelled tags, or tags entered by users who don't understand what tags are. That's why I was so surprised to see Jon's name there! I've frequently seen his name on the posts he edits, and knew he was a good community-member who works hard to make the sites better. He's exactly the opposite if the kind of user I expect to see there!
I don't have particular problems with most of his particular tags. I have some question as to how many other users will follow the same thought process Jon followed and will reach the same tags he did, but that remains to be  seen. I notice that one of his tags already has about six uses, so I guess I'm answered on that particular tag.
Jon, thanks again for all your hard work.

A: Looks good to me, thanks for doing this work, and for putting so much consideration into it!

A: I'd say that last one (12) could be validly tagged indexing-service because it is about checking to see if the Windows Indexing Service is running.
Other than that, can't see any problems with the other.


text:
Q: In Atwood machines, is the direction of the acceleration an observational fact or can be deduced mathematically? In Atwood machines type problems, we set one block heavier than the other. Then we usually "know" the direction of rotation of the pulley and the direction of acceleration based on the location of the heaviest block: If the heaviest block is on the right side, the acceleration is clockwise, if the heaviest is on the left, counter-clockwise.
Is this an experimental fact based on observation or can be deduced from a mathematical perspective?

A: You don't have to know which block is heavier than the other. But you do have to adopt some sign convention for the direction of the acceleration.
Without actually knowing which mass is heavier, you can arbitrarily assign the acceleration $a$ is to be positive for say mass 1 moving downward, and then applying Newton's second law you get the equation for the acceleration to be
$$a=g\frac{m_{1}-m_{2}}{m_{1}+m_{2}}$$
Now, if in fact you are given that $m_{2}>m_{1}$ then $a$ will be negative, and $m_{1}$ accelerates upward instead of downward.
But you could just as well assign $a$ to be positive for $m_{2}$ moving downward, in which case the equation is.
$$a=g\frac{m_{2}-m_{1}}{m_{1}+m_{2}}$$.
With the same result.
It's kind of like the application of Kirchhoff's voltage law where you arbitrarily assign a direction to a loop current. If as a result of analysis that current has a negative value, then the current is in the opposite direction to that assumed.
Hope this helps.

A: With two masses hanging over a pulley, Newton's laws predict that the heavier mass will determine the direction of motion.


text:
Q: Backbone/RequireJS model data storage I am using Backbone/RequireJS to provide my application with modularization and structure. One thing I am coming up against, and would greatly appreciate some advice in this area.
When a user visits the page, the first thing that happens is some JSON that populates a couple of models. I would like these models to be available where-ever I am in the app, as they contain the data and support for the program. Is it permissible to use window.modelName, or do you recommend another/better way of accomplishing this?

A: Using your suggested solution defies the whole purpose of using AMD in the first place.
Define a module (let's call it globals) as such:
define(function (require) {
  var globals = function () {
    return {};
  };
  return globals();
});

Now, when you init you can add values to it:
globals = require('globals');
globals.mymodel = new MyModel();
mymodel.fetch();

Later, and from any other module, you can access your globals module:
globals = require('globals');
console.log(globals.mymodel.get('myattr');


text:
Q: How to migrate a running Java program from one machine to another? Say I have one Java program running on machine A, now I want to interrupt it, save its context and resume its execution on machine B. Is it possible to do that? How?

A: no, there's no good way to "freeze" a process and "revive" it on a separate machine, the process might be holding all sorts of state (open files/sockets etc) that you cant move with it.
if its an application youre writing its better to make it clusterable and then just start up another node on the target machine, wait for those 2 nodes to sync and shut fown your original node.
if its not an application youre writing or the above is too much, run your application inside a VM and use the VM's capabilities to migrate the entire VM with the running app in it (so, just use vmotion).

A: You might try something like this - the point at which you interrupt your program, just serialize all its properties / objects and also set a flag to indicate the point from where it can re-start executing. Now copy the serialized stuff to the other machine and start the program. Your code should be able to handle the conditions to correctly store (serialize) the state of your program and continue from that point whenever the class is started on another machine.


text:
Q: Rijndael encryption in python I wanna use Rijndael encryption with key and block 256bit size in python and padding should be PKCS7. either with utf-8 encode.
I have searched a lot and finally wrote this code, I don't know this is a good way but that's all I know. when run the code I got this Error:
Traceback (most recent call last):
File "testForRijndael.py", line 1, in <module>
  from rijndael.cipher import crypt
File "/opt/odoo/odoo11-venv/lib/python3.6/site-
  packages/rijndael/cipher/crypt.py", line 1, in <module>
  from rijndael.cipher.blockcipher import *
File "/opt/odoo/odoo11-venv/lib/python3.6/site-
  packages/rijndael/cipher/blockcipher.py", line 64
    raise Exception,"the IV length should be %i bytes"%self.blocksize
               ^
SyntaxError: invalid syntax

If anybody can help me, I'll be appreciate him/her
This is my code:
from rijndael.cipher import crypt
from rijndael.cipher.blockcipher import MODE_CBC
from pkcs7 import PKCS7Encoder

class Rijndael():
    def __init__(self, key, iv):
       self.KEY = key
       self.IV = iv
       self.BLOCKSIZE = 32

   def encrypt(self, plain_text):
        rjn = crypt.new(self.KEY, MODE_CBC , self.IV,
blocksize=self.BLOCKSIZE)
        pad_text = PKCS7Encoder.encode(plain_text)
        return rjn.encrypt(pad_text).encode()

   def decrypt(self, cipher_text):
       rjn = crypt.new(self.KEY, MODE_CBC , self.IV,
                       blocksize=self.BLOCKSIZE)
       cipher_text = cipher_text.decode()
       return rjn.decrypt(cipher_text)

  r = Rijndael('abcdefghijklmnopqrstuvwxyz123456',
  'abcdefghijklmnopqrstuvwxyzgh3456')
  test_text = "this is a test :)"
  encrypt = r.encrypt(test_text)
  decrypt = r.decrypt(encrypt)
  print(test_text)
  print(encrypt)
  print(decrypt)

A: The rijndael library you're importing from is written for python 2, but you're running it with python 3. See below for the syntax that works in python 2, but not python 3.
$ cat raise.py
  raise Exception,"text"
$ python2 raise.py
Traceback (most recent call last):
  File "raise.py", line 1, in <module>
    raise Exception,"text"
Exception: text
$ python3 raise.py
  File "raise.py", line 1
    raise Exception,"text"
                   ^
SyntaxError: invalid syntax

You can try to migrate it yourself, using the 2to3 tool, see if someone has written a port, or write and execute your program with python 2.
Try pip2 install rijndael and then python2 testForRijndael.py.
To run 2to3 on the local code (not really recommended but it might work), run 2to3 -w /opt/odoo/odoo11-venv/lib/python3.6/site-packages/rijndael/**/*.py


text:
Q: Finding Binet form in Mathematica Suppose I have a linear recurrence* and I want to find its closed-form 'Binet' representation.  Is there a good way to do this in Mathematica?
It seems like a very basic request, and there are certainly many natural ways to ask Mathematica to do it for me.  But so far everything I've tried has failed: it churns until its memory use is so high the operating system is obliged to close it, or it gives warnings that it does not know how to simplify simple expressions†, or the like.  I could understand this if the question was hard, but it's not—factor the characteristic equation, find the roots, and solve a linear system. The most recent time I tried this (and had the program crash) was on a degree-9 example, and I just don't think a 9-by-9 linear system should be that hard to solve.
Surely I'm not the only one who need to do this from time to time!  What is the right way to do this?
I lost my session so I don't have the exact code I tried.  One solution created a List with the recurrence and its initial points and used RSolve.  Another found and factored the characteristic equation and took appropriate roots to the n-th power multiplied by polynomials of degree corresponding to the multiplicity with coefficients generated from C[i].  I also tried Solve and Reduce in various ways.
* Or a rational generating function. Actually I'll start from a List of numbers which are described by a recurrence of less than half its length, and FindLinearRecurrence or FindGeneratingFunction can do the not-too-difficult conversion.
† For example, when I asked it to solve one recurrence it choked on sin^2 (3pi/14) + cos^2(3pi/14) in the course of the calculation, saying that ran out of precision.  You'd think it could symbolically simplify something like that, but no.

A: I have no knowledge of Binet form, but addressing your concern regarding simplification:
expr = Sin[3 pi/14]^2 + Cos[3 pi/14]^2;

Simplify[expr]

1

A: I'm not sure if this is what you had in mind, but you could do something like
Binet[ker_List, init_List] :=
 Module[{charp, roots, polynomials, coeffs, base, p},
  roots = Tally[
    N@Eigenvalues[
      PadLeft[Append[IdentityMatrix[Length[ker] - 1], Reverse[ker]]]]];
  coeffs = Table[p[i, j], {i, Length[roots]}, {j, roots[[i, 2]]}];
  polynomials =
   Table[(Evaluate[i.#^Range[0, Length[i] - 1]]) &, {i, coeffs}];
  base = roots[[All, 1]];
  {polynomials /.
    Solve[Table[
       Through[polynomials[n]].base^n == init[[n + 1]], {n, 0,
        Length[init] - 1}], Flatten[coeffs]][[1]], base}]

Then for a linear recurrence kernel and initial values init, Binet[kernel, init] returns two lists. The first one contains the polynomials and the second the roots of the characteristic polynomial. The n-th entry in the recurrence table is then equal to a[kernel, init][n] with
a[kernel_, init_] := Evaluate@Module[{p, b},
   {p, b} = Binet[kernel, init];
   Through[p[#]].b^#] &

So for example for the Fibonacci sequence you would get
kernel = {1, 1};
init = {1, 1};
{p, b} = Binet[kernel, init]

(* ==> {{0.723607 &, 0.276393 &}, {1.61803, -0.618034}} *)

With[{sol = a[{1, 1}, {1, 1}]},
  Table[Chop@sol[n], {n, 0, 10}]];

(* ==> {1., 1., 2., 3., 5., 8., 13., 21., 34., 55., 89.} *)


text:
Q: DooPHP: How to output an image from a controller action? In one of the actions I need to return an image to the user. Is there a way to achieve this with DooPHP?
Sample action code:
public function view() {
   $path = $this->params['path']; // contains path to the image

   // $this->render($path); // does not work
}

Thanks and happy holidays!

A: I wasn't able to find anything in the DooPHP framework and simply ended doing it the php way as described in this answer: https://stackoverflow.com/a/900228/39843


text:
Q: Last Action Event get Fired on back Click I have a Form which contains :
Category TextBox
Button to Save the TextBox value in database.
The code works fine, all textbox value get Saved successfully on Save Button Click.
Problem:
After Saving I redirect to same page, and now here when I click on some link suppose 'Google.Com' and then if I click back button the browser redirect me to previous page on my application. on Click on Back Button the Postback value is found to be True, and again Save Button Event gets Fired and again textbox value gets saved in database.
I don't want the event must get fired on back click.
What should I do?
Please help me , I m getting issue and not getting solution on it.

A: What you need to do is to implement a Post/Redirect/Get (PRG) pattern in your app.  The basic rule is that your POST should not return a page (or a view); instead, it should return just a redirect request that will GET the page/view to show.
While you'll find a lot more information about PRG in relation to ASP.NET MVC, I'm assuming your working with web forms - so there's not much in terms of examples out there that I'm familiar with.
But the concept is pretty straight-forward.  After your POST, just return a Response.Redirect back to the page that you want to display.  It may seem like duplicate work, but you'll save yourself the problems that you're describing.
Hopefully this helps!


text:
Q: Modifying Pydantic json_encoders for a class not working I have a pydantic model that has an instance of another model as one of its attributes.
For my application, I need that model to be written out in a custom way. I thought I could do this by setting json_encoders in the model Config but I can't get it working. I can get it to work for basic types eg. datetime but not with my own class.
See minimal example below:

from pydantic import BaseModel

def write_list_item(item):
    return [item.a, item.b]

class ListItem(BaseModel):
    a: str
    b: str

class ToyList(BaseModel):
    list_item: ListItem

    class Config:
        json_encoders = {ListItem: write_list_item}

tl = ToyList(list_item=ListItem(a="a1", b="b2"))

print(tl.json())

Expected output:
["a1, "b1"]

Observed output:
{"a": "a1", "b": "b1"}

Can anyone spot what i'm doing wrong?

A: At the moment it is not straightforwardly possible. It will be possible when this PR is merged.
Therefore, you can consider a different design of the model or a workaround through a custom root type, for example (not production-ready):
class ListItem(BaseModel):
    __root__: List[str]

    @root_validator(pre=True)
    def root_val(cls, values):
        return {"__root__": [values['a'], values['b']]}

    @property
    def a(self):
        return self.__root__[0]

    @property
    def b(self):
        return self.__root__[1]

    def __setattr__(self, key, val):
        if key == 'a':
            self.__root__[0] = val
        elif key == 'b':
            self.__root__[1] = val
        else:
            super().__setattr__(key, val)


text:
Q: How to create keystore (.pfx) file I have newly purchased RAPID  wild card SSL certificate with me.
Now i want to generate keystore(.pfx) file.
Could anyone please help me and tell me what is the step for the same.

A: From the this link.
In Windows open a console window, cd to somewhere sensible and type:
cipher /r:whateveryoulike

Enter a password and you have a certificate (whateveryoulike.cert) and a .pfx file (whateveryoulike.pfx).


text:
Q: Selecting a specific User Certificate on a given URL Below is the sample code which am making use of , upon access of this url am shown a dialog box with the list of user certificates available, here, from the table any one of the user certificates should be selected after that click OK , which takes you to the landing page.
The following is already tried, Handle Alert, Get Window handles and even iframe i.e Select ifarme, after spending few hours it became evident that the issue is as described below.

Issue
What is happening here is that the Open Browser line in the below code is not getting completed until i make the appropriate user certificate selection, hence, HELLO1 or any other code is not executed until i make the selection.
Which means that either i need to pass a parameter at the time of URL request itself to make that selection or ??
Does robot framework / selenium support any other way to get the user certificate selected OR using javascript in robot framework.
*** Settings ***
Documentation  OAM OAuth TestSuite
Library SeleniumLibrary
Library String
Library Process
Library Collections
Library json

*** Variables ***
${waittime}=    10s

*** Test Cases ***
SELECT USER CERTIFICATE
    [Tags]  aminhell
    [Documentation]     sample
    ${ID}=    Open Browser     http://wren22uiy.us.iyio.com:8879/odd.html   Chrome      options=add_argument("--ignore-certificate-errors")
    Select Frame    Select a Certificate
    LOG TO CONSOLE  HELLO1
    ${message} =    Get Window handles
    LOG TO CONSOLE  HELLO2
    LOG TO CONSOLE  ${message}

A: After having done a research in this topic, it seems that there is no easy way to solve this situation:

*

*The Chrome is not easily manageable by AutoIT Library

*The "Open Browser" or any keyword is stuck while the certificate is not selected

I found an "infrastructure" workaround that I would like to share with you consisting on using a proxy that will select the certificate for you. You can install the Nginx and configure make it select the certificate for you, and then test the website directly by HTTP.
The nginx.conf I used:
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  0;
    ssl_session_cache  off;
    proxy_ssl_session_reuse off;

    server {
        listen       8335;
        server_name  localhost;

        location / {
            proxy_pass https://localhost:8443/;
            proxy_ssl_verify off;
            proxy_ssl_certificate keys/A123456.crt.pem;
            proxy_ssl_certificate_key keys/A123456.key.pem;
            proxy_ssl_session_reuse off;
        }
    }
    server {
        listen       8336;
        server_name  localhost;

        location / {
            proxy_pass https://localhost:8443/;
            proxy_ssl_verify off;
            proxy_ssl_certificate keys/B123457.crt.pem;
            proxy_ssl_certificate_key keys/B123457.key.pem;
            proxy_ssl_session_reuse off;
        }
    }
}

HINT: If you use P12 as certificate/key file, it is possible to extract certificate and key by using the following openssl commands:
openssl pkcs12 -in filename.p12 -nocerts -nodes -out filename.key.pem
openssl pkcs12 -in filename.p12 -clcerts -nokeys -out filename.crt.pem

The RF test cases:
TESTCASE001 - Certificate for A123456
    [Teardown]    Close All Browsers
    Open Browser    http://localhost:8335/myapp    Chrome
    Page Should Contain    A123456

TESTCASE002 - Certificate for B123457
    [Teardown]    Close All Browsers
    Open Browser    http://localhost:8336/myapp    Chrome
    Page Should Contain    B123457


text:
Q: Truncate the fractional part of a BigDecimal when its scale is zero in Java I need to remove the fractional part of a BigDecimal value when its scale has a value of zero. For example,
BigDecimal value = new BigDecimal("12.00").setScale(2, RoundingMode.HALF_UP);

It would assign 12.00. I want it to assign only 12 to value in such cases.

BigDecimal value = new BigDecimal("12.000000").setScale(2, RoundingMode.HALF_UP);

should assign 12,

BigDecimal value = new BigDecimal("12.0001").setScale(2, RoundingMode.HALF_UP);

should assign 12.

BigDecimal value = new BigDecimal("12.0051").setScale(2, RoundingMode.HALF_UP);

should assign12.01

BigDecimal value = new BigDecimal("00.000").setScale(2, RoundingMode.HALF_UP);

should assign 0.

BigDecimal value = new BigDecimal("12.3456").setScale(2, RoundingMode.HALF_UP);

should assign 12.35 and alike. Is this possible? What is the best way to do?

A: For the crosslink from there: https://codereview.stackexchange.com/questions/24299/is-this-the-way-of-truncating-the-fractional-part-of-a-bigdecimal-when-its-scale

Is this possible? What is the best way to do?

Probably stripTrailingZeros().
To check your tests:
public static void main(final String[] args) {
    check(truncate("12.000000"), "12");
    check(truncate("12.0001"), "12");
    check(truncate("12.0051"), "12.01");
    check(truncate("12.99"), "12.99");
    check(truncate("12.999"), "13");
    check(truncate("12.3456"), "12.35");
    System.out.println("if we see this message without exceptions, everything is ok");
}

private static BigDecimal truncate(final String text) {
    BigDecimal bigDecimal = new BigDecimal(text);
    if (bigDecimal.scale() > 2)
        bigDecimal = new BigDecimal(text).setScale(2, RoundingMode.HALF_UP);
    return bigDecimal.stripTrailingZeros();
}

private static void check(final BigDecimal bigDecimal, final String string) {
    if (!bigDecimal.toString().equals(string))
        throw new IllegalStateException("not equal: " + bigDecimal + " and " + string);

}

output:

if we see this message without exceptions, everything is ok

A: The following code does what you specify with the help of regex and the construction of BigDecimal, it is probably not the most efficient way to go about:
    BigDecimal value = new BigDecimal("12.0000").setScale(2, RoundingMode.HALF_UP);
    Pattern pattern = Pattern.compile("\\d+\\.(\\d)0");
    Matcher matcher = pattern.matcher(value.toString());
    if (matcher.find()) {
        if (matcher.group(1).equals("0"))
            value = value.setScale(0);
        else
            value = value.setScale(1);
    }

Note: this also makes 12.100 -> 12.1, I assume that is wanted functionality.

A: Instead of modifying the original value on my own by hand, I have simply tried to apply some conditions like,
String text="123.008";
BigDecimal bigDecimal=new BigDecimal(text);

if(bigDecimal.scale()>2)
{
    bigDecimal=new BigDecimal(text).setScale(2, RoundingMode.HALF_UP);
}

if(bigDecimal.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO)==0)
{
    bigDecimal=new BigDecimal(text).setScale(0, BigDecimal.ROUND_HALF_UP);
}

System.out.println("bigDecimal = "+bigDecimal);

The first if condition checks, if the scale is greater than 2. If so, then perform the rounding operation as specified.
The next if condition checks, if the value of the fractional part yields zero. If so, then truncate it. Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by the compareTo() method. Therefore, the condition is satisfied whenever the the value of the fractional part is evaluated to zero.
Otherwise, the original value is left untouched (if the scale is either 1 or 2).
If I'm missing something or it's a wrong thing to implement, then please clarify it.

A: Try this one:
new BigDecimal("12.3456").setScale(2, RoundingMode.FLOOR).stripTrailingZeros()


text:
Q: Spree - i18n gem issue I got a problem with a new version of spree gem (branch: '2-3-stable'). When i try to install it, I receive this error.
my_store$ rails server
The git source https://github.com/spree/spree_gateway.git is not yet checked out. Please  run `bundle install` before trying to start your application

my_store$ bundle install
Bundler could not find compatible versions for gem "i18n":
 In Gemfile:
  spree (= 2.3.1) ruby depends on
   spree_core (= 2.3.1) ruby depends on
    i18n (= 0.6.9) ruby

 rails (= 4.1.2) ruby depends on
  activesupport (= 4.1.2) ruby depends on
    i18n (0.6.11)

But according to gem list i got both of this gems installed i18n (0.6.11, 0.6.9). Can someone help me to fix this problem

A: Copy from comment section:

Sorry. i figured it out myself simple execution of bundle update and then bundle install command fixed my issue


text:
Q: type deduction from char array to std::string I'm trying to write sum function using variadic template.
In the code I would write something like
sum(1, 2., 3)

and it will return most general type of the sum (in this case - double).
The problem is with characters. When I call it like
sum("Hello", " ", "World!")

template parameters are deduces as const char [7] for example, thus it won't compile. I found the way to specify last argument as std::string("World!"), but it's not pretty, is there any way to achieve automatic type deduction to std::string or correctly overload sum?
The code I have so far:
template<typename T1, typename T2>
auto sum(const T1& t1, const T2& t2) {
    return t1 + t2;
}

template<typename T1, typename... T2>
auto sum(const T1& t1, const T2&... t2) {
    return t1 + sum(t2...);
}

int main(int argc, char** argv) {
    auto s1 = sum(1, 2, 3);
    std::cout << typeid(s1).name() << " " << s1 << std::endl;

    auto s2 = sum(1, 2.0, 3);
    std::cout << typeid(s2).name() << " " << s2 << std::endl;

    auto s3 = sum("Hello", " ", std::string("World!"));
    std::cout << typeid(s3).name() << " " << s3 << std::endl;

    /* Won't compile! */
    /*
    auto s4 = sum("Hello", " ", "World!");
    std::cout << typeid(s4).name() << " " << s4 << std::endl;
    */

    return 0;
}

Output:
i 6
d 6
Ss Hello World!

A: Ultimately you're char pointer types don't deal well with being on both the left and right side of operator +.` You can overload to manufacture an intermediary if desired.
Below I took liberty to refactor this down to a single-param-supported sum (not a required step, but allows sum(x) overloads, which are clearer to understand). Hopefully you get the idea.
#include <iostream>
#include <string>

// generic identity
template<typename T1>
auto sum(const T1& t1)
{
    std::cout << __PRETTY_FUNCTION__ << '\n';
    return t1;
}

// specialized for const char [N]
auto sum(const char *s)
{
    std::cout << __PRETTY_FUNCTION__ << '\n';
    return std::string(s);
}

template<typename T1, typename... T2>
auto sum(const T1& t1, const T2&... t2)
{
    std::cout << __PRETTY_FUNCTION__ << '\n';
    return t1 + sum(t2...);
}

int main(int argc, char** argv) {

    std::cout << sum(1,2,3) << '\n';
    std::cout << sum(1, 2.0, 3) << '\n';
    std::cout << sum("Hello", " ", std::string("World!")) << '\n';
    std::cout << sum("Hello", " ", "World!");
    return 0;
}

Output
auto sum(const T1 &, const T2 &...) [T1 = int, T2 = <int, int>]
auto sum(const T1 &, const T2 &...) [T1 = int, T2 = <int>]
auto sum(const T1 &) [T1 = int]
6
auto sum(const T1 &, const T2 &...) [T1 = int, T2 = <double, int>]
auto sum(const T1 &, const T2 &...) [T1 = double, T2 = <int>]
auto sum(const T1 &) [T1 = int]
6
auto sum(const T1 &, const T2 &...) [T1 = char [6], T2 = <char [2], std::__1::basic_string<char>>]
auto sum(const T1 &, const T2 &...) [T1 = char [2], T2 = <std::__1::basic_string<char>>]
auto sum(const T1 &) [T1 = std::__1::basic_string<char>]
Hello World!
auto sum(const T1 &, const T2 &...) [T1 = char [6], T2 = <char [2], char [7]>]
auto sum(const T1 &, const T2 &...) [T1 = char [2], T2 = <char [7]>]
auto sum(const char *)
Hello World!

Best of luck

A: I would just write a simple overloaded identity function which handles const char* specially.
template<typename T>
decltype(auto) fix(T&& val)
{
    return std::forward<T>(val);
}

auto fix(char const* str)
{
    return std::string(str);
}

template<typename T1, typename T2>
auto sum(const T1& t1, const T2& t2) {
    return fix(t1) + t2;
}

template<typename T1, typename... T2>
auto sum(const T1& t1, const T2&... t2) {
    return t1 + sum(t2...);
}


text:
Q: how to go multithreaded for puppeteer using worker-threads for web-automation purpose hello so am doing some web automation and I want to open run puppeteer multithreaded what I mean like open the same page 10s of times and what I understood of what I read the worker thread is the best solution I guess?  but I didn't get how to use it properly  and I will put a sample code of what I did
 const { Worker, isMainThread } = require('worker_threads');

    const puppeteer = require('puppeteer') ;
        let scrapt = async()=>{

                        /* -------------------------------------------------------------------------- */
                        /*                             Launching puppeteer                            */
                        /* -------------------------------------------------------------------------- */
            try{
              const browser = await puppeteer.launch({headless: true }) ;

            const page = await browser.newPage();
            await page.setUserAgent(
              `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36`
            );
            let Browser_b = new Date()
              await page.goto('https://www.supremenewyork.com/')
            let browser_e = new Date()
            console.log(browser_e - Browser_b)
    }
    catch(e){
        console.log(e)
    }
let ex = [1,2,3,4]
if (isMainThread) {
    // This re-loads the current file inside a Worker instance.asdasd
    new Worker(__filename);
  } else {
    for(let val of ex) {
      scrapt();

    }
  }

this script opens 4 browsers but if I open more the pc lag  ALOT since I think it's only using one thread not using them all?
Thank u in advance and sorry for my stupidity

A: ever tried using Cluster? it's a good way for multi_processing and easier to use than worker_threads in my opinion here is an example from HERE
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  // Fork workers.
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });
} else {
  // Workers can share any TCP connection
  // In this case it is an HTTP server
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello world\n');
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}


text:
Q: How To delete Azure diagnostics in PAAS server after transferring data to azure blob Facing problem with azure diagnostics(SDK Ver 2.6).
Problem Statement:
The diagnostic logs are stored into Azure blobs(final storage point), meanwhile  these log files are stored in below path in my PAAS VM.
C:\Resources\Directory\%RoleDeploymentID%.%RoleName%.LocalStorageName/LogFiles\Web\W3SVC1273337584
from here data is transferred to Azure blobs.
Since there is high utilization of website, log files are lined up in Local storage, crashing the site due to disk overflow(these logs are not getting deleted from local folder). I can't manually delete the logs from PAAS VM.
I use below config snippet in diagnostics.wadcfgx file
 <PerformanceCounters scheduledTransferPeriod="PT1M">
<PerformanceCounterConfiguration counterSpecifier="\Memory\Available MBytes" sampleRate="PT3M" />
      <PerformanceCounterConfiguration counterSpecifier="\Web Service(_Total)\ISAPI Extension Requests/sec" sampleRate="PT3M" />
      <PerformanceCounterConfiguration counterSpecifier="\Web Service(_Total)\Bytes Total/Sec" sampleRate="PT3M" />
      <PerformanceCounterConfiguration counterSpecifier="\ASP.NET Applications(__Total__)\Requests/Sec" sampleRate="PT3M" />
      <PerformanceCounterConfiguration counterSpecifier="\ASP.NET Applications(__Total__)\Errors Total/Sec" sampleRate="PT3M" />
      <PerformanceCounterConfiguration counterSpecifier="\ASP.NET\Requests Queued" sampleRate="PT3M" />
      <PerformanceCounterConfiguration counterSpecifier="\ASP.NET\Requests Rejected" sampleRate="PT3M" />
      <PerformanceCounterConfiguration counterSpecifier="\Processor(_Total)\% Processor Time" sampleRate="PT3M" />
    </PerformanceCounters>

Need help..


text:
Q: IF Statement For Session - Formatting Q So I have this IF statement in my view. it works and all, but wondering if there's a better way to write this. Having both session calls seem unneccessary...
if($this->session->userdata('campaign_name')){
    echo $this->session->userdata('campaign_name');
}
else {
    echo 'this';
}

Note this function will be used inline on a text input. So I'm looking for as minimal code as possible.

A: Note that CI's Session class's userdata method will return false if no campaign_name exists. So assign a variable to the potentially undefined array key (campaign_name)
$campaign_name = $this->session->userdata('campaign_name');

if($campaign_name)
{
    echo $campaign_name;
}
else
{
    echo 'this';
}

OR
if($campaign_name = $this->session->userdata('campaign_name'))
{
   echo $campaign_name;
}

Controller Method (/application/controllers/test_controller.php)
    <?php if (!defined('BASEPATH')) exit('No direct script access allowed');

    class Test_Controller extends CI_Controller
    {
        function __construct()
        {
            parent::__construct();

        }
        public function myFunction()
        {
            $data['campaign_name'] = $this->session->userdata('campaign_name');
            $this->load->view('test_view',$data);

        }
    }

View (/application/view/test_view.php)
<html>
<head></head>
<body>
     <input type="text" value="<?php echo $campaign_name; ?>">
</body>
</html>

A: In your controller, you can store the value of that session data into a variable and pass that along to the view. In the view, you can then have your if else statements that just look at the variable. I would advise against setting a variable in the view as RPM did. While it works, it breaks the separation of concerns you have going.
Also, look into using the alternative PHP syntax for views in CodeIgniter. It'll make your code neater and more maintainable.
Edit: I see now that RPM has updated his answer to set the variable in the controller. That's a good example to follow.


text:
Q: Installing Ubuntu on a VM | Can anyone help with this warning? I am fairly new to Ubuntu but I must say first of all... I LOVE IT! I am going through all of the installation and setup for it, but when I get to the installation type screen that is where my worry started. The screen looks as follows:
This computer currently has no detected operating systems. What would you like to do?⚪Erase disk and install Ubuntu
Warning: This will delete all your programs, documents, photos, music and any other files in all operating systems
Will this delete everything in my host machine?
Thanks in advance.
PS: My apologies for the awful formatting, this is my first time posting here as im sure you can tell.

A: Unless you seriously misconfigured the VM, no, it will not.  I believe most VM's offer a simpler route to just get set up with an OS image: you might want to look into that.  In any case, VM's work to prevent even a malicious program from doing this, so the Ubuntu installer won't.


text:
Q: Working with Accelerometer I am working on gestures using acceleration values (x, y, z) from a device.
If I hold the device in my hand in a resting position (x,y,z) = ((0,0,0)). But if I change the direction of device (still at resting position) the values are changed to something like ((766,766,821)). As all the x, y, z axis are changed compared to their original orientations.
Is there any way (trigonometric function OR other) to resolve this issue?

A: The acceleration due to gravity will always be present. It appears you are subtracting that value from one of the axes when the device is in a particular orientation.
What you will need to do to detect gestures is to detect the tiny difference that momentarily appears from the acceleration due to gravity as the devices begins moving. You won't be able to detect if the device is stationary or moving at a constant velocity, but you will be able to determine if it is turning or being accelerated.
The (x,y,z) values give you a vector, which gives the direction of the acceleration. You can compute the (square of the) length of this vector as x^2 + y^2 + x^2. If this is the same as when the device is at rest, then you know the device is unaccelerated, but in a certain orientation. (Either at rest, or moving at a constant velocity.)
To detect movement, you need to notice the momentary change in the length of this vector as the device begins to move, and again when it is brought to a stop. This change will likely be tiny compared to gravity.
You will need to compare the orientation of the acceleration vector during the movement to determine the direction of the motion. Note that you won't be able to distinguish every gesture. For example, moving the device forward (and stopping there) has the same effect as tilting the device slightly, and then bringing it back to the same orientation.
The easier gestures to detect are those which change the orientation of the device. Other gestures, such as a punching motion, will be harder to detect. They will show up as a change in the length of the acceleration vector, but the amount of change will likely be tiny.
EDIT:
The above discussion is for normalized values of x, y, and z. You will need to determine the values to subtract from the readings to get the vector. From a comment above, it looks like 766 are the "zero" values to subtract. But they might be different for the different axes on your device. Measure the readings with the devices oriented in all six directions. That is get the maximum and minimum values for x, y, and z. The central values should be halfway between the extremes (and hopefully 766).
Certain gestures will have telltale signatures.
Dropping the device will reduce the acceleration vector momentarily, then increase it momentarily as the device is brought to a stop.
Raising the device will increase the vector momentarily, before decreasing it momentarily.
A forward motion will increase the vector momentarily, but tilt it slightly forward, then increase it again momentarily, but tilted backward, as the device is brought to a stop.
Most of the time the length of the vector will equal the acceleration due to gravity.

A: I find your question unclear. What exactly do you measure and what do you expect?
In general, an accelerometer will, if held in fixed position, measure the gravity of the earth. This is displayed as acceleration upwards, which might sound strange at first but is completely correct: as the gravity is accelerating "down" and the device is in a fixed position some force in the opposite direction, i.e. "up" needs to be applied. The force you need to hold the device in a fixed position is this force, which has a corresponding acceleration in the "up" direction.
Depending on your device this gravity acceleration might be substracted before you get the values in the PC. But, if you turn the acceleratometer, the gravity acceleration is still around and still points to the same "up" direction. If, before turning the acceleratometer, "up" would correspond to x it will correspond to a different axis if turned 90°, say y. Thus, both the measured acceleration on x and y axis will change.
So to answer your question it's necessary to know how your accelerometer presents the values. I doubt that in a resting position the acceleration values measured are (0, 0, 0).

A: Your comment makes your question clearer.  What you need to do is calibrate your accelerometer every time the orientation changes.  There is no getting around this.  You could make it a UI element in your application or if it fits with your uses, recalibrate to 0 if the acceleration is relatively constant for some amount of time (won't work if you measure long accelerations).
Calibration is either built into the device's api (check the documentation) or something you have to do manually.  To do it manually, you have to read the current acceleration and store those 3 values.  Then whenever you take a reading from the device, subtract those 3 values from each read value.

A: If the device is not compensating automatically for the gravitational acceleration you need to substract the (0,0,~9.8m/s2) vector from the output of the device.
However, you will also need to have the orientation of the device (Euler angle or Rotation Matrix). If your device isn't providing that it's basically impossible to tell if the signaled acceleration is caused by actually moving the device (linear acc) or by simply rotating it (gravity changing direction).
Your compensated acceleration will become:
 OutputAcc = InputAcc x RotMat - (0,0,9.8)

This way your OutputAcc vecor will always be in a local coord frame (ie. Z is always up)