text:
Q: Download Image from URL & Post to API via AJAX There are a number of images that I'm displaying on our website. In addition, we allow users to upload images or preview images from an external source URL. All images on the site are available via standard <img> tags, where the src is set to the relevant image URL.
When an image is clicked, I'd like to take the image and post it to an API, which will then process the image and return a result:
Base64 Encode:
function getBase64Image(img) {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);
  var dataURL = canvas.toDataURL("image/png");
  return dataURL.replace(/^data:image\/(png|jpg|jpeg);base64,/, "");
}

AJAX
$("#img").click(function () {

  var base64 = getBase64Image(document.getElementById("img"));

  $.ajax({
    url: post_url,
    type: 'POST',
    data: { "img_data": base64 },
    dataType: 'jsonp',
    processData: false,
    contentType: false,
    success: function () {
    ...
    },
  });
});

There are a couple of issues that I'm aware of and probably more. I'm not technically "uploading" an image, because most of the images are already being displayed on the page. I'm also encoding in Base64 to send to the server, but I really need the data decoded in UTF-8. I suppose that I can do that server-side, but would be nice to have it done here.

A: I think in this scenario you should have two flows: one to the image the user upload, and one to the image from external resource.
In the flow to the images from external resource: your system knows the external URL to the images, so you can pass the URL in the post request, then in the server you download the image and manipulate it as you want.
And the flow to the image selected by the user, you post the file to the server and manipulate it as you want.


text:
Q: how to send email through amazon ses I'm using nodemailer and nodemailer-ses-transport.
everytime I run my test code for send mail, I get an error message like this.
but I specified 'From' field in test I don't know why it won't recognize the field.
{ [InvalidParameterValue: Missing required header 'From'.]
message: 'Missing required header \'From\'.',
code: 'InvalidParameterValue',
time: Fri Apr 10 2015 01:34:36 GMT+0000 (UTC),
statusCode: 400,
retryable: false,
retryDelay: 30 }

the test code is here.
please let me know wrong code.
var nodemailer = require('nodemailer');
var ses = require('nodemailer-ses-transport');

var sendAuthCode = function(gmail, message, callback) {
    var transporter = nodemailer.createTransport(ses({
        accessKeyId : MY_ACCESS_KEY_ID,
        secretAccessKey : MY_SECRET_ACEESS_KEY,
        region : "us-west-2",
        rateLimit : 1
    }));

    transporter.sendMail({
        from: 'mail bot',
        to: gmail,
        subject: 'TEST',
        text: message
    }, function(err, resStatus) {
        if (err) {
            callback(err);
        } else {
            callback('success');
        }
    });
}

sendAuthCode("some@gmail.com", "hello", function (result) {
    console.log(result);
});

UPDATED
I solved the problem!!
problem was that amazon ses can only send mail between verified email address.
if you want send an email to user who not verified,
you should request to increase ses limit on ses dashboard.
anyway thanks for reply

A: You cannot use "mail bot" as sender. Use legitimate email.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I find time continuous A, B matrices from a discrete state space model? The easiest way to compute a discrete state space model from time continuous state space model is by this method.
$$
\begin{bmatrix}
A_d & B_d \\
0 & I
\end{bmatrix} = \exp\left(
\begin{bmatrix}
A & B \\
0 & 0
\end{bmatrix} h\right),
$$
But how would it be if I have the discrete state space model and I want to find the time continuous state space model?
Edit: I'm just guessing now. Is this the right method?
$$\frac {1}{h}\ln \left(\begin{bmatrix}
A_d & B_d \\
0 & I
\end{bmatrix}\right) = \begin{bmatrix}
A & B \\
0 & 0
\end{bmatrix}$$

A: If you want to find $T=\begin{bmatrix} A & B \\ 0 & 0 \end{bmatrix}$ such that $\exp(hT)=\begin{bmatrix} A_d & B_d \\ 0 & I \end{bmatrix}=:M$, then you can compute $\log(M)/h$ where $\log$ is the matrix logarithm. The matrix logarithm, like the complex logarithm, is multi-valued, but the principal one can be obtained by the Matlab function logm.


text:
Q: How can i make buttons, text, and images layed over another image resize with the image? How can I make buttons and images that are placed over a banner be responsive, as in when the browser is made smaller the image gets smaller however buttons and images and text do not shrink with the banner. What can i add to my code to make this all shrink correctly. here is part of my css and html code below. any help on this would be very appreciated, thanks!

#putimage {
  display: inline-block;
  position: relative;
}

#button1 {
  position: absolute;
  bottom: 25%;
  right: 38%;
  background-color: transparent;
  color: black;
  border: 2px solid #ffffff;
  font-size: 35px;
  color: white;
}

#button2 {
  position: absolute;
  bottom: 25%;
  right: 22%;
  background-color: transparent;
  color: black;
  border: 2px solid #ffffff;
  font-size: 35px;
  color: white;
}

#button3 {
  position: absolute;
  bottom: 25%;
  right: 3.4%;
  background-color: transparent;
  color: black;
  border: 2px solid #ffffff;
  font-size: 35px;
  color: white;
}

#text1 {
  position: absolute;
  bottom: 25%;
  right: 75%;
}

.headshot {
  position: absolute;
  top: 60px;
  left: 47px;
  z-index: 3;
}

.name {
  position: absolute;
  top: 71%;
  left: 7.8%;
}

.photos {
  position: absolute;
  top: 38%;
  left: 51.6%;
  font-size: 220%;
}

.photoscount {
  position: absolute;
  top: 28%;
  left: 55.8%;
  font-size: 220%;
}

  <input type="button" id="button1" value="Subscribe">
  <input type="button" id="button2" value="Message">
  <input type="button" id="button3" value="VIP Photos">

    ELO KITTY

    PHOTOS

    72

A: You can use @media queries to change style attributes according to screen size.
For instance, change the size of the .headshot image to 20% of its original when the screen has a minimum width of 200px and a maximum width of 700px. Please run the snippet and then switch to fullscreen to see that in action.
Here is a resource with more information on media queries.

@media (min-width: 200px) and (max-width:700px) {
  .headshot {
    width:20%;
  }
}

#putimage {
  display: inline-block;
  position: relative;
}

#button1 {
  position: absolute;
  bottom: 25%;
  right: 38%;
  background-color: transparent;
  color: black;
  border: 2px solid #ffffff;
  font-size: 35px;
  color: white;
}

#button2 {
  position: absolute;
  bottom: 25%;
  right: 22%;
  background-color: transparent;
  color: black;
  border: 2px solid #ffffff;
  font-size: 35px;
  color: white;
}

#button3 {
  position: absolute;
  bottom: 25%;
  right: 3.4%;
  background-color: transparent;
  color: black;
  border: 2px solid #ffffff;
  font-size: 35px;
  color: white;
}

#text1 {
  position: absolute;
  bottom: 25%;
  right: 75%;
}

.headshot {
  position: absolute;
  top: 60px;
  left: 47px;
  z-index: 3;
}

.name {
  position: absolute;
  top: 71%;
  left: 7.8%;
}

.photos {
  position: absolute;
  top: 38%;
  left: 51.6%;
  font-size: 220%;
}

.photoscount {
  position: absolute;
  top: 28%;
  left: 55.8%;
  font-size: 220%;
}

  <input type="button" id="button1" value="Subscribe">
  <input type="button" id="button2" value="Message">
  <input type="button" id="button3" value="VIP Photos">

    ELO KITTY

    PHOTOS

    72


text:
Q: Why is a .NET Core application always heavy? I would like to know why a .NET Core application is always heavy?
Because when I create a basic hello world application and publish it. Whether in one or more files. The program is at least 20 MB, it's huge. In fact the dependencies (.dll) are very numerous. While a "hello world" only requests a call to the System library (using System;) for example. But lots of libraries are generated so that the application is autonomous.
Actually I'm trying to create a tcp server / client connection but the client is way too heavy (At least 20mo...)

A: You are presumably building this application in self-contained mode. This means that the entire .NET Core runtime is included in your build output, which is going to add a fixed data size to your build files.
If you don't want to include the .NET Core runtime, then you have to build your application as runtime-dependent. Keep in mind that you can then only run this application in environments where the .NET Core runtime has already been pre-installed.

For reference:

Publishing your app as self-contained produces an application that includes the .NET Core runtime and libraries, and your application and its dependencies. Users of the application can run it on a machine that doesn't have the .NET Core runtime installed.
Publishing your app as runtime-dependent (previously known as framework-dependent) produces an application that includes only your application itself and its dependencies. Users of the application have to separately install the .NET Core runtime.


text:
Q: How to show zooming bar in google map I am using the following google map and everything looks perfect:
Google map
The only problem is that when a person zoom in to the street level and wants to zoom out he needs to have a mouse and use mouse wheel and if he does not have mouse working with this map is a pain.
So I need to put zooming bar  for example at left side of my map like this:

Is it possible to do that and how can I do that?(I appreciate any help)

A: You need to add the control to your map, like this:
map.addControl(new GSmallZoomControl());

You can find more information about GMaps controls here: https://developers.google.com/maps/documentation/javascript/v2/controls
This quote is from the above mentioned documentation

GSmallZoomControl - a small zoom control (no panning controls) used in the small map blowup windows used to display driving directions steps on Google Maps.


text:
Q: Laravel validate json data in this code i'm try to validate json data but validater return false
        $username = $data['username'];
        $password = $data['password'];

        $input = Input::json();
        $rules = array(
            'username' => 'required',
            'password' => 'required',
        );
        $input_array = (array)$input;
        $validation = Validator::make($input_array, $rules);
        if ($validation->fails()) {
            var_dump( $input_array );
        }else {
                $result = array('code'=>'3');
            }

var_dump result is :
array(1) {  ["parameters"]=>  array(3) {    ["password"]=>    string(9) "world"    ["username"]=>    string(1) "hello"    ["function"]=>    string(8) "register"  }}""

username and password is not null and $validation must be return true. but return false

A: Your var_dump shows the data you're trying to validate is inside a 'parameters' array.  You either need to change your rules to include the parameters, or you need to pass the parameters array to the validate method.
Option 1 - change your rules:
$rules = array(
    'parameters.username' => 'required',
    'parameters.password' => 'required',
);
$input_array = (array)$input;
$validation = Validator::make($input_array, $rules);

Option 2 - validate the data in the parameters array:
$rules = array(
    'username' => 'required',
    'password' => 'required',
);
$input_array = (array)$input;
$validation = Validator::make($input_array['parameters'], $rules);

A: Here is a method that has worked for me.
$InputData = array('username' =>Input::json('username'),
                    'password'=>Input::json('password'));

$validation = Validator::make( $InputData,array('username'=>'required|email','password'=>'required'));

Hope you find it usefull.


text:
Q: Haskell, unnamed command line arguments for optparse-generic I'm using optparse-generic to parse the command line arguments of a program called example. I have a datatype with named fields (record syntax). For example:
data Example = Example { foo :: Int, bar :: String } deriving (Generic, Show)

This generates a program which can be called as follows:
./example --foo 42 --bar "baz"

How can I tell optparse-generic that bar should be an unnamed, mandatory, positional command line argument. That means, I don't want to type --bar when I call example. For example, I want to call example the following:
./example --foo 42 "baz"

A: optparse-generic does not support generating such a parser from a single data type definition since Haskell does not support records with both labeled and unlabeled fields.
However, what you can do is generate one data type for all the labeled fields and one type for the unlabeled fields and then combine them using Applicative operations, like this:
data Labeled = Labeled { foo :: Int } deriving (Generic, Show)

instance ParseRecord Labeled

data Unlabeled = Unlabeled String deriving (Generic, Show)

instance ParseRecord Unlabeled

data Mixed = Mixed Labeled Unlabeled deriving (Show)

instance ParseRecord Mixed where
    parseRecord = Mixed <$> parseRecord <*> parseRecord


text:
Q: Angular - Use $index to load product images I have the following form in my AngularJS app:

        {{ relative image here }}

                 <select name="manufacturer[ [[$index]] ]" ng-model="selectedManufacturer" ng-change="getManufacturerModels(selectedManufacturer)">
                     <option value="">Manufacturer</option>
                     <option ng-repeat="manufacturer in manufacturers" value="[[manufacturer.id]]">[[manufacturer.name]]</option>
                 </select>

                 <select name="device[ [[$index]] ]" ng-model="selectedModel" ng-change="loadModelImage(selectedModel, $index)">
                     <option value="">Model</option>
                     <option ng-repeat="model in manufacturerModels" value="[[model.id]]">[[model.model + ' ' + model.variants[$index].memory + ' ' + model.variants[$index].colour]]</option>
                 </select>

What happens in this form is that a user will select a manufacturer from the first dropdown and a model from the model dropdown. The model dropdown will populate with the relative models after a manufacturer has been selected using Angular's $filter.
When the user has selected a model, loadModelImage is fired and what needs to happen here is that after a model selection, that model image is then loaded into the {{relative image here}} placeholder. This is currently being done like so:
$scope.loadModelImage = function (modelId, $index) {

        $http.get(ajaxurl + '?action=get_handset&hid=' + modelId)
            .success(function (data) {
                $scope.selectedHandsets++;
                $scope.modelImages.splice(0, 0, data.handset.images);
            })

    }

This issue with this is that if I replace the relative image here placeholder text with an  loading in the model images, each model that's been selected appears in every row.
My other issue is that if you remain on the same 'row' (see below screenshot) and change the handset image, another array of images is pushed to $scope.modelImages when it in fact the images for that 'row' should effectively be overwritten with the new selection.
To give you a clear understanding of how the form looks, here's a screenshot:

When you click 'add new handset' the row containing the dropdowns is visually duplicated and you can add select another handset.
I hope my problem's explained clearly enough, any Q's ask.


text:
Q: Adding android notification that notifies at a given time I want to add my app a feature wherein it will show a notification at a particular time, I.e. When the patient needs to take a medicine it will show a notification based on a given time. Where can i have a complete tutorial? Thanks =D

A: AlarmManager can be used to schedule when you want the notification to occur. Details about how to create notifications are available here.


text:
Q: How to add string to empty lines of file in scripting? Example : file1 has data like
abc
cab

def
xxy
zay

sri

ram

In this file 3rd,7th,9th lines are empty, how to fill this empty lines with Specific string?.
For example if i want to fill these lines with Hello
Output File should be like:
abc
cab
Hello
def
xxy
zay
Hello
sri
Hello
ram

A: sed 's/^$/Hello/' file1
will output what you want.
You can redirect that to the output file as below.
sed 's/^$/Hello/' file1 > file2
If you want to change the original file itself, you can use the -i option.
sed -i 's/^$/Hello/' file1


text:
Q: How do I use CPAN.pm to download other Perl modules? I'm new to Object-Oriented programming and the perldoc page on CPAN.pm confuses the hell out of me. My program needs to download a couple of modules if they don't already exist. Is this basically just:
CPAN::Shell->install("Module::Name::Here");

or is there more to it? Does that download the package, unarchive it, and install it, or just one or two of those steps? If it's not all three, how do I do the other one (or two)? I would like it to make sure it doesn't try to re-install anything if the package is already there - is this the default behavior of the function or no?
And how can I tell if Perl couldn't connect to CPAN to get the package?

A: No one else has mentioned it, but you have to load the CPAN config first:
use CPAN;

CPAN::HandleConfig->load;
CPAN::Shell::setup_output;
CPAN::Index->reload;

# now do your stuff

You can also look at the cpan(1) script that comes with CPAN.pm to see a lot of the programmer's interface in action. I also wrote on article for the latest issue of The Perl Review showing examples of the programmer's interface to CPAN.pm.
However, you might not need to do any of this. Why is your program downloading modules on its own? Are you trying to create a distribution that has dependencies? There are better ways to handle that so you don't have to repeat the work that's already done in other tools. For instance, see my article Creating Perl Application Distributions. You treat your program as if it's a module and get the benefit of all the cool module tools so you don't have to reinvent something.
If you tell us more about the problem that you're actually trying to solve, we might have other good answers too. :)
Good luck,

A: the perldoc page on CPAN.pm confuses the hell out of me.
Yes, documentation of the CPAN API is still a bit lacking.  It wasn't every really designed for programmatic use by others.  You might have better luck with CPANPLUS, if that's available to you.
My program needs to download a couple of modules if they don't already exist. Is this basically just: CPAN::Shell->install("Module::Name::Here");
Yes, that's pretty much it for the simplest possible thing.  In fact, that's pretty much all the 'cpan' command line program does when you type "cpan Module::Name::Here".  However, you will need to have CPAN.pm configured in advance.
Does that download the package, unarchive it, and install it?
Yes, all three.
I would like it to make sure it doesn't try to re-install anything if the package is already there - is this the default behavior of the function or no?
Yes, the default behavior is not to install anything if the module is up to date.  You can actually check that yourself with the "uptodate()" method like this:
my $mod = CPAN::Shell->expand("Module", "Module::Name::Here");
$mod->install unless $mod->uptodate;

And how can I tell if Perl couldn't connect to CPAN to get the package?
That's hard to do programmatically in a way that would be simple to explain.  You either need to look at the output or else just check $mod->uptodate afterwards;
my $mod = CPAN::Shell->expand("Module", "Module::Name::Here");
if ( ! $mod->uptodate ) {
    $mod->install;
    die "Problems installing" unless $mod->uptodate;
}

Best of luck!

A: Basically using CPAN is the following:
perl -MCPAN -e shell

if this is the first time you are running it, it will ask you a few questions and save the results in a configuration file.
then to install PGP::Sign just type:
install PGP::Sign

and you're set.
As for you last question, don't worry, it will say to you whether it can connect or not.

A: As you can tell, most of us use only use CPAN.pm in the interactive mode, however, you're on the right track.
Things I can point out for the moment:

*

*Yes, calling CPAN::Shell->install() will download, compile, test and install a package. It should also do the same for any dependencies the package has, recursively.

*The default behaviour is to not install anything which is already installed (unless a newer version is available).

*I'm not strictly sure how the error handling works - I'll look into it, and report back.

*It might prompt your user, though.

A: Keltia has it right.  I'll add that his first instruction is done from the command prompt, usually as root, but not necessarily so.  The second command is done from the CPAN prompt.  You can also do it all on the command line, but I usually don't.
If you're using windows, your best bet is to use PPM, but its repositories are annoyingly out of date most times.


text:
Q: Adding graphics showing $\pm\Delta_{c^1}$, $\pm\Delta_{c^2}$, $\pm\Delta_{c^3}$ to a plot I have a ellipsoid equation given bellow. I want to find $\pm\Delta_{c^1}$, $\pm\Delta_{c^2}$, $\pm\Delta_{c^3}$ around the point $(81.32, 10.62, 17.17)$
Show[
  ContourPlot3D[
    425182.22 + 64.14985 c1^2 + 2.176 c2^2 +
    c2 (-1.013*10^-13 - 0.006 c3) +
    c1 (-10442.15 - 0.567c2 + 0.863846077 c3) -
    70.3549202 c3 + 0.0052366 c3^2 == 1,
    {c1,81,81.7}, {c2,9,12},{c3,-5,40},
    AxesLabel -> {c1, c2, c3},
    ContourStyle -> Directive[Orange, Opacity[0.7]],
    LabelStyle -> Directive[Black, 15],
    Mesh-> None],
  Graphics3D[{Black, PointSize[0.015], Point[{81.32, 10.62, 17.17}]}]]

A: f = 425182.22 + 64.14985 c1^2 + 2.176 c2^2 +
   c2 (-1.013*10^-13 - 0.006 c3) +
   c1 (-10442.15 - 0.567 c2 + 0.863846077 c3) - 70.3549202 c3 +
   0.0052366 c3^2 - 1;

c = {c1, c2, c3};
(*Finding the center by finding the minimum of the quadratic function*)

center = c /. Solve[D[f, {c, 1}] == {0, 0, 0}, c][[1]];
x = {x1, x2, x3};
(*Finding the principal axes with  Eigensystem.*)
A = 1/2 D[f /. Thread[c -> x], {x, 2}] /(-f /. Thread[c -> center]);
{a, e} = Eigensystem[A];
paxes = 1/Sqrt[a] e;

contour =
  ContourPlot3D[f == 0, {c1, 81, 81.7}, {c2, 9, 12}, {c3, -5, 40},
   PlotPoints -> 60,
   ContourStyle -> Opacity[.25],
   Mesh -> None
   ];

Show[
 contour,
 Graphics3D[{Opacity[0.25], Blue,
   Ellipsoid[center, Inverse[A]], PointSize[Large],
   Point[center],
   Thick, Black, Opacity[1],
   Red, Line[{center, center + paxes[[1]]}],
   Green, Line[{center, center + paxes[[2]]}],
   Blue, Line[{center, center + paxes[[3]]}]
   }]
 ]


text:
Q: Methods of Autowiring in Spring - Difference between the two possible alternatives below I have a basic Auto-wiring Question. I see the following two implementations that are possible in Spring auto-wiring
Method1
public class SimpleMovieLister {

private MovieFinder movieFinder;

@Autowired
public void setMovieFinder(MovieFinder movieFinder) {
    this.movieFinder = movieFinder;
}
// ...
}

Method2
public class SimpleMovieLister {

@Autowired
private MovieFinder movieFinder;
}

My understanding is that both are the same and I use a lot of Method2 in my code. What are the situations in which Method1 is useful ? Or is it just a case of Spring evolution and we have both possible ways in which to  implement.
Sorry, if the question is too basic, but I need to get this cleared up

A: Method 1 is Setter Injection.
Method 2 is Field Injection.
A 3rd method is Constructor Injection
Example:
public class SimpleMovieLister {

private MovieFinder movieFinder;

@Autowired
public SimpleMovieLister(MovieFinder movieFinder) {
    this.movieFinder = movieFinder;
}
// ...
}

Method 3, Constructor Injection is preferred because it makes testing significantly easier since you can pass in the required dependency.
Also, if your Bean only has 1 Constructor, then you can omit the @Autowired annotation.  Spring will automatically choose that constructor method when creating the bean.
A good snippet from the docs:

The Spring team generally advocates constructor injection as it
  enables one to implement application components as immutable objects
  and to ensure that required dependencies are not null. Furthermore
  constructor-injected components are always returned to client
  (calling) code in a fully initialized state. As a side note, a large
  number of constructor arguments is a bad code smell, implying that the
  class likely has too many responsibilities and should be refactored to
  better address proper separation of concerns.
Setter injection should primarily only be used for optional
  dependencies that can be assigned reasonable default values within the
  class. Otherwise, not-null checks must be performed everywhere the
  code uses the dependency. One benefit of setter injection is that
  setter methods make objects of that class amenable to reconfiguration
  or re-injection later. Management through JMX MBeans is therefore a
  compelling use case for setter injection.
Use the DI style that makes the most sense for a particular class.
  Sometimes, when dealing with third-party classes for which you do not
  have the source, the choice is made for you. For example, if a
  third-party class does not expose any setter methods, then constructor
  injection may be the only available form of DI.

A: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html
Method 1 is setter Injection

Setter injection should primarily only be used for optional
  dependencies that can be assigned reasonable default values within the
  class. Otherwise, not-null checks must be performed everywhere the
  code uses the dependency. One benefit of setter injection is that
  setter methods make objects of that class amenable to reconfiguration
  or re-injection later.

Method 2 is field Injection


text:
Q: Check if the directory content has changed with shell script or python I have a program that create files in a specific directory.
When those files are ready, I run Latex to produce a .pdf file.
So, my question is, how can I use this directory change as a trigger
to call Latex, using a shell script or a python script?
Best Regards

A: inotify replaces dnotify.
Why?

...dnotify requires opening one file descriptor for each directory that you intend to watch for changes...
Additionally, the file descriptor pins the directory, disallowing the backing device to be unmounted, which causes problems in scenarios involving removable media. When using inotify, if you are watching a file on a file system that is unmounted, the watch is automatically removed and you receive an unmount event.

...and more.
More Why?

Unlike its ancestor dnotify, inotify doesn't complicate your work by various limitations. For example, if you watch files on a removable media these file aren't locked. In comparison with it, dnotify requires the files themselves to be open and thus really "locks" them (hampers unmounting the media).

Reference

A: Is dnotify what you need?

A: Make on unix systems is usually used to track by date what needs rebuilding when files have changed. I normally use a rather good makefile for this job. There seems to be another alternative around on google code too

A: You not only need to check for changes, but need to know that all changes are complete before running LaTeX.  For example, if you start LaTeX after the first file has been modified and while more changes are still pending, you'll be using partial data and have to re-run later.
Wait for your first program to  complete:
#!/bin/bash
first-program &&
  run-after-changes-complete

Using && means the second command is only executed if the first completes successfully (a zero exit code).  Because this simple script will always run the second command even if the first doesn't change any files, you can incorporate this into whatever build system you are already familiar with, such as make.

A: Python FAM is a Python interface for FAM (File Alteration Monitor)
You can also have a look at Pyinotify, which is a module for monitoring file system changes.

A: Not much of a python man myself. But in a pinch, assuming you're on linux, you could periodically shell out and "ls -lrt /path/to/directory" (get the directory contents and sort by last modified), and compare the results of the last two calls for a difference. If so, then there was a change. Not very detailed, but gets the job done.

A: You can use native python module hashlib which implements MD5 algorithm:
>>> import hashlib
>>> import os
>>> m = hashlib.md5()
>>> for root, dirs, files in os.walk(path):
    for file_read in files:
        full_path = os.path.join(root, file_read)
        for line in open(full_path).readlines():
            m.update(line)

>>> m.digest()
'pQ\x1b\xb9oC\x9bl\xea\xbf\x1d\xda\x16\xfe8\xcf'

You can save this result in a file or a variable, and compare it to the result of the next run. This will detect changes in any files, in any sub-directory.
This does not take into account file permission changes; if you need to monitor these change as well, this could be addressed via appending a string representing the permissions (accessible via os.stat for instance, attributes depend on your system) to the mvariable.


text:
Q: Deferred non-critical caused high CLS I've deferred non-critical CSS/JS and preloaded base CSS of the website.
Every lab data on PageSpeed Insights have become better. Except "Largest Contentful Paint" and "Cumulative Layout Shift".
Especially, the CLS increases from 0.002 to 1.148!
The images on the website are set as background-image which I think there won't be "Images without dimensions" problem. I also tried to fix the font by using font-display, but the CLS is still the same.
Are there any other techniques I can use to optimize the CLS?

A: CLS Optimization
My answer addresses the second part of your question, regarding techniques that can be used to optimize CLS.
In broad terms, my solution hides the problematic elements in CSS, and makes them visible again in javascript. Layout shift is a problem - and contributes to the CLS score - only if if it is visible to the user; when it is invisible, it does not contribute to the CLS score. The detailed implementation is as follows.
First, create a class "antiCls" and add it to your custom CSS (in the HEAD element) as follows:
.antiCls {
    visibility: hidden;
}

Next, add the following code to the end of your custom JS file (at the bottom of the BODY element). First, the JQUERY version:
$(document).ready(function(){

...
existing jquery code
...

    $(window).on("load", function()

        $('.antiCls').css("visibility", "visible");

    });
});

Here is the vanilla javascript version, without jquery:
var cls = document.getElementsByClassName('antiCls'),
    i = cls.length;

for (i = 0; i < cls.length; i++) {
    cls[i].style.visibility = "visible";
    }

Next, you need to identify the elements to which you will apply your new "antiCls" class. Under the Google "PageSpeed Insights" for the page, look under the section "Diagnostics", and expand the sub-heading "Avoid large layout shifts". There, you will find the offending (non-zero) DOM elements listed: these will probably be images, but other elements (including whole divs) may be listed there as well.
For images, apply the new antiCls class to the parent div, not to the image itself. For elements grouped together under one parent div, apply the new antiCls class to the parent div. Some experimentation will be required, but a CLS score of zero can usually be achieved easily using this technique.
Whether a CLS score of zero should be achieved is another question. To be effective, the antiCls class needs to be applied "above the fold" - that is, to elements that appear in the viewport without scrolling. It is important that at least some elements remain at the top to the page to which the antiCls class has not been applied: these elements will usually include a logo, and possibly some navigation. That way, the speed with which the user is presented with some critical content ("First Contentful Paint") won't be negatively effected.
In my own tests I have discovered that this CLS optimization technique makes no perceptible difference to the speed with which the page is displayed; meaning that a low or zero CLS score can be achieved at nearly zero performance cost.

A: You need to inline your critical CSS.
Basically when the page loads it has to wait for all of your CSS to render the "above the fold" (everything immediately viewable without scrolling) content.
When you deferred all of your CSS you made that happen later so the HTML loads and then as your CSS loads the styles are applied, causing things to shift around on the page.
The key part of what it says is "defer non-critical CSS" needs deferring, "critical CSS" needs to load as early as possible.
What is critical CSS?
Critical CSS is all of the CSS required for the "above the fold" content.
What you do is add a <style> element to your document <head> and place all of the critical CSS in that.
That way the second all your HTML has loaded the browser also has all of the CSS it needs to render the page so it will render it almost instantly.
This is critical on a slow mobile connection as a large portion of load time on 3G / 4G is latency (round trip time to the server). Having the CSS required to render the initial page served as part of your HTML means there is only 1 request (your main page).
See this article which is quite good at explaining the concept
Please note this is not an easy task for most themes (locating the critical CSS is hard and most of the tools out there do not find all relevant styles) but is worth the effort if you are attempting to get super high initial load times.
This will fix your CLS as everything renders at once (so no layout shift).
The exception
You did mention you use background-image as part of your CSS.
You either need to give that initial dimensions for the container that has the background image or use the Padding top CSS hack or similar to set the dimensions of the box first.
Otherwise when the image loads in it will cause a layout shift. These dimensions should be set in your critical CSS.
Final things
Please note this will fix Page Speed Insights.
However it doesn't mean all CLS in the real world is fixed. If you get problems with "field data" (real world data) showing large CLS after you fixed the "Lab Data" (simulated) you may have things lazy loading in too late further down the page etc.
It is beyond the scope of this question but bear in mind that CLS is measured until page unload in the real world, as mentioned in this explanation on CLS from Addy Osmani who works on Google Chrome.


text:
Q: Error Message "/var/lib/snapd not root-owned 1001:1001" I have changed some ownerships by mistake through the following commands and now, I am facing an issue in accessing any software on my ubuntu 20.04. I am unable to access vs code, brave, and many more applications. PFA screenshot for your reference. Please help me with the same.

*

*chown -R man: /var/cache/man/

*sudo chown name -R name

*chmod 777 *

error prompt


text:
Q: Do not synchronize on objects that may be reused Why it is a bad practice to synchronize on the object which are changable.
How they lead to deadlock ?
For ex ::
private int count = 0;
private final Integer Lock = count; // Boxed primitive Lock is shared

public void doSomething() {
  synchronized (Lock) {
   count++;
   // ...
 }
}


text:
Q: python bash command: how to escape single quote? I'm trying to execute a shell command through python. The command is like the following one:
su -c "lftp -c 'open -u user,password ftp://127.0.0.1; get ivan\'s\ filename.pdf' " someuser

So, when I try to do it in python:
command = "su -c \"lftp -c 'open -u user,password ftp://127.0.0.1; get ivan\'s\ filename.pdf' \" someuser"
os.system(command)

Or:
command = subprocess.Popen(["su", "-c", "lftp -c 'open -u user,password ftp://127.0.0.1; get ivan\'s\ filename.pdf'", "someuser"])

I get the following error:
bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file

Referred to: ivan\'s single quote.
I know there are a lot of single/double quotes in that but how can I escape this?
Thanks in advance!
EDIT: THIS WORKED FOR ME:
subprocess.call(["su","-c",r"""lftp -c "open -u user,password ftp://127.0.0.1; get ivan\'s\ filename.pdf" """, "someuser"])

Thank you all very much!

A: If you printed your test string you would notice that it results in the following:
su -c "lftp -c 'open -u user,password ftp://127.0.0.1; get ivan's\ filename.pdf' " someuser

The problem is that you need to escape the slash that you use to escape the single quote in order to keep Python from eating it.
command = "su -c \"lftp -c 'open -u user,password ftp://127.0.0.1; get ivan\\'s\\ filename.pdf' \" someuser"

will get the backslash across, you will then get an error from lftp instead...
This works:
command = "su -c \"lftp -c \\\"open -u user,password ftp://127.0.0.1; get ivan\\'s\\ filename.pdf\\\" \" someuser"

(It uses (escaped) double quotes instead, to ensure that the shell started by su still interprets the escape sequences)
(os.system(a) effectively does subprocess.call(["sh","-c",a]), which means that sh sees su -c "lftp -c 'open -u user,password ftp://127.0.0.1; get ivan's\ filename.pdf' " someuser (for the original one). It does escape sequence processing on this and sees an unclosed single quote (it is initially closed by ivan'), resulting in your error). Once that is fixed, sh calls su, which in turn starts up another instance of sh doing more escape processing, resulting in the error from lftp (since sh doesn't handle escape sequences in the single quotes)
subprocess.call() or curl are better ways to implement this - curl will need much less escaping, you can use curl "ftp://user:password@127.0.0.1/ivan's filename.pdf" on the command line, some more escaping is needed for going viasu -cand for python.sudoinstead ofsu` also results in less escaping being needed....
If you want to use subprocess.call() (which removes one layer of shell), you can use
subprocess.call(["su","-c","lftp -c \\\"open -u user,password ftp://127.0.0.1; get ivan\\'s\\ filename.pdf\\\"", "someuser"])

(The problem is that python deals with one level of escaping, and the sh -c invoked from su with the next layer... This results in quite an ugly command...) (different quotes might slightly reduce that...)
Using r"" can get rid of the python level escape processing: (needing only the shell level escapes) (Using triple quotes to allow quotes in the string)
subprocess.call(["su","-c",r"""lftp -c \"open -u user,password ftp://127.0.0.1; get ivan\'s\ filename.pdf\"""", "someuser"])

Adding a space allows for stripping the shell escapes, since lftp doesn't seem to need the filename escaped for the spaces and single quote.
subprocess.call(["su","-c",r"""lftp -c "open -u user,password ftp://127.0.0.1; get ivan's filename.pdf" """, "someuser"])

This results in the eventual lftp ARGV being
["lftp","-c","open -u user,password ftp://127.0.0.1; get ivan's filename.pdf"]

For curl instead (it still ends up bad due to the su being involved):
subprocess.call(["su","-c",r"""curl "ftp://user:password@127.0.0.1/ivan's filename.pdf" """, "someuser"])

A: Using subprocess.call() is the best and more secure way to perform this task.
Here's an example from the documentation page:
subprocess.call(["ls", "-l"]) # As you can see we have here the command and a parameter

About the error I think it is something related to the spaces and the ' charachter.
Try using string literals (pay attention to the r before the string, also be sure that the command is 100% matching the one you use in BASH):
r"My ' complex & string"

So, in your case:
command = subprocess.Popen(["su", "-c", r"lftp -c 'open -u user,password ftp://127.0.0.1; get ivan's filename.pdf'", "someuser"])


text:
Q: How to tell sphinx to ignore the 'include' directive when building documentation? I run sphinx-build command from the command line to build both latex and html documentation, since they have the same source .rst files:
$ sphinx-build -b html <source> <output>
$ sphinx-build -b latex <source> <output>
However, for the latex output I want to ignore all the "include" directives.
This can be done by adding a docutils.conf file in the same directory as the conf.py of sphinx with the following content:
[parsers]
[restructuredtext parser]
file-insertion-enabled:false

This is a partial solution though, since I have to change the content (false or true) of the docutils.conf file every time I run the sphinx-build for both html and latex outputs.
It is possible to tell sphinx to ignore the 'include' directive without relying on docutils.conf file, specifying that I want no-file-insertion when running the sphinx-build command?

A: After some time searching, I found a sphinx directive that include its content only when a expression is true (the only directive):
.. only:: html

    .. include:: <path/to/file.rst>

This was a simple solution that works fine for me; the contents of file.rst are only included when making html documentation and not when making latex files.
Thanks!


text:
Q: How to check when network is not available on android device? I use android device
and I want when app start, check current network state.
so, I try this.
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERIVCE);
NetworkInfo ethernet = manager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
NetworkInfo wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (wifi.isConnected()) {
   Log.d(TAG, "WIFI isConnected");
} else if (ethernet.isConnected()) {
   Log.d(TAG, "Ethernet isConnected");
} else if (wifi.isAvaiable()) {
   Log.d(TAG, "Wifi not connect, but wifi isAvailable");
} else {
   Log.d(TAG, "not available network");
}

this source check Wi-Fi and Ethernet network state.
but when unable network. not check.
My device if use wifi, connect Wireless LAN on my device.
when disconnect Wireless Lan on my device. my source is Check wifi.isAvailable()
in conclusion,

*

*How to check when network is not available (current source, when network is not available check wifi.isAvailable)

*When connect Wireless Lan and Wifi off, check wifi.isAvailable() but When disconnect Wireless Lan and Wifi off , check wifi.isAvailable()
How to distinguish from this situation.
THANKS.

A: you should use getActiveNetworkInfo() to check connectivity of currently active default data network--no need to check for particular data network; be it Ethernet or Wi-Fi.
  public static boolean NetAvailable(final Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    final boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    return isConnected;
   }

A: Try this function
public boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

and check like this
if(isNetworkAvailable(this))
{
System.out.println(""Internet Connected);
}else
{
System.out.println(""Internet Not Connected);
}

A: public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(
                Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

A: For knowing working internet state use this snippet
public static boolean isInternetAccess() {
    try {
        HttpURLConnection urlc = (HttpURLConnection)
            (new URL("http://www.google.com")
            .openConnection());
        urlc.setRequestProperty("User-Agent", "Android");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1500);
        urlc.connect();
        return (urlc.getResponseCode() == 200);
    } catch (IOException e) {
        Log.e(TAG, "Error checking internet connection", e);
    }

return false;

}
If this code returns failed result that means network is not available,and call your code for getting available networks.

A: you need to use BroadcastReceiver for check connectivity. when status change it call onReceive() method.
public BroadcastReceiver internetConnectionReciever = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        @SuppressWarnings("static-access")
        NetworkInfo activeWIFIInfo = connectivityManager
                .getNetworkInfo(connectivityManager.TYPE_WIFI);

        if (activeWIFIInfo.isConnected() || activeNetInfo.isConnected()) {

        }
    }
};

Register Receiver in onResume() and destroy it in onDestroy()
 @Override
protected void onResume() {
    super.onResume();
    registerReceiver(internetConnectionReciever, new IntentFilter(
            "android.net.conn.CONNECTIVITY_CHANGE"));

}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(internetConnectionReciever);
}

A:    public static boolean checkInternetConnection(Context context) {
        try {
            ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            android.net.NetworkInfo ethernet = connec.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);

            if ((wifi != null && wifi.isConnected())
                    || (mobile != null && mobile.isConnected())
                    || (ethernet != null && ethernet.isConnected())) {
                return true;
            }
            log("Connection", "Connection failed");
            return false;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return false;
        }
    }
Use this method. you don't need to check wifi.isAvailable(), just check isConnected()

A: Try this for checking device online or offline.
private boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnectedOrConnecting()){
        return true;
    }else return false;
}


text:
Q: How can I shutdown ReactiveMongo 0.11.14 without a bunch of dead letter messages? I'm using ReactiveMongo 0.11.14 with Play 2.5.8.  When I try to shut down reactivemongo, I get a bunch of akka messages about dead letters.  The lost messages all seem to relate directly to closing down. (They are all of class ChannelClosed or ChannelDisconnected.)
How do I properly shut down reactivemongo to avoid these annoying messages?
Here's the way I'm trying to do it now:
for (connection <- reactiveMongoApi.driver.connections) {
  //close them sequentially just to be extra safe
  Await.ready(connection.askClose()(5.seconds), 5.seconds)
}
reactiveMongoApi.driver.close(5.seconds)

Here's two examples of the dead-letter messages I get:

[INFO] [10/06/2016 15:14:07.387] [reactivemongo-akka.actor.default-dispatcher-7] [akka://reactivemongo/user/Connection-2] Message [reactivemongo.core.actors.ChannelClosed] from Actor[akka://reactivemongo/deadLetters] to Actor[akka://reactivemongo/user/Connection-2#1711870153] was not delivered. [9] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
[INFO] [10/06/2016 15:14:07.387] [reactivemongo-akka.actor.default-dispatcher-7] [akka://reactivemongo/user/Connection-2] Message [reactivemongo.core.actors.ChannelDisconnected] from Actor[akka://reactivemongo/deadLetters] to Actor[akka://reactivemongo/user/Connection-2#1711870153] was not delivered. [10] dead letters encountered, no more dead letters will be logged. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.

I've tried closing the connections after the driver, skipping connection close() altogether, and initiating a shutdown via driver.system.terminate() instead of driver.close().


text:
Q: For PHP is there a significant difference in memory usage if creating new array or adding same indexes to existing array? If I am creating an array with several hundred indexes, how much overhead is required for the additional array versus adding a second dimension to an existing array?
I.E. $pages['page']['url'] and $titles['page']['title'] versus $pages['page']['url']['title'] versus $pages['page']['title'], where the last example assumes each index of $pages contains an associative array.
The goal is to be able to be to lookup two attributes of each 'page'. Each 'page' has a 'url' and a 'title', which would be more efficient for memory usage on the arrays? Which for access/storing the data?
Two associative arrays:
// Store the information in arrays
$titles['page1'] = 'Page 1 Title';
$titles['page2'] = 'Page 2 Title';

$urls['page1'] = 'http://www.page1.com';
$urls['page2'] = 'http://www.page2.com';

// Display an example
echo $titles['page1'] . ' is at ' . $urls['page1'];

or one array of arrays:
$pages['page1'] = array( 'title' => 'Page 1 Title', 'url' => 'http://www.page1.com' );
$pages['page2'] = array( 'title' => 'Page 2 Title', 'url' => 'http://www.page2.com' );

// Display an example
echo $pages['page1']['title'] . ' is at ' . $pages['page1']['url'];

A: The memory usage of a two dimensional array is slightly bigger, but this may result from bad code (?).

<?php

function genRandomString() {
    $length = 10;
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $string = '';

    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $string;
}

$i = 0;

// ----- Larger 1D array -----
$mem_start = memory_get_usage();
echo "initial1: " . $mem_start . "
";
$arr = array();

for ($i = 1; $i <= 1000; $i++) {
    $arr[ genRandomString() ] = "Hello world!";
}

echo "array1: " . (memory_get_usage() - $mem_start) . "
";
unset($arr);

// ----- 2D array -----
$mem_start = memory_get_usage();
$arr2 = array();

echo "initial2: " . $mem_start . "
";

for ($i = 1; $i <= 500; $i++) {
    $arr2["key______1"][ genRandomString() ] = "Hello world!";
    $arr2["key______2"][ genRandomString() ] = "Hello world!";
}

echo "array2: " . (memory_get_usage() - $mem_start) . "
";

unset($arr2);

unset($i);
unset($mem_start)
echo "final: " . memory_get_usage() . "
";

?>

A: One array consume less memory than two:
 total mem two arrays: 2496
 total mem one array: 1848

I do calculations assign 'aaaa' to each element in one and two arrays, capturing memory_get_usage().
EDIT:
CORRECTION: If one of these is one level array, is better two arrays than one.
Added the code. I moddifie it to put more elements to the array and do one array with only one level:

total mem two arrays: 1,009,720
total mem one array: 1,011,112
$memI = memory_get_usage();

for ($i = 0; $i < 1000; $i++)
{
     $pages[uniqid()][uniqid()] = 'aaaa';
     $titles[uniqid()] = 'aaaa';
}

$memF = memory_get_usage();

$memCalc = $memF - $memI;

echo "
total mem two arrays: " . number_format($memCalc);

unset($pages);
unset($titles);

$memI = memory_get_usage();

for ($i = 0; $i < 1000; $i++)
{
    $pages['page'][uniqid()][uniqid()]  = 'aaaa';
    $pages['title'][uniqid()] = 'aaaa';
}

$memF = memory_get_usage();

$memCalc = $memF - $memI;

echo "
total mem one array: " . number_format($memCalc);

A: I don't think that the difference in multi-dimensional array's vs several arrays would be large enough to focus on it for memory usage, strings and int's however are quite different in memory.
Applying conventions to coding would use less ram.
Using this example:
$pages['page1'] = array( 'title' => 'Page 1 Title', 'url' => 'http://www.page1.com' );
$pages['page2'] = array( 'title' => 'Page 2 Title', 'url' => 'http://www.page2.com' );

// Display an example
echo $pages['page1']['title'] . ' is at ' . $pages['page1']['url'];

You could re-write it:
$pages[] = array('Page 1 Title','www.page1.com' );
$pages[] = array('Page 2 Title','www.page2.com' );

// Display an example
foreach ($pages as $page){
   echo $page[0] . ' is at http://' . $page[1];
}

You could also use Definitions for keys for the self-documenting code idea:
define("TITLE_KEY", 0);
define("URL_KEY", 1);
$pages[] = array(TITLE_KEY=>'Page 1 Title',URL_KEY=>'www.page1.com' );
$pages[] = array(TITLE_KEY=>'Page 2 Title',URL_KEY=>'www.page2.com' );

// Display an example
foreach ($pages as $page){
   echo $page[TITLE_KEY] . ' is at http://' . $page[URL_KEY];
}

A: PHP don't has really array. PHP technically has a map, or sometimes called associatyve array. Map speed depends on number of elements, and memory usage doesn't matter on time when you add elements.


text:
Q: Ethernet connection slightly handicapped compared to Wi-Fi I'm using an Arris TG862 router and noticed that computers connected to the internet via an ethernet cable suffer some problems when browsing that don't happen when connected through the Wi-Fi.
The cases that I was able to reproduce were:

*

*Upload on Imgur.com or Imageshack.com almost always fails

*Upload on Gfycat and other webm hosting sites almost always fails too

*Windows update always fails with error 0x8024401C

It's worth noting that those problems go away when the connection is made through a wireless adapter (even on the same computer).
What could be the cause of this behavior?
Here are some screenshots from the router's configuration page (I can provide more if it's needed to reach a solution):
http://imgur.com/a/IOHTn


text:
Q: How to use nltk.Text findall() API to determine success and failure in client logic I can use the findall() API without and issue. Below is the simple case
import nltk

raw = "Management Discussion and Analysis"
raw = raw.lower()
tokens = nltk.word_tokenize(raw)
text = nltk.Text(tokens)
text.findall(r"<.*> <.*> <.*> <analysis>")

Output
management discussion and analysis

Now if I change the raw variable so that findall does not find anything.
import nltk

raw = "Management Discussion and Analysisss"
raw = raw.lower()
tokens = nltk.word_tokenize(raw)
text = nltk.Text(tokens)
text.findall(r"<.*> <.*> <.*> <analysis>")

Output

So the question is how to distinguish at the caller side between success and failure?.
I also checked and debugged the library code and the implementation is to just print the content and return nothing. I found it little strange but do not know why API does not return anything.
hits = self._token_searcher.findall(regexp)
hits = [" ".join(h) for h in hits]
print(tokenwrap(hits, "; "))

Kindly advise.

A: With further working on this, I was able to think/implement a logic which worked for my requirement. I posted the answer so that somebody else can refer it in future.
def nltk_text_findall_object(nltkText, regexp):
    outList      = []
    finalOutList = []

    # now assign stdout handle with some text file so that
    # nltk findall() API output/print could be redirected.
    tempFileName = "tempFile.txt"
    orig_out = sys.stdout
    sys.stdout = open(tempFileName, "w")

    nltkText.findall(regexp)
    # now restore the stdout handle with original value.
    sys.stdout.close()
    sys.stdout = orig_out

    # Now check for the content in the file and return the list.
    file = open(tempFileName,"r")
    raw = file.read()
    file.close()
    # nltk findall() API returns the list of strings separated
    # by ; as per their current implementation.
    outList = raw.split(";")
    outList = [str(item).strip() for item in outList]
    for item in outList:
        if(len(item) > 1):
            finalOutList.append(item)

    # now we are done with the file, let's us delete it.
    os.remove(tempFileName)
    return finalOutList

Client Logic To Use Above Method
raw = "Management Discussion and Analysis"
raw = raw.lower()
tokens = nltk.word_tokenize(raw)
regex  = r"<.*> <.*> <.*> <analysis>"
outList = nltk_text_findall_object(text, regex)
if(len(outList) == 0):
    print("Did Not Found")
else:
    print("Found")

Kindly somebody let me know in case there is better way to achieve/implement use case posted in my question.


text:
Q: Changed Mac homefolder name, Docker doesn't start I have renamed my home folder name (let's say from userA to userB) and Docker stopped working.
The error is:
Cannot create/resize "/Users/userA/Library/Containers/com.docker.docker/Data/com.dockser.driver.amd64-linux/Docker.qcow2":exit status 1"
Notice that the path it shows is to the old folder name, userA. I have uninstalled and reinstalled Docker CE from the docker store (https://store.docker.com/editions/community/docker-ce-desktop-mac) but still have the same error.
Why is it still using the old folder even after I uninstalled?

A: You need a clean setup.
WARNING: the below procedure will delete all of your containers and images❗
Try to delete following folders: some of them may require sudo privileges.
~/.docker
~/Library/Containers/com.docker.docker
~/Library/Group\ Containers/group.com.docker
~/Library/Caches/com.docker.docker
~/Library/PrivilegedHelperTools/com.docker.vmnetd
~/Library/Preferences/com.docker.docker.plist

A: I know this is old and would prefer not to rez it, but this answer came up when searching Google and I found a better solution that doesn't require you do delete anything - which I felt would be useful for anyone who comes across this question.
Assuming the old name is UserA, and the new is UserB

*

*Create a new UserA directory in /Users/, then all the directories in the "missing" file path. IE: Library/Containers/com.docker.docker/Data/com.dockser.driver.amd64-linux/

*Move Docker.qcow2 from UserB/Library/Containers/com.docker.docker/Data/com.dockser.driver.amd64-linux/ to the directory created in step 1.

*Start Docker

*Open Docker preferences -> Go to the Disk menu

*Select "Move Disk Image" and pick the new location to move that docker file into. IE: you'll want to move it to UserB/Library/Containers/com.docker.docker/Data/com.dockser.driver.amd64-linux/


text:
Q: Integrate this abstract integral I want to integrate(in this case: find an antiderivatie) $\int f(\sqrt{c^2+x^2})x\, dx$, where $f \in C$ and $F'=f$ for some $F' \in C^1$ and $c \in \mathbb{R}$.
It seems to me as if I'm missing the trick for this integral. Does anybody here have an idea?

A: If you know a primitive (an antiderivative) $G$ of $F$, it is relatively easy by substituting $u = \sqrt{c^2+x^2}$. Then
$$\begin{align}
\int f(\sqrt{c^2+x^2})x\,dx &= \int\sqrt{c^2+x^2}\cdot f(\sqrt{c^2+x^2}) \frac{x}{\sqrt{c^2+x^2}}\,dx\\
&= \int u\cdot f(u)\,du\\
&= u\cdot F(u) - \int F(u)\,du\\
&= u\cdot F(u) - G(u)\\
&= \sqrt{c^2+x^2}\cdot F(\sqrt{c^2+x^2}) - G(\sqrt{c^2+x^2}).
\end{align}$$

A: Let  $F(x)$  is   the antiderivative   for $f(\sqrt{x}).$  Change  the  variable $t=x^2+c^2,  dt=2 x dx.$ Then
$$
\int f(\sqrt{x^2+c^2})x dx=\int f(\sqrt{t})  \frac 12 dt= \frac 12 F(t)= \frac{1}{2}F(\sqrt{x^2+c^2})+C.
$$


text:
Q: Android Media Player back button null pointer crash I have the rest of my app running amazingly well until it comes to the back button being pressed to stop and exit the program.  I didn't know if its this part of the line of code or where but here is the DDMS logcat and below is the back button coding.  Any help would be greatly appreciated.
05-03 18:32:35.597: W/KeyCharacterMap(475): No keyboard for id 0
05-03 18:32:35.597: W/KeyCharacterMap(475): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
05-03 18:32:35.667: D/AndroidRuntime(475): Shutting down VM
05-03 18:32:35.677: W/dalvikvm(475): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
05-03 18:32:35.736: E/AndroidRuntime(475): FATAL EXCEPTION: main
05-03 18:32:35.736: E/AndroidRuntime(475): java.lang.NullPointerException
05-03 18:32:35.736: E/AndroidRuntime(475):  at com.mrj05hua.skylanders.SkylandersSoundboardActivity.onBackPressed(SkylandersSoundboardActivity.java:344)
05-03 18:32:35.736: E/AndroidRuntime(475):  at android.app.Activity.onKeyUp(Activity.java:1888)
05-03 18:32:35.736: E/AndroidRuntime(475):  at android.view.KeyEvent.dispatch(KeyEvent.java:1061)
05-03 18:32:35.736: E/AndroidRuntime(475):  at android.app.Activity.dispatchKeyEvent(Activity.java:2068)
05-03 18:32:35.736: E/AndroidRuntime(475):  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1643)
05-03 18:32:35.736: E/AndroidRuntime(475):  at android.view.ViewRoot.deliverKeyEventToViewHierarchy(ViewRoot.java:2471)
05-03 18:32:35.736: E/AndroidRuntime(475):  at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2441)
05-03 18:32:35.736: E/AndroidRuntime(475):  at android.view.ViewRoot.handleMessage(ViewRoot.java:1735)
05-03 18:32:35.736: E/AndroidRuntime(475):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-03 18:32:35.736: E/AndroidRuntime(475):  at android.os.Looper.loop(Looper.java:123)
05-03 18:32:35.736: E/AndroidRuntime(475):  at android.app.ActivityThread.main(ActivityThread.java:4627)
05-03 18:32:35.736: E/AndroidRuntime(475):  at java.lang.reflect.Method.invokeNative(Native Method)
05-03 18:32:35.736: E/AndroidRuntime(475):  at java.lang.reflect.Method.invoke(Method.java:521)
05-03 18:32:35.736: E/AndroidRuntime(475):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-03 18:32:35.736: E/AndroidRuntime(475):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-03 18:32:35.736: E/AndroidRuntime(475):  at dalvik.system.NativeStart.main(Native Method)
05-03 18:32:39.327: I/Process(475): Sending signal. PID: 475 SIG: 9
05-03 18:36:59.016: D/dalvikvm(484): GC_EXTERNAL_ALLOC freed 873 objects / 61256 bytes in 96ms
05-03 18:36:59.316: D/dalvikvm(484): GC_EXTERNAL_ALLOC freed 276 objects / 13632 bytes in 70ms
05-03 18:36:59.626: D/dalvikvm(484): GC_EXTERNAL_ALLOC freed 139 objects / 7040 bytes in 82ms
05-03 18:36:59.936: D/dalvikvm(484): GC_EXTERNAL_ALLOC freed 88 objects / 4552 bytes in 78ms
05-03 18:37:00.416: D/dalvikvm(484): GC_EXTERNAL_ALLOC freed 96 objects / 5184 bytes in 92ms
05-03 18:37:00.826: D/dalvikvm(484): GC_EXTERNAL_ALLOC freed 101 objects / 5520 bytes in 90ms
05-03 18:37:35.257: W/KeyCharacterMap(484): No keyboard for id 0
05-03 18:37:35.257: W/KeyCharacterMap(484): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
05-03 18:37:35.336: D/AndroidRuntime(484): Shutting down VM
05-03 18:37:35.349: W/dalvikvm(484): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
05-03 18:37:35.427: E/AndroidRuntime(484): FATAL EXCEPTION: main
05-03 18:37:35.427: E/AndroidRuntime(484): java.lang.NullPointerException
05-03 18:37:35.427: E/AndroidRuntime(484):  at com.mrj05hua.skylanders.SkylandersSoundboardActivity.onBackPressed(SkylandersSoundboardActivity.java:344)
05-03 18:37:35.427: E/AndroidRuntime(484):  at android.app.Activity.onKeyUp(Activity.java:1888)
05-03 18:37:35.427: E/AndroidRuntime(484):  at android.view.KeyEvent.dispatch(KeyEvent.java:1061)
05-03 18:37:35.427: E/AndroidRuntime(484):  at android.app.Activity.dispatchKeyEvent(Activity.java:2068)
05-03 18:37:35.427: E/AndroidRuntime(484):  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1643)
05-03 18:37:35.427: E/AndroidRuntime(484):  at android.view.ViewRoot.deliverKeyEventToViewHierarchy(ViewRoot.java:2471)
05-03 18:37:35.427: E/AndroidRuntime(484):  at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2441)
05-03 18:37:35.427: E/AndroidRuntime(484):  at android.view.ViewRoot.handleMessage(ViewRoot.java:1735)
05-03 18:37:35.427: E/AndroidRuntime(484):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-03 18:37:35.427: E/AndroidRuntime(484):  at android.os.Looper.loop(Looper.java:123)
05-03 18:37:35.427: E/AndroidRuntime(484):  at android.app.ActivityThread.main(ActivityThread.java:4627)
05-03 18:37:35.427: E/AndroidRuntime(484):  at java.lang.reflect.Method.invokeNative(Native Method)
05-03 18:37:35.427: E/AndroidRuntime(484):  at java.lang.reflect.Method.invoke(Method.java:521)
05-03 18:37:35.427: E/AndroidRuntime(484):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-03 18:37:35.427: E/AndroidRuntime(484):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-03 18:37:35.427: E/AndroidRuntime(484):  at dalvik.system.NativeStart.main(Native Method)

--
       @Override
  public void onBackPressed(){
     //Handles back button to close MediaPlayer
        if (player.isPlaying()) {
            super.finish();
        }
        else if (player.isPlaying())
              player.stop();
          player.release();
          super.finish();
  }

A: Well, for one you have a redundant if statement
if (player.isPlaying())
...
else if (player.isPlaying())
...

You are checking the same thing in both of these statements
Next, the reason you are getting the null pointer is because player likely is null when you are trying to access it
Make sure you check to see if player is null before accessing it
@Override
public void onBackPressed(){
  if (player != null){
      if(player.isPlaying())
          player.stop();

      player.release();
  }

  //there is no reason to call super.finish(); here
  //call super.onBackPressed(); and it will finish that activity for you
  super.onBackPressed();
}


text:
Q: Get selected text, replace it, etc. using jQuery for a simple editor I am creating a small HTML editor using jQuery. I have created my own button-icons for:

*

*bold

*italics

*underline

*insert hyperlink

*insert image

*unordered list

*ordered list

But I donot know how to get it working. My idea:

*

*bold: when user clicks on this button, selected text in the editor box() should be replaced with  ..selected_text.. . Otherwise, insert  at cursor position.

*italic: when user clicks on this button, selected text in the editor box() should be replaced with  ..selected_text.. . Otherwise, insert  at cursor position.

*same as above for Underline

*etc....
So my question is, how to get the selected text from TEXTAREA and how to replace it with the tags? And also, how to insert a text at cursor position (ie. at that blinking line) ?
This is same as the buttons present in Stackoverflow's editor, when you post some questions. (for example, try clicking on the BOLD button in Stackoverflow's editor, when you have selected a text and when not selected)

A: I strongly recommend using a JavaScript library which smooths out the cross-browser differences when working with ranges and selections: Rangy.

A cross-browser JavaScript range and selection library. It provides a simple standards-based API for performing common DOM Range and Selection tasks in all major browsers, abstracting away the wildly different implementations of this functionality between Internet Explorer and DOM-compliant browsers.
For manipulating selections in <textarea> and <input type="text"> elements, see see Rangy's poorly-named and svelter twin project, Rangyinputs.

How to get the selected text from TEXTAREA and how to replace it with the tags?

Check out the Rangy CSS Class Applier Module (and associated demo page).


text:
Q: error of sql query in MS Access database I need to do a sql query in MS Access.
But I got error in MS Access:
SELECT *
FROM
(
   SELECT *
   FROM table1
   where not exists
   (
     SELECT *
     FROM table2
     where table2.id = table1.id
   ) as t
 )  as t1, table3
 where  table3.id = t1.id

Syntax error: (missing operator) in query expression 'not exists ( ... ) as t'
Any help would be appreciated.

A: The not exists subselect does not require an alias.  Note that I've removed the as t
SELECT *
FROM
(
   SELECT *
   FROM table1
   where not exists
   (
     SELECT *
     FROM table2
     where table2.id = table1.id
   )
 )  as t1, table3
 where  table3.id = t1.id

You might also consider using an inner join and a left join to get rid of your not exists:
This should be exactly equivalent of the above:
SELECT t1.*, t3.*
FROM
  table1 t1
  inner join table3 t3 on t1.id = t3.id
  left join table2 t2 on t1.id = t2.id
where
  t2.id is null


text:
Q: Getting large number of small files (images) from FTP using python I have a following problem to solve:
Camera takes a picture roughly three times a second and saves it on a FTP server. I would like to access the FTP server using python, download images and do some further processing using OpenCV. It wouldn't be a challenge if the system could work offline, but I would like to achieve online processing i.e. I want to download files with such rate to be able to do live processing (or at least live preview for start).
Currently downloading one file takes about one second or more. Files are small (50 kB) and I guess that the issue here is the overhead caused by downloading files one by one. Is there a way to download e.g. 10 or 100 files from FTP at once? This would introduce some delay to my processing, but hopefully I could get much better fluency. Is there maybe other solution to my problem?
The code I have so far:
from ftplib import FTP
from StringIO import StringIO
import numpy as np
import cv2

ftp = FTP("ftp.name")
ftp.login("login", "passwd")
ftp.cwd("camera")
#Getting listing
ls = []
ftp.retrlines('MLSD', ls.append)

for entry in ls:
    prop = entry.split(";")

    #Skip if directory
    if prop[0].split("=")[1] == "dir":
        continue

    #Getting file
    r = StringIO()
    ftp.retrbinary('RETR' + filename, r.write) #filename starts with space character

    nparr = np.fromstring(r.getvalue(), np.uint8)
    img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

    cv2.imshow("image", img_np)
    cv2.waitKey(1)


text:
Q: Query-first approach for MongoDB? I'm beginning to design a brand new MongoDB database for a project that will surely have a lot of concurrent access.
I'm choosing MongoDB for I know how scalable it is and how fast my queries will be.
I know, however, that even using MongoDB, for the sake of performance, I should try to hit the database as few times as possible.
I know that Apache Cassandra, another NoSQL database, advocates the "query-first" approach, which means you should think of your queries first, and then organize your data structures according to them.
Now, I'm wondering if the same principle applies to MongoDB.
I didn't find any related discussion about this on the web so far.

A: For organizing and modeling your data in Mongo, the word you want to learn and search on is denormalization. I would definitely think of your queries first when working with Mongo. Not just for modeling, but for indexing as well.
A good rule I heard at a Mongo conference for how to denormalize:

*

*If the data is fairly static, go ahead and denormalize/embed the data in a document.

*If the data changes quite often, make a reference to another document.

I've seen this to be very true after a year of production Mongo work. Embedding data that changes often has caused us a lot of pain.

A: Query first is important while working with MongoDB as you just can't store all your data "as is" and just create arbitrary queries and joins across tables (collections) latter. MonogDB is a document oriented database, ie. you always work with documents instead of result sets from different tables.
Good news is that MongoDB is schema less. You can structure your documents as you like and even change the schema of your documents over time as needed. But what you do need to think about beforehand is how (using what kind of key and index) and when (remember, you can't do joins!) you're going to retrieve them.
As ryan1234 suggested, denormalization is an option to deal with this. However, this can lead to redundant data and can become hard to maintain over time. So you probably don't want denormalize just everything. You need to be pragmatically address those short comings in your application code. Heres some suggestions for that:

*

*Prefetch frequently used data, such as lookup tables, as long as memory footprint is acceptable.

*Decide about what data needs to be available really fast on demand, e.g. by request on a web interface. Ideally you'll just have a single key that can be queried using an index which will serve you all data needed for a single request.

*Decide about what data can be handled in the background using long running jobs such as map reduce or queues. Or even have custom cronjob scheduled jobs that will do something with your data, e.g. preparing reports that you can retrieve later using an index.

*Do multiple requests and join data in your client. E.g. if you have a web client you can do several subsequent requests for pulling your data, which you probably would have done in a single request using a RDBMS. Queries in MongoDB are really fast if indexed, theres nothing wrong doing many requests per se as long you don't synchronize multiple queries and join data on the server. Doing this on the client allows you to leverage the whole stack (load balancer, caches,..) while progressively building the UI


text:
Q: Android OpenCV: AddWeighted function implementation in C++ I am using OpenCV4Android. I know it OpenCV functions are available in android via Java wrappers. Now i have an issue with function "addWeighted". I want to access its C++ code so that i can make a change in it and get my desired results. Can any one tell me where is its C++ code. I did lot of search/google but did not get function implementation in C++.

A: if you just needs to know where is the source code.
I check my opencv(2.4.5 for PC) and find it here: \modules\core\src\arithm.cpp.
void cv::addWeighted( InputArray src1, double alpha, InputArray src2,
                          double beta, double gamma, OutputArray dst, int dtype )
    {
        double scalars[] = {alpha, beta, gamma};
        arithm_op(src1, src2, dst, noArray(), dtype, addWeightedTab, true, scalars);
    }

compile opencv yourself and add the path to source directories. then you can check the code easily in your IDE and even debug inside opencv codes.
opencv source codes(cpp) wrapped to android java code through jni, I don't think it worth modifying the opencv source codes and compile a opencv_java.so yourself. Instead, you can just past the Mat through jni and write your own addWeighted() function in cpp.


text:
Q: How to display local notification when the app is not in the recent history of the device using Xamarin Crossplatform I want to display local notification when the app is closed and also app is not in the recent history of the device.How can I do this.
Please help me..
Here is my code MainPage.cs
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        var startTimeSpan = TimeSpan.Zero;
        var periodTimeSpan = TimeSpan.FromMinutes(5);

        Device.StartTimer(TimeSpan.FromSeconds(5), () =>
        {
            GetData();

            return true;
        });
    }

    public void GetData()
    {
        IAlarmReceiver _local = DependencyService.Get<IAlarmReceiver>();
        _local.LocalNotifications("Xamarin", "Hello world");
    }

    private void btn_Click_Clicked(object sender, EventArgs e)
    {
        GetData();
    }
}

Here I call the notification method in every 5 seconds.
Here is my AlarmReciever.CS
    public void GetNotification(string Title, string Text)
    {
        Intent _intent = new Intent(Application.Context, typeof(MainActivity));
        const int _pendingIntentId = 0;
        PendingIntent _pintent = PendingIntent.GetActivity(Application.Context, _pendingIntentId, _intent, PendingIntentFlags.CancelCurrent);

        Notification.Builder builder = new Notification.Builder(Application.Context)
       .SetContentIntent(_pintent)
       .SetContentTitle(Title)
       .SetContentText(Text)
       .SetDefaults(NotificationDefaults.Sound)
       .SetAutoCancel(true)
       .SetSmallIcon(Resource.Drawable.icon);

        Notification _notification = builder.Build();
        NotificationManager _notificationmanager = Android.App.Application.Context.GetSystemService(Context.NotificationService)
            as NotificationManager;

        _notificationmanager.Notify(0, _notification);

A: you can use  ACR Notifications Plugin for Xamarin this will display the local notification when app is closed.
Example await CrossNotifications.Current.Send("Happy Birthday", "I sent this a long time ago", when = TimeSpan.FromDays(50));

A: If you tested your program using the debugger the notification will be terminated with the rest of your application as soon as you close it.
I tested your code (assuming _local.LocalNotifications should be _local.GetNotification) and it worked, when the app is started on the device without the debugger.
EDIT
To display the notification all x minutes, use a ScheduledJob
Add a StartJob Method to your IAlarmReceiver inteface and its implementation
public void StartJob()
{
  var builder = new JobInfo.Builder(1234, new ComponentName(Android.App.Application.Context, Java.Lang.Class.FromType(typeof(ScheduledJob))));
  builder.SetPeriodic(15L * 60L * 1000L); // <- change the intervall

  var jobInfo = builder.Build();
  var jobScheduler = (JobScheduler)Android.App.Application.Context.GetSystemService(Context.JobSchedulerService);
  jobScheduler.Schedule(jobInfo);
}

This method starts the ScheduledJob (defined in the android project)
[Service(Exported = true, Permission = "android.permission.BIND_JOB_SERVICE")]
public class ScheduledJob : JobService
{
    public override bool OnStartJob(JobParameters @params)
    {
        new AlarmReceiver().GetNotification("Hello World!", "Xamarin");
        return false;
    }

    public override bool OnStopJob(JobParameters @params)
    {
        return false;
    }
}

Replace
Device.StartTimer(TimeSpan.FromSeconds(5), () =>
    {
        GetData();

        return true;
    });

with
DependencyService.Get<IAlarmReceiver>().StartJob();


text:
Q: How do I show that some eigenvalues of two square matrices of different dimensions are the same? I have three matrices in a field $F$:
$X \in F^{a,a}, Y \in F^{b,b}, Z \in F^{a,b}$, where $a,b \in \mathbb{N}, a \geq b$ and $\text{rank}(Z) = b$. The following term describes their relation:
$X \cdot Z = Z \cdot Y$
I want to show that all eigenvalues of $Y$ are eigenvalues of $X$.

A: Note: Not all of the determinants you wrote down are well-defined, since $XZ$ and $ZY$ are not quadratic if $a \neq b$.
Also, as stated, this does not seem quite correct. Set $a = 2, b = 1$ and
$$X = \begin{pmatrix} 1 & 0 \\ 0 & 2 \end{pmatrix}, \quad
Y = (1), \quad
Z = \begin{pmatrix} 1 \\ 0 \end{pmatrix},$$
then $a \geq b$, the rank of $Z$ is equal to $b = 1$, and
$$XZ = \begin{pmatrix} 1 \\ 0 \end{pmatrix} = ZY.$$
Then $X$ has the eigenvalues 1 and 2, but $Y$ has the eigenvalue 1. Note that you can replace the 2 in $X$ with any other value.

Generally, with problems like these it's a good idea to start by comparing if you can somehow make eigenvectors of one of the matrices into an eigenvector of the other one, and here this gives us some insight, as well.
If $x \neq 0$ is an eigenvector of $Y$ to the value $\lambda$, then
$$\lambda Zx = Z(\lambda x) = Z Yx = XZx,$$
hence, if $Zx \neq 0$, then it is an eigenvector of $X$ to the value $\lambda$. But the full rank condition on $Z$ and $a \geq b$ means that its kernel is empty, so if $x \neq 0$ then also $Zx \neq 0$. So every eigenvalue of $Y$ is an eigenvalue of $X$.
But, looking at the counterexample above, that's all that you can show from the given requirements. X might have a bunch of other eigenvalues that you do not know anything about from the given data.


text:
Q: Saving generated images on IIS virtual directory? I need to create web API that generate some images and return their paths.
I create the path to save using:
var resultPath = "Images/" + obiektId.ToString() + ".png";
var fullPath = HttpContext.Current.Server.MapPath("/" + resultPath);

and return resultPath.
The problem is, that the virtual directory where I keep my site is C:\\sites\siteA and HttpContext.Current.Server.MapPath("/" + resultPath) returns C:\\inetpub\wwwroot\Images\123456.png. Then it is impossible for me to load the image from 10.0.0.106/siteA/Images/123456.png.
How can I save my image in my base virtual directory instead of saving it in wwwroot directory?

A: string resultPath = obiektId.ToString() + ".png";
string fullPath  = System.Web.HttpContext.Current.Server.MapPath("~/Images"+ resultPath );


text:
Q: Can we define the dual of a set? In the wikipedia page of the category of sets, I see that this category is monoidal, and the tensor product of two sest is just the cartesian product.
My question is : can we define a "dual" of a set ?
Thanks for help

A: The notion of dual can be defined in any monoidal category, yes, and the unit is always dualizable, but it turns out that for the category of sets the unit object $1$ is the only dualizable object. More generally, if $\mathcal{C}$ is a cartesian closed category and $X \in \mathcal{C}$ is dualizable, then its dual must be $[X,1]$, which is just $1$, so that $X=1$ as well.


text:
Q: Write CreateDIBSection BMP Data to File I have taken a screenshot programtically and I want to write out the BGRA to file. The BGRA is held in pixelBuffer.
Here is the code I am using to write to file:
    BYTE *pixelBuffer;
    HBITMAP hbmp;
    hbmp = CreateDIBSection(hdcScreen, &bmi, DIB_RGB_COLORS, (void **)&pixelBuffer, NULL, 0);

FILE *stream;\
if (fopen_s(&stream, "C:\\Users\Vayeate\\Desktop\\blah.txt", "wb+") == 0) {
    fwrite(pixelBuffer, (screenHeight * screenWidth * 4), (size_t)(sizeof(CHAR) + 1), stream); // (screenWidth * screenHeight * 4)
    fclose(stream);
}

However this writes a bunch of gibberish that looks like:
òîîÿòîîÿ

And that repeat forever. I was hoping to get something like 255, 100, 100, 255.
Here is my full code:
#include <Windows.h>
#include <stdio.h>

int WINAPI WinMain(HINSTANCE hinst, HINSTANCE, LPSTR, int)
{
    //Sleep(1000)

    MessageBox(0, L"Hello World", L"Unipen", MB_ICONINFORMATION);

    int i = 0;
    DISPLAY_DEVICE device;

    device.cb = sizeof(device);

    while (EnumDisplayDevices(NULL, i, &device, 0) && ++i) {
        if ((device.StateFlags & DISPLAY_DEVICE_ACTIVE) != DISPLAY_DEVICE_ACTIVE) {
            MessageBox(0, device.DeviceName, L"CONTINUE", MB_ICONINFORMATION);
            continue;
        }
        MessageBox(0, device.DeviceName, L"BREAK", MB_ICONINFORMATION);
        break;
    }

    size_t screenWidth = 1920;
    size_t screenHeight = 1200;
    size_t colorLen = 4;

    HDC hdcScreen;
    hdcScreen = CreateDC(NULL, device.DeviceName, NULL, NULL);
    if (hdcScreen == (HDC)NULL) {
        MessageBox(0, L"UnableToCreateDC", L"ERROR", MB_ICONINFORMATION);
        return 0;
    }

    HDC hdcMemoryDC;
    hdcMemoryDC = CreateCompatibleDC(hdcScreen);
    if (hdcMemoryDC == (HDC)NULL) {
        DeleteDC(hdcScreen);
        MessageBox(0, L"UnableToCreateCompatibleDC", L"ERROR", MB_ICONINFORMATION);
        return 0;
    }

    BITMAPINFO bmi;
    bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmi.bmiHeader.biWidth = (LONG)screenWidth;
    bmi.bmiHeader.biHeight = (-1)*(LONG)screenHeight;
    bmi.bmiHeader.biPlanes = 1;
    bmi.bmiHeader.biBitCount = 32;
    bmi.bmiHeader.biCompression = BI_RGB;

    BYTE *pixelBuffer;
    HBITMAP hbmp;
    hbmp = CreateDIBSection(hdcScreen, &bmi, DIB_RGB_COLORS, (void **)&pixelBuffer, NULL, 0);
    if (hbmp == (HBITMAP)NULL) {
        DeleteDC(hdcScreen);
        DeleteDC(hdcMemoryDC);
        MessageBox(0, L"UnableToCreateDIBSection", L"ERROR", MB_ICONINFORMATION);
        return 0;
    }

    //HGDIOBJ rez_selected;
    HBITMAP rez_selected_bmp;
    rez_selected_bmp = (HBITMAP)SelectObject(hdcMemoryDC, hbmp);
    if (rez_selected_bmp == (HBITMAP)NULL) {
        DeleteDC(hdcScreen);
        DeleteDC(hdcMemoryDC);
        DeleteObject(hbmp);
        MessageBox(0, L"UnableToCreateDIBSection", L"ERROR", MB_ICONINFORMATION);
        return 0;
    }

    BitBlt(hdcMemoryDC, 0, 0, screenWidth, screenHeight, hdcScreen, 0, 0, SRCCOPY);

    //(void) SelectObject(hdcMemoryDC, rez_selected_bmp); // i dont do this step in nativeshot

    FILE *stream;\
    if (fopen_s(&stream, "C:\\Users\Vayeate\\Desktop\\blah.txt", "wb+") == 0) {
        fwrite("asdfasdfasdf", 1, (size_t)(sizeof(CHAR) + 1), stream); // (screenWidth * screenHeight * 4)
        fclose(stream);
    }

    DeleteDC(hdcScreen);
    DeleteDC(hdcMemoryDC);
    DeleteObject(hbmp);

    MessageBox(0, L"DONE", L"Unipen", MB_ICONINFORMATION);

    return 0;
}

How can I get space delimited BGRA data to file?

A: You're writing binary data and reading it as text. Thus, òîîÿòîîÿ is incidentally probably the correct output, as these are the characters that the binary values map to, according to the character map used by the text editor that displayed it.
If you want to have space-delimited values of the pixels in the buffer as "human-readable" ASCII written into a text file, you'll first have to use fprintf to convert these values accordingly.
Use this as an example :
if (fopen_s(&stream, "C:\\Users\Vayeate\\Desktop\\blah.txt", "w") == 0) {
    for(size_t px = 0 ; px < (screenHeight * screenWidth * 4) ; ++px) {
        fprintf(stream, "%hhu, ", pixelBuffer[px]);
    }
    fclose(stream);
}


text:
Q: Google Charts - aligning Combo Chart data maximally to left and right I have a combo chart containing area, bars and line graphs. I'd like the area and line charts to align maximally to the left and right side. For bars chart it's not required. Unfortunately I'm unable to align the graphs properly. I went through the documentation and couldn't find a solution to my problem.
Current chart:

Expected chart:

Here is the GoogleChartInterface object of the chart (I'm adding dataTable and ticks dynamically):

{
  chartType: 'ComboChart',
  dataTable: [],
  options: {
    focusTarget: 'category',
    animation: {
      startup: true,
      easing: 'out',
      duration: 500,
    },
    height: '160',
    chartArea: {
      width: '90%',
      height: '79%',
    },
    vAxes: {
      0: {
        titlePosition: 'none',
        textStyle: {
          color: '#febd02',
          bold: true,
          fontSize: 13,
        },
        format: '#',
        gridlines: {
          color: '#eaeaea',
          count: '5',
        },
        interpolateNulls: true,
      },
      1: {
        titlePosition: 'none',
        format: '#',
        gridlines: {
          color: 'transparent'
        },
        interpolateNulls: true,
      },
      2: {
        groupWidth: '100%',
        titlePosition: 'none',
        textStyle: {
          color: '#0284ff',
          bold: true,
          fontSize: 13,
        },
        format: 'decimal',
        gridlines: {
          color: 'transparent'
        },
      },
    },
    hAxis: {
      textStyle: {
        color: '#393939',
        bold: true,
        fontSize: 13,
      },
      format: 'EEEE',
      gridlines: {
        count: 0,
        color: 'transparent'
      },
      ticks: [],
    },
    series: {
      0: {
        targetAxisIndex: 0,
        type: 'area',
      },
      1: {
        type: 'line'
      },
      2: {
        targetAxisIndex: 2,
        type: 'bars',
        dataOpacity: 0.5,
      },
    },
    colors: [
      '#febd02',
      '#a5a5a5',
      '#0284ff',
    ],
    bar: {
      groupWidth: '35'
    },
    legend: {
      position: 'none'
    },
  },
};

A: in order to stretch the area and line series to the edges of the chart,
we must first use a data type that will render a continuous x-axis.
in this case, we will use date time.
next, we use option hAxis.viewWindow to control where the series start and end.
viewWindow has two properties, min & max.
the values of min & max should match the data type of the x-axis.
in this case, we set the values to the dates where the series should begin and end.
hAxis: {
  viewWindow: {
    min: new Date(2020, 10, 13),
    max: new Date(2020, 10, 19)
  }
}

this will stretch the series to the edges of the chart.
see following working snippet for an example...

google.charts.load('current', {
  packages: ['controls', 'corechart']
}).then(function() {
  var data = google.visualization.arrayToDataTable([
    ['Date', 'y0', 'y1', 'y2'],
    [new Date(2020, 10, 13), 100, 50, 25],
    [new Date(2020, 10, 14), 110, 45, 5],
    [new Date(2020, 10, 15), 90, 40, 60],
    [new Date(2020, 10, 16), 80, 30, 10],
    [new Date(2020, 10, 17), 70, 20, 0],
    [new Date(2020, 10, 18), 60, 10, 0],
    [new Date(2020, 10, 19), 50, 5, 0]
  ]);

  var chart = new google.visualization.ChartWrapper({
    chartType: 'ComboChart',
    containerId: 'chart',
    dataTable: data,
    options: {
      focusTarget: 'category',
      animation: {
        startup: true,
        easing: 'out',
        duration: 500,
      },
      chartArea: {
        left: 60,
        top: 12,
        right: 60,
        bottom: 72,
        height: '100%',
        width: '100%'
      },
      height: '100%',
      width: '100%',
      vAxes: {
        0: {
          titlePosition: 'none',
          textStyle: {
            color: '#febd02',
            bold: true,
            fontSize: 13,
          },
          format: '#',
          gridlines: {
            color: '#eaeaea',
            count: '5',
          },
          interpolateNulls: true,
        },
        1: {
          titlePosition: 'none',
          format: '#',
          gridlines: {
            color: 'transparent'
          },
          interpolateNulls: true,
        },
        2: {
          groupWidth: '100%',
          titlePosition: 'none',
          textStyle: {
            color: '#0284ff',
            bold: true,
            fontSize: 13,
          },
          format: 'decimal',
          gridlines: {
            color: 'transparent'
          },
        },
      },
      hAxis: {
        textStyle: {
          color: '#393939',
          bold: true,
          fontSize: 13,
        },
        format: 'dd MMM. yyyy',
        gridlines: {
          color: 'transparent'
        },
        ticks: data.getDistinctValues(0),
        viewWindow: data.getColumnRange(0)
      },
      series: {
        0: {
          targetAxisIndex: 0,
          type: 'area',
        },
        1: {
          type: 'line'
        },
        2: {
          targetAxisIndex: 2,
          type: 'bars',
          dataOpacity: 0.5,
        },
      },
      colors: [
        '#febd02',
        '#a5a5a5',
        '#0284ff',
      ],
      bar: {
        groupWidth: '35'
      },
      legend: {
        position: 'none'
      },
    },
  });
  chart.draw();
});
html, body {
  height: 100%;
  margin: 0px 0px 0px 0px;
  padding: 0px 0px 0px 0px;
}

#chart {
  min-height: 160px;
  height: 100%;
}


text:
Q: Fill values directly in HDF5 Im trying to enter a double value in the same hdf5 databse. It consist (for now) of 1 dataset which I extend before entering a new value. That is because I am simulating a model and want to record > 100000 entries. That works well, the extending part too, but I do not understand a part of the writing. My code for writing an entry:
double pizza[1] = {7.0};
status = H5Dwrite (dataset, H5T_NATIVE_DOUBLE, memspace, filespace,H5P_DEFAULT, pizza);

With dataset, memspace, and filespace correct variables for the corresponding argument (taken from here). But why should the last argument be a predefined list? When I try to enter 7.0 directly
    status = H5Dwrite (dataset, H5T_NATIVE_DOUBLE, memspace, filespace,H5P_DEFAULT, {7.0});

like this or this:
    status = H5Dwrite (dataset, H5T_NATIVE_DOUBLE, memspace, filespace,H5P_DEFAULT, 7.0);

it gives an error:
    error: cannot convert 'double' to 'const void*' for argument '' to 'herr_t H5Dwrite(hid_t, hid_t, hid_t, hid_t, hid_t, const void*)' = H5Dwrite (dataset, H5T_NATIVE_DOUBLE, memspace, filespace,H5P_DEFAULT, 7.0);

And in the second case:
    error: cannot convert '<brace-enclosed initializer list>' to 'const void*' for argument '6' to 'herr_t H5Dwrite(hid_t, hid_t, hid_t, hid_t, hid_t, const void*)'H5Dwrite (dataset, H5T_NATIVE_DOUBLE, memspace, filespace,H5P_DEFAULT, {7.0});

Why is a list different then a single value, even when surrounded by brackets?

A: compiler is taking the value 7.0 and by default its the nature of the compiler to convert it into double. Hence it is showing you this error.
If you need to make it work, use the base address of pizza , and type cast it into (const void *)
The brace enclosed initializer list might be coming because compiler thinks its a variable arguments list.


text:
Q: Error message"...No such file or directory" when trying to set up project to inteact with Git Using the following programs and interfaces:

*

*R-4.2.2 for Windows

*RStudio Desktop: Open Source Edition (AGPL v3)

*Git Bash

*GitHub

I am currently in the early stages of a tech program learning Data Analytics.
On my PC, working within RStudio, I've created a project that is currently not under version control. I am trying to get it set up to interact with Git.
When I type in my command (cd ~/dir/name/of/path/to/file) for it to move around and navigate to the directory containing my files, I keep getting this error message:
bash: cd: /c/Users/Administrator.STEPHHOWERTON/dir/name/of/path/to/file: No such file or directory"

I've tried creating different pathways. My original directory pathway was:
 cd: /c/Users/Administrator.STEPHHOWERTON/RStudio Projects/Temporary_add_to_version_control

Then I tried to simplify by creating a easier path like the example in my module:
c/Desktop/Temporary_add_to_version_control

No luck with either.
I went ahead to try initialize the directory to as a Git repository and also tried to add files, but of course it said the directory was empty.
Any help would be greatly appreciated.

A: It is best to switch to command line (simple CMD, no bash required), after having installed Git for Windows.
Go to the root folder of your repository (not path/to/file, but path/to/root/folder/of/repository), where your project is.
You can then create a repository
git init .
git add .
git config --global user.name "your name"
git config --global user.email "your@email.com"
git commit -m "Import project"

If you need to create a GitHub repository and push your project, you can, from that same folder, after installing GitHub CLI gh, use gh auth login (with a classic PAT, scope repo):
gh auth login --with-token < echo ghp_...

Then gh repo create:
gh repo create my-project --public --source=. --push

You can reopen RStudio from there, and check everything is working.


text:
Q: mostrar un Object[] en un JList Tengo un JFrame en el cual coloqué un JList para visualizar un arreglo, pero el arreglo que obtengo es un Object[] ya que compilo el código en matlab, pero el resultado lo proceso en java, este es mi código:
private void jButtonOpenActionPerformed(java.awt.event.ActionEvent evt) {
    // Obtiene el path del Folder con el volumen adquirido
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    fileChooser.setCurrentDirectory(new File("C:\\...\\ProjectColorCT"));

    int show_fileC = fileChooser.showOpenDialog(this);

    String pathFolder = null;
    if (show_fileC != JFileChooser.CANCEL_OPTION ){
        File folderName = fileChooser.getSelectedFile();
        pathFolder = folderName.getAbsolutePath();
        jTextPathFolder.setText(pathFolder);
    }
    // ---
    System.out.println(pathFolder);
    Object[] arrList = null;
    getNameClass nameObj = null;
    try {
        nameObj = new getNameClass();
        arrList = nameObj.getNameSlices(1, pathFolder);
        System.out.println(arrList[0]);

    } catch (MWException ex) {
        Logger.getLogger(TACframe.class.getName()).log(Level.SEVERE, null, ex);
    }
}

En el objeto llamado "arrList" obtengo toda la lista de nombres que quiero mostrar, pero no sé como mostrarla en un JList, he intentado pasar el objeto a un String[] pero no funciona.


text:
Q: Check burned Ubuntu CD My OS is Ubuntu 10.10. I have burned Ubuntu 11.04 into a CD. Now I tried to check the CD following https://help.ubuntu.com/community/HowToMD5SUM#Check%20the%20CD, as following:
$ ls -l
-rwxrwx--- 1 root plugdev 718583808 2011-05-19 10:26 ubuntu-11.04-desktop-i386.iso

$ dd if=/dev/cdrom bs=1 count=718583808 | md5sum
dd: reading `/dev/cdrom': Input/output error
718581760+0 records in
718581760+0 records out
718581760 bytes (719 MB) copied5f0528a1b0a834bcf6d25f0b52d97736  -
, 3918.18 s, 183 kB/s

My questions are:

*

*I found my CD appears as
/media/Ubuntu 11.04 i386, why not
verify it, but to verify /dev/cdrom?

*why did I get "dd: reading
`/dev/cdrom': Input/output error",
and only 718581760 out of 718583808
bytes are processed?

*How shall I check the CD then?

Thanks and regards!

A: Just boot the CD and from the menu run Check disc for defects:

If everything's ok, you should get the message Check finished: no errors found.