text:
Q: How to create date-based ImageView (weekly change) I want to create an ImageView whose image source changes weekly. I started here, but the app always crashes so unfortunately I can't run it. I searched on GitHub and did not find anything useful. Here is my Java code:
package com.zahit.mehmet.onlinetp;

import android.media.Image;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Ders_Programi extends AppCompatActivity {

    TextView textView;
    ImageView imageview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ders__programi);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        textView = (TextView) findViewById(R.id.textview_date);

        imageview = (ImageView) findViewById(R.id.imageprogram);

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat  mdformat = new SimpleDateFormat("yyyyMMdd");
        String strdate = mdformat.format(calendar.getTime());
        int currenttime;
        currenttime = Integer.valueOf(strdate.toString());

        textView.setText(strdate.toString());

        if(20160115< currenttime){
            if (currenttime< 20160213) {

                imageview.setBackgroundResource(R.drawable.filepage33);

            }
            else {

            }

        }
        else {

        }

    }

}

And here is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.zahit.mehmet.onlinetp.Ders_Programi"
    tools:showIn="@layout/activity_ders__programi"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textview_date" />

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/imageprogram" />
</LinearLayout>

Any ideas?

A: From just looking at your source code (without any logcat) I'd say the reason for your crash is a NullPointerException because the Toolbar can't be found. In the following snippet you are referencing a Toolbar with an id of R.id.toolbar which is not declared in your layout and thus returning null:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

So in order to solve your problem you'd have to add a Toolbar to your layout:
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_height="?attr/actionBarSize"
    android:layout_width="match_parent"
    android:background="?attr/colorPrimary" />

That should fix your issue (again, only if it actually is a NullPointerException you are getting, posting the actual logcat would be helpful).

A: Your problem comes from the setBackgroundResource() call as the logcat says:
at android.support.v7.widget.AppCompatImageView.setBackgroundResource(AppCompatImageView.java:77)

Which kind of resource are you trying to load?


text:
Q: Monopoly game problems I have a problem in a class, Shipping, in my monopoly game. I want to find out how many shippings a player owns and thereby determine the rent. (It is a danish version of the game, so i think the rules differ from country to country). I use the Collections.frequency but for some reason it always goes to the else statement and gives me 8 times the rent. Here is the code:
package fields;

import java.util.Collections;
import java.util.Scanner;

public class Shipping extends Ownable
{
    public int rent;
    private int occurence;
    private String yesOrNo;
    private Shipping shipping;
    Scanner scan = new Scanner(System.in);

public Shipping(int fieldNumber, String fieldName, int price)
{
    super(fieldNumber, fieldName, price);
    this.rent = 500;
}

public int getRent()
{
    return rent;
}

@Override
public int getPrice()
{
    return price;
}

@Override
public String getName()
{
    return fieldName;
}

@Override
public int getNumber()
{
    return fieldNumber;
}

@Override
public matador.Player getOwner()
{
    return owner;
}

@Override
public void getConsequence()
{
    if(getOwner() == null)
    {
        System.out.println("Do you want to buy it? (Y/N)");
        yesOrNo = scan.next();

        if(yesOrNo.equalsIgnoreCase("y"))
        {
            matador.Main.currentPlayer.money -= getPrice();
            owner = matador.Main.currentPlayer;
            matador.Main.currentPlayer.ownedGrounds.add((Shipping) data.board[matador.Main.currentPlayer.getPosition()]);
            System.out.println(matador.Main.currentPlayer.getName()
                    + " bought " + getName());
        }
        else
        {
            System.out.println(matador.Main.currentPlayer.getName() +
                    " did not buy " + data.board[matador.Main.currentPlayer.getPosition()].getName());
        }
    }
    else if(getOwner() != matador.Main.currentPlayer)
    {
        occurence = Collections.frequency(owner.ownedGrounds, shipping);
        if(occurence == 1)
        {
            System.out.println(matador.Main.currentPlayer.getName() + " needs to pay " +
                    owner.getName() + " " + getRent());
            matador.Main.currentPlayer.money -= getRent();
            owner.money += getRent();
        }
        else if(occurence == 2)
        {
            System.out.println(matador.Main.currentPlayer.getName() + " needs to pay " +
                    owner.getName() + " " + (2 * getRent()));
            matador.Main.currentPlayer.money -= (2 * getRent());
            owner.money += (2 * getRent());
        }
        else if(occurence == 3)
        {
            System.out.println(matador.Main.currentPlayer.getName() + " needs to pay " +
                    owner.getName() + " " + (4 * getRent()));
            matador.Main.currentPlayer.money -= (4 * getRent());
            owner.money += (4 * getRent());
        }
        else
        {
            System.out.println(matador.Main.currentPlayer.getName() + " needs to pay " +
                    owner.getName() + " " + (8 * getRent()));
            matador.Main.currentPlayer.money -= (8 * getRent());
            owner.money += (8 * getRent());
        }
    }
}
}

I think the problem is the object i try to get the frequency of, but i have no idea.
thanks in advance!
Regards!

A: occurence = Collections.frequency(owner.ownedGrounds, shipping);

Collections.frequency relies on the object's equals method to compare the objects in the Collection to the object whose occurrences you wish to find. Since your Shipping class doesn't seem to override equals, is uses Object's default implementation, which compares the references.
Therefore you will always get a frequency of 0 (unless you pass a Shipping reference that is already in the Collection, in which case you would get a frequency of 1, but it would probably still be the wrong result).

A: Collections.frequency(c, o) uses the equals() method for comparison. I can see that you've not overridden it with your own implementation, therefore it will default to Object.equals() which uses references.
Although not strictly needed for this problem you should also implement .hashCode() when implementing equals().
This is stated sort-of in the javadoc.

Returns the number of elements in the specified collection equal to
  the specified object. More formally, returns the number of elements e
  in the collection such that (o == null ? e == null : o.equals(e)).

redpajama_set_name: RedPajamaStackExchange


text:
Q: e1000e Reset adapter unexpectedly / Detected Hardware Unit Hang I have a Dell 1U Server with Intel(R) Xeon(R) CPU L5420 @ 2.50GHz, 8 cores running Ubuntu Server Kernel Version 3.13.0-32-generic on x86_64. It has dual 1000baseT networking cards. I have it set up to forward packets from eth0 to eth1.
I have noticed that in my kern.log file it keeps hanging then resting. This is happening often. This happens every few second then maybe it will be ok for a few minutes then back to every few seconds.
Here is the log file dump:
 [118943.768245] e1000e 0000:00:19.0 eth0: Detected Hardware Unit Hang:
 [118943.768245]   TDH                  <45>
 [118943.768245]   TDT                  <50>
 [118943.768245]   next_to_use          <50>
 [118943.768245]   next_to_clean        <43>
 [118943.768245] buffer_info[next_to_clean]:
 [118943.768245]   time_stamp           <101c48d04>
 [118943.768245]   next_to_watch        <45>
 [118943.768245]   jiffies              <101c4970f>
 [118943.768245]   next_to_watch.status <0>
 [118943.768245] MAC Status             <80283>
 [118943.768245] PHY Status             <792d>
 [118943.768245] PHY 1000BASE-T Status  <7800>
 [118943.768245] PHY Extended Status    <3000>
 [118943.768245] PCI Status             <10>
 [118944.780015] e1000e 0000:00:19.0 eth0: Reset adapter unexpectedly

Here is the info from ethtool:
Settings:
Settings for eth0:

Supported ports: [ TP ]
Supported link modes:   10baseT/Half 10baseT/Full
                        100baseT/Half 100baseT/Full
                        1000baseT/Full
Supported pause frame use: No
Supports auto-negotiation: Yes
Advertised link modes:  10baseT/Half 10baseT/Full
                        100baseT/Half 100baseT/Full
                        1000baseT/Full
Advertised pause frame use: No
Advertised auto-negotiation: Yes
Speed: 1000Mb/s
Duplex: Full
Port: Twisted Pair
PHYAD: 1
Transceiver: internal
Auto-negotiation: on
MDI-X: off (auto)
Supports Wake-on: pumbg
Wake-on: g
Current message level: 0x00000007 (7)
               drv probe link
Link detected: yes

Driver info:
ethtool -i eth0

driver: e1000e
version: 2.3.2-k
firmware-version: 1.4-0
bus-info: 0000:00:19.0
supports-statistics: yes
supports-test: yes
supports-eeprom-access: yes
supports-register-dump: yes
supports-priv-flags: no

What could be causing this? Is this just a bug in the software or a actual hardware issue?  I have seen many other having similar issues but no real solution and this also leads me to believe that its a software issue?
Maybe someone can shed some light on this for me?

A: Disabling Enhanced C1 (C1E) in the BIOS fixed it for me.
Not sure if the lower power state of C1E is messing with the driver, or that there's an oops in the driver when the processor is in this state.
Anyway, problem solved.

A: Disabling only TCP Segmentation Offload (TSO) does the trick for me.
ethtool -K eth0 tso off

Note: It does not seem to be necessary to also disable Generic Receive Offload (GRO) and Generic Segmentation Offload (GSO), as it is recommended by various sources. As far as I learned, these are implemented purely in software, and should be safe. Don't sacrifice more performance than necessary.

A: Ok so after posting this question last night night I continued to do some research the only real solution I came across seems to have taken care of the problem.
Disabling TSO, GSO and GRO using ethtool:
ethtool -K eth0 gso off gro off tso off

According to a post found here: http://ehc.ac/p/e1000/bugs/378/
From what I understand this will or can cause a reduction in performance.
I also noticed another solution was to disable Active-State Power Management
pcie_aspm=off

According to this post on serverfault: Linux e1000e (Intel networking driver) problems galore, where do I start?
I haven't tried this solution yet. I will try it and see if that makes a difference and post back my findings.
EDIT:
Ok so I have tried turning off Active-State Power Management, pcie_aspm=off and this didn't have any effect. I continued to notice errors in my log file.
This may still work for some as some of the Intel nics have issues with different kernels of falling asleep when power management is enabled.

A: I had the issue (triggering same kernel error as you and userspace SSH errors like "Corrupted MAC on
input").
Solution
What worked for me was to disable TCP checksum offloading :
# ethtool -K eth0 tx off rx off
Clean & long-term integration of this with debian-ish /etc/network/interfaces:
#!/bin/bash
#
# Disables TCP offloading on all ifaces
#
# Inspired by: @Michelunik https://serverfault.com/a/422554/62953

RUN=true
case "${IF_NO_TOE,,}" in
    no|off|false|disable|disabled)
        RUN=false
    ;;
esac

# Other offloading options that could be disabled (not TCP related):
#  sg tso ufo gso gro lro rxvlan txvlan rxhash
# see man ethtool

if [ "$MODE" = start -a "$RUN" = true ]; then
  TOE_OPTIONS="rx tx"
  for TOE_OPTION in $TOE_OPTIONS; do
    /sbin/ethtool --offload "$IFACE" "$TOE_OPTION" off &>/dev/null || true
  done
fi

source, inspiration.
Context

*

*Debian Jessie

*Kernel 4.7.0-0.bpo.1-amd64

*lspci  00:19.0 Ethernet controller: Intel Corporation Ethernet Connection I218-V (rev 04)

A: I just stumbled upon this readme from intel:
https://downloadmirror.intel.com/15817/eng/readme.txt
which says

82573(V/L/E) TX Unit Hang Messages
Several adapters with the 82573 chipset display "TX unit hang" messages during normal operation with
the e1000edriver. The issue appears both with TSO enabled and disabled
and is caused by a power management function that is enabled in the
EEPROM. Early releases of the chipsets to vendors had the EEPROM bit
that enabled the feature. After the issue was discovered newer
adapters were released with the feature disabled in the EEPROM.
If you encounter the problem in an adapter, and the chipset is an
82573-based one, you can verify that your adapter needs the fix by
using ethtool:
ethtool -e eth0
Offset    Values

0x0000    00 12 34 56 fe dc 30 0d 46 f7 f4 00 ff ff ff ff
0x0010    ff ff ff ff 6b 02 8c 10 d9 15 8c 10 86 80 de 83
The value at offset 0x001e (de) has bit 0 unset. This enables the
problematic power saving feature. In this case, the EEPROM needs to
read "df" at offset 0x001e.

Unfortunately my problematic adapters are 82579V and I219-V in two different NUCs, so it's unclear if the same fix applies for me.

A: Try update your driver.  Don't know where it is for Ubuntu or what version recommended but for CentOS or EL 6 it is:
http://mirror.symnds.com/distributions/elrepo/elrepo/el6/x86_64/RPMS/kmod-e1000e-3.1.0.2-1.el6.elrepo.x86_64.rpm


text:
Q: Loop with modulus gives me an error this is my first time posting a question, but this loop drove me crazy. I cant figure out what is wrong with it. It crashes at the moment when it enters the second loop. It looks fine and makes sense but still it does not work. Any help will be greatly appreciated. Thanks!
/**
Author: Yunus Kulyyev
Date: 10-Dec-2016
Description:
**/

#include <iostream>

using namespace std;

int main()
{
    for (int x=1; x < 10; x++)
    {
        cout << x <<": ";
        for (int y = 0; y <= x; y++)
        {
            if (x%y == 0)
            {
            cout << y;
            }
        }
        cout << endl;
    }

    return 0;
}

A: If the second operand of / or % is zero, then the behavior is undefined. See this post in SO. In your program, for the first iteration of the inner for loop, y = 0 and thus the following code snippet results in undefined behavior.
if (x%y == 0) {
    cout << y;
}


text:
Q: Sample Function in R returning same value over and over I am trying to simulate rolling three dice and taking their sum but for some reason this code is returning 11 over and over.
sample(3:18 ,1, prob = c(1/216, 3/216, 6/216, 10/216, 15/216, 21/216, 25/216, 27/216, 27/216, 25/216, 21/216, 15/216, 10/216, 6/216, 3/216, 1/216))

A: When I rerun your code 100 times, I get a variety of results. In other words, your code doesn't seem to produce the issue you describe.
replicate(n = 100,
          expr = {
            sample_probs <- c(1/216, 3/216, 6/216, 10/216,
                              15/216, 21/216, 25/216, 27/216,
                              27/216, 25/216, 21/216, 15/216,
                              10/216, 6/216, 3/216, 1/216)

            sample(3:18, size = 1,
                   prob = sample_probs)
          })
#>   [1] 12 11 11 11  8  8 11  9 10 15  8 16  9 16 14 15  9 12  8 11 12 13 16  8 12
#>  [26] 11  5 11 14 16 11  7 11 15  8 11  9  5  6  6 12  8  8  7 10  5 10 14  8 10
#>  [51] 10 10 13  6 16  9  9 10 10 14 11  7 16 12 10 13  8 11 11  9 11  8 13  8 11
#>  [76]  4 12  9 13 13 11  8  6  8 14  9 15 12  8  7  6 11 10 11  4  9 10  9 14 12

Created on 2021-03-11 by the reprex package (v1.0.0)


text:
Q: PyQt5.4.1 failing to install with python 3.4 on Mac OS X 10.10.2 I am having a problem installing PyQt5.4.1 with Python 3.4 on Mac OS X 10.10.2.  I have followed these suggestions, but the following occurs:
    Nates-iMac:PyQt-gpl-5.4.1 Nate$ python configure.py --destdir /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages --qmake ~/Qt5.4.1/5.4/clang_64/bin/qmake
    Querying qmake about your Qt installation...
    Determining the details of your Qt installation...
    This is the GPL version of PyQt 5.4.1 (licensed under the GNU General Public License) for Python 3.4.2 on darwin.

    Type 'L' to view the license.
    Type 'yes' to accept the terms of the license.
    Type 'no' to decline the terms of the license.

    Do you accept the terms of the license? yes
    Found the license file pyqt-gpl.sip.
    Error: Make sure you have a working sip on your PATH or use the --sip argument to explicitly specify a working sip.

A: When you install sip with "make install" you should see a line like
cp -f sip /Library/Frameworks/Python.framework/Versions/2.7/bin/sip

When you configure PyQt with "python configure.py" add the --sip argument with something like the path cp -f sip /Library/Frameworks/Python.framework/Versions/2.7/bin/sip
I had the same problem as described in your post, and now it works fine.

A: Try typing:
python3 configure.py -q /Users/Lexynux/Qt5.4.2/5.4/clang_64/bin/qmake -d /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/

Because that's the version of python you have installed, or not? So you must execute the correct version of python.
PD.
Do not forget to change the username 'Lexynux' for yours!


text:
Q: Granting Capabilities to a user through PAM doesn't apply to SSH I am using CentOS 8, and I would like to grant a user the cap_dac_read_search capability though PAM. It seems to work through local login and su, but not through ssh.
I followed these steps, and only them:

*

*created the file /etc/security/capability.conf, and wrote inside:
cap_dac_read_search user1

*edited /etc/pam.d/sshd:
#%PAM-1.0
auth       required     pam_cap.so
auth       substack     password-auth
auth       include      postlogin
...

*Restarted the SSH service:
systemctl restart sshd

However, when I log in with user1 through ssh, and use the capsh command I can see:
[user1@localhost ~]$ capsh --print
Current: =

When I am doing a similar thing with /etc/pam.d/login and /etc/pam.d/su, everything seems to be in order.
I made sure, and checked the sshd config, and UsePam is set to true.
Update:
I get the following error in audit.log, I think SELinux is blocking me for some reason:
type=AVC msg=audit(1621457365.510:253): avc: denied { setcap } for pid=1969 comm="sshd" scontext=system_u:system_r:sshd_t:s0-s0:c0.c1023 tcontext=system_u:system_r:sshd_t:s0-s0:c0.c1023 tclas s=process permissive=0

A: [I'm relatively new here, so don't have enough reputation to add this as a comment. So...]
For an answer, I converted the concerns expressed here into a feature request for pam_cap.so. This was implemented via the autoauth module argument in the libcap-2.51 release.

A: With sshd you need to explicitly configure it to use PAM
 UsePAM  Enables the Pluggable Authentication Module interface.  If set to
         yes this will enable PAM authentication using
         ChallengeResponseAuthentication and PasswordAuthentication in
         addition to PAM account and session module processing for all
         authentication types.

Note that this is still limited in authentication types; so if you authenticate via ssh keys then PAM isn't called for "auth" stack.


text:
Q: Network change Connectivity receiver not working I have implemented broadcastReciever in my code as follows for dynamically getting toast when internet is disconnected:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="<MY PACKAGE>">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:name=".network.MyApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".activity.LoginPage"
        android:theme="@style/Theme.AppCompat.NoActionBar"
        android:windowSoftInputMode="stateHidden|adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver
        android:name=".network.ConnectivityReceiver"
        android:enabled="true">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>
</manifest>

MyApplication.java
public class MyApplication extends Application {

private static MyApplication mInstance;

@Override
public void onCreate() {
    super.onCreate();

    mInstance = this;
}

public static synchronized MyApplication getInstance() {
    return mInstance;
}

public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
    ConnectivityReceiver.connectivityReceiverListener = listener;
}
}

BaseActivity.java
public abstract class BaseActivity extends AppCompatActivity implements ConnectivityReceiver.ConnectivityReceiverListener {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

private void checkConnection() {
    boolean isConnected = ConnectivityReceiver.isConnected();
    showSnack(isConnected);
}

public void showSnack(boolean isConnected) {
    String message;
    int color;
    if (isConnected) {
        message = "Good! Connected to Internet";
        color = Color.WHITE;
    } else {
        message = "Sorry! Not connected to internet";
        color = Color.RED;
    }
    Toast.makeText(getBaseContext(),message,Toast.LENGTH_LONG).show();
}

@Override
protected void onResume() {
    super.onResume();
    MyApplication.getInstance().setConnectivityListener(this);
}

@Override
public void onNetworkConnectionChanged(boolean isConnected) {
    showSnack(isConnected);
}
}

LoginPage.java
public class LoginPage extends BaseActivity {

Button btnSignin, btnSignup;
EditText etUserEmail, etUserPassword;
ImageView ivViewPassword;
private int mStatusCode;
Boolean flagLogin, flagPass = true;
private RequestQueue mRequestQueue;
ProgressBar pbLoading;
RelativeLayout loadingView, rootlayout_loginPage;
Boolean success = false;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    init();
    testdata();
    ivViewPassword.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (flagPass) {
                ivViewPassword.setImageResource(R.drawable.ic_hide_password);
                etUserPassword.setTransformationMethod(null);
                flagPass = false;
            } else {
                ivViewPassword.setImageResource(R.drawable.ic_show_password);
                etUserPassword.setTransformationMethod(new PasswordTransformationMethod());
                flagPass = true;
            }
        }
    });

    btnSignin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            flagLogin = validateDetails();
            if (flagLogin) {
                etUserEmail.setError(null);
                etUserPassword.setError(null);
                loadingView.setVisibility(View.VISIBLE);
                pbLoading.setIndeterminate(true);
                pbLoading.setVisibility(View.VISIBLE);

            }
        }
    });

    btnSignup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(), Registration.class);
            startActivity(intent);
        }
    });

}

private void testdata() {
    etUserEmail.setText("mncc@example.com");
    etUserPassword.setText("1234");
}

private void init() {
    btnSignin = (Button) findViewById(R.id.btnSignin);
    etUserEmail = (EditText) findViewById(R.id.etUserEmail);
    etUserPassword = (EditText) findViewById(R.id.etUserPassword);
    ivViewPassword = (ImageView) findViewById(R.id.ivViewPassword);
    loadingView = (RelativeLayout) findViewById(R.id.loadingView);
    pbLoading = (ProgressBar) findViewById(R.id.pbLoading);
    btnSignup = (Button) findViewById(R.id.btnSignup);
    rootlayout_loginPage = (RelativeLayout) findViewById(R.id.rootlayout_loginPage);
}

@Override
protected void onResume() {
    super.onResume();
    MyApplication.getInstance().setConnectivityListener(this);

}

@Override
public void onNetworkConnectionChanged(boolean isConnected) {
    showSnack(isConnected);
}

private boolean validateDetails() {
    if (etUserEmail.getText().toString().equalsIgnoreCase("")) {
        etUserEmail.setError("Email-ID can't be blank!");
        etUserEmail.setFocusable(true);
        return false;
    } else if (!Utils.isValidEmail(etUserEmail.getText().toString())) {
        etUserEmail.setError("Invalid Email-ID!");
        etUserEmail.setFocusable(true);
        return false;
    } else if (etUserPassword.getText().toString().equalsIgnoreCase("")) {
        etUserPassword.setError("Password can't be blank!");
        etUserPassword.setFocusable(true);
        return false;
    } /*else if (etUserPassword.getText().toString().length() < 8 || etUserPassword.getText().toString().length() > 16) {
        etUserPassword.setError("Password must be between 8-16 characters!");
        etUserPassword.setFocusable(true);
        return false;
    }*/ else {
        return true;
    }
}

When i run the application on my android version oreo phone, it does not work ie it does not show any toast when i toggle network or wifi state. I am unable to figure out what mistake I am making.

A: Apps targeting Android 7.0 and higher must register the CONNECTIVITY_ACTION dynamic Broadcast Receiver in an activity, not in the Manifest file. For example:
private ConnectivityReceiver connectivityReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    connectivityReceiver= new ConnectivityReceiver();
}

@Override
protected void onStart() {
    super.onStart();
    registerReceiver(connectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}

@Override
protected void onStop() {
    super.onStop();
    unregisterReceiver(connectivityReceiver);
}


text:
Q: Excel - Refer to column/range with Networkdays =COUNTIFS(NETWORKDAYS(C:C, TODAY(), 1),">=" & 5)

I am trying to use something like the above to count any values in Column C (Date column of my dataset) where the working days from then to todays date is greater than 5. Can this be done without creating a working days column?

A: It's actually not so obvious but NETWORKDAYS does not work with ranges. Arrays however are completely fine. See this post on SuperUser too.
So in your case you could simply use:
=SUMPRODUCT(--(NETWORKDAYS(C:C+0,TODAY())>=5))

Obviously it's better not to reference the whole of column C. Depending if one has Excel O365, you could also just use =SUM instead of =SUMPRODUCT.


text:
Q: Nginx permission issue (404) Trying to get let's encrypt setup using the webroot method, which creates and needs to access files in  the ./.well-known/acme-challenge/ directory. Everything there (including the manual test file I added) shows up as 404.
Going kind of crazy as I've tried variants of:
location ~ /.well-known {
    allow all;
}
location /.well-known/acme-challenge {
    default_type text/plain;
}
location /.well-known {
    try_files $uri $uri/ =404;
}

with no luck. I've also checked permissions on the folders and even set to 777. I'm pretty new to setting up nginx config so I'm sure there's an existing condition that's throwing it off:
server{
    listen 80;
    server_name domain.com www.domain.com;
    location / {
        rewrite ^(.*)$ https://domain.com$1 permanent;
    }
    location ~ /.well-known {
            allow all;
    }
}

server {
        listen 0.0.0.0:443 ssl;
        root /var/www/domain.com/public_html;
        index index.php index.html index.htm;
        server_name domain.com www.domain.com;
        ssl on;
        ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem;
        location / {
                try_files $uri $uri/ /index.php?$args;
        }
        location ~ \.php$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
                client_max_body_size 32m;
        }
        location ~ /.well-known {
            allow all;
        }
}

A: As Richard Smith said, a root directive is needed. It can go in the server block or the location block.
Note, even if root is in the location block, the path should not contain "/.well-known"
location ~ /.well-known {
    allow all;
    root /var/www/domain.com/public_html;

    # NOT
    # root /var/www/domain.com/public_html/.well-known;
}

A: Your first server block needs a root directive to resolve local files.
See this document for more.


text:
Q: Magento 2 is use MVC or MVMM? There is also have a question same as mine. However, there is still more thing I really don't understand, because when you develop module, all of them use MVC architecture. But at the same time, there are people still said that Magento 2 follow MVVM. So, what architecture that Magentro 2 use?

A: Magento 2 is a Model View ViewModel System and no more a design structured by MVC. The MVC model was incorporated in the previous version and seems to be quite similar to MVVM, but MVVM is a way more rich in dividing the View and Model in an application.
MVVM has three layers that include Model, View, and ViewModel. The business logic of an extension or application is represented as Model, whereas front-end is represented by the View. Just like the way Controllers serve as a mediator in an MVC model, the ViewModel bridges the gap between the Model and View in an MVVM system.
An extension developed for Magento 2 is said to consist of the basic design elements that are discussed above. Whereas, the role of controllers is not fully removed from Magento 2 as it is made responsible for managing the user flow that includes communicating the system about users' requests.
Let me explain the same with the help of an example. For the sake of an example, you can try setting up a new URL and creating a phtml template for it. When you request a new URL in Magento 2, like http://magento.abc.com/hi/friend the MVVM system will send the request to a controller to process it just like the way it is done in MVC. But, there is a major difference in the responsibility of the controller in MVVM. It is held responsible for
Determining the page layout to select
Managing to preserve the data from user requests
And, either communicate the system to respond with HTTP, or
Direct users to next or previous page

Setting up an example URL will help you notice that not a single variable gets mentioned in the View because each View component is held responsible to derive data or information itself from the model layer, object, or an external source.  The MVVM makes Magento split an HTML page into multiple sections that are called as containers. These containers possess blocks that are connected through a tree-like structure. The blocks further include a phtml template file.
The Magento block object serves as a ViewModel if you speak specifically about the MVVM system. The object block is capable of scanning and reading the business models, user requests, acquiring data from external system, etc. the template file is termed as View that solely collaborates with the block object that is the View Model
For more detail refer: https://weblizar.com/blog/magento-2-is-model-view-view-model-system-and-not-mvc-explained/


text:
Q: Application of Law of Large numbers (1) If we have an i.i.d random variable $X_i$ with mean variance $(\mu, \sigma^2)$.
By Law of Large number, we have $\bar{X}\rightarrow^p \mu$.
But can we use Law of large number as well and claim that the expression:
$$\frac{\sum_{i=1}^n X_i}{n+1} \rightarrow^p \mu$$ as well?
I tried the following manipulation:
$\frac{\sum_{i=1}^n X_i}{n+1}= \frac{n}{n+1} \frac{\sum_{i=1}^n X_i}{n}$ and claim by Law of Large number,$\frac{\sum_{i=1}^n X_i}{n} \rightarrow^p \mu$ and $\frac{n}{n+1} \rightarrow 1$ and thus it converges to $\mu$.
Is this approach correct? I couldn't find any theorem supporting such manipulation though.

A: Yes, your approach is correct. This manipulation is justified by Slutsky's theorem. See the article If $a_n \rightarrow 1$, does $X_n \overset{p}{\rightarrow} X$ implies $a_n X_n \overset{p}{\rightarrow} X$? for a reference to, and discussion about, Slutsky's theorem (and also a proof).


text:
Q: Why is there a private access modifier in an abstract class in Java, even though we cannot create an instance of an abstract class? I know it is not a good coding practice to declare a method as private in an abstract class.  Even though we cannot create an instance of an abstract class, why is the private access modifier available within an abstract class, and what is the scope of it within an abstract class? In which scenario is the private access specifier used in an abstract class?
check out this code where Vehicle class is abstract  and Car  extends  Vehicle.
package com.vehicle;

abstract class Vehicle {

 // What is the scope of the private access modifier within an abstract class, even though  method below cannot be accessed??
  private void onLights(){
   System.out.println("Switch on Lights");
  }

  public void startEngine(){
   System.out.println("Start Engine");
  }

}

Within is the same package creating a Car class
package com.vehicle;
/*
 * Car class extends the abstract class Vehicle
 */
public class Car extends Vehicle {

 public static void main(String args[]){
  Car c =  new Car();
  c.startEngine();
  // Only startEngine() can be accessed
 }

}

A: It's the same as in a non-abstract class, there's no difference.
Which means that if nothing in your abstract class calls the private method, then you can just as well remove it, as it won't be called (baring some evil reflection work).
Usually, private methods are only used as internal utility methods that have a very specific task that the other methods in the class use to do their work.

A: Since an abstract class can contain functionality (as opposed to an interface) it can have private variables or methods.
In your example you might do something like
 public void startEngine(){
   injectFuel();
   igniteSpark();
   // etc. my understanding of engines is limited at best
   System.out.println("Start Engine");
 }

 private void injectFuel() {}
 private void igniteSpark() {}

That way you can spread some of the work to other methods (so you don't have a 1000 line startEngine method), but you don't want the children to be able to call injectFuel separately since it doesn't make sense outside the context of startEngine (you want to make sure it's only used there).
Or even more you might have a private method that gets called in several other public methods, with different parameters. This way you avoid writing the same code twice or more in each of the public methods, and grouping the common code in a private method makes sure the children don't access it (like they couldn't just call part of the public method before). Something like this:
 public void startEngine() {
   dishargeBattery(50);
   System.out.println("Start Engine");
 }

 public void startRadio() {
   dischargeBattery(20);
 }

 private void dischargeBattery(int value) {
   battery.energy -= value; //battery should probably be a private field.
 }

This way your methods can have access to the battery, but the children shouldn't mess with it, and you don't write the same line (battery.energy -= value) in both of them. Take note though, that these are very simple examples, but if dischargeBattery was a 500 line method, writing it in both the other methods would be a hassle.

A:
I know it is not a good coding
  practice to declare a method as
  private in an abstract class.

I don't. Where did you get that idea?

what is the scope of it within an abstract class?

The abstract class.

A: The method can be accessed only from within the abstract class. For example, you could have an abstract class with a public final method that makes use of a private helper method.

A: package arrayafter;

public abstract class Abstract_Demo {

    abstract void display();

    private void display1() {
        System.out.println("Private Method");
    }

    final void display2() {
        System.out.println("final Method");
        display1();
    }

    public static void display3() {

        System.out.println("Static methods");
    }

}

package arrayafter;

import java.util.Scanner;

public class Practice extends Abstract_Demo{

    public static void main(String[] args) {

        Practice pr=new Practice();
        pr.display();
        pr.display2();
        Abstract_Demo.display3();
    }

    @Override
    void display() {
        // TODO Auto-generated method stub
        System.out.println("Abstract method");

    }

}


text:
Q: If I want to stream tweet into BigQuery, which is the best way? I want to do some tweet analytics and show real time result to customer. The first step is stream tweet into BigQuery. I found some method, cloud pub/sub, app engine, compute engine etc. How to choose? Is there any better ways to do that?

A: I would:

*

*Push tweet into Pub/Sub. Encode it as a full [{row:""}]

*Click on the Pub/Sub button "stream to BigQuery" (make sure to have an existing table with a column called "row").

*Parse the "" inside BigQuery into a full fledged table.


text:
Q: CSS MIME mismatch in browser using Angular and Deno I'm setting up an Angular-Deno stack proof of concept. For Angular app generation @angular/cli version 9.1.9 is used. After the app was generated, I create a production build with npm run build -- --prod and the output is in the dist folder of the application.
The deno server code is following:
import { Application } from "https://deno.land/x/abc@v1.0.0-rc8/mod.ts";

const app = new Application();

app.static("/", "./client/dist/client");
app.file("/", "./client/dist/client/index.html");
app.start({ port: 8080 });

The paths are correct, the built Angular app is in ./client/dist/client.
When I start the server with deno run --allow-net --allow-read .\server.ts command and navigate to `http://localhost:8080/ url in the browser the Angular application is downloaded. This is working fine.
However, there is a warning on the browser console:
Resource interpreted as Stylesheet but transferred with MIME type text/plain

I checked the generated index.html of the Angular app, and the CSS reference looks following:
<link rel="stylesheet" href="styles.09e2c710755c8867a460.css">

If I change the above <link> to
<link type="text/css" href="styles.09e2c710755c8867a460.css">

then it is working fine, the warning disappears from the browser console.
Is there a way to generate the index.html of the Angular app so that it contains the <link> entry of the second way above?
Or is there a configuration in deno request pipeline that can handle the originally generated <link> entry of the Angular app and set the CSS MIME correctly?
I would like to avoid using a custom post-build script to change the <link> entry of the generated html.

A: The link tag is correct but the abc framework is not setting the right Content-Type header for css files, in fact static middleware does not set Content-Type at all for any file type.
To fix it, you can set the Content-Type yourself using a middleware, or use a framework that has that functionality already built-in. You can use Oak.
import { Application, send } from "https://deno.land/x/oak/mod.ts";

const app = new Application();

app.use(async (context) => {
  await send(context, context.request.url.pathname, {
    root: `${Deno.cwd()}/client/dist/client`,
    index: "index.html",
  });
});

await app.listen({ port: 8080 });


text:
Q: LayoutInflater in RecyclerView adapter Im trying to create a popup in recycler view adapter to show a small menu when the user click on an item of the recycler view.
This is the popup function:
public void Popup(final int id) {
        AlertDialog.Builder rBuilder = new AlertDialog.Builder(context);
        LayoutInflater i = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View rView = i.inflate(R.layout.comment_setting_popup, null);
    rBuilder.setView(rView);
        dialog = rBuilder.create();
        dialog.show();
    }

I call this function in the onBindViewHolder of the adapter.
This code work fine in one adapter but in another one it always show me the same error:
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.ayhemprod.jokesbox, PID: 4939
                  android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
                      at android.view.ViewRootImpl.setView(ViewRootImpl.java:765)
                      at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
                      at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
                      at android.app.Dialog.show(Dialog.java:330)
                      at com.ayhemprod.jokesbox.Adapters.AddShowCommentsAdapter.signalePopup(AddShowCommentsAdapter.java:295)
                      at com.ayhemprod.jokesbox.Adapters.AddShowCommentsAdapter$1.onClick(AddShowCommentsAdapter.java:71)
                      at android.view.View.performClick(View.java:6294)
                      at android.view.View$PerformClick.run(View.java:24770)
                      at android.os.Handler.handleCallback(Handler.java:790)
                      at android.os.Handler.dispatchMessage(Handler.java:99)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6494)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

I tried some solution i found here in stackoverflow but nothing helped and i couldnt find the source of the problem especially that the same code work in another adapter in the same project.
UPDATE:
this is the code for the onBindViewHolder:
public void onBindViewHolder(AddShowCommentsAdapter.MyViewHolder holder, final int position) {
        Comment c = commentsList.get(position);
holder.comment_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signalePopup(commentsList.get(position).getId());
            }
        });
}

Im getting the context threw the adapter constructor, when i call the adapter from activity i add the getApplicationContext as a parameter.
public AddShowCommentsAdapter(List<Comment> commentsList, Context context) {
        this.context = context;
        this.commentsList = commentsList;
    }

A: In case of AlertDialog you should be using Activity as your Context instead of getApplicationContext().
You can find more detailed information on that here:
Why does AlertDialog.Builder(Context context) only accepts Activity as a parameter?
and here:
Dialog throwing "Unable to add window — token null is not for an application" with getApplication() as context

A: Instead of writing popup function in Adapter class, Write in Fragment/Activity class where adapter object is attached to recyclerview.
Delegate user click event from Adapter class to respective Activity/Fragment by writing Interface. Call Popup function from callback function of interface


text:
Q: ExtJS 4 - Wrapping the column headers in grid panel I have a grid which has long phrases as header texts. These texts are never displayed properly in the available width for the column.
Is there any way these texts can be wrapped and limited to the column width?
Here is an image of the issue:

A: Give this a shot in your CSS:
.x-grid3-hd-inner {
     overflow: hidden;
     padding: 3px 3px 3px 5px;
     white-space: normal;
}

And additionally, another option if the first doesn't work:
.x-column-header-inner .x-column-header-text {
    white-space: normal;
}

.x-column-header-inner {
    line-height: normal;
    padding-top: 3px !important;
    padding-bottom: 3px !important;
    text-align: center;
    top: 20%;
}


text:
Q: how to implement use of join() method in titanium? I am developing android app in titanium studio, my question how to join array of elements separated by comma.
I used like
temp = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
var string_temp = temp.join();

but it is not working any suggestions?

A: What you have there is an object not an array. temp should be ["a", "b", "c", ....]


text:
Q: Segmentation fault (core dumped) while using matplotlib python module I am using matplotlib in a python script in order to create a pie chart, but facing the bellow issue while running it:
Segmentation fault (core dumped)

Even if I went through some related issue in StackOverflow, but didn't find something covering my testcase.
I am using python3.6, matplotlib: '3.3.2' and I am  importing the modules as follows:
import matplotlib.backends
import matplotlib.figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.font_manager import FontProperties

This is my code:
fig = matplotlib.figure.Figure(figsize=(4,4))
fig.set_facecolor('lightgrey')
ax = fig.add_subplot(111)
Found_over_Res = {}
for _asw in over_Res:
    if over_Res[_asw] != 0:
        Found_over_Res[_asw] = over_Res[_asw]
        ax.pie(Found_over_Res.values(), autopct='%1.1f%%')
        fontP = FontProperties()
        fontP.set_size('xx-small')
        ax.legend(Found_over_Res.keys(), loc='best', prop=fontP)
        overCanvas = FigureCanvasTkAgg(fig, master=_Tempo)
        overCanvas.get_tk_widget().grid(row=0, column=4)
        overCanvas.draw()

Don't know if I missed something, for that I am facing that error, anyone could support, that will be appreciated thanks!


text:
Q: Bipartite Graph: Show that if $\deg(V_0)=3$, then we may $\Delta +1$ edge colour such a graph $G$. Suppose that every odd cycle in a graph $G$ contains some specific vertex
$V_0$
a) Give an example that shows that $\chi^E(G)$ may be larger than $\Delta$
b) Show that if $\deg(V_0)=3$, then we may $\Delta +1$ edge colour such a graph $G$.
$\chi^E(G)$ is the edge chromatic number which is the minimum # colors needed to edge color G.

A: I assume that $\Delta$ is the maximal degree and that $\chi^E(G)$ is the edge-chromatic number (minimal number of coulours for an edge-colouring).
a) The triangle graph has $\Delta=2$, but $\chi^E(G)=3$ (and any vertex can play the role of $V_0$)
b) If we remove two of the edges $V_0A$, $V_0B$ incident with $V_0$, the graph becomes bipartite (because there are no odd cycles). A bipartite graph has $\chi^E(G')=\Delta(G')\le \Delta(G)$. Construct a valid colouring for $G$ from this (you may need to swap a few colours)


text:
Q: Thousands of IF statements in Python I'm a beginner with Python. Currently I'm making a car reading tool just to build some programming skill. All works well.
When I get a fault code from a control module from a car, I get a P-code. Like:
P2348 and P21E2 (random P codes)
I can retrieve these P codes, but I want to add a little more info to them. P codes can be linked to a fault description:

P2348 - Misfire detected (random)

I want my program to give the extended information, and not just the P code. There are thousands of P codes and I have them all with discription. But a thousand If statements would be bad coding. I could look the P code up in a textfile and get the complete string from it, but that's not really an option (unless it's possible in the code itself or compiled with the executable).
What would be a neat way to do this? I have encountered this problem before when I took programming lessons. I used IF statements then (about 20) and I hated it.

A: Use a dictionary:
code_descr = {
   'P2348': 'Misfire detected',
   'P8866': 'Engine is on fire',
   'P7777': 'Tires missing',
}

then you can lookup a key in the dict, no if needed:
print('{} - {}'.format(code, code_descr[code]))

You can write code to read a database in some format (csv, json, etc) and generate the dict, so you have the descriptions external to the program


text:
Q: When the Induced homomorphism on fundamental groups is surjective? If $X$ is a path-connected topological space and $A$ is a pathconnected subspace of $X$, do we have some "standard" conditions on $X$ or $A$ or the inclusion $i:A\hookrightarrow X$ under which the inclusion $i$  induces an epimorphism  $$i_*:\pi_1(A)\longrightarrow \pi_1(X)\;
 $$
on fundamental groups?

A: One standard such condition is that $X$ is obtained from $A$ by (iteratively) attaching cells of dimension $\ge 2$. You can find this result in Hatcher's book for example, as a straightforward application of Van Kampen's Theorem.
As a consequence, if $X$ is a CW complex then for any $n \ge 1$ the inclusion of the $n$-skeleton $X^{(n)} \hookrightarrow X$ induces an epimorphism of fundamental groups (for any base point in $X^{(n)}$).
Indeed one can go further: If in addition $X$ is obtained from $A$ by iteratively attaching only cells of dimension $\ge 3$ then the inclusion $A \hookrightarrow X$ induces an isomorphism of fundamental groups. Thus for any $n \ge 2$ the inclusion of the $n$-skeleton of a CW complex induces an isomorphism of fundamental groups.


text:
Q: В чем смысл некоторых аннотаций в Doctrine? Работаю над своим небольшим проектом, использую Laravel и Doctrine как основную ORM. Doctrine была выбрана только с целью получить опыт работы с ней. Для миграций, принял решение использовать встроенные в laravel средства.
Собственно вопрос: когда определяешь Entity, обязательно ли указывать опции в аннотациях, которые были заданы в миграциях(тип, длины строки, nullable ...)?
Как я понял: эти опции используются только при генерации таблиц. Или все же, doctrine как-то контролирует целостность в runtim'e?

A: Она контроллирует, допустим у вас есть модель User с полем $name, ассертами указано, что оно не должно быть пустым и представляет собой строку. Теперь при попытке записать туда пустую строку или запихнуть массив, вы получите Doctrine\DBAL\Exception, которое можно перехватить и выдать красивую ошибку о неверных данных


text:
Q: Overwriting injected object I'm a little bit confused about the CDI-behavior regarding the changing of injected objects.
I've got a simple user-class containing login and password. I produce an object for CDI:
public class SessionService {

    @LoggedIn
    @Produces @SessionScoped
    public User loggedInUser() {
        return new User("login", "pass");
    }
}

In the next step, the user opens an login-view and the login-controller checks the credentials.
@Named
@SessionScoped
public class LoginController extends Controller implements Serializable {

    private static final long serialVersionUID = 6047784887724513434L;

    @Inject
    UserService userService;

    @Inject
    Credentials credentials;

    @Inject
    @LoggedIn
    User currentUser;

    public void doLogin() {
        User check = userService.findUser(credentials.getLogin());
        if((check != null) && (check.getPasswort().equals(SHA256.hash(credentials.getPasswort())))) {
            currentUser = check;
            FacesRedirect.fromOutcome("login.success");
        } else {
            addErrorMessage("loginFailed");
        }
    }
}

When I try to overwrite the initially produced currentUser-object with the found "check"-user this doesn't work - I don't get an error, but the injected object in other classes is the same as before.
When I call the setLogin() / setPassword() methods of the injected currentUser-object, these changes are available to all other classes.
currentUser.setId(check.getId());
currentUser.setLogin(check.getLogin());
currentUser.setPasswort(check.getPassword());

Is there another way to overwrite the whole object instead of calling all the setters?
On the first try I used @Produces in the LoginController, but when I what to inject it into an Filter, the startup fails.
Thanks for the help,
Tobias
==================== edit ====================
Like @atamanroman suggested, I removed the SessionService and added this to the LoginController:
@Produces
@LoggedIn
public User getCurrentUser() {
    return currentUser;
}

I use javax.enterprise.context.SessionScoped for the controllers SessionScope, the LoginFilter looks like this:
package de.mad_onion.thweb.util;

import java.io.IOException;

import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import de.mad_onion.thweb.domain.User;

@Named("loginFilter")
@WebFilter(filterName = "LoginFilter", urlPatterns = {"/einsatz.xhtml"})
public class LoginFilter implements Filter {

    @Inject
    @LoggedIn
    User currentUser;

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain fc) throws IOException, ServletException {

        HttpServletResponse httpResponse = (HttpServletResponse)response;
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        HttpSession httpSession = httpRequest.getSession();

        if(currentUser == null) {
            System.out.println("No user");
        } else {
            System.out.println("User:");
            System.out.println(currentUser.toString());
        }
        fc.doFilter(request, response);

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        System.out.println("Filter initialized");
    }
}

If I try to deploy the application, I get this stacktrace:
18:03:47,025 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/thweb]] (MSC service thread 1-2) Exception starting filter LoginFilter: java.lang.IllegalStateException: JBAS011048: Failed to construct component instance
    at org.jboss.as.ee.component.BasicComponent.constructComponentInstance(BasicComponent.java:163) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.ee.component.BasicComponent.createInstance(BasicComponent.java:85) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.web.deployment.component.WebComponentInstantiator$1.<init>(WebComponentInstantiator.java:57) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.web.deployment.component.WebComponentInstantiator.getReference(WebComponentInstantiator.java:55) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.web.deployment.WebInjectionContainer.instantiate(WebInjectionContainer.java:99) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.web.deployment.WebInjectionContainer.newInstance(WebInjectionContainer.java:78) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.web.deployment.WebInjectionContainer.newInstance(WebInjectionContainer.java:72) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:441) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3269) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:3865) [jbossweb-7.0.13.Final.jar:]
    at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:90) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [rt.jar:1.6.0_31]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [rt.jar:1.6.0_31]
    at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_31]
Caused by: org.jboss.weld.context.ContextNotActiveException: WELD-001303 No active contexts for scope type javax.enterprise.context.SessionScoped
    at org.jboss.weld.manager.BeanManagerImpl.getContext(BeanManagerImpl.java:598) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
    at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:616) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
    at org.jboss.weld.bean.AbstractReceiverBean.getReceiver(AbstractReceiverBean.java:73) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
    at org.jboss.weld.bean.ProducerMethod$1.produce(ProducerMethod.java:131) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
    at org.jboss.weld.bean.AbstractProducerBean.create(AbstractProducerBean.java:299) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
    at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:61) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
    at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:616) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
    at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:681) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
    at org.jboss.as.weld.injection.InjectableField.inject(InjectableField.java:56) [jboss-as-weld-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.weld.injection.WeldEEInjection.inject(WeldEEInjection.java:81) [jboss-as-weld-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.weld.injection.WeldInjectionInterceptor.processInvocation(WeldInjectionInterceptor.java:60) [jboss-as-weld-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ee.component.ManagedReferenceInterceptorFactory$ManagedReferenceInterceptor.processInvocation(ManagedReferenceInterceptorFactory.java:95) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ee.component.TCCLInterceptor.processInvocation(TCCLInterceptor.java:45) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ee.component.BasicComponent.constructComponentInstance(BasicComponent.java:161) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    ... 15 more

18:03:47,095 ERROR [org.apache.catalina.core.StandardContext] (MSC service thread 1-2) Error filterStart
18:03:47,097 ERROR [org.apache.catalina.core.StandardContext] (MSC service thread 1-2) Context [/thweb] startup failed due to previous errors
18:03:47,100 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-2) MSC00001: Failed to start service jboss.web.deployment.default-host./thweb: org.jboss.msc.service.StartException in service jboss.web.deployment.default-host./thweb: JBAS018040: Failed to start context
    at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:95)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [rt.jar:1.6.0_31]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [rt.jar:1.6.0_31]
    at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_31]

18:03:47,313 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS015870: Deploy of deployment "thweb.war" was rolled back with failure message {"JBAS014671: Failed services" => {"jboss.web.deployment.default-host./thweb" => "org.jboss.msc.service.StartException in service jboss.web.deployment.default-host./thweb: JBAS018040: Failed to start context"}}
18:03:47,319 WARN  [org.jboss.as.ee] (MSC service thread 1-3) JBAS011005: Failed to destroy component instance org.jboss.as.ejb3.component.singleton.SingletonComponentInstance@cafb6f: org.agoncal.application.petstore.exception.ValidationException: Category object is null
    at org.agoncal.application.petstore.service.CatalogService.removeCategory(CatalogService.java:75)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_31]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [rt.jar:1.6.0_31]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [rt.jar:1.6.0_31]
    at java.lang.reflect.Method.invoke(Method.java:597) [rt.jar:1.6.0_31]
    at org.jboss.as.ee.component.ManagedReferenceMethodInterceptorFactory$ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptorFactory.java:72) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:374) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.weld.ejb.DelegatingInterceptorInvocationContext.proceed(DelegatingInterceptorInvocationContext.java:81)
    at org.agoncal.application.petstore.util.LoggingInterceptor.logMethod(LoggingInterceptor.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_31]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [rt.jar:1.6.0_31]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [rt.jar:1.6.0_31]
    at java.lang.reflect.Method.invoke(Method.java:597) [rt.jar:1.6.0_31]
    at org.jboss.interceptor.proxy.InterceptorInvocation$InterceptorMethodInvocation.invoke(InterceptorInvocation.java:72)
    at org.jboss.interceptor.proxy.SimpleInterceptionChain.invokeNextInterceptor(SimpleInterceptionChain.java:82)
    at org.jboss.weld.bean.InterceptorImpl.intercept(InterceptorImpl.java:90)
    at org.jboss.as.weld.ejb.DelegatingInterceptorInvocationContext.proceed(DelegatingInterceptorInvocationContext.java:71)
    at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.delegateInterception(Jsr299BindingsInterceptor.java:112)
    at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.doMethodInterception(Jsr299BindingsInterceptor.java:125)
    at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:135)
    at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:36) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:36) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.jpa.interceptor.SBInvocationInterceptor.processInvocation(SBInvocationInterceptor.java:47)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:82)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.invocation.InitialInterceptor.processInvocation(InitialInterceptor.java:21) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor.processInvocation(ComponentDispatcherInterceptor.java:53) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ejb3.component.pool.PooledInstanceInterceptor.processInvocation(PooledInstanceInterceptor.java:51)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:202)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.required(CMTTxInterceptor.java:306)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(CMTTxInterceptor.java:190)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor.processInvocation(CurrentInvocationContextInterceptor.java:41)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ejb3.component.interceptors.LoggingInterceptor.processInvocation(LoggingInterceptor.java:59)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ejb3.component.interceptors.AdditionalSetupInterceptor.processInvocation(AdditionalSetupInterceptor.java:32)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ee.component.TCCLInterceptor.processInvocation(TCCLInterceptor.java:45) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ee.component.ViewService$View.invoke(ViewService.java:165) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.ee.component.ViewDescription$1.processInvocation(ViewDescription.java:173) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ee.component.ProxyInvocationHandler.invoke(ProxyInvocationHandler.java:72) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.agoncal.application.petstore.service.CatalogService$$$view127.removeCategory(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_31]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [rt.jar:1.6.0_31]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [rt.jar:1.6.0_31]
    at java.lang.reflect.Method.invoke(Method.java:597) [rt.jar:1.6.0_31]
    at org.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:264)
    at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:52)
    at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:137)
    at org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:260)
    at org.jboss.weld.bean.proxy.EnterpriseBeanProxyMethodHandler.invoke(EnterpriseBeanProxyMethodHandler.java:111)
    at org.jboss.weld.bean.proxy.EnterpriseTargetBeanInstance.invoke(EnterpriseTargetBeanInstance.java:56)
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:105)
    at org.agoncal.application.petstore.service.CatalogService$Proxy$_$$_Weld$Proxy$.removeCategory(CatalogService$Proxy$_$$_Weld$Proxy$.java)
    at de.mad_onion.thweb.service.DBPopulator.clearDB(DBPopulator.java:96)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_31]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [rt.jar:1.6.0_31]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [rt.jar:1.6.0_31]
    at java.lang.reflect.Method.invoke(Method.java:597) [rt.jar:1.6.0_31]
    at org.jboss.as.ee.component.ManagedReferenceLifecycleMethodInterceptorFactory$ManagedReferenceLifecycleMethodInterceptor.processInvocation(ManagedReferenceLifecycleMethodInterceptorFactory.java:130) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ee.component.ManagedReferenceReleaseInterceptorFactory$ManagedReferenceReleaseInterceptor.processInvocation(ManagedReferenceReleaseInterceptorFactory.java:90) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(CMTTxInterceptor.java:228)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.requiresNew(CMTTxInterceptor.java:333)
    at org.jboss.as.ejb3.tx.SingletonLifecycleCMTTxInterceptor.processInvocation(SingletonLifecycleCMTTxInterceptor.java:56)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor.processInvocation(CurrentInvocationContextInterceptor.java:41)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ee.component.TCCLInterceptor.processInvocation(TCCLInterceptor.java:45) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
    at org.jboss.as.ee.component.BasicComponentInstance.destroy(BasicComponentInstance.java:119) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.ejb3.component.singleton.SingletonComponent.destroySingletonInstance(SingletonComponent.java:179)
    at org.jboss.as.ejb3.component.singleton.SingletonComponent.stop(SingletonComponent.java:136)
    at org.jboss.as.ee.component.ComponentStartService.stop(ComponentStartService.java:49) [jboss-as-ee-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.msc.service.ServiceControllerImpl$StopTask.stopService(ServiceControllerImpl.java:1911) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at org.jboss.msc.service.ServiceControllerImpl$StopTask.run(ServiceControllerImpl.java:1874) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [rt.jar:1.6.0_31]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [rt.jar:1.6.0_31]
    at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_31]

A: If you inject your current User in other beans with @Inject @LoggedIn the container will always call the method annotated with @Producer and alas create a new User (return new User("login", "pass");). The correct User will only be set in your LoginController, which has nothing at all to do with your SessionService. I guess removing SessionService and creating a getter for currentUser in LoginController which is marked with @Produces @LoggedIn will solve the problem in your logic.
The real problem seems to be that injection into your Filter does not work. Could you please verify that you use the correct @SessionScoped annotation (not from jsf) and show your filter implementation with a detailed error message?
As stated here, you have to annotate your Filter class with @WebFilter/@Named instead of @ManagedBean or @Inject won't work. Mixing both may cause unwanted headache.

A: I had a couple of "fancy" ways to do this, but honestly, using the setters is the cleanest way to do this.


text:
Q: Possible to add HTML formatting (bold, italics) to string data cells in parse? My app is reading text content from a string data cell in Parse. Is it possible to add HTML formatting to this text within Parse? Bold, italics, etc.

A: Can you add strings such as these when you are parsing?
<b> Defines bold text
<em> Defines emphasised text
<i> Defines italic text
<small> Defines smaller text
<strong> Defines important text

An example of parsing a string can be found in the jQuery API Documentation at: http://api.jquery.com/jquery.parsehtml/


text:
Q: In Git-Bash-Windows `openssl pkcs12` does not prompt for password The SSL certificate authority sent me the signed certificate in .pfx format and it was password-protected; so I need to convert it to .crt file.
The first attempt was to call openssl pkcs12 -in server.pfx -out server.crt -nokeys -clcerts, simply in Git-Bash Windows; but it waits forever, and there was no output nor hint. Eventually, I switched to Linux (RHEL7), and the same command worked OK. It turns out, in Linux the command prompts "Enter Import Password:"; however, running in Windows Git-Bash the it's missing the prompt for password, and will be hanging there forever.
I'm wondering if there is anything to make it work in Windows Git-Bash, e.g. command argument, etc., as my work computer is still running Windows OS. Any pointers will be highly appreciated.
Screenshot of Linux:
[root@host]# openssl pkcs12 -in server.pfx -out server.crt -nokeys -clcerts
Enter Import Password:
MAC verified OK
[root@host]#

A: First, on Windows 10, you could switch to any Linus distro of your choice through WSL2.
Second, on Windows, I always had to include the password in the command line:
openssl pkcs12 -password pass:aPassword -in server.keystore.pfx -nokeys -clcerts -out server.cert
# or
openssl pkcs12 -passin pass:aPassword -in server.keystore.pfx -nokeys -clcerts -out server.cert

A: On Git-Bash, you have to use winpty in front; e.g.,
$ winpty openssl pkcs12 -in server.keystore.pfx -nokeys -clcerts -out server.cert

A: I just found out how - After a whole day of thinking. You may refer to this link for the explanation https://omgdebugging.com/2019/03/17/openssl-hanging-up-when-trying-to-convert-certificates/
"This issue arises because in the difference how input is passed to the OpenSSL command by Git Bash console. The fix to this issue is adding the word winpty before the entire command. Doing this will make the prompt enter your password, confirm the password again and once done, you will notice that a PFX file has been generated."


text:
Q: Pyspark Error ReduceByKey I have a problem with my reduceByKey(). I don't display the result... I have keys, values... But impossible to use reduceByKey...
data_test_bis = data_textfile.map(lambda x: (x.split(",")[8].encode("utf-8").replace('"','').replace("'",''), 1)).filter(lambda x: x[0].startswith('Ru'))#.reduceByKey(lambda x, y: x + y)
#data_test_filter = data_test_bis.filter(lambda x: x[0].startswith('"R'))
print("TEST FILTER !")
print(type(data_test_bis))
print(data_test_bis.take(5))
print(data_test_bis.keys().take(10))
print(data_test_bis.values().take(10))

Results:
TEST FILTER !
<class 'pyspark.rdd.PipelinedRDD'>
[('Rueil-Malmaison', 1), ('Ruse', 1), ('Rueil Malmaison', 1), ('Rueil-Malmaison', 1), ('Ruda Slaska', 1)]
['Rueil-Malmaison', 'Ruse', 'Rueil Malmaison', 'Rueil-Malmaison', 'Ruda Slaska', 'Ruisbroek (Belgique)', 'Ruda \xc3\x85\xc5\xa1l\xc3\x84\xe2\x80\xa6ska', 'Rueil malmaison', 'Rueil', 'Ruisbroek']
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

When i try this one, there are an error:
print(data_test_bis.reduceByKey(add).take(10))

or
print(data_test_bis.reduceByKey(lambda x, y: x + y).take(10))

Error:
17/01/03 17:47:09 ERROR scheduler.TaskSetManager: Task 18 in stage 3.0 failed 4 times; aborting job
Traceback (most recent call last):
  File "/home/spark/julien/Test_.py", line 89, in <module>
    test()
  File "/home/spark/julien/Test_.py", line 33, in test
    print(data_test_bis.reduceByKey(lambda x, y:x+y).take(10))
  File "/home/spark/opt/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 1297, in take
  File "/home/spark/opt/spark/python/lib/pyspark.zip/pyspark/context.py", line 939, in runJob
  File "/home/spark/opt/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py", line 813, in __call__
  File "/home/spark/opt/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 45, in deco
  File "/home/spark/opt/spark/python/lib/py4j-0.9-src.zip/py4j/protocol.py", line 308, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.runJob.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 18 in stage 3.0 failed 4 times, most recent failure: Lost task 18.3 in stage 3.0 (TID 67, 10.0.15.7): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/opt/spark/python/lib/pyspark.zip/pyspark/worker.py", line 111, in main
    process()
  File "/opt/spark/python/lib/pyspark.zip/pyspark/worker.py", line 106, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/home/spark/opt/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2346, in pipeline_func
  File "/home/spark/opt/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2346, in pipeline_func
  File "/home/spark/opt/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 317, in func
  File "/home/spark/opt/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 1776, in combineLocally
  File "/opt/spark/python/lib/pyspark.zip/pyspark/shuffle.py", line 236, in mergeValues
    for k, v in iterator:
  File "/home/spark/julien/Test_.py", line 25, in <lambda>
IndexError: list index out of range

I don't understand why i have an IndexError...

A: Just repeat after me: I will never assume that an unstructured data source is well formed.
Things like:
... .map(lambda x: (x.split(",")[8].encode("utf-8") ...)

are great for quick tutorials but are useless in practice. In general never depend on the assumptions that:

*

*Data has specific shape (there will be for example 9, comma-separated fields).

*Encoding / decoding will succeed (here we actually can but it is not true in general).

At least include a minimalistic exception handling:
def parse_to_pair(line):
    try:
        key = (line
            .split(",")[8]
            .encode("utf-8")
            .replace('"', '')
            .replace("'", ''))

        return [(key, 1)]
    except:
        return []

and use flatMap:
data_textfile.flatMap(parse_to_pair)

Notes:

*

*You can skip encode by calling SparkContext.textFile with use_unicode set to False. It will:

*

*Use str instead of unicode in Python 2.

*Use bytes in Python 3.

*You should not only make sure that line contains at least 9 fields, but that it contains an expected number of fields.

*If you by any chance have csv as an input use csv reader.


text:
Q: AMQP + NodeJS wait for channel I have a service in FeathersJS that initiates a connection to RabbitMQ, the issue is how to await for a channel to be ready before receiving requests:
class Service {
  constructor({ amqpConnection, queueName }) {
    this.amqpConnection = amqpConnection;
    this.queueName = queueName;
    this.replyQueueName = queueName + "Reply"
  }

  async create(data, params) {
    new Promise(resolve => {
      if (!this.channel) await this.createChannel();
      channel.responseEmitter.once(correlationId, resolve);
      channel.sendToQueue(this.queueName, Buffer.from(data), {
        correlationId: asyncLocalStorage.getStore(),
        replyTo: this.replyQueueName,
      });
    });
  }

  async createChannel() {
    let connection = this.amqpConnection();
    let channel = await connection.createChannel();

    await channel.assertQueue(this.queueName, {
      durable: false,
    });

    this.channel = channel;
    channel.responseEmitter = new EventEmitter();
    channel.responseEmitter.setMaxListeners(0);
    channel.consume(
      this.replyQueueName,
      (msg) => {
        channel.responseEmitter.emit(
          msg.properties.correlationId,
          msg.content.toString("utf8")
        );
      },
      { noAck: true }
    );
  }
  ....
}

Waiting for the channel to be created during a request seems like a waste. How should this be done "correctly"?

A: Feathers services can implement a setup method which will be called when the server is started (or you call app.setup() yourself):
class Service {
  async setup () {
    await this.createChannel();
  }
}


text:
Q: How to resize two RAID-1 partitions? I have an Ubuntu 12.04 server with two 3TB disks and Software-RAID 1. Currently they are partitioned as follows:
# discus
Mount           Total         Used         Avail      Prcnt      Graph
/                1.00 TB      8.55 GB      0.99 TB     0.8%   [----------]
+onnections         0 KB         0 KB         0 KB     0.0%   [----------]
+rnel/debug         0 KB         0 KB         0 KB     0.0%   [----------]
+l/security         0 KB         0 KB         0 KB     0.0%   [----------]
/run             3.12 GB       304 KB      3.12 GB     0.0%   [----------]
/run/lock         5.0 MB         0 KB       5.0 MB     0.0%   [----------]
/run/shm         7.79 GB         0 KB      7.79 GB     0.0%   [----------]
/home            1.70 TB     13.06 GB      1.68 TB     0.8%   [----------]
/boot           495.8 MB      38.0 MB     457.9 MB     7.7%   [*---------]

# df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/md2        1.0T  8.6G  964G   1% /
udev            7.8G  4.0K  7.8G   1% /dev
tmpfs           3.2G  304K  3.2G   1% /run
none            5.0M     0  5.0M   0% /run/lock
none            7.8G     0  7.8G   0% /run/shm
/dev/md3        1.7T   14G  1.6T   1% /home
/dev/md1        496M   38M  433M   9% /boot

# cat /proc/partitions
major minor  #blocks  name

   8        0 2930266584 sda
   8        1   33554432 sda1
   8        2     524288 sda2
   8        3 1073741824 sda3
   8        4 1822443975 sda4
   8        5       1024 sda5
   8       16 2930266584 sdb
   8       17   33554432 sdb1
   8       18     524288 sdb2
   8       19 1073741824 sdb3
   8       20 1822443975 sdb4
   8       21       1024 sdb5
   9        0   33553336 md0
   9        1     524276 md1
   9        2 1073740664 md2
   9        3 1822442815 md3

I would like to reduce / to 100Gb and grow /home to 2.6Tb. What's the best way to do that? Server has no important data so I don't care about possible data loss.

A: The trick is using your second drive in RAID as spare one:

*

*Break the mirror(s) you have (except /boot one, if you have it);

*Create one big single partition for RAID on the disengaged drive (in addition to /boot's);

*Create RAID-1 using missing device (see man mdadm for that) and the partition;

*Make new mirror to be LVM-2 disk (pvcreate);

*Create volume group (vgcreate) and needed logical volumes (lvcreate), format them, mount temporary;

*Copy your stuff;

*Correct new /etc/fstab, make sure initrd would handle root filesystem on LVM-2 ok;

*Boot in;

*Stop old (intentionally broken) RAID;

*Partition its disk as replica of disengaged drive;

*Add it to new RAID so it would be based on missing drive no more.


text:
Q: How to remove duplicates in postgres (no unique id) I have some difficulty in removing duplicates rows. I thought user_id and time_id together acting as an identifier but there were even duplicates for those.
user_id (text), time_id(bigint), value1 (numeric)
user_id; time_id; value1|
aaa;1;3|
aaa;1;3|
aaa;2;4|
baa;3;1|

In this case how do I remove duplicates?
Since I have 16 distinct values in time_id and 15,000 distinct ones in user_id, I tried something like this but I do not have an unique id..
    DELETE FROM tablename a
     USING tablename b
    WHERE a.unique_id < b.unique_id
    AND   a.user_id = b.user_id
    time_id = 1       (repeat till time_id 16)

A: Please use any advice on deletions with care, make sure you have a way to "undo it" if needed. I think you need to add an auto-numbered column to assist in this endeavor
alter table tablename add column is_uniq serial

Then I'd suggest using row_number() to help identify the rows you do want to retain (where rn=1) and those to be deleted (where rn>1). Use the following as a guide:
select *
   , ROW_NUMBER()over(partition by user_id, time_id, value1 order by is_uniq) as rn from tablename

I'm not sure if there is any other columns(s) to use for order by, but if there are then you can include that into over clause as well.
Once you have the "is_uniq" column and the rn>1 rows you should be able to safely delete the unwanted rows.

A: Each table in Postgres has a few hidden system columns. One of them (ctid) is unique by definition and can be used in cases when a primary key is missing.
DELETE FROM tablename a
USING tablename b
WHERE a.ctid < b.ctid
AND a.user_id = b.user_id
AND a.time_id = b.time_id;

The problem is due to lack of primary key. Using hidden columns should not be a systematic method (see comments below). Once you delete duplicates you should create a primary key on (user_id, time_id) or create a new unique column for this purpose.

A: If you don't want to rely on ctid (personally,I do) ,you can add a unique column (such as aserial) and use that for identity-purposes,

CREATE TABLE lutser
        ( user_id text not null
        ,  time_i integer not null
        , value integer not null
        );
INSERT INTO lutser(user_id,time_i,value) VALUES
('aaa', 1, 3)
,('aaa', 1, 3)
,('aaa', 2, 4)
,('baa', 3, 1)
        ;

SELECT*FROM lutser;

ALTER TABLE lutser
        ADD COLUMN seq serial NOT NULL UNIQUE
        ;
SELECT*FROM lutser;

DELETE FROM lutser del
WHERE EXISTS(
        SELECT*FROM lutser x
        WHERE x.user_id=del.user_id
        AND x.time_i=del.time_i
        AND x.seq < del.seq
        );

ALTER TABLE lutser
        ADD PRIMARY KEY (user_id,time_i)
        ;

SELECT*FROM lutser;


text:
Q: What is the cgo type equivalent to a const pointer to a struct? I have an extern function decalred in C:
//extern void goCallback(const struct libvlc_event_t*, void*);

To be defined in go:
//export goCallback
func goCallback(event unsafe.Pointer, userData unsafe.Pointer) {
    log.Fatal("TODO goCallback")
}

When compiling the code, I get type conflicting errors
# github.com/tarrsalah/libvlc-go
In file included from $WORK/github.com/tarrsalah/libvlc-go/_obj/_cgo_export.c:3:0:
cgo-gcc-export-header-prolog:42:13: error: conflicting types for 'goCallback'
In file included from $WORK/github.com/tarrsalah/libvlc-go/_obj/_cgo_export.c:3:0:
../../../tarrsalah/libvlc-go/event_manager.go:6:13: note: previous declaration of 'goCallback' was here
 //extern void goCallback(const struct libvlc_event_t*, void*);
             ^~~~~~~~~~
/tmp/go-build855229382/github.com/tarrsalah/libvlc-go/_obj/_cgo_export.c:17:6: error: conflicting types for 'goCallback'
 void goCallback(void* p0, void* p1)
      ^~~~~~~~~~
In file included from $WORK/github.com/tarrsalah/libvlc-go/_obj/_cgo_export.c:3:0:
../../../tarrsalah/libvlc-go/event_manager.go:6:13: note: previous declaration of 'goCallback' was here
 //extern void goCallback(const struct libvlc_event_t*, void*);
             ^~~~~~~~~~

What is the go equivalent to const struct libvlc_event_t*?

A: Create type alias to the struct with typedef as follows:
/*

typedef const struct libvlc_event_t clibvlc_event_t;
extern void goCallback(clibvlc_event_t*, void*);
*/
import "C"

//export goCallback
func goCallback(event *C.clibvlc_event_t, userData unsafe.Pointer) {
    log.Fatal("TODO goCallback")
}

If you want to know go type definition which is compatible to C.clibvlc_event_t, run cgo with -godefs options, i.e.
go tool cgo -godefs <YOUR-GO-FILE>

For example, if the struct is defined as in https://docs.libreoffice.org/avmedia/html/Types_8hxx_source.html
struct libvlc_event_t
{
    int   type;  // event type
    void *p_obj; // object emitting that event

    union // so far we don't need this.
    {
     struct {
        const char *dummy1;
        const char *dummy2;
      } padding;
    } u;
};

then, the compatible struct in go will be:
type VLCEvent struct {
    Type      int32
    Pad_cgo_0 [4]byte
    Obj       *byte
    U         [16]byte
}

//Cast C struct to Go struct
ev := (*VLCEvent)(unsafe.Pointer(event))

//Cast Go struct to C struct
p := (*C.clibvlc_event_t)(unsafe.Pointer(&VLCEvent{}))

EDIT:
Add example struct.


text:
Q: Using r.js to build entire project without needing overhead of require.js I have a project with multiple javascript files, all formatted as AMD modules. I'm using r.js as part of my build process (using this grunt plugin to handle everything).
After I build my project, I end up with a concatenated, minified file that has jQuery, followed by all my modules ordered correctly. That said, these modules still make calls to require and define, so I need to include the entire require.js library when I send over my minified JS file to the client.
Is there any way I can build my JS such that I don't need to send require.js to the client? Like, when I build all my JS, can I just strip out the calls to define or require?
Any help would be greatly appreciated. This article from 2013 says there's no solution yet, but I'm hoping theres a fix now.
EDIT: One good suggestion I've heard is to use Almond.js, which I can do if that's the best solution to date. I was just hoping I didn't have to ship over any 3rd party library in the first place.

A: Use almond as a replacement for require.js in your built module.  Have it loaded first to give you what you need.


text:
Q: How do I design my switch case function in base class under this situation Let's say we have a Person class
class Person{
   int id;
   Status* cur_status;
   ...
}

and we have class Status as follows:
class Status{
    int income;
    int tax;
    virtual void reform(int _case);
    ...
}

class Unemployed : public Status{
    void reform(int _case){
        switch (_case){
            case 1: tax /= 2;   //recession
            case 2: tax /= 3;   //depression
            case 3: tax = 0;
            ...
        }
    }
}

class Worker : public Status{
    void reform(int _case){
        switch (_case){
            case 1: tax /= 2;   //recession
            case 2: tax /= 3;   //depression
            case 3: tax = 100;
            ...
        }
    }
}

Given the person, his/her status could be changed dynamically,
so now I've encountered a problem:
Some of the reformation case are the SAME between 2 statuses, while the others are not.
Do I have to declare ALL OF 'EM in the derived class respectively ?
Actually, I want to extract the common case into Base class, but I don't know how.
Is there anyone could help me ?

A: Something along these lines, perhaps:
class Unemployed : public Status{
    void reform(int _case){
        switch (_case){
          // Special case for this kind of Status
          case 1:
            tax /= 2;
            break;
          // Everything else is implemented by base class
          default:
            Status::reform(_case);
            break;
        }
    }
}


text:
Q: dynamically generate content for a page when clicking on product everyone. I am making a website with t-shirts. I dynamically generate preview cards for products using a JSON file but I also need to generate content for an HTML file when clicking on the card. So, when I click on it, a new HTML page opens like  product.html?product_id=id. I do not understand how to check for id or this part ?prodcut_id=id, and based on id it generates content for the page. Can anyone please link some guides or good solutions, I don't understand anything :(.

A: There are some solutions, how you can get the parameters from the url:
Get ID from URL with jQuery
It would also makes sense to understand what is a REST Api and how to build a own one, because i think you dont have a backend at the moment.
Here some refs:
https://www.conceptatech.com/blog/difference-front-end-back-end-development
https://www.tutorialspoint.com/nodejs/nodejs_restful_api.htm

A: It sounds like you want the user's browser to ask the server to load a particular page based on the value of a variable called product_id.
The way a browser talks to a server is an HTTP Request, about which you can learn all the basics on javascipt.info and/or MDN.
The ?product_id=id is called the 'query' part of the URL, about which you can learn more on MDN and Wikipedia.
A request that gets a page with this kind of URL from the server is usually a GET request, which is simpler and requires less security than the more common and versatile POST request type.
You may notice some of the resources talking about AJAX requests (which are used to update part of the current page without reloading the whole thing), but you won't need to worry about this since you're just trying to have the browser navigate to a new page.
Your server needs to have some code to handle any such requests, basically saying:
"If anybody sends an HTTP GET request here, look at the value of the product_id variable and compare it to my available HTML files. If there's a match, send a response with the matching file, and if there's no match, send a page that says 'Error 404'."
That's the quick overview anyway. The resources will tell you much more about the details.