text:
Q: How to forward X over SSH to run graphics applications remotely? I have a machine running Ubuntu which I SSH to from my Fedora 14 machine. I want to forward X from the Ubuntu machine back to Fedora so I can run graphical programs remotely. Both machines are on a LAN.
I know that the -X option enables X11 forwarding in SSH, but I feel like I am missing some of the steps.
What are the required steps to forward X from a Ubuntu machine to Fedora over SSH?

A: X11 forwarding needs to be enabled on both the client side and the server side.
On the client side, the -X (capital X) option to ssh enables X11 forwarding, and you can make this the default (for all connections or for a specific connection) with ForwardX11 yes in ~/.ssh/config.
On the server side, X11Forwarding yes must be specified in /etc/ssh/sshd_config. Note that the default is no forwarding (some distributions turn it on in their default /etc/ssh/sshd_config), and that the user cannot override this setting.
The xauth program must be installed on the server side. If there are any X11 programs there, it's very likely that xauth will be there. In the unlikely case xauth was installed in a nonstandard location, it can be called through ~/.ssh/rc (on the server!).
Note that you do not need to set any environment variables on the server. DISPLAY and XAUTHORITY will automatically be set to their proper values. If you run ssh and DISPLAY is not set, it means ssh is not forwarding the X11 connection.
To confirm that ssh is forwarding X11, check for a line containing Requesting X11 forwarding in the output of ssh -v -X. Note that the server won't reply either way, a security precaution of hiding details from potential attackers.

A: Make sure that:

*

*You've xauth installed on the server (see: xauth info/xauth list).

*On the server your /etc/ssh/sshd_config file have these lines:
X11Forwarding yes
X11DisplayOffset 10
X11UseLocalhost no

*On the client side your ~/.ssh/config file have these lines:
Host *
  ForwardAgent yes
  ForwardX11 yes

*On the client side, you've X server installed (e.g. macOS: XQuartz; Windows: Xming).

Then to do X11 forwarding using SSH, you need to add -X to your ssh command, e.g.
ssh -v -X user@host

then verify that your DISPLAY is not empty by:
echo $DISPLAY

If it is, then having verbose parameter for ssh (-v), check for any warnings, e.g.
debug1: No xauth program.
Warning: untrusted X11 forwarding setup failed: xauth key data not generated

In case you've got untrusted X11 as shown above, then try -Y flag instead (if you trust the host):
ssh -v -Y user@host

See: What does "Warning: untrusted X11 forwarding setup failed: xauth key data not generated" mean when ssh'ing with -X?

In case you've warning: No xauth data, you may try to generate a new .Xauthority file, e.g.
xauth generate :0 . trusted
xauth list

See: Create/rebuild a new .Xauthority file

If you've got a different warnings than above, follow the further clues.

A: Letting Ubuntu bash on Windows 10 run ssh -X  to get a GUI environment on a remote server

*

*First

Install all the following. On Window, install Xming. On Ubuntu in the terminal, use sudo apt install to install ssh xauth xorg.
sudo apt install ssh xauth xorg

*

*Second

Go to the folder contains ssh_config file, mine is /etc/ssh.

*

*Third

Edit ssh_config as administrator(USE sudo). Inside ssh_config, remove the hash # in the lines ForwardAgent, ForwardX11, ForwardX11Trusted, and set the corresponding arguments to yes.
# /etc/ssh/ssh_config

Host *
    ForwardAgent yes
    ForwardX11 yes
    ForwardX11Trusted yes

*

*Forth

In ssh_config file, remove the front hash # before Port 22 and Protocol 2, and also append a new line at the end of the file to state the xauth file location, XauthLocation /usr/bin/xauth, remember write your own path of xauth file.
# /etc/ssh/ssh_config

#   IdentifyFile ...
    Port 22
    Protocol 2
#   Cipher 3des
#   ...
#   ...
    ...
    ...
    GSSAPIDelegateCredentials no
    XauthLocation /usr/bin/xauth

*

*Fifth

Now since we are done editing ssh_config file, save it when we leave the editor. Now go to folder ~ or $HOME, append export DISPLAY=localhost:0 to your .bashrc file and save it.
# ~/.bashrc
...
...
export DISPLAY=localhost:0

*

*Last

We are almost done. Restart your bash shell, open your Xming program and use ssh -X yourusername@yourhost. Then enjoy the GUI environment.
ssh -X yourusername@yourhost

The problem is also in Ubuntu subsystem on Windows, and the link is at
https://gist.github.com/DestinyOne/f236f71b9cdecd349507dfe90ebae776

A: Add X11UseLocalhost no to /etc/ssh/sshd_config and restart the SSH server.
If you get no DISPLAY, check if xauth is installed correctly and then try it again.
RHE/CEntos doesn't have this issue, this is a Ubuntu thing!

A: If you are doing ssh from Windows (10) to a Linux system - do yourself a favour and use a SSH client like Putty ( regular ssh -X etc does not work).
Step 1: Install a XServer in Windows : Example XMing Server (listens on localhost:0.0)
Step 2: In putty enable X11 forwarding
Step 3: Connect to remote Linux server
Make sure all conditions here are met in Linux server - that is X11Forwarding is yes and xauth is present as explained in the answer https://unix.stackexchange.com/a/12772/121634
Fire up XClock and wait a minute for the display to appear in your Windows machine
Note - If from this Linux server you are connecting to another server and want to forward X11 back to your Windows, you just need to connect to the next in chain with ssh -X.
That is
[Windows] Putty (with X11forwarding) --> [Server1] (xclock works) --> ssh -X [Server 2] (xclock works)

A: The fix is to add this line to your /etc/ssh/sshd_config:
X11UseLocalhost no

https://joshua.hoblitt.com/rtfm/2013/04/how_to_fix_x11_forwarding_request_failed_on_channel_0/

A: To get X11 forwarding working over SSH, you'll need three things in place:

*

*Your client must be set up to forward X11.

*Your server must be set up to allow X11 forwarding.

*Your server must be able to set up X11 authentication.

If you have both #1 and #2 in place but are missing #3, then you'll end up with an empty DISPLAY environment variable.
Soup-to-nuts, here is how to get X11 forwarding working:

*

*On your server, make sure /etc/ssh/sshd_config contains:
X11Forwarding yes
X11DisplayOffset 10

You may need to SIGHUP sshd so it picks up these changes.
cat /var/run/sshd.pid | xargs kill -1

*On your server, make sure you have xauth installed.
belden@skretting:~$ which xauth
/usr/bin/xauth

If you do not have xauth installed, you will run into the empty DISPLAY environment variable problem.

*On your client, connect to your server. Be certain to tell ssh to allow X11 forwarding. I prefer
belden@skretting:~$ ssh -X blyman@the-server

but you may like
    belden@skretting:~$ ssh -o ForwardX11=yes blyman@the-server

or you can set this up in your ~/.ssh/config.

I was running into this empty DISPLAY environment variable earlier today when ssh'ing into a new server that I do not administer. Tracking down the missing xauth part was a bit fun. Here is what I did, and what you can do too.
On my local workstation, where I am an administrator, I verified that /etc/ssh/sshd_config was set up to forward X11. When I ssh -X back in to localhost, I do get my DISPLAY set correctly.
Forcing DISPLAY to get unset was not too hard. I just needed to watch what sshd and ssh were doing to get it set correctly. Here is the full output of everything I did along the way.
    blyman@skretting:~$ mkdir ~/dummy-sshd
    blyman@skretting:~$ cp -r /etc/ssh/* ~/dummy-sshd/
    cp: cannot open `/etc/ssh/ssh_host_dsa_key' for reading: Permission denied
    cp: cannot open `/etc/ssh/ssh_host_rsa_key' for reading: Permission denied

Instead of using sudo to force copying my ssh_host_{dsa,rsa}_key files into place, I used ssh-keygen to create dummy ones for myself.
    blyman@skretting:~$ ssh-keygen -t rsa -f ~/dummy-sshd/ssh_host_rsa_key
    Generating public/private rsa key pair.
    Enter passphrase (empty for no passphrase):
    Enter same passphrase again:
    Your identification has been saved in /home/blyman/dummy-sshd/ssh_host_rsa_key.
    Your public key has been saved in /home/blyman/dummy-sshd/ssh_host_rsa_key.pub.

Rinse-and-repeate with -t dsa:
    blyman@skretting:~$ ssh-keygen -t dsa -f ~/dummy-sshd/ssh_host_dsa_key
    # I bet you can visually copy-paste the above output down here

Edit ~/dummy-sshd/sshd_config to point to the correct new ssh_host key files.
    # before
    blyman@skretting:~$ grep ssh_host /home/blyman/dummy-sshd/sshd_config
    HostKey /etc/ssh/ssh_host_rsa_key
    HostKey /etc/ssh/ssh_host_dsa_key

    # after
    blyman@skretting:~$ grep ssh_host /home/blyman/dummy-sshd/sshd_config
    HostKey /home/blyman/dummy-sshd/ssh_host_rsa_key
    HostKey /home/blyman/dummy-sshd/ssh_host_dsa_key

Fire up sshd on a new port in non-detach mode:
    blyman@skretting:~$ sshd -p 50505 -f ~/dummy-sshd/sshd_config -d
    sshd re-exec requires execution with an absolute path

Whoops, better correct that path:
    blyman@skretting:~$ /usr/sbin/sshd -p 50505 -f ~/dummy-sshd/sshd_config -d
    debug1: sshd version OpenSSH_5.5p1 Debian-4ubuntu6
    debug1: read PEM private key done: type RSA
    debug1: Checking blacklist file /usr/share/ssh/blacklist.RSA-2048
    debug1: Checking blacklist file /etc/ssh/blacklist.RSA-2048
    debug1: private host key: #0 type 1 RSA
    debug1: read PEM private key done: type DSA
    debug1: Checking blacklist file /usr/share/ssh/blacklist.DSA-1024
    debug1: Checking blacklist file /etc/ssh/blacklist.DSA-1024
    debug1: private host key: #1 type 2 DSA
    debug1: setgroups() failed: Operation not permitted
    debug1: rexec_argv[0]='/usr/sbin/sshd'
    debug1: rexec_argv[1]='-p'
    debug1: rexec_argv[2]='50505'
    debug1: rexec_argv[3]='-f'
    debug1: rexec_argv[4]='/home/blyman/dummy-sshd/sshd_config'
    debug1: rexec_argv[5]='-d'
    Set /proc/self/oom_adj from 0 to -17
    debug1: Bind to port 50505 on 0.0.0.0.
    Server listening on 0.0.0.0 port 50505.
    debug1: Bind to port 50505 on ::.
    Server listening on :: port 50505.

Pop a new terminal and ssh into localhost on port 50505:
    blyman@skretting:~$ ssh -p 50505 localhost
    The authenticity of host '[localhost]:50505 ([::1]:50505)' can't be established.
    RSA key fingerprint is 81:36:a5:ff:a3:5a:45:a6:90:d3:cc:54:6b:52:d0:61.
    Are you sure you want to continue connecting (yes/no)? yes
    Warning: Permanently added '[localhost]:50505' (RSA) to the list of known hosts.
    Linux skretting 2.6.35-32-generic #67-Ubuntu SMP Mon Mar 5 19:39:49 UTC 2012 x86_64 GNU/Linux
    Ubuntu 10.10

    Welcome to Ubuntu!
     * Documentation:  https://help.ubuntu.com/

    1 package can be updated.
    0 updates are security updates.

    Last login: Thu Aug 16 15:41:58 2012 from 10.0.65.153
    Environment:
      LANG=en_US.UTF-8
      USER=blyman
      LOGNAME=blyman
      HOME=/home/blyman
      PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
      MAIL=/var/mail/blyman
      SHELL=/bin/bash
      SSH_CLIENT=::1 43599 50505
      SSH_CONNECTION=::1 43599 ::1 50505
      SSH_TTY=/dev/pts/16
      TERM=xterm
      DISPLAY=localhost:10.0
    Running /usr/bin/xauth remove unix:10.0
    /usr/bin/xauth add unix:10.0 MIT-MAGIC-COOKIE-1 79aa9275ced418dd445d9798b115d393

Look at the last three lines there. I fortuitously had DISPLAY set, and had those two nice-looking lines from /usr/bin/xauth.
From there it was child's play to move aside my /usr/bin/xauth to /usr/bin/xauth.old, disconnect from ssh and stop the sshd, then launch sshd and ssh back in to localhost.
When /usr/bin/xauth was gone, I did not see DISPLAY reflected in my environment.

There is nothing brilliant going on here. Mostly I got lucky in choosing a sane approach to try reproducing this on my local machine.

A: X11Forwarding must be set on the SSH server (in your case the Ubuntu box) in its sshd_config, and you must allow X11 to be forwarded for the SSH client (your Fedora box) by passing the -X option or editing the ssh_config file to add the ForwardX11 default.

A: For me the problem was in nodev mount option for /tmp filesystem.
X11 needs a special file to be created in there.
So check what are the mount options for /tmp filesystem if you use a separate partition or disk for that.

A: xauth can get locked.
   -b      This  option  indicates  that  xauth  should  attempt to break any authority file locks before proceeding.  Use this
           option only to clean up stale locks.

Using
xauth -b

On the machine that I was trying to ssh into broke the lock on xauth. Logging out of the ssh session after issuing xauth -b then logging back in finally allowed me to successfully echo $DISPLAY. Definitely try this before re-creating .Xauthority

A: To add to the previous excellent answers (setting up ~/.ssh/config and checking to see if the DISPLAY environment variable is set on the client, setting up /etc/ssh/sshd_config and installing xauth on the server), also make sure xterm is installed on the client, e.g.
sudo apt-get install xterm

A: *

*Follow this steps on both server and client sides

*

*For the server I have a unix-like OS

*

*make sure on file /etc/ssh/sshd_config you have yes line
X11Forwarding yes

*if was just enabled, restart ssh. In my case
sudo systemctl restart ssh

*On the client side I am on a macOS

*

*Provide xterm
brew install --cask xquartz

*Restart the computer was necessary before the first connect to server
ssh -Y user@host

*Check if it's working
chromium http://google.com

A: If you're using connection sharing, you need to close all existing connections before any changes to your client ssh options will take effect.
I was using a script to connect to a remote machine with these options set.
-oControlPath=${control_path}
-oControlMaster=auto

I was trying to change my client ssh options to enable X11 forwarding and couldn't figure out why they weren't taking effect. I had to close the existing connections and reconnect with the new client ssh options for enabling X11 forwarding for it to work. You could also just open a new connection by removing any options for setting the control path.
Took me awhile to figure this out. Hope this helps someone.


text:
Q: Fitnesse Eclipse plugin - How to convert eclipse project to Fitnesse project I am trying to use Fitnesse plugin available at:
http://fitnesse-eclipse.github.io/#intro
I have downloaded and installed the plugin in eclipse. I can see a new option 'FitNesse' on my tool bar and when I right-click on the project I can see the option of 'FitNesse->Open in Browser' as well. The thing which I am not able to get is that the user-guide mentions an option to convert the project to FitNesse Project. I do not get this option when I right-click on the project.
Is this something anyone else came across while using this plugin or am I the only one. Please help.

A: if you have the Open in Browser, it looks like you have already converted to a fitness project. what version of the plugin are you using?
it may be that you have installed the (https://code.google.com/p/fitnesse-editor/)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compute explicitly this oscillatory integral I would like to compute explicitly the oscillatory integral
$$I(y):=\int_{\mathbb{R}^{n}}\frac{e^{\imath |x-y|^2}}{1+|x|^m}dx,$$
$m> n$. Notice that when $m>n$ the integral $I(y)$ converges absolutely.
In spherical coordinates
$$I(y)=\int_{\mathbb{S}^{n-1}}\int_{0}^{\infty}\frac{e^{\imath |r\omega-y|^2}}{1+r^m}r^{n-1}drd\omega=e^{\imath |y|^2}\int_{\mathbb{S}^{n-1}}e^{\imath (\omega\cdot y)^2}\int_{0}^{\infty}\frac{e^{\imath (r-\omega\cdot y)^2}}{1+r^m}r^{n-1}drd\omega$$
as we can complete the square
$|r\omega-y|^2=r^{2}-2r\omega\cdot y+|y|^2=(r-\omega\cdot y)^2-(\omega\cdot y)^2+|y|^2$


text:
Q: Number Theory , Primes and sum of squares Show that if $a^2+b^2≡0 \pmod{p}$ , with $p$ a prime number and $p≡3\pmod{4}$
Then automatically $a≡0\pmod{p}$ and $b≡0\pmod{p}$
What I have done so far,
Suppose $a^2≡0\pmod{p}$ and $b^2≡0\pmod{p}$ , then $x+y≡0\pmod{p}$ with $0≤x<p$ and $0≤y<p$
Then $0≤x+y<2p$, which concludes that $x+y=0$ or $x+y=p$
I need to show that $x+y=p$ is impossible so that we're left with $x+y=0$ which helps me solve the problem.


text:
Q: Parallel freeze my form For Form1.cs
...
delegate void SetTextCallback(string text);
...

public void setText(string s)
{
    if (this.textbox1.InvokeRequired)
    {
        SetTextCallback d = new SetTextCallback(setText);
        this.Invoke(d, new object[] { s });
    }
    else
    {
        textbox1.AppendText(s + Environment.NewLine);
        Application.DoEvents();
    }
}
...
private void btn_Click(object sender, eventArgs e)
{
     Test t = new Test();
     t.run();
}

and for Test.cs
...
public void run()
{
    Parallel.ForEach(list, test =>
    {
        DoSomething(test);
        Form1.setText(test + "done!");
    }
}
...

After I run the program, it always frozen.
I searched about my problem, and I figured out it is because of deadlock problem.
How can I fix this?

A: You are correct it is a deadlock issue.
Parallel.ForEach blocks till the all of the items in list have been processed, and you made that run on the UI thread, so now the UI thread is blocked.
You then call Form1.setText(test + "done!"); and setText (the s really should be capital btw) calls this.Invoke which will block till the invoke call has finished being processed. However because we blocked the UI thread on the Parallel.ForEach it will never be processed and you just deadlocked!
The way to solve this is put the Parallel.ForEach call on it's own thread too so you do not block the UI thread.
public void run()
{
    Task.Factory.StartNew(() => Parallel.ForEach(list, test =>
    {
        DoSomething(test);
        Form1.setText(test + "done!");
    }), TaskCreationOptions.LongRunning);
}

You also could likely improve performance by changing this.Invoke to this.BeginInvoke1 so the text updating is non blocking too. However, If you only make the BeginInvoke change to your program and leave Parallel.ForEach on the UI thread you may not deadlock anymore but your UI will still freeze and say Not Responding until Parallel.ForEach completes.

1. Everywhere else if you call BeginXxxxx you MUST call EndXxxxx, however BeginInvoke on a class derived from Control is except from that rule and you are not required to call EndInvoke.


text:
Q: $dialog injection causing error in AngularJS Although this program works fine in Plunker http://plnkr.co/edit/1RmSI3liMKrE89f9YwFC?p=preview, When I add similar in MVC I get error about angular injector.
More specifically in following line:
var app = angular.module('MainCtrl', ['ui.bootstrap']);

app.controller('MainCtrl', ['$scope', '$dialog', function ($scope, $dialog) {

And error is as followed:
Error: [$injector:unpr] http://errors.angularjs.org/1.2.19/$injector/unpr?p0=%24dialogProvider%20%3C-%20%24dialog v/<@http://localhost:51533/Scripts/angular.min.js:6:443 dc/l.$injector<@http://localhost:51533/Scripts/angular.min.js:36:196 c@http://localhost:51533/Scripts/angular.min.js:34:273 dc/n.$injector<@http://localhost:51533/Scripts/angular.min.js:36:266 c@http://localhost:51533/Scripts/angular.min.js:34:273 d@http://localhost:51533/Scripts/angular.min.js:35:1 g/<.instantiate@http://localhost:51533/Scripts/angular.min.js:35:163 Pd/this.$get</<@http://localhost:51533/Scripts/angular.min.js:67:417 K/<@http://localhost:51533/Scripts/angular.min.js:54:40 q@http://localhost:51533/Scripts/angular.min.js:7:363 K@http://localhost:51533/Scripts/angular.min.js:53:405 f@http://localhost:51533/Scripts/angular.min.js:47:243 f@http://localhost:51533/Scripts/angular.min.js:47:243 z/<@http://localhost:51533/Scripts/angular.min.js:46:374 cc/c/</<@http://localhost:51533/Scripts/angular.min.js:18:279 Zd/this.$get</k.prototype.$eval@http://localhost:51533/Scripts/angular.min.js:112:308 Zd/this.$get</k.prototype.$apply@http://localhost:51533/Scripts/angular.min.js:113:24 cc/c/<@http://localhost:51533/Scripts/angular.min.js:18:237 d@http://localhost:51533/Scripts/angular.min.js:35:27 cc/c@http://localhost:51533/Scripts/angular.min.js:18:145 cc@http://localhost:51533/Scripts/angular.min.js:18:349 Xc@http://localhost:51533/Scripts/angular.min.js:17:432 @http://localhost:51533/Scripts/angular.min.js:213:1 jQuery.Callbacks/fire@http://localhost:51533/Scripts/jquery-2.1.1.js:3073:1 jQuery.Callbacks/self.fireWith@http://localhost:51533/Scripts/jquery-2.1.1.js:3185:7 .ready@http://localhost:51533/Scripts/jquery-2.1.1.js:3391:3 completed@http://localhost:51533/Scripts/jquery-2.1.1.js:3407:2
e/<()angular.min.js (line 92)
Rd/this.$get</<()angular.min.js (line 68)
Zd/this.$get</k.prototype.$apply()angular.min.js (line 113)
cc/c/<()angular.min.js (line 18)
d()angular.min.js (line 35)
cc/c()angular.min.js (line 18)
cc()angular.min.js (line 18)
Xc()angular.min.js (line 17)
angular.min.js()angular.min.js (line 213)
jQuery.Callbacks/fire()jquery-2.1.1.js (line 3073)
jQuery.Callbacks/self.fireWith()jquery-2.1.1.js (line 3185)
.ready()jquery-2.1.1.js (line 3391)
completed()jquery-2.1.1.js (line 3407)
angul

A: I see you are using angular bootstrap, then the proper way to inject it is
angular.module('yourApp', ['ui.bootstrap']);

not $dialog as it's undefined at this level
you also have to inject $dialog into controller
http://plnkr.co/edit/anfWml1umuH7miU4JDhM?p=preview


text:
Q: Want to integrate zxing library in to my application I integrated zxing libary using this tutorial http://www.androidaz.com/development/zxing-qr-reader-direct-integration, but i can not able to read QR Code continuously it is in progress of reading .

A: I recently completed working on QR Code scanner. you should use this library. How to use it is explained properly and it works great. It also scans continuously, so it will solve that problem of yours as well.
Let me know if you need any other help.

A: For me,
I will use original Intent method for your case. There should have an android version for the zxing library for the barcode scanning.
Unlike the page you have mentioned, you will have to include the below in your androidManifest.xml inside application tag:
<activity
        android:name="com.google.zxing.client.android.CaptureActivity"
        android:clearTaskOnLaunch="true"
        android:screenOrientation="sensorLandscape"
        android:stateNotNeeded="true"
        android:theme="@style/CaptureTheme"
        android:windowSoftInputMode="stateAlwaysHidden" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
        <intent-filter>
            <action android:name="com.google.zxing.client.android.SCAN" />

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

In your Activity Class, you should call the barcode scanner by using intent as follow:
private final int QR_CODE = 0;
try {
        Intent intent = new Intent(
                "com.google.zxing.client.android.SCAN");
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
        intent.putExtra("SCAN_MODE", "SCAN_MODE");
        startActivityForResult(intent, QR_CODE);
} catch (Exception e) {
            //Handle the case when barcode scanner is absence.
}

and handle the result from the barcode scanner using:
@Override
protected void onActivityResult(int requestCode, int resultCode,
        Intent intent) {
    if (requestCode == QR_CODE) {
        if (resultCode == RESULT_OK) {
            String code = intent.getStringExtra("SCAN_RESULT");
//you should handle recall of the barcode scanner using intent here
        }else if (resultCode == RESULT_CANCELED) {{
            //user cancelled barcode scanning process.
        }
    }
}

Hope that the above code could provide some idea for your case.


text:
Q: Termux - Android(pip install --only-binay :all: mysqlclient --user) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.

Did you install mysqlclient?

$ pip install --only-binary :all: mysqlclient --user

ERROR: Could not find a version that satisfies the requirement mysqlclient (from versions: none)

ERROR: No matching distribution found for mysqlclient

I am trying to execute a Python web-based Django project in Android.
How to solve this error? How can I be able to install required mysqlclient in termux?

A: The package name is mysql not mysqlclient.
pip install mysql

And don't install a precompiled binary from PyPI. Most likely that won't work in termux.


text:
Q: Simple way to identify concurrent events in pandas dataframe I am looking for a simple way to add a column to a dataframe that indicates if a given part has been purchased for at least two years in a row
Here is an example dataframe
df = pd.DataFrame(
    {
        'PART_UNIT':['A','A','A','B','B'],
        'FiscalYear':['2015/2016','2016/2017','2018/2019','2015/2016','2017/2018'],
        'PO_UNIT_PRICE':[10,12,11,45,54]
    }
)
print(df)

0         A  2015/2016             10
1         A  2016/2017             12
2         A  2018/2019             11
3         B  2015/2016             45
4         B  2017/2018             54

I am looking for a function like the one I would use when adding a standard deviation column
df['std'] = df.groupby(['PART_UNIT'])['PO_UNIT_PRICE'].transform(np.std)

to get a result like this
  PART_UNIT FiscalYear  PO_UNIT_PRICE  Concurrent
0         A  2015/2016             10           1
1         A  2016/2017             12           1
2         A  2018/2019             11           1
3         B  2015/2016             45           0
4         B  2017/2018             54           0

As you can see part "B" gets a 0 in the column, as it has not been purchased two years in a row.

A: import pandas as pd

df = pd.DataFrame(
    {
        'PART_UNIT': ['A', 'A', 'A', 'B', 'B'],
        'FiscalYear': ['2015/2016', '2016/2017', '2018/2019', '2015/2016', '2017/2018'],
        'PO_UNIT_PRICE': [10, 12, 11, 45, 54]
    }
)

print(df)

def two_years_in_a_row(fiscal_years):
    tmp = list(fiscal_years)
    for idx, year in enumerate(tmp):
        if idx > 0:
            if tmp[idx - 1].split('/')[1] == year.split('/')[0]:
                return 1
    return 0

print('----------------------------------------')

df['concurrent'] = df.groupby(['PART_UNIT'])['FiscalYear'].transform(two_years_in_a_row)

print(df)

output
 PART_UNIT FiscalYear  PO_UNIT_PRICE
0         A  2015/2016             10
1         A  2016/2017             12
2         A  2018/2019             11
3         B  2015/2016             45
4         B  2017/2018             54
----------------------------------------
  PART_UNIT FiscalYear  PO_UNIT_PRICE  concurrent
0         A  2015/2016             10           1
1         A  2016/2017             12           1
2         A  2018/2019             11           1
3         B  2015/2016             45           0
4         B  2017/2018             54           0


text:
Q: How to "get" a reliable parallel port on a laptop without a PCMCIA slot? Usb-Parallel port (for an old, but reliable matrix printer that has its special use) connections (cables) are unreliable. They sometimes work, sometimes don't - and since I installed Windows 7 I can't get neither of my old ones to work properly.
PCMCIA is usually considered (and it is) a much more reliable solution, but unfortunatelly, none of my new laptops has a PCMCIA slot.
So, all ideas are welcomed. What should I do? I'm open to all suggestions as long as you have some experience that they work more reliably than USB-Parallel cables and their wicked drivers.


text:
Q: PostingBack from ModalPopup, but keeping it visible? I have a ModalPopup that will contain a gridview and 4 fields to enter items into the gridview itself.
Is it possible to postback to the server and update the gridview while keeping the modal open?
When you submit the fields and the postback occurs the modal closes has anyone done this before? Someone mentioned a solution using jQuery, but this was long ago.

A: Wrapping the popup's content (i.e. not the popup itself!) in an UpdatePanel worked for me.
My popup content is a search panel with sortable/pageable grid of results.  The UpdatePanel gave me the exact behaviour I require with no additional code.
Thanks to Patel Shailesh for the idea.
<asp:Panel runat="server" ID="PopupPanel" Height="650" Width="900" Style="display: none">
    <asp:UpdatePanel runat="server" ID="UpdatePanel1">
        <ContentTemplate>
            <!-- popup content -->
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Panel>

<ajax:ModalPopupExtender runat="server" ID="PopupExtender" PopupControlID="PopupPanel"
    TargetControlID="PopupButton" />
<asp:Button runat="server" ID="PopupButton" Text="Popup" />

A: The key to doing this is going to be using AJAX of some flavor -- Microsoft.Ajax or jQuery Ajax.  If the UpdatePanel is not working, then I'd suggest using jQuery to submit back to the server using AJAX.  This would involve creating a WebMethod to accept the AJAX post on the server side and instrumenting the client-side with jQuery to send the request/receive the response.  Without seeing your HTML it's a little hard to be very specific.
Basic idea:
 $(function() {
    $('#modalSubmitButton').click( function() {
       $.ajax({
           url: 'path-to-your-web-method',
           dataType: 'json',  // or html, xml, ...
           data: function() {
               var values = {};
               values['field1'] = $('#field1ID').val();
               ...
               values['field4'] = $('#field4ID').val();
               return values;
           },
           success: function(data,status) {
              ... update page based on returned information...
           }
           ... error handling, etc. ...
       });
       return false; // stop any default action from the button clicked
    });
 });

A: I am not sure if this would work, but try to put whatever inside the modalpopup in a UpdatePanel
Please if this works don't hate me after you release, I hate updatepanels too

A: A kind of ugly option is to force a postback when showing the modal popup in the first place and setting a ViewState["ModelPopupOn"] = true; and then check that on page load and finally postback again and set it to false/remove it from viewstate when closing the popup.
(these kind of issues are why I hate the ajax toolkit)

A: I was experimenting with the modalpopupextender, and find a ugly solution.
If the modal panel has a button that makes the postback to happen
<asp:Panel runat="server" ID="PopupPanel" Height="650" Width="900" Style="display: none">
    <asp:Button ID="OkButton" runat="server" Text="OK" OnClick="OkBtn_Click"  />
</asp:Panel>

If the OkBtn_Click in the code-behind has a call to:
System.Web.HttpContext.Current.Response.Write("<script></script>");

Then the modalpopupextender is not closed.
This happened too to this guy:
http://forums.asp.net/t/1591860.aspx


text:
Q: Woocommerce Checkout does not complete – infinite spinning icon I'm having issues on Woo Commerce checkout page where there is infinite spinning icon stays there. Site hosted on Nginx virtual server. Woo commerce version is 3.2.1.
I have searched o forums and people had solved their issues either by increasing php memory or some css tricks.
Chrome Console shown these errors:
Failed to load resource: the server responded with a status of 405 (Not Allowed)
/?wc-ajax=update_order_review
Failed to load resource: the server responded with a status of 405 (Not Allowed)/?wc-ajax=get_refreshed_fragments
What I have tried to solve:

*

*Increased memory to 128M.
Disabled all other plugins, even disabled and enabled Woo commerce
plugin too.
Disabled cache.
Disabled Nginx redirect force to https.
Tried using another theme, also tried default simple theme.
In general settings, everything looks ok.
Woocommerce status shows no errors.
Still looking for solution..
Any solution/idea?


text:
Q: Using sys.exit in for loops I am writing a small python script that iterates through a large json output and grabs the information I need and puts it into small dictionaries. It then iterates through the dictionaries to look for an key called restartcount. If the count is more than more than 3 but less than 5 it prints warning. If greater than 5 it prints critical. However this script is set to be a nagios plugin which requires exit codes to be placed with warning sys.exit(1), and sys.exit(2) for critical. If you look at my script I use my function to grab the info I need into a small dictionary, then run a for loop. If I place a sys.exit after inside any if statement I iterate only through the first dictionary and the rest are not checked. Any help will be appreciated as to how to incorporate the exit codes without losing skipping or missing any information.
Code:
import urllib2
import json
import argparse
from sys import exit

def get_content(pod):
    kube = {}
    kube['name'] = pod["metadata"]["name"]
    kube['phase'] = pod["status"]["phase"]
    kube['restartcount'] = pod["status"]["containerStatuses"][0]["restartCount"]
    return kube

if __name__ == '__main__':
    parser = argparse.ArgumentParser( description='Monitor Kubernetes Pods' )
    parser.add_argument('-w', '--warning', type=int, help='levels we should look into',default=3)
    parser.add_argument('-c', '--critical', type=int, help='its gonna explode',default=5)
    parser.add_argument('-p', '--port', type=int, help='port to access api server',default=8080)
    args = parser.parse_args()

try:
    api_call = "http://localhost:{}/api/v1/namespaces/default/pods/".format(args.port)
    req = urllib2.urlopen(api_call).read()
    content = json.loads(req)
except urllib2.URLError:
    print 'URL Error. Please re-check the API call'
    exit(2)

for pods in content.get("items"):
    try:
        block = get_content(pods)
        print block
    except KeyError:
        print 'Container Failed'
        exit(2)

    if block["restartcount"] >= args.warning and block["restartcount"] < args.critical:
        print "WARNING | {} restart count  is {}".format(block["name"], block["restartcount"])

    if block["restartcount"] >= args.critical:
        print "CRITICAL | {} restart count  is {}".format(block["name"], block["restartcount"])

what the block variable looks like:
{'phase': u'Running', 'restartcount': 0, 'name': u'pixels-1.0.9-k1v5u'}

A: Create a variable called something like exit_status. Initialize it to 0, and set it as needed in your code (e.g. where you are currently calling exit). At the end of program execution, call sys.exit(exit_status) (and no where else).
Rewriting the last section of your code:
exit_status = 0
for pods in content.get("items"):
    try:
        block = get_content(pods)
        print block
    except KeyError:
        print 'Container Failed'
        exit(2)

    if block["restartcount"] >= args.warning and block["restartcount"] < args.critical:
        print "WARNING | {} restart count  is {}".format(block["name"], block["restartcount"])
        if exit_status < 1: exit_status = 1

    if block["restartcount"] >= args.critical:
        print "CRITICAL | {} restart count  is {}".format(block["name"], block["restartcount"])
        exit_status = 2

sys.exit(exit_status)

A: The variable approach is correct
Problem is that as you check further you probably set it to 1 when it was already 2 so I would suggest add here a condition not to set it to 1 if it is already 2


text:
Q: Proof of the inequality for the tail of the maximum of sums of independent random variables Let $ \xi_1, \ldots, \xi_n $ be independent random variables with $ \mathbf{E}\xi_i = 0 $ for $ 1\le i \le n. $ I need to prove that for all $ a>0 $
$$ \mathbf{P}(\max_\limits{1\le k \le n} S_k \ge a) \le 2 \mathbf{P}(S_n \ge a-\mathbf{E}|S_n|), $$
where $ S_n = \sum\limits_{k=1}^n \xi_k. $
I tried a lot of ways to solve this problem, but none were completed.
The first approach, that I tried to implement, was using the next statement:
$\textbf{Statement:}$
Denote $S_n^* = \max_\limits{1\le k \le n} S_k $ then for all $a, b \in \mathbf{R}$
$$ \mathbf{P}(S_n^* \ge a) \le \frac{\mathbf{P}(S_n\ge a-b)}{\max_\limits{1\le k \le n} \mathbf{P}(S_n - S_k \ge -b)}. $$
I tried to use it taking $ b = \mathbf{E}|S_n|$. All I needed to prove here is that
$$ \mathbf{P}(S_n - S_k \ge -\mathbf{E}|S_n|)\ge \frac{1}{2}. $$
I have done the next:
$$ \mathbf{P}(S_n - S_k < -\mathbf{E}|S_n|) = \mathbf{P}(S_k - S_n > \mathbf{E}|S_n|)\le \mathbf{P}(|S_n - S_k| > \mathbf{E}|S_n|) $$
and here in need to show that it is less than 1/2. But I don't know how to do that.
The second approach was to draw an analogy with the proof of Levi's inequality for the median-centered maximum sums. I introduced the next events:
$$ A_k = \{ S^*_{k-1}< a, S_k \ge a\} \quad \text{for} \quad k \le n $$
such that
$$ \{ S_n^* \ge a\} = \sum_{k\le n}A_k $$
also following this method I had to introduce the events $B_k$ (I don't know exactly how they look) such that
$$ \sum_{k\le n}A_kB_k \subset \{S_n > a - b\},\quad P(B_k) \ge 1/2. $$
But I got nothing. May be I need to use this strategy:
$$ \mathbf{P}(\max_\limits{1\le k \le n} S_k - \mathbf{E}|S_n| \ge a - \mathbf{E}|S_n|) \le \mathbf{P}(\max_\limits{1\le k \le n} S_k - \mathbf{E}S_n \ge c) $$
and show that right part of this equation is less than $ 2\mathbf{P}(S_n \ge c), $ where $c = a - \mathbf{E}|S_n|$.
I'm stuck. I will be very grateful for any help.


text:
Q: Spring security OAuth authentication requires ClientId and Secret In my Spring Security application I have able to use postman to fetch a JWT token from my "/oauth/token" endpoint successfully. However I wish for the /oauth/endpoint to be accessible by anybody wish to authenticate without needing clientId and secret.
My Security Server
@Configuration
@EnableWebSecurity
public class GatewaySecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Autowired
    private GatewayUserDetailsService gatewayUserDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        daoAuthenticationProvider.setUserDetailsService(gatewayUserDetailsService);
        return daoAuthenticationProvider;
    }

    @Override
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) {
        authenticationManagerBuilder.authenticationProvider(daoAuthenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/oauth/token").permitAll()
                .antMatchers("actuator/**").fullyAuthenticated();
    }

}

and my Resource Server
@EnableResourceServer
@Configuration
@Import(GatewaySecurityConfigurer.class)
public class GatewayResourceServerConfigurer extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer config) {
        config.tokenServices(tokenServices());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/oauth/token").permitAll()
                .antMatchers("actuator/**").fullyAuthenticated();
    }

    @Bean
    public TokenStore tokenStore() {
        TokenStore store = new JwtTokenStore(accessTokenConverter());
        return store;
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("123");
        return converter;
    }

    @Bean
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }

}

As you can see in both classes I've tried to implement a HttpSecurity configuration which will allow all requests to /oauth/token to be allowed which having other paths required to be authenticated. However I am struck with 401 null http responses in my postman requests when I post without clientId & secret.
How can I have my code as so clientId & Secret aren't needed to authenticate?

A: OAuth is a authorization framework. (See RFC 6749.) It allows third-party applications (clients) to obtain limited access to an HTTP service on behalf of a user. The authorization without a client doesn't make sense.
You probably just want a simple endpoint where users can log in and get a JWT.
The following tutorial explains how to build JWT authentication with custom Spring security filters: https://auth0.com/blog/securing-spring-boot-with-jwts


text:
Q: Задание: перевернуть список циклом. Есть код, но по какой-то причине он не работает Вот сам код:
j = len(list1)

for j in range(len(list1),0):
 slovo += list1[j]
 j -= 1

Python ошибки не выдает, просто останавливается на моменте между
j = len(list1) и

for j in range(len(list1,0):

A: Вообще разворот списка делается так:
print (list1[::-1])

A: Сделать переворот через цикл for:
items = [1, 2, 3, 4, 5, 6]
new_items = []

for i in range(len(items)):
    new_items.append(items[len(items) - i - 1])

# OR:
# for i in range(len(items), 0, -1):
#     new_items.append(items[i - 1])

# OR:
# for i in reversed(range(len(items))):
#     new_items.append(items[i])

print(new_items)  # [6, 5, 4, 3, 2, 1]

Или сделать через while:
items = [1, 2, 3, 4, 5, 6]
new_items = []

index = len(items) - 1

while index >= 0:
    item = items[index]
    new_items.append(item)

    index -= 1

print(new_items)  # [6, 5, 4, 3, 2, 1]

Помимо алгоритма через цикл и разворота через срез ([::-1]), есть конкретные функции:
list1.reverse()
list1 = reversed(list1)
# Чтобы получить именно тип список
list1 = list(reversed(list1))

reverse разворачивает элементы в самом списке
reversed возвращает итератор списка с развернутыми элементами


text:
Q: Opening xlsx file created with SpreadSheetGear I have created a simple Excel file using SpreadSheetGear. If I save it as an xls file
workbook.SaveAs("file.xls", SpreadsheetGear.FileFormat.Excel8);

and attach it to an email, I can open it on my phone (tested both with iPhone and Android).
If I save it as an xlsx file
workbook.SaveAs("file.xlsx", SpreadsheetGear.FileFormat.OpenXMLWorkbook);

and attach it to an email, I CANNOT open it on my phone.
If I open the xlsx file attachment on my computer and save it with no changes and attach it to an email, I now can open it on my phone.
Apparently Excel saves the file differently than SSG. The file size of the xlsx file attachment is 9 KB. When I open it on my computer and save it, the new file size is 24 KB.
Some of my users prefer the xlsx format. Is there anything I can do with to make the SSG generated file attachment open like an Excel generated file attachement?

A: iOS depends on certain attributes being present in the worksheet data of the Open XML file format to properly parse these files.  SpreadsheetGear does not write these attributes out because they are listed as optional in the Open XML file format specification and, also, omitting them reduces file size, as you have noted.  Excel, for whatever reason, always writes out these optional attributes and other third-party components often times rely on their presence to function correctly.  SpreadsheetGear V5 added a workaround to write out these attributes by enabling a certain "Experimental" option.  This option was added because the OLE DB provider also exhibits this errant behavior.  You might try something like the following and see if this helps in getting SpreadsheetGear to better work with your viewer:
IWorkbookSet workbookSet = Factory.GetWorkbookSet();
workbookSet.Experimental = "OleDbOpenXmlWorkaround";
IWorkbook workbook = workbookSet.Workbooks.Open(@"C:\temp\BadWorkbook.xlsx");
workbook.SaveAs(@"C:\temp\GoodWorkbook.xlsx", FileFormat.OpenXMLWorkbook);

Please see the SpreadsheetGear.IWorkbookSet.Experimental property for more information on this feature.
From what I can tell, iOS/Andriod/etc often also depend on other certain optional features available in the file formats that SpreadsheetGear either doesn't support or write out by default.  For instance, iOS depends on a "data cache" stored within charts to display chart series data points and SpreadsheetGear's support for writing out this data cache is limited.  This can result in charts not displaying as expected in iOS, Android, etc.


text:
Q: IntelliJ / Android Studio - Replace all as refactor I want to change (Replace All - ctrl + R) text occurrences at the same time refactoring it. Is it possible? Something like: (ctrl + R) + (shift + f6)

A: Use "Replace in Path" (Ctrl + Shift + R).
It works as simple Replace All in whole project. That means in some scenarios (check my comment to CrazyCoder) we have to use it few times (e.q. one time on resources files, the second time on code files).


text:
Q: Facebook app with an iframe on rails I'm attempting to create a facebook app and went through the book http://pragprog.com/titles/mmfacer/developing-facebook-platform-applications-with-rails.  Everything works fine on my development machine when I have my canvas render method set as fbml.  But, for various reasons I want to build an app with an iframe.  When I set my app to use an iframe I am unable to connect to my development machine.  I went through a lot of different articles about creating an iframe app, but none seem to work.  That includes
http://wiki.developers.facebook.com/index.php/Cross_Domain_Communication_Channel
http://wiki.developers.facebook.com/index.php/XFBML
and any other site found googling any combination of facebook, iframe, rails and others.
I have the xd_receiver.htm file in my public directory and my layout looks like
<!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  <title><%= controller.controller_name %>: <%= controller.action_name %></title>
  <%= stylesheet_link_tag "jquery-ui-1.7.1.custom.css", "styles" %>
  <%= javascript_include_tag "jquery-1.3.2.min.js", "application" %>
</head>
<body>

<%= yield  %>
<script src="http://static.ak.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>
<script type="text/javascript">
    FB_RequireFeatures(["XFBML"], function(){
    FB.Facebook.init("my api key", "xd_receiver.htm"); });
</script>
</body>
</html>

My question is, what am I missing that is preventing facebook from connecting to my rails development machine when I set the canvas render method to iframe?  Since my development log does not show any attempts of a connection, I'm guessing that it has something to do with the cross domain stuff, but I can't find a good answer about it anywhere.

A: If you place that file under /public, its important to note that the ERB contained within the template will not get parsed as you expected. I'm not too familiar with the plugin you are trying to use but have used the Facebooker gem (http://facebooker.rubyforge.org/) which provides a tidy way to interact with the Facebook REST API.

A: I strongly suggest using Facebooker from the beginning.
It'll save you a lot of time.

A: /xd_receiver
there are facebooker methods for this sort of thing check this out
http://blog.yangtheman.com/2009/08/23/how-to-integrate-facebook-connect-with-a-rails-app/


text:
Q: PythonL: invalid syntax file "", line 1 When doing python3 Webhook.py (this is the file), it gives me the error:

  File "<fstring>", line 1
    (%X - %x)
     ^
SyntaxError: invalid syntax

I've tried to print out the raw contents of the file and I also used a hex editor, there is nothing on line 1 that should be causing erorrs. I also did:

import time, os, aiohttp, plistlib, discord, asyncio, json, subprocess

In the Terminal.app version of Python3 and I had no errors, my version was 3.6.3 but updated to 3.6.5 to check if the issue would go away, which didn't. Can anyone help?

A: I had a similar issue. After removing parts of the code to narrow down the problem, I found the root cause.
In my case I was printing an f-string and inside the f-string I had a space in the name of the variable I was calling
var32 = x
print(f"This is a statement {var 23} "

Removing that space fixed the problem.

A: it might also be that you have a python 3.8 compatible way of string formating, such as:
f"print{count=}"

which is not compatible with 3.6, 3.7.
In that case, you can either decide to require the user to upgrade to python3.8, or downgrade your code.

A: This happens when anything inside {} is not valid, in a string formatted using the f string formatting prefix. Python 3.7 in my case. The upside is you get the string causing the problem on the error message. You don't get the line number, but it's still easy to figure out once you acknowledge that line number 1 is not the correct line number of the error.

A: for my code. the problem was
I was printing {=*10} instead the right form {"="*10}
that mistake generated my problem

A: I pass the string in the  like
print(f"The length of the set is {len(s) elements}")
So I just move my string out of  and problem solved.
print(f"The length of the set is {len(s)} elements")

A: This happened to me. What solved it for me is that I put f before a string for example print(f'string {hello}') and had the curly brackets in my string, which were meant to be a string and not a variable due to the f before the string. Hopefully, this helped for you.


text:
Q: How do I compare array value to the next value in array I am wanting to compare the next value in the array with my current value. If you look at my code I think you will see what I am trying to do but to explain I need only one picture to show if $row[2] is the same on the next loop thru.
My error start at // ERROR HERE in if Statement in the code below.
I am sure there is a simple solution to this but I don't know the proper name and could not find it in my searches.
-Disclaimer I am still an newbie at this please forgive me.
$connection = mysqli_connect($host, $user, $pass, $db);
if (mysqli_connect_errno($connection)) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// create query
$query = "SELECT * FROM 1098";
$result = mysqli_query($connection, $query);

if (mysqli_num_rows($result) > 0) {

    while($row = mysqli_fetch_row($result)) {
        echo "";

        // ERROR HERE in if Statement
        $nextrow = 1 + $row;
        if ( $row[2] <> $nextrow[2]){

            if ( $row[6] == "kit"){
                $img ='';
                echo $img.$filepath;
            }
            else
            {
                $img ='';
                echo $img.$filepath ;
            }
        }
        echo  "";
    }
}

A: $nextrow = 1 + $row doesn't make sense. That would be attempting to add an integer to a database record, i.e. 1 + array('foo', 'bar', 'baz').
If you simply want to compare the current record with the previous record (on all loops after the first one) how about something like this:
while($row = mysqli_fetch_row($result)) {
  print '';

  // If there is no previous record set (first record) or if the 2nd value is different.
  if (!isset($prev_record) || $prev_record[2] != $row[2]) {
    // ...
  }

  print '';

  // Assign the current row to a variable so that it's available on the next run.
  $prev_record = $row;
}

Edit – here's an example of how you can get all records into a single array and then play with them:
$records = array();
while($row = mysqli_fetch_row($result)) {
  $records[] = $row;
}

foreach ($records as $i => $record) {
  $record; // current record
  $records[$i-1]; // last record
  $records[$i+1]; // next record
}

I would recommend splitting your data up into multiple tables, though, and using a cleaner approach.

A: $nextrow = 1 + $row;
Given $row is a row, this is not doing what you think it is.
If you want the nextrow from the query you have to fetch it.
If you can reverse your logic to use previous row , you could preserve that and compare it to the current row.
You could read them all into an array first, but on a big result set that would be expensive....
You could do two fetches, one to current row, one to next row,
And then add a lot of logic to deal with the first and last, and making current = next and fetching the next next :(
Or you could rework the query so it returned the data you need in one row.
You definitely can't do what you are trying to do though. There is no next row until you fetch. $row is an array of columns, there is no rows as in an array of rows.


text:
Q: Trying to append child to all elements with same class name I am trying to use the appendChild() method to add a document.createElement("div") element to multiple
 elements with the same class name.
I have tried this way:
const childElement = document.createElement("div");
childElement.className = "second";
const parentObject = document.getElementsByClassName("first");

[...parentObject].map(parent => parent.appendChild(childElement))

Which didnt work, so I tried:
for(let i = 0; i < parentObject.length; i++){
  parentObject[i].appendChild(childElement);
}

The only way it worked was if I wrote the html element myself and then added it to the innerHTML of each parent:
[...parentObject].map(parent => parent.innerHTML = "

")

But since I am generating all different kind of HTML element tags, like IMG, DIV, SPAN I need the convenience of calling the createElement() method.
Has anyone any experience with this?

A: An element can only exist in one place in the DOM. What you need to do is create a new element to append to each parent:

const parentObject = document.getElementsByClassName('first');

[...parentObject].forEach((parent, i) => {
  const childElement = document.createElement('div');
  childElement.className = 'second';
  childElement.innerHTML = `second ${i}`;
  parent.appendChild(childElement)
});
div { padding: 5px; }
.first { background-color: pink; display: inline-block; }
.second { background-color: lightblue; }

first

first

first

first


text:
Q: Visual Studio debug web app from another machine in the same network I wrote a web-app  asp.net (.net framework) identity framework in Visual studio 2019, for different reasons I used a Windows PC to do it.
The consumer of this web app is a mobile application, I wrote it in xamarin forms but in iOS pc (another machine in the same network).
When I run the web app I use postman to check if my controllers works fine by sending request to https://localhost:1234' (random port).
Obviusly from Mac I can't use the localhost path, for this reason I do these steps:

*

*In Documents\IISExpress\config\applicationhost.config file I addthe string  <binding protocol="http" bindingInformation="*:8080:" /> (I tried also with<binding protocol="http" bindingInformation="*:8080:*" />)

*from command line i run netsh http add urlacl url=http://*:1234/ user=Everyone

*I retrieve the IP from ipconfig /all

*I run visual studio as Admin

but when I try to send the request it return the Could not get any response error.
I tried also with htpps://COMPUTER-NAME:1234/ but the result is the same.
So, my question is, how I can debug the web app run locally on windows machine from another machine in the same network?
Thank you
G.


text:
Q: Persistent CSS3 transition effect on graphic Button I am kinda new to web development, and I would like to create a graphic button with a highlight pulsed effect, let me explain :
The button is built with 2 layers, the first is the default state always displayed, and the second layer is the highlighted state (white) displayed only when the button is clicked or touched (opacity of this layer is 1 when displayed, 0 when hidden).
My problem is that I would like the opacity of the highlight to go from 0 to 1 regardless the duration of the click or the touch event. The transition back to opacity 0 value should occur only when value 1 has been reached, that means that release events (mouseup or touchend) shouldn't be triggered until the opacity of the hightlight layer has reached 1.
I am using Compass (scss) and jquery mobile with phonegap encapsulation.
I have coded a version which works, but doesn't meet my goal :
The transition to highlighted state is stopped as soon as I release the button (for instance, if I make a very quick touch, even with a 0.2s transition on opacity, the highlighted state is not visible, though the touchend event is triggered... (the transition returns to 0 before reaching 1)...
The whole code maybe not so clean, but I am trying to learn :)
Any clue or advice is welcome!
the HTML code looks like this :

</div

the SCSS looks like this :
@import "compass/reset";
@import "compass/css3";

.btn-test {

  span {
      @include background-image(image-url("foo.png"));
      background-position: 0px 0px;

      width: 72px;
      height: 70px;

      display: inline-block;
    }

  a {
      @include background-image(image-url("foo.png"));
      background-position: 0 71px;

      @include transition-property(opacity);
      @include transition-duration(0.2s);
      @include transition-timing-function(ease);

      width: 72px;
      height: 70px;

      display: inline-block;

      -webkit-touch-callout: none !important;
  }

  .btn-a {

    opacity: 0;
  }

  .btn-a:active {

    opacity: 1;
  }

}

A: What you want is an animation, not a simple transition. You get cross browser animation in compass 0.13 alpha with gem install compass --pre
The solution would be to add keyframes for your different states :
@import "compass/css3/animation";

@include keyframes(flashButton){
  0%{
    opacity: 0;
  }
  50%{
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

.animate-button {
  @include animate(flashButton 1s ease);
}

And then with a little bit of jQuery :
$('.btn-test').on('click', function(){
  //reset state in case animation has already been played
  $('.btn-test').removeClass('animate-button');
  setTimeout(function(){$('.btn-test').addClass('animate-button')}, 1)
});

I didn't use it yet but you can also use https://github.com/ericam/compass-animate which is a compass port of the great css animations found here http://daneden.me/animate/


text: Q: Binary Palindrome Let an integer n be given. Write the integers from 1 to n in binary notation successively from left to right. In the resulting string consisting of zeros and ones, choose a palindrome substring of maximal length. It is required to find the length of this substring. For example, if n=5, we can get a string which is 1 10 11 100 101. And we can get the longest substring that is palindromic: 11011 or 01110. So the answer to the question is 5. The n can be very big. Are there any good algorithm to solve this problem? Thanks in advance!


text:
Q: tool or framework for penetration test There are couple of tools for penetration testing. Some of them free like MSF (community) as commercial version. Which is the best tool for the penetration test. Also suggest good book fo the same.
I am looking for pen test for distributed and web application.

A: I have used some useful vulnerability scanner just like Sparks AWVS and APPScan.I think AWVS is the best because of "login scan".It can help scan the Web pages what only can be accessed by "root",with a brief,it can help you scan more infomation and vulnerability.Of course,you can have a trail https://www.acunetix.com/vulnerability-scanner/download/  :)

A: I would suggest starting with getting familiar with Kali Linux or Parrot OS. Those OS distributions come with loads of tools to explore. Offensive Security offers a free ebook to get familiar with Kali.
For you web pentesting, Burpsuite has a free Community edition that is preinstalled on both above OS distros.
Kali:
https://www.offensive-security.com/kali-linux-vm-vmware-virtualbox-image-download/
Parrot OS:
https://parrotsec.org/download/
Burpsuite:
https://portswigger.net/

A: I would suggest Metasploit in the tool category.
You might wanna check out www.exploit-db.com for useful information about existing vulnerabilities of software.
Regards,
Peter

A: I second Kali and Parrot OS. Both are really good and come pre-loaded with tools.


text:
Q: The canvas has been tainted by cross-origin data local image This question has been asked a lot, but I just don't understand why this is happening to me.
Basically, I have a canvas, and an image, and when I try to do this:

var canvas = document.getElementById('somecanvas');
var ctx = canvas.getContext('2d');
var someimage = document.createElement('img');
someimage.setAttribute('src', 'img/someimage.png');
someimage.onload = function(){
    ctx.drawImage(someimage, 0, 0, canvas.width, canvas.height);
    data = ctx.getImageData(0,0,canvas.width,canvas.height);
}

I get the unsightly:
"Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
    at HTMLImageElement.someimage.onload"

I should mention that I'm fairly new to pogramming, and even moreso to javascript. Should this be happening when I'm running it from file:\\?
I haven't found anyone having the exact same problem as me, and the explanations people got for the other questions had to do with the server the images were hosted on. But in this case it isn't hosted on a server, so I'm confused as to how it all works. Or rather, doesn't work.

A: For security reasons, many browsers will complain if you try to do certain things (canvas image drawing among them), if you use a file:// URL.
You really should serve both the page and the images from a local HTTP server in order to avoid those restrictions.

A: Ah, you've hit the CORS restriction, and I'm guessing here that you're encountering this in Google Chrome, which is notorious for being the most aggressive implementor of this. I've seen this a LOT.
CORS is a protocol, to prevent cross-origin content being inserted into a web page. It not only affects script files (as you might expect, because you don't want anyone to be able to inject malicious scripts into your web page), but also affects such resources as images and fonts.
The reason it affects images, is because malicious individuals discovered that they could use the HTML5 canvas object to copy the contents of your web page to a PNG file, and hoover personal data from that at will.You can imagine what would happen if you were engaging in Internet banking transactions whilst this happened to you!
But, and this is the annoying part you're encountering, stopping such malicious activity also impinges on legitimate uses of cross-origin resources (e.g, keeping all your images in a separate repository).
So how do you get around this?
On Firefox, you shouldn't have a problem. Firefox applies some intelligence to the matter, and recognises that images coming from the same file:// specification as your web page, are not actually cross-origin. It lets these through, so long as they're in the same directory on your hard drive as your web page.
Chrome, on the other hand, is much less permissive. It treats all such accesses as cross-origin, and implements security shutdowns the moment you try using getImageData() and putImageData() on a canvas.
There is a workaround, if you don't want to go to the trouble of installing and configuring your own local web server, but still want to use Chrome and its nice, friendly debugger. You have to create a shortcut, that points to your Chrome executable and runs it when you double click on it, but which starts Chrome up using a special command line flag:
--allow-file-access-from-files
Save this shortcut, labelling it something like "Chrome Debug Version" to remind you ONLY to use this for debugging your own code (you should never access the Internet proper with weakened security!), and you should be able to debug your code without issues from this point on.
But, if you're going to be doing a lot of debugging of this sort, the better long-term solution, is to install a web server, and configure it to serve up code from your desired directories every time you use the "localhost" URL.  This is, I know, tedious and time consuming, and distracts from your desire to get coding, but once it's done, it's done and dusted, and solves your woes permanently.
If you really want to put your programming skills to the test, you could even write your own web server to do the job, using something like the node.js server side framework, but if you're new to JavaScript, that's a task you're better leaving until you have a lot more experience! But once your skills reach that point, doing that is a nice educational exercise that will also solve some of your other woes, once you've worked out how a web server works.
If you run with an established web server, you then, of course, have the fun of deciding which one involves the least headaches. Apache is powerful, but big. Hiawatha is both lightweight and secure, and would be my first choice if it wasn't for the fact that a 64-bit version is still not available (sigh), because the 32-bit version that ran on my old XP box was a joy to use. Nginx I know little about, but some people like it. Caveat emptor and all that.


text:
Q: Stirling number and number of 5 letter words with {a,b,c} in which each letter occur atleast once I came across following problem:

How many number of 5 letter words that use letters from the 3 letter set {a,b,c} in which each letter occur atleast once?

This can be solved manually by enumerating individual cases as follows:

Number of words contains no A: 32, no B:32, no C:32. Total:96. Each of AAAAA,BBBBB and CCCCC are counted twice. Thus 96-3 = 93. Number of letters in which each letter occurs at least once = $3^5-93=150$

Now I see that this problem sounds like a problem of number of onto function from set A (with n elements) to set B (with k elements) which solution is given as $k! \begin{Bmatrix}n\\k\\\end{Bmatrix}$ where $\begin{Bmatrix}n\\k\\\end{Bmatrix}$ is a Stirlings number of second kind.
In onto function elements of set $A$ are distinguishable. Elements of set $B$ are distinguishable groups. And each group should have at least 1 element. This exactly maps to the above problem, where $A=\{a,b,c\}$ and $B=\{$5 letter word$\}$.
So, if I am not wrong, in above question $n=3$ and $k=5$. But we cannot define $\begin{Bmatrix}3\\5\\\end{Bmatrix}$. So how we can use Stirling number's onto functions counting approach to this problem. Surprisingly, if we make it reverse, i.e. $n=5$ and $k=3$, then answer comes correctly as $3! \begin{Bmatrix}5\\3\\\end{Bmatrix}=150$. How it works if I reverse the values of $n$ and $k$. Am I wrong in thinking that its $n=3$ and $k=5$ in this question? Or I miss something?

A: The number of words with at most $3$ types of letters i.e. $\binom{3}{3}. 3^5$ here we have overcounted and hence we exclude the number of words with at most $2$ types of letters i.e. $\binom{3}{2}.2^5$ and we have to exclude more and hence have to include the number of words with at most $1$ types of letters: $\binom{3}{1}.1^5$. Here we have used PIE.


text:
Q: Controller received data whilst busy I am trying to use interrupts in code vision for proteus. INT0 for increasing the counter value and INT1 for decreasing it. for that purpose I declared two funcions interrupt [EXT_INT0] void ext_int0_isr(void) and interrupt [EXT_INT1] void ext_int1_isr(void) but when I run the code it doesn't work and I get the infinite warning "Controller received data whilst busy" in proteus. I'd really appreciate if you could help me.
#include <mega8535.h>
#include <alcd.h>
#include <stdio.h>
#include <delay.h>
int i = 0 ;
int j = 0 ;
char number[16];

// External Interrupt 0 service routine
interrupt [EXT_INT0] void ext_int0_isr(void)
{
#asm("cli")// Global disable interrupts

i++;

//go to products counting
if(i < 10) goto ENTERED;

//go to products packaging process
if(i >= 11)
{
lcd_clear();
lcd_gotoxy(2,0);
lcd_putsf("Products Are");

for (j=0; j < 10; j++)
{
lcd_gotoxy(1,1);
lcd_putsf("Being Packaged.");
delay_ms(500);
lcd_gotoxy(1,1);
lcd_putsf("Being          ");
delay_ms(500);
}
}
i=1;

ENTERED:
if(i < 11)
{
sprintf(number,"Number Of People=%d  \n (one Entered)",i);
}

}

// External Interrupt 1 service routine
interrupt [EXT_INT1] void ext_int1_isr(void)
{
#asm("cli")// Global disable interrupts

i--;

//go to products counting
if(i < 11) goto WENTOUT;

//go to products packaging process
if(i >= 11)
{
lcd_clear();
lcd_gotoxy(2,0);
lcd_putsf("Products Are");

for (j=0; j < 10; j++)
{
lcd_gotoxy(1,1);
lcd_putsf("Being Packaged.");
delay_ms(500);
lcd_gotoxy(1,1);
lcd_putsf("Being          ");
delay_ms(500);
}
}
i=1;

WENTOUT:
if(i < 11)
{
sprintf(number,"Number Of People=%d \n (one went out)",i);
}

}

void main(void)
{

// External Interrupt(s) initialization
// INT0: On
// INT0 Mode: Falling Edge
GICR|=(1<<INT1) | (1<<INT0) | (0<<INT2);
MCUCR=(1<<ISC11) | (0<<ISC10) | (1<<ISC01) | (0<<ISC00);
MCUCSR=(0<<ISC2);
GIFR=(1<<INTF1) | (1<<INTF0) | (0<<INTF2);
// Alphanumeric LCD initialization
// Connections are specified in the
// Project|Configure|C Compiler|Libraries|Alphanumeric LCD menu:
// RS - PORTA Bit 0
// RD - PORTA Bit 1
// EN - PORTA Bit 2
// D4 - PORTA Bit 4
// D5 - PORTA Bit 5
// D6 - PORTA Bit 6
// D7 - PORTA Bit 7
// Characters/line: 16

lcd_init(16);

sprintf(number,"Number Of People=%d",i);

while (1)
      {
      lcd_gotoxy(4,0);
      lcd_puts(number);
      #asm("sei")// Global enable interrupts
      delay_ms(50);
      lcd_clear();
      }
}

A: The problem was that the string's length that I was trying to put in the LCD was more than LCD's capacity and after I shortened the string the problem was solved.


text:
Q: The request was aborted: Could not create SSL/TLS secure channel.' this.ResponseStreamFromServer = string.Empty;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
       | SecurityProtocolType.Ssl3;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();


text:
Q: Rails, Mongoid & Unicorn config for Heroku I am using Mongoid 3, with Rails 3.2.9 and Unicorn for production. Would like to setup a before_fork & after_fork for the connection to mongodb, found the following code for active record:
before_fork do |server, worker|
  # Replace with MongoDB or whatever
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.connection.disconnect!
    Rails.logger.info('Disconnected from ActiveRecord')
  end
end

after_fork do |server, worker|
  # Replace with MongoDB or whatever
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.establish_connection
    Rails.logger.info('Connected to ActiveRecord')
  end
end

What is the relevant code for Mongoid (to connect and disconnect)?
Update:
You dont actually need to do this, so for people coming to view this question see:
http://mongoid.org/en/mongoid/docs/rails.html
"Unicorn and Passenger
When using Unicorn or Passenger, each time a child process is forked when using app preloading or smart spawning, Mongoid will automatically reconnect to the master database. If you are doing this in your application manually you may remove your code."
Though it would still be interesting to know what would be the equivalent Mongoid code.

A: You dont actually need to do this, so for people coming to view this question see:
http://mongoid.org/en/mongoid/docs/rails.html
"Unicorn and Passenger
When using Unicorn or Passenger, each time a child process is forked when using app preloading or smart spawning, Mongoid will automatically reconnect to the master database. If you are doing this in your application manually you may remove your code."
Though it would still be interesting to know what would be the equivalent Mongoid code.

A: What about

::Mongoid.default_session.connect
::Mongoid.default_session.disconnect

A: https://docs.mongodb.com/mongoid/current/tutorials/mongoid-configuration/#usage-with-forking-servers
The documentation on mongodb.com says that after_fork and before_fork for unicorn or passenger are required.
This probably changed recently.  This is the 7.0 mongoid documentation


text:
Q: How to have a certain user inherit all file permissions from another user as if they were the owner I just switched to Fedora 27 and was wondering if what I want is possible.
I want a certain user to inherit all permissions from another user (Meaning: Being able to access files as if I were the owner)
I'd like a structure as follows:
root
├── desktop_user
│   ├── firefox
│   ├── chrome
│   └── games
│       ├── game_1
│       └── game_2
└── All other applications

Where I want the desktop_user to be able to access files from all sub-users in the tree.
but firefox and chrome would not be able to act as desktop_user.
The same goes for desktop_user and root. I do not want to have access to root unless I enter a password. I am looking for a clean way to do this, preferably.

A: Allright, I think I have it figured out with the help of George Udosen.
I edited the sudoers rules using:
visudo -f /etc/sudoers.d/overrides
desktop_user ALL=(%desktop_child) NOPASSWD: ALL

Where desktop_child is the group assigned to all children in the tree from desktop_user.
This allows desktop_user to sudo all it's children, but not vice versa.


text:
Q: EnumChildWindows or FindWindowEx? I have option to use any one of the API EnumChildWindows or FindWindowEx.
Any suggestions which api is better performance oriented?
Is FindWindowEx internally uses EnumChildWindows to get handle to particular window?

A: This really depends a lot on your scenario.
The FindWindowEx function is used to search for windows having a particular class and optionally a particular piece of text in the window.  The EnumChildWindows function is simply there to enumerate child windows.
I think performance should be your last concern here.  The first is choosing the right API.  If you are indeed searching for windows of a particular class then use FindWindowEx, otherwise EnumChildWindows.  There is no sense in hand implementing a function using EnumChildWindows to have the same behavior as FindWindowEx.
Now after choosing the right solution, if a profiler specifically tells you that the solution is too slow, then you should consider hand implementing a more specific function. Not before.


text:
Q: python: creating chararray of unicode strings I need to substitute some data in a FITS file that I would like to modify with astropy.fits in python3. In order to be consistent with the original FITS file, I would like to write a numpy.chararray of dtype='<U100'.
I have tried with numpy.chararray(x), where x is a list of string, and I get *** TypeError: 'str' object cannot be interpreted as an integer.
I am very confused because I though that in python 3 all the string are unicode and in my understanding '<U100' is unicode. I would love some hint on what I am doing wrong here

A: The FITS standard does not deal with unicode. Within astropy.fits when you are writing it will try to encode as ASCII. When you read a FITS file there is some magic under the hood to make the ASCII bytes appear like str.
The short answer is that you need to use bytes if you are trying to deal directly with data stored in FITS.  For instance:
In [8]: s = np.array(['hello', 'world'])

In [9]: np.char.encode(s, 'ascii')
Out[9]: array([b'hello', b'world'], dtype='|S5')

A: Without more details of exactly what you're trying to change it's hard to say, but assuming you're working with a FITS table the easiest way is probably to use the Table API.
Here's an example table:
>>> from astropy.table import Table
>>> t = Table({'a': ['a', 'b', 'c']})
>>> t.write('table.fits')

You can load it with Table.read and just modify it like any array of strings.  It will handle re-encoding it properly.
>>> t = Table.read('table.fits')
>>> t

  a
bytes1
------
     a
     b
     c
>>> t['a'] = ['d', 'e', 'f']
>>> t.write('table.fits', overwrite=True)
>>> t = Table.read('table.fits')
>>> t

  a
bytes1
------
     d
     e
     f

If you want to use the lower-level FITS interface directly that's fine too.  In most cases it shouldn't be necessary to construct a chararray (which is an internal implementation detail) manually:
>>> from astropy.io import fits
>>> hdul = fits.open('table.fits')
>>> hdul[1].data
FITS_rec([('d',), ('e',), ('f',)], dtype=(numpy.record, [('a', 'S1')]))
>>> hdul[1].data['a']
chararray(['d', 'e', 'f'], dtype='<U1')
>>> hdul[1].data['a'] = ['g', 'e', 'h']
>>> hdul[1].data['a']
chararray(['g', 'e', 'h'], dtype='<U1')
>>> hdul.writeto('table.fits', overwrite=True)
>>> hdul = fits.open('table.fits')
>>> hdul[1].data
FITS_rec([('g',), ('e',), ('h',)], dtype=(numpy.record, [('a', 'S1')]))


text:
Q: Looking for a Theorem Relating Polynomial Coeffecients and Roots I recall seeing this theorem in a book on Euler, but I can't recall the books name nor the theorems name (if it had one). I remember reading that this theorem was originally put forth and proved by Newton then Euler created his own proof.
Here's what I recall of it:

If $P(x)=x^n-Ax^{n-1}+Bx^{n-2}-Cx^{n-3}+ \dots \pm N$ is a polynomial who can be factored as $P(x)=(x-r_1)(x-r_2) \dots (x-r_n) $, then
$\sum_{k=1}^n r_k = A$
$\sum_{k=1}^n r_k^2 = A\sum_{k=1}^n r_k - B$

And some pattern continues, although I can only remember this much.


text:
Q: Unable to locate Keycloak configuration file: keycloak.json I have a Spring Boot service that is secured via a Keycloak server. I get the status code "404 Not Found" for every request with no log entries in the Spring Boot Server. So my guess was that the controller classes are not found. I added @ComponentScan annotation and since then I get the error message "Caused by: java.io.FileNotFoundException: Unable to locate Keycloak configuration file: keycloak.json". No matter if the file exists or not.
I want to read all properties from the application.properties file and I don't need the keycloack.json file.
I am grateful for any tip.
main:
@Import({ WebSecurityConfiguration.class})
@SpringBootApplication
@ComponentScan({"com.company.xy.controller","com.company.xy.client"})
public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

application.properties
spring.datasource.url=jdbc:postgresql://database:5432/db
spring.datasource.username=db
spring.datasource.password=db
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect

server.port=8585

keycloak.realm=realm
keycloak.auth-server-url=http://localhost:8180
keycloak.resource=resource
keycloak.credentials.secret=abc
keycloak.credentials.username=adm
keycloak.credentials.password=password
keycloak.credentials.provider=secret

keycloak.public-client=true
keycloak.bearer-only=true

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.6.1</version>
      <relativePath />
      <!-- lookup parent from repository -->
   </parent>
   <groupId>com.example</groupId>
   <artifactId>spring-boot-keycloak</artifactId>
   <version>1.0.0</version>
   <name>spring-boot-keycloak</name>
   <description>Demo project for Spring Boot with Keycloak</description>
   <properties>
      <java.version>11</java.version>
      <keycloak.version>17.0.0</keycloak.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <scope>provided</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-security</artifactId>
      </dependency>
      <dependency>
         <groupId>org.keycloak</groupId>
         <artifactId>keycloak-spring-boot-starter</artifactId>
         <version>${keycloak.version}</version>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.postgresql</groupId>
         <artifactId>postgresql</artifactId>
      </dependency>
      <dependency>
         <groupId>org.keycloak</groupId>
         <artifactId>keycloak-admin-client</artifactId>
         <version>19.0.3</version>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>

error message
2023-02-24 09:31:56.249 ERROR 8052 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:163) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:577) ~[spring-context-5.3.13.jar:5.3.13]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1290) ~[spring-boot-2.6.1.jar:2.6.1]
        at com.company.xy.Application.Application.main(Application.java:16) ~[classes/:na]
Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
        at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:142) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:104) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:473) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:206) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:182) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:160) ~[spring-boot-2.6.1.jar:2.6.1]
        ... 8 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'keycloakAuthenticationProcessingFilter' defined in com.company.xy.security.WebSecurityConfiguration: Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'adapterDeploymentContext' defined in com.company.xy.security.WebSecurityConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.keycloak.adapters.AdapterDeploymentContext]: Factory method 'adapterDeploymentContext' threw exception; nested exception is java.io.FileNotFoundException: Unable to locate Keycloak configuration file: keycloak.json
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:213) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.boot.web.servlet.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:212) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.web.servlet.ServletContextInitializerBeans.addAsRegistrationBean(ServletContextInitializerBeans.java:175) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.web.servlet.ServletContextInitializerBeans.addAsRegistrationBean(ServletContextInitializerBeans.java:170) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.web.servlet.ServletContextInitializerBeans.addAdaptableBeans(ServletContextInitializerBeans.java:155) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.web.servlet.ServletContextInitializerBeans.<init>(ServletContextInitializerBeans.java:87) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getServletContextInitializerBeans(ServletWebServerApplicationContext.java:260) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.selfInitialize(ServletWebServerApplicationContext.java:234) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.springframework.boot.web.embedded.tomcat.TomcatStarter.onStartup(TomcatStarter.java:53) ~[spring-boot-2.6.1.jar:2.6.1]
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5219) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317) ~[na:na]
        at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:145) ~[na:na]
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:835) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317) ~[na:na]
        at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:145) ~[na:na]
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:263) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at org.apache.catalina.core.StandardService.startInternal(StandardService.java:432) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:927) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at org.apache.catalina.startup.Tomcat.start(Tomcat.java:486) ~[tomcat-embed-core-9.0.55.jar:9.0.55]
        at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:123) ~[spring-boot-2.6.1.jar:2.6.1]
        ... 13 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'adapterDeploymentContext' defined in com.company.xy.security.WebSecurityConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.keycloak.adapters.AdapterDeploymentContext]: Factory method 'adapterDeploymentContext' threw exception; nested exception is java.io.FileNotFoundException: Unable to locate Keycloak configuration file: keycloak.json
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:486) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:233) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1273) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1234) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveBean(DefaultListableBeanFactory.java:494) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:349) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1172) ~[spring-context-5.3.13.jar:5.3.13]
        at org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter.afterPropertiesSet(KeycloakAuthenticationProcessingFilter.java:134) ~[keycloak-spring-security-adapter-17.0.0.jar:17.0.0]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.13.jar:5.3.13]
        ... 51 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.keycloak.adapters.AdapterDeploymentContext]: Factory method 'adapterDeploymentContext' threw exception; nested exception is java.io.FileNotFoundException: Unable to locate Keycloak configuration file: keycloak.json
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.13.jar:5.3.13]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.13.jar:5.3.13]
        ... 69 common frames omitted
Caused by: java.io.FileNotFoundException: Unable to locate Keycloak configuration file: keycloak.json
        at org.keycloak.adapters.springsecurity.AdapterDeploymentContextFactoryBean.loadKeycloakDeployment(AdapterDeploymentContextFactoryBean.java:83) ~[keycloak-spring-security-adapter-17.0.0.jar:17.0.0]
        at org.keycloak.adapters.springsecurity.AdapterDeploymentContextFactoryBean.afterPropertiesSet(AdapterDeploymentContextFactoryBean.java:76) ~[keycloak-spring-security-adapter-17.0.0.jar:17.0.0]
        at org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter.adapterDeploymentContext(KeycloakWebSecurityConfigurerAdapter.java:72) ~[keycloak-spring-security-adapter-17.0.0.jar:17.0.0]
        at com.company.xy.security.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$c632c0df.CGLIB$adapterDeploymentContext$10(<generated>) ~[classes/:na]
        at com.company.xy.security.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$c632c0df$$FastClassBySpringCGLIB$$45b88d07.invoke(<generated>) ~[classes/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.3.13.jar:5.3.13]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.3.13.jar:5.3.13]
        at com.company.xy.security.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$c632c0df.adapterDeploymentContext(<generated>) ~[classes/:na]
        at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
        at java.base/java.lang.reflect.Method.invoke(Method.java:578) ~[na:na]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.13.jar:5.3.13]
        ... 70 common frames omitted

I have already implemented the following class so that only the Spring Boot application.properties are used.:
@Configuration
public class KeycloakConfig {

    @Bean
    public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }
}