text:
Q: Google Map is not getting loaded after signing the application ? How to solve this? Hello everyone I created an Android application which displays a google map and sets markers on the google map. The application is working fine until I sign that application.
My problem is after signing the application google map is not being loaded.
What is the problem?
I am using Google Api v2 and map fragment to view the map.
Here is my manifest code....
       <?xml version="1.0" encoding="utf-8"?>
        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
         package="example.tranzlogix_map"
         android:versionCode="1"
         android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="4"
    android:targetSdkVersion="19" />

 <permission
    android:name="example.tranzlogix_map.permission.MAPS_RECEIVE"
    android:protectionLevel="signature"></permission>

<uses-permission
    android:name="example.tranzlogix_map.permission.MAPS_RECEIVE"/>
<uses-permission
    android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission
    android:name="android.permission.INTERNET"/>
<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
    android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission
    android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/goo"
    android:label="@string/app_name"
    android:theme="@style/Translucent" >

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaSyB6ut74Pvg8T2rs7jg5GSjD6Es4beyxSYI"/>

    <activity
        android:name="example.tranzlogix_map.LoginActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name="example.tranzlogix_map.HelpActivity"
        android:label="@string/app_name" >

    </activity>
      <activity
        android:name="example.tranzlogix_map.MainActivity"
        android:label="@string/app_name" >

       </activity>

     </application>

  </manifest>

A: You probably still have your Google maps API key based on the SHA1 hash of the DEBUG certificate.
After signing the app for release you will have to set your Maps API key based on the SHA1 hash of the RELEASE Certificate.
See displaying the release certificate fingerprint
https://developers.google.com/maps/documentation/android/start#getting_the_google_maps_android_api_v2
Obtain the Release SHA1 hash ,generate the API Key and set this as the key in the manifest

A: add this meta_data under your meta_data:
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

and add this permission:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

-------------Edit---------------
here is your Manifest, with the needed meta and Permissions as well. If you still have an error please add it to the question as edited
      <?xml version="1.0" encoding="utf-8"?>
        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
         package="example.tranzlogix_map"
         android:versionCode="1"
         android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="19" />

 <permission
    android:name="example.tranzlogix_map.permission.MAPS_RECEIVE"
    android:protectionLevel="signature"></permission>

<uses-permission
    android:name="example.tranzlogix_map.permission.MAPS_RECEIVE"/>
<uses-permission
    android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission
    android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
    android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission
    android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/goo"
    android:label="@string/app_name"
    android:theme="@style/Translucent" >

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaSyB6ut74Pvg8T2rs7jg5GSjD6Es4beyxSYI"/>
    <meta-data android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />

    <activity
        android:name="example.tranzlogix_map.LoginActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name="example.tranzlogix_map.HelpActivity"
        android:label="@string/app_name" >

    </activity>
      <activity
        android:name="example.tranzlogix_map.MainActivity"
        android:label="@string/app_name" >

       </activity>

     </application>

  </manifest>

looking at this the minimum API level for map is 8 so you need to change minSdkVersion to 8

A: <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.example.androidmapsv2.permission.MAPS_RECEIVE" />`

A: Did you try importing 'google-play-services'? Problem can occur in importing a different version of google-play-services'. I imported v29 first and was not working so sometimes you just have to stay low. I got it on using v12.


text:
Q: Is it possible to run gRPC or HTTP/2 application in a AppEngine Managed VM? I am trying to build a gRPC backend and trying to deploy it on an AppEngine Managed VM. Is HTTP/2 supported? If not, can I simply expose it on a separate port and disable health checks or should I deploy this on compute engine/container engine.

A: At this point http/2 is not supported by Managed VMs. The best current solution is to run your http/2 server on a different port and specify the port number to forward in app.yaml (doc link).
You can keep health checking active on the default (8080) port if you want as long as you have an http endpoint listening there as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ExpressJS + Mongoose : Can't update a record in findByIdAndUpdate mongoose's function I'm a newbie in JS, NodeJS, Mongodb and I am trying to figure out my issue have.
exports.like = function (req, res, next) {
    PostModel.findByIdAndUpdate(req.params.postIdLike, req.body, {new : true},function (err, post) {
        if (err) {
            console.log(this.getErrorMessage(err));
            return next(err);
        } else {
            var numberPeopleLike = post.Like.PeopleLike.length;
            var currentUserID = req.body.CurrentUserID;
            console.log(numberPeopleLike);
            if (numberPeopleLike === 0) {
                post.Like.PeopleLike.push({id: currentUserID, flag: true});
                post.Like.NumberLike += 1;
                var data = {
                    value: post,
                    message: "Like",
                    status: 1
                };
                res.json(data);
                next();
            } else {
                // post like != null
                console.log("numberPeopleLike");
                for (var i = 0; i < numberPeopleLike; i++) {
                    if (post.Like.PeopleLike[i].id === currentUserID && post.Like.PeopleLike[i].flag === true) {
                        // user Liked
                        post.Like.NumberLike -= 1;
                        post.Like.PeopleLike[i].flag = false;
                        var data = {
                            value: post,
                            message: "Undo Like",
                            status: 0
                        };
                        res.json(data);
                        next();
                    } else {
                        // user don't like
                        post.Like.NumberLike += 1;
                        post.Like.PeopleLike.push({id: currentUserID, flag: true});
                        var data = {
                            value: post,
                            message: "Like",
                            status: 1
                        };
                        res.json(data);
                        next();
                    }

                }
            }

        }
    });
};

My Problem :
The findByIdAndUpdate function isn't update result code in if(numberPeopleLike === 0) condition. Although data json has value , the result can't update on collections. What's wrong?
[UPDATE]
When I implement with PUT method to excute function (Update )then
Value of data in if(numberPeopleLike === 0 ) condition
{
  "value": {
    "_id": "5717938a857e9c8a0e71a512",
    "IDMemberProfile": "5711114c2b5ecdf11a23947d",
    "Title": "test",
    "Content": "test",
    "Status": 1,
    "__v": 0,
    "Like": {
      "NumberLike": 1,
      "PeopleLike": [
        {
          "id": "570f932dfc642a4f1df5b450",
          "flag": true,
          "_id": "5717a9e42ae3ca5f12180844"
        }
      ]
    },
    "PostTime": "2016-04-20T14:34:50.973Z"
  },
  "message": "Like",
  "status": 1
}

But when I get GET list post in collection , this document can't update
{
      "_id": "5717938a857e9c8a0e71a512",
      "IDMemberProfile": "5711114c2b5ecdf11a23947d",
      "Title": "test",
      "Content": "test",
      "Status": 1,
      "__v": 0,
      "Like": {
        "NumberLike": 0,
        "PeopleLike": []
      },
      "PostTime": "2016-04-20T14:34:50.973Z"
    }


text:
Q: How do I change timezone in a docker container? I am running docker container for my development stack which I pulled from docker-hub, the image is created for a different timezone than where my application is supposed to be deployed.
How do I change timezone in a docker container?
I tried to change the timezone config within the container by running
echo "Africa/Lusaka" > /etc/timezone

and restarted the container but I still get the same timezone.

A: You can override as suggest by @LinPy during the run stage, but if you want to set at your Dockerfile you can set using ENV as tzdata is already there in your base image.
FROM postgres:10
ENV TZ="Africa/Lusaka"
RUN date

Build
docker build -t dbtest .
RUN
docker run -it dbtest -c "date"
Now you can verify on DB side by running
show timezone;

You will see Central Africa Time in both container and Postgres
in the alpine base image, the environment variable will not work. You will need to run
 RUN ls /usr/share/zoneinfo && \
cp /usr/share/zoneinfo/Europe/Brussels /etc/localtime && \
echo "Africa/Lusaka" >  /etc/timezone && \

A: There's a few ways to do it .

*

*You can declare the time zone directly as an environment variable in the docker compose file

   environment:
      - TZ=Asia/Singapore
      - DEBIAN_FRONTEND=noninteractive

*You can map the container's time zone and local time files to use that of the host machine in the docker compose file

volumes:
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro

I personally prefer to use the second method, in this way , all of my containers will have the same time configuration as my host machine

A: A simpler method would be to add an env var to your deployment:
env:
  - name: TZ
    value: "Europe/London"

(kubernetes deployment yaml)

A: Simply change the /etc/localtime to the time zone in the /usr/share/zoneinfo directory.
follow these steps:
first log into bash of your container:
docker exec -u 0 -it mycontainer bash

then remove the symbolic link file (/etc/localtime):
sudo rm -rf /etc/localtime

Identify the timezone you want to configure and create the symbolic link for it:
For instance, I would like to set Asia/Tehran timezone:
ln -s /usr/share/zoneinfo/Asia/Tehran /etc/localtime

Now verify it by:
date

and the output would be your timezone:
Sat Jan 30 14:22:17 +0330 2021

A: If you have TZ env set correctly and you still get the wrong time, make sure the tzdata system dependency is installed.

A: the best way is to use ENV in your run stage
-e TZ=Africa/Lusaka

and make sure that the package tzdata is present in the Container

A: This question was about a postgres base, mine was about an Alpine base, but based on the Alpine Wiki, what I can glean of best practice means my Dockerfile looks like:
FROM alpine:3.14
RUN apk add --no-cache alpine-conf && \
    setup-timezone -z Europe/London

https://wiki.alpinelinux.org/wiki/Alpine_setup_scripts#setup-timezone

A: For anyone who are using --env-file. add
# .env
TZ=Asia/Shanghai

To .env file, and it will get the time zone you want.

A: use
ls /usr/share/zoneinfo/

to show all zone


text:
Q: Cannot retrieve number val of $firebaseObject I have an issue where I can't retrieve a number value from a $firebaseObject in AngularFire.
if I console.log($scope.slideGen) the value correctly shows up in the log output of the entire object, but if I
console.log($scope.slideGen.time) then I get undefined.
Got the following code in a controller
Auth.$onAuth(function(authData) {
      $scope.userKey = authData.uid;
      $scope.ref = Ref.child('users').child($scope.userKey);
      loadSlide();
    });

function loadSlide() {
      if ($scope.slideKey !== '') {

        $scope.slide = $firebaseObject($scope.ref.child('slides').child($scope.slideKey));

        $scope.slideGen = $firebaseObject($scope.ref.child('slidesGeneral').child($scope.slideKey));
        $scope.time = new Date(1970, 0, 1, 0, 0, 0).setSeconds($scope.slideGen.time);
        console.log('Current time set to: ' + $scope.slideGen.time); //This returns undefined
      }
    }


text:
Q: Uniform convergence of $\sum\limits_{n=1}^{+\infty} \left(\sin{{1} \over {n}}\right) x^n$ $f_n(x)=\left(\sin{{1} \over {n}}\right) x^n$
pointwise convergence: $|f_n(x)|=\left(\sin{{1} \over {n}}\right) |x|^n \sim {{|x|^n}\over{n}}$ for $n \rightarrow +\infty$
$\sum\limits_{n=1}^{+\infty}{{|x|^n}\over{n}}$ is a power series and it converges in $E=[-1,1)$
uniform convergence: I calculate sup$_E|f_n(x)|=f_n(1)$ so there isn't unif. convergence in E. Can I have convergence in a subset of E?
If I consider interval $E=[a,b], -1<a<b<1$, $\sup_E|f_n(x)|=\max\left\{\sin{{1} \over {n}}|a|^n,\sin{{1} \over {n}}|b|^n\right\}$, general term of convergent series so there is uniform convergence in $[a,b]$?

A: The series converges uniformly on any compact interval $[-1,a] \subset [-1,1)$ with $-1$ as the left endpoint by the Dirichlet test.
Note that $\sin \frac{1}{n} \searrow 0$ monotonically and $\sum_{n = 1}^m x^n$ is uniformly bounded for all $m \in \mathbb{N}$ and all $x \in [-1,a]$ with
$$\left|\sum_{n = 1}^m x^n \right| \leqslant \max(1,|a|/(1-|a|)$$
However even though the series converges pointwise for each $x \in [-1,1)$ the convergence is not uniform on any interval $(a,1)$.  We can take $a = 0$ with no loss of generality to prove this non-uniform convergence.
Note that
$$\sup_{x \in (0,1)} \left|\sum_{k=n+1}^{\infty}x^k \sin \frac{1}{k}\right| > \sup_{x \in (0,1)} \sum_{k=n+1}^{2n}x^k \sin \frac{1}{k} \\>  \sup_{x \in (0,1)} nx^{2n}\sin \frac{1}{2n} = \frac{1}{2}\frac{\sin \frac{1}{2n}}{\frac{1}{2n}}$$
Since the RHS converges to $\frac{1}{2}$ as $n \to \infty$ the Cauchy criterion for uniform convergence is violated.

A: Note that the series $\sum_{n=1}^\infty \sin\left(\frac1n\right)x^n$ fails to converge uniformly on $(-1,1)$.  To see this, we can write
$$\sum_{n=1}^\infty \sin\left(\frac1n\right)x^n=\sum_{n=1}^\infty \left(\sin\left(\frac1n\right)-\frac1n\right)x^n+\sum_{n=1}^\infty \frac{x^n}n\tag1$$
The first series on the right-hand side of $(1)$ converges uniformly on $[-1,1]$ since the term $\sin\left(\frac1n\right)-\frac1n=O\left(\frac1{n^3}\right)$.  Therefore, it is enough to show that the second series on the right-hand side of $(1)$ fails to converge on $(-1,1)$.

To negate the uniform convergence of $\sum_{n=1}^\infty \frac{x^n}{n}=-\log(1-x)$ on $(-1,1)$, we choose $\varepsilon=\frac18\log(2)$.  Then, we have for any $N\ge1$ and $x=1-\frac1{N+1}\in(0,1)$
$$\begin{align}
\left|-\log(1-x)-\sum_{n=1}^N \frac{x^n}{n}\right|=&\left|\sum_{n=1}^\infty \frac{x^n}{n}-\sum_{n=1}^{N} \frac{x^n}{n}\right|\\\\
&=\sum_{n=N+1}^\infty \frac{x^n}{n}\\\\
&\ge \sum_{n=N+1}^{2N+1} \frac{x^n}{n}\\\\
&\ge \left(1-\frac1{N+1}\right)^{2N+1}\sum_{n=N+1}^{2N+1}\frac1n\\\\
&\ge \left(1-\frac1{N+1}\right)^{2N+1}\log(2)\\\\
&\ge \frac18\log(2)\\\\
&=\varepsilon
\end{align}$$
And hence the series $\sum_{n=1}^\infty \frac{x^n}{n}$ converges on $[-1,1)$ but fails to converge uniformly on $[-1,1)$.


text:
Q: apache httpclient doesn't set basic authentication credentials Have a look at the following code:
DefaultHttpClient http = new DefaultHttpClient();
            http.getCredentialsProvider().setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                        new UsernamePasswordCredentials(
                                                Configuration.username,
                                                Configuration.developerKey ) );

            HttpPost post = new HttpPost(strURL);
            StringEntity entity = new StringEntity( ac.toXMLString() );
            entity.setContentType("text/xml");
            post.setEntity( entity );
            org.apache.http.HttpResponse response = http.execute( post );

It produces no errors. However a response from the server I get "No Authorization header". Checking the request with Wireshark unveils that there is indeed no basic authentication set.
How is that possible?

A: Okay, by default the basic authentication is turned off. However, enabling it is far too complicated (link) . Therefore one can use this code, which works fine:
DefaultHttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost(strURL);
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(
                    Configuration.username,
                    Configuration.developerKey);
post.addHeader( BasicScheme.authenticate(creds,"US-ASCII",false) );
StringEntity entity = new StringEntity( ac.toXMLString() );
entity.setContentType("text/xml");
post.setEntity( entity );
org.apache.http.HttpResponse response = http.execute( post );

A: User of credential provider
HttpClient client = new DefaultHttpClient();
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(apiUser,apiPassword);
provider.setCredentials(new AuthScope(apiHost, apiPort, AuthScope.ANY_REALM), credentials);
HttpComponentsClientHttpRequestFactory commons = new HttpComponentsClientHttpRequestFactory(client);


text:
Q: Preventing a browser from getting stuck on an AJAX request I am currently trying to send a request when an user closes the page. I am using the onbeforeunload event.
The event triggers when the tab is closed or the page is refreshed. My event looks as follows:
window.onbeforeunload = function () {
    $.ajax({ //jQuery
        type: "POST",
        url: "offline.php",
        data: {
            logout: 'false'
        }
    });
};

offline.php (this is not the complete script):
...
unset($_SESSION["onpage"];
if ($_POST['logout'] == "false") {
    sleep(3);
    if (isset($_SESSION["onpage"]) || !empty($_SESSION["onpage"])) die();
}
...

When a user closes the page, script unsets a session that is set on the page of the chat. After three seconds, the script should check if the user has returned but checking the onpage session. However, the problem comes in when I hit the refresh button. On refresh, the page does not load because the three seconds have completed. This is causing my whole system to be ruined.
I have tried adding ignore_user_abort(true); but it did not solve my issue. Is there any other way of getting this to work?
Side Note: This is for a chat. When a user closes the page, it should notify the other users on the chat with a "The user has left" message. This should not be displayed on refresh. When a user comes back to the page, it should notify the other users that the user has returned with a "The user has entered" message.

A: The Problem
I'm afraid what you're attempting to do isn't really possible, as there are many times in which onbeforeunload won't get called, due to browser implementation, user preference, your pet zebra knocking your computer off the table, etc.
From Mozilla's beforeunload documentation:

Note also that various mobile browsers ignore the result of the event (that is, they do not ask the user for confirmation). Firefox has a hidden preference in about:config to do the same. In essence this means the user always confirms that the document may be unloaded.

https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
The Solution
That doesn't mean handling users going offline is impossible, however.
Most chat web applications instead employ a heartbeat (a regular ping-like request), and use the distance between last ping to determine user disconnects. As an additional note, I would recommend allowing a wider window than three seconds to determine user disconnects, because there are many reasons a ping may not make it within a three second timeframe.
Implementation Strategy
You have a few options to implement a ping. Most commonly, people will use a window.setTimeout to invoke the ping, which will restart the window.setTimeout upon completion or failure, usually doubling the delay on successive failures so you aren't barraging a potentially-overloaded service.
setTimeout to Ping:
var i = 1000;

(function ping() {
  $.ajax({
    type: "POST",
    url: "ping.php"
  }).done(function() {
    i = 1000;
    window.setTimeout(ping, i);
  }).fail(function() {
    i = i * 2;

    if (i > 60000) {
      // We don't wait to wait longer than a minute
      i = 60000;
    }

    window.setTimeout(ping, i);
  });
}());

What about window.setInterval instead? Won't my code be shorter?
Please don't do that. My above note about "barraging an overloaded service"? It'll be plenty worse if you do that.

A: You really shouldn't be counting on onbeforeunload or beforeunload since a browser shouldn't require itself to do something on your behalf right before a user closes your webpage.  If it did, it would open up a whole avenue of attack for malicious code where you could never close a page (think going to a torrent website and having 2 pages pop up every time you click on any DOM element, only now every time a user tries to close the tab, a recursive loop starts and prevents them from ever leaving without killing the browser through task manager).
Heartbeats
Most chat clients use a heartbeat system where the client automatically pings the server every x seconds.  This method works - but it's costly and inefficient.  You're forced to open and close new connections on a constant basis just to tell the server that you are still engaged.
Web Sockets
The contemporary way of building something like a chat system is to use web sockets.  These are persistent connections established by the server between your web browser and the server.  On a traditional web page, the server always reacts to the what the client does.  The client makes a request, the server responds; this process repeats itself over and over again.  The server never tells the client what to do and then wait for the client response.  With web sockets, instead of having this one way communication channel, we have a pipeline that allows for a continuously open connection with bidirectional communication.
Creating Web Sockets
This isn't a trivial task.  There's a lot of boilerplate code out of the gate you would have to write to get some basic functionalities working.  But the good news is that you don't have to do this.  There are several 3rd party JavaScript SDKs / back-end services that encapsulate all of the ground level browser implementation logic for you and make available to you a simple, clear interface.  Think of their relationship to web sockets as what jQuery was to plain JavaScript.  They standardize everything for you so you don't have to worry about writing low level web socket implementation and syncing up cross browser compatibility.
One of my favorite web socket services is Firebase.  Coincidentally, the demo project they showcase on their website is a real-time chat application built using the web socket support their service provides.  Firebase can be set up to be an indepedent database source if you want it to be that.  Or it can simply be used as a medium of communications between your traditional SQL database (which communicates with it through a RESTful API) and client devices (browsers, apps, etc...).

A: I would like to point out that, as others have said, doing an AJAX request on the page unload event is highly unreliable.
However, you may be interested in Navigator.sendBeacon()
Relevant excerpt:

This method addresses the needs of analytics and diagnostics code that typically attempt to send data to a web server prior to the unloading of the document.

https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
It is experimental, but once fully supported, should do what you want.

A: AJAX can get cut off as the page leaves.
You need to use navigator.sendBeacon() instead.
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
window.addEventListener('unload', function () {

     navigator.sendBeacon("offline.php", {
         logout: 'false'
     });

}, false);

This is simple, reliable, and needs no server smarts like juggling heartbeats entails.
Of course, like anything good in webdev, IE compat is lacking...


text:
Q: How to make step progress bar arrow with border color I'm looking for a reference on how to make a step progress bar arrow with CSS. Where the step progress bar arrow that is made has a border and has a different background color than the border. An example can be seen in the following image:
step progress bar arrow with border
How to make step progress bar arrow with border color
can anyone help how to make it?


text:
Q: How do I install modernizr 3 via rails-assets? modernizr 2 was easy to install from rails-assets.
# Gemfile
gem 'rails-assets-modernizr'
# application.js
//= require modernizr

However, the modernizr 3 docs say:

A lot has changed since the last version of Modernizr. There no longer is a single, base modernizr.js file. Instead, just head over to the Download page as you could have previously, and select the features you want to use in your project.
  https://modernizr.com/docs/

This makes it sound like I can't get modernizr 3 from rails-assets anymore. Is this true?
As expected, if I try to install modernizr 3 from rails-assets I get:
An ActionView::Template::Error occurred ...

  couldn't find file 'modernizr' ...
  app/assets/javascripts/application.js:20

A: I didn't get v3 to work. I down versioned to 2.8.3 like by changing my gemfile like this:
source 'https://rails-assets.org' do
  gem 'rails-assets-respond'
  gem 'rails-assets-modernizr', '2.8.3'
end


text:
Q: How to reassign variable value in ajax response javascript jquery I already spend my time to knowing why my variable is cannot be reassign when my ajax response is successfull, but the result is still giving nothing happen with my variable value, I already do some trick to reassign my variable value but the result is still same nothing changed, here my code :
setTimeout(() => {
   let scrollHeight = 1500;
   $(".my-class-content-scroll").animate({scrollTop: scrollHeight}, 5000);

   $(".my-class-content-scroll").on('scroll', function () {
       let newScrollHeight = 0 ;

       if (scrollHeight >= 1500) {
          $.ajax({
            url: `/my-url`,
            method: "GET",
            dataType: "JSON",
            success: function (success) {
               /* my process when response is success */
               /* start reassign the value */
               const newValue = $(".my-class-content-scroll").prop("scrollHeight");
               newScrollHeight = newValue
            }
          });
       }
       console.log(newScrollHeight) /* <= the result is giving 0 value */
   })
}, 1000)

for another trick I try to reassign the variable value with the function, like this :
setTimeout(() => {
   let scrollHeight = 1500;
   $(".my-class-content-scroll").animate({scrollTop: scrollHeight}, 5000);

   $(".my-class-content-scroll").on('scroll', function () {
       let newScrollHeight = 0 ;

       function setScrollHeight (height) {
           newScrollHeight = height
       }

       if (scrollHeight >= 1500) {
          $.ajax({
            url: `/my-url`,
            method: "GET",
            dataType: "JSON",
            success: function (success) {
               /* my process when response is success */
               /* start reassign the value */
               const newValue = $(".my-class-content-scroll").prop("scrollHeight");
               setScrollHeight(newValue)
            }
          });
       }
       console.log(newScrollHeight) /* <= the result is still same than before and giving 0 value */
   })
}, 1000)

I hope anyone can explain to me why my method is not working if anyone found the answer about my problem, thank you good people


text:
Q: For each name and namespace I'm trying to run some bulk commands. In the below case I want to delete
all pods which doesn't have the state running.
The piped input to xargs looks as below
ingress-nginx nginx-ingress-controller-b84c455b-5k48p
ingress-nginx nginx-ingress-controller-b84c455b-5kwsc
ingress-nginx nginx-ingress-controller-b84c455b-88tnp
ingress-nginx nginx-ingress-controller-b84c455b-q96rj
ingress-nginx nginx-ingress-controller-b84c455b-tb98v
ingress-nginx nginx-ingress-controller-b84c455b-v9xmw
kafka kafka-0
kafka zookeeper-2
kube-system kubernetes-dashboard-5946dfdf8d-hz7gk
kube-system kubernetes-dashboard-5946dfdf8d-sv5lb
logging es-data-1
...

I want to both values in the same command. My attempt looks as below
$ kubectl get pods --all-namespaces | \
                    grep -v Running | \
                          tr -s ' ' | \
                   cut -d" " -f 1,2 | \
                         tail -n +2 | \
         xargs -n 1 echo "cmd $1 $2"

The output is
cmd   ingress-nginx
cmd   nginx-ingress-controller-b84c455b-5k48p
cmd   ingress-nginx
cmd   nginx-ingress-controller-b84c455b-5kwsc
cmd   ingress-nginx
cmd   nginx-ingress-controller-b84c455b-88tnp
cmd   ingress-nginx
cmd   nginx-ingress-controller-b84c455b-q96rj
cmd   ingress-nginx
cmd   nginx-ingress-controller-b84c455b-tb98v
cmd   ingress-nginx
cmd   nginx-ingress-controller-b84c455b-v9xmw
cmd   kafka
cmd   kafka-0
cmd   kafka
cmd   zookeeper-2
cmd   kube-system
cmd   kubernetes-dashboard-5946dfdf8d-hz7gk
cmd   kube-system
cmd   kubernetes-dashboard-5946dfdf8d-sv5lb
cmd   logging
cmd   es-data-1

Clearly I want a single command with both input values. Any suggestions on how to make that happen? Possible with a simpler command?

A: Be sure to capture per-line (-L1) then let a shell take care of the $ parsing, i.e. below should work for you
xargs -L1 sh -c 'echo cmd $1 $2' --

A: You can process two args with -n 2:
xargs -n 1 echo cmd

Specifying $1 and $2 doesn't work with xargs, the two parameters will be sent to the command automatically. In fact, they're the reason of the spaces after cmd in your output: they get interpreted by the shell before xargs sees them, and they expand to empty strings.


text:
Q: android data from previous intent not being save I'm sure this is a novice question, but in my MainActivity I have a map of objects that I got from a sqlite database. This is just a simple listView that has an onClick that opens a detail view. The list works fine, and going to the details page works fine, but when I hit the back button to get back to the list my map is not in the same position as it was before. The keys are still intact so my listview LOOKS like it should, but the data behind the keys is either corrupted or missing compared to how it was before the view change. Is there something I have to do to preserve my map before switching to the detailView?
I could get the data again from the database but that seems really inefficient and poor practice.


text:
Q: Laravel: Route returns 404 page on form submit SOLVED
web.php route:
Route::post('/admin/users/action', [
    'uses' => 'UserController@massAction',
    'as' => 'user.massAction'
]);

form:
<form id="users-form" role="form" method="POST" action="{{ url('/admin/users/action') }}">
    {{ csrf_field() }}
    ...
</form>

UserController massAction method that doesn't get reached:
public function massAction(Request $request)
{
    $userIds = $request->input('users');
    $user = new User();

    switch ($request->input('mass-action')) {
        case 1:
            $user->deleteUser($userIds);
            $request->session()->flash('message-success', 'User(s) deleted!');
            break;
    }

    return redirect()->back();
}

On form submit it should return back with a message, but it doesn't even reach the controller. Setting a breakpoint inside the method confirms that it doesn't reach it.
It just goes to /admin/users/action and returns 404 error, because this page doesn't exist. It should go to massAction method inside UserController and get redirected back to the page where form was submitted.
I am doing the same thing for products, attributes, etc. and it works fine. Only this route and method doesn't work. Other routes in the same UserController work.

A: Try to use route() instead url().
Change action in  from url() to route() and check this out.
action="{{ route('user.massAction') }}"

A: I think you need change your route like:
web.php route:
 Route::post('/admin/users/action','UserController@massAction')->name('user.massaction');

form:
<form id="users-form" role="form" method="POST" action="{{ route('user.massaction') }}">
    {{ csrf_field() }}
    ...
</form>

A: The problem was in one of input fields. Have no idea why it didn't throw any errors or even reach the controller before.
This
<input class="entity-select" type="checkbox" name="specifications[{{ $user->id }}][id]" value="{{ $user->id }}">

needed to be like this
<input class="entity-select" type="checkbox" name="users[{{ $user->id }}[id]" value="{{ $user->id }}">

After changing it back to the wrong input field name it now throws out a error and also reached breakpoint in UserController. Maybe some view cache problem? If that is a thing.

A: Use put in the form after CSRF like this.

@csrf
 @if(isset($category))
  @method('PUT')
 @endif


text:
Q: Django context processor not rendering from shell Using Django 3.2
Have defined few global variables like
app/context_processors.py
from app.settings import constants

def global_settings(request):
    return {
        'APP_NAME': constants.APP_NAME,
        'APP_VERSION': constants.APP_VERSION,
        'STATIC_URL_HOST': constants.STATIC_URL_HOST
    }

and in settings.py file
TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                ...
                'app.context_processors.global_settings',
            ],
        },
    },
]

Have used APP_NAME in the email template footer like
account/emails.py
def welcome_email(user):

    subject_file = 'account/email/welcome_subject.txt'
    body_text_file = 'account/email/welcome_message.txt'
    body_html_file = 'account/email/welcome_message.html'

    subject_text = get_template(subject_file)
    body_text = get_template(body_text_file)
    body_html = get_template(body_html_file)

    context = {
        'username': user.username,
    }

    subject_content = subject_text.render(context)
    body_text_content = body_text.render(context)
    body_html_content = body_html.render(context)

    to = [user.email]

    msg = EmailMultiAlternatives(
        subject=subject_content,
        body=body_text_content,
        from_email='{} <{}>'.format('Admin', 'admin@example.com'),
        to=to,
    )
    msg.attach_alternative(body_html_content, 'text/html')
    msg.send()

templates/account/welcome_message.html
Hi {{ username }},

Welcome to the application.

{{ APP_NAME }}

When the email is sent from the web portal, the APP_NAME is rendered fine, but when the email send is initiated from the Django shell
python manage.py shell

> from account.emails import welcome_email
> welcome_email(user)

Then the APP_NAME is not rendered in the email.
How the context processor can be rendered from the shell as well?

A: A context processor takes as input an HttpRequest object, hence for a context processor to be run when a templates render method is called a request is needed to be passed to it like template.render(context, request). Your welcome_email function doesn't take request and naturally can't pass it.
If this function is called from some view all you need to do is take the request as an argument and pass it to the templates render method:
def welcome_email(user, request):
    ...
    subject_content = subject_text.render(context, request)
    body_text_content = body_text.render(context, request)
    body_html_content = body_html.render(context, request)
    ...

If it is called by some automated process which doesn't have a request object, well since your processor doesn't even need the request and the values you use are constant just pass them yourself from the function.


text:
Q: Codeigniter multi forms on one page validation errors I have two forms in my page. when I submit either of the form, both of them show the same validation error message. I used
if (isset ($_POST['click_cus_button']))

to check what button is licked in the from seems it does not work for me.
Can anyone tell me why this bit of code isn't working?
this is my controller (admin.php)
function add_users_data()
{

    if (isset ($_POST['click_cus_button']))// click_cus_button is set load this validation errors
    {
        $this->form_validation->set_rules('cus_name', 'Name', 'trim|required|min_length[5]');
        // validate name
        $this->form_validation->set_rules('cus_email', 'Email', 'trim|required|valid_email');
        // validate email
        $this->form_validation->set_rules('cus_phone', 'Phone Number', 'trim|required|min_length[10]|max_length[10]');
        // validate phone number
        $this->form_validation->set_rules('cus_password', 'Password', 'required|matches[cus_passconf]');
        // validate password
        $this->form_validation->set_rules('cus_passconf', 'Retype Password', 'required');
        // validate password
        if ($this->form_validation->run() == FALSE)// if from validation failed load following pages from views
        {

            $this->load->view('admin/admin_add_users.php');

        }
        else // if from validation success load following pages from views
        {
            $data = array(
                'cus_name' => $this->input->post('cus_name'),
                'cus_email' => $this->input->post('cus_email'),
                'cus_mobile' => $this->input->post('cus_mobile'),
                'cus_phone' => $this->input->post('cus_phone'),
                'cus_status' => $this->input->post('cus_status')
                //'database_field' => $this->input->post('text_box_name')
            );
            $this->mod_users->add_record($data);//add a comment
            $data['result']="Customer Added Successfully ";
            $this->load->view('admin/admin_add_users.php',$data);

        }
    }
    else if (isset ($_POST['click_oper_button']))// click_oper_button is set load this validation errors
    {
        $this->form_validation->set_rules('oper_firstname', 'Name', 'trim|required|min_length[5]');
        // validate name
        $this->form_validation->set_rules('oper_lastname', 'Name', 'trim|required|min_length[5]');
        // validate name
        if ($this->form_validation->run() == FALSE)// if from validation failed load following pages from views
        {

            $this->load->view('admin/admin_add_users.php');

        }
        else // if from validation success load following pages from views
        {

            $data['result']="Customer Added Successfully ";
            $this->load->view('admin/admin_add_users.php',$data);

        }
    }
}

this is my View (admin_add_users.php)
I removed some fields to make the code shorter in the view
 <?php  echo form_open('admin/add_users_data')   ?>

                <?php  echo validation_errors('
', '
'); ?>
                <?php

                if(isset($result))
                {
                    echo '
'.$result.'
';
                }

                ?>

                <feildset>
                    <legend>Add Customer</legend>

                    <input name='cus_status' type='hidden' value='disabled'/>
                    <input type="submit" value="Add Customer" class="info" name="click_cus_button">
                </feildset>

            <?php  echo validation_errors('
', '
'); ?>
            <?php

            if(isset($result))
            {
                echo '
'.$result.'
';
            }

            ?>
            <feildset>
                <legend>Add Operator</legend>

*All fields marked are required

                <lable>Name*</lable>

                    <input type="text" name="oper_firstname" placeholder="First Name">

                    <input type="text" name="oper_lastname" placeholder="Last Name">

                        Gender*

                        <input type="radio" checked="" name="oper_gender">

                        Male

                        <input type="radio" name="oper_gender">

                        Female

                <lable>Date of Birth*</lable>

                    <input id="datepicker" name="oper_dob" type="text">

                <lable>Address*</lable>

                    <input type="text" name="oper_add_no" placeholder="No">

                <input type="submit" value="Add Operator" class="info" name="click_oper_button">
            </feildset>

            RadioButton 3 Selected

    <?php  echo form_close(); ?>


text:
Q: Calculating size of Directory in C I want to calculate the size of the directory (path) recursively. In my current code I have a function that identifies if it's a directory or file, if it's a directory it calls the function with the subdirectory (file) and if it's a file it adds to the totalSize variable. However, my current code doesn't return anything meaning that there is an error somewhere.
here is my code -
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>

void getsize(const char *path,int* totalSize);

int main()
{
    int total = 0;
    char path [] = "C:\\Users\\abbas\\Desktop\\Leetcode airplane";
    getsize(path,&total);
    printf("%d",total);
    return total;

}

void getsize(const char *path,int* totalSize)
{
    struct dirent *pDirent;
    struct stat buf;
    struct stat info;
    DIR *pDir;
    int exists;
    char str[100];
    pDir = opendir (path);
    while ((pDirent = readdir(pDir)) != NULL)
    {
        stat(pDirent->d_name,&info);
        if(S_ISDIR(info.st_mode))
        {
            strcpy(str,path);
            strcat(str,"/");
            strcat(str,pDirent->d_name);
            getsize(str,totalSize);
        }
        else
        {
            strcpy(str,path);
            strcat(str,"/");
            strcat(str,pDirent->d_name);
            exists = stat(str,&buf);
            if (exists < 0)
            {
                continue;
            }
            else
            {
                (*totalSize) += buf.st_size;
            }

        }
    }
    closedir(pDir);
}

A: *

*Include string.h.

*The arbitrary fixed sizestr[100] is problematic.  If you are on Linux include linux/limits.h and use str[PATH_MAX] or even better pathconf(path, _PC_NAME_MAX).  In either case you should either ensure the buffer is big enough (using snprintf() for instance), or dynamically allocate the buffer.

*You need to exclude . and .. otherwise you end up with an infinite loop (path/../path/..).

*stat(pDirent->d_name,&info) fails as you need to stat() path/pDirect->d_name not just pDirect->d_name.

*(not fixed) Maybe snprintf(path2, sizeof path2, "%s%s%s", path, PATH_SEP, pDirenv->d_name) instead of strcpy() and strcat()?

*Check return values of functions otherwise you are wasting time.

*No point of doing two stat() calls on the same path so just use (*totalSize) += buf.st_size;.

*(not fixed) On Windows, consider using _stat64() with the address of a struct __stat64 (@AndrewHenle).

*I assume you only want the size of files.

*(not fixed) It would be more natural if getsize() returned the size instead of using int *totalSize out parameter.

*(not fixed) Consider using nftw() (or the older ftw()) to walk the tree.

Note that program now accept path via command line for testing purposes.
#include <dirent.h>
#include <errno.h>
#include <linux/limits.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

const char PATH_SEP =
#ifdef _WIN32
    "\\";
#else
     "/";
#endif

void getsize(const char *path,int *totalSize) {
    struct dirent *pDirent;
    DIR *pDir = opendir (path);
    while ((pDirent = readdir(pDir)) != NULL) {
        if(
            !strcmp(pDirent->d_name, ".") ||
            !strcmp(pDirent->d_name, "..")
        )
            continue;

        char path2[PATH_MAX];
        strcpy(path2, path);
        strcat(path2, PATH_SEP);
        strcat(path2, pDirent->d_name);
        struct stat info;
        if(stat(path2, &info) == -1) {
            perror("stat");
            return;
        }
        if(S_ISDIR(info.st_mode))
            getsize(path2, totalSize);
        else if(S_ISREG(info.st_mode))
            (*totalSize) += info.st_size;
    }
    closedir(pDir);
}

int main(argc, char *argv[]) {
    if(argc != 2) {
        printf("usage: your_program path\n");
        return 1;
    }
    int total = 0;
    getsize(argv[1], &total);
    printf("%d\n",total);
}

and example test:
$ mkdir -p 1/2
$ dd if=/dev/zero of=1/file count=123
123+0 records in
123+0 records out
62976 bytes (63 kB, 62 KiB) copied, 0.000336838 s, 187 MB/s
$ dd if=/dev/zero of=1/2/file count=234
234+0 records in
234+0 records out
119808 bytes (120 kB, 117 KiB) copied, 0.0015842 s, 75.6 MB/s
$ echo $((62976 + 119808))
182784
$ ./your_program 1
182784

A: I think the major error of your code lies in the recursive logic.
To quote pp.183 of The C Programming Language:

Each directory always contains entries for itself, called ".",
and its parent, ".."; these must be skipped, or the program will
loop forever.

Therefore, maybe you can try adding the following if test
at the beginning of the while loop:
while ((pDirent = readdir(pDir)) != NULL)
{
    if (strcmp(pDirent->d_name, ".") == 0
        || strcmp(pDirent->d_name, "..") == 0)
        continue;  /* skip self and parent */
    /* ... */
}

Still, there might be other errors, but I think this one is the most significant.

A: Practice safe coding.
Below risks buffer overflow.
        // Risky
        strcpy(str,path);
        strcat(str,"/");
        strcat(str,pDirent->d_name);

Had code done,
int len = snprintf(str, sizeof str, "%s/%s", path, pDirent->d_name);
if (len < 0 || (unsigned) len >= sizeof str) {
  fprintf(stderr, "Path too long %s/%s\n", path, pDirent->d_name);
  exit (-1);
}

Then the code would have readily errored out do to recursion on "." and ".." and led to OP's self-discovery of a key problem.
This make for faster code production and more resilient code.  Saves OP time.


text:
Q: Replacing asp:imagebutton with processing image using jquery So I have an asp:imagebutton for lets say loginning into a web site.
OnClick the page does xyz and then redirects you, there is a pause time between the redirect from when the button was clicked. To make the wait a bit more user friendly I am replacing the button with a processing image and text the javascript that does this is:
$(document).ready(function () {
    $(".ShowProcessing").click(function () {
        $(this).replaceWith(" Processing");
    });
});

This is the button:
<asp:ImageButton ID="Login" runat="server" OnClick="Login_Click" CssClass="ShowProcessing" />

The problem is the change to processing image happens but the asp OnClick event however does not fire.

A: Instead of replacing the entire element with something else entirely, just alter the src of the current element:
$(".ShowProcessing").click(function () {
    $(this).attr("src", "/content/images/processing.gif");
});

This is if ImageButton is rendered as an img proper, somewhere, and not just some funky input with scripting (I don't recall off the top of my head, and webforms does some things in strange ways). Then proceed to insert text after the existing element as desired.

A: Instead of using .replace() tried and succeeded with:
$(".ShowProcessing").click(function () {
    $(this).hide();
    $(this).after(" Please wait..." )

});

A: I guess you may try to remove the first image and then add the new processing image.
instead of replace use (Remove then add) functions.


text:
Q: How to show selected values sent from Controller as List of Objects? AddTruck.jsp Page form below:
    <form:form method="post" modelAttribute="truckDto" action="myController">

       <form:checkbox path="operatingDays[0].weekDays"
value="MONDAY" class="weekday" id="weekday-mon"/>

       <form:checkbox path="operatingDays[1].weekDays"
value="TUESDAY" class="weekday" id="weekday-tue"/>

// likewise its for all days of week till sunday and the index of operatingDays keeps incrementing till end of week.
TruckDto has following property of ArrayList of Objects:
private List<TruckOperatingDays> operatingDays = new ArrayList<TruckOperatingDays>();
//getter setter below

TruckOperatingDays POJO has following properties with their getter-setter methods:
@Enumerated(EnumType.STRING)
    @Column(name = "week_days")
    private WeekDaysEnum weekDays;

    @Column(name = "opening_hours")
    private String openingHours;

    @Column(name = "closing_hours")
    private String closingHours;

When I submit the form, I get values in my controller as needed and I can save the values to my database with no issues. The problem is at the "Edit" time.
When I open this page to edit the values that has been saved previously in database, I fail to get the checkboxes already selected because of the index positions of operatingDays are static in the form and the ArrayList passed from controller doesn't set values to my input fields/checkboxes in the form.
Please note that I cannot use JSTL foreach loop to generate the form fields from the ArrayList because I need to show labels too as Monday, Tuesday etc.
Is there any way through which my form fields can automatically bind through my DTO proeprties just like we can bind simple input fields with no issues?

A: You can still use JSTL , just add an additional list to store the week days into (NOTE: this example assumes that your ArrayList returns all 7 days but some days may be null( not selected)).
<%
    String[] days = new String[]{ "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY" };
pageContext.setAttribute("wDays", days);
    %>
//and then use JSTL
<c:forEach items=${operatingDays} var="day", varStatus="counter">
   <form:checkbox path=${day.weekDays}
   value=${wDays[counter]} class="weekday" id="weekday-mon"/>
</c:forEach>

If you would like to avoid scriptlets, you can use <c:set> in your JSP page to populate the week days list or just populate the days list in your Java code (not in JSP)


text:
Q: Separate text using regex I have a string like
abcdefangners

and a set of numbers that specifies how to group the above string, such as
3,4

In this case, the output should be
abc,defa,gners

Is something like this possible using regex? I have one option of using a loop to get the comparisons of the set one by one, but is there a better way to do it?

A: You could do:-
/(.{3})(.{4})(.*)/

This would give you the substrings which you'd then have to join together.
You'd have to create the regexp for each set of numbers so it would not be as easy as other methods of string manipulation.


text:
Q: htaccess - Redirect root pages to folder What I have
http://www.my-domain.com/my-product1/
http://www.my-domain.com/another-product/
http://www.my-domain.com/about-us/

What I want
http://www.my-domain.com/product/my-product1/
http://www.my-domain.com/product/another-product/
http://www.my-domain.com/about-us/

The problems

*

*I have about 100+ products.

*The products needs to be redirected to the same URL prefixed with a "folder" called "product". The two first are products.

*I need to exclude pages like "about-us" and others like it.

*The redirect should be 301.

Question
How is it done? Would be too long to list redirecting every product manually, I think.
What I have found out so far
This might be a good start.
http://www.brightcherry.co.uk/scribbles/htaccess-301-redirect-an-entire-directory-folder/
RewriteEngine on
RewriteBase /
RewriteRule ^old_dir/(.*) http://www.example.com/new_dir/ [R=301,L]


text:
Q: Laravel 5.2 mail-tracker I build new project using laravel  5.2 and I want track emails opens,clicks and bounced emails .  But I didn't found the best. If you know please point me

A: This two package will be use full for you :

*

*https://github.com/jdavidbakr/mail-tracker

*https://github.com/ipunkt/laravel-analytics


text:
Q: Dialog onCreateDialog show error when pick up the DatePickerDialog My code is working fine in Activity but when i used this code in fragment its not override the method Dialog onCreateDialog() , its shows 'Method does not override the method from itssuperclass'.
TestFragment.java:
public class TestFragment extends DialogFragment implements View.OnClickListener{
private ImageView calendarOne_ime;
Context context;
private TextView tv_dateone;
private int myear;
private int mmonth;
private int mday;
static final int DATE_DIALOG_ID = 999;
TestFragment dialogFragment;

public TestFragment()
{
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootview = inflater.inflate(R.layout.activity_date_test, container, false);

     FragmentManager fm = getFragmentManager();
     dialogFragment = new TestFragment ();

    calendarOne_ime = (ImageView)rootview. findViewById(R.id.cone);
    tv_dateone = (TextView)rootview. findViewById(R.id.dateone_txt);
    calendarOne_ime.setOnClickListener(this);

    return rootview;

}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.cone:
            setCurrentDateOnView();
            addListenerOnButton();
            break;
    }
}

public void setCurrentDateOnView() {
    final Calendar c = Calendar.getInstance();
    myear = c.get(Calendar.YEAR);
    mmonth = c.get(Calendar.MONTH);
    mday = c.get(Calendar.DAY_OF_MONTH);
}
public void addListenerOnButton() {
    getActivity().showDialog(DATE_DIALOG_ID);
}
@Override
public Dialog onCreateDialog(int id){
    switch (id) {
        case DATE_DIALOG_ID:
            DatePickerDialog _date =   new DatePickerDialog(getActivity(), datePickerListener, myear,mmonth, mday){
                @Override
                public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
                {
                    if (year < myear)
                        view.updateDate(myear, mmonth, mday);
                    if (monthOfYear < mmonth && year == myear)
                        view.updateDate(myear, mmonth, mday);
                    if (dayOfMonth < mday && year == myear && monthOfYear == mmonth)
                        view.updateDate(myear, mmonth, mday);
                } };
            return _date; }
    return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
    // when dialog box is closed, below method will be called.
    public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
        myear = selectedYear;
        mmonth = selectedMonth;
        mday = selectedDay;
        // set selected date into textview
        // Toast.makeText(getApplicationContext(),new StringBuilder()  .append(mmonth + 1).append("-").append(mday).append("-") .append(myear).append(" "),Toast.LENGTH_LONG).show();
        tv_dateone.setText(new StringBuilder().append(mmonth + 1).append("/").append(mday).append("/").append(myear).append(" "));
    }
   };
 }

xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<RelativeLayout
    android:id="@+id/dateviewone_layout"
    android:layout_width="wrap_content"
    android:layout_weight="1.2"
    android:text="Area"

    android:gravity="center_vertical"

    android:layout_height="match_parent">

    <TextView
        android:id="@+id/dateone_txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Date"

        android:gravity="center_vertical"
        android:textStyle="bold"/>

    <ImageView
        android:id="@+id/cone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/appointment"
        android:layout_alignParentRight="true"

        android:layout_gravity="right"
        />

</RelativeLayout>

I also share the screen shot where i face the problem.
Any idea how to solve it?

A: Use this
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import com.pickcel.lite.agent.R;
import java.util.Calendar;

/**
 * A simple {@link Fragment} subclass.
 */
public class TestFragment extends Fragment implements View.OnClickListener{
    private ImageView calendarOne_ime;
    Context context;
    public static TextView tv_dateone;

    public TestFragment()
    {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootview = inflater.inflate(R.layout.fragment_payment, container, false);
        calendarOne_ime = (ImageView)rootview. findViewById(R.id.cone);
        tv_dateone = (TextView)rootview. findViewById(R.id.dateone_txt);
        calendarOne_ime.setOnClickListener(this);
        return rootview;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cone:
                android.support.v4.app.DialogFragment newFragment = new SelectDateFragment();
                newFragment.show(getFragmentManager(), "DatePicker");
                break;
        }
    }

  public static class SelectDateFragment extends android.support.v4.app.DialogFragment implements DatePickerDialog.OnDateSetListener {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar calendar = Calendar.getInstance();
        int yy = calendar.get(Calendar.YEAR);
        int mm = calendar.get(Calendar.MONTH);
        int dd = calendar.get(Calendar.DAY_OF_MONTH);
        return new DatePickerDialog(getActivity(), this, yy, mm, dd);
    }

    public void onDateSet(DatePicker view, int yy, int mm, int dd) {
        populateSetDate(yy, mm+1, dd);
    }
    public void populateSetDate(int year, int month, int day) {
        tv_dateone.setText(month+"/"+day+"/"+year);
    }

   }
}

Output:

A: Make Dialog fragment abstract.Follow below code:
public abstract class DialogFragment extends Fragment

For Datepicker follow below code:
Only need to send context of fragment/activity and textview/editext on
 which you need to open date picker.
  public static void setDateFromDatePicker(Context context, TextView textView) {

        int mYear, mMonth, mDay;

        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        // Launch Date Picker Dialog
        DatePickerDialog dpd = new DatePickerDialog(context,
                (view, year, monthOfYear, dayOfMonth) -> {
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(year, monthOfYear, dayOfMonth);
                    SimpleDateFormat sdf = new SimpleDateFormat(Constants.LOCAL_DATE_FORMAT, Locale.ENGLISH);
                    String formattedDate = sdf.format(calendar.getTime());
                    textView.setText(formattedDate);
//                    textView.setText(String.valueOf(dayOfMonth) + "/" + (monthOfYear + 1) + "/" + year);
                }, mYear, mMonth, mDay);
        dpd.show();
    }


text:
Q: Store paragraphs of text (including line breaks) in cloud kit and query I have another newbie question. Hopefully one of you programming gurus can help me with it.
I'm trying to fetch multiple paragraphs of text (e.g. a news article) from CloudKit. I don't know how to format the text so that it includes a line break. I've been told that I should use CKAsset instead of a String on the CloudKit record, but I don't understand how it's supposed to be formatted.
Can anyone help me understand this more?
Thanks in advance.

A: Would it suffice to have \n as the new line identifier? CKAsset is the way to go, you just need to:

*

*create the file

*create asset with the file's url

*save it to database

*remove the temp file afterwards.

When you get the record from CloudKit:

*

*access it's file path

*load the data using NSFileManager

*decode the data (this uses NSString, which is a bore, but don't know any other way)

Save Record:
let str = "sample \n string save to file"
if let url = NSURL(fileURLWithPath: NSTemporaryDirectory())?.URLByAppendingPathComponent("tempFile", isDirectory: false) {
    if str.writeToURL(url, atomically: true, encoding: NSUTF8StringEncoding, error: nil) {
        let asset = CKAsset(fileURL: url)
        let record = CKRecord(recordType: "TextAsset")
        record.setValue(asset, forKey: "text")
        CKContainer.defaultContainer().publicCloudDatabase.saveRecord(record) { savedRecord, error in
            if error != nil {
                println(error)
            } else {
                println(savedRecord)
            }
            // do this in completion closure, otherwise the file gets deleted before uploading
            NSFileManager.defaultManager().removeItemAtURL(url, error: nil)
        }
    }
}

Load record:
let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "TextAsset", predicate: predicate)
CKContainer.defaultContainer().publicCloudDatabase.performQuery(query, inZoneWithID: nil) { queryRecords, error in
    if let records = queryRecords {
        for record in records {
            let asset = record.valueForKey("text") as! CKAsset
            if let content = NSFileManager.defaultManager().contentsAtPath(asset.fileURL.path!) {
                let text = NSString(data: content, encoding: NSUTF8StringEncoding)
                println(text)
            }
        }
    }
}

Remember to handle errors appropriately, this is just a showcase sample code.


text:
Q: How to run VBS function with parameters from Java and assign result to variable I have this excel macro:
Function Calculate_Something(StartDate As Date, EndDate As Date) As Double

//some math is here, not important

Calculate_Something = Result
End Function

And I want to pass my dates to this macro, execute it in my Java program and finally get returned value and assign it to my value in Java.
I have created VBS script with this function and try to execute it like this in Java:
 String[] parms = {"wscript", "calc.vbs", "2017-02-06 09:38:36", "2017-02-06 12:47:41"};
 Runtime.getRuntime().exec(parms);

But it didn't work. Do you know how could I do that?

A: You will want to use cscript.exe instead of wscript.exe, they are both the same host but one is designed for GUI while the other is designed for the command line.
Modify the VBScript function to output the Result to screen (the executed command output stream) then retrieve it using the Process object derived from calling Runtime.getRuntime().exec(parms);.
There is a method of the Process object called getInputStream() which should allow you to access and read the value you returned by the script output.
try {
    String[] parms = {"cscript", "calc.vbs", "2017-02-06 09:38:36", "2017-02-06 12:47:41"};
    Process p = Runtime.getRuntime().exec(parms);

    // Get Input Stream from the Process
    BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));

    // Do something with stream, read etc.
    String line;
    while ((line = is.readLine()) != null)
        System.out.println(line);

} catch (Exception ex) {
    ex.printStackTrace();
}

Useful Links

*

*vbscript output to console

*What is InputStream & Output Stream? Why do we use them and when do we use each of them?

*Understanding getInputStream and getOutputStream


text:
Q: jQuery-UI Slide div right onClick I have an input search field and a div, in that div is a table that I can search through with the input search field;

$(document).on("click", '#zoekenbtn', function (event) {
    $("#zoekenpanel").toggle('slide', { direction: 'left' });
});

<input id="zoekenbtn" type="search" placeholder="&#128270"/>

<input type="button" class="zoekclose" value="X" />

                Klant

                Locatie

                Plaats

        @foreach (var temp in Model.Select(x => new { x.Id, x.Klant, x.Locatie, x.Plaats }))
        {

                    @temp.Klant

                    @temp.Locatie

                    @temp.Plaats

        }

<input id="zoekenbtn" type="search" placeholder="&#128270"/>

but this causes a problem; if you click on the input and click somewhere else. you're no longer focussed on the input, thus you can't type in it anymore. so you have to click it again to be able to type. which toggles the div again and closes it.
I need a way so that it doesn't toggle, but slides open from left to right.
Thank you :)

A: add
$(document).keypress(function() {
   $("#zoekenbtn").focus();
});

it would capture the keystroke and focus in you input field

$(document).on("click", '#zoekenbtn', function (event) {
    $("#zoekenpanel").toggle('slide', { direction: 'left' });

});
$(document).keypress(function() {
   $("#zoekenbtn").focus();
});

<input id="zoekenbtn" type="search" placeholder="&#128270"/>

<input type="button" class="zoekclose" value="X" />

                Klant

                Locatie

                Plaats

        @foreach (var temp in Model.Select(x => new { x.Id, x.Klant, x.Locatie, x.Plaats }))
        {

                    @temp.Klant

                    @temp.Locatie

                    @temp.Plaats

        }

A: I found what I wanted, I succeeded by adding
$(document).on("click", '#zoekenbtn', function (event) {
    if ($('#zoekenpanel').is(":hidden")) {
        $("#zoekenpanel").toggle('slide', { direction: 'left' });
    }
});

This way the slideToggle won't toggle while the panel is open :)


text:
Q: Alarm manager delay not working Hi,
I use the following code snippet to invoke an action after a delay using the AlarmManager. But the alarm is invoked immediately.
AlarmUtility.java
public void setAlarm(Context context) {
    AlarmManager am = (AlarmManager) context
            .getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
    am.setRepeating(AlarmManager.RTC_WAKEUP, 1000 *24*3600,
            1000 *24*3600, pi); // Millisec * Second * Minute
    } // trying to first trigger the alarm after 24 hrs and repeat after 24 hours

Please let me know what is my error

A: 1000 *24*3600 is definitely in the past and so, the alarm will trigger immediately:

If the time occurs in the past, the alarm will be triggered
  immediately, with an alarm count depending on how far in the past the
  trigger time is relative to the repeat interval.

Instead get the current time then add 24 hours for the inital wakeup:
Calendar calendar =  Calendar.getInstance();
calendar.add (Calendar.DATE,1);
long day = 1000 *24*3600;

am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), day , pi);

A: u should use like this:
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+time, time, pi);

and if u r want to use 1000 *24*3600, then use (1000 *24*3600)L. because 1000 *24*3600 is larger than Integer.Max_value.

A: Upon first look the problem seems to be with
am.setRepeating(AlarmManager.RTC_WAKEUP, 1000 *24*3600,
        1000 *24*3600, pi);

The second parameter triggerAtTime should point to a time, when the alarm should go off. It should not be a time interval.
Check the below sample:
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000 *24*3600,
        1000 *24*3600, pi);


text:
Q: How to prevent autoimplementation of Sync I have a struct containing unsafe code with the following method:
use std::sync::Arc;
use std::thread;

#[derive(Debug)]
struct Foo<T> {
    items: Vec<Box<(T, String)>>,
}

impl<T> Foo<T> {
    pub fn add_element(&self, element: T, key: String) {
        if !(self.items.iter().any( |i| i.1 == key)) {
            let mut items = unsafe {change_mut(&(self.items))};
            items.push(Box::new((element,key)));
        }
    }
}

unsafe fn change_mut<T>(x: &T) -> &mut T { // changes &self to &mut self
    &mut *(x as *const T as *mut T)
}

fn main() {
    let foo = Arc::new(Foo { items: vec!() });
    let clone = foo.clone();

    // This should not be possible, as it might lead to UB
    thread::spawn(move || clone.add_element(1, String::from("one")));

    println!("{:?}", *foo);

}

This struct is completely safe until someone starts using this method while multithreading. However, due to the fact the struct only contains a Vec<Box<T,String>>, Syncis implemented by default, which I would like to prevent.
I have found two ways to do this, both of which are not that great...

*

*Add a struct field which does not implement Sync for example *const u8, this is obviously rather bad, as it ends up resulting in unnecessary and unclear code and does not clearly show my intent.

*impl !Sync for Struct {} is not available on stable and will be removed according to this issue.
The corresponding error is telling me to use marker types instead, but the documention does not present a way to solve my problem either.

error: negative trait bounds are not yet fully implemented; use marker types for
 now (see issue #13231)
  --> src\holder.rs:44:1
   |
44 | impl !Sync for Struct {}
   | ^^^^^^^^^^^^^^^^^^^^^^^^

A: Interior mutability in Rust requires1 the use of UnsafeCell as a hint to the compiler that the normal rules do not apply.
Your structure should therefore look such:
#[derive(Debug)]
struct Foo<T> {
    items: UnsafeCell<Vec<Box<(T, String)>>>,
}

And then, the implementation of add_element is adjusted to:
impl<T> Foo<T> {
    pub fn add_element(&self, element: T, key: String) {
        if !(self.items.iter().any( |i| i.1 == key)) {
            let mut items = unsafe { &mut *self.items.get() };
            //                       ^~~~~~~~~~~~~~~~~~~~~~
            items.push(Box::new((element,key)));
        }
    }
}

The use of UnsafeCell makes change_mut completely unnecessary: it is the purpose of UnsafeCell, after all, to allow interior mutability. Note how its get method returns a raw pointer, which cannot be dereferenced without an unsafe block.

Since UnsafeCell does not implement Sync, Foo<T> will not implement Sync either, and therefore it becomes unnecessary to use negative implementations or any marker.

1 If you do not use it directly, chances are the abstractions you do use are built on it. It is as special as it could be: it is a lang item, as denoted by its attribute #[lang = "unsafe_cell"].


text:
Q: Path of a particle spiraling into a black hole Consider a stationary Schwarzschild black hole: in a vacuum, no rotation, no electric charge. Using the Schwarzschild metric, we can draw diagrams describing how the radial coordinate $r$ varies with the angular coordinate $\varphi$ when a photon or a massive test particle spirals from a large distance towards the black hole.
The $r$ coordinate relates to the circumference $2\pi r$ of a great circle around the singularity, to the area $4\pi r^2$ or the volume $\frac{4}{3}\pi r^3$ of a sphere, but $r$ itself is not the physical distance from the singularity, if I'm correct. Bearing this in mind, we may loosely call the $r,\varphi$-graph the path of the particle.
How about the path of the particle inside the event horizon? Is the Schwarzschild metric valid within the horizon? What is the meaning of "space and time change roles within the horizon"? Does the path within the event horizon still describe how the spatial coordinate $r$ varies with $\varphi$? Does it make sense physically to draw a path here?

A: One of the aspects of general relativity that students find hard is that coordinates do not have a physical relevance. In Newtonian mechanics we are used to thinking of coordinates $(t,x,y,z)$ as meaning times we can measure with our clock and distances we can measure with our rulers. However in GR coordinates are just labels we apply to identify points in spacetime. We often try to choose coordinates that do correspond to measurements in an intuitive way but this isn't always convenient or indeed possible. For example in the Schwarzschild coordinates the $r$ is not a radial distance i.e. not what you would measure if you dangled a tape measure radially down towards the event horizon.
The one quantity that all observers will agree on is the proper time. In your example we would attach a stopwatch to the infalling object, and zero it when the object started its plummet. Then the elapsed proper time, usually denoted by $\tau$, is just the time shown on the stopwatch. We describe the trajectory by using the proper time as a parameter, that is the position in spacetime is given by functions of the proper time:
$$ \begin{align} t(\tau) \\ r(\tau) \\ \theta(\tau) \\ \phi(\tau) \end{align} $$
The falling object reaches the singularity in a finite (usually short!) proper time so for every value of the proper time $\tau$ we can use the functions $t(\tau)$, $r(\tau)$, etc to assign a position $(t,r,\theta,\phi)$. In this sense the trajectory is well defined over the whole region outside and inside the event horizon.
The problem is that if we use the Schwarzschild coordinates we find the function $t(\tau) \to \infty$ as the trajectory approaches the horizon. This doesn't mean there is anything strange about the trajectory there, an infalling observer wouldn't even notice when they crossed the horizon. It just means we have chosen coordinates that don't make sense at the horizon.
And the same applies inside the horizon. A lot of nonsense has been written about the fact that $t$ becomes spacelike and $r$ timelike inside the horizon. The trajectory inside the horizon is perfectly well defined and the problem is just that our choice of coordinates isn't useful. We get round this by switching to a different set of coordinates e.g. the simplest coordinates that remain reasonably intuitive are the Gullstrand-Painlevé coordinates, though for numerical work we'd probably use the (much less intuitive) Kruskal-Szekeres coordinates.
I've ranted on a bit here. The point I want you to take away is that the trajectory parameterised by the proper time is perfectly well defined everywhere. We may get weird results when we express it in our chosen coordinate system, but that's our fault for making a poor choice of coordinates.


text:
Q: Can Connecting devices with the wrong type of cable (crossover/straight through) damage them? This is a CCNA question, the title pretty much says it all. What would happen if I connected a device with the wrong type of cable? Could the cable damage the device in some way?

A: Assuming we're talking about Ethernet connecting to Ethernet, without PoE (power over Ethernet) then no, connecting an Ethernet cable will not harm either device.
Connecting Ethernet to a modem port may harm one of the devices, but I forget which one.  Connecting Ethernet with PoE to a device with the incorrect cable MAY harm the device NOT supplying power. There are likely several other combinations which could cause harm to either or both sides.


text:
Q: Compiler deduction of rvalue-references for variables going out of scope Why won't the compiler automatically deduce that a variable is about to go out of scope, and therefore let it be considered an rvalue-reference?
Take for example this code:
#include <string>

int foo(std::string && bob);
int foo(const std::string & bob);

int main()
{
    std::string bob("  ");
    return foo(bob);
}

Inspecting the assembly code clearly shows that the const & version of "foo" is called at the end of the function.
Compiler Explorer link here: https://godbolt.org/g/mVi9y6
Edit: To clarify, I'm not looking for suggestions for alternative ways to move the variable. Nor am I trying to understand why the compiler chooses the const& version of foo. Those are things that I understand fine.
I'm interested in knowing of a counter example where the compiler converting the last usage of a variable before it goes out of scope into an rvalue-reference would introduce a serious bug into the resulting code. I'm unable to think of code that breaks if a compiler implements this "optimization".
If there's no code that breaks when the compiler automatically makes the last usage of a variable about to go out of scope an rvalue-reference, then why wouldn't compilers implement that as an optimization?
My assumption is that there is some code that would break where compilers to implement that "optimization", and I'd like to know what that code looks like.
The code that I detail above is an example of code that I believe would benefit from an optimization like this.
The order of evaluation for function arguments, such as operator+(foo(bob), foo(bob)) is implementation defined. As such, code such as
return foo(bob) + foo(std::move(bob));

is dangerous, because the compiler that you're using may evaluate the right hand side of the + operator first. That would result in the string bob potentially being moved from, and leaving it in a valid, but indeterminate state. Subsequently, foo(bob) would be called with the resulting, modified string.
On another implementation, the non-move version might be evaluated first, and the code would behave the way a non-expert would expect.
If we make the assumption that some future version of the c++ standard implements an optimization that allows for the compiler to treat the last usage of a variable as an rvalue reference, then
return foo(bob) + foo(bob);

would work with no surprises (assuming appropriate implementations of foo, anyway).
Such a compiler, no matter what order of evaluation it uses for function arguments, would always evaluate the second (and thus last) usage of bob in this context as an rvalue-reference, whether that was the left hand side, or right hand side of the operator+.

A: Here's a piece of perfectly valid existing code that would be broken by your change:
// launch a thread that does the calculation, moving v to the thread, and
// returns a future for the result
std::future<Foo> run_some_async_calculation_on_vector(std::pmr::vector<int> v);

std::future<Foo> run_some_async_calculation() {
    char buffer[2000];
    std::pmr::monotonic_buffer_resource rsrc(buffer, 2000);
    std::pmr::vector<int> vec(&rsrc);
    // fill vec
    return run_some_async_calculation_on_vector(vec);
}

Move constructing a container always propagates its allocator, but copy constructing one doesn't have to, and polymorphic_allocator is an allocator that doesn't propagate on container copy construction. Instead, it always reverts to the default memory resource.
This code is safe with copying because run_some_async_calculation_on_vector receives a copy allocated from the default memory resource (which hopefully persists throughout the thread's lifetime), but is completely broken by a move, because then it would have kept rsrc as the memory resource, which will disappear once run_some_async_calculation returns.

A: The answer to your question is because the standard says it's not allowed to. The compiler can only do that optimization under the as if rule. String has a large constructor and so the compiler isn't going to do the verification it would need to.
To build on this point a bit: all that it takes to write code that "breaks" under this optimization is to have the two different versions of foo print different things. That's it. The compiler produces a program that prints something different than the standard says that it should. That's a compiler bug. Note that RVO does not fall under this category because it is specifically addressed by the standard.
It might make more sense to ask why the standard doesn't say so, e.g.why not extend the rule governing returning at the end of a function, which is implicitly treated as an rvalue. The answer is most likely because it rapidly becomes complicated to define correct behavior. What do you do if the last line were return foo(bob) + foo(bob)? And so on.

A: Because the fact it will go out of scope does not make it not-an-lvalue while it is in scope. So the - very reasonable - assumption is that the programmer wants the second version of foo() for it. And the standard mandates this behavior AFAIK.
So just write:
int main()
{
    std::string bob("  ");
    return foo(std::move(bob));
}

... however, it's possible that the compiler will be able to optimize the code further if it can inline foo(), to get about the same effect as your rvalue-reference version. Maybe.

A:
Why won't the compiler automatically deduce that a variable is about to go out of scope, and can therefore be considered an rvalue-reference?

At the time the function gets called, the variable is still in scope. If the compiler changes the logic of which function is a better fit based on what happens after the function call, it will be violating the standard.


text:
Q: How do I merge datasets in H2O Flow on string columns? I am trying to merge two datasets. The dataset on the left contains data about input variables. The dataset on the right contains data about output variable. The two datasets has a common column that contains data of type string. I am trying to merge them into a single dataset, suign the common column, in H2O Flow. When I call the merge operation I get following error:
ERROR MESSAGE: DistributedException from /10.151.9.92:54321: 'Operation not allowed on string vector.'
H2O is running on my local machine.

A: This error indicates that the data type of the column you want to merge on is of type string. Merges are not allowed on columns of type string, so when you parse your datasets, set the data type of your merge column to enum. After that you should be able to do the merge.


text:
Q: Error in parsing the json and formatting to pretty json I have used requests module and now i got the data back in json format and by taking help from this How to Python prettyprint a JSON file i have written my code and while executing the code it gave me an errro Expected a string or buffer, so i have changed the variable passed to the parser to string. Now it again gave another error.
#Import
import requests
import json

r = requests.post('http://httpbin.org/post', data = {'key':'value'})
print(r.status_code)
got_data_in_json = r.json()
parsed_json = json.loads(str(got_data_in_json))
print(json.dumps(parsed_json, indent=4 ,sort_keys=True))

Error Log:
python requests_post.py
200
Traceback (most recent call last):
  File "requests_post.py", line 8, in <module>
    parsed_json = json.loads(str(got_data_in_json))
  File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 380, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

Any solutions to this problem?

A:
ValueError: Expecting property name: line 1 column 2 (char 1)

The problem is, str(got_data_in_json) is not a valid JSON:
In [2]: str(got_data_in_json)
Out[2]: "{u'files': {}, u'origin': u'50.57.61.145', u'form': {u'key': u'value'}, u'url': u'http://httpbin.org/post', u'args': {}, u'headers': {u'Content-Length': u'9', u'Accept-Encoding': u'gzip, deflate', u'Accept': u'*/*', u'User-Agent': u'python-requests/2.11.1', u'Host': u'httpbin.org', u'Content-Type': u'application/x-www-form-urlencoded'}, u'json': None, u'data': u''}"

The got_data_in_json is already a Python data structure which you can dump:
got_data_in_json = r.json()
print(json.dumps(got_data_in_json, indent=4, sort_keys=True))

A: r.json() parses the JSON for you and returns a Python data structure. There is no need to call json.loads() on that data.

A: r.json() returns json
so you don't need to json.loads(str(got_data_in_json))
import requests
import json

r = requests.post('http://httpbin.org/post', data = {'key':'value'})
print(r.status_code)
got_data_in_json = r.json()
print(json.dumps(got_data_in_json, indent=4 ,sort_keys=True))

output :
200
{
    "args": {},
    "data": "",
    "files": {},
    "form": {
        "key": "value"
    },
    "headers": {
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate",
        "Content-Length": "9",
        "Content-Type": "application/x-www-form-urlencoded",
        "Host": "httpbin.org",
        "User-Agent": "python-requests/2.11.1"
    },
    "json": null,
    "origin": "103.227.98.245",
    "url": "http://httpbin.org/post"
}


text:
Q: Servlet request.getParameter() always returning "null" I'm trying to send parameter from text box in JSP to the servlet.
For some reason I always get null when trying to get the parameter from the servlet.
My HTML code is :
<FORM method="POST" action="eimLoggingServlet">
        Execution Id <b><INPUT type="text" name="Execution_Id" size="10"> <INPUT
        type="submit" name="submit" value="Find log">
</FORM>

My Servlet Code is :
public class EimLoggingServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {

            String exeId = request.getParameter("Execution_Id");

        } catch (Exception e) {

        }

    }

}

And my Web.xml :
 <servlet>
    <servlet-name>eimServlet</servlet-name>
    <servlet-class>com.viewlinks.eim.monitoring.servlet.EimLoggingServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>eimServlet</servlet-name>
    <url-pattern>/eimLoggingServlet</url-pattern>
  </servlet-mapping>

exeId is always null.

A: I have Changed 'POST' to 'GET' and apparently the problem was solved:
JSP :
 <FORM method="GET" action="eimLoggingServlet">
        Execution Id <b><INPUT type="text" name="Execution_Id" size="10"> <INPUT
        type="submit" name="submit" value="Find log">
</FORM>

Servlet :
public class EimLoggingServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {

            String exeId = request.getParameter("Execution_Id");

        } catch (Exception e) {

        }

    }

}


text:
Q: Supremum of $\mathbb D \cap \left[0,\frac{1}{3}\right]$ I want to formally prove that $\sup\left(\mathbb D \cap \left[0,\frac{1}{3}\right]\right)=\frac{1}{3}$, where $\mathbb D=\left\{\frac{p}{10^n} ~|~ p \in {\mathbb Z}, n\in \mathbb
 N\right\}$ is the set of decimal numbers.
Clearly, any $x\in \mathbb D \cap \left[0,\frac{1}{3}\right]$ satisfies $x\leq \frac{1}{3}$.
Now, it remains to check that $\frac{1}{3}$  is the least upper bound, i.e. that for any $\varepsilon >0 $, there exists an element $x_0$ of $\mathbb D \cap \left[0,\frac{1}{3}\right]$ such that $x_0 + \varepsilon > \frac{1}{3}$.
If $\varepsilon> \frac{1}{3}$, then any $x_0$ from $\mathbb D \cap \left[0,\frac{1}{3}\right]$ is good. But how do I construct this element in the case when $0 \le \varepsilon \le \frac{1}{3}$. Clearly, this element is of form $x_0=\frac{p}{10^n}$ for natural numbers $p$ and $n$... But how can I justify its existence?

A: Note that, for each natural $n$,$$\frac13-\sum_{k=1}^n\frac3{10^k}=\sum_{k=n+1}^\infty\frac3{10^k}=\frac3{10^{n+1}}\cdot\frac1{1-\frac1{10}}=\frac1{3\times10^n}.$$Besides, $\sum_{k=1}^n\frac3{10^k}\in\Bbb D\cap\left[0,\frac13\right]$. So, for any $\varepsilon>0$, take $n\in\Bbb N$ such that $\frac1{3\times10^n}<\varepsilon$, and then$$\sum_{k=1}^n\frac3{10^k}\in\Bbb D\cap\left]\frac13-\varepsilon,\frac13\right].$$


text:
Q: copying zipfile results in being unable to expand it in my code, I do the following with a zipfile:
zipped = zipfile.ZipFile('reports.zip', 'w', compression=zipfile.ZIP_DEFLATED)
for f in os.listdir(csv_path):
  zipped.write('%s/%s' % (csv_path, f))
if zipped.testzip() != None:
  raise IOError('Something was wrong with the zipfile!')
copy2('reports.zip', os.path.join(app.config['DOWNLOADS'], 'reports.zip'))
zipped.close()

When I uncompress it in the directory it was created in, it seems to expand plenty fine. However, when I go to the downloads folder, it says
Unable to expand "reports.zip" into "downloads"
Error 1 - Operation Not Permitted

(archive utility mac os x)
What would cause this with copying the file? How would it be effectively avoided?

A: You copied file before it was closed. Change order of two last lines.


text:
Q: How to detach tmux when the shell exits but not when killed from session overview? Every terminal window I open automatically attaches to a new tmux session. Closing the shell inside such a tmux session should detach the tmux client for the terminal window to close. This can be done by setting this option:
set -g detach-on-destroy on

However, when I kill the current session from the session overview (Ctrl+b,w,x,y), the tmux client also detaches. Instead, I would like it to stay attached so I can select another session from the session overview.
The question is, how can I have tmux detach when the session exits because the process it's running (i.e. the shell) exits but stay attached when the session is killed from the session overview?

A: You might be able to do this by having detach-on-destroy off but putting detach-client in the pane-exited hook.

A: Here it is a bit more readably:
set -g remain-on-exit on
set -g pane-died 'if -F "#{&&:#{==:#{session_windows},1},#{==:#{window_panes},1}}" "killp; detach" "killp"'
set -g detach-on-destroy off


text:
Q: Best way to run external app only if it exists I've got a Perl script that as one of its final steps creates a compressed version of a file it has created.  Due to some unfortunate setups, we cannot guarantee that a given customer will have a specific compression function.  I want to put something like this together:
if ($has_jar) {
    system("jar -c $compressed_file $infile");
}
elsif ($has_zip) {
    system("zip -j $compressed_file $infile");
}
else {
    copy($infile, $compressed_file);
}

Where if they don't have either of the compression apps, it will just copy the file into the location of the compressed file without compressing it.
My sticky wicket here is that I'm not quite sure what the best way is to determine if they have jar or zip.  It looks like I can used exec() instead of system() and take advantage of the fact that it only returns if it fails, but the script actually does do a couple of things after this, so that wouldn't work.
I also need this to be a portable solution as this script runs on both Windows and various Unix distros.  Thanks in advance.

A: I think your best bet is File::Which.

A: For *nix based systems, this should work:
my $has_jar = `which jar` ne '';

This could potentially work for Windows as well if you include which.
Alternatively, you could try the command suggested by this answer,
my $has_jar = `for %i in (jar.exe) do @echo.   %~$PATH:i` ne '';

It most likely doesn't return '' if it doesn't find it, however, but I don't have Perl available on a Windows machine to test it out.

A: See my multi-which.

A: Look through the directories specified by the PATH environment variable.

A: Usually, things like that don't suddenly disappear from the system, so I suggest to check the presence of the tools during setup/installation and save the one to use in the config.

A: How about just try to run the program. If it can't be run, then you know there's a problem.

A: Why not use the Archive::Zip package to do the compression, eliminating the need for an external program altogether?

A: There are a couple of things to think about if you are going to do this:

*

*Use system and exec in the list form so the shell doesn't get a chance to interpret special characters.

*Can you store this as configuration instead of putting it in the code? See how CPAN.pm does it, for instance.

*How do you know that you are running what you think you are running? If someone makes a trojan horse of the same name, is your program going to happily execute it? Note that using the PATH, as noted in Sinan's multi-which, still has this problem since it relies on the user setting the PATH.


text:
Q: Yii2 doesn't link styles I want to use styles located at web/css and web/js using AppAsset.php. Here's the snippet from the top of my layout/main.php:
<?php

AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
    <meta charset="<?= Yii::$app->charset ?>">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php $this->registerCsrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>

And here's my AppAsset.php:
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        "css/bootstrap.min.css",
        "css/font-awesome.min.css",
        "css/prettyPhoto.css",
        "css/price-range.css",
        "css/animate.css",
        "css/main.css",
        "css/responsive.css"
    ];
    public $js = [
        "js/jquery.js",
        "js/bootstrap.min.js",
        "js/jquery.scrollUp.min.js",
        "js/price-range.js",
        "js/jquery.prettyPhoto.js",
        "js/main.js"
    ];
    public $depends = [
        'yii\web\YiiAsset',
    ];
}

Can you please point out my mistake.