text:
Q: How to solve ODEs with Java? I'm trying to solve an ODE with Java and so far I have tried two different libraries. The one I trust the most is Apache Commons Math however even for simple problems I don't seem to get the correct solution.
When I solve my system in Mathematica I get this:

whereas if I solve it with the Dormand-Prince 8(5,3) solver in Apache Commons Math I get this:

According to the theory behind this the circle should be closed like in the first picture. How can I get this solution in Java?
Here is the Java code I currently use (I have tested different settings for step size etc.):
program.java:
import org.apache.commons.math3.ode.*;
import org.apache.commons.math3.ode.nonstiff.DormandPrince853Integrator;
import org.apache.commons.math3.ode.sampling.StepHandler;
import org.apache.commons.math3.ode.sampling.StepInterpolator;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;

import static java.lang.Math.*;

public class program {

    public static void main(String[] args) {

        FirstOrderIntegrator dp853 = new DormandPrince853Integrator(1.0E-8, 10E-5, 1.0E-20, 1.0E-20);
        FirstOrderDifferentialEquations ode = new CometSun();

        double G = 1.48808E-34;
        double sunMass = 1.9891E30;

        double a = 1;
        double e = 0.1;
        double rp = a*(1-e);
        double v0 = sqrt(G*sunMass*(2/rp-1/a));
        double t = 2*PI*sqrt(pow(a,3)/(G*sunMass));

        double[] y = new double[6];

        y[0] = -rp;
        y[1] = 0;
        y[2] = 0;

        y[3] = 0;
        y[4] = v0;
        y[5] = 0;

        StepHandler stepHandler = new StepHandler() {

            ArrayList<String> steps = new ArrayList<String>();

            public void init(double t0, double[] y0, double t) {

            }

            public void handleStep(StepInterpolator interpolator, boolean isLast) {
                double   t = interpolator.getCurrentTime();
                double[] y = interpolator.getInterpolatedState();

                if( t > steps.size() )
                    steps.add(t + " " + y[0] + " " + y[1] + " " + y[2]);

                if(isLast) {
                    try{
                        PrintWriter writer = new PrintWriter(new File("results.txt"), "UTF-8");
                        for(String step: steps) {
                            writer.println(step);
                        }
                        writer.close();
                    } catch(Exception e) {};
                }
            }
        };
        dp853.addStepHandler(stepHandler);

        dp853.integrate(ode, 0.0, y, t, y);

        System.out.println(y[0]);
        System.out.println(y[1]);
    }

}

CometSun.java:
import org.apache.commons.math3.ode.FirstOrderDifferentialEquations;

import static java.lang.Math.*;

public class CometSun implements FirstOrderDifferentialEquations {

    double G = 1.48808E-34;
    double sunMass = 1.9891E30;

    public int getDimension() {
        return 6;
    }

    public void computeDerivatives(double t, double[] y, double[] yp) {
        double coeff = G*sunMass/pow(pow(y[0],2)+pow(y[1],2)+pow(y[2],2),3/2);

        yp[0] = y[3];
        yp[1] = y[4];
        yp[2] = y[5];

        yp[3] = -coeff*y[0];
        yp[4] = -coeff*y[1];
        yp[5] = -coeff*y[2];
    }

}

A: I can neither predict nor promise or verify that you'll receive exactly the same results as Mathematica: There are some very large and some very small numbers involved, and you might hit the limitations of the double precision.
But in this case, the main reason for the error is most likely a very simple and very subtle one:
double coeff = G*sunMass/pow(pow(y[0],2)+pow(y[1],2)+pow(y[2],2),3/2);

The last exponent is 1. You are performing an integer division there, and 3/2 yields 1. You could change this to
double coeff = G*sunMass/pow(pow(y[0],2)+pow(y[1],2)+pow(y[2],2),3.0/2.0);

and see whether you get closer to the perfect circle.
BTW: Computing x² as pow(x,2) is very inefficient. If efficiency may be an issue here (and I assume that it is), you should consider writing this as something like
double yy0 = y[0]*y[0];
double yy1 = y[1]*y[1];
double yy2 = y[2]*y[2];
double coeff = G*sunMass/pow(yy0+yy1+yy2,3.0/2.0);


text:
Q: Can I make a WinForms OpenFileDialog.ShowDialog not yield the main thread? I have a WinForms program which downloads then converts a collection of files each on their own thread via a batch thread used to report overall progress and job completion.  Each file will be downloaded on its own thread, then once downloaded, it will be passed over to its own conversion thread via a second batch thread via the main thread.  The reason for this pass-over via the main thread is so that the main thread can prompt the user for a save location for the converted version of all of these files once the first one has been downloaded.
The problem I am having is that the OpenFileDialog.ShowDialog() method (which is used to obtain a save directory from the user) blocks the main thread callback from the first completed download thread.  This in turn allows other download thread to complete (not a problem) but then also begin executing their callbacks to the main thread at which point they all hit OpenFileDialog.ShowDialog() which they otherwise wouldn't have done as my second batch thread would be running with the first conversion and they would be able to be added to the batch thread manager as a result of this.
I am using Dispatcher.CurrentDispatcher.BeginInvoke(myCallbackDelegate, DispatcherPriority.Normal, myParameter) in order to make the callback to the Main Thread upon item work completion.  I have created a simplified example below to demonstrate the problem code.
public partial class TestForm : Form
{
    private readonly Dispatcher dispatcher = Dispatcher.CurrentDispatcher;

    //An instance of my own BatchBackgroundWorkerThread<T> class; this class parrarlelizes tasks and can report their individual and overall progress, completion and cancellation.
    private readonly BatchBackgroundWorkerThread<int> conversionBatchBackgroundWorker = new BatchBackgroundWorkerThread<int>();

    public TestForm()
    {
        InitializeComponent();

        for (int threadIndex = 0; threadIndex < 4; threadIndex++)
        {
            new Thread(DoSomeBackgroundWork).Start(threadIndex);
            Thread.Sleep(10);
        }
    }

    private void DoSomeBackgroundWork(object threadIndex)
    {
        Thread.Sleep(1000);

        dispatcher.BeginInvoke(new ParameterizedThreadStart(WorkCompletedCallback), DispatcherPriority.Normal, threadIndex);
    }

    private void WorkCompletedCallback(object threadIndex)
    {
        //Waits for CanQueueNewItems to be in a valid readable state.
        conversionBatchBackgroundWorker.WaitForPendingRun();

        //CanQueueNewItems is true when the batch background worker's batch thread has been launched and its internal CountdownEvent and cancellationState have been initialized.
        if (conversionBatchBackgroundWorker.IsBusy && conversionBatchBackgroundWorker.CanQueueNewItems)
            //Queues the item in the BatchBackgroundWorker for parrarelization with any other items.
            //NOTE: This code is not currently hit unless the user makes a dialog selection before another callback can reach the above if statement.
            conversionBatchBackgroundWorker.Additem(threadIndex);
        else
        {
            FolderBrowserDialog.ShowDialog();

            conversionBatchBackgroundWorker.RunWorkerAsync(new int[] { (int)threadIndex }, FolderBrowserDialog.SelectedPath);
        }
    }
}

I have tried changing the DispatcherPriority to DispatcherPriority.SystemIdle - this made all the pending ShowDialog dialogs appear before having to click "OK" or "Cancel" to each one but aside that the result was still the same.
Is there a way I can stop ShowDialog from allowing other pending callbacks to the main thread from executing?
Update:
I've modified the code above to closer reflect what is happening in my real application.  All callback operations need to be enqueued into a BatchBackgroundWorker class I have created in order to perform their related conversions.  This is why I cannot simply set a variable before ShowDialog() is called saying that it was called since the remaining callbacks would then try to enqueue themselves into a BatchBackgroundWorker which currently has not been launched (the BatchBackgroundWorker thread is not running at this point as the launch is pending on the user's response to the dialog).

A: Simply invert the statements, so that the flag is set before the dialog is opened.
wasDialogShown = true;
OpenFileDialog.ShowDialog();

You also should lock the code part working with wasDialogShown:
private readonly object dialogLock = new Object();

private void WorkCompletedCallback(object threadIndex)
{
    bool wasShown;
    lock(dialogLock) {
        wasShown = wasDialogShown;
        wasDialogShown = true;
    }
    if (wasShown) {
        MessageBox.Show("Success!");
    } else {
        OpenFileDialog.ShowDialog();
    }
}

The Lock Statement prevents that another thread reads wasDialogShown after you have read it but before you have set it to true.

Update (in response to your update)
The solution could be to have 2 state variables: dialogLaunched and conversionWorkerLaunched. The first returning task launches the dialog. This task and tasks completing after the dialog was launched but before the conversion worker was launched are added to a queue. When the dialog closes the conversion is started and all the queued tasks are added to it. Tasks returning after the conversion was launched are added to the worker immediately.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Someone whose ancestors were artists How would you succinctly describe someone whose parents and ancestors were artists ?
I thought about: "He has artist lineage."
Or: "He comes from an artist family."

A: She comes from a long line of artists.

a long line of :
  a series of people or things that follow each other
  in time:
She is the latest in a long line of controversial leaders. He comes
  from a long line of doctors (= a lot of his relatives were doctors
  before him)
  cambridge dictionary


text:
Q: Call laravel controller via command line In kohana framework I can call controller via command line using
php5 index.php --uri=controller/method/var1/var2

Is it possible to call controller I want in Laravel 5 via cli? If yes, how to do this?

A: There is no way so far (not sure if there will ever be). However you can create your own Artisan Command that can do that. Create a command CallRoute using this:
php artisan make:console CallRoute

For Laravel 5.3 or greater you need to use make:command instead:
php artisan make:command CallRoute

This will generate a command class in app/Console/Commands/CallRoute.php. The contents of that class should look like this:
<?php namespace App\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Illuminate\Http\Request;

class CallRoute extends Command {

    protected $name = 'route:call';
    protected $description = 'Call route from CLI';

    public function __construct()
    {
        parent::__construct();
    }

    public function fire()
    {
        $request = Request::create($this->option('uri'), 'GET');
        $this->info(app()['Illuminate\Contracts\Http\Kernel']->handle($request));
    }

    protected function getOptions()
    {
        return [
            ['uri', null, InputOption::VALUE_REQUIRED, 'The path of the route to be called', null],
        ];
    }

}

You then need to register the command by adding it to the $commands array in app/Console/Kernel.php:
protected $commands = [
    ...,
    'App\Console\Commands\CallRoute',
];

You can now call any route by using this command:
php artisan route:call --uri=/route/path/with/param

Mind you, this command will return a response as it would be sent to the browser, that means it includes the HTTP headers at the top of the output.

A: I am using Laravel 5.0 and I am triggering controllers using this code:
$ php artisan tinker
$ $controller = app()->make('App\Http\Controllers\MyController');
$ app()->call([$controller, 'myMethodName'], []);

the last [] in the app()->call() can hold arguments such as [user_id] => 10 etc'

A: You can do it in this way too. First, create the command using
php artisan command:commandName

Now in the handle of the command, call the controller and trigger the method.
Eg,
public function handle(){
 $controller = new ControllerName(); // make sure to import the controller
 $controller->controllerMethod();
}

This will actually do the work. Hope, this helps.
DEPENDENCY INJECTION WON'T WORK

A: Laravel 5.7
Using tinker
 // URL: http://xxx.test/calendar?filter[id]=1&anotherparam=2
 $cc = app()->make('App\Http\Controllers\CalendarController');
 app()->call([$cc, 'getCalendarV2'], ['filter[id]'=>1, 'anotherparam' => '2']);

A: For Laravel 5.4:
php artisan make:command CallRoute
Then in app/Console/Commands/CallRoute.php:

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Http\Request;

class CallRoute extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'route:call {uri}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'php artsian route:call /route';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $request = Request::create($this->argument('uri'), 'GET');
        $this->info(app()->make(\Illuminate\Contracts\Http\Kernel::class)->handle($request));
    }

}

Then in app/Console/Kernel.php:
protected $commands = [
    'App\Console\Commands\CallRoute'
];

Call like: php artisan route:call /path

A: To version 8 of laravel.
First step: type command in terminal
php artisan tinker
Secound step:
$instante = new MyController(null);

Or if argument by an instance of model, then, pass name model class.
Example:
$instante = new MyController(new MyModelHere());

Press enter.
Finally, call method with  $instante->myMethod() here.
See:


text:
Q: powershell script exits in "if" clause if run from command prompt I am feeling surprised by the difference between two seemingly identical scripts.
first.ps1:
"A"
if ($true) { "B" }
"C"

second.ps1:
"A"
if ($true) { "B"
}
"C"

Now open a CMD window, and run these scripts like this:

    powershell - < first.ps1
    powershell - < second.ps1

first produces:

A
B
C

while second produces just

A

A: Not sure why the redirection to input doesn't work, but if you just specify the script as an input argument to powershell, it seems to work:
C:\fa2>powershell.exe C:\fa2\tc.ps1
Comparison starts
There was a difference
Comparison over

A: This has to be a bug.
In the redirection under cmd.exe case, the function completes normally and correctly if the if and else blocks are individually all on one line:
$candidate = '.\foo.txt'
$current= '.\bar.txt'

"Comparison starts"
if ($(diff $(get-content $current) $(get-content $candidate)).length -gt 0){"There was a difference"}
else {"There was not a difference"}
"Comparison over"

But if either block is split up onto more than one line and that branch is taken, the script aborts with no warning/output.
I'd report this on the PowerShell feedback site (connect.microsoft.com).

A: Edit:
Yep, Jay proved it. The root problem is that Powershell does not support the '<' operator. I've been searching all day for some official documentaion on the web, but have not found it. I just occured to me to check some old notes, and I found a reference to this not being supported in v1. It only supports '>'.
I'll try to update if I find something more official than my memory. Leaving original text just for completnes.

I dont think the accepted answer is enitrely true here.
Take a look at Lee Holmes blog: link
He is one of the devs on the Powershell team, and wrote the Powershell Cookbook, just to give a little credence to his words.
I've run into this kind of problem with some complicated and archaic Bat scripts that relied on some funky fancy binary redirection. Powershell would run the Bat file, but at the point where the binary redirection took place it would just stop. Using [Process]:Start as described in the blog post worked wonderfully, and allowed me to parse the output of the Bat file like any other nicely behaved script to boot.
In your case I assume "diff" is an actuall exe and not a function, and its outputing binary and not text.
On a side note, I really don't see the need for redirecting the output of the script to Powershell like youre doing. Seems kind of counterproductive. You wrote a powershell script, seems like a waste not to use the paramter specifically provided to handle running input.

A: I don't think this is a bug.  Try typing each of those lines in on the console and you will see what is happening.  When you type and open bracket and don't close it, PowerShell goes into a multiline entering mode.  To exit this mode, you need a closing bracket AND a blank line afterward.  If you have a blank line before or after the "C" it should work.
Of course, maybe it is a bug and just has the same effect as multiline input.  :)
I can't get this to work myself, powershell is ignoring what I send into it.


text:
Q: 8-bit indexed images for games developed in the 90s I am currently working on an old classic PC game. The programming face a lot of issues as I go along, mostly because I am not educated as a programmer nor designer. Although my passion for this particular game makes it wort it.
I am currently trying to open the images for the game. The images are made using Paint Deluxe 2. From what I have found out they are all PCX-format when you open them to add changes. Then they are saved into the game in a external achieve beside the executable file as .bmp-files (from what I can understand). The palette used is actually a bit weird with 6-bits channels (not 8-bits as you would expect).
I face a issue with the developers way of doing it. Before adding the images to the file, the header was stripped off, and the palette stored in an external file.
As Paint Deluxe 2 save the length of the pixels for a 190x107 to 20544 bytes (189x107-190x107-191x107 and 192x107 are all stored as 20544 bytes of pixels excluding the header and palette). While is should actually be 20330 bytes. This brings some headache for me. As well as it seems like the images used for the game is somehow the other way around. Looks like the images is stored going in the opposite direction somehow.
To clear things up:
FILE34 which is 20330 byte is the ORGINAL file loaded by the game onto the screen.
FILE34 which is 20544 byte is what I end up with when I stripp the file after changing it back to pcx-format and then to bmp-format. The pcx-file is also included and can be opened with GIMP for example.
BIN_PALETTE.PAL is the palette used for the images.
Are anyone familiar with this issue, and can give me some advice?
enter link description here

A: BMP files are usually stored bottom-up (the last scanline is stored first, all the up, until the first scanline). More recent BMP files can also be stored top-down like other formats, but this is less common. If the game's files are stored top-down, they will appear as upside down, compared to a normal BMP file.
Also, the BMP format pads each scanline to a 32 bit (long word) boundary, which is why the file size is the same for widths 189-192 (they all need 192 bytes per scanline). If game's files are stored without this padding, this is the reason for the difference.
For more info, see BMP file format on Wikipedia.
It is quite easy to rewrite your headerless BMPs to the format used in the game (given those are the two only differences). I'll outline the process/use pseudo code, as there's no language tag in your question:

*

*Read the entire BMP array into memory (192 x 107).

*Create a new array that can hold the output (190 x 107)

*Loop over the rows in the original

*

*For each row, copy the first 190 bytes (skip the 2 padding bytes)

*Store these bytes into the new array, but fill from the end

*Write the resulting bytes to disk

(I can write the above in Java if it helps you).


text:
Q: Not able to call the webhook deployed on my server from the dialogflow agent Using my gmail account I created an actions project in google console -> then created the intents in the dialogflow agent-> then enabled the webhook for the intents, then I included the server path where my webservice(written in node.js) is hosted under the fulfillment button available in Dialog flow agent.
But the webservice hosted on my server is not at all getting called. If I call the same webservice from the browser its getting called.
I am getting this below log in actions console:

"Webhook call failed. Error: Webhook response was empty."

*

*
*

*Code written in node js (created on my server) - - In fulfillment of dialogflow I entered "https://DomainNameWhereXXXPortIsLocated" with version as "v2" - -

app.js - -
var express = require('express')
  , https = require('https')
  , fs = require('fs')
  , path = require('path');

var app = express();

var  bodyParser = require('body-parser');
const {actionssdk,Image,} = require('actions-on-google');
const app2 = actionssdk();

//to display in console
app.get('*' , function (req, res, next) {
    console.log('Request URL:', req.originalUrl)
    next();
});

//intents created in my dialogflow
app2.intent('favourite_Color',function (conv, {color})  {
    var luckyNumber = color.length;
    conv.close('This is our lucky number - ' + luckyNumber);
});

app2.intent('call',function (conv, {contacts})  {
    console.log(contacts);
    console.log("call intent is triggered");
   conv.close('You are trying depu to call this person - ' + contacts);

app.use(bodyParser.json(),app2).listen(3000);

var options = {
            key:fs.readFileSync(pathIncluded),
            cert:fs.readFileSync(pathIncluded)
};

//this is the port I am trying to listen
https.createServer(options, app).listen(xxx, function(){
    console.log('Express server listening on port ' + xxx);
});


text:
Q: getJSON PHP não mostra resultado Estou fazendo uma consulta simples via getJSON, mas não esta retornando os valores para ser mostrado.
Arquivo testeJson.php
<!doctype html>

<meta charset="utf-8">
<title>Documento sem título</title>

Cardápio de Pizzas

    <input type="text" name="nome" id="nome">

Arquivo testeConexaoMobileJson.php
<?php
$mysqli = new mysqli('localhost','','',''); if($mysqli->connect_error){echo "Erro";exit();}

if($_GET['acao'] == 'listar'){
    header('Content-Type: application/json; charset=utf-8');
    $rs = $mysqli->query("SELECT * FROM cadastro");
    $row_rs = $rs->fetch_assoc();
    $row = $rs->fetch_array();
    $registros = mysqli_num_rows($rs);

    while($campos=mysqli_fetch_array($rs)) {
        extract($campos);
        $Array = Array();

        $Array[] = Array(
                            "nome"  => "$nome",
                            "email" => "$email",
                        );

        $json_encode = json_encode($Array);
        echo $json_encode;
    }

}
?>

Resultado do arquivo testeConexaoMobileJson.php
Inspetor:

Resultado:

[{"nome":"Tiago","email":"email1@hotmail.com"}][{"nome":"Tiago","email":"email2@hotmail.com"}]

A: Seu códigos está muito redundante, basicamente o que você precisa é isso:
$rs = $mysqli->query("SELECT * FROM cadastro");

$registros = $rs->num_rows;

$arr = array();
while($row = $rs->fetch_assoc()) {
    $arr[] = $row;
}

$json_encode = json_encode($arr);
echo $json_encode;

Problemas:
$row_rs recebe o primeiro registro da consulta em um array associativo, $row faz a mesma coisa exceto que recebe um array indexado por números e um associativo. Dica elimine a linha da atribuição do $row.
$rs = $mysqli->query("SELECT * FROM cadastro");
$row_rs = $rs->fetch_assoc();
$row = $rs->fetch_array();

 while($campos=mysqli_fetch_array($rs)) {
    extract($campos);
    $Array = Array();
    $Array[] = Array("nome"  => "$nome", "email" => "$email",);
    $json_encode = json_encode($Array);
    echo $json_encode;
}

Não faz muito sentido usar extract() elemine ele. A cada volta do while $array é resetado com um array vazio, a linha seguinte já tem um erro de sintaxe, yep um vírgula sobrando lá no final.
A conversão do array para json só deve ser feita após o while pois assim todos os valores são convertidos de um vez só.
Caso queira apenas alguns campos da tabelas e não todos, troque o asterisco pelo nome dos campos.
Mude:
SELECT * FROM cadastro

Para:
SELECT nome, email FROM cadastro

A: Você só pode exibir os dados com json_encode fora do while, meu amigo.
while ($campos = mysqli_fetch_array($rs)) {

    extract($campos);

    $Array[] = Array(
        "nome"  => "$nome",
        "email" => "$email",
    );

    //  Melhor assim

    $Array[] = $campos;

}

echo json_encode($Array);

A: Pode ser que esteja indo para o browser alguma saída após o echo. Experimente encerrar o PHP assim echo json_encode( $resultado); exit();. No javascript, você pode utilizar o seguinte código:

$.post ( url, data, function( response ) {

    // Abra o console do navegador para visualizar esta saída
    console.log( response );

    // Digite seu código aqui

}, 'json' );

// Observe que você pode passar o parâmetro 'json' no final
// para converter a resposta ao invés de usar uma função específica


text:
Q: my php code is in my form i dont know how to fix this Hi i am currently coding for a school project i am not a master in coding.
I am making a form using php and html with wampserver.
Some of my php code stays in the boxes wich u have to put your name in etc.
Can you please help me. Below is my php code and html. i tried everything w3schools and other stuff but still cant fix it please help me
i tried to begin over and now if i click the send button i get an error.
error code:
Parse error: syntax error, unexpected '&' in C:\wamp64\www\web\formprocessor.php on line 4. i did tried to delete some & but still didnt work.
this is my code
&Naam=&_POST["&fNaam"]
&Email=&_POST["&fEmail"]

echo("Hallo &myNaam
");
echo("&myEmail isje mail.
");

A: *

*change your contact.html to another file name with .php extension

*replace contact.php in form action


text:
Q: How to Draw some shape on JPanel using ActionListener? I'm practising to draw a shape on a JPanel by clicking on a Jbutton, but I cannot. It's been five hours that I'm surfing the web, but I cannot find the way to do it.
This is what I want to do: if I click on "Rectangle" button a rectangle appears under the buttons and if I click on "Circle" button a circle appears.
   import javax.swing.*;
   import java.awt.*;
   import java.awt.event.*;

   class Shape extends JFrame {
       JButton rec, circle;
       static String botSelected;
       Shape (){
           frameSet ();
       }

       void frameSet(){
           JFrame frame = new JFrame();
           frame.setVisible(true);
           frame.setSize(600,300);
           rec = new JButton ("Rectangle");
           circle = new JButton("Circle");
           JPanel panel = new JPanel();
           frame.add(panel);
           panel.add(rec);
           panel.add(circle);
           Click clk = new Click();
           rec.addActionListener(clk);
           circle.addActionListener(clk);
       }

       public void paint (Graphics g){
           super.paint(g);
           if (botSelected.equals("Rectangle"))
               g.fillRect(50,50,50,50);
           else if (botSelected.equals("Circle"))
               g.fillOval(50,50,50,50);
       }

       public static void main (String [] arg){
           Shape s = new Shape();
       }
   }

   class Click implements ActionListener{
       public void actionPerformed (ActionEvent e){
           Shape.botSelected = e.getActionCommand();
       }
   }

A: The first thing I would do is have a read through Painting in Swing and Performing custom painting to better understand how the painting process works.
Next you need to understand that JFrame is a bad choice for painting to. Why? Because it's multilayered.

A JFrame contains a JRootPane, which contains a JLayeredPane the contentPane, glassPane and the JMenuBar and in your example, it also contains a JPanel.
With the (default) exception of the glassPane, all these components are opaque.
While it's possible to have something drawn in the paint method show it, if any of the other components paint themselves, it will be wiped clean - this is because Swing components can actually be painted independently of each other, with having to have the parent paint itself first.
A better solution is to start by extending from JPanel and override its paintComponent method.
For simplicity, I'd also encourage you to implement the ActionListener against this class as well, it will allow the actionPerformed method to access the properties of the component and, in your case, call repaint to trigger a paint cycle when you want to update the UI.

A: Here is a derived example from your code.
As @MadProgrammer said, don't extend JFrame.
In the following example, here are the major changes :

*

*give a non-null value to botSelected, or the first calls to paintComponent will give you a NullPointerException

*the class now extends JPanel, and overrides paintComponent for custom painting

*the ActionListener is an anonymous class, because you don't need a separate class, and it has direct access to the fields from Shape

*botSelected is no longer static (see above point)
.
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

class Shape extends JPanel {
    JButton rec, circle;
    String botSelected = "";// don't let it be null, it would make paintComponent crash on startup

    Shape() {
        frameSet();
    }

    void frameSet() {
        JFrame frame = new JFrame();
        frame.setVisible(true);
        frame.setSize(600, 300);
        rec = new JButton("Rectangle");
        circle = new JButton("Circle");

        frame.add(this);
        this.add(rec);
        this.add(circle);
        // anonymous class, has access to fields from the outer class Shape
        ActionListener clk = new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                botSelected = e.getActionCommand();
                repaint();
            }

        };
        rec.addActionListener(clk);
        circle.addActionListener(clk);
    }

    //custom painting of the JPanel
    @Override
    public void paintComponent(final Graphics g) {

        super.paintComponent(g);
        if (botSelected.equals("Rectangle")) {
            g.fillRect(50, 50, 50, 50);
        } else if (botSelected.equals("Circle")) {
            g.fillOval(50, 50, 50, 50);
        }
    }

    public static void main(final String[] arg) {
        Shape s = new Shape();
    }

}


text:
Q: do you know why useEffect execute everytimes i enter input? do you why useEffect execute every times i type a letter at input?
I don't think the input will affect 'useEffect'...
import React, { useEffect, useState } from 'react';

const DBLab = () => {
    const [inputValue, setInputValue] = useState("");

    const printfunc = () => {
        console.log("print");
    }
    useEffect(()=> {
        const print = () => {
            printfunc();
        }
        print();
    },[printfunc]);
    return (

dblab

{hashHistory}

            <input type='text' value={inputValue} onChange={(e)=>setInputValue(e.target.value)}/>

    )
}

export default DBLab;

A: Each time you enter a letter you update the inputValue which causes the component to re-render. When the component re-renders, the variable printfunc is re-initialised. And because your useEffect function has printfunc in the dependency array it is triggered each time this variable changes.
To solve this, remove printfunc from the array like so:
    useEffect(()=> {
        const print = () => {
            printfunc();
        }
        print();
    },[]);


text:
Q: Django filter: Searching in User and Profile Models with paginator I'm trying to create an admin panel where the admin can search for a user by username, first_name, last_name, zip_code (from profile model), etc. For some reason, the paginator works, but when I try to search using django-filter, nothing happens. The results don't change and I still see the whole list of all the users.
Models.py:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birthdate = models.DateField(null=True, blank=False, max_length=8)
phone_number = PhoneNumberField(null=True, blank=False, unique=True)

filters.py
import django_filters
from django_filters import CharFilter
from django.contrib.auth.models import User
from .models import *

class AdminUserFilters(django_filters.FilterSet):
    first_name_bitch = CharFilter(field_name='first_name', lookup_expr='icontains')
    # last_name = CharFilter(field_name='last_name', lookup_expr='icontains')
    # zip_code = User.profile.objects.filter(author__user__profile__screenname__icontains=w)
    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email',)

views.py
User_list = User.objects.all().order_by('username')
User_filter = AdminUserFilters(request.GET, queryset=User_list)

paginator = Paginator(User_filter.qs, 10)
page_num = request.GET.get('page', 1)

try:
    User_list = paginator.page(page_num)
except PageNotAnInteger:
    User_list = paginator.page(1)
except EmptyPage:
    User_list = paginator.page(paginator.num_pages)

context = {'User_list': User_list, 'User_filter':User_filter, 'paginator':paginator, 'page_num':page_num,}
return render(request, "admin/listusers.html", context)

listusers.html
    {{ User_filter.form }}

<button type="submit" type="button" style="height:40px; width:120px" class="btn btn-primary">Search</button>

{% for user in User_list %}

        {{ user.username }}
        {{ user.date_joined}}
        Edit Household
        {{ user.first_name }}
        {{ user.last_name }}
        {{ user.profile.birthdate }}
        {{ user.email }}
        {{ user.profile.phone_number }}
        {{ user.profile.zip_code }}

    {% endfor %}

    {% if User_list.has_previous %}
    Previous
    {% endif %}

    {% if User_list.has_next %}
    Next
    {% endif %}

    {% for pg in User_list.paginator.page_range %}
        {% if page_num|slugify != pg|slugify %}
        <input type="button" style="height:50px; width:40px;display: inline-block;" class="btn-primary" onclick="location.href='?page={{pg}}';" value="{{ pg }}" />
        {% endif %}
    {% endfor %}


text:
Q: Hidden Characters using subprocess.Popen I am trying to get a numeric value from the following code.  When I "print" out the value I get a number "1".  Yet when it goes to the "if" statement I always get "closed" as the stored variable in "STORE".  The third line of the code is used to remove the carriage return.
CLOSED = subprocess.Popen(
    [
        "ssh",
        "hostname",
        "/usr/blaine/store_status | grep 00 | awk \{\'print $5\'\}"
    ],
    stdout=subprocess.PIPE
)

CLOSED_OUTPUT = CLOSED.stdout.read()
CLOSED_OUTPUT = CLOSED_OUTPUT.replace('\n','')

(Having a hard time getting the if statement to show properly, I do have proper indentions and it does work if I assign the variable)
if CLOSED_OUTPUT == 1:
    STORE = "open"
else:
    STORE = "closed"

print ("The store is %s." % (STORE))

A: CLOSED_OUTPUT is a string, so it will never compare equal to the integer 1.
You could try
if CLOSED_OUTPUT == '1':

or, if you expect that the result is usually an integer, convert it to an integer before using it.

A: from subprocess import check_output

output = check_output(["ssh", "hostname",
    "/usr/blaine/store_status | grep 00 | awk \{'print $5'\}"])
try:
    value = int(output)
except ValueError:
    opened = False
else:
    opened = (value == 1)

print("The store is {}.".format("open" if opened else "closed"))

int() ignores whitespace such as '\n' i.e., you don't need to do the replacement. You could also reimplement grep .. | awk part in Python. paramiko (Python ssh library) allows you to run a remote command via ssh without running ssh subprocess.


text:
Q: Getting "The body you sent contains an unknown key." when trying to create a Contentful entry I have created a contentful model called "User" with two fields:

*

*id - text, unique, required

*email - text, optional

When I try to create a new entry via content management API using these parameters:
Headers:
X-Contentful-Content-Type : user
Content-Type : application/vnd.contentful.management.v1+json

Method
PUT

URL
https://api.contentful.com/spaces/qilo7tiaixh8/environments/entries/

Body:
    {
        "id":"whatever",
        "email": "peter@petervukovic.com"
    }

I get the following error:
    {
        "requestId": "2849bbcd7ee0486bb36b47927071f37b",
        "sys": {
            "type": "Error",
            "id": "UnknownKey"
        },
        "message": "The body you sent contains an unknown key.",
        "details": {
            "errors": [
                {
                    "keys": [
                        "id",
                        "email"
                    ]
                }
            ]
        }
    }

I have no idea what I'm doing wrong as the examples in the official documentation aren't helpful  (they assume multi-lingual content I'm not using) and there are no debugging hints.

A: Contentful DevRel here.
I just tried it and the following CURL works for me on a user content type that defines a title field.
curl --include \
     --request PUT \
     --header 'Authorization: Bearer ...' \
     --header 'Content-Type: application/vnd.contentful.management.v1+json' \
     --header 'X-Contentful-Content-Type: user' \
     --data-binary '{
       "fields": {
         "title": {
           "en-US": "Hello Test"
         }
       }
     }' \
     https://api.contentful.com/spaces/.../environments/master/entries/\test-1

It looks like you were missing to include the fields property in your payload. About the localization part, I think it's required to provide the locale for your field values. So in my example, en-US is the default value and it is required.
For using PUT you have to define or come up with an entry id.
To create an entry without passing and defining an id have a look at the docs in Entry collection.
curl --include \
     --request POST \
     --header 'Authorization: Bearer ...' \
     --header 'Content-Type: application/vnd.contentful.management.v1+json' \
     --header 'X-Contentful-Content-Type: user' \
     --data-binary '{
       "fields": {
         "title": {
           "en-US": "Hello Test 2"
         }
       }
     }' \
     https://api.contentful.com/spaces/.../environments/master/entries/


text:
Q: How to cross-compile Qt6 on Linux for Windows? I'm trying to cross-compile Qt 6.2.1. Target - Windows, my machine OS - Linux (Mint 20.2) (both 64bit). Unfortunately I can't compile it on Windows, so I have to do this cross-compilation.
My configure cmd:
./../qt-everywhere-src-6.2.1/configure -prefix $PWD/. -platform linux-gcc-64 -xplatform win32-g++ -device-option CROSS_COMPILE=/usr/bin/x86_64-w64-mingw32- -opensource -opengl desktop -qt-host-path /home/papoj/Projects/host_qtbuild

At the end of CMake work I'm getting this:
CMake Warning:
  Manually-specified variables were not used by the project:

    QT_QMAKE_DEVICE_OPTIONS

And then, after cmake --build . --parallel:
FAILED: qtbase/src/tools/bootstrap/CMakeFiles/Bootstrap.dir/__/__/corelib/global/qglobal.cpp.o
/usr/bin/c++ -DHAVE_CONFIG_H -DQT_BOOTSTRAPPED -DQT_NO_CAST_FROM_ASCII -DQT_NO_CAST_TO_ASCII -DQT_NO_DEBUG -DQT_NO_FOREACH -DQT_USE_QSTRINGBUILDER -DQT_VERSION_MAJOR=6 -DQT_VERSION_MINOR=2 -DQT_VERSION_PATCH=1 -DQT_VERSION_STR=\"6.2.1\" -D_LARGEFILE64_SOURCE -D_LARGEFILE_SOURCE -I/home/papoj/Projects/qtbuild/qtbase/src/corelib/Core_autogen/include -I/home/papoj/Projects/qtbuild/qtbase/include -I/home/papoj/Projects/qtbuild/qtbase/include/QtCore -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/corelib -I/home/papoj/Projects/qtbuild/qtbase/src/corelib -I/home/papoj/Projects/qtbuild/qtbase/src/corelib/global -I/home/papoj/Projects/qtbuild/qtbase/src/corelib/kernel -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/corelib/../3rdparty/tinycbor/src -I/home/papoj/Projects/qtbuild/qtbase/include/QtCore/6.2.1 -I/home/papoj/Projects/qtbuild/qtbase/include/QtCore/6.2.1/QtCore -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/corelib/../3rdparty/double-conversion/double-conversion -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/corelib/../3rdparty/double-conversion -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/corelib/../3rdparty/forkfd -I/home/papoj/Projects/qtbuild/qtbase/src/corelib/.rcc -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/mkspecs/win32-g++ -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/home/papoj/Projects/qtbuild/qtbase/src/xml/Xml_autogen/include -I/home/papoj/Projects/qtbuild/qtbase/include/QtXml -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/xml -I/home/papoj/Projects/qtbuild/qtbase/src/xml -I/home/papoj/Projects/qtbuild/qtbase/include/QtXml/6.2.1 -I/home/papoj/Projects/qtbuild/qtbase/include/QtXml/6.2.1/QtXml -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/tools/bootstrap/.. -I/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/tools/bootstrap/../../3rdparty/tinycbor/src -DNDEBUG -O2 -fPIC -fvisibility=hidden -fvisibility-inlines-hidden -Wall -Wextra -ffunction-sections -fdata-sections -mshstk -Wsuggest-override -std=gnu++17 -MD -MT qtbase/src/tools/bootstrap/CMakeFiles/Bootstrap.dir/__/__/corelib/global/qglobal.cpp.o -MF qtbase/src/tools/bootstrap/CMakeFiles/Bootstrap.dir/__/__/corelib/global/qglobal.cpp.o.d -o qtbase/src/tools/bootstrap/CMakeFiles/Bootstrap.dir/__/__/corelib/global/qglobal.cpp.o -c /home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/corelib/global/qglobal.cpp
In file included from /home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/src/corelib/global/qglobal.cpp:41:
/home/papoj/Projects/qt-everywhere-src-6.2.1/qtbase/mkspecs/win32-g++/qplatformdefs.h:55:10: fatal error: tchar.h: No such file or directory
   55 | #include <tchar.h>
      |          ^~~~~~~~~

I have checked (this is also visible in log above) and CMake, for some reason, ignore my "CROSS_COMPILE" option and uses Linux c++ tool to compile instead of 'x86_64-w64-mingw32-g++', but I dont know how to fix that.
Does anybody cross-compiled Qt6 for Windows on Linux manually? I cannot find any working solution on the Internet.

A: For those coming here from google with same problem.
In Qt6 you need to specify Cmake toolchain for cross-compilation (I get something similar to toolchain shared here), as 'alone' device-option CROSS_COMPILE (as in cmd from my question) is depreciated/outdated (or smth like that).
In my case I needed to use CMake toolchain and device-option CROSS-COMPILE as well, because in other way qmake was not able to find proper cross-platform compiler (in my case x86_64-w64-mingw32-g++-posix). To use compiler with "posix" at the end I needed to modify qtbase/mkspecs/win32-g++/qmake.conf. This is how it looks like after changes:
#
# qmake configuration for win32-g++
#
# Written for MinGW-w64 / gcc 5.3 or higher
#
# Cross compile example for i686-w64-mingw32-g++:
#   configure -xplatform win32-g++ -device-option CROSS_COMPILE=i686-w64-mingw32-
#

include(../common/g++-win32.conf)
include(../common/windows-desktop.conf)

# modifications to g++-win32.conf

QMAKE_CC                = $${CROSS_COMPILE}gcc-posix
QMAKE_CFLAGS           += -fno-keep-inline-dllexport
QMAKE_CFLAGS_WARN_ON   += -Wextra

QMAKE_CXX               = $${CROSS_COMPILE}g++-posix
QMAKE_CXXFLAGS         += -fno-keep-inline-dllexport
QMAKE_CXXFLAGS_WARN_ON  = $$QMAKE_CFLAGS_WARN_ON
QMAKE_CXXFLAGS_EXCEPTIONS_ON += -mthreads

QMAKE_LINK              = $${CROSS_COMPILE}g++-posix
QMAKE_LINK_C            = $${CROSS_COMPILE}gcc-posix

QMAKE_CFLAGS_LTCG       = -flto
QMAKE_CXXFLAGS_LTCG     = $$QMAKE_CFLAGS_LTCG
QMAKE_LFLAGS_LTCG       = $$QMAKE_CFLAGS_LTCG
QMAKE_LFLAGS_EXCEPTIONS_ON += -mthreads

load(qt_config)

Final ./configure cmd:
./../qt-everywhere-src-6.2.1/configure -prefix $HOME/Projects/testing_qt_builds/qtbuild_with_old_params -platform linux-g++ -xplatform win32-g++ -device-option CROSS_COMPILE=/usr/bin/x86_64-w64-mingw32- -opensource -opengl desktop -qt-host-path $HOME/Qt/6.2.1/gcc_64 -nomake tests -nomake examples -skip qtwebengine -- -DQT_BUILD_TOOLS_WHEN_CROSSCOMPILING=ON -DCMAKE_TOOLCHAIN_FILE=$HOME/Projects/toolchain.cmake

After cmake --build and cmake --install I got host-qmake script in my build path

$HOME/Projects/testing_qt_builds/qtbuild_with_old_params/bin/

Which I had to use to build my Qt project by passing .pro file to it. And then I just copied .exe file to Windows, provided all needed dlls and POOF, app works. :D
My thread on qt forum with same problem where one of moderators helped me a lot to get final solution.

A: Another, possibly simpler approach to cross-compiling Qt for Windows on Linux is to use qmake with MXE and mxedeployqt (the latter is the equivalent of windeployqt and collates the required DLLs).
I've got a couple of projects that use MXE and mxedeployqt within Docker to build Qt.  The docker container builds MXE from source (because I wanted a recent gcc and it wasn't available in the MXE repositories) which takes a long time, but once that's done, compiling Qt code is very straightforward: docker-compose up.
Once set up, creating a new project that uses the same method is very simple as it uses the same Dockerfile and build script.  Two example repositories that use this method are ARPCalc and Digraph.  Most of the configuration required to get a working build system is in the dockerfiles/winqt folder: https://github.com/abudden/digraph/blob/master/dockerfiles/winqt


text:
Q: Selected item in ASP.NET Core razor not being passed I'm using ASP.NET Core Razor for the first time. I'm trying to simply set a bound property with the selected value of a dropdown but the property is always null when the form is posted. Also, how does one get the form posted when a selection is made? TIA
Razor page:

    <form method="post">
        <select asp-for="@Model.selectedReport" asp-items="@Model.Reports" class="form-control">
        </select>
    </form>

Code behind:
public class SubscribedReportsModel : PageModel
{
    [BindProperty]
    public List<SelectListItem> Workspaces { get; private set; }

    [BindProperty]
    public List<SelectListItem> Reports { get; private set; }

    [BindProperty]
    public string selectedReport { get; set; }

    public async Task OnGetAsync()
    {
        await GetWorkspaces();
    }

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        if (selectedReport != null)
        {
            return Page();
        }

        return RedirectToPage("./Index");
    }
}

A: I'm a bit rusty it appears. All I had to do was add onchange="this.form.submit()" to the  control:

                    <form method="post">
                    <select asp-for="@Model.selectedReport" asp-items="@Model.Reports" class="form-control" onchange="this.form.submit()">
                                </select>
                        @*@Html.DropDownList("ddl_Reports", Model.Reports, new {@class="form-control"})*@
                        @*@Html.DropDownListFor(m => m.selectedReport, Model.Reports, "--Select Report--", new{@class="form-control"})*@
                    </form>


text:
Q: Dart: How to work around the diamond pattern with mixins? Is there a way to solve the diamond problem when using Mixins in Dart?
Have a look on the following simple example:
class M1 {
  String sayHello() => "hello M1";
}
class M2 {
  String sayHello() => "hello M2";
}
class S {
  String sayHello() => "hello S";
}
class C extends S with M1, M2 {}

main() {
  C c = new C();
  print(c.sayHello());
  print((c as M1).sayHello());
}

Output:
hello M2
hello M2

If you call "sayHello" on c, it depends on the order of the mixins in the class declaration of
C, which of the implementations is executed. Always the implementation of the last mixin on the list is used. This is hardly explicit and might often be a matter of chance. Worse: The implementation of the superclass C is always hidden.
The typecast doesn't change a thing, which of course is in accord with the general Dart philosophy that the runtime type doesn't come into play when executing code. Still it would be good if there were any means to explicitly decide between the different implementations. Is there such a possibility?

A: In short: No.
You can't solve a diamond problem in Dart because Dart doesn't have multiple inheritance, so it doesn't have the problem (or feature).
Adding mixins on top of a class is completely normal single inheritance, and Dart class implementation is always a single chain down to Object.
The only thing mixins do is to allow the same members to occur in more than one chain.
That also means that there is no way to access overridden members higher in the chain.
You can only ever access the top-most declaration, or, as a member function, the top-most declaration of your super-chain (using super.foo()).


text:
Q: Jest in Node JS I installed jest on my node js project with : npm install --save-dev jest.
I added jest in the script of package.json:
"scripts": {
   "start": "node app/index.js",
   "dev": "nodemon app/index.js",
   "test": "jest"
}

I try launching jest with the commande: npm run test but I always get this error:
PS P:\Projets Angular\dblogwebapp\back-end> npm run test
> back-end@1.0.0 test
> jest

Error: EPERM: operation not permitted, realpath 'myPath\back-end'
at Function.realpathSync.native (node:fs:2550:3)
at tryRealpath (myPath\back-end\node_modules\jest-util\build\tryRealpath.js:26:39)
at Object.<anonymous> (myPath\back-end\node_modules\jest-resolve\build\resolver.js:124:49)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (myPath\back-end\node_modules\jest-resolve\build\index.js:9:40)

Can anyone help me plz. thanks


text:
Q: Lists of Theorems (XeLaTeX) I've found out how to use the thmtools package to make lists of theorems. My questions on this are:

*

*Adding [name=xxx,label=thm:...] after \begin{yyy} (xxx is a title for the theorem, ... a label appearing in the list, yyy the theorem kind) labels a theorem. If I try to put any maths beyond superscript and subscript (for now I've only tried \mathbb) into a label, I get a missing \endcsname inserted error related to a line of the .aux files. MWE:
\documentclass[a4paper]{report}
\usepackage{thmtools,amssymb}
\declaretheorem[name=Definizione]{defi}
\begin{document}
\begin{defi}[name=$\mathbb R$,label=thm:$\mathbb R$definizione]
Ah beh, s\`i beh.
\end{defi}
\listoftheorems
\end{document}

which gives:
.
The same error is obtained by placing a \ref in a label. In fact, \mathbb gives problems anywhere in those [], just like a comma in the middle of a name or label, even within dollars to mark an interval like (0,1). How do I solve that?

*(should be 2) And finally, I'm using theorems with [subsection] numbering. Now, in the list, the number overlaps the theorem kind (i.e. I get 1.2.1.1 overlapping Definizione (Spazio Metrico)). How do I solve that?

A: The value for the key label should be a mnemonic string to be used in the argument of \ref for referring to this theorem number.
It shouldn't contain any command and any special character (and it will never appear in print). So
\begin{defi}[name=$\mathbb{R}$,label=thm:R-definizione]

is what you need. When you want to refer to this definition, type
\ref{thm:R-definizione}

Please, note that the correct input is \mathbb{R}, not \mathbb R. The fact that the latter gives the same result shouldn't be taken as a proof that the input is valid.


text:
Q: Script not exiting on error bash ios So I am having to do my own error handling and am running into issues, the code below is causing the issue.
sbalert -t "Checking" -m "Checking for updates please wait" -d "" &
alert_id="$!"
ping -c 1 repod00r.com || kill $alert_id && sbalert -t "Connection error" -m "Unable to connect to the update server." && exit

whenever the ping succeeds or fails I get the error handler thrown and once I close the sbalert the sbalert -t "Checking" -m "Checking for updates please wait" -d "" reappears on screen when it should have been killed.
I have already tried re-ordering the three parts of the error handling around to try and fix this. But to no avail...
I am a bit of a noob, so sorry if the answer is punching me in the face...

A: In bash, the connectors || and && are simply executed left to right. || does not have higher precedence.
Try this to see how it works:
true || echo 1 && echo 2
false || echo 1 && echo 2
false || false && echo 1 && echo 2

So when you do: (simplified)
ping || kill $alert_id && sbalert && exit

The kill only executes if the ping fails, but the sbalert executes if either the ping or the kill succeed, and exit executes if the sbalert executed and succeeded.
So if the ping succeeds, the second sbalert will execute, but the original sbalert will not be killed, which seems to be what you are experiencing.
Your code would be easier to read and write with if statements:
sbalert -t "Checking" -m "Checking for updates please wait" -d "" &
alert_id=$!
if ! ping -c 1 repod00r.com; then
    kill $alert_id
    sbalert  -t "Connection error" -m "Unable to connect to the update server."
    exit
fi

A: If either the ping or the kill succeed that second sbalert will trigger.
Shell && and || are not ternary operators.
When the shell sees a || b && c it interprets that as (a || b) && c when you are expecting it to be a || (b && c).
Either explicitly group your commands (e.g. a || { b && c; }) or use an explicit if.


text:
Q: Updating heroku pipeline environment variables If I want to update environment config variables for a heroku app, I would run the following command:
heroku config:set FROM_EMAIL=$(FROM_EMAIL) --app=my-app

Say I have a pipeline which I would like to add the same environment variable. What would be the equivalent command to update my Heroku CI config variables.
I have had a look at all the available options to me by running:
heroku help pipelines

Nothing seems to facilitate this. I have looked at adding these environment variables to individual pipeline apps, but it does not change the pipeline settings.
I need to configure lots of different config variables and need to be able to do this via the command line, doing it manually would be too problematic.

A: There is the option:
heroku ci:config:set FROM_EMAIL=$(FROM_EMAIL) --pipeline=my-pipeline


text:
Q: Executing installed batch file in Inno Setup I want the installer to create a service. I usually do this manually just by running the command prompt as an Administrator and going to the location of the .bat file and typing
service.bat install

Is there a way to execute this batch file inside an installer? If so, how? What do I add to my script? The location of this service file is {the location of my installed app}\bin and inside there is this service.bat file that needs to be executed.

A: To execute a batch file in Inno Setup during installation, use the [Run] section entry:
[Run]
Filename: "{app}\bin\service.bat"; Parameters: "install"; Flags: runhidden


text:
Q: What is the difference between the simple past and the passive voice? I always get confused trying to explain the difference between the past tense and the passive voice. If I say something like "The gym opened yesterday" or "The gym was opened yesterday", what would the difference be? Could you say the second example draws more emphasis on the gym itself? In that case, when would it be appropriate to use one of these instead of the other? What do you think?

A: Aside from their names sounding alike, there's no similarity at all between past and passive.
Almost every verb in English has several forms, two tensed and two untensed:

*

*a present tense form (used for infinitive): go, see, learn, say, fold

*a past tense form: went, saw, learned, said, folded

*a present participle form (used for gerund): going, seeing, learning, saying, folding

*a past participle form: gone, seen, learned, said, folded
The present tense is no. 1. The past tense is no. 2. Only. That's all the tenses there are. Every main clause in every English sentence has to have a tense form (either present or past) as the first auxiliary verb (if there is one), or otherwise as the main verb. And that's all there is for the past tense.
Passive, on the other hand, is not a verb form, and doesn't have anything to do with time, present or past. Passive is a Construction, which means it's not just one thing, but a whole bunch of things done together, like driving a car involves more than just turning the wheel.
Passive is something that happens only to transitive clauses, which means the verb has a direct object. So not every sentence can have a passive form; it has to be the right kind of verb and there has to be a direct object. You don't need a specific subject -- indeed, if you are using passive, you probly don't care or even know about the subject. That's the point of the passive construction -- it focusses on the direct object by promoting it to subject in a new sentence:

*

*(Someone) has washed the floor --> The floor has been washed.

*(Someone) gave beer to the guests --> Beer was given to the guests.

*(Someone) gave the guests beer --> The guests were given beer.
In each passive example, the main verb is a type 4 form, immediately preceded by a form of auxiliary be. This auxiliary takes whatever form the main verb of the original transitive clause had: present perfect in the first, and simple past in the last two.
And the nouns move around, too. The object becomes subject, the old subject usually disappears (but it can hang around in a by-phrase if you want). So there's a lot going on, which is the norm with constructions. But not with tenses. Tenses are really simple.


text:
Q: How to fire *ngIf directive for validation when navigating away from input control I am new to Angular and I am making a Reactive Form.
I have a *ngIf directive on an 'em' tag that validates whether the Input text value is valid, if not valid the 'em' tag is supposed to be injected into the HTML and shows "Required"
Required

How can I get this *ngIf to fire each time I move my mouse away from the Input control?
Here is the whole div:

          Last Name:
          Required
          <input formConrolName="lastName" id="lastName" type="text"
          class="form-control" placeholder="Last Name..." />

Here is the validation code in the component:
validateLastName(){
   return this.lastName.valid || this.lastName.untouched
}

I am taking an Angular course on Pluralsight (Angular Fundamentals
by Jim Cooper and Joe Eames) and the course author is able to have his "validateLastName() method on the em tag fire when he navigates away from the control. I don't see where they have any other settings or code that causes the validation to happen, it just seems to happen automatically when they navigate away from the Input.
Any ideas?
Here is the whole HTML code for this component (profile.component.html):

Edit Your Profile

      <form [formGroup]="profileForm" (ngSubmit)="saveProfile(profileForm.value)"
      autocomplete="off" novalidate>

          First Name:
          Required
          <input fromControlName="firstName" id="firstName" (blur)="validateLastName()" type="text"
          class="form-control" placeholder="First Name..." />

          Last Name:
          Required
          <input formConrolName="lastName" id="lastName" type="text"
          class="form-control" placeholder="Last Name..." />

        <button type="submit" class="btn btn-primary">Save</button>
        <button type="button" (click)="cancel" class="btn btn-default">Cancel</button>
      </form>

Here is the component (profile.component.ts):
import { Component, OnInit } from '@angular/core'
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { AuthService } from './auth.service'
import { Router } from "@angular/router"

@Component({
templateUrl: "./profile.component.html",
styles: [`
    em {float-right; color:#E05C65; padding-left: 10px;}
    .error input {background-color:#E3C3C5;}
    .error ::-webkit-input-placeholder { color: #999; }
    .error ::-moz-placeholder { color: #999 }
    .error :-moz-placeholder { color: #999 }
    .error :ms-input-placeholder { color: #999 }
 `]
})
export class ProfileComponent implements OnInit {
  profileForm:FormGroup
  private firstName:FormControl
  private lastName:FormControl
  constructor(private auth:AuthService, private router:Router){
  }

  ngOnInit(){
     this.firstName = new FormControl(
      this.auth.currentUser.firstName, Validators.required)

    this.lastName = new FormControl(
      this.auth.currentUser.lastName, Validators.required)

      this.profileForm = new FormGroup({
      firstName: this.firstName,
      lastName: this.lastName

    })
  }

  saveProfile(formValues){
    console.log("Form is valid: " + this.profileForm.valid)
    if (this.profileForm.valid){
      this.auth.updateCurrentUser(formValues.firstName.value,
       formValues.lastName.value)
      this.router.navigate(["events"])
    }
  }

  validateFirstName(){
    console.log("Is Valid: " + (this.firstName.valid ||
    this.firstName.untouched))
    return this.firstName.valid || this.firstName.untouched
  }

  validateLastName(){
    return this.lastName.valid || this.lastName.untouched
  }

  cancel(){
    this.router.navigate(["events"])
  }
}

A: There are proper methods to handle your case, here is the runnable demo:
two-way binding
Required

   <input type="text" [(ngModel)]="value"/>

  value = "Cattie";
  isLastNameValid() {
    return this.value === "Cattie";
  }

listen blur event
   Required

   <input type="text" #myInput (blur)="validateName(myInput.value)"/>

  isValid = false;
  validateName(value: string) {
    this.isValid = value === "Cattie";
  }

A: This can help: the "mouseleave" event
<input formConrolName="lastName" id="lastName" type="text"
          class="form-control" (mouseleave)="validateLastName()" placeholder="Last Name..." />

Edit: depending upon your Angular version, you may want to try:
(mouseout)="validateLastName()"

A: You can simply use form methods rather than calling a component method like this.
Required

There are multiple flags for each control such as valid, invalid, pristine, touched etc.,. you can play around with the flags directly in HTML template rather than calling a component method to validate your fields.


text:
Q: Create a drop-down menu in a QGIS Processing script? I'm trying to write a QGIS processing script using the new API (3.4), but I hardly find any documentation. Based on this excellent resource by Anita Graser (https://anitagraser.com/2018/03/25/processing-script-template-for-qgis3/), I could manage to set up a basic script that mostly fits my needs.
But I have some fixed-value (eg: ['walking', 'car']) options for which I'd like to include drop-down menus. I assume that I have to use a QgsProcessingParameterString but using the available documentation, I could'nt figure out how to do it.

A: The PyQGIS documentation can be searched for all potential QgsProcessingParameter classes: https://qgis.org/pyqgis/master/search.html?q=QgsProcessingParameter&check_keywords=yes
For your use case, QgsProcessingParameterEnum seems fitting.
Here's a usage example from qgis-latlontools-plugin:
self.addParameter(
    QgsProcessingParameterEnum(
        self.PrmCoordinateOrder,
        tr('Coordinate order when using 1 field'),
        options=[tr('Lat,Lon (Y,X) - Google map order'),tr('Lon,Lat (X,Y) order')],
        defaultValue=0,
        optional=True)
        )


text:
Q: How to display an image along with audio in html/html5? I want to display an image with an audio attachment like an mp3 file. What's the best way to make this work in html5?

A: Something as simple as this?

<audio controls
   src="some_audio.mp3">
   Your browser does not support the audio element.
</audio>

This will display whatever image with an audio track underneath. If you'd like some sort of dynamic interaction with the img+audio you will need to use javascript. I can give an example if that's the case.


text:
Q: How do I stop the form submitting until the end? All I am designing a sign up form with 3 steps:

*

*Enter your name and email

*Select the sector (option 1, option 2)

*Select what your interested in (option 1, option 2, option 3)

Each step is in a row and its hidden with navigation buttons to go to the next or previous step using jQuery, but for some reason when you click next at step 1 it automatically submits the form even though its not the button that would submit your form, the subscribe button is at the end called subscribe, this is a Mailchimp embedded form that I'm having to adapt.

My HTML

    <link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">

        <form action="<formLink>" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Subscribe to our mailing list

                                <input type="text" value="" name="FNAME" class="" id="mce-FNAME" placeholder="Name *">

                                <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Email *">

                            <button name="step1" id="step1">Next</button>

Choose A Sector

                                        <input type="checkbox" value="1" name="group[13][1]" id="mce-group[13]-13-0">

Employment & Skills

                                        <input type="checkbox" value="2" name="group[13][2]" id="mce-group[13]-13-1">

Welfare Services & Social Care

                        <button name="step2b" id="step2b">Back</button><button name="step2" id="step2">Next</button>

Choose A Topic

                                    <input type="checkbox" value="4" name="group[13][4]" id="mce-group[13]-13-2">

News

                                    <input type="checkbox" value="8" name="group[13][8]" id="mce-group[13]-13-3">

Opportunities

                                    <input type="checkbox" value="16" name="group[13][16]" id="mce-group[13]-13-4">

Training & Events

                            <button name="step3b" id="step3b">Back</button>
                            <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

                        <input type="text" name="b_769d2bdcba23fce40f0162f65_817220ff9c" tabindex="-1" value="">

        </form>

My jQuery is pretty straight forward:
btstep1 = $('button#step1'),
btstep2 = $('button#step2'),
btstep2b = $('button#step2b'),
btstep3b = $('button#step3b');

var step1 = $('div.step1');
var step2 = $('div.step2');
var step3 = $('div.step3');

btstep1.click( function(){step1.hide(),step2.show();});
btstep2.click( function(){step2.hide(),step3.show();});
btstep2b.click( function(){step2.hide(),step1.show();});
btstep3b.click( function(){step3.hide(),step2.show();});

https://jsfiddle.net/hpus6r5e/
So my question is how do I stop the form submitting until the end ? when they hit subscribe?

A: Make all navigation buttons type as button (<button type="button">) and the subscribe buttons type as submit (<button type="submit">)
Refer : JS Fiddle

  btstep1 = $('button#step1'),
    btstep2 = $('button#step2'),
    btstep2b = $('button#step2b'),
    btstep3b = $('button#step3b');

  var step1 = $('div.step1');
  var step2 = $('div.step2');
  var step3 = $('div.step3');

  step2.hide();
  step3.hide();

  btstep1.click(function() {
    step1.hide(), step2.show();
  });
  btstep2.click(function() {
    step2.hide(), step3.show();
  });
  btstep2b.click(function() {
    step2.hide(), step1.show();
  });
  btstep3b.click(function() {
    step3.hide(), step2.show();
  });

  $("#testForm").submit(function(e) {
    alert('Form Submitted');
    event.preventDefault();
  });

<form id="testForm">

    Step 1
    <button type="button" id="step1">
      Next
    </button>

    Step 2
    <button type="button" id="step2b">
      Back
    </button>
    <button type="button" id="step2">
      Next
    </button>

    Step 3
    <button type="button" id="step3b">
      Back
    </button>
    <button type="submit">
      Subscribe
    </button>

</form>


text:
Q: Uploading data to shared drive using service account in java I want to upload the files to shared drive using java.
I have created a service account and I have shared the shared-drive (name is DB-Drive) with the service account's address.
Global variables
private static HttpTransport httpTransport;
private static Drive drive;

Main function (initialize and listing of the files)
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    Credential credential = authorize();
    drive = new Drive.Builder(httpTransport, JacksonFactory.getDefaultInstance(), credential).setApplicationName(
                    "Quickstart").build();

    uploadFile();

    FileList result = drive.files().list().execute();
    List<File> files = result.getFiles();
    if (result == null || result.isEmpty()) {
        System.out.println("No files found.");
      } else {
        System.out.println("Files:");
        for (File file : files) {
             System.out.printf("%s %s \n", file.getName(),file.getId());
                }
            }
        }

Authorization code
        GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("resources/credentials.json"))
                .createScoped(Collections.singleton(DriveScopes.DRIVE_FILE));

        return credential;

Uploading code
 String folderId = "***DB-Drive id****";
        File fileMetadata = new File();
        fileMetadata.setName("photo.jpg");
        fileMetadata.setParents(Collections.singletonList(folderId));
        java.io.File filePath = new java.io.File("/home/*****/Downloads/qck_1552369371.jpeg");
        FileContent mediaContent = new FileContent("image/jpeg", filePath);
        File file = drive.files().create(fileMetadata, mediaContent)
                .setFields("id, parents")
                .execute();
        System.out.println("File ID: " + file.getId());
        return file;

I am setting DB-Drive which is the teamdrive or the shareddrive as the parent of the uploaded file but still I am not able to view this in the shared drive folder.. Please help me with this.
I am adding the complete flow :-
1.) I create the service account using the steps mentioned at https://developers.google.com/identity/protocols/oauth2/service-account
I selected the project and gave the description and everything.
2.) I did'nt gave domain level delegation to service account rather I shared the DB-drive(team drive) with service account address (which was mentioned in credentials.json file as client_email *****.gserviceaccount.com)
3.)  Then I used the above code to upload the file asking service account to upload the file to shared drive i.e DB-Drive by specifying the DB-Drive's id as the parent id of the file.
4.) but still the file is getting uploaded to service account's drive it is not getting linked to shared drive.
5.) DB-Drive is the parent folder (the only folder).
Any leads would be a great help.

A: As @ziganotschka points out you need to set supportsAllDrives to true if creating a file in a shared drive. The Java client's setSupportsTeamDrives option is deprecated. Instead use setSupportsAllDrives to true.

When you have troubles uploading a file with a service ccount to a shared Drive, you should take the following steps for troubleshooting:

*

*Isolate the problem

*Ask yourself - is the problem related to the usage of the service account or something else?

*For this, test the same request without a service account

*If the service account turns out to be the culpit

*

*Verify that you enabled domain-wide delegation correctly in the GCP console

*Verify that you provided the correct scopes to the delegated service account in the Admin console

*Verify that your code implementation is correct

*If the problem is not service account related - verify either it is code syntax related or request related

*For this,  use the Try this API tool to test your request without coding

*

*If the issue is coding related - debug your code

*If the issue is request related, act according to the error the Try this API returns you

*If you receive a 404 File not found error - it either means that

*

*the file is located on a shared Drive (in this case you have to set supportsAllDrives to true as mentioned above)

*or the fileId is not correct

*Or the file is not accessible to the account you use for authentication


text:
Q: Maven compiler not adding getters/setters(generated using Lombok) to the build jar file I have the below Pojo class to which I have added the @Data from Lombok.
The Project is working fine in Eclipse IDE, and I can even see the getters/setters in the outline window of IDE. But, when I am running mvn clean install or Run As Maven Install from IDE, the jar file gets generated without any error, but there are no methods(getters, setters, equals, hashcode) which are generated by the Lombok.

Since, IDE is showing the methods, there must be some issue with the maven compiler plugin in the POM file. I tried every possible solution from SO, but nothing worked.
Here is the POM:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test-boot</name>
    <description>Demo project</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>1.3.0.Final</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgument>-proc:none</compilerArgument>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>${lombok.version}</version>
                        </path>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>1.3.0.Final</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
        </plugins>

    </build>

</project>

I have pushed the test project to the Github. Can be cloned from here: https://github.com/Puspendert/test-lambok.git
Update: To verify if the generation of getter/setter would effect anything, I changed the main method:
@SpringBootApplication
public class TestBootApplication {

    public static void main(String[] args) {
        User user = new User();
        user.setName("hero");
        System.out.println(user.getName());

    }
}

and boom, as expected the project gave compilation error on mvn clean install:
[INFO] Building test-boot 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ example ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ example ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 3 source files to /Users/puspender/git/test-lambok/test-boot/target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /Users/puspender/git/test-lambok/test-boot/src/main/java/com/example/TestBootApplication.java:[11,21] cannot find symbol
  symbol:   method setName(java.lang.String)
  location: variable user of type com.example.User
[ERROR] /Users/puspender/git/test-lambok/test-boot/src/main/java/com/example/TestBootApplication.java:[12,40] cannot find symbol
  symbol:   method getName()
  location: variable user of type com.example.User
[INFO] 2 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE

Please suggest, what could be wrong here?

A: You are explicitly disabling annotation processing!
<compilerArgument>-proc:none</compilerArgument>
Remove this line - lombok is an annotation processing library after all - and everything (should) work file
EDIT: for fairness, there's another deleted answer (for some reason) which also suggests that


text:
Q: Approaching the circumference of a circle We had a lengthy discussion yesterday, on how to prove that the circumference of a circle is $2\pi r$. By using google, the most commonly found proof starts in the following way.
"Consider the regular n-gon inside the circle touching the circle at its vertices, and the regular n-gon outside the circle touching the circle at its edges. Then the circumference of the inner n-gon is smaller than the circumference of the circle, which is smaller than the circumference of the outer n-gon."
While this apparently is true for n-gons, it is not true for arbitrary geometric shapes inside and outside the circle. So we conjectured it was the convexity of the n-gon that is of importance. Which leads to the question:
Let $C$ be a circle with radius $r$, and $A_n$ be a family of convex sets with $A_n \subset C$ for each $n$. If, for $n \rightarrow \infty$, the volume of these sets converges to $\pi r^2$ (the volume of $C$), will the circumference necessarily converge to $2\pi r$?

A: Yes.
If you don't mind, I'll do the problem in $\mathbb R^d$.  Write $B_2^d$ for the unit Euclidean ball (centred at the origin, radius 1).  Let $A_n$, as before, be a sequence of convex subsets of $B_2^d$ with $V(A_n)\to V(B_2^d)$, where $V(\cdot)$ denotes volume.  Write
$$ V_1(K,B_2^d) = V(\underbrace{K,\dotsc,K}_{d-1},B_2^d) $$
for that mixed volume.  I will use the following facts about mixed volume:

*

*$V_1(K,K) = V(K)$

*$V_1(K,L)$ is increasing in both arguments.

*The surface area of a convex body $K$ is
$$ S(K) = \lim_{\epsilon\downarrow 0} \frac{V(K+\epsilon B_2^d) - V(K)}{\epsilon} = dV_1(K,B_2^d) $$
(where $K+\epsilon B_2^d$ is the Minkowski sum).

*Minkowski's first inequality:
$$ V(K)^{(d-1)/d} V(L)^{1/d} \le V_1(K,L) $$

Using (4), then (2) (we assumed $A_n\subset B_2^d$), then (1) yields
$$ V(A_n)^{(d-1)/d} V(B_2^d)^{1/d} \le V_1(A_n,B_2^d) \le V_1(B_2^d,B_2^d) = V(B_2^d) $$
Sending $n\to\infty$ yields, by the squeeze law,
$$ \lim_{n\to\infty} V_1(A_n,B_2^d) = V(B_2^d) = V_1(B_2^d,B_2^d) $$
Multiplying by $d$ and using (3) twice yields
$$ \lim_{n\to\infty} S(A_n) = S(B_2^d) $$
as desired.


text:
Q: input and print don't like parentheses I have working knowledge of Python3, but I'm trying to adapt to a work environment that uses 2.7.2. Trying basic things, I can't get either input or print actions to work.
In 3.6.8 this works like so:
>> foo=("seven")
>> print("She lives with", foo, "small men")
She lives with seven small men

In my unix environment with 2.7.2, any variation using parentheses gives me a syntax error "(' is not expected". I can print without (), but I can't seem to find a way that works to assign and/or print the variable foo.
>> foo="seven"
>> print "She lives with", foo, "small men"
She lives with, foo, small men

Enclosing foo in the print statement with () [] {} or ++ all simply print whatever is typed into the code after "print".
Any help is appreciated.

A: This turned out to be an even simpler newbie problem and fix. In the unix environment, the script needs to be preceeded with "python" at the command line. I was lulled into complacency by working in Windows previously, where the command line only required the name of the script. (Windows applies some voodoo to know to run it as python, where in unix, that'snot the case.)
Saving the same code as "foo.py" and run command with "python" yields the correct result:
=> python foo.py
She lives with seven small men

Thanks for humoring a sheepish newbie.


text:
Q: PermissionError: [Errno 13] Permission denied trying to save an excel file with python I am trying to write some data and save it in an excel sheet, so I used openpyxl, it worked its way to access the file, write the data, but not saving the file, the problem is that it did save but the terminal threw an error that stopped the program.
Code:
self.wb = lw(f'{self.view.path.text()}')
self.ws = self.wb.active
*******writing some data************
self.wb.save(f'{self.view.path.text()}')

Error:
PermissionError: [Errno 13] Permission denied

I tried excuting this command that is supposed to give my program access, but didn't work, or I did it wrong
chown admin:admin filename.xlsx

A: The solution was to close the excel file if it is opened cause it can't give the program permission while I am using the file


text:
Q: TypeScript compiler API: typeChecker.typeToString() vs. Playground tooltips Example:
const red = Symbol('red');
const green = Symbol('green');
type TColor2 =
  | typeof red
  | typeof green
;

Getting a description for the type whose alias is TColor2:

*

*Playground tooltip: 'typeof red | typeof green'

*Compiler API: 'TColor2'
Approach:
// node is either ts.TypeAliasDeclaration or ts.TypeNode
const type = typeChecker.getTypeAtLocation(node);
const typeName = typeChecker.typeToString(type, node);

Is there a way to get the text of the Playground tooltip via the compiler API?

A: You can pass TypeFormatFlags.InTypeAlias flag to typeToString:
typeChecker.typeToString(type, node, TypeFormatFlags.InTypeAlias);

Then it will print typeof red | typeof green


text:
Q: Phone Gap external HTML intergration I have built an application using phone gap, and plan to release the app for Apple iOS and Android OS.
The app it's self is fairly simple, and is essentially a glorified HTML website with a few jQuery mobile add-ins for slide functionality etc.
The client have an existing document management system which under request I have amended to be compatible for mobile displays. This being so that users can write notes and save them directly into the system from their phones.
The web document management system is restricted by login and locked out to a select group of static IPs, and because the App is going public, the want the functionality with the database to be limited to the same contraints as the web system...
To all intents and purposes, they want it to be an iframe within the app. So hey, this is what I did... iFrame complete and hey presto works a dream, oh wait, non of the form features work. I can't file upload or anything like this :/
So I tried using  but no such luck here :/ same issues.
Over the weekend I looked into http://docs.phonegap.com/en/2.2.0/guide_cordova-webview_android.md.html but this looks to be completely in the wrong direction.
I've been looking all weekend for iFrame alternatives that will retain functionality, and am still looking as we speak.
Can I emphasise that this functionality works in the web system on Chrome for Android, Android native browser and also iOS's safari browser.
I essentially need a way of creating something like an iframe, but with the functionality of the native browsers :/ = bamboozled...


text:
Q: JavaScript - Compare dates I have a question for you guys. I want to compare the date of today and an other self made date. The date of today is called a and the name of the self made date is b. If ais later then b I want to do something, but how. And the date format should be year,month,day,hour,minute,second e.g: 2015,03,20,09,58,44

A: // First date is older

var a = new Date(2015,03,20,09,58,44).valueOf(),
b = new Date(2015,04,20,09,58,44).valueOf();

console.log((a > b), (a < b), (a === b)); // false, true, false

// Second date is older

var c = new Date(2015,03,20,09,58,44).valueOf(),
d = new Date(2015,02,20,09,58,44).valueOf();

console.log((c > d), (c < d), (c === d)); // true, false, false

// Same date

var now = new Date().valueOf(),
now2 = new Date().valueOf();

console.log((now > now2), (now < now2), (now === now2)); // false, false, true

// As a function

function isLater(a, b) {
    a = a.valueOf();
    b = b.valueOf();

    if (a > b) {
        return true;
    } else if (a < b) {
        return false;
    } else if (a === b) {
        // edge case
    }
}


text:
Q: Invert raster's min with max values (as well as the in between values) and vice versa using R I have a raster with pixel values, 1 to 255 (no decimals). I want to invert their values in a way that pixels with value 1 will get value of 255, pixel with value 2 will get 254, pixel with value 3 will get 253 and vice versa (255 will become 1 and so on). Is is possible to achieve that in R? Unfortunately, I couldn't find any example. My data:
dput(is)
new("RasterLayer", file = new(".RasterFile", name = "C:\\Users\\Geography\\Desktop\\step\\imper_surf.tif",
    datanotation = "INT1U", byteorder = "little", nodatavalue = -Inf,
    NAchanged = FALSE, nbands = 1L, bandorder = "BIL", offset = 0L,
    toptobottom = TRUE, blockrows = 11L, blockcols = 717L, driver = "gdal",
    open = FALSE), data = new(".SingleLayerData", values = logical(0),
    offset = 0, gain = 1, inmemory = FALSE, fromdisk = TRUE,
    isfactor = FALSE, attributes = list(), haveminmax = TRUE,
    min = 0, max = 255, band = 1L, unit = "", names = "imper_surf"),
    legend = new(".RasterLegend", type = character(0), values = logical(0),
        color = logical(0), names = logical(0), colortable = logical(0)),
    title = character(0), extent = new("Extent", xmin = 582758.61,
        xmax = 604268.61, ymin = 1005774.596, ymax = 1047384.596),
    rotated = FALSE, rotation = new(".Rotation", geotrans = numeric(0),
        transfun = function ()
        NULL), ncols = 717L, nrows = 1387L, crs = new("CRS",
        projargs = "+proj=lcc +lat_0=18.88015774 +lon_0=76.75 +lat_1=16.625 +lat_2=21.125 +x_0=1000000 +y_0=1000000 +datum=WGS84 +units=m +no_defs"),
    history = list(), z = list())

A: You can just use a bit of algebra to compute the new pixel values in the inverted raster. Namely, you want to subtract the values from the max value (here it is 256). Try something like this:
library('raster')

r <- raster('image.jpg')

r_inverse = r

values(r_inverse) <- 256 - values(r)

plot(r)

plot(r_inverse)


text:
Q: How to generate multiple files from a search by date? I have the following situation, in the database the content column where the entire structure of an XML file is stored.
I need to make it generate multiple files according to the amount of records.
Example: If on 02/07/2019 there are 08/02/2019 you have 100 records, I want you to generate 100 files.
The way I'm doing it, it's generating 1 file, with 100 information inside.
The code I created today is the one I can't think of how to generate by registration.
<?php
    header('Content-Type: application/xml; charset=utf-8');
    header("Content-disposition: attachment; filename=TestXML.xml");

    $data1 = '2019-02-07';
    $data2 = '2019-02-08';
    $pdo = new PDO("mysql:host=localhost;dbname=73519225000122", "root", "");

    $buscar = $pdo->prepare("SELECT conteudo FROM xml WHERE modelo = '55' AND data_gravacao BETWEEN date('$data1') AND date('$data2')");
    $buscar->execute();
    $linha = $buscar->fetchAll(PDO::FETCH_COLUMN);

    foreach ($linha as $key => $value) {
        echo count($key);
    }
?>

A: so, after understanding, you'd have something like that ..
  $dirPath="xxxxw/whereyouwant/tmpxxx";

  $generated=arrray(); // or =[];
  foreach ($linha as $key => $value) {
        $content=$value['content'];
        $fileName=$dirPath.'/fileBaseName'.$key;
        $result=file_put_contents ($fileName , $content);
        if ($result===FALSE) {
          // handle error, throw exception, etc...
        } else {
            $generated[]=$fileName; // remember this file
          }
  }

  // then zip all (but it's another problem...
  // you have now a $generated array with all files to zip and send..


text:
Q: Python click: subcommand from partial func Say I have a function created not by def but by a partial() call (or even just by assignment).  In the example below, how can I add bar as a click sub-command to the cli group?  I can't use the decorator approach (as with foo).  My failed approaches are shown below in-line.
import functools
import click

@click.group()
def cli():
    pass

@cli.command()
def foo(myname="foo"):
    print(f"I am {myname}")

bar = functools.partial(foo, myname="bar")

# this has no effect
# cli.command(bar)

# results in: AttributeError: 'functools.partial' object has no attribute 'name'
# cli.add_command(bar)

# results in: AttributeError: 'functools.partial' object has no attribute 'hidden'
# cli.add_command(bar, name="bar")

if __name__ == "__main__":
    cli()

UPDATE: Actually, it looks like the partial is the culprit here.  This answer in a different but related thread, points out that partial objects are "missing certain attributes, specifically __module__ and __name__".

A: I think you're missing the fact that the @command decorator turns the foo function into a Command that uses the original foo as callback. The original function is still accessible as foo.callback but foo is a Command. Still, you can't use a partial object as callback because it lacks __name__, but you can work around that passing the name explicitly:
bar = functools.partial(foo.callback, myname="bar")
cli.command("bar")(bar)

# Alternative:
cli.add_command(click.Command("bar", callback=bar))


text:
Q: WPF animation does not trigger iff animating Opacity from 0.0 I would like to fade in/out animate FontAwesome.WPF spinner icon when it starts/stops spinning. Luckily, MSDN provides almost identical example how to Trigger an Animation on Property Change which uses IsMouseOver. Chaning the property to icon's Spin and opacity to 0.0 should be straightforward:
<CheckBox x:Name="IsExecuting"/>
<fa:ImageAwesome xmlns:fa="http://schemas.fontawesome.io/icons/"
                 Icon="Refresh" Height="8" Width="8"
                 Spin="{Binding IsChecked, ElementName=IsExecuting}">
    <fa:ImageAwesome.Style>
        <Style TargetType="{x:Type fa:ImageAwesome}">
            <Setter Property="Opacity" Value="0.0" />
            <Style.Triggers>
                <Trigger Property="Spin" Value="True">
                    <Trigger.EnterActions>
                        <BeginStoryboard>
                            <Storyboard>
                                <DoubleAnimation Storyboard.TargetProperty="Opacity" To="1" Duration="0:0:1" />
                            </Storyboard>
                        </BeginStoryboard>
                    </Trigger.EnterActions>
                    <Trigger.ExitActions>
                        <BeginStoryboard>
                            <Storyboard>
                                <DoubleAnimation Storyboard.TargetProperty="Opacity" To="0.0" Duration="0:0:1" />
                            </Storyboard>
                        </BeginStoryboard>
                    </Trigger.ExitActions>
                </Trigger>
            </Style.Triggers>
        </Style>
    </fa:ImageAwesome.Style>
</fa:ImageAwesome>

But it does not work - nothing happens at all, spinner is invisible regardless of Spin property value. Curiously, the fade in/out works flawlessly, as long as the 'hidden' Opacity is not 0, i.e. if I rolled back to 0.25 as in MSDN example, it would work.
What is the problem here and how can I fix it?


text:
Q: Check whether the series converges I want to check if the series $$\sum_{n=0}^{\infty}\left (\frac{3n+1}{4n+1}\right )^{(-1)^nn}$$ converges or not.
I tried to apply the root test and I got the following: Let $a_n:=\left (\frac{3n+1}{4n+1}\right )^{(-1)^nn}$
We have that $$\sqrt[n]{|a_n|}=\sqrt[n]{\left |\left (\frac{3n+1}{4n+1}\right )^{(-1)^nn}\right |}=\sqrt[n]{\left (\frac{3n+1}{4n+1}\right )^{(-1)^nn}}=\left (\frac{3n+1}{4n+1}\right )^{(-1)^n}$$
Can we continue from here? Or do we have to apply an other convergence criterium?

A: A necessary condition for convergence is: $\lim \limits_{n \to \infty} a_{n} = 0$, which is clearly not the case here. So the series will not converge.
In other words it won't converge because every term is positive and for all $n = 2k+1$,  $a_{n} > 1$, so you are adding at least 1 infinitely many times to your sum.

A: For $\sum a_n$ to converge we need $a_n\to 0$.
This is not the case here since for $n$ odd then $a_n=\left(\dfrac{4n+1}{3n+1}\right)^n\ge 1$
So the series is not convergent.


text:
Q: Using $\ln(e+x)$ to approximate $\ln(e+x^2)$ I made a MacLaurin series which was $\displaystyle1+\frac{x}{e}-\frac{x^2}{2e^2}+\frac{x^3}{3e^3}\dots$
I had to use the first three terms of this series to approximate $\displaystyle\int_0^1 \ln(e+x^2)\,dx$.
So I just went with my gut instinct and plugged $x^2$ for $x$ in $\displaystyle\int_0^1 \left (1+\frac{x^2}{e} - \frac{x^4}{2e^2} \right)\,dx$
I got $\displaystyle1+\frac{3}{e}-\frac{1}{10e^2}$.
I checked in the answer manual and it was right. However, why is it valid to substitute $x^2$ for $x$? Is it because $x^2$ and $x$ are close on the interval $(0,1)$?

A: There is no coincidence here. If you have a function $f$ given by a power series $$f(x)=a_0+a_1x+a_2x^2+\cdots$$then the function $f\circ g$ is given by
$$
f(g(x))=a_0+a_1g(x)+a_2(g(x))^2+\cdots
$$In your case, $f(x)=\ln(e+x)$ and $g(x)=x^2$.
Of course, if the series for $f$ has a finite radius of convergence, then the above series for $f\circ g$ only works whenever $g(x)$ is within that radius. And if you instead insert a series for $g$ and expand using the binomial theorem, then you have to take into account the radius of convergence of that series too.

A: Hint: If $|x|<1$, then $|x^2|\leq |x|<1$. Think about the radius of convergence.


text:
Q: How to validate an input date from individual day, month, year input in Laravel 5 I have a user registration form which takes input birth day split in 3 different input fields i.e. day, month, year
{!! Form::selectMonth('month', null) !!}
{!! Form::selectRange('day', 1, 31, null) !!}
{!! Form::selectYear('year', Carbon\Carbon::now()->year, (new Carbon\Carbon('100 years ago'))->year, null) !!}

In the backend I have modified the Registrar.php/validator() to check the input date is a valid one:
public function validator(array $data) {

    $data['date_of_birth'] = Carbon::create($data['year'], $data['month'], $data['day'], 0, 0, 0)->toDateString();
    $current_year          = Carbon::now()->year;
    $hundred_years_ago     = (new Carbon("100 years ago"))->year;

    return Validator::make($data, [
        'year'          => 'Required|Integer|Between:'.$hundred_years_ago.','.$current_year,
        'month'         => 'Required|Integer|Between:1,12',
        'day'           => 'Required|Integer|Between:1,31',
        'date_of_birth' => 'Required|Date',
    ]);

}

But surely it doesn't check if an invalid date was provided. If the user provides an invalid date such as 31st February, 1982, the Carbon::create() transforms the date to 3rd March, 1982 which turns out to be a valid one.
If I want to filter this type of date input what do I need to do? I do believe this is likely a very common requirement for those who don't use any datepicker of some sort.

A: Laravel using the strtotime and checkdate functions to validate a date.
How the validateDate function of Laravel works? An example:
strtotime('30-2-2015'); // returns a timestamp
checkdate(2, 30, 2015); // returns false
// laravel raises an error

Therefore, the value of $data['date_of_birth'] should be a string in a particular format.
public function validator(array $data)
{
    $data['date_of_birth'] = $data['day'].'-'.$data['month'].'-'.$data['year'];
    $current_year          = Carbon::now()->year;
    $hundred_years_ago     = (new Carbon("100 years ago"))->year;

    return Validator::make($data, [
        'year'          => 'Required|Integer|Between:'.$hundred_years_ago.','.$current_year,
        'date_of_birth' => 'Required|Date',
    ]);
}

Also you can ignore the validation of day and month, since the date will be validated.