问:
How to make QProgressBar display updates while another procedure is running in pyqt
I want to be able to show the progress of a procedure while it is running.  My problem is that the QProgressBar seems to be frozen while the procedure is running.  Below is an example that shows that while execute_procedure is running (first 5 seconds), the progress_bar doesn't visually update even though the thread is emitting.  </p>

```<code>from PyQt5 import QtWidgets, QtCore
import sys
import time

class ProgressThread(QtCore.QThread):
    progress_changed = QtCore.pyqtSignal(int)

    def __init__(self):
        super().__init__()

    def run(self):
        completed = 0
        max_time = 15

        increment = float(100 / max_time)
        while completed < 100:
            completed += increment
            time.sleep(1)
            self.progress_changed.emit(completed)
            # print('emitted ', completed) -- this is emitting while
            # execute_procedure is running but the progress bar
            # is not visually updating until the procedure is completed

class TestProgress(QtWidgets.QDialog):
    def __init__(self):
        super().__init__()

        self.tab = QtWidgets.QWidget()
        self.tab.setGeometry(300, 300, 1000, 200)

        self.button_execute = QtWidgets.QPushButton("Execute", self.tab)
        self.button_execute.clicked.connect(self.on_click)

        self.progress_bar = QtWidgets.QProgressBar(self.tab)
        self.progress_bar.move(0, 40)
        self.progress_bar.setProperty("value", 100)

        self.worker = ProgressThread()
        self.worker.progress_changed.connect(self.update_progress_bar)

        self.tab.show()

    def on_click(self):
        self.worker.start()
        self.execute_procedure()

    def execute_procedure(self):
        # while this procedure is running, the progress bar is not updating
        cnt = 0
        while cnt <= 5:
            cnt += 1
            time.sleep(1)

    def update_progress_bar(self, value):
        self.progress_bar.setValue(value)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = TestProgress()
    sys.exit(app.exec_())
</code>```

答:
You cannot and should not execute a blocking task in the main thread since it prevents the GUI from executing its task correctly.

There are 2 options depending on the use of time.sleep:

If the task of time.sleep() is just to give a delay T seconds  then use a QTimer.

```<code># ...
class TestProgress(QtWidgets.QDialog):
    # ...
    def execute_procedure(self):
        self.counter = 0
        QtCore.QTimer.singleShot(1000, self.execute_counter)

    def execute_counter(self):
        if self.counter <= 5:
            self.counter += 1
            QtCore.QTimer.singleShot(1000, self.execute_counter)
    # ...
</code>```

If in case time.sleep() emulates a task that consumes T seconds then execute it in another thread.

import threading
# ...
class TestProgress(QtWidgets.QDialog):
    # ...
    def on_click(self):
        self.worker.start()
        threading.Thread(target=self.execute_procedure, daemon=True).start()
    # ...
```

Body:
I want to be able to show the progress of a procedure while it is running.  My problem is that the QProgressBar seems to be frozen while the procedure is running.  Below is an example that shows that while execute_procedure is running (first 5 seconds), the progress_bar doesn't visually update even though the thread is emitting.

from PyQt5 import QtWidgets, QtCore
import sys
import time

class ProgressThread(QtCore.QThread):
    progress_changed = QtCore.pyqtSignal(int)

    def __init__(self):
        super().__init__()

    def run(self):
        completed = 0
        max_time = 15

        increment = float(100 / max_time)
        while completed < 100:
            completed += increment
            time.sleep(1)
            self.progress_changed.emit(completed)
            # print('emitted ', completed) -- this is emitting while
            # execute_procedure is running but the progress bar
            # is not visually updating until the procedure is completed

class TestProgress(QtWidgets.QDialog):
    def __init__(self):
        super().__init__()

        self.tab = QtWidgets.QWidget()
        self.tab.setGeometry(300, 300, 1000, 200)

        self.button_execute = QtWidgets.QPushButton("Execute", self.tab)
        self.button_execute.clicked.connect(self.on_click)

        self.progress_bar = QtWidgets.QProgressBar(self.tab)
        self.progress_bar.move(0, 40)
        self.progress_bar.setProperty("value", 100)

        self.worker = ProgressThread()
        self.worker.progress_changed.connect(self.update_progress_bar)

        self.tab.show()

    def on_click(self):
        self.worker.start()
        self.execute_procedure()

    def execute_procedure(self):
        # while this procedure is running, the progress bar is not updating
        cnt = 0
        while cnt <= 5:
            cnt += 1
            time.sleep(1)

    def update_progress_bar(self, value):
        self.progress_bar.setValue(value)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = TestProgress()
    sys.exit(app.exec_())

Body:
You cannot and should not execute a blocking task in the main thread since it prevents the GUI from executing its task correctly.

There are 2 options depending on the use of time.sleep:

If the task of time.sleep() is just to give a delay T seconds  then use a QTimer.

# ...
class TestProgress(QtWidgets.QDialog):
    # ...
    def execute_procedure(self):
        self.counter = 0
        QtCore.QTimer.singleShot(1000, self.execute_counter)

    def execute_counter(self):
        if self.counter <= 5:
            self.counter += 1
            QtCore.QTimer.singleShot(1000, self.execute_counter)
    # ...

If in case time.sleep() emulates a task that consumes T seconds then execute it in another thread.

import threading
# ...
class TestProgress(QtWidgets.QDialog):
    # ...
    def on_click(self):
        self.worker.start()
        threading.Thread(target=self.execute_procedure, daemon=True).start()
    # ...


来源: stackexchange

问:
Input shape for 1D convolution network in keras
I am quite new to keras and I have a problem in understanding shapes.

I wanted to create 1D Conv Keras model as follows, I don't know this is correct or not:

```<code>TIME_PERIODS = 511
num_sensors = 2
num_classes = 4
BATCH_SIZE = 400
EPOCHS = 50
model_m = Sequential()
model_m.add(Conv1D(100, 10, activation='relu', input_shape=(TIME_PERIODS, num_sensors)))
model_m.add(Conv1D(100, 10, activation='relu'))
model_m.add(MaxPooling1D(3))
model_m.add(Conv1D(160, 10, activation='relu'))
model_m.add(Conv1D(160, 10, activation='relu'))
model_m.add(GlobalAveragePooling1D())
model_m.add(Dropout(0.5))
model_m.add(Dense(num_classes, activation='softmax'))
</code>```

The input data I have is 888 different panda data frame where each frame is of shape (511, 3) where 511 is numbers of signal points and 0th column is sensor1 values, 1st column is sensor2 values and 2nd column is labelled signals.

Now how I should combine all my 888 different panda data frame so I have x_train and y_train from X and Y using  Sklearn train_test_split.

Also, I think the input shape I am defining for the model is wrong and I don't think I actually have TIME_PERIODS because, for 1-time point, I have 2 sensor inputs (orange, blue line) value and 1 output label (green line).

The context of the problem I am trying to solve e.g.
 input: time-based 2 sensors values say for 1 AM-2 AM hour from a user, output: the range of times e.g where the user was doing activity 1, activity 2, activity X on 1:10-1:15, 1:15-1:30, 1:30-2:00, The above plot show a sample training input and output.

The problem is inspired from here but in my case, I don't have any time period, my 1-time point has 1 output label.

Update 1:
I am almost certain that my TIME_PERIODS=1 as for the prediction I will give 511 inputs and expects to get 511 output values.

答:
To say the least, you're in the correct path. The full solution for this would be like,

```<code>df = pd.concat([pd.read_csv(fname, index_col=<int>, header=<int>) for f filenames], ignore_index=True, axis=0)

inputs = df.loc[:,:-1]
labels = df.loc[:,0]

X_train, X_test, y_train, y_test = train_test_split(inputs, labels, test_size=<float>)
</code>```

To add a bit more information, note how you are doing,

```<code>model_m.add(Conv1D(100, 10, activation='relu', input_shape=(TIME_PERIODS, num_sensors)))
</code>```

and not

```<code>model_m.add(Conv1D(100, 10, activation='relu', padding='SAME', input_shape=(TIME_PERIODS, num_sensors)))
</code>```

So, as you're not setting padding="Same" for the convolution layers this might have the undesirable effect of input becoming smaller and smaller as you go deeper to the model. If that's what you need, that's okay. Otherwise, set `padding="SAME".

For example, without same-padding you'll get, a width around 144 when you get to the GlobalPooling layer, where if you use same-padding it would be roughly 170. It's not a major problem here, but can easily lead to negative sizes in your input for deeper layers.

ContentLicense: CC BY-SA 4.0

Body:
I am quite new to keras and I have a problem in understanding shapes.

I wanted to create 1D Conv Keras model as follows, I don't know this is correct or not:

TIME_PERIODS = 511
num_sensors = 2
num_classes = 4
BATCH_SIZE = 400
EPOCHS = 50
model_m = Sequential()
model_m.add(Conv1D(100, 10, activation='relu', input_shape=(TIME_PERIODS, num_sensors)))
model_m.add(Conv1D(100, 10, activation='relu'))
model_m.add(MaxPooling1D(3))
model_m.add(Conv1D(160, 10, activation='relu'))
model_m.add(Conv1D(160, 10, activation='relu'))
model_m.add(GlobalAveragePooling1D())
model_m.add(Dropout(0.5))
model_m.add(Dense(num_classes, activation='softmax'))

The input data I have is 888 different panda data frame where each frame is of shape (511, 3) where 511 is numbers of signal points and 0th column is sensor1 values, 1st column is sensor2 values and 2nd column is labelled signals.

Now how I should combine all my 888 different panda data frame so I have x_train and y_train from X and Y using  Sklearn train_test_split.

Also, I think the input shape I am defining for the model is wrong and I don't think I actually have TIME_PERIODS because, for 1-time point, I have 2 sensor inputs (orange, blue line) value and 1 output label (green line).

The context of the problem I am trying to solve e.g.
 input: time-based 2 sensors values say for 1 AM-2 AM hour from a user, output: the range of times e.g where the user was doing activity 1, activity 2, activity X on 1:10-1:15, 1:15-1:30, 1:30-2:00, The above plot show a sample training input and output.

The problem is inspired from here but in my case, I don't have any time period, my 1-time point has 1 output label.

Update 1:
I am almost certain that my TIME_PERIODS=1 as for the prediction I will give 511 inputs and expects to get 511 output values.

Body:
To say the least, you're in the correct path. The full solution for this would be like,

df = pd.concat([pd.read_csv(fname, index_col=<int>, header=<int>) for f filenames], ignore_index=True, axis=0)

inputs = df.loc[:,:-1]
labels = df.loc[:,0]

X_train, X_test, y_train, y_test = train_test_split(inputs, labels, test_size=<float>)

To add a bit more information, note how you are doing,

model_m.add(Conv1D(100, 10, activation='relu', input_shape=(TIME_PERIODS, num_sensors)))

and not

model_m.add(Conv1D(100, 10, activation='relu', padding='SAME', input_shape=(TIME_PERIODS, num_sensors)))

So, as you're not setting padding="Same" for the convolution layers this might have the undesirable effect of input becoming smaller and smaller as you go deeper to the model. If that's what you need, that's okay. Otherwise, set `padding="SAME".

For example, without same-padding you'll get, a width around 144 when you get to the GlobalPooling layer, where if you use same-padding it would be roughly 170. It's not a major problem here, but can easily lead to negative sizes in your input for deeper layers.


问:
Flutter cached image is it possible to reload image instead of getting the cached image?
I'm using the package flutter_cached_network_image to load images from firebase. When a user updates his profile picture (filename is still the same) the image that is loaded is still the same as the one before the update because it is loaded from cache (because it still has the same url as before).
Is it possible to clear the picture from the cache so the new image is loaded?</p>

答:
Apparently there is no solution at the moment. See here: https://github.com/Baseflow/flutter_cached_network_image/issues/77

I use the version of the image in the address to get around this. Something like: https://example.com/image.jpg?version=14


问:
ruby version is latest but still getting error while installing rack and passenger, How to fix this?
On centos-7</p>

```<code>sudo gem install rack passenger

[root@puppetmaster bin]# sudo gem install rack passenger
ERROR:  Error installing rack:
        rack requires Ruby version >= 2.3.0.
ERROR:  Error installing passenger:
        rake requires Ruby version >= 2.2.

[root@puppetmaster bin]# yum update ruby
Loaded plugins: fastestmirror
Setting up Update Process
Loading mirror speeds from cached hostfile
 * base: mirror.atlanticmetro.net
 * extras: mirror.atlanticmetro.net
 * updates: mirror.atlanticmetro.net
No Packages marked for Update

[root@puppetmaster bin]# yum upgrade ruby
Loaded plugins: fastestmirror
Setting up Upgrade Process
Loading mirror speeds from cached hostfile
 * base: mirror.atlanticmetro.net
 * extras: mirror.atlanticmetro.net
 * updates: mirror.atlanticmetro.net
No Packages marked for Update

[root@puppetmaster bin]# ruby --version
ruby 1.8.7 (2013-06-27 patchlevel 374) [x86_64-linux]

[root@puppetmaster bin]# yum install ruby
Loaded plugins: fastestmirror
Setting up Install Process
Loading mirror speeds from cached hostfile
 * base: mirror.cc.columbia.edu
 * extras: mirror.cc.columbia.edu
 * updates: mirror.cc.columbia.edu
Package ruby-1.8.7.374-5.el6.x86_64 already installed and latest version
Nothing to do
</code>```

答:
I'd use rbenv for managing ruby

First install dependencies for rbenv and Ruby

```<code>   $ sudo yum install -y git-core zlib zlib-devel gcc-c++ patch readline readline-devel libyaml-devel libffi-devel openssl-devel make bzip2 autoconf automake libtool bison curl sqlite-devel
</code>```

After install rbenv

```<code>    cd ~
    git clone git://github.com/sstephenson/rbenv.git .rbenv
    echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
    echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
    git clone git://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
    echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bash_profile
    source ~/.bash_profile
</code>```

Pick updated ruby version to use

```<code>rbenv install -l
</code>```

Install ruby version

```<code>rbenv install -v $RUBY_VERSION
rbenv rehash
</code>```

Set for global use

```<code>rbenv global $RUBY_VERSION
</code>```

reference for full instructions
Install Ruby on Rails with Rbenv on CentOS 7

Body:
On centos-7

sudo gem install rack passenger

[root@puppetmaster bin]# sudo gem install rack passenger
ERROR:  Error installing rack:
        rack requires Ruby version >= 2.3.0.
ERROR:  Error installing passenger:
        rake requires Ruby version >= 2.2.

[root@puppetmaster bin]# yum update ruby
Loaded plugins: fastestmirror
Setting up Update Process
Loading mirror speeds from cached hostfile
 * base: mirror.atlanticmetro.net
 * extras: mirror.atlanticmetro.net
 * updates: mirror.atlanticmetro.net
No Packages marked for Update

[root@puppetmaster bin]# yum upgrade ruby
Loaded plugins: fastestmirror
Setting up Upgrade Process
Loading mirror speeds from cached hostfile
 * base: mirror.atlanticmetro.net
 * extras: mirror.atlanticmetro.net
 * updates: mirror.atlanticmetro.net
No Packages marked for Update

[root@puppetmaster bin]# ruby --version
ruby 1.8.7 (2013-06-27 patchlevel 374) [x86_64-linux]

[root@puppetmaster bin]# yum install ruby
Loaded plugins: fastestmirror
Setting up Install Process
Loading mirror speeds from cached hostfile
 * base: mirror.cc.columbia.edu
 * extras: mirror.cc.columbia.edu
 * updates: mirror.cc.columbia.edu
Package ruby-1.8.7.374-5.el6.x86_64 already installed and latest version
Nothing to do

Body:
I'd use rbenv for managing ruby

First install dependencies for rbenv and Ruby

   $ sudo yum install -y git-core zlib zlib-devel gcc-c++ patch readline readline-devel libyaml-devel libffi-devel openssl-devel make bzip2 autoconf automake libtool bison curl sqlite-devel

After install rbenv

    cd ~
    git clone git://github.com/sstephenson/rbenv.git .rbenv
    echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
    echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
    git clone git://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
    echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bash_profile
    source ~/.bash_profile

Pick updated ruby version to use

rbenv install -l

Install ruby version

rbenv install -v $RUBY_VERSION
rbenv rehash

Set for global use

rbenv global $RUBY_VERSION

reference for full instructions
Install Ruby on Rails with Rbenv on CentOS 7


问:
How can I insert element in Recycler View?
I have a problem with RecyclerView.
Every time I try to manage a Rec View for insert or delete or update some element I have to fight with Recycler View and the evil notifyDataSetChange.

I tried with runOnUiThread and everytime this solution is useless.
I tried to call notifyDataSetChange in the Adapter or in the Activity that instance the Rec View.

I really need to know how to make this work everytime to be a little better developer.
I really hope to solve this problem definitely.

This is my new try

```<code>
public class MainActivity extends AppCompatActivity {

    private Button nextTurn;
    private Button submit;
    private EditText name;
    private EditText number;

    private CounterElementAdapter mAdapter;
    private RecyclerView recV;
    private List<CounterElement> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nextTurn = (Button) findViewById(R.id.button2);
        submit = (Button) findViewById(R.id.button);
        name = (EditText) findViewById(R.id.editText);
        number = (EditText) findViewById(R.id.editText2);
        recV = (RecyclerView) findViewById(R.id.recV);

        list = new ArrayList<CounterElement>();

        mAdapter = new CounterElementAdapter(list);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recV.setLayoutManager(mLayoutManager);
        recV.setItemAnimator(new DefaultItemAnimator());
        recV.setAdapter(mAdapter);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(name.getText().toString().length() > 0 && number.getText().toString().length() > 0) {
                    mAdapter.addElement(new CounterElement(name.getText().toString(), Integer.parseInt(number.getText().toString())));
                }
            }
        });

        nextTurn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAdapter.nextTurn();
            }
        });
    }
}

</code>```

```<code>public class CounterElementAdapter extends RecyclerView.Adapter<CounterElementAdapter.MyViewHolder> {

    private List<CounterElement> elementList;

    public class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView name, counter;

        public MyViewHolder(View view) {
            super(view);
            name = view.findViewById(R.id.name);
            counter = view.findViewById(R.id.counter);
        }
    }

    public CounterElementAdapter(List<CounterElement> elementList) {
        this.elementList = elementList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.element, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        CounterElement ce = elementList.get(position);
        holder.name.setText(ce.getName());
        holder.counter.setText(ce.getDuration());
    }

    @Override
    public int getItemCount() {
        return elementList.size();
    }

    public void addElement(CounterElement ce){
        elementList.add(ce);
        notifyDataSetChanged();
    }

    public void nextTurn(){
        for(CounterElement ce : elementList){
            if(ce.getStatus() >= 1)
                ce.setStatus(ce.getStatus() - 1);
            else {
                elementList.remove(elementList.indexOf(ce));
                notifyDataSetChanged();
            }
        }
    }
}
</code>```

Thanks in advance

答:
Your code looks fine. I would recommend you to take a look at this article
Also try to debug your code and check if your elementList updates correctly.

Body:
I have a problem with RecyclerView.
Every time I try to manage a Rec View for insert or delete or update some element I have to fight with Recycler View and the evil notifyDataSetChange.

I tried with runOnUiThread and everytime this solution is useless.
I tried to call notifyDataSetChange in the Adapter or in the Activity that instance the Rec View.

I really need to know how to make this work everytime to be a little better developer.
I really hope to solve this problem definitely.

This is my new try

public class MainActivity extends AppCompatActivity {

    private Button nextTurn;
    private Button submit;
    private EditText name;
    private EditText number;

    private CounterElementAdapter mAdapter;
    private RecyclerView recV;
    private List<CounterElement> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nextTurn = (Button) findViewById(R.id.button2);
        submit = (Button) findViewById(R.id.button);
        name = (EditText) findViewById(R.id.editText);
        number = (EditText) findViewById(R.id.editText2);
        recV = (RecyclerView) findViewById(R.id.recV);

        list = new ArrayList<CounterElement>();

        mAdapter = new CounterElementAdapter(list);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recV.setLayoutManager(mLayoutManager);
        recV.setItemAnimator(new DefaultItemAnimator());
        recV.setAdapter(mAdapter);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(name.getText().toString().length() > 0 && number.getText().toString().length() > 0) {
                    mAdapter.addElement(new CounterElement(name.getText().toString(), Integer.parseInt(number.getText().toString())));
                }
            }
        });

        nextTurn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAdapter.nextTurn();
            }
        });
    }
}

public class CounterElementAdapter extends RecyclerView.Adapter<CounterElementAdapter.MyViewHolder> {

    private List<CounterElement> elementList;

    public class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView name, counter;

        public MyViewHolder(View view) {
            super(view);
            name = view.findViewById(R.id.name);
            counter = view.findViewById(R.id.counter);
        }
    }

    public CounterElementAdapter(List<CounterElement> elementList) {
        this.elementList = elementList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.element, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        CounterElement ce = elementList.get(position);
        holder.name.setText(ce.getName());
        holder.counter.setText(ce.getDuration());
    }

    @Override
    public int getItemCount() {
        return elementList.size();
    }

    public void addElement(CounterElement ce){
        elementList.add(ce);
        notifyDataSetChanged();
    }

    public void nextTurn(){
        for(CounterElement ce : elementList){
            if(ce.getStatus() >= 1)
                ce.setStatus(ce.getStatus() - 1);
            else {
                elementList.remove(elementList.indexOf(ce));
                notifyDataSetChanged();
            }
        }
    }
}

Thanks in advance


问:
How to use --wait with post-install hook in helm?
I use an install script in a post-install hook.
When I run helm install with --wait option, helm waits that all pods are ready, but helm does not launch post-install hooks script.
Then, the pods are not yet ready (pods are waiting for install script to finish).

I tried with pre-install hook instead, but the install script needs other services to be running...

PS: it works fine if I don't use "--wait", but CI from gitlab won't fail if there is an error during pod startups.

Is there a way to run the post-install hooks during the helm install --wait period?

答:
I don't think you can solve your problem with Helm post-install hook, but you may with vanilla Kubernetes jobs or perhaps hooks, i.e. running job/hook along with your deployment that will depend only on Kubernetes.

One of the first things to try is to remove helm.sh/hook annotations from your existing job.

```<code>  annotations:
    # This is what defines this resource as a hook. Without this line, the
    # job is considered part of the release.
    "helm.sh/hook": post-install
    "helm.sh/hook-weight": "-5"
    "helm.sh/hook-delete-policy": hook-succeeded
</code>```

Helm can then wait for them to finish as they will be executed by Kubernetes.

Body:
I don't think you can solve your problem with Helm post-install hook, but you may with vanilla Kubernetes jobs or perhaps hooks, i.e. running job/hook along with your deployment that will depend only on Kubernetes.

One of the first things to try is to remove helm.sh/hook annotations from your existing job.

  annotations:
    # This is what defines this resource as a hook. Without this line, the
    # job is considered part of the release.
    "helm.sh/hook": post-install
    "helm.sh/hook-weight": "-5"
    "helm.sh/hook-delete-policy": hook-succeeded

Helm can then wait for them to finish as they will be executed by Kubernetes.


问:
TypeScript convert generic object from snake to camel case
I would like to write a function that accepts an object with snake case keys and converts it to an object with camel case keys. What is the best way such a function could be typed in TypeScript, assuming we know the type of the input object, but want the solution to be generic.

```<code>type InputType = {
  snake_case_key_1: number,
  snake_case_key_2: string,
  ...
}

function snakeToCamelCase(object: T): U {
  ...
}
</code>```

What is the best job that could be done to type T and U.

I would like U to be as narrowly typed as possible, and the type of U to be based on T ideally.

Ideally, if T is my example InputType I would like U to be typed as

```<code>{
  snakeCaseKey1: number,
  snakeCaseKey2: string,
  ...
}
</code>```

答: Unfortunately, something like this is not possible. Typescript in its current form does not support type keys transformation/mapping.</p>

Body:
I would like to write a function that accepts an object with snake case keys and converts it to an object with camel case keys. What is the best way such a function could be typed in TypeScript, assuming we know the type of the input object, but want the solution to be generic.

type InputType = {
  snake_case_key_1: number,
  snake_case_key_2: string,
  ...
}

function snakeToCamelCase(object: T): U {
  ...
}

What is the best job that could be done to type T and U.

I would like U to be as narrowly typed as possible, and the type of U to be based on T ideally.

Ideally, if T is my example InputType I would like U to be typed as

{
  snakeCaseKey1: number,
  snakeCaseKey2: string,
  ...
}


问:
How can I use Jq to help me make "individual" json files with specific values?
I want to use jq to help me make a file for every key, with the 3 specific values pertaining to that key, formatted in json.

I know how to get my keys, and I know how to get my values. But how can I do all this in one command so that I have the info I want, in different files, per key with the keys respective values?

Here is how I get keys:

cat $DCAR_API | jq .vendors[].products[].images | jq -r 'keys[]'

Here is the info I want to be in every json file:

```<code>cat "$DCAR_API" \
| jq -r '.vendors[]|.products[]|.images[].tags[].pgpSignature'

cat "$DCAR_API" \
| jq -r '.vendors[]|.products[]|.images[].tags[].imageManifest'

cat "$DCAR_API" \
| jq -r '.vendors[]|.products[]|.images[].tags[].image'
</code>```

答:
Since you haven't provided sample data, I've had to make my own:

```<code>json='
{ "vendors":
  { "vendorA":
    { "products":
      { "productA":
        { "images":
          { "imageA":
            { "tags":
              { "2019-01-01":
                { "pgpSignature":  "productA-imageA-20190101-sig",
                  "imageManifest": "productA-imageA-20190101-manifest",
                  "image":         "productA-imageA-20190101-image"
                }
              }
            }
          }
        }
      }
    }
  }
}
'

buildJsonStream() {
  jq -j '
    .vendors[]|.products[]|.images | to_entries[] |
    .key as $key |
    .value.tags[] |
    ($key, "\u0000",
     ({ pgpSignature, imageManifest, image } | tojson), "\n", "\u0000"
    )' "$@"
}

declare -A alreadyCreated=( )
while IFS= read -r -d '' key && IFS= read -r -d '' content; do
  if ! [[ ${alreadyCreated[$key]} ]]; then
    printf '%s' "$content" >"$key.json"
    alreadyCreated[$key]=1
  else
    printf '%s' "$content" >>"$key.json"
  fi
done < <(buildJsonStream <<<"$json")
</code>```

...will write, to imageA.json, the text:

```<code>{"pgpSignature":"productA-imageA-20190101-sig","imageManifest":"productA-imageA-20190101-manifest","image":"productA-imageA-20190101-image"}
</code>```

The important thing to note here is that we're having jq write alternating, NUL-separated key/content pairs, and then having bash be responsible for actually writing to the (key-name-derived) files.

Body:
I want to use jq to help me make a file for every key, with the 3 specific values pertaining to that key, formatted in json.

I know how to get my keys, and I know how to get my values. But how can I do all this in one command so that I have the info I want, in different files, per key with the keys respective values?

Here is how I get keys:

cat $DCAR_API | jq .vendors[].products[].images | jq -r 'keys[]'

Here is the info I want to be in every json file:

cat "$DCAR_API" \
| jq -r '.vendors[]|.products[]|.images[].tags[].pgpSignature'

cat "$DCAR_API" \
| jq -r '.vendors[]|.products[]|.images[].tags[].imageManifest'

cat "$DCAR_API" \
| jq -r '.vendors[]|.products[]|.images[].tags[].image'

Body:
Since you haven't provided sample data, I've had to make my own:

json='
{ "vendors":
  { "vendorA":
    { "products":
      { "productA":
        { "images":
          { "imageA":
            { "tags":
              { "2019-01-01":
                { "pgpSignature":  "productA-imageA-20190101-sig",
                  "imageManifest": "productA-imageA-20190101-manifest",
                  "image":         "productA-imageA-20190101-image"
                }
              }
            }
          }
        }
      }
    }
  }
}
'

buildJsonStream() {
  jq -j '
    .vendors[]|.products[]|.images | to_entries[] |
    .key as $key |
    .value.tags[] |
    ($key, "\u0000",
     ({ pgpSignature, imageManifest, image } | tojson), "\n", "\u0000"
    )' "$@"
}

declare -A alreadyCreated=( )
while IFS= read -r -d '' key && IFS= read -r -d '' content; do
  if ! [[ ${alreadyCreated[$key]} ]]; then
    printf '%s' "$content" >"$key.json"
    alreadyCreated[$key]=1
  else
    printf '%s' "$content" >>"$key.json"
  fi
done < <(buildJsonStream <<<"$json")

...will write, to imageA.json, the text:

{"pgpSignature":"productA-imageA-20190101-sig","imageManifest":"productA-imageA-20190101-manifest","image":"productA-imageA-20190101-image"}

The important thing to note here is that we're having jq write alternating, NUL-separated key/content pairs, and then having bash be responsible for actually writing to the (key-name-derived) files.


问:
I need help making a java constructor that akes a string and initilizes the value var with appropriate in
so sorry if my question is dumb but i haven't done java in 2 years. I'm working in my hw right now and i'm one method away from being done. but one of my constructor is wrong and idk where. thanks in advance!
the value variable is a private integer.
so far i have:

```<code>public  FancyInt(String a) {
       value = "";

       a = this.value;
}
</code>```

basically this constructor takes a string and initalizes the value to the appropriate int

答:
Firstly if you want to equal "value" TO "a", you must write:

```<code>this.value = a;
</code>```

in Java (and a lot of programming languages), you must write variable that you change before equal mark.

Second, if you will make "value" Integer. You must change it to int first:

```<code>try {
   this.value = Integer.parseInt(a);
} catch (NumberFormatException e) {
    e.printStackTrace();
}
</code>```

Third, if "value" is an Integer. You must define that with numbers:

```<code>value = ""; //if value is an Integer, delete this line.
</code>```

Body:
so sorry if my question is dumb but i haven't done java in 2 years. I'm working in my hw right now and i'm one method away from being done. but one of my constructor is wrong and idk where. thanks in advance!
the value variable is a private integer.
so far i have:

public  FancyInt(String a) {
       value = "";

       a = this.value;
}

basically this constructor takes a string and initalizes the value to the appropriate int

Body:
Firstly if you want to equal "value" TO "a", you must write:

this.value = a;

in Java (and a lot of programming languages), you must write variable that you change before equal mark.

Second, if you will make "value" Integer. You must change it to int first:

try {
   this.value = Integer.parseInt(a);
} catch (NumberFormatException e) {
    e.printStackTrace();
}

Third, if "value" is an Integer. You must define that with numbers:

value = ""; //if value is an Integer, delete this line.


问:
Static field initialization order (C#) - can someone explain this snippet?
I am a C++ programmer learning C#. I am currently reading C#4.0 in a Nutshell.

I have come accross this statement/snipet on page 74:

Static field initializers run in the
  order in which the fields are
  declared. The following example
  illustrates this: X is initialized to
  0 and Y is initialized to 3.

```<code>class Foo
{
    public static int X = Y; // 0
    public static int Y = 3; // 3
}
</code>```

I dont understand how X can be assigned the value in Y, without Y being first declared. Am I missing something here?

As an aside, coming from a C++ background, I tend to use the term ctor for constructor - however, I haven't yet come accross the term in C# - is the term ctor also used in the C# world?

[Edit]

A further example on the same page (in the book mentioned earlier) is this:

```<code>class Program
{
    static void Main() { Console.WriteLine (Foo.X); } // 3
}
class Foo
{
    public static Foo Instance = new Foo();
    public static int X = 3;
    Foo() { Console.WriteLine (X); } // 0
}
</code>```

The book states (for the example above):

The example prints 0 followed by 3
  because the field initializer that
  instantiates a Foo executes before X
  is initialized to 3:

I have some further questions w.r.t the examples.

Both examples appear under the section entitled Static constructors and field initialization order however, the code examples dont show a static ctor - atleast, not one that I can easily recognise. I was expecting a static ctor to have the same name as the class, be parameterless and be preceeded by the 'static' keyword. So I dont see how the examples relate to the section heading. What am I missing here?

In the second example, the (non static) ctor prints out the value of X - which had explicitly been assigned the value of 3 in the previous line - and yet, the output printed out is 0. Why?!

答:
if you create a class such as :

```<code>   class Foo
    {
        public static int y1 = 3;
        public static int x1 = y1;

        public static int X = Y; // 0
        public static int Y = 3; // 3

    }
</code>```

and disassemble it you will see

```<code>        public static int y1 = 3;
00000021  mov         dword ptr ds:[009E9360h],3
        public static int x1 = y1;
0000002b  mov         eax,dword ptr ds:[009E9360h]
00000030  mov         dword ptr ds:[009E9364h],eax

        public static int X = Y; // 0
00000035  mov         eax,dword ptr ds:[009E936Ch]
0000003a  mov         dword ptr ds:[009E9368h],eax
        public static int Y = 3; // 3
0000003f  mov         dword ptr ds:[009E936Ch],3
</code>```

Y has not been initialized and its default value is 0.

ContentLicense: CC BY-SA 3.0

Body:
I am a C++ programmer learning C#. I am currently reading C#4.0 in a Nutshell.

I have come accross this statement/snipet on page 74:

Static field initializers run in the
  order in which the fields are
  declared. The following example
  illustrates this: X is initialized to
  0 and Y is initialized to 3.

class Foo
{
    public static int X = Y; // 0
    public static int Y = 3; // 3
}

I dont understand how X can be assigned the value in Y, without Y being first declared. Am I missing something here?

As an aside, coming from a C++ background, I tend to use the term ctor for constructor - however, I haven't yet come accross the term in C# - is the term ctor also used in the C# world?

[Edit]

A further example on the same page (in the book mentioned earlier) is this:

class Program
{
    static void Main() { Console.WriteLine (Foo.X); } // 3
}
class Foo
{
    public static Foo Instance = new Foo();
    public static int X = 3;
    Foo() { Console.WriteLine (X); } // 0
}

The book states (for the example above):

The example prints 0 followed by 3
  because the field initializer that
  instantiates a Foo executes before X
  is initialized to 3:

I have some further questions w.r.t the examples.

Both examples appear under the section entitled Static constructors and field initialization order however, the code examples dont show a static ctor - atleast, not one that I can easily recognise. I was expecting a static ctor to have the same name as the class, be parameterless and be preceeded by the 'static' keyword. So I dont see how the examples relate to the section heading. What am I missing here?

In the second example, the (non static) ctor prints out the value of X - which had explicitly been assigned the value of 3 in the previous line - and yet, the output printed out is 0. Why?!

Body:
if you create a class such as :

   class Foo
    {
        public static int y1 = 3;
        public static int x1 = y1;

        public static int X = Y; // 0
        public static int Y = 3; // 3

    }

and disassemble it you will see

        public static int y1 = 3;
00000021  mov         dword ptr ds:[009E9360h],3
        public static int x1 = y1;
0000002b  mov         eax,dword ptr ds:[009E9360h]
00000030  mov         dword ptr ds:[009E9364h],eax

        public static int X = Y; // 0
00000035  mov         eax,dword ptr ds:[009E936Ch]
0000003a  mov         dword ptr ds:[009E9368h],eax
        public static int Y = 3; // 3
0000003f  mov         dword ptr ds:[009E936Ch],3

Y has not been initialized and its default value is 0.


问:
Create worksheets based on multiple filters
I found and am using the following code and works great for what it is intended, but for my purpose i need to be able to provide more than just 1 filter before creating the sheets.

```<code>'https://access-excel.tips/excel-vba-filter-value-then-copy-data-to-new-worksheet/

Public Sub FilterThenCopy()
   Dim ws, newWS, currentWS As Worksheet
   targetCol = 1   'define which column you want to break
   Dim objDict As Variant
   Set objDict = CreateObject("Scripting.Dictionary")
   Set currentWS = ActiveSheet
   'Add unique value in targetCol to the dictionary
   Application.DisplayAlerts = False
   For r = 2 To Cells(Rows.Count, targetCol).End(xlUp).Row
     If Not objDict.exists(Cells(r, targetCol).Value) Then
       objDict.Add Cells(r, targetCol).Value, Cells(r, targetCol).Value
     End If
   Next r

  If currentWS.AutoFilterMode = True Then
     currentWS.UsedRange.AutoFilter
  End If
  currentWS.UsedRange.AutoFilter
  For Each k In objDict.Keys
    currentWS.UsedRange.AutoFilter Field:=1, Criteria1:=objDict.Item(k)
   'delete worksheet if worksheet of item(k) exist
    For Each ws In ActiveWorkbook.Worksheets
      If wsExists(objDict.Item(k)) Then
        Sheets(objDict.Item(k)).Delete
      End If
    Next ws
   'crate worksheet using item(k) name
    Set newWS = ThisWorkbook.Worksheets.Add(After:=Worksheets(Worksheets.Count))
    newWS.Name = objDict.Item(k)
    'copy filtered contents to new worksheet
    currentWS.Cells.Copy
    newWS.Range("A1").Select
    Sheets(objDict.Item(k)).Paste
  Next k
  currentWS.Activate
  currentWS.AutoFilterMode = False
  Application.DisplayAlerts = True
End Sub

Function wsExists(wksName As String) As Boolean
   On Error Resume Next
   wsExists = CBool(Len(Worksheets(wksName).Name) > 0)
   On Error GoTo 0
End Function
</code>```

If i record a macro to set multiple filters, this is what is recorded

```<code>    ActiveSheet.Range("$A$1:$C$13").AutoFilter Field:=1, Criteria1:="Daniel"
    ActiveSheet.Range("$A$1:$C$13").AutoFilter Field:=3, Criteria1:="0078"
    ActiveSheet.Range("$A$1:$C$13").AutoFilter Field:=5, Criteria1:="661"
    ActiveSheet.Range("$A$1:$C$13").AutoFilter Field:=6, Criteria1:="0007"
</code>```

Im trying to figure out how i can make this work. The first 3 criterias needs to be dynamic as it is now and produce a sheet for each unique value combindation. But the 3 will need to be either dynamic as well(95% sure it needs to be) or a way that it can be provided at execution time. Because of the way they work, may need to be able to provide a way to allow the user to select how they want the sheets created based on the fields they pick, if not then default would be to created based on the 3 criteria.

Can anyone point me in the right direction with this ask..

Here is the test data im working with and the expected tabs based on unique combination of Dept, Class and Sub

答: You could use another dictionary like objDict with values from column B and then loop over both dicts to make the filters. The worksheet names could be a concatenation of the values from both dicts e.g "Daniel-0078" or "Daniel-0079" so you can compare and delete them if necessary. You could also use this reasoning to make the twelve tabs you wanted (using four different dictionaries) but also consider that the maximum length for worksheet names is 30.

Body:
I found and am using the following code and works great for what it is intended, but for my purpose i need to be able to provide more than just 1 filter before creating the sheets.

'https://access-excel.tips/excel-vba-filter-value-then-copy-data-to-new-worksheet/

Public Sub FilterThenCopy()
   Dim ws, newWS, currentWS As Worksheet
   targetCol = 1   'define which column you want to break
   Dim objDict As Variant
   Set objDict = CreateObject("Scripting.Dictionary")
   Set currentWS = ActiveSheet
   'Add unique value in targetCol to the dictionary
   Application.DisplayAlerts = False
   For r = 2 To Cells(Rows.Count, targetCol).End(xlUp).Row
     If Not objDict.exists(Cells(r, targetCol).Value) Then
       objDict.Add Cells(r, targetCol).Value, Cells(r, targetCol).Value
     End If
   Next r

  If currentWS.AutoFilterMode = True Then
     currentWS.UsedRange.AutoFilter
  End If
  currentWS.UsedRange.AutoFilter
  For Each k In objDict.Keys
    currentWS.UsedRange.AutoFilter Field:=1, Criteria1:=objDict.Item(k)
   'delete worksheet if worksheet of item(k) exist
    For Each ws In ActiveWorkbook.Worksheets
      If wsExists(objDict.Item(k)) Then
        Sheets(objDict.Item(k)).Delete
      End If
    Next ws
   'crate worksheet using item(k) name
    Set newWS = ThisWorkbook.Worksheets.Add(After:=Worksheets(Worksheets.Count))
    newWS.Name = objDict.Item(k)
    'copy filtered contents to new worksheet
    currentWS.Cells.Copy
    newWS.Range("A1").Select
    Sheets(objDict.Item(k)).Paste
  Next k
  currentWS.Activate
  currentWS.AutoFilterMode = False
  Application.DisplayAlerts = True
End Sub

Function wsExists(wksName As String) As Boolean
   On Error Resume Next
   wsExists = CBool(Len(Worksheets(wksName).Name) > 0)
   On Error GoTo 0
End Function

If i record a macro to set multiple filters, this is what is recorded

    ActiveSheet.Range("$A$1:$C$13").AutoFilter Field:=1, Criteria1:="Daniel"
    ActiveSheet.Range("$A$1:$C$13").AutoFilter Field:=3, Criteria1:="0078"
    ActiveSheet.Range("$A$1:$C$13").AutoFilter Field:=5, Criteria1:="661"
    ActiveSheet.Range("$A$1:$C$13").AutoFilter Field:=6, Criteria1:="0007"

Im trying to figure out how i can make this work. The first 3 criterias needs to be dynamic as it is now and produce a sheet for each unique value combindation. But the 3 will need to be either dynamic as well(95% sure it needs to be) or a way that it can be provided at execution time. Because of the way they work, may need to be able to provide a way to allow the user to select how they want the sheets created based on the fields they pick, if not then default would be to created based on the 3 criteria.

Can anyone point me in the right direction with this ask..

Here is the test data im working with and the expected tabs based on unique combination of Dept, Class and Sub


问:
Unmet dependencies installing R 3.6.2 on Ubuntu 18.14 LTS
I use 18.04.4 LTS (Bionic Beaver)

I wanted to upgrade my R version from 3.4.4 to 3.6.2, but now I have no R at all.

here are my actions:

1 step:

```<code>sudo apt update
sudo apt-get upgrade
sudo apt-get dist-upgrade
</code>```

2 step:

```<code>sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
</code>```

3 step:

```<code>sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/'
</code>```

return:

```<code>Hit:1 http://ua.archive.ubuntu.com/ubuntu bionic InRelease
Hit:2 http://ua.archive.ubuntu.com/ubuntu bionic-updates InRelease
Hit:3 http://ua.archive.ubuntu.com/ubuntu bionic-backports InRelease
Hit:4 http://cran.rstudio.com/bin/linux/ubuntu bionic-cran35/ InRelease
Hit:5 http://ppa.launchpad.net/ondrej/php/ubuntu bionic InRelease
Hit:6 http://security.ubuntu.com/ubuntu bionic-security InRelease
Hit:7 https://cloud.r-project.org/bin/linux/ubuntu xenial-cran35/ InRelease
Hit:8 https://cloud.r-project.org/bin/linux/ubuntu disco-cran35/ InRelease
Hit:9 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ InRelease
Reading package lists... Done
</code>```

4 step:

```<code>sudo apt update
sudo apt install r-base
</code>```

return:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
  r-base : Depends: r-base-core (>= 3.6.2-1xenial) but it is not going to be installed
      Depends: r-recommended (= 3.6.2-1xenial) but it is not going to be installed
      Recommends: r-base-html but it is not going to be installed
 E: Unable to correct problems, you have held broken packages.
</code>```

then I try:

```<code>R --version
</code>```

return:

```<code>Command 'R' not found, but can be installed with:
sudo apt install r-base-core
</code>```

I try:

```<code> sudo apt install r-base-core

 The following packages have unmet dependencies:
  r-base-core : Depends: libreadline6 (>= 6.0) but it is not
  installable
           Recommends: r-recommended but it is not going to be
  installed
           Recommends: r-base-dev but it is not going to be
  installed
  E: Unable to correct problems, you have held broken packages.
</code>```

答:
You can try two things:

As you already appear to have installed, just to sudo apt-get dist-upgrade.  It will list candidate upgrades, you can still back out. Advantage: it resolved interdependent upgrades for you.

Continue what you did but list the affected packages, i.e. sudo apt-get install r-base r-recommended r-base-hmtml.  This will work, but may requires several iterative steps.

Body:
I use 18.04.4 LTS (Bionic Beaver)

I wanted to upgrade my R version from 3.4.4 to 3.6.2, but now I have no R at all.

here are my actions:

1 step:

sudo apt update
sudo apt-get upgrade
sudo apt-get dist-upgrade

2 step:

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9

3 step:

sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/'

return:

Hit:1 http://ua.archive.ubuntu.com/ubuntu bionic InRelease
Hit:2 http://ua.archive.ubuntu.com/ubuntu bionic-updates InRelease
Hit:3 http://ua.archive.ubuntu.com/ubuntu bionic-backports InRelease
Hit:4 http://cran.rstudio.com/bin/linux/ubuntu bionic-cran35/ InRelease
Hit:5 http://ppa.launchpad.net/ondrej/php/ubuntu bionic InRelease
Hit:6 http://security.ubuntu.com/ubuntu bionic-security InRelease
Hit:7 https://cloud.r-project.org/bin/linux/ubuntu xenial-cran35/ InRelease
Hit:8 https://cloud.r-project.org/bin/linux/ubuntu disco-cran35/ InRelease
Hit:9 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ InRelease
Reading package lists... Done

4 step:

sudo apt update
sudo apt install r-base

return:

Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
  r-base : Depends: r-base-core (>= 3.6.2-1xenial) but it is not going to be installed
      Depends: r-recommended (= 3.6.2-1xenial) but it is not going to be installed
      Recommends: r-base-html but it is not going to be installed
 E: Unable to correct problems, you have held broken packages.

then I try:

R --version

return:

Command 'R' not found, but can be installed with:
sudo apt install r-base-core

I try:

 sudo apt install r-base-core

 The following packages have unmet dependencies:
  r-base-core : Depends: libreadline6 (>= 6.0) but it is not
  installable
           Recommends: r-recommended but it is not going to be
  installed
           Recommends: r-base-dev but it is not going to be
  installed
  E: Unable to correct problems, you have held broken packages.


问:
DBD::mysql::st execute failed: Unknown column
When I do the query below from a mysql console it works fine but when I wrap into perl/DBI I get:

```<code>DBD::mysql::st execute failed: Unknown column 'AR_email' in 'field list'
</code>```

Here is the query:

```<code>my $q = "SELECT SUBSTRING(AR_email, LOCATE('@', AR_email) + 1) AS domain
         FROM carrier
         WHERE AR_email IS NOT NULL
         AND SUBSTRING(AR_email, LOCATE('@', AR_email) + 1) =?";
my $sth=$dbh->prepare($q);
$sth->execute($domain);
</code>```

Any idea how I can fix this?

答:
The problem here is unintented string interpolation.

You are using double quotes (") when assigning the query string to $q, but it contains an arobas (@), which is interpolated.

So $q actually ends up containing:

```<code>SELECT SUBSTRING(AR_email, LOCATE(', AR_email) + 1) AS domain
FROM carrier
WHERE AR_email IS NOT NULL
AND SUBSTRING(AR_email, LOCATE(', AR_email) + 1) =?
</code>```

If you were running this under use warnings, you would get this message:

```<code>Possible unintended interpolation of @' in string
</code>```

One way to solve this is to define the query as a litteral string, for example:

```<code>my $q = q/SELECT SUBSTRING(AR_email, LOCATE('@', AR_email) + 1) AS domain
         FROM carrier
         WHERE AR_email IS NOT NULL
         AND SUBSTRING(AR_email, LOCATE('@', AR_email) + 1) =?/;
</code>```

Moral of the story:

use double quotes only when you do want string interpolation

always use strict; use warnings;

Body:
When I do the query below from a mysql console it works fine but when I wrap into perl/DBI I get:

DBD::mysql::st execute failed: Unknown column 'AR_email' in 'field list'

Here is the query:

my $q = "SELECT SUBSTRING(AR_email, LOCATE('@', AR_email) + 1) AS domain
         FROM carrier
         WHERE AR_email IS NOT NULL
         AND SUBSTRING(AR_email, LOCATE('@', AR_email) + 1) =?";
my $sth=$dbh->prepare($q);
$sth->execute($domain);

Any idea how I can fix this?

Body:
The problem here is unintented string interpolation.

You are using double quotes (") when assigning the query string to $q, but it contains an arobas (@), which is interpolated.

So $q actually ends up containing:

SELECT SUBSTRING(AR_email, LOCATE(', AR_email) + 1) AS domain
FROM carrier
WHERE AR_email IS NOT NULL
AND SUBSTRING(AR_email, LOCATE(', AR_email) + 1) =?

If you were running this under use warnings, you would get this message:

Possible unintended interpolation of @' in string

One way to solve this is to define the query as a litteral string, for example:

my $q = q/SELECT SUBSTRING(AR_email, LOCATE('@', AR_email) + 1) AS domain
         FROM carrier
         WHERE AR_email IS NOT NULL
         AND SUBSTRING(AR_email, LOCATE('@', AR_email) + 1) =?/;

Moral of the story:

use double quotes only when you do want string interpolation

always use strict; use warnings;


问:
org.hibernate.exception.ConstraintViolationException: could not execute statement
I am getting the below error, when I try to add a app and app settings.
Here is the detailed error message:

```<code>org.hibernate.exception.ConstraintViolationException: could not
execute statement   at
org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:72)
    at
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
    at
org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at
org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
    at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
    at
org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:492)
    at
org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:197)
    at
org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:181)
    at
org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:216)
    at
org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:334)
    at
org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:289)
    at
org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:195)
    at
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
    at
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
    at
org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    at
org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)    at
org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)   at
com.ips.tvadmindao.services.TVAppService.addTVappsWithSettings(TVAppService.java:237)
    at TVAppserviseTest.testsSaveApps(TVAppserviseTest.java:46)     at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)     at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)     at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at
org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)    at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)  at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)     at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)   at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)     at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)    at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at
org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)    at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'company_id' cannot be null  at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:400)     at
com.mysql.jdbc.Util.getInstance(Util.java:383)  at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)   at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847)  at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783)  at
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447)   at
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594)    at
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)     at
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901)
    at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2113)
    at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2049)
    at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2034)
    at
com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:147)
    at
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    ... 50 more

2015-12-21 21:23:15 DEBUG SqlExceptionHelper:139 - could not execute
statement [n/a]
    com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'company_id' cannot be null
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:400)
        at com.mysql.jdbc.Util.getInstance(Util.java:383)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783)
        at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447)
        at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594)
        at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)
        at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901)
        at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2113)
        at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2049)
        at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2034)
        at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:147)
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
        at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
        at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
        at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
        at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:492)
        at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:197)
        at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:181)
        at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:216)
        at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:334)
        at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:289)
        at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:195)
        at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
        at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
        at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
        at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
        at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
        at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
        at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
        at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
        at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
        at com.ips.tvadmindao.services.TVAppService.addTVappsWithSettings(TVAppService.java:237)
        at TVAppserviseTest.testsSaveApps(TVAppserviseTest.java:46)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
        at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
    2015-12-21 21:23:15 WARN  SqlExceptionHelper:144 - SQL Error: 1048, SQLState: 23000
    2015-12-21 21:23:15 ERROR SqlExceptionHelper:146 - Column 'company_id' cannot be null
</code>```

Here is the junit test

```<code>@Test
    public void testsSaveApps() {
        List<AppSetting> settings = new ArrayList<AppSetting>();
        //int settingid = types.getMaxSettingId()+1;
        settings.add(createSettingsOne());
        settings.add(createSettingsTwo());
        assertEquals(true,types.addTVappsWithSettings( 1,13, "App1", settings, "Danka" ) );

    }

    private static AppSetting createSettingsOne(){

        AppSetting setting = new AppSetting();
        setting.setCreated_by("Kasun");
        LocalDateTime time = new LocalDateTime();
        setting.setCreated_time(time);
        setting.setDisplayOrder(1);
        setting.setEditable(true);
        setting.setSettings_key("url");
        setting.setSettings_value("www.google.com");
        setting.setUpdated_time(time);
        setting.setUpdated_by("Kasun");
        //setting.setSettings_id(settingid);
        return setting;
    }
    private static AppSetting createSettingsTwo(){

        AppSetting setting = new AppSetting();
        setting.setCreated_by("Kasun");
        LocalDateTime time = new LocalDateTime();
        setting.setCreated_time(time);
        setting.setDisplayOrder(2);
        setting.setEditable(true);
        setting.setSettings_key("url2");
        setting.setSettings_value("www.CBC.com");
        setting.setUpdated_time(time);
        setting.setUpdated_by("Kasun");
        //setting.setSettings_id(settingid);

        return setting;
    }
</code>```

This is the app and settings saving method

```<code>public boolean addTVappsWithSettings(int appTypeId,int companyid, String appName, List<AppSetting> settings, String createdBy) {
    //set properties of the app to persist
    App app = new App();

    //app.setSettings_id(settingid);
//  app.setSettings_id(settingid);
    app.setApp_id(appTypeId);
    app.setCompany_id(companyid);
    app.setApp_name(appName);
    app.setCreated_by(createdBy);
    LocalDateTime created_time = new LocalDateTime();
    app.setCreated_time(created_time);
    app.setUpdated_by(createdBy);
    app.setUpdated_time(created_time);
    app.setEnable(true);
    app.setapps(settings);
    session.save(app);
    if (!HibernateUtil.INSTANCE.commitTransaction())
        return false;
    return true;
}
</code>```

These are DAO classes.

```<code>@Entity
@Table(name="company")
public class Company {
    @Id  //primary key
    @GeneratedValue(strategy = GenerationType.IDENTITY)//strategy for generating auto generated number
    @Column(name= "company_id", nullable = false)
    private int company_id;

    @OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
    @Fetch(value = FetchMode.SUBSELECT)
    @JoinColumn(name = "company_id", nullable = false)
    private List<App> threatviewapps = new ArrayList<App>();

    @NotEmpty
    @Column(name= "short_name", nullable = false)
    private String short_name;

    @NotEmpty
    @Column(name= "company_description", nullable = false)
    private String company_description;

    @NotEmpty
    @Column(name= "company_name", nullable = false)
    private String company_name;

    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name= "created_time", nullable = false)
    private LocalDateTime created_time;

    @Column(name= "created_by", nullable = false)
    private String created_by;

    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name= "update_time", nullable = false)
    private LocalDateTime update_time;

    @Column(name= "updated_by", nullable = false)
    private String updated_by;

    @Column(name= "enable", nullable = false)
    private boolean enable;
</code>```

This is the App DAO

```<code>@Entity
@Table(name = "apps")
public class App {

    @Id // primary key
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "settings_id", insertable = false, updatable = false)
    private int settings_id;

    @Column(name = "app_id", nullable = false)
    private int app_id;

/*  @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "settings_id", nullable = false)
    private List<AppSetting> tvsettings = new ArrayList<AppSetting>();*/

    @ElementCollection
    @CollectionTable(name="threatview_app_settings",joinColumns = @JoinColumn(name = "settings_id"))
    private List<AppSetting> tvsettings = new ArrayList<AppSetting>();

    @Column(name = "company_id", insertable = false, updatable = false)
    private int company_id;

    @Column(name = "app_name", nullable = false)
    private String app_name;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name = "created_time", nullable = false)
    private LocalDateTime created_time;

    @Column(name = "created_by", nullable = false)
    private String created_by;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name = "updated_time", nullable = false)
    private LocalDateTime updated_time;

    @Column(name = "updated_by", nullable = false)
    private String updated_by;

    @Column(name = "enable", nullable = false)
    private boolean enable;
</code>```

Why do I get the above error? If you guys need any more information, please let me know.

Update

```<code>@Entity
@IdClass(SettingIDKey.class)
@Table(name = "app_settings")
public class AppSetting {

    @Id
    private int settings_id;

    @Id
    private String settings_key;

    @Column(name = "settings_value", nullable = false)
    private String settings_value;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name = "created_time", nullable = false)
    private LocalDateTime created_time;

    @Column(name = "created_by", nullable = false)
    private String created_by;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name = "updated_time", nullable = false)
    private LocalDateTime updated_time;

    @Column(name = "updated_by", nullable = false)
    private String updated_by;

    @Column(name = "editable", nullable = false)
    private boolean editable;

    @Column(name = "enable", nullable = false)
    private boolean enable;

    @Column(name = "display_order", nullable = false)
    private int displayOrder;
</code>```

答: in your form look at the name of the company_id antite is it the same with what is in the database. If yes, you must give the company id at the form level.</p>

Body:
I am getting the below error, when I try to add a app and app settings.
Here is the detailed error message:

org.hibernate.exception.ConstraintViolationException: could not
execute statement   at
org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:72)
    at
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
    at
org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at
org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
    at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
    at
org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:492)
    at
org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:197)
    at
org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:181)
    at
org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:216)
    at
org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:334)
    at
org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:289)
    at
org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:195)
    at
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
    at
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
    at
org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    at
org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)    at
org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)   at
com.ips.tvadmindao.services.TVAppService.addTVappsWithSettings(TVAppService.java:237)
    at TVAppserviseTest.testsSaveApps(TVAppserviseTest.java:46)     at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)     at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)     at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at
org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)    at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)  at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)     at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)   at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)     at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)    at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at
org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)    at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'company_id' cannot be null  at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:400)     at
com.mysql.jdbc.Util.getInstance(Util.java:383)  at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)   at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847)  at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783)  at
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447)   at
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594)    at
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)     at
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901)
    at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2113)
    at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2049)
    at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2034)
    at
com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:147)
    at
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    ... 50 more

2015-12-21 21:23:15 DEBUG SqlExceptionHelper:139 - could not execute
statement [n/a]
    com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'company_id' cannot be null
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:400)
        at com.mysql.jdbc.Util.getInstance(Util.java:383)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783)
        at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447)
        at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594)
        at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)
        at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901)
        at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2113)
        at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2049)
        at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2034)
        at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:147)
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
        at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
        at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
        at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
        at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:492)
        at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:197)
        at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:181)
        at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:216)
        at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:334)
        at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:289)
        at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:195)
        at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
        at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
        at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
        at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
        at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
        at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
        at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
        at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
        at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
        at com.ips.tvadmindao.services.TVAppService.addTVappsWithSettings(TVAppService.java:237)
        at TVAppserviseTest.testsSaveApps(TVAppserviseTest.java:46)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
        at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
    2015-12-21 21:23:15 WARN  SqlExceptionHelper:144 - SQL Error: 1048, SQLState: 23000
    2015-12-21 21:23:15 ERROR SqlExceptionHelper:146 - Column 'company_id' cannot be null

Here is the junit test

@Test
    public void testsSaveApps() {
        List<AppSetting> settings = new ArrayList<AppSetting>();
        //int settingid = types.getMaxSettingId()+1;
        settings.add(createSettingsOne());
        settings.add(createSettingsTwo());
        assertEquals(true,types.addTVappsWithSettings( 1,13, "App1", settings, "Danka" ) );

    }

    private static AppSetting createSettingsOne(){

        AppSetting setting = new AppSetting();
        setting.setCreated_by("Kasun");
        LocalDateTime time = new LocalDateTime();
        setting.setCreated_time(time);
        setting.setDisplayOrder(1);
        setting.setEditable(true);
        setting.setSettings_key("url");
        setting.setSettings_value("www.google.com");
        setting.setUpdated_time(time);
        setting.setUpdated_by("Kasun");
        //setting.setSettings_id(settingid);
        return setting;
    }
    private static AppSetting createSettingsTwo(){

        AppSetting setting = new AppSetting();
        setting.setCreated_by("Kasun");
        LocalDateTime time = new LocalDateTime();
        setting.setCreated_time(time);
        setting.setDisplayOrder(2);
        setting.setEditable(true);
        setting.setSettings_key("url2");
        setting.setSettings_value("www.CBC.com");
        setting.setUpdated_time(time);
        setting.setUpdated_by("Kasun");
        //setting.setSettings_id(settingid);

        return setting;
    }

This is the app and settings saving method

public boolean addTVappsWithSettings(int appTypeId,int companyid, String appName, List<AppSetting> settings, String createdBy) {
    //set properties of the app to persist
    App app = new App();

    //app.setSettings_id(settingid);
//  app.setSettings_id(settingid);
    app.setApp_id(appTypeId);
    app.setCompany_id(companyid);
    app.setApp_name(appName);
    app.setCreated_by(createdBy);
    LocalDateTime created_time = new LocalDateTime();
    app.setCreated_time(created_time);
    app.setUpdated_by(createdBy);
    app.setUpdated_time(created_time);
    app.setEnable(true);
    app.setapps(settings);
    session.save(app);
    if (!HibernateUtil.INSTANCE.commitTransaction())
        return false;
    return true;
}

These are DAO classes.

@Entity
@Table(name="company")
public class Company {
    @Id  //primary key
    @GeneratedValue(strategy = GenerationType.IDENTITY)//strategy for generating auto generated number
    @Column(name= "company_id", nullable = false)
    private int company_id;

    @OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
    @Fetch(value = FetchMode.SUBSELECT)
    @JoinColumn(name = "company_id", nullable = false)
    private List<App> threatviewapps = new ArrayList<App>();

    @NotEmpty
    @Column(name= "short_name", nullable = false)
    private String short_name;

    @NotEmpty
    @Column(name= "company_description", nullable = false)
    private String company_description;

    @NotEmpty
    @Column(name= "company_name", nullable = false)
    private String company_name;

    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name= "created_time", nullable = false)
    private LocalDateTime created_time;

    @Column(name= "created_by", nullable = false)
    private String created_by;

    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name= "update_time", nullable = false)
    private LocalDateTime update_time;

    @Column(name= "updated_by", nullable = false)
    private String updated_by;

    @Column(name= "enable", nullable = false)
    private boolean enable;

This is the App DAO

@Entity
@Table(name = "apps")
public class App {

    @Id // primary key
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "settings_id", insertable = false, updatable = false)
    private int settings_id;

    @Column(name = "app_id", nullable = false)
    private int app_id;

/*  @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "settings_id", nullable = false)
    private List<AppSetting> tvsettings = new ArrayList<AppSetting>();*/

    @ElementCollection
    @CollectionTable(name="threatview_app_settings",joinColumns = @JoinColumn(name = "settings_id"))
    private List<AppSetting> tvsettings = new ArrayList<AppSetting>();

    @Column(name = "company_id", insertable = false, updatable = false)
    private int company_id;

    @Column(name = "app_name", nullable = false)
    private String app_name;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name = "created_time", nullable = false)
    private LocalDateTime created_time;

    @Column(name = "created_by", nullable = false)
    private String created_by;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name = "updated_time", nullable = false)
    private LocalDateTime updated_time;

    @Column(name = "updated_by", nullable = false)
    private String updated_by;

    @Column(name = "enable", nullable = false)
    private boolean enable;

Why do I get the above error? If you guys need any more information, please let me know.

Update

@Entity
@IdClass(SettingIDKey.class)
@Table(name = "app_settings")
public class AppSetting {

    @Id
    private int settings_id;

    @Id
    private String settings_key;

    @Column(name = "settings_value", nullable = false)
    private String settings_value;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name = "created_time", nullable = false)
    private LocalDateTime created_time;

    @Column(name = "created_by", nullable = false)
    private String created_by;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    @Column(name = "updated_time", nullable = false)
    private LocalDateTime updated_time;

    @Column(name = "updated_by", nullable = false)
    private String updated_by;

    @Column(name = "editable", nullable = false)
    private boolean editable;

    @Column(name = "enable", nullable = false)
    private boolean enable;

    @Column(name = "display_order", nullable = false)
    private int displayOrder;