text:
Q: Prove $\frac{a}{1+b^2}+\frac{b}{1+c^2}+\frac{c}{1+d^2}+\frac{d}{1+a^2} \ge 2$ if $a+b+c+d=4$
if $a,b,c,d$ are positive real numbers that $a+b+c+d=4$,Prove:$$\frac{a}{1+b^2}+\frac{b}{1+c^2}+\frac{c}{1+d^2}+\frac{d}{1+a^2} \ge 2$$
  Additional info:I'm looking for solutions and hint that using Cauchy-Schwarz and AM-GM because I have background in them.

Things I have done: Using AM-GM $$LHS=\sum\limits_{cyc}\left(a-\frac{ab^2}{1+b^2}\right)\ge \sum\limits_{cyc}\left(a-\frac{ab^2}{2b}\right)=\sum\limits_{cyc}a-\frac{1}{2}(ab+bc+cd+da)$$
So it lefts to Prove that $$\sum\limits_{cyc}a-\frac{1}{2}(ab+bc+cd+da)\ge 2$$
If I show that $ab+bc+cd+da \le4$ then the upper inequality will be true.But I have problem in showing that.

A: You could continue using AM-GM
$$ab + bc + cd + da = (a+c)(b+d) \le \frac{(\overline{a+c}+\overline{b+d} )^2}4 = 4$$

A: For your missing step, just observe
$$
(a+b+c+d)^2-4(ab+bc+cd+da)=(a-b+c-d)^2\geq 0\\
\implies ab+bc+cd+da\leq\frac{4^2}{4}=4.
$$


text:
Q: Representación gráfica en Eclipse EDITO CON LA SOLUCIÓN (LA HE ENCONTRADO AL TIEMPO)
Buenas estoy intentando representar unos valores que me llegan de un dispositivo en una gráfica, para ver como varían, el código donde se encuentra el Main es:
public class Servidor {
private static double aceleracion;

public static void main(String args[]) throws Exception{

    try {
            //Obtención de la aceleración total
            aceleracion= Math.sqrt(Math.pow(x, 2)+Math.pow(y, 2)+Math.pow(z, 2));
            senal.add(aceleracion);//pasar los datos a un ArrayList
            System.out.println(aceleracion);

            GraficaMagnitud gm=new GraficaMagnitud("Aceleracion");
            gm.addValue(aceleracion);
    }

     } catch (IOException ex) {
            System.err.println(ex.getMessage());
        }
    }
}

Y donde se encuentra GraficaMagnitud, con el código correcto:
public class GraficaMagnitud extends javax.swing.JFrame{
private static final long serialVersionUID = 1L;
private XYSeries aceleracion;
private JFreeChart chart;
public GraficaMagnitud(ArrayList<Double> aceleraciones, String title) {
    aceleracion = new XYSeries("Aceleracion");
    XYSeriesCollection xyDataset = new XYSeriesCollection();
    xyDataset.addSeries(aceleracion);
    for(Double er : aceleraciones) aceleracion.add(aceleracion.getItemCount(), er);
    chart = ChartFactory.createXYLineChart(title,"Muestras", "aceleracion", xyDataset);
    ChartPanel chartPanel = (ChartPanel) createDemoPanel(chart);
    if(chartPanel != null){
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        chartPanel.setRangeZoomable(true); chartPanel.setDomainZoomable(true);
        setContentPane(chartPanel); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
        RefineryUtilities.centerFrameOnScreen(this); this.setVisible(true);
        }
    }
private JPanel createDemoPanel(JFreeChart chart) {
    try{
        if(chart != null){
            ChartPanel panel = new ChartPanel(chart);
            panel.setFillZoomRectangle(true);
            panel.setMouseWheelEnabled(true);
            return panel; }else return null;
        }catch(Exception e){
            e.printStackTrace();
            return null;
            }
    }
}

Ya se dibuja bien la gráfica como veis
Edito más que nada por si a alguien alguna vez le surge el mismo problema o parecido y pueda ayudarse en mi código para guiarse
Un saludo

redpajama_set_name: RedPajamaStackExchange


text:
Q: does it worth switching a PRIMARY KEY from the type NVARCHAR to the type INT? On our SQL SERVER 2008 R2 database we have an COUNTRIES referential table that contains countries. The PRIMARY KEY is a nvarchar column:
create table COUNTRIES(
   COUNTRY_ID nvarchar(50) PRIMARY KEY,
   ... other columns
)

The primary key contains values like 'FR', 'GER', 'US', 'UK', etc. This table contains max. 20 rows.
We also have a SALES table containing sales data:
create table SALES(
    ID int PRIMARY KEY
    COUNTRY_ID nvarchar(50),
    PRODUCT_ID int,
    DATE datetime,
    UNITS decimal(18,2)
    ... other columns
)

This sales table contains a column named COUNTRY_ID, also of type nvarchar (not a primary key). This table is much larger, containing around 20 million rows.
Inside our app, when querying on the SALES table, we filter almost every time on the COUNTRY_ID. Even like this it takes too long to perform most of aggregation queries (even with the proper indexes in place)
We're in a development phase to improve the query performance on the SALES table. My question is:
Does it worth switching the COUNTRY_ID type from nvarchar(50) to the type int? If  the column COUNTRY_ID is converted in both tables to the type int, can I expect a better performance when joining the two tables?

A: I would personally recommend changing COUNTRY_ID from nvarchar(50) to an INT. An int uses 4bytes of data and is usually quicker to JOIN than VARCHAR.
You can also check to see if the space used is reduced by using the stored procedure sp_spaceused
EXEC sp_spaceused 'TableName'


text:
Q: Can't read from xml into an <> using linq, get nulls I have an XML file:
<?xml version="1.0" encoding="us-ascii"?>
<TestItems xmlns="http://www.blogger.com">
  <TestItem correct="0" incorrect="0">
    <Question>question</Question>
    <Answer>answer</Answer>
    <Tags>test1;test2</Tags>
  </TestItem>
  <TestItem correct="0" incorrect="0">
    <Question>question3</Question>
    <Answer>answer3</Answer>
    <Tags>tagA;tagB;tagC</Tags>
  </TestItem>
</TestItems>

I also have an object:
class TestItem
{
    public string Question { get; set; }
    public string Answer { get; set; }
    public int NumberCorrect { get; set; }
    public int NumberIncorrect { get; set; }
    public string Tags { get; set; }
}

And here is the code that I use to read the data into memory:
XDocument ktdb = XDocument.Load("KTdb.xml");

XNamespace ns = ktdb.Root.Name.Namespace;

var testItems = from item in ktdb.Descendants(ns + "TestItem")
    select new TestItem
    {
        Question = item.Element(ns + "Question").Value,
        Answer = (string)item.Element(ns + "Answer").Value,
        Tags = item.Element(ns + "Tags").Value,
        NumberCorrect = Convert.ToInt32(item.Attribute(ns + "correct").Value),
        NumberIncorrect = Convert.ToInt32(item.Attribute(ns + "incorrect").Value)
    };

But it would not let me do that. When the LINQ statement is executed, the default constructor is called on the TestItem object, and then I get the null exception because  item.Element(ns + "Question").Value is null.
Why do I get the error? How do I fix my code?
Thanks.

A: Change this:
NumberCorrect = Convert.ToInt32(item.Attribute(ns + "correct").Value),
NumberIncorrect = Convert.ToInt32(item.Attribute(ns + "incorrect").Value)

To this:
NumberCorrect = Convert.ToInt32(item.Attribute("correct").Value),
NumberIncorrect = Convert.ToInt32(item.Attribute("incorrect").Value)

i.e. Remove the concatenation of ns from the attribute name.


text:
Q: How to use global variable - Flutter How to use global variable in dart/flutteer?
class UserPage extends StatefulWidget {
  // UserPage({Key key}) : super(key: key);
  final int userId; //my variable

  UserPage({@required this.userId});

  @override
  UserPageState createState() => UserPageState();
}

I want use this variable like a parameter in my method in url
Future<User> getCurrentUser() async {
    var url = 'http://10.0.2.2:80/user/';
    var response = await http.get(url);

    print(response.statusCode);

    if (response.statusCode == 200) {
      var userJson = json.decode(response.body);
      print(userJson);
      return User.fromJson(json.decode(response.body));
    } else {
      print('dupa');
      // throw Exception('Failed to load post');
    }
  }

A: If you want to access an instance variable inside the method of the state class, you can use widget.variableName. So here you can use widget.userId and you can define your url as below:
Future<User> getCurrentUser() async {
    var url = 'http://10.0.2.2:80/user/${widget.userId}';
    var response = await http.get(url);

    print(response.statusCode);

    if (response.statusCode == 200) {
      var userJson = json.decode(response.body);
      print(userJson);
      return User.fromJson(json.decode(response.body));
    } else {
      print('dupa');
      // throw Exception('Failed to load post');
    }
  }

A: you can use the widget variable that is available inside state classes,
in your case you can aceess the userId using
 Future<User> getCurrentUser() async {
    var url = 'http://10.0.2.2:80/user/{widget.userid}';
    var response = await http.get(url);

    print(response.statusCode);

    if (response.statusCode == 200) {
      var userJson = json.decode(response.body);
      print(userJson);
      return User.fromJson(json.decode(response.body));
    } else {
      print('dupa');
      // throw Exception('Failed to load post');
    }
  }


text:
Q: Process State Diagram : Transition of a process from Suspend Wait to Suspend Ready? Lets say a process is in Suspend Wait state waiting for its i/o to complete . Whenever its i/o gets completed the state of the process changes to Suspend Ready.
Will the process inside Ready but Suspended state be considered to be in the Ready queue and will it participate in the process scheduling competition along  with other processes which are already in the Ready Queue.

A: No. The process will be in the suspend ready queue from which only the medium term scheduler will pick up and put it in the ready queue. From there the short term scheduler will pick it and give to the CPU for processing.
https://www.geeksforgeeks.org/gate-notes-operating-system-process-management-introduction/

A: one thing that you need to understand that computer science is not mathematics and lot of terms that we use often are not clearlly defined. same is the case with the process states you describe above.
that being said, generally when a process completes its IO then it moves directlly to ready queue


text:
Q: Printing a reverse list in python In the following code I got None, why ?
Thanks,
numbers = [10, 15, 20, 30]
print(numbers)
print(numbers.reverse())
numbers.reverse()
print(numbers)

A: If you look at that operation in the documentation of the Mutable Sequence Types, you will see this note:

The reverse() method modifies the sequence in place for economy of space when reversing a large sequence. To remind users that it operates by side effect, it does not return the reversed sequence.

So numbers.reverse() won't return anything but will still change the order of the list.


text:
Q: Visual Studio 2013 Professional linker errors I really want to use Visual Studio Professional's debugger to take a look at a segmentation fault I encountered in my program. However, the IDE would not compile even a simple program such as this:
// test_aug.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
     cout << "Test" ;
     return 0;
}

It keeps throwing the error "error LNK1104: cannot open file 'gdi32.lib'.
The thing is I don't want to fix this one linking error just to keep getting more for different libraries (I have also seen it for different libraries).
Can someone please tell me how to fix this error in general so I will not encounter it anymore, and can move on to ACTUALLY DEBUGGING.

A: If the linker cannot find that library check for its existence and/or set the path to find it into additional library directories.
The linking phase won't go on without solving that error first.
Other two thoughts:

*

*gd123.lib sounds wrong, I believe you wanted to use gdi32.lib. Make sure the name is right

*make sure that is included into the Windows SDK (express editions don't include it)


text:
Q: Does this count as a one way function? So I was simply reading up on the P=NP problem and in the article it said that the existence of a one way function would imply that P does not equal to NP.
Of course I read up on it since it was interesting and the definition, at least from my gatherings, is that it is a function that is easily evaluated but not easily inverted roughly speaking.
Well I was mulling it over and I thought about something. Suppose I have a function f that I call a game, that maps natural numbers n to a set A which contains all possible positions the pieces on a chessboard may take.
Define a game to be a function that takes in the number of moves n as an input, and the state the chessboard is in as an output, and that the state of the board evaluated at input n can be legally reached in one move from the state evaluated at input n-1.
Obviously such a function is 'easy' to evaluate but given any possible state of a chessboard, there are a multitude of ways to reach it and thus it is definitely much more difficult to evaluate the number of moves required to reach it.
Does such a function count as a one way function?
Btw I don't know how to tag this so please help if you do thanks.


text:
Q: MVC Owin Identity Linking multiple social accounts to a single user I have MVC website that have MVC Owin Identity login.
So user can access my website using social networks.
Now I want to allow users connect more than one social network to there accounts.
e.g.
User registered using Facebook on my website.
During registration new local user was created for him with Facebook UserLogin connection.
Now on user's profile page I want to add other socials and show already connected socials.
How to do this using MVC Owin Identity?

A: my solution was easy.
I just check if user is logged in and attach new social to him.
    public async Task<ActionResult> Callback(string provider)
    {
        var externalLoginInfo = await _applicationSignInManager.AuthenticationManager.GetExternalLoginInfoAsync();
        if (externalLoginInfo == null)
        {
            return RedirectToAction("Index", "SignIn");
        }

        // Check if the user with this external login provider already has a login
        if (await _applicationSignInManager.UserManager.FindAsync(externalLoginInfo.Login) != null) return RedirectToAction("Index", "Social");

        await _applicationSignInManager.UserManager.AddLoginAsync(HttpContext.GetOwinContext().Authentication.User.Identity.GetUserId<long>(), externalLoginInfo.Login);

        return RedirectToAction("Index", "Social");
    }


text:
Q: php if-else failing What is wrong with this if-else statement.
if((strlen($objectData['pss'] >= 8))AND(strlen($objectData['pss'] <= 20)))
{
  //do my bidding
}
else
{
  echo "String to short or to long";
}

Ultimately I am trying to find if the variable is greater than or equal to 8 chars while being under or equal to 20 chars. My test string is 11 char, and I am seeing string to short/to long. I've done similar to this in the past, so I dunno what I mucked up at the moment (maybe Im just to tired to realize it)

A: if (strlen($objectData['pss']) >= 8 && strlen($objectData['pss']) <= 20)

A: if ((strlen($objectData['pss']) >= 8) and (strlen($objectData['pss']) <= 20))
{
  //do my bidding
}
else
{
  echo "String to short or to long";
}

I have corrected you brackets

A: Yes you are indeed "to tired".. You are basically counting the length of an expression instead of the string itself:
if((strlen($objectData['pss']) >= 8)AND(strlen($objectData['pss']) <= 20))


text:
Q: deleting dynamically allocated memory (MSVS 2012) I've got a weird problem when deleting dynamically allocated memory. I am using MSVS 2012, and the error occurs
1) Only in release mode
2) Not during every run, although I always execute the same way and using the same data. The error occurs on average every 3-4th run.
Since it only occurs in release mode I put some cout commands in there to see where the program fails, and it always fails between tags #6 and #7, i.e. where I delete dynamically allocated memory which I have allocated a few steps earlier.
Here's the code:
long FOO::MainComputation(vector<double>InputArray, vector<double> & OutputArray)
{
    cout << "#1" << endl;
    // determine the size of the input array
    long NR_TOTINP = InputArray.size();
    // create dynamic array to hold the input array and copy values
    double * inparr = new double [NR_TOTINP];
    for (long i=0; i < NR_TOTINP; i++){inparr[i] = InputArray[i];}
    cout << "#2" << endl;
    // guess the size of the output array to allocate
    long NR_TOTOUT = InputArray.size() * 20 + 1;
    double * outarr = new double [NR_TOTOUT];
    cout << "#3" << endl;
    // call on the dll
    FOO_lfldld main_comp = (FOO_lfldld)GetProcAddress(hDLL,"Main_Comp");
    cout << "#4" << endl;
    long res = main_comp(NR_TOTINP,inparr,NR_TOTOUT,outarr);                                                    // todo: protect this with try... catch?
    // copy output parameters over
    cout << "#5" << endl;
    OutputArray.resize(NR_TOTOUT);
    for (long i=0; i < NR_TOTOUT; i++){OutputArray[i] = outarr[i];}
    cout << "#6" << endl;
    // delete dynamic arrays
    delete [] inparr;
    cout << "#7" << endl;
    delete [] outarr;
    cout << "#8" << endl;
    // done!
    return res;
}

I should note that the DLL called works fine with other code I have written (though in Python), so I do not suspect it to delete the memory on its own.
Any ideas?


text:
Q: RHEL8 ppc64le ... fatal error: vips/vips8: No such file or directory This works on my MAC, but now I need to install on ppc64le running RHEL8.  I googled for an answer but have not found anything that helps me identify a solution.  Can anyone give me a little direction on how to solve this issue?
Operating System: Red Hat Enterprise Linux 8.0 (Ootpa)
Kernel: Linux 4.18.0-80.el8.ppc64le
gcc version 8.2.1 20180905 (Red Hat 8.2.1-3) (GCC)
yarn install v1.21.1
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.2.9: The platform "linux" is incompatible with this module.
info "fsevents@1.2.9" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
[1/3] ⠄ dtrace-provider
[2/3] ⠄ sharp
error /home/flame/auth-server/node_modules/sharp: Command failed.
Exit code: 1
Command: (node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)
Arguments:
Directory: /home/flame/auth-server/node_modules/sharp
Output:
info sharp Downloading https://github.com/lovell/sharp-libvips/releases/download/v8.8.1/libvips-8.8.1-linux-ppc64.tar.gz
/home/flame/auth-server/node_modules/sharp/install/libvips.js:85
          throw new Error(`Status ${response.statusCode}`);
          ^

Error: Status 404
    at /home/flame/auth-server/node_modules/sharp/install/libvips.js:85:17
    at f (/home/flame/auth-server/node_modules/once/once.js:25:25)
    at ClientRequest.<anonymous> (/home/flame/auth-server/node_modules/simple-get/index.js:63:5)
    at Object.onceWrapper (events.js:300:26)
    at ClientRequest.emit (events.js:210:5)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:583:27)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:115:17)
    at TLSSocket.socketOnData (_http_client.js:456:22)
    at TLSSocket.emit (events.js:210:5)
    at addChunk (_stream_readable.js:308:12)
gyp info it worked if it ends with ok
gyp info using node-gyp@5.0.5
gyp info using node@12.13.0 | linux | ppc64
gyp info find Python using Python version 2.7.15 found at "/usr/bin/python2"
gyp info spawn /usr/bin/python2
gyp info spawn args [
gyp info spawn args   '/home/flame/.nvm/versions/node/v12.13.0/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/home/flame/auth-server/node_modules/sharp/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/home/flame/.nvm/versions/node/v12.13.0/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/home/flame/.cache/node-gyp/12.13.0/include/node/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/home/flame/.cache/node-gyp/12.13.0',
gyp info spawn args   '-Dnode_gyp_dir=/home/flame/.nvm/versions/node/v12.13.0/lib/node_modules/npm/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=/home/flame/.cache/node-gyp/12.13.0/<(target_arch)/node.lib',
gyp info spawn args   '-Dmodule_root_dir=/home/flame/auth-server/node_modules/sharp',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.'
gyp info spawn args ]
gyp info spawn make
make: Entering directory '/home/flame/auth-server/node_modules/sharp/build'
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
  TOUCH Release/obj.target/libvips-cpp.stamp
  CXX(target) Release/obj.target/sharp/src/common.o
../src/common.cc:25:10: fatal error: vips/vips8: No such file or directory
 #include <vips/vips8>
          ^~~~~~~~~~~~
compilation terminated.
make: *** [sharp.target.mk:137: Release/obj.target/sharp/src/common.o] Error 1
make: Leaving directory '/home/flame/auth-server/node_modules/sharp/build'
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/home/flame/.nvm/versions/node/v12.13.0/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:194:23)
gyp ERR! stack     at ChildProcess.emit (events.js:210:5)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:272:12)
gyp ERR! System Linux 4.18.0-80.el8.ppc64le
gyp ERR! command "/home/flame/.nvm/versions/node/v12.13.0/bin/node" "/home/flame/.nvm/versions/node/v12.13.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/flame/auth-server/node_modules/sharp
gyp ERR! node -v v12.13.0
gyp ERR! node-gyp -v v5.0.5

A: The first failure is where it tries to download the sharp-libvips source tarball:
info sharp Downloading https://github.com/lovell/sharp-libvips/releases/download/v8.8.1/libvips-8.8.1-linux-ppc64.tar.gz
[...]
Error: Status 404

... and that looks like it's because the sharp-libvips project doesn't provide a release for the ppc64 architecture (at https://github.com/lovell/sharp-libvips/releases/tag/v8.8.1 ).
Perhaps you can ask that project to provide builds for ppc64?


text:
Q: How to access child route params in react router I am trying to access route params from a parent component. I know that using withRouter you only have access to nearest parent route params. Therefore, what is the solution for access the current route params in a parent component? I am using react router v5.

A: If i got your question correctly, you can capture the current match props in childs componentDidUpdate and pass it up as prop. something like this:
child.js:
//skipping the class definition and render method
componentDidUpdate(prevProps){
    // when location gets updated in child component
    if(JSON.stringify(this.props.match)!=JSON.stringify(prevProps.match)){
        //match.id or whatever param you need in parent component
        this.props.cb(this.props.match.id);
    }
}

parent:
handleParamUpdate(id){
    console.log(id)
}
render(){
    return(
        <Child cb={this.handleParamUpdate}/>
    )
}


text:
Q: Is there any Bigdata tool to process pdf document I have to process PDF document.
Is there any tool in Bigdata to process my pdf documents(semi structured data)??
for example..
if my PDF document contains any topics like summary or action any thing i have to retrieve those paragraph with out any footer.
Now I am using pdfBox & java API to extract my pdf document but is there any bigdata tool available to do the same extraction??

A: I am not aware of a tool to do what you want to do, but if you are OK with setting up a Hadoop cluster (or using Amazon AWS services), then you can easily use Hadoop streaming to pass PDF documents through a user-defined program (what you have in java should work fine).
There is a good example of how to use Hadoop streaming with a custom Java program in this earlier SO question.


text:
Q: How do I recognise a browser tab has closed and close the listener? I'm using the following code (Adapted from this example) to perform PKCE authorization.
 public static async Task<string> ReceiveCodeAsync(string authorisationUrl, string redirectUrl, string state)
        {
            using var listener = new HttpListener();
            listener.Prefixes.Add(redirectUrl);
            try
            {
                listener.Start();

                var process = new Process { StartInfo = { UseShellExecute = true, FileName = authorisationUrl } };
                process.Start();

                // Wait to get the authorization code response.
                var context = await listener.GetContextAsync().ConfigureAwait(false);
                var coll = context.Request.QueryString;

                // Write a "close" response.
                await using (var writer = new StreamWriter(context.Response.OutputStream))
                {
                    writer.WriteLine(ClosePageResponse);
                    writer.Flush();
                }
                context.Response.OutputStream.Close();

                if (coll["state"] != state)
                    throw new SpotifyAuthException("The returned state was invalid");

                return coll["code"];
            }
            finally
            {
                listener.Close();
            }
        }

It works fine normally, the browser launches, the user authorises and a code is returned. However, if the user closes the tab instead, the listener is always waiting to GetContextAsync().
I've tried using the process exited event to recognise when the tab has closed, but that triggers as soon as the tab is launched if a browser window is already open.
Is there another way I can release the listener if the user closes the login tab?


text:
Q: How does correlation and conditional probability relate? Suppose we have two random variables $p \in [0,1]$ and $q \in [0,1]$ with correlation $\rho$. My question: knowing $\rho$, how do I update my probability distribution over values of one of the variables, when I learn the value of the other?
As an example, suppose that $\rho = 0.5$, and I learn that $p=1$. What can I say about the expected value $q$? If I'm maximizing accuracy, what value should I predict? Plausibly, if the expected value of $q$ was $0.5$ before (perhaps by the principle of insufficient reason) then I should adjust this upwards when I learn of the correlation and value of $p$. But in what way, and how much exactly?
I think I'm confused about how correlation relates to probabilities and Bayesian updating. Any help would be much appreciated!


text:
Q: MongoDB Limit fields and slice projection together I have the following User object:
{
  "_id" : ObjectId("someId"),
  "name" : "Bob",
  "password" : "fakePassword",
  "follower" : [...],
  "following" : [..]
}

I need to paginate over the follower list, so I use the slice projection operator, but I just need the paginated followers list to be returned. And I don't know if I am doing it the wrong way, or this can't be done, but limit fields doesn't work with slice projection.
Following are a couple of queries I tried:
 collection.findOne(
          {
            _id: new ObjectId(userId)
          },
          {
            follower: {$slice:[skip, parseInt(pageSize)]},
            follower: 1
          },..

and
collection.findOne(
          {
            _id: new ObjectId(userId)
          },
          {
            follower: 1,
            follower: {$slice:[skip, parseInt(pageSize)]}
          },

But these return all the values in the object, and does not limit the fields, although, the slice works fine in both the cases.
Also when I do something like _id:0,following:0 , this part works, but I don't want to mention each and every field in the query like this, it may create problems once I decide to change the schema.
How do I get this to work, what could be the syntax for the query to get this working..??

A: Not sure I'm getting your usage pattern here. Perhaps we can simplify the example a little. So considering the document:
{
    "_id" : ObjectId("537dd763f95ddda3208798c5"),
    "name" : "Bob",
    "password" : "fakePassword",
    "follower" : [
            "A",
            "B",
            "C",
            "D",
            "E",
            "F",
            "G",
            "H",
            "I",
            "J",
            "K"
    ]
}

So the simple query like this:
db.paging.find(
    { "name": "Bob" },
    {
        "_id": 0,
        "name": 0,
        "password": 0,
        "follower": { "$slice": [0,3] }
}).pretty()

Gives results:
{
    "follower" : [
            "A",
            "B",
            "C"
    ]
}

And similarly from the following page:
db.paging.find(
    { "name": "Bob" },
    {
        "_id": 0,
        "name": 0,
        "password": 0,
        "follower": { "$slice": [3,3] }
}).pretty()

Gives the results:
{
    "follower" : [
        "D",
        "E",
        "F"
    ]
}

So for me personally I am not sure whether you were asking about the field exclusion or whether you were asking about "paging" the array results, but either way, both of those examples are shown here.

A: One way is to actually use _id here by saying {_id:1}:
{ "_id" : ObjectId("537de1bc08eb9d89a7d3a1b2"), "f" : [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20 ], "d" : 1 }
> db.test.findOne({ "_id" : ObjectId("537de1bc08eb9d89a7d3a1b2")},{f:{$slice:[0,2]}})
{
        "_id" : ObjectId("537de1bc08eb9d89a7d3a1b2"),
        "f" : [
                1,
                2
        ],
        "d" : 1
}
> db.test.findOne({ "_id" : ObjectId("537de1bc08eb9d89a7d3a1b2")},{_id:0, f:{$slice:[0,2]}})
{ "f" : [ 1, 2 ], "d" : 1 }
> db.test.findOne({ "_id" : ObjectId("537de1bc08eb9d89a7d3a1b2")},{_id:1, f:{$slice:[0,2]}})
{ "_id" : ObjectId("537de1bc08eb9d89a7d3a1b2"), "f" : [ 1, 2 ] }


text:
Q: Android studio: I need to implement a zoom in functionality to my camera app The preview is showing but when I click zoom in or out nothing happens. Here is the code
This is the xml for the main activity
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

    <RelativeLayout
    android:id="@+id/activity_main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        android:onClick="captureImage"
        android:text="Capture" />

    <Button
        android:id="@+id/button2"
        android:layout_alignTop="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="5dp"
        android:text="Gallery" />

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="686dp">

    </FrameLayout>

    <ZoomControls
        android:id="@+id/zoomControls"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="104dp"
        android:layout_marginBottom="-4dp" />

</RelativeLayout>

This is the code in java for the MainActivity
MainActivity.java
package com.example.mycustomcamera;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity
{
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    String currentPhotoPath = null;
    private static final String TAG = "MainActivity";
    Camera camera;
    FrameLayout frameLayout;
    ShowCamera showCamera;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        frameLayout = (FrameLayout)findViewById(R.id.frameLayout);
        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                camera.takePicture(null, null, mPictureCallBack);
            }
        });
        //open the camera
        camera = camera.open();
        showCamera = new ShowCamera(this,camera);
        frameLayout.addView(showCamera);
    }

    Camera.PictureCallback mPictureCallBack = new Camera.PictureCallback()
    {
        @Override
        public void onPictureTaken(byte[] data, Camera camera)
        {
            File picture_file = getOutputMediaFile(MEDIA_TYPE_IMAGE);
            if(picture_file == null)
            {
                Log.d(TAG, "Error creating media file, check storage permissions");

                return;
            }
            else
                {
                    try
                    {
                        FileOutputStream fos = new FileOutputStream(picture_file);
                        fos.write(data);
                        fos.close();
                        //sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
                        //camera.startPreview();

                        //galleryAddPic();
                    }
                    catch (FileNotFoundException e)
                    {
                    Log.d(TAG, "File not found: " + e.getMessage());
                    }
                    catch (IOException e)
                    {
                        Log.d(TAG, "Error accessing file: " + e.getMessage());
                     }
                    camera.startPreview();
                    //camera.stopPreview();
                    //camera.release();

                }
        }
    };

    /** Create a file Uri for saving an image or video */
    private static Uri getOutputMediaFileUri(int type){
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "MyCustomCamera");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCustomCamera", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE){
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_"+ timeStamp + ".jpg");
        } else if(type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "VID_"+ timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }

    private void galleryAddPic()
    {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(currentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

}

This is the code in java for the camera preview
ShowCamera.java
package com.example.mycustomcamera;

import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ZoomControls;
import java.io.IOException;
import java.util.List;

public class ShowCamera extends SurfaceView implements
        SurfaceHolder.Callback
{
    private static final String TAG = " => Main Activity: ";
    private SurfaceHolder holder;
    private Camera mcamera;
    private Context mContext;
    int currentZoomLevel = 0;
    int maxZoomLevel = 0;
    ZoomControls zoomControls;

    public ShowCamera(Context context, Camera camera)
    {
        super(context);
        mContext = context;
        this.mcamera = camera;
        holder = getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder)
    {
        if(mcamera == null) return;
        try
        {
            mcamera.setDisplayOrientation(90);
            mcamera.setPreviewDisplay(holder);
            mcamera.startPreview();
        }
        catch (IOException e)
        {
            Log.d(TAG, "Blad wlaczania podgladu kamery: " + e.getMessage());
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        if (holder.getSurface() == null) {
            return;
        }
        try {
            mcamera.stopPreview();
        } catch (Exception e) {

        }
        Camera.Parameters params = mcamera.getParameters();
        List<Camera.Size> sizes = params.getSupportedPreviewSizes();
        Camera.Size optionalSize = getBestPreviewSize(width, height);
        params.setPreviewSize(optionalSize.width, optionalSize.height);

        mcamera.setParameters(params);

        Display display = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        switch (display.getRotation()) {
            case Surface.ROTATION_0:
                mcamera.setDisplayOrientation(90);
                break;
            case Surface.ROTATION_90:
                mcamera.setDisplayOrientation(0);
                break;
            case Surface.ROTATION_180:
                mcamera.setDisplayOrientation(270);
                break;
            case Surface.ROTATION_270:
                mcamera.setDisplayOrientation(180);
                break;
        }

        try {
            mcamera.setParameters(params);
            mcamera.setPreviewDisplay(holder);
            mcamera.startPreview();

        } catch (IOException e) {
            Log.d(TAG, "Blad wlaczania podgladu kamery" + e.getStackTrace());
        }

        ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoomControls);

        if (params.isZoomSupported()) {
            maxZoomLevel = params.getMaxZoom();

            try {

                zoomControls.setIsZoomInEnabled(true);
                zoomControls.setIsZoomOutEnabled(true);

                zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        if (currentZoomLevel < 500) {
                            currentZoomLevel++;
                            mcamera.startSmoothZoom(currentZoomLevel);
                        }
                    }
                });

                zoomControls.setOnZoomOutClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        if (currentZoomLevel > 0) {
                            currentZoomLevel--;
                            mcamera.startSmoothZoom(currentZoomLevel);
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            zoomControls.hide();
        }

    }
        @Override
        public void surfaceDestroyed(SurfaceHolder holder)
        {
            mcamera.release();
            mcamera = null;
        }

        private Camera.Size getBestPreviewSize(int width, int height) {
        Camera.Size result = null;
        Camera.Parameters p = mcamera.getParameters();
        for (Camera.Size size : p.getSupportedPreviewSizes()) {
            if (size.width <= width && size.height <= height) {
                if (result == null) {
                    result = size;
                } else {
                    int resultArea = result.width * result.height;
                    int newArea = size.width * size.height;

                    if (newArea > resultArea) {
                        result = size;
                    }
                }
            }
        }
        return result;
    }

    }

This is the manifest
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mycustomcamera">
    <uses-permission android:name="android.permission.CAMERA"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyCustomCamera">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.android.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/paths"></meta-data>
        </provider>

    </application>

</manifest>


text:
Q: Cleanup and close interop excel com object when exception occurs. Winforms vb.net How to cleanup excel com objects correctly. Hanging excel process running in task manager when exception is thrown while working with the object
If there is no error then after exiting the application there is no excel.exe process left behind in taskmanager
My example code. If you comment out the error line and close the application all is good. How to handle cleanup in error cases such as this??
Imports Microsoft.Office.Interop

Public Class Form1
    Private xlApp As Excel.Application
    Private xlWorkBook As Excel.Workbook
    Private misValue As Object
    Property xlWorkSheet As Excel.Worksheet

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            ''EXCEL CREATION/INITAILIAZATION
            misValue = System.Reflection.Missing.Value
            xlApp = New Microsoft.Office.Interop.Excel.Application()
            If xlApp Is Nothing Then
                MessageBox.Show("Excel is not properly installed!!")
                xlApp = Nothing
            End If
            xlWorkBook = xlApp.Workbooks.Add(misValue)

            ''WRITE TO WORKSHEET
            xlWorkSheet = xlWorkBook.Sheets("sheet1")
            xlWorkSheet.Cells(1, 1) = "THIS"
            xlWorkSheet.Cells(1, 2) = "IS"
            xlWorkSheet.Cells(1, 3) = "A"
            xlWorkSheet.Cells(1, 4) = "TEST"

            ''FORCEFULLY CAUSING ERROR, NOW THE EXCEL PROCESS HANGING IN TASK MANAGER
            xlWorkSheet.Cells(1, -1) = "ERROR LINE"

            ''SAVE WORKSHEET
            Dim Name = DateTime.Now.ToString("s").Replace(":", "_")
            Dim Dir = AppDomain.CurrentDomain.BaseDirectory & Name & "Output.xls"
            xlApp.DisplayAlerts = False
            xlWorkBook.CheckCompatibility = False
            xlWorkBook.DoNotPromptForConvert = True
            xlWorkBook.SaveAs(Dir, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, _
                                Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue)

        Catch ex As Exception
            Dim exMsg = ex.Message
        Finally
            ''TIME TO CLEAN EXCEL STUFF
            Cleanup()
        End Try
    End Sub

    Private Sub Cleanup()
        ReleaseObject(xlWorkSheet)
        ReleaseObject(xlWorkBook)
        xlApp.Quit()
        ReleaseObject(xlApp)
    End Sub

    Private Sub ReleaseObject(ByRef obj As Object)
        Try
            If Not IsNothing(obj) And System.Runtime.InteropServices.Marshal.IsComObject(obj) Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
                obj = Nothing
            End If
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub

End Class

A: Figured it out. xlWorkBook.close and xlApplication.Quit needed to called before releasing the object. Here is the updated Cleanup function
Private Sub Cleanup()
    xlWorkBook.Close(False)
    xlApp.Quit()
    ReleaseObject(xlWorkSheet)
    ReleaseObject(xlWorkBook)
    ReleaseObject(xlApp)
End Sub


text:
Q: Chage in spring data rest output format in spring-data-rest-webmvc version 2.2.1.RELEASE I am using spring data rest web mvc 2.2.1.RELEASE.
I am expecting out in below format
{
    "content": [ {
        "price": 499.00,
        "description": "Apple tablet device",
        "name": "iPad",
        "links": [ {
            "rel": "self",
            "href": "http://localhost:8080/product/1"
        } ],
        "attributes": {
            "connector": "socket"
        }
    }, {
        "price": 49.00,
        "description": "Dock for iPhone/iPad",
        "name": "Dock",
        "links": [ {
            "rel": "self",
            "href": "http://localhost:8080/product/3"
        } ],
        "attributes": {
            "connector": "plug"
        }
    } ],
    "links": [ {
        "rel": "product.search",
        "href": "http://localhost:8080/product/search"
    } ]
}

But I am getting output like this :
    {
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/people{?page,size,sort}",
      "templated" : true
    },
    "search" : {
      "href" : "http://localhost:8080/people/search"
    }
  },
  "_embedded" : {
    "people" : [ {
      "firstName" : "Frodo",
      "lastName" : "Baggins",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/people/1"
        }
      }
    }, {
      "firstName" : "Frodo",
      "lastName" : "shukla",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/people/2"
        }
      }
    } ]
  },
  "page" : {
    "size" : 20,
    "totalElements" : 2,
    "totalPages" : 1,
    "number" : 0
  }
    }

Why I am getting _embedded in place of content
_links in place of links
and rel attribute is missing..
I am try to de-serializing  json out back to  hateos Resource but because of change in format I am not able to achieve this .
Thanks for help in advance

A: SDR 2.X outputs content in  HAL format and hence the _links & _embedded. Refer to HAL specification for further details

A: The result you are expecting is the one produced by spring-data-rest 1.x. The default format in 2.x is HAL. But a fall back to the old format should possible by changing the default media format as stated in the resolution of this bug: https://jira.spring.io/browse/DATAREST-213.

A: I adapted my JPA Rest Client as per HAL specification/


text:
Q: Dev: non-center backoffice module (top left) always with my module, prestashop 1.6
I have a problem to correctly center and automatically my config page of my module in the admin, everything is displayed except that it is in the top left
public function __construct()
{
    $this->bootstrap = true;

private function _displayForm()
{
    $smarty->assign(array(
    'url' => "http://".$_SERVER['HTTP_HOST'].__PS_BASE_URI__.'/',
    $smarty->display(_PS_MODULE_DIR_ . 'monmodule/option.tpl');

option.tpl

thanks in advance

A: Did you try with

?
EDIT:
Well in my modules I always use the class=""panel" then within you can add a new div with your content and set the div to content="flex" and justify-content="center" along with align-items="center" if necessary.

A: replaces

public function getContent()
{
$this->_displayForm();

replaced by

public function getContent()
{
 $smarty->assign(array(
 'url' => "http://".$_SERVER['HTTP_HOST'].__PS_BASE_URI__.'/',
 $smarty->display(_PS_MODULE_DIR_ . 'monmodule/option.tpl');


text:
Q: weird characters in Chinese In browser, it's showing something like below:

when I inspect it in developer console, it is showing normal:

so, it looks like the colon is a not being improperly encoded.
The problem is that I don't have control of the content, the information is retrieved from somewhere else using ajax call and I use jQuery to retrieve city information.
var toCity = $(infoOutHtml).find('#HeaderDes').text();

when I console.log(toCity)  it shows normal in console:   目 的 地:中国
but when I render it to html, it become weird:
var Information = "
"+
     ""+toCity +""+
"
"

$($info).html(information);

I am just wondering what's the problem here? how to ignore the colon before render it to html?
I tried this, but doesn't work at all:
function somefunction(string){

  return string.replace(/:/,'\\\\:');

}

toCity = somefunction(toCity);

A: @krtek is right, I used the font family which doesn't have ":".


text:
Q: AWS: disable default domain name for alb Using a containerized app which is linked with an application load balancer to route traffic from port 80 to 443 and also handle health check and scaling.
But the issue is the application load balancer when created both through the console and the cli gets assigned default dns name.
Which is something im trying to get rid of, since i have a dns record in route53 to forward traffic to the alb.
And my end goal is for the app to be aviable only through my domain name.
What im interested is either how to disable the default dns name for my alb

A: There is no way to do that. Your ALB needs a DNS name, so you can point your Route53 record to it. When publishing your app, you can use your custom domain name, but the app will stay available at the ALB DNS name.


text:
Q: How to use jProgress bar for ProcessBuilder process? I am developing an java application to make a usb drives bootable,by executing CMD command through ProcessBuilder. This takes few seconds, in that i want to show an jprogressbar to increase GUI, i have tried so for, i dont get, Please help me.
This is My Code :
private void btn_StartActionPerformed(java.awt.event.ActionEvent evt)
{
      String[] command ={"CMD", "/C", "MyCmdCommand"};
      ProcessBuilder probuilder = new ProcessBuilder( command );
      probuilder.directory(new File(dri+":\\"));

      try
      {
            Process process = probuilder.start();
            process.waitFor();
      }

      catch(IOException e)
      {
            JOptionPane.showMessageDialog(this, e);
      }
}

How i can use JProgressbar in my code and where i have to use?
thank you

A: Swing is a single threaded environment, it is also not thread safe.
This means that any long running or blocking process should never be run within the context of the Event Dispatching Thread, as it will prevent it from processing new events, including repaint requests, making the program look like it's hung.
It also means that you should NEVER create or modify the state of ANY UI component from outside the context of the EDT.
See Concurrency in Swing for more details.
You can use a Thread to run the process within, but you will become responsible for ensure that any changes you want to make to the UI are carried out within the context of the EDT manually.  This can become troublesome especially when you want to pass information from the thread to the EDT.
Another solution is to use a SwingWorker which provides functionality that can synchronise data between it's background thread and the EDT more easily.  It supports progress notification via the setProgress method and PropertyListener support as well as the ability to publish data from the background thread and process within the context of the EDT.  It also has a nice done method which lets you know when the background thread has completed, but which is executed within the context of the EDT, for example...
public static class FormatWorker extends SwingWorker<Integer, Integer> {

    private String drive;

    public FormatWorker(String drive) {
        this.drive = drive;
    }

    @Override
    protected Integer doInBackground() throws Exception {
    String[] command = {"CMD", "/C", "MyCmdCommand"};
    ProcessBuilder probuilder = new ProcessBuilder(command);
    probuilder.directory(new File(drive + ":\\"));

    Process process = probuilder.start();
    return process.waitFor();
        return 0;
    }

}

Now, you might be tempted to pass in the JProgressBar to the SwingWorker and reset its state within the done method, but this does leave it a hanging a little, not knowing when the worker has actually started, sure, you should set the state before you call the worker, but still, it's not the responsibility of the worker to manage the state of the UI
Instead, you could take advantage of the workers PropertyChangeListener support, for example...
    PropertyChangeListener listener = new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            System.out.println(evt.getPropertyName() + "; " + evt.getNewValue());
            if ("state".equals(evt.getPropertyName())) {

                SwingWorker.StateValue state = (SwingWorker.StateValue) evt.getNewValue();
                switch (state) {
                    case DONE:
                        try {
                            int exitLevel = ((SwingWorker<Integer, ?>)evt.getSource()).get();
                            JOptionPane.showMessageDialog(null, "Format command completed with exit level of " + exitLevel);
                        } catch (InterruptedException | ExecutionException ex) {
                            JOptionPane.showMessageDialog(progressBar, ex.getMessage());
                        } finally {
                            progressBar.setIndeterminate(true);
                        }
                        break;
                    case STARTED:
                        progressBar.setIndeterminate(true);
                        break;
                }

            }
        }
    };
    FormatWorker worker = new FormatWorker("G");
    worker.addPropertyChangeListener(listener);
    worker.execute();

This allows you to decide how you want to respond to the worker, without coupling you to a particular work flow.
See Worker Threads and SwingWorker


text:
Q: Android Java. Strange behaviour with invalidate(Rect) I am getting astrange effect with invalidate(Rect).
I use an onDraw method on a canvas. In the simplest case, I have a background and a sprite.
On the first pass through onDraw, I draw the background and use invalidate(Rect) (a rect which covers the whole playfield) and in the same pass, I draw a sprite and (because the code is the same for all passes) I do an invalidate(Rect) for the Rect the sprite was in.
After the first pass, the playfield is correct. The whole background is in place, with the sprite superimposed.
On the next and subsequent passes through onDraw, I draw the "dirty" bit of the background the sprite was on, and do an invalidate(Rect) on that, together with the sprite and its new "dirty" rectangle, and another invalidate(Rect) for the sprite.
After this pass and all subsequent passes, I only see the sprite. It's as though the canvas had been cleared.
Is it not allowed to do multiple invalidate(Rect)s in one pass? Is this the problem? Have I come up against some problem with asynchronicity?
Here is the onDraw() code. It works fine, but slowly, if I do a full screen invalidate() at the end of onDraw() instead.
It's also scaling all the images. All the images and screen positions are based on a 640x480 playfield,
and scaled to the size of the current android device. All that works fine until I try to optimise the screen
drawing by using invalidate(Rect).
    @Override
    protected void onDraw(Canvas canvas)
{
    int ii;

    // Draw the background scene
    // Restore all the bits of the backcloth that got
    // trampled on by any sprites or the cursor
    // On the first pass the whole playfield dirty rectangle is in place in mask
    paint.reset();
    mask.collapse();
    ArrayList <Rect> usedSet = mask.getUsedRectSet();
    for (ii = 0; ii < usedSet.size(); ii++)
    {
        Rect src = rescaleRect(usedSet.get(ii));
        Rect dst = displaceRect(src);
        canvas.drawBitmap(backcloth, src, dst, paint);
        invalidate(dst);
    }
    // Leave used Rect set clear for next set of sprites
    mask.ClearUsedRectSet();

    //
    // draw Sprites
    //   screen scaling and
    //   displacement is done here.
    //
    ArrayList <Sprite> slist = jadedata.getCurrentSprites();
    //Sort sprites into ascending order of priority
    //      This is a sinking sort. On first pass, the highest
    //      priority sprite arrives at the bottom. On second,
    //      the next highest arrives at second bottom, etc.
    //      Sprites of the same priority remain in their
    //      original sequence with respect to each other.
    for (ii = 0; ii< slist.size()-1; ii++)
    {
        int sw=0;
        for (int jj = 0; jj < (slist.size()-ii-1); jj++)
        {
            Sprite spare1 = slist.get(jj);
            Sprite spare2 = slist.get(jj+1);
            if (spare1.getPriority() > spare2.getPriority())
            {
                slist.set(jj+1, spare1);
                slist.set(jj, spare2);
                sw=1;
            }
        }
        if (sw==0) break;  // exit if slist is already in sequence
    }

    for (ii = 0; ii< slist.size(); ii++)
    {
        Point p = new Point();
        Point e = new Point();
        Rect o = new Rect();
        Sprite sprite = (Sprite)slist.get(ii);
        // Zero-priority sprites do not get drawn
        if (sprite.getPriority() == 0) continue;
        p = sprite.getPosition();
        e = sprite.getExtent();
        // make a rect for usedRects
        Rect r = new Rect(0, 0, e.x-1, e.y-1);
        Rect src = new Rect(r);
        // move it to the model playfield position
        r.offset(p.x-e.x/2, p.y-e.y/2);
        // make an overlap rect so we can apply it to the source image
        o = overlapRect(r, 0, 0, iWidth, iHeight);
        // trim r for the used rectangles
        r = trimRect(r, 0, 0, iWidth, iHeight);
        // add it to used Rectangles
        mask.addNewRect(r);
        // draw the sprite image
        Rect d = rescaleRect(usedSet.get(ii));
        Rect dst = displaceRect(d);
        Bitmap spriteim = sprite.getCurrentImage();
        src.top += o.top;
        src.left += o.left;
        src.bottom -= o.bottom;
        src.right -= o.right;
        canvas.drawBitmap(spriteim, src, dst, paint);
        invalidate(dst);
    }

A: not sure what you are doing since you didn't provide code , so i will just give a general tip:
for the passes after the first pass , use the invalidate only on the rectangle that is dirty , and in the onDraw method , draw everything that needs to be drawn , but only inside the dirty rectangle.


text:
Q: Tensorboard event file size is growing after consecutive model training I'm training 8 models in a for loop and saving each tensorboard log file into a seperate directory. Folder structure is like Graph is my main directory for graphs and directories under Graph such as net01 net02... net08 are the ones I'm outputting my event files. By doing this I can visualize training logs in Tensorboard in that fancy fashion with every single training process gets its own colour.
My problem is the growing sizes of eventfiles. The first event file is apporoximately 300KB's, but the second event file have a size of 600KB's, third is 900 KB and so on. They each reside in their own seperate directory and each of them are different training sessions from each other but somehow tensorboard appends the earlier sessions into last one. In the end I should've a total size of 12*300Kb= 3600 KB of session files, but I endup with something like 10800KB of session files. As the nets are getting deeper I endup with session file sizes of like 600 MB. So clearly I'm missing something out.
I tried to visualize last file with the biggest size to check whether it includes all the previous training sessions and can draw like 8 nets but it failed. SO a big bunch of irrelevant information is stored in this session file.
I'm using Anaconda3-Spyder on Win7-64. Database is divided into 8 and for each run I'm leaving one out for validation and using the rest as training. Here is a simplified version of my code:
from keras.models import Model
from keras.layers import Dense, Flatten, Input, Conv2D, MaxPooling2D
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import TensorBoard, ModelCheckpoint, CSVLogger
import os.path
import shutil
import numpy
#  ------------------------------------------------------------------
img_width, img_height = 48, 48
num_folds=8
folds_path= "8fold_folds"
nets_path = "8fold_nets_simplenet"
csv_logpath = 'simplenet_log.csv'
nets_string = "simplenet_nets0"
nb_epoch = 50
batch_size = 512
cvscores = []
#%%
def foldpath(foldnumber):
    pathbase= os.path.join(folds_path,'F')
    train_data_dir = os.path.join(pathbase+str(foldnumber),"train")
    valid_data_dir = os.path.join(pathbase+str(foldnumber),"test")
    return train_data_dir,valid_data_dir

#%%
for i in range(1, num_folds+1):
    modelpath= os.path.join(nets_path,nets_string+str(i))
    if os.path.exists(modelpath):
        shutil.rmtree(modelpath)
    os.makedirs(modelpath)
    [train_data_dir, valid_data_dir]=foldpath(i)
    img_input = Input(shape=(img_width,img_height,1),name='input')

    x = Conv2D(32, (3,3), activation='relu', padding='same', name='conv1-'+str(i))(img_input)
    x = MaxPooling2D((2, 2), strides=(2, 2), name='pool1-'+str(i))(x)
    x = Conv2D(64, (3,3), activation='relu', padding='same', name='conv2-'+str(i))(x)
    x = MaxPooling2D((2, 2), strides=(2, 2), name='pool2-'+str(i))(x)
    x = Conv2D(128, (3,3), activation='relu', padding='same', name='conv3-'+str(i))(x)
    x = MaxPooling2D((2, 2), strides=(2, 2), name='pool3-'+str(i))(x)
    x = Flatten()(x)
    x = Dense(512, name='dense1-'+str(i))(x)
    #x = Dropout(0.5)(x)
    x = Dense(512, name='dense2-'+str(i))(x)
    #x = Dropout(0.5)(x)
    predictions = Dense(6, activation='softmax', name='predictions-'+str(i))(x)
    model = Model(inputs=img_input, outputs=predictions)
    #  compile model-----------------------------------------------------------
    model.compile(optimizer='Adam', loss='binary_crossentropy',
                  metrics=['accuracy'])
    #  ----------------------------------------------------------------
    # prepare data augmentation configuration
    train_datagen = ImageDataGenerator(rescale=1./255,
                                       featurewise_std_normalization=True,
                                       featurewise_center=True)
    valid_datagen = ImageDataGenerator(rescale=1./255)
    train_generator = train_datagen.flow_from_directory(
        train_data_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        color_mode='grayscale',
        classes = ['1','3','4','5','6','7'],
        class_mode='categorical',
        shuffle='False'
    )
    validation_generator = valid_datagen.flow_from_directory(
        valid_data_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        color_mode='grayscale',
        classes = ['1','3','4','5','6','7'],
        class_mode='categorical',
        shuffle='False'
    )
    #  --------------------callbacks---------------------------
    csv_logger = CSVLogger(csv_logpath, append=True, separator=';')
    graph_path = os.path.join('Graphs',modelpath)
    os.makedirs(graph_path)
    tensorboard = TensorBoard(log_dir= graph_path, write_graph=True, write_images=False)
    callbacks_list=[csv_logger,tensorboard]

    #  ------------------
    print("Starting to fit the model")

    model.fit_generator(train_generator,
                        steps_per_epoch = train_generator.samples/batch_size,
                        validation_data = validation_generator,
                        validation_steps = validation_generator.samples/batch_size,
                        epochs = nb_epoch, verbose=1, callbacks=callbacks_list)

A: Not sure about this one but my guess would be that it has to do with your graphs being stored after each loop iteration. To check if your graphs are responsible for this, you could try write_graph = False, and see if you still have the same problem. To make sure the graph is reset, you could try to clear the tensorflow graph at the end of each iteration using this:
keras.backend.clear_session()

A: The problem is that with training of each model, the next model still contains all the graph elements of previous trainings. Thus before training each model, reset the Tensorflow graph and then continue with the training.


text:
Q: Fermion field structure in non-abelian gauge theories I am trying to understand the structure of the fermions in non-abelian gauge theories. Disclaimer: my question might be very trivial (I suspect the answer could simply be "a change of basis"), but I would be grateful is someone could shed some light if there's something deeper lurking around the corner.
Let's consider the Yang-Mills Lagrangian
$$ \mathcal{L} = -\frac{1}{4} (F_{\mu \nu}^a)^2 + \bar{\psi}(i \gamma^\mu D_\mu -m)\psi $$
where $ D_\mu = \mathbf{1} \partial_\mu - i g A_\mu^a t^a$, then $\psi$ needs to have both Dirac ($\mu$) and colour (a) degrees of freedom. I get confused when I change the regular approach to the problem and I am not sure if it is a real issue or if I'm just overcomplicating/overthinking this.
For instance, let's consider $SU(N)$ YM where the generators $t^a$ are $N \times N$ matrices, and there are $N^2-1$ of them. Therefore, the covariant derivative $D_\mu$ is an $N \times N$ matrix, and the index $a$ above runs over $N^2-1$ value.
When we start by contracting $D_\mu$ with the $\gamma$-matrices,
$$ (\gamma^\mu D_\mu)_{ij} = \delta_{ij} \gamma^\mu \partial_\mu - i g (\gamma^\mu A_\mu^a) (t^a)_{ij}  $$
one gets an $N \times N$ matrix of $4 \times 4$ matrices. The corresponding $4N$-component object this matrix acts upon is the $N$ Dirac spinors arranged in a column.
However, notice that if we start in the following way instead:
$$ (D_\mu \psi)_i = \partial_\mu  \psi_i - i g A_\mu^a (t^a)_{ij} \psi_j $$
we get that the covariant derivative acts on $\Psi \equiv (\psi_1, \cdots, \psi_N)$. For all we know, $\Psi$ has no spinor structure since we haven't contracted with the gamma matrices yet.
Contracting with the $\gamma^\mu$, one gets a $4 \times 4$ matrix of $N \times N$ matrices that encodes the same information as before. This time, it would seem that we only have one Dirac spinor, where each component is a $N$-valued singlet.
However, it seems that the matrix $\gamma^\mu D_\mu$ and the $4N$-component spinor look different, even though all we did was to change the order in which we constructed things.
In the first case, we get $N$ spinors corresponding to the $N$ colors of the adjoint representation. In $SU(3)$, this would be like saying we effectively have 3 spinors which correspond to the red/blue/green colors as $(\psi_R, \psi_B, \psi_G)$. In the second case, this identification fails since we only have one big complicated object.
What went wrong? Is this difference simply a change of basis for $\psi$? Is there something relevant we can learn from looking at the YM Lagrangian in these two different ways?
Also, in the first case, when we get $N$ spinors, I am confused about their signification. I always assumed that in QCD, $\psi$ would correspond to a quark, which is a fermion by itself. Does it mean that quarks are fermions that can be described by fermionic fields/degrees of freedom that we call color?

A: In a sense, you are right. It's the same information, put in a different order. Try to do that with a simpler case, for instance two two-dimensional vector space, one with index $\alpha=1,2$, the other with index $a=1,2$. Then any vector of this now four-dimensional vector space can be written either $\psi_{\alpha,a}$ or $\psi'_{a,\alpha}$ or even $v_i$ with $i=1,2,3,4$. Then the matrix $\sigma$ and $S$ acting respectively on the space $\alpha$ and $a$ can associated to create
$\gamma=\sigma \otimes S$ or $\gamma'=S\otimes \sigma$  acting respectively  on $\psi_{\alpha,a}$ and $\psi'_{a,\alpha}$, or any other complicated 4 by 4 matrix acting $v$ depending on how we associate a given $i=1,2,3,4$ to a set $(\alpha,a)=(1,1), (1,2),(2,1),(2,2)$.
The choice to associate $i$ to $(\alpha,a)$ is free, but some choices are more natural than others. In you case, we are used to this of the system as $N$ fermions, described by spinors, which corresponds to $1\otimes \gamma_\mu$, because we think of the well defined spinors in interaction through the gauge field. But this is just a convenient representation.

A: You may write :
$(\gamma^\mu D_\mu) (\psi_i)_k = [\delta_i^j  \partial_\mu - i g  A_\mu^a (t_a)_{i}^j] ~~ (\gamma^\mu)^k_l ~~(\psi_j)_l \tag{1}$
Here $i,j$ are in $1..N$, and $k,l$ are in $1..4$, $(\psi_i)_k$ is the k-th ($1 \leq k \leq 4$) component of the i-th ($1 \leq i \leq N$) spinor.
We could use the notation $\psi_{j~l} = (\psi_j)_l$, now we see that $[\delta_i^j  \partial_\mu - i g  A_\mu^a (t_a)_{i}^j]$ is acting on the first indice of $\psi_{j~l}$, while $(\gamma^\mu)^k_l$ is acting on the second indice of $\psi_{j~l}$, so we could use a tensorial compact notation, with $\psi$ representing the $\psi_{{j~l}}$ :
$(\gamma^\mu D_\mu) ~\psi = ([\mathbb{Id}~ \partial_\mu- i g  A_\mu^a t_a] \otimes \tag{2}\gamma^\mu) ~\psi $
Of course, it is not very much useful for practical calculus, but it is, at least, a view on the whole structure.


text:
Q: mounting local directory in Rstudio docker with read permission without running a ROOT? I would like to mount a local directory when I call docker and have that directory available to be written to without going to drastic extremes of making the user root.
The closest answer I can find is this:  Mount local volume accessible to R/RStudio in docker (tidyverse)
or this
Permission denied on accessing host directory in Docker
Here, some responders go into detailed explanation: Permission denied on accessing host directory in Docker
That is very close given I am also running the exact same rocker container.  That poster seems to be happy, but I wonder if the solution gives the ability to write. Yes I have spent a lot of time reading documentation on this.
In this case is would be nice if the answer to this problem was posted on https://hub.docker.com/r/rocker/rstudio
because given the number of similar question on SO, the solution is not clear to many people.
The closest they get to answering the question is this:
Additional configuration options

    Custom user name: -e USER=<CUSTOM_NAME>
    Custom user id, group id, UMASK: -e USERID=<UID>, -e GROUPID=<GID>, e UMASK=022

Custom uid/gid etc is usually only needed when sharing a local volume for a user/group whose id does not match the default (1000:1000). Failing to do this could make files change permissions on the linked volume when accessed from RStudio.

Adding additional users: From a root bash shell (see above), the usual debian linux commands can be used to create new users and passwords, e.g.

Here is my solution:
docker run -d -p 8787:8787 -v $(pwd)/myfolder:/home/rstudio/myfolder:z -e PASSWORD=aPogee rocker/rstudio

Here is the error I get when trying to save.
When I try to write a simple file
> getwd()
[1] "/home/rstudio/myfolder"

10 Apr 2021 01:04:52 [rsession-rstudio] ERROR system error 2 (No such file or directory) [path: /home/rstudio/myfolder/temp.R]; OCCURRED AT rstudio::core::Error rstudio::core::FilePath::openForWrite(std::shared_ptr<std::basic_ostream<char> >&, bool) const src/cpp/shared_core/FilePath.cpp:1482; LOGGED FROM: rstudio::core::Error rstudio::core::{anonymous}::openFileForWritingWithRetry(const rstudio::core::FilePath&, bool, int, std::shared_ptr<std::basic_ostream<char> >*) src/cpp/core/FileSerializer.cpp:73


text:
Q: Using Wireguard VPN for whitelisted public domains only The current setup: I have a set of private ec2 instances running a few services that I don't want to be accessible publicly and should be accessible only via the Wireguard VPN connection. There is also an ec2 instance with in the same VPC running a Wireguard VPN server. There is an ALB sitting in front of these private instances to route the public domains of the private services to their respective ALB target groups.
Looking for: A way to use the Wireguard VPN connection on the client side(for example my local host) to only route the public domains of the private services via the VPN connection and to send all the remaining traffic via the default network interface(not the Wireguard VPN interface). So I need to whitelist a handful of domain names to the client configuration.
Edit #1 Please mention any other tool that's better suited for my purpose.


text:
Q: Is There a Way to Dynamically Create a React Component I have multiple places in my React app where I have code like the below, just a large switch based on a format that will load the appropriate Component.  Is there a way to dynamically create the component in React?  Something similar to Reflection in Java, where I could do Class.instanceOf("Rule" + this.props.selectedFormatId");
renderRules() {
   switch (this.props.selectedFormatId) {
     case 1:
       return <Rules1 intl={this.props.intl} onRuleChange={this.props.onRuleChange}/>
     case 6:
       return <Rules6 intl={this.props.intl} onRuleChange={this.props.onRuleChange}/>
     case 7:
       return <Rules7 intl={this.props.intl} onRuleChange={this.props.onRuleChange}/>
       }
}

The ultimate goal is to just keep adding new Rules to the software without having to go into each of 5 places these switches appear and update them.

A: Yes, it's absolutely possible. You can do something like this:
const dynamicComponents = {
  1: Rules1,
  2: Rules2,
  3: Rules3
}
const someValue = 1
const DynamicComponent = dynamicComponents[someValue]
return <DynamicComponent intl={this.props.intl} onRuleChange={this.props.onRuleChange} /> // This would be Rules1

This would render Rules1. This would mean that in order to add a new component you just need to add it to the dynamicComponents object. If you want to keep it even simpler, you could just have an array:
const dynamicComponents = [
  Rules1,
  Rules2,
  Rules3
]
const someValue = 2
const DynamicComponent = dynamicComponents[someValue]
return <DynamicComponent intl={this.props.intl} onRuleChange={this.props.onRuleChange} /> // this would be Rules2

A: My method to solve similar issue is to save an object literal ("map") between key and component constructor, then given the key I have a reference to the Component.
const compMap = {
  key1: require('./Component1'),
  key2: require('./Component2'),
  key3: require('./Component3'),
};

// usage of the map
renderRules() {
  const Comp = compMap[this.props.selectedFormatId];
  return (<Comp prop1="prop1" />);
}


text:
Q: Vue.js problems with custom validation directive I have a custom validation directive in vue.js. Validator works fine while typing in textbox, but as soon as I call this.$validator.validateAll(), it passees validation, even it should not.
What i'm doing wrong here?
Validation code
//validiates email in database. if email is not same as initial and email is taken, it will fail validation
VeeValidate.Validator.extend('unique-email', {
    messages: {
        hr: (field, args) => {
            return "Some error message";
        }
    },
    validate: (value, args) => {
        var initialEmail = args[0];
        if (initialEmail === value) {
            return { valid: true }
        } else {
            return profileService.emailTaken(value).then((response) => {
                var emailTaken = response.data;
                return {valid:!emailTaken};
            });
        }
    }
});

Save button
 methods: {
    save: function() {
        this.$validator.validateAll().then(() => {
            //should not enter here, but it does
        });

    }
},

Html elemenent
 <input type="text" class="form-control" name="EMail" v-validate="'required|unique-email:'+ initialEmail" v-model="profile.EMail"/>

A: I verified the same issue. I'm not sure what the problem is. The issue appears to be discussed here, but it doesn't seem to be actually resolved.
I do have a workaround for you though. The errorBag property of $validator does appear to be set properly if there is a validation failure, so you can check it in your save method.
save: function() {
    this.$validator.validateAll().then(() => {
        const err = this.$validator.getErrors();
        if (err.errors.length > 0)
            //failed validation
        else
            //passed validation
    });
}


text: Q: Удаление большого количества записей со связанных таблиц Postgresql Я разрабатываю социальную сеть. У меня есть много таблиц, и некоторые из них: User, Post, UserAction (в этой таблице я сохраняю пользователя, которому понравился пост). У меня есть связь между User и Post и UserAction. Например, для одного пользователя у нас есть 100 000 постов. И если пользователь решит удалить учетную запись, нам нужно удалить все его посты. Это означает, что мы должны удалить все связанные данные из соответствующих таблиц. Но это займет очень много времени (и, возможно, это заблокирует запросы к таблице, я не помню, есть ли у Postgres механизм concurrent-удаления). Так какие же методы использовать, чтобы очень быстро удалить все эти данные? Большое спасибо за ваши ответы!


text:
Q: question regarding javascript;Html generation and search current webpage for tags Hi I have 3 questions, if you have for example this simple website

 www.hello1.com

 www.hello2.com

Question 1)
If I for instance decide to click on link number 2 (www.hello2.com), Is this stored in some kind of variable?
I know that this is storing the current URL but not the one that you click
window.location.href;

Question 2)
How do you search your document, say that I would like to search the this website and store all the links in a javascript array like this
    var myArray = [];

searchThisWebSiteForURLS()//Do this function that I don't know to write that search this htmlsite for url's

var myArray = [ 'http://www.hello1.com', 'http://www.hello2.com'];//This is the reslt after that the function has been executed

Question 3)
I would like to write out these links. Say that I have another table like this

 X

 Y

Where X = http://www.hello1.com
And Y = http://www.hello2.com

Of course it shall be as many rows as there are elements in the array like this

 X

 Y

 Z

 A

 B

Where Z, A, B are the elements 3,4,5 in the array
 var myArray = [ 'http://www.hello1.com', 'http://www.hello2.com','http://www.hello3.com','http://www.hello4.com','http://www.hello5.com'];

EDIT!--------------------------------------------------------------------------
Wow really thanks, all of you, really thanks! I just have one more question regarding the links, when comparing two links, say that the array looks like this
var pageLinks = ['http://www.example.at', 'http://www.example2.at', 'http://www.someothersite.at'];

And say that the user has pressed the example "http://www.example.at" link, then I want to create the table containing the similar links. So I do something like this
function checkForSimilarLink(theLinkToCompareWith){// in this case theLinkToCompareWith = "http://www.example.at"
    var numLinks = pageLinks.length;

    for(var i = 0; i < numLinks; i++) {
       //Check if numLinks[i]== theLinkToCompareWith*
    }
}

So how would you write this compare function? In this case we can consider
"http://www.example.at" and "http://www.example1.at" the "same" while "http://www.someothersite.at" obviosly aren't
Thanks again :)

A: I didn't understand question 1, but here's something for question 2 and 3:
Question 2:
var pageLinks  = [];
var anchors    = document.getElementsByTagName('a');
var numAnchors = anchors.length;
for(var i = 0; i < numAnchors; i++) {
    pageLinks.push(anchors[i].href);
}
//now pageLinks holds all your URLs

Question 3:
// say pageLinks holds your desired URLs
var pageLinks = ['http://www.example.at', 'http://www.example2.at', 'http://www.example3.at'];

// create an empty table
var table     = document.createElement('table');

// ... and it's tbody
var tbody     = document.createElement('tbody');

// loop through your URLs
var numLinks = pageLinks.length;
for(var i = 0; i < numLinks; i++) {

    // create new table row...
    var tr   = document.createElement('tr');

    // a cell...
    var td   = document.createElement('td');

    // and your anchor...
    var a    = document.createElement('a');

    // set the anchor's href
    a.setAttribute('href', pageLinks[i]);
    // set the anchor's text, it's also the URL in this example
    a.innerHTML = pageLinks[i];

    // append the anchor to the table cell
    td.appendChild(a);

    // ... and that cell to the new row
    tr.appendChild(td);

    // ... and that row to the tbody, right? ;-)
    tbody.appendChild(tr);
}

// after all rows were added to the tbody,
// append tbody to the table
table.appendChild(tbody);

// and finally append this table to any existing
// element in your document, e.g. the body:
document.body.appendChild(table);

// ...or add it to a div for example:
//document.getElementById('anyDiv').appendChild(table);

A: Go study JQuery!!!! XDD The best for web development.
for the first and second question in with jquery:
var anchors = $('a'); //returns all  elements from here you can get the url from all of theam

With jquery u can write any element that you want.
var table = $('

');
var tr = $('

').appendTo(table);
var td = $('	').setText('your link here')appendTo(tr);

. . .
table.appendTo(The parent element to add the table);

A: Question 1:
You can capture the onclick event for clicking on the link and during that store whatever information you want to a variable of your choosing (though, this would only be relevant if you included return false in the onclick event because the link would otherwise take the user to a new page and end your session).
Question 2 and 3 were answered quite well by Alex.


text:
Q: Find a file and execute a command in the file's directory I am trying to use find so it would find a script file and if found execute it in the same directory it found it in.
Something like this:
find . -name "CLEAN" -execdir "CLEAN" {} \;

except {} is the found file itself, which is not what I want.

A: May I suggest:
find . -type f -name "CLEAN" -execdir ./CLEAN \;

and in CLEAN, set your pwd rather than having it passed:
#!/bin/sh

MYDIR=`pwd`
echo "${MYDIR}"

A: if "CLEAN" is shell script file
than this work
  find . -name "CLEAN.sh" -execdir sh -c './CLEAN.sh' sh {} \;

this command file CLEAN.sh and it execute in finding directory.


text:
Q: Calculate active contracts based on start and end date in Power BI? My Data looks something like this:
ContractID  Start Date  End Date
1           01.01.2020  23.03.2020
2           15.02.2020  29.07.2020
3           06.06.2020  null

The last contract would be still active. I have a DateTable with the Start Date as the active relationship.
I need the end result too look like this:
Date    Active Contracts
Jan     1
Feb     2
Mar     2
Apr     1
May     1
Jun     2

How should the measure look like?
Thanks in advance!

A: Assuming you have a month in your date table
VAR currentMonth = SELECTEDVALUE(MyDataTable[Month value]) --needs to be a number 1 to 12
RETURN CALCULATE(COUNTROWS(MyDataTable),
    ALL(DateTable),
    MONTH(MyDataTable[Start Date]) >= currentMonth,
    ISBLANK(MyDataTable[End Date]) || MONTH(MyDataTable[End Date]) <= currentMonth)


text:
Q: Erlang error: no function clause matching io:request I'm an experienced programmer new to Erlang and I'm stuck on the following:
myread() ->
    {_, MyData } = file:read_file( "hands.txt" ),
    io:format( "hands-out.txt", "~w", MyData ).

yields, when myread() is invoked from the shell:
** exception error: no function clause matching io:request("hands-out.txt",
          {format,"~w", <<"3h 5h 7h 8h 3h 5h 7h 8h q"...>>})
      (io.erl, line 556)  in function  io:o_request/3 (io.erl, line 63)

Any help would be appreciated.

A: Two things:
"hands-out.txt", "~w" needs to be one string: "hands-out.txt: ~w"
and the data that's replacing the ~w needs to be a list. So:
io:format( "hands-out.txt: ~w", [MyData] ).
See http://erlang.org/doc/man/io.html#format-2
Also, you should pattern match on the status value in the return from file:read_file/1. In your version, an error, which would be returned as {error, Reason} would match here, since you're using _, and you'd print the error reason rather than the file, which might be confusing.
So either make it {ok, MyData } = file:read_file( "hands.txt" ) if you want to crash on read error, or something like the following if you want to handle that case:
myread() ->
  case file:read_file( "hands.txt" ) of
    {ok, MyData } ->
      io:format( "hands-out.txt: ~w", [MyData] );
    {error, Error} ->
      io:format("Error: ~w~n", [Error])
  end.


text:
Q: Multiple start scripts using Gradle I have a working Maven build (shown below) that prepares a couple of executables to launch as two separate processes.
Although this works fine, how can this be done using Gradle? I see that Gradle provides a plugin called application, but I have a hard time finding a nice example on how to tell it that when typing: gradle stage, it should create 2 executables.
Right now when I call stage it only provides an executable on the "root" mainclass defined in my gradle script:
apply plugin: 'java'
apply plugin: 'application'

mainClassName = 'SpringLauncher'
applicationName = 'foo'
compileJava.options.encoding = 'UTF-8'
targetCompatibility = '1.7'
sourceCompatibility = '1.7'

task stage(dependsOn: ['clean', 'installApp', 'hello'])

And the Maven build:
<build>
<plugins>
  <plugin>
    <groupId>org.codehaus.mojo</groupId>
      <artifactId>appassembler-maven-plugin</artifactId>
      <version>1.1.1</version>
      <configuration>
        <assembleDirectory>target</assembleDirectory>
        <programs>
            <program>
                <mainClass>foo.bar.scheduler.SchedulerMain</mainClass>
                <name>scheduler</name>
            </program>
            <program>
                <mainClass>SpringLauncher</mainClass>
                <name>web</name>
            </program>
        </programs>
      </configuration>
      <executions>
          <execution>
              <phase>package</phase><goals><goal>assemble</goal></goals>
          </execution>
      </executions>
  </plugin>
</plugins>

A: It might be better to use JavaExec
task scheduler(type: JavaExec) {
   main = "foo.bar.scheduler.SchedulerMain"
   classpath = sourceSets.main.runtimeClasspath
}

task web(type: JavaExec) {
   main = "SpringLauncher"
   classpath = sourceSets.main.runtimeClasspath
}

You can then run gradle scheduler web

A: Unfortunately the gradle application plugin does not provide first class support for multiple executable scripts.
Luckily though, because gradle scripts are groovy, you can change what the application plugin does reasonably easily.
The documentation for the Application plugin show that the startScripts task is of type CreateStartScripts, so try creating yourself a second task of the same type
task schedulerScripts(type: CreateStartScripts) {
    mainClassName = "foo.bar.scheduler.SchedulerMain"
    applicationName = "scheduler"
    outputDir = new File(project.buildDir, 'scripts')
    classpath = jar.outputs.files + project.configurations.runtime
}

then include the output of that task in your distribution
applicationDistribution.into("bin") {
            from(schedulerScripts)
            fileMode = 0755
}

A: Kotlin DSL
Reusable Function
The equivalent of the accepted answer using Gradle Kotlin DSL, and additionally abstracting out the common logic for creating multiple scripts into a re-usable function:
fun createAdditionalScript(name: String, configureStartScripts: CreateStartScripts.() -> Unit) =
  tasks.register<CreateStartScripts>("startScripts$name") {
    configureStartScripts()
    applicationName = name
    outputDir = File(project.buildDir, "scripts")
    classpath = tasks.getByName("jar").outputs.files + configurations.runtimeClasspath.get()
  }.also {
    application.applicationDistribution.into("bin") {
      from(it)
      fileMode = 0b000_111_101_101
      duplicatesStrategy = DuplicatesStrategy.EXCLUDE
    }
  }

and now you can use it like this:
createAdditionalScript("foo") {
  mainClassName = "path.to.FooKt"
}

createAdditionalScript("bar") {
  mainClassName = "path.to.BarKt"
}

Reusability via buildSrc
The function createAdditionalScript is better placed in buildSrc or plugin to keep the main script clean, and to do that, it would look like this:
import org.gradle.api.Project
import org.gradle.api.file.DuplicatesStrategy
import org.gradle.api.plugins.JavaApplication
import org.gradle.api.tasks.application.CreateStartScripts
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.register
import java.io.File

fun Project.createAdditionalScript(name: String, configureStartScripts: CreateStartScripts.() -> Unit) =
  tasks.register<CreateStartScripts>("startScripts$name") {
    configureStartScripts()
    applicationName = name
    outputDir = File(buildDir, "scripts")
    classpath = tasks.getByName("jar").outputs.files + configurations.getByName("runtimeClasspath")
  }.also {
    configure<JavaApplication> {
      applicationDistribution.into("bin") {
        from(it)
        fileMode = 0b000_111_101_101
        duplicatesStrategy = DuplicatesStrategy.EXCLUDE
      }
    }
  }

Note the fileMode uses the binary permissions representation to set the r, w, and x bits for user, group, and other. The Kotlin DSL doesn't interpret values like 0755 as octal like Groovy does.

A: The simples approach I found was adding a new CreateStartScripts task and making it a dependency of schedulerScripts:
task schedulerScripts(type: CreateStartScripts) {
    mainClassName = 'foo.bar.scheduler.SchedulerMain'
    applicationName = 'scheduler'
    classpath = startScripts.classpath
    outputDir = startScripts.outputDir
}
startScripts.dependsOn schedulerScripts


text:
Q: SMLNJ list traversion How would I go about traversing a list in SMLNJ. I have been at this for 3 hours now and I cannot figure it out for the life of me.
So just to traverse and print a list out. In the simplest way [5,2,3] would print out 5 2 3 or a list variant of this.

A:
How would I go about traversing a list in SMLNJ

It depends on the type of traversal you want to do: mapping, folding, iterating.
Using recursion:
(* mapping: *)
fun incr_each_by_1 [] = []
  | incr_each_by_1 (x::xs) = x + 1 :: incr_each_by_1 xs

val demo_1 = incr_each_by_1 [5,2,3] (* [6,3,4] *)

(* folding: *)
fun sum_all_together [] = 0
  | sum_all_together (x::xs) = x + sum_all_together xs

val demo_2 = sum [5,2,3] (* 10 *)

(* iteration: *)
fun print_each [] = ()
  | print_each (x::xs) = ( print (Int.toString x ^ "\n") ; print_each xs )

val demo_3 = print_each [5,2,3] (* no result, but side-effect *)

Using higher-order functions:
val demo_1 = List.map (fn x => x + 1) [5,2,3]
val demo_2 = List.foldl (fn (x, result) => x + result) 0 [5,2,3]
val demo_3 = List.app (fn x => Int.toString x ^ "\n") [5,2,3]


text:
Q: Android: Private message app I want to develop an app which broadcast messages which can be viewed only through this app. so, it can be used by teachers to broadcast instructions which students with this app (or a reciever app) can access. Can anyone help me with ideas to implement this?

A: You need to have external server which will store the messages. Your client app will then connect to the server and pull new data.
Personally, I'd go with PHP website for the server, as it can be implemented quickly.

A: Try to have a look on the http://www.parse.com API to implement User access and Push easily. It's really awesome !
You can create a free account and use it until 1 000 000 request by month, which can be enough I think...


text:
Q: How to create a Python HMAC from a Postman JavaScript I am trying to recreate a portion of JavaScript code taken in Postman and need to do the same in Python.
Basically I need to generate a HMAC SHA256 in Python that needs to be used on all requests when communicationg with an API.
Testing in Postman (JavaScript code) with my credentials (app_id and app_secret), everything runs fine.
In Python I am getting a 401 error response (wrong signature).
The Original JavaScript code:
let uuid = require('uuid');

const client_id = pm.environment.get("app_id").toString();
const client_secret = pm.environment.get("app_secret").toString();

let request_content_base64 = "";
let request_method = request.method;
let request_nonce = uuid.v4().toString();
let request_timestamp = Math.round(new Date().getTime() / 1000);
let body_string = pm.variables.replaceIn(pm.request.body.toString());
let request_url = pm.variables.replaceIn(pm.request.url.toString());

if (body_string) {
    var md5 = CryptoJS.MD5(body_string);
    request_content_base64 = CryptoJS.enc.Base64.stringify(md5);
}

let signature = `${client_id}${request_method}${request_url}${request_timestamp}${request_nonce}${request_content_base64}`;

let client_secret_string = CryptoJS.enc.Base64.parse(client_secret);
let signature_bytes = CryptoJS.HmacSHA256(signature, client_secret_string);
let signature_hashBase64 = CryptoJS.enc.Base64.stringify(signature_bytes);

pm.variables.set("hmac", `${client_id}:${signature_hashBase64}:${request_nonce}:${request_timestamp}`);

My hardcoded Python code:
def generate_mac(uri, method, body=None):
    app_id = 'my_secret_app_id'
    app_secret = 'my_secret_app_secret_key'
    app_secret = base64.b64decode(app_secret)

    timestamp = int(time.time())
    nonce = str(uuid.uuid4())
    content = ""
    if body is not None:
        body_md5 = hashlib.md5(body.encode('utf-8')).digest()
        content = base64.b64encode(body_md5).decode('utf-8')

    message = app_id + method + uri + str(timestamp) + nonce + content
    message_bytes = message.encode('utf-8')

    signature = hmac.new(app_secret, msg=message_bytes, digestmod=hashlib.sha256).digest()
    hashed = base64.b64encode(signature).decode('utf-8')
    return "{}:{}:{}:{}".format(app_id, hashed, nonce, timestamp)

I am using GET request as:
data = {
        'sample_key': 1,
        'sample_key1': 10,
    }
uri = 'https://api-serviceprovider-url/posts'
method = 'GET'
body = str(data)
hashed = generate_mac(uri, method, body)

head = {'Authorization': f"ApiKey {hashed}"}
r = requests.get(uri, headers=head)

For generating the signature, the documentation refers (translated into English):
First, the client needs to create a string (MAC) that will have all the data from the request that wants to send to API:
AppId + HTTP Method + Nonce (unique string for each request) + URI + UNIX Timestamp + base64 string of md5 from payload
Once the string is created, a SHA256 hash of the string must be generated using the appsecret provided initially. The signature will consist of AppId, signature, timestamp, and nonce separated by : .
[ApiKey AppId:hash:nonce:timestamp]
Tried with no sucess to generate the Python version of the HMAC as per python code block.