问:
How can I check if a telephone number exist programmatically?
I want to do an Android App that check if a number exist or not. In particular I was thinking of calling the number to check and if it ring it means that exist, otherwise it does not.

At the moment I can read the state "IDLE" and "OFFHOOK" but not  the state "CALL_STATE_RINGING" that as far as I understood trigger only for received call.

How can I understand when it is ringing and when the number is not valid?

Note: The calling approach is just an idea but I could accept others solutions if they are effective.

My code at the moment:

Listener:

```<code>public class EndCallListener extends PhoneStateListener {
private String TAG = "CALL_AUTOMATICALLY_LISTENER";

@Override
public void onCallStateChanged(int state, String incomingNumber) {
    if(TelephonyManager.CALL_STATE_RINGING == state) {
        // TODO
        Log.i(TAG, "RINGING, number: " + incomingNumber);
    }
    if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
        Log.i(TAG, "OFFHOOK");
    }
    if(TelephonyManager.CALL_STATE_IDLE == state) {
        Log.i(TAG, "IDLE");
    }
}
}

public class MainActivity extends AppCompatActivity {
    private String TAG = "CALL_AUTOMATICALLY";

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

    private void askPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE},0);
    }

    public void startCall(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                String number = "+39555555555"; // fake number
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:" + number));
                // Activate listener
                EndCallListener callListener = new EndCallListener();
                TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
                if (mTM != null) mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
                else Log.d(TAG, "TelephonyManager null");
                // start call
                startActivity(intent);
            } else {
                askPermission();
            }
        }
    }

    public void startCallNotExisting(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                String number = "+39456464564545555565656565";
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:" + number));
                // Activate listener
                EndCallListener callListener = new EndCallListener();
                TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
                if (mTM != null) mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
                else Log.d(TAG, "TelephonyManager null");
                // start call
                startActivity(intent);
            } else {
                askPermission();
            }
        }
    }
}
</code>```

答:
I suggest you check phone number regex instead of calling them.place this method in your helper or activity or fragment class

```<code>public static boolean validateMobile(String mobile) {
    if (mobile.matches("^[+]?[0-9]{10,13}$")) {
        return true;
    } else {
        return false;
    }
}
</code>```

And use it like

```<code>if(Helper.validateMobile(mobile){
//mobile is valid
}else{
//mobile is not valid}
</code>```

also this regex can be different if you target one specific country.for example i use below regex for iran phone numbers

```<code>(\\+98|0)?9\\d{9}
</code>```

Body:
I want to do an Android App that check if a number exist or not. In particular I was thinking of calling the number to check and if it ring it means that exist, otherwise it does not.

At the moment I can read the state "IDLE" and "OFFHOOK" but not  the state "CALL_STATE_RINGING" that as far as I understood trigger only for received call.

How can I understand when it is ringing and when the number is not valid?

Note: The calling approach is just an idea but I could accept others solutions if they are effective.

My code at the moment:

Listener:

public class EndCallListener extends PhoneStateListener {
private String TAG = "CALL_AUTOMATICALLY_LISTENER";

@Override
public void onCallStateChanged(int state, String incomingNumber) {
    if(TelephonyManager.CALL_STATE_RINGING == state) {
        // TODO
        Log.i(TAG, "RINGING, number: " + incomingNumber);
    }
    if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
        Log.i(TAG, "OFFHOOK");
    }
    if(TelephonyManager.CALL_STATE_IDLE == state) {
        Log.i(TAG, "IDLE");
    }
}
}

public class MainActivity extends AppCompatActivity {
    private String TAG = "CALL_AUTOMATICALLY";

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

    private void askPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE},0);
    }

    public void startCall(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                String number = "+39555555555"; // fake number
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:" + number));
                // Activate listener
                EndCallListener callListener = new EndCallListener();
                TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
                if (mTM != null) mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
                else Log.d(TAG, "TelephonyManager null");
                // start call
                startActivity(intent);
            } else {
                askPermission();
            }
        }
    }

    public void startCallNotExisting(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                String number = "+39456464564545555565656565";
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:" + number));
                // Activate listener
                EndCallListener callListener = new EndCallListener();
                TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
                if (mTM != null) mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
                else Log.d(TAG, "TelephonyManager null");
                // start call
                startActivity(intent);
            } else {
                askPermission();
            }
        }
    }
}

Body:
I suggest you check phone number regex instead of calling them.place this method in your helper or activity or fragment class

public static boolean validateMobile(String mobile) {
    if (mobile.matches("^[+]?[0-9]{10,13}$")) {
        return true;
    } else {
        return false;
    }
}

And use it like

if(Helper.validateMobile(mobile){
//mobile is valid
}else{
//mobile is not valid}

also this regex can be different if you target one specific country.for example i use below regex for iran phone numbers

(\\+98|0)?9\\d{9}


来源: stackexchange

问:
Get the domain name of the subdomain Javascript
How i can get the domain name example.com from the set of possible subdomains sub1.example.com sub2.example.com sub3.example.com  using javascript ...?

答:
    function getDomain() {
        const hostnameArray = window.location.hostname.split('.')
        const numberOfSubdomains = hostnameArray.length - 2
        return hostnameArray.length === 2 ? window.location.hostname : hostnameArray.slice(numberOfSubdomains).join('.')
    }
    console.log(getDomain());```

This will remove all subdomains, so "a.b.c.d.test.com" will become "test.com"

ContentLicense: CC BY-SA 3.0

Body:
    function getDomain() {
        const hostnameArray = window.location.hostname.split('.')
        const numberOfSubdomains = hostnameArray.length - 2
        return hostnameArray.length === 2 ? window.location.hostname : hostnameArray.slice(numberOfSubdomains).join('.')
    }
    console.log(getDomain());

This will remove all subdomains, so "a.b.c.d.test.com" will become "test.com"

ContentLicense: CC BY-SA 4.0


问:
Remove old project dbs from macbook
During my time in school and creating my own applications, I've had to delete projects from my laptop to free up space. Is there a way to remove the db from said deleted projects if the project is no longer on my computer? I've had an issue before , when I was starting out that I had to delete my project and start over. But I had forgotten to drop the db. So when I went to create the project again with the same name, it told me the db already exists.

So is there a way to remove stale dbs that do not correspond to a project anymore?

EDIT Sorry, I may need to clarfy. I am trying to clear up space on my laptop by remove old dbs that I forgot to drop before deleting the project folder. I no longer remember the names of the deleted projects

答:
If it says DB already exists then run

```<code>rake db:drop
</code>```

It will drop the existing DB

Title: Remove old project dbs from macbook

Body:
If it says DB already exists then run

rake db:drop

It will drop the existing DB


问:
Get current working directory from Vte (GTK Terminal Widget) in Python
Hey,
How can I get the current working directory of a VTE widget in Python?
Thanks.</p>

答:
Borrowing from Mark, a slightly more elegant approach:</p>

```<code>import vte
import os
v = vte.Terminal()
vPid = v.fork_command()
workingDir = os.readlink('/proc/%s/cwd' % vPid)
</code>```

Body:
Borrowing from Mark, a slightly more elegant approach:

import vte
import os
v = vte.Terminal()
vPid = v.fork_command()
workingDir = os.readlink('/proc/%s/cwd' % vPid)


问:
Scala: Cannot find an implicit value for ContextShift[cats.effect.IO]
I just started with scala and want to build a connection to my DB.

(My knowledge stems from the scala/doobie Tutorial's on https://www.scala-exercises.org/)

Now here is the Code:

```<code>import doobie._
import doobie.implicits._
import cats.effect._
import cats.implicits._
import doobie.hikari._

...
val transactor: Resource[IO, HikariTransactor[IO]] =
    for {
      ce <- ExecutionContexts.fixedThreadPool[IO](32)         // our connect EC
      be <- Blocker[IO]                                       // our blocking EC
      xa <- HikariTransactor.newHikariTransactor[IO](
        "org.h2.Driver",                                      // driver classname
        "jdbc:mysql://localhost:3306/libraries",              // connect URL
        "root",                                               // username
        "",                                                   // password
        ce,                                                   // await connection here
        be                                                    // execute JDBC operations here
      )
    } yield xa
</code>```

When I try to Build my Code i get the following error message:

Error:(25, 53) Cannot find an implicit value for ContextShift[cats.effect.IO]:

import ContextShift[cats.effect.IO] from your effects library

if using IO, use cats.effect.IOApp or build one with cats.effect.IO.contextShift
    xa <- HikariTransactor.newHikariTransactor[IO](

Now I've got two questions:

What exactly is the problem?

How do I fix it?

答:
The problem that compiler cant find ContextShift[IO] instance in implicit scope, which is required for some of methods (not sure which exactly).
You need to declare your own in implicit scope, like

```<code>val dbExecutionContext = ExecutionContext.global // replace with your DB specific EC.
implicit val contextShift: ContextShift[IO] = IO.contextShift(dbExecutionContext)
</code>```

or as error suggested message cats.effect.IOApp has declared ContextShift[IO] as protected implicit def - see https://github.com/typelevel/cats-effect/blob/master/core/shared/src/main/scala/cats/effect/IOApp.scala#L83 which you can use and pass reference in the place where this code is located.
But be careful, because it uses Scala default global execution context.

Hope this helps!

Body:
I just started with scala and want to build a connection to my DB.

(My knowledge stems from the scala/doobie Tutorial's on https://www.scala-exercises.org/)

Now here is the Code:

import doobie._
import doobie.implicits._
import cats.effect._
import cats.implicits._
import doobie.hikari._

...
val transactor: Resource[IO, HikariTransactor[IO]] =
    for {
      ce <- ExecutionContexts.fixedThreadPool[IO](32)         // our connect EC
      be <- Blocker[IO]                                       // our blocking EC
      xa <- HikariTransactor.newHikariTransactor[IO](
        "org.h2.Driver",                                      // driver classname
        "jdbc:mysql://localhost:3306/libraries",              // connect URL
        "root",                                               // username
        "",                                                   // password
        ce,                                                   // await connection here
        be                                                    // execute JDBC operations here
      )
    } yield xa

When I try to Build my Code i get the following error message:

Error:(25, 53) Cannot find an implicit value for ContextShift[cats.effect.IO]:

import ContextShift[cats.effect.IO] from your effects library

if using IO, use cats.effect.IOApp or build one with cats.effect.IO.contextShift
    xa <- HikariTransactor.newHikariTransactor[IO](

Now I've got two questions:

What exactly is the problem?

How do I fix it?

Body:
The problem that compiler cant find ContextShift[IO] instance in implicit scope, which is required for some of methods (not sure which exactly).
You need to declare your own in implicit scope, like

val dbExecutionContext = ExecutionContext.global // replace with your DB specific EC.
implicit val contextShift: ContextShift[IO] = IO.contextShift(dbExecutionContext)

or as error suggested message cats.effect.IOApp has declared ContextShift[IO] as protected implicit def - see https://github.com/typelevel/cats-effect/blob/master/core/shared/src/main/scala/cats/effect/IOApp.scala#L83 which you can use and pass reference in the place where this code is located.
But be careful, because it uses Scala default global execution context.

Hope this helps!


问:
Run thread with derived method from base class without using templates
I'd like to achieve non-templated class just like commented one. Uncommented class will results in an compilation error error: invalid use of non-static member function 'virtual void BaseThread::worker()

```<code>#include <iostream>
#include <thread>

/*
class BaseThread
{
public:
    void start()
    {
// error: invalid use of non-static member function 'virtual void BaseThread::worker()'
        thread_ = std::thread(worker);
    }

private:
    virtual void worker() = 0;

    std::thread thread_;
};
*/

template <typename Derived>
class BaseThread
{
public:
    void start()
    {
        thread_ = std::thread(Derived::worker);
    }

private:
    virtual void worker() = 0;

    std::thread thread_;
};

class DerivedThread : public BaseThread<DerivedThread>
{
private:
    void worker()
    {
        std::cout << "Derived\n";
    }
};

int main()
{
    DerivedThread dt;
}
</code>```

答:
Call it via static member function</p>

```<code>class BaseThread
{
public:
    void start()
    {
        thread_ = std::thread(sworker, this);
    }

private:
    virtual void worker() = 0;
    static void sworker(BaseThread *t) {
        t->worker();
    }
    std::thread thread_;
};
</code>```

Body:
I'd like to achieve non-templated class just like commented one. Uncommented class will results in an compilation error error: invalid use of non-static member function 'virtual void BaseThread::worker()

#include <iostream>
#include <thread>

/*
class BaseThread
{
public:
    void start()
    {
// error: invalid use of non-static member function 'virtual void BaseThread::worker()'
        thread_ = std::thread(worker);
    }

private:
    virtual void worker() = 0;

    std::thread thread_;
};
*/

template <typename Derived>
class BaseThread
{
public:
    void start()
    {
        thread_ = std::thread(Derived::worker);
    }

private:
    virtual void worker() = 0;

    std::thread thread_;
};

class DerivedThread : public BaseThread<DerivedThread>
{
private:
    void worker()
    {
        std::cout << "Derived\n";
    }
};

int main()
{
    DerivedThread dt;
}

Body:
Call it via static member function

class BaseThread
{
public:
    void start()
    {
        thread_ = std::thread(sworker, this);
    }

private:
    virtual void worker() = 0;
    static void sworker(BaseThread *t) {
        t->worker();
    }
    std::thread thread_;
};


问:
How to create and construct a class from another class in Java
Is it possible to create a class (starting from nothing) and construct/write his content from another class?

For example, I got a class StartingClass. And with the methods of this class I want to create ConstructClass (that doesn't exist yet). Inside StartingClass methods I want to specify the content of ConstructClass, like the class it extends, its attributes, its methods.

I need to do this because i need to create new classes from generated classes and unmarshalled xml datas.

I thought about editing a file with .java extension but it's not very clean.

答:
Using the JavaCompiler, you can create and compile at runtime. This example below shows how to do that and you can parametrize the generation of the files and folders and also read the content of one existent Java file as a template for your generation.

```<code>import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class StackOverFlowClassFileGenerationTest {
  public static void main(String[] args) throws IOException {
    FileOutputStream fos = new FileOutputStream("ClassGenerationTest.java");
    PrintStream ps = new PrintStream(fos);
    ps.println("public class ClassGenerationTest {\n");
    ps.println("\t\tpublic static void main(String[] args) {\n");
    ps.println("\t\t\t\tSystem.out.println(\"Testing the class generation at runtime\");\n");
    ps.println("\t\t}\n}\n");
    ps.close();
    fos.close();

    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    String javacOpts[] = {"ClassGenerationTest.java"};
    if (javac.run(null, null, null,  javacOpts) != 0) {
      System.out.println("Error");
    } else {
      System.out.println("Success");
    }
  }
}
</code>```

It's possible to do something similar easily using jOOR version 0.9.8, which will offer some methods to compile classes at runtime. You can check this post to understand better.

Body:
Using the JavaCompiler, you can create and compile at runtime. This example below shows how to do that and you can parametrize the generation of the files and folders and also read the content of one existent Java file as a template for your generation.

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class StackOverFlowClassFileGenerationTest {
  public static void main(String[] args) throws IOException {
    FileOutputStream fos = new FileOutputStream("ClassGenerationTest.java");
    PrintStream ps = new PrintStream(fos);
    ps.println("public class ClassGenerationTest {\n");
    ps.println("\t\tpublic static void main(String[] args) {\n");
    ps.println("\t\t\t\tSystem.out.println(\"Testing the class generation at runtime\");\n");
    ps.println("\t\t}\n}\n");
    ps.close();
    fos.close();

    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    String javacOpts[] = {"ClassGenerationTest.java"};
    if (javac.run(null, null, null,  javacOpts) != 0) {
      System.out.println("Error");
    } else {
      System.out.println("Success");
    }
  }
}

It's possible to do something similar easily using jOOR version 0.9.8, which will offer some methods to compile classes at runtime. You can check this post to understand better.


问:
How to arrange JComboBox item
I have a JComboBox contain 9 image items. How can I arrange them to 3*3?

I want my items arrange like this

I've tried google it for several days, but I don't know what is the keyword for this question. Any advice is appreciated. Thanks for reading my question.

Edit:

Thanks for everyone's feedback.
I am making a map editor where I can put map element together.
The editor.
It is more intuitive to arrange the stone road 3*3. The user can easily know which elements match each other.

I am not necessarily using combo box. I've also consider using buttons, but I think that buttons will waste a lat of space. Because I will have more map elements in the future.

答:
It is possible to do this by giving the JComboBox a custom UI. However that UI is, at least in my case, a mess, so only use it as a workaround and clearly mark it as such with inline documentation.

The following code is made for the default Swing Look and Feel (Metal). If you want to use another L&F you need to exchange the class the custom UI is extending and maybe do some other adjustements. This will get tricky for distribution specific L&F (may force you to use reflection and delegation).

(If you also want to center your images, see this answer.)

Code:

(Sorry for the wierd comment wrapping, don't know whats wrong with my eclipse.)

To set the UI:

```<code>comboBox.setUI(new WrapComboBoxUI(3)); // 3 columns
</code>```

Source code of WrapComboBoxUI:

```<code>import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.ComboPopup;
import javax.swing.plaf.metal.MetalComboBoxUI;

public class WrapComboBoxUI extends MetalComboBoxUI {

    private int columnCount;

    public WrapComboBoxUI() {
        this(0);
    }

    /**
     * @param columnCount
     *            the amount of items to render on one row. <br/>
     *          A value of 0 or less will cause the UI to fit as many items
     *            into one row as possible.
     */
    public WrapComboBoxUI(int columnCount) {
        this.columnCount = columnCount;
    }

    public static ComponentUI createUI(JComponent c) {
        return new WrapComboBoxUI();
    }

    @Override
    protected ComboPopup createPopup() {
        ComboPopup created = super.createPopup();
        try {
            if (created instanceof JPopupMenu) {
                JPopupMenu popup = (JPopupMenu) created;
                JScrollPane scroll = (JScrollPane) popup.getComponent(0);
                JList<?> elementList = (JList<?>) scroll.getViewport().getView();
                elementList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
                elementList.setVisibleRowCount(-1);

                new Thread() {
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                int fixedWidth = -1;
                                if (columnCount > 0) {
                                    int width = elementList.getWidth() - elementList.getInsets().left - elementList.getInsets().right;
                                    fixedWidth = width / columnCount;
                                }
                                boolean changed = false;
                                if (fixedWidth < 0 && elementList.getFixedCellWidth() >= 0 || fixedWidth >= 0 && elementList.getFixedCellWidth() < 0) {
                                    // if changed from not fixed to fixed or
                                    // other way around
                                    changed = true;
                                } else if (fixedWidth > 0 && fixedWidth - elementList.getFixedCellWidth() > 1) {
                                    // if width itself changed, ignoring slight
                                    // changes
                                    changed = true;
                                }
                                final int width = fixedWidth;

                                // no need to loop again before this is done, so
                                // we wait
                                if (changed)
                                    SwingUtilities.invokeAndWait(() -> elementList.setFixedCellWidth(width));

                                sleep(100);
                            } catch (Throwable e) {
                                // ignored
                            }
                        }
                    };
                }.start();
            }
        } catch (Throwable e) {
            System.err.println("Failed to customize ComboBoxUI:");
            e.printStackTrace();
        }
        return created;
    }
}
</code>```

Title: How to arrange JComboBox item

Body:
It is possible to do this by giving the JComboBox a custom UI. However that UI is, at least in my case, a mess, so only use it as a workaround and clearly mark it as such with inline documentation.

The following code is made for the default Swing Look and Feel (Metal). If you want to use another L&F you need to exchange the class the custom UI is extending and maybe do some other adjustements. This will get tricky for distribution specific L&F (may force you to use reflection and delegation).

(If you also want to center your images, see this answer.)

Code:

(Sorry for the wierd comment wrapping, don't know whats wrong with my eclipse.)

To set the UI:

comboBox.setUI(new WrapComboBoxUI(3)); // 3 columns

Source code of WrapComboBoxUI:

import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.ComboPopup;
import javax.swing.plaf.metal.MetalComboBoxUI;

public class WrapComboBoxUI extends MetalComboBoxUI {

    private int columnCount;

    public WrapComboBoxUI() {
        this(0);
    }

    /**
     * @param columnCount
     *            the amount of items to render on one row. <br/>
     *          A value of 0 or less will cause the UI to fit as many items
     *            into one row as possible.
     */
    public WrapComboBoxUI(int columnCount) {
        this.columnCount = columnCount;
    }

    public static ComponentUI createUI(JComponent c) {
        return new WrapComboBoxUI();
    }

    @Override
    protected ComboPopup createPopup() {
        ComboPopup created = super.createPopup();
        try {
            if (created instanceof JPopupMenu) {
                JPopupMenu popup = (JPopupMenu) created;
                JScrollPane scroll = (JScrollPane) popup.getComponent(0);
                JList<?> elementList = (JList<?>) scroll.getViewport().getView();
                elementList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
                elementList.setVisibleRowCount(-1);

                new Thread() {
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                int fixedWidth = -1;
                                if (columnCount > 0) {
                                    int width = elementList.getWidth() - elementList.getInsets().left - elementList.getInsets().right;
                                    fixedWidth = width / columnCount;
                                }
                                boolean changed = false;
                                if (fixedWidth < 0 && elementList.getFixedCellWidth() >= 0 || fixedWidth >= 0 && elementList.getFixedCellWidth() < 0) {
                                    // if changed from not fixed to fixed or
                                    // other way around
                                    changed = true;
                                } else if (fixedWidth > 0 && fixedWidth - elementList.getFixedCellWidth() > 1) {
                                    // if width itself changed, ignoring slight
                                    // changes
                                    changed = true;
                                }
                                final int width = fixedWidth;

                                // no need to loop again before this is done, so
                                // we wait
                                if (changed)
                                    SwingUtilities.invokeAndWait(() -> elementList.setFixedCellWidth(width));

                                sleep(100);
                            } catch (Throwable e) {
                                // ignored
                            }
                        }
                    };
                }.start();
            }
        } catch (Throwable e) {
            System.err.println("Failed to customize ComboBoxUI:");
            e.printStackTrace();
        }
        return created;
    }
}


问:
Running Strapi in production and version control sync issues
I'm wondering what the best practice is for running Strapi in production. I noticed that Strapi generates new files when a content type is added. This means that the production environment's files will become out of sync with version control. Is there a recommended deployment process? Am I supposed to commit changes from production to my git repo after making changes in the admin?</p>

答:
The file generation which is made primarily by content-type-builder and other settings are disabled in production mode NODE_ENV=production

The admin panel is supposed to be already built on prod, so you only add necessary data into DB based on the given data structure.

TLTR:

Summarizing answer to your question in from github.com/strapi/strapi/issues/1986:

emadicio commented on 20 Sep 2018

If you run your app with NODE_ENV=production you'll notice that plugins that actually edit or create files are disabled. So that means you cannot create or edit content types in prod

Downloaddave commented on 22 Sep 2018:

I had deployed Strapi locally then to a Prod environment, and was confused since I didn't see the content-type-builder in the production CMS.

I'm trying to understand the deployment and update process as well...

Developer sets Strapi up locally

Creates content-types using the content-type-builder

Strapi makes updates to the file structure locally and on the local MongoDB

On production we will have to push both the code and db updates?

I understand that making changes to the content-type-builder reboots the service, and we don't want production to go down during the rebuild, but it seems like data would get really out of sync between production and development.

Aurelsicoko commented on 2 Oct 2018

You're right! The Content-Type Builder is a development plugin. His goal is to speed up the development of your project. It should not be used in production. We didn't design this plugin like for this usage.

The real pain is to migrate the development configuration to production, and vice-versa. We plan to offer a new command with the CLI called strapi migrate to easily migrate from an environment to another. I can't give you a release date though...


问:
Delete line in powershell file
I have a file with the following lines

```<code>Servicetag
P4M8K82
P4M8l582
O5M8K82
</code>```

I wish I had the serial numbers only and not the name ServiceTag.
I would like: Browse the .csv file if the line contains SerivceTag then you don't get the value and copy the rest.

As a result, I wish I had:

```<code>P4M8K82
P4M8l582
O5M8K82
</code>```

Do you think it's possible?

答:
Your input file looks like a CSV File with only one field.  When there is only one field, there aren't any separating commas.  Servicetag is not a data entry.  It's the name of the field, also known as a header.

Try the following:

```<code>Import-Csv Test.csv | Format-Table
</code>```

The result is a table with just one column header.  If you do something like:

```<code>$testdata = Import-Csv Test.csv
</code>```

now your data is imported in a form suitable for processing.

Title: Delete line in powershell file

Body:
I have a file with the following lines

Servicetag
P4M8K82
P4M8l582
O5M8K82

I wish I had the serial numbers only and not the name ServiceTag.
I would like: Browse the .csv file if the line contains SerivceTag then you don't get the value and copy the rest.

As a result, I wish I had:

P4M8K82
P4M8l582
O5M8K82

Do you think it's possible?

Body:
Your input file looks like a CSV File with only one field.  When there is only one field, there aren't any separating commas.  Servicetag is not a data entry.  It's the name of the field, also known as a header.

Try the following:

Import-Csv Test.csv | Format-Table

The result is a table with just one column header.  If you do something like:

$testdata = Import-Csv Test.csv

now your data is imported in a form suitable for processing.


问:
How to use appsettings value in section property of web.config
I want to use appsettings value in user defined section in web.cofig.

```<code><coredistributedcache factory-class="NHibernate.Caches.CoreDistributedCache.Redis.RedisFactory,NHibernate.Caches.CoreDistributedCache.Redis">
    <properties>
      <property name="configuration">127.0.0.1:6379</property>
    </properties>
  </coredistributedcache>
</code>```

I have already defined the configuration value in appsetting like this

```<code><add key="RedisServer" value="127.0.0.1:6379" />
</code>```

So basically I don't want to hard code property configuration  to 127.0.0.1:6379, I want to set it like

```<code><property name="configuration">{{RedisServer}}</property>
</code>```

Is this even possible?

Or is there any other way to avoid duplication?

答:
The configs are not dynamic. However you can use WebConfigurationManager to manupulate it.

This approach helps you, from reference :

```<code>var configFile = WebConfigurationManager.OpenWebConfiguration("~");
ClientSettingsSection section = (ClientSettingsSection)configFile.SectionGroups["applicationSettings"].Sections[0];
var value = section.Settings;
SettingElement settingElement = new SettingElement();
SettingValueElement settingValueElement = new SettingValueElement();
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/Web.config"));
XmlNodeList nodeList;
XmlNode root = doc.DocumentElement;
nodeList = root.SelectNodes("applicationSettings");
var valuenode = nodeList[0].SelectNodes("coredistributedcache/properties/property")[0];
var oldValue = valuenode.InnerText;
valuenode.InnerText = "New Value1";
settingValueElement.ValueXml = valuenode;
settingElement.Value = settingValueElement;
value.Clear();
value.Add(settingElement);
configFile.Save();
</code>```

Body:
I want to use appsettings value in user defined section in web.cofig.

<coredistributedcache factory-class="NHibernate.Caches.CoreDistributedCache.Redis.RedisFactory,NHibernate.Caches.CoreDistributedCache.Redis">
    <properties>
      <property name="configuration">127.0.0.1:6379</property>
    </properties>
  </coredistributedcache>

I have already defined the configuration value in appsetting like this

<add key="RedisServer" value="127.0.0.1:6379" />

So basically I don't want to hard code property configuration  to 127.0.0.1:6379, I want to set it like

<property name="configuration">{{RedisServer}}</property>

Is this even possible?

Or is there any other way to avoid duplication?

Body:
The configs are not dynamic. However you can use WebConfigurationManager to manupulate it.

This approach helps you, from reference :

var configFile = WebConfigurationManager.OpenWebConfiguration("~");
ClientSettingsSection section = (ClientSettingsSection)configFile.SectionGroups["applicationSettings"].Sections[0];
var value = section.Settings;
SettingElement settingElement = new SettingElement();
SettingValueElement settingValueElement = new SettingValueElement();
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/Web.config"));
XmlNodeList nodeList;
XmlNode root = doc.DocumentElement;
nodeList = root.SelectNodes("applicationSettings");
var valuenode = nodeList[0].SelectNodes("coredistributedcache/properties/property")[0];
var oldValue = valuenode.InnerText;
valuenode.InnerText = "New Value1";
settingValueElement.ValueXml = valuenode;
settingElement.Value = settingValueElement;
value.Clear();
value.Add(settingElement);
configFile.Save();


问:
x86_64 assembly instructions changed in link stage of GCC
I'm compiling a program using the sqlite3 libary in Linux(centos7_64). As the user has an old CPU, I set the -march=nehalem flag in GCC (-march=nehalem -mtune=nehalem -m64 -O3). I find I can't limit the assembly instructions to nehalem, some BMI operations still exist in the final binary.

Follow the output step by step, I find the problem comes from the linker (ld).

libsqlite3.a:

```<code>   632c2:       66 41 83 4f 26 01       orw    $0x1,0x26(%r15)
   632c8:       0f b6 84 24 80 00 00    movzbl 0x80(%rsp),%eax
   632cf:       00
   632d0:       c1 e0 08                shl    $0x8,%eax
   632d3:       89 c2                   mov    %eax,%edx
   632d5:       0f b6 84 24 81 00 00    movzbl 0x81(%rsp),%eax
   632dc:       00
   632dd:       c1 e0 10                shl    $0x10,%eax
   632e0:       09 d0                   or     %edx,%eax
   632e2:       8d 90 00 fe ff ff       lea    -0x200(%rax),%edx
   632e8:       41 89 47 30             mov    %eax,0x30(%r15)
   632ec:       81 fa 00 fe 00 00       cmp    $0xfe00,%edx
   632f2:       0f 87 d1 05 00 00       ja     638c9 <sqlite3BtreeOpen+0xb29>
   632f8:       8d 50 ff                lea    -0x1(%rax),%edx
   632fb:       85 c2                   test   %eax,%edx
   632fd:       0f 85 c6 05 00 00       jne    638c9 <sqlite3BtreeOpen+0xb29>
</code>```

However, in the final binary:

```<code>  9499f2:       66 41 83 4f 26 01       orw    $0x1,0x26(%r15)
  9499f8:       0f b6 84 24 80 00 00    movzbl 0x80(%rsp),%eax
  9499ff:       00
  949a00:       0f b6 94 24 81 00 00    movzbl 0x81(%rsp),%edx
  949a07:       00
  949a08:       c1 e0 08                shl    $0x8,%eax
  949a0b:       89 c1                   mov    %eax,%ecx
  949a0d:       89 d0                   mov    %edx,%eax
  949a0f:       c1 e0 10                shl    $0x10,%eax
  949a12:       09 c8                   or     %ecx,%eax
  949a14:       8d 90 00 fe ff ff       lea    -0x200(%rax),%edx
  949a1a:       41 89 47 30             mov    %eax,0x30(%r15)
  949a1e:       81 fa 00 fe 00 00       cmp    $0xfe00,%edx
  949a24:       0f 87 cf 05 00 00       ja     949ff9 <sqlite3BtreeOpen+0xb09>
  949a2a:       c4 e2 78 f3 c8          blsr   %eax,%eax
  949a2f:       85 c0                   test   %eax,%eax
  949a31:       0f 85 c2 05 00 00       jne    949ff9 <sqlite3BtreeOpen+0xb09>
</code>```

Notice the last few lines, the linker changed the lea to blsr, which is unexpected.

Thus, why will this happen. Will the linker (ld) optimize the code further? How to limit the instrutions for the linker to use?

答:
Many thanks for the comments. I have found the problem, as Peter Cordes said in the comment, I linked to another set of sqlite library. I installed too many sets of GCC compiler environment, and each compiler has its own sqlite in its default library path. My project was managed by cmake, it remembered all previous GCC settings...

Steps to discover:

add -v flag to gcc commands.

copy the ld commands out, and add flag "--print-map -Map=demo.map", run the full ld command again.

search the library name (sqlite here) in demo.map, I clearly find another set of sqlite library has been linked. Realise how stupid I am...

Update: I have a new problem: if the library.a is compiled with an advanced CPU instruction, how to downgrade it in link stage, seems those instructions will be copied into binary without checking the -march flags in GCC.

Body:
I'm compiling a program using the sqlite3 libary in Linux(centos7_64). As the user has an old CPU, I set the -march=nehalem flag in GCC (-march=nehalem -mtune=nehalem -m64 -O3). I find I can't limit the assembly instructions to nehalem, some BMI operations still exist in the final binary.

Follow the output step by step, I find the problem comes from the linker (ld).

libsqlite3.a:

   632c2:       66 41 83 4f 26 01       orw    $0x1,0x26(%r15)
   632c8:       0f b6 84 24 80 00 00    movzbl 0x80(%rsp),%eax
   632cf:       00
   632d0:       c1 e0 08                shl    $0x8,%eax
   632d3:       89 c2                   mov    %eax,%edx
   632d5:       0f b6 84 24 81 00 00    movzbl 0x81(%rsp),%eax
   632dc:       00
   632dd:       c1 e0 10                shl    $0x10,%eax
   632e0:       09 d0                   or     %edx,%eax
   632e2:       8d 90 00 fe ff ff       lea    -0x200(%rax),%edx
   632e8:       41 89 47 30             mov    %eax,0x30(%r15)
   632ec:       81 fa 00 fe 00 00       cmp    $0xfe00,%edx
   632f2:       0f 87 d1 05 00 00       ja     638c9 <sqlite3BtreeOpen+0xb29>
   632f8:       8d 50 ff                lea    -0x1(%rax),%edx
   632fb:       85 c2                   test   %eax,%edx
   632fd:       0f 85 c6 05 00 00       jne    638c9 <sqlite3BtreeOpen+0xb29>

However, in the final binary:

  9499f2:       66 41 83 4f 26 01       orw    $0x1,0x26(%r15)
  9499f8:       0f b6 84 24 80 00 00    movzbl 0x80(%rsp),%eax
  9499ff:       00
  949a00:       0f b6 94 24 81 00 00    movzbl 0x81(%rsp),%edx
  949a07:       00
  949a08:       c1 e0 08                shl    $0x8,%eax
  949a0b:       89 c1                   mov    %eax,%ecx
  949a0d:       89 d0                   mov    %edx,%eax
  949a0f:       c1 e0 10                shl    $0x10,%eax
  949a12:       09 c8                   or     %ecx,%eax
  949a14:       8d 90 00 fe ff ff       lea    -0x200(%rax),%edx
  949a1a:       41 89 47 30             mov    %eax,0x30(%r15)
  949a1e:       81 fa 00 fe 00 00       cmp    $0xfe00,%edx
  949a24:       0f 87 cf 05 00 00       ja     949ff9 <sqlite3BtreeOpen+0xb09>
  949a2a:       c4 e2 78 f3 c8          blsr   %eax,%eax
  949a2f:       85 c0                   test   %eax,%eax
  949a31:       0f 85 c2 05 00 00       jne    949ff9 <sqlite3BtreeOpen+0xb09>

Notice the last few lines, the linker changed the lea to blsr, which is unexpected.

Thus, why will this happen. Will the linker (ld) optimize the code further? How to limit the instrutions for the linker to use?


问:
In TypeScript, is there a way to omit a type of true or false?
This was my best attempt at trying this. Is it possible or even necessary? Maybe there is something I'm missing about typescript that makes more sense.</p>

```<code>const TrueOrFalse = True | False;

const OnlyTrue = Omit<TrueOrFalse, false>;
</code>```

答:
Omit removes properties from an object type. What you want to do is exclude a type from a union. You can do this with the built-in conditional type Exclude.

```<code>type X = Exclude<boolean, true> // X is false
</code>```

Playground Link

Exclude will take out of the first type parameter, any type that is a subtype of the second parameter.

You can read more about exclude here

Exclude and its cousin Extract can be useful also in manipulating discriminated unions, to extract or exclude a specific constituent from a union, even if you only know the discriminant not the whole the type:

```<code>type Shape = { type: "sq", size: number } | { type: "circle", radius: number }

type Square = Exclude<Shape, { type: "circle" }> //  { type: "sq", size: number }
type Circle = Extract<Shape, { type: "circle" }> //  { type: "circle", radius: number }
</code>```

Playground Link

Body:
This was my best attempt at trying this. Is it possible or even necessary? Maybe there is something I'm missing about typescript that makes more sense.

const TrueOrFalse = True | False;

const OnlyTrue = Omit<TrueOrFalse, false>;

Body:
Omit removes properties from an object type. What you want to do is exclude a type from a union. You can do this with the built-in conditional type Exclude.

type X = Exclude<boolean, true> // X is false

Playground Link

Exclude will take out of the first type parameter, any type that is a subtype of the second parameter.

You can read more about exclude here

Exclude and its cousin Extract can be useful also in manipulating discriminated unions, to extract or exclude a specific constituent from a union, even if you only know the discriminant not the whole the type:

type Shape = { type: "sq", size: number } | { type: "circle", radius: number }

type Square = Exclude<Shape, { type: "circle" }> //  { type: "sq", size: number }
type Circle = Extract<Shape, { type: "circle" }> //  { type: "circle", radius: number }

Playground Link


问:
Enforcing UNIQUE KEY only on active devices mySQL
How does one go about enforcing a UNIQUE KEY within a database that applies only in certain conditions? For a specific example the table consists of several columns which must remain unique only when another BIT column is set.

Simply adding the BIT column to the key is insufficient as there could be several retired devices of the same configuration.

This seems such a prevalent use case, surely there are several work-arounds if no inbuilt capability?

答:
MySQL supports computed columns now.  So, you can use that:

```<code>alter table t
    add unq_column as (case when bitcol = 1 then othercol end);

create unique index unq_t_bit_othercol on t(unq_column);
</code>```

This uses the feature of MySQL that it allows duplicates for NULL in unique indexes.

Body:
MySQL supports computed columns now.  So, you can use that:

alter table t
    add unq_column as (case when bitcol = 1 then othercol end);

create unique index unq_t_bit_othercol on t(unq_column);

This uses the feature of MySQL that it allows duplicates for NULL in unique indexes.


问:
Currently we are using image as checkbox using CSS now when I click the checkbox i want to hide the image and show the background color
Currently we are using image as checkbox using CSS
now when I click the checkbox
I want to hide the image and show the background color.

My Demo is:

What I need?

答: You can just change its visibility to hidden.</p>


问:
firing a jQuery change function at document ready
My change function allows users to switch from country to country and get different text and features. It works when changing country selections. But at initial page load, it does not fire jQuery change to set the hide and show text divs for the default / initial country.

Both divs display at initial page load. When I change away and then back to the default/initial country, change fires, hide and show fire, and shows the proper information and features.

I have tried document.ready with a change function both inside the switch selections and outside the change function. Neither work - they don't fire the hide, show and other jQuery in the switch cases at doc ready.  Its not clear to me whether 'ready' is a valid trigger event.

I have also tried:

```<code>$('input[name=country]').value('US').trigger('click');
</code>```

but it broke the change function. Here's the code.  The country selection below is just 2 countries to keep it simple, but actually, there are many.

```<code>$(document).ready(function()
{
//1st tier - select country via radio buttons:
//Initialize country
$('input[name=country]:first').attr('checked', true);   //Set first radio button (United States)
//$('input[name=country]:first').attr('checked', true).trigger('ready');  //sets 1st button, but does not fire change
//$('input[name=country]:first').trigger('click'); //sets 1st button, but does not fire change

$('input[name=country]').change(function ()
{
// change user instructions to be country specific
    switch ($('input[name=country]:checked').val())
    {
        case 'US':
        $('#stateMessage1').text('2. Select a state or territory of the United States.');
        $('#stateMessage2').text('Start typing a state of the United States, then click on it in the dropdown box.');
        $('#threeSelects').show();
        $('#twoSelects').hide();
        //select via 3 steps
        break;
        case 'CA':
        $('#stateMessage1').text('2. Select a province or territory of Canada.');
        $('#stateMessage2').text('Start typing a province of Canada, then click on it in the dropdown box.');
        $('#twoSelects').show();
        $('#threeSelects').hide();
        //select town via 2 steps - country, town
        break;
    }
});
});
</code>```

答:
This usually is made as:</p>

```<code>function onChange ()
{
    switch ($('input[name=country]:checked').val())
    ....
}

$('input[name=country]').change(onChange); // 1. attach it as event handler.
onChange();                                // 2. call it first time.
</code>```

Body:
My change function allows users to switch from country to country and get different text and features. It works when changing country selections. But at initial page load, it does not fire jQuery change to set the hide and show text divs for the default / initial country.

Both divs display at initial page load. When I change away and then back to the default/initial country, change fires, hide and show fire, and shows the proper information and features.

I have tried document.ready with a change function both inside the switch selections and outside the change function. Neither work - they don't fire the hide, show and other jQuery in the switch cases at doc ready.  Its not clear to me whether 'ready' is a valid trigger event.

I have also tried:

$('input[name=country]').value('US').trigger('click');

but it broke the change function. Here's the code.  The country selection below is just 2 countries to keep it simple, but actually, there are many.

$(document).ready(function()
{
//1st tier - select country via radio buttons:
//Initialize country
$('input[name=country]:first').attr('checked', true);   //Set first radio button (United States)
//$('input[name=country]:first').attr('checked', true).trigger('ready');  //sets 1st button, but does not fire change
//$('input[name=country]:first').trigger('click'); //sets 1st button, but does not fire change

$('input[name=country]').change(function ()
{
// change user instructions to be country specific
    switch ($('input[name=country]:checked').val())
    {
        case 'US':
        $('#stateMessage1').text('2. Select a state or territory of the United States.');
        $('#stateMessage2').text('Start typing a state of the United States, then click on it in the dropdown box.');
        $('#threeSelects').show();
        $('#twoSelects').hide();
        //select via 3 steps
        break;
        case 'CA':
        $('#stateMessage1').text('2. Select a province or territory of Canada.');
        $('#stateMessage2').text('Start typing a province of Canada, then click on it in the dropdown box.');
        $('#twoSelects').show();
        $('#threeSelects').hide();
        //select town via 2 steps - country, town
        break;
    }
});
});

Body:
This usually is made as:

function onChange ()
{
    switch ($('input[name=country]:checked').val())
    ....
}

$('input[name=country]').change(onChange); // 1. attach it as event handler.
onChange();                                // 2. call it first time.


答:
You are looking for a partial unique key. The solution in MySQL varies depending on your version.

In MySQL 8.0:

```<code>create table mydevices (
    id int primary key,
    device_id int,
    location_id,
    is_active tinyint(1),
    unique key (device_id, location_id, nullif(is_active, 0))
);
</code>```

This takes advantage of the fact that null values are ignored when checking unique constraint. So the above allows duplicates on device_id / location_id when is_active is 0, while forbidding them when is_active is 1.

Title: Enforcing UNIQUE KEY only on active devices mySQL

Body:
How does one go about enforcing a UNIQUE KEY within a database that applies only in certain conditions? For a specific example the table consists of several columns which must remain unique only when another BIT column is set.

Simply adding the BIT column to the key is insufficient as there could be several retired devices of the same configuration.

This seems such a prevalent use case, surely there are several work-arounds if no inbuilt capability?

Body:
You are looking for a partial unique key. The solution in MySQL varies depending on your version.

In MySQL 8.0:

create table mydevices (
    id int primary key,
    device_id int,
    location_id,
    is_active tinyint(1),
    unique key (device_id, location_id, nullif(is_active, 0))
);

This takes advantage of the fact that null values are ignored when checking unique constraint. So the above allows duplicates on device_id / location_id when is_active is 0, while forbidding them when is_active is 1.


问:
Hibernate not correctly saving an Object in the db (?, ?, ?, ?)
Following from this question. (I'm using Hibernate 4.)

As suggested in one of the answers I tried using the FeedbackDto-Feedback approach.

Inside my RequestsController.java I have this:

```<code>@PostMapping("/feedback")
public void postFeedback(@RequestBody FeedbackDto feedbackDto) {
    Feedback feedback = new Feedback(new Product(feedbackDto.getProductId()), feedbackDto.getScore(), feedbackDto.isPreferred(), feedbackDto.getTextNote());
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.save(feedback);
    session.flush();
    session.close();
}
</code>```

If I try to print the content of feedback and feedbackDto I get what I was expecting, but running save() and flush() I get no data inserted in the database. Why?

Output from hibernate:

```<code>Hibernate:
    insert
    into
        feedback
        (preferred, score, textnote, product)
    values
        (?, ?, ?, ?)
</code>```

Here's the create statement I used to create the feedback table:

```<code>CREATE TABLE feedback(
  product INTEGER PRIMARY KEY,
  score NUMERIC,
  preferred INTEGER,
  textnote VARCHAR(255),
  FOREIGN KEY(product) REFERENCES product(id)
)
</code>```

答:
The problem with your code is the call of the product constructor:

```<code>new Product(feedbackDto.getProductId())
</code>```

You should first fecth the product object from the database (or create it if doesn't exists and the product's id is enough to create it).

Another problem is in your database representation. You should use an integer ID for your feedback table primary key and have another field to record the foreign key. It is a better approach than mixing ID and foreign key.

So this should be something like this :

```<code>CREATE TABLE feedback(
  feedbackid INTEGER PRIMARY KEY,
  score NUMERIC,
  preferred INTEGER,
  textnote VARCHAR(255),
  productid INTEGER
  FOREIGN KEY(productid) REFERENCES product(id)
)
</code>```

And then your method should be like this :

```<code>@PostMapping("/feedback")
public void postFeedback(@RequestBody FeedbackDto feedbackDto) {
    // I assume you have a field productDao in your class
    Product product = productDao.findById(feedbackDto.getProductId());
    if (product != null) {
        // Assuming the product should exists
        Feedback feedback = new Feedback(feedbackDto.getProductId()), feedbackDto.getScore(), feedbackDto.isPreferred(), feedbackDto.getTextNote(), product);
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.save(feedback);
        session.flush();
        session.close();
     } else {
        // return an error code
     }
}
</code>```

Body:
Following from this question. (I'm using Hibernate 4.)

As suggested in one of the answers I tried using the FeedbackDto-Feedback approach.

Inside my RequestsController.java I have this:

@PostMapping("/feedback")
public void postFeedback(@RequestBody FeedbackDto feedbackDto) {
    Feedback feedback = new Feedback(new Product(feedbackDto.getProductId()), feedbackDto.getScore(), feedbackDto.isPreferred(), feedbackDto.getTextNote());
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.save(feedback);
    session.flush();
    session.close();
}

If I try to print the content of feedback and feedbackDto I get what I was expecting, but running save() and flush() I get no data inserted in the database. Why?

Output from hibernate:

Hibernate:
    insert
    into
        feedback
        (preferred, score, textnote, product)
    values
        (?, ?, ?, ?)

Here's the create statement I used to create the feedback table:

CREATE TABLE feedback(
  product INTEGER PRIMARY KEY,
  score NUMERIC,
  preferred INTEGER,
  textnote VARCHAR(255),
  FOREIGN KEY(product) REFERENCES product(id)
)

Body:
The problem with your code is the call of the product constructor:

new Product(feedbackDto.getProductId())

You should first fecth the product object from the database (or create it if doesn't exists and the product's id is enough to create it).

Another problem is in your database representation. You should use an integer ID for your feedback table primary key and have another field to record the foreign key. It is a better approach than mixing ID and foreign key.

So this should be something like this :

CREATE TABLE feedback(
  feedbackid INTEGER PRIMARY KEY,
  score NUMERIC,
  preferred INTEGER,
  textnote VARCHAR(255),
  productid INTEGER
  FOREIGN KEY(productid) REFERENCES product(id)
)

And then your method should be like this :

@PostMapping("/feedback")
public void postFeedback(@RequestBody FeedbackDto feedbackDto) {
    // I assume you have a field productDao in your class
    Product product = productDao.findById(feedbackDto.getProductId());
    if (product != null) {
        // Assuming the product should exists
        Feedback feedback = new Feedback(feedbackDto.getProductId()), feedbackDto.getScore(), feedbackDto.isPreferred(), feedbackDto.getTextNote(), product);
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.save(feedback);
        session.flush();
        session.close();
     } else {
        // return an error code
     }
}


问:
What does the fdim acronym stand for?
All C math functions seems to have an understandable name, but I can't find what the fdim acronym stands for.
(fdim computes the positive difference of it two floating-point inputs).</p>

答:
I can't find any good published first source for this. fdim first appeared in C99, and the C99 rationale (7.12.12) only mentions this:

The names for fmax, fmin and fdim have f prefixes to allow for
  extension integer versions following the example of fabs and abs.

But we could already guess as much, the f stands for floating point.

Similarly, the last f in fdimf stands for float, and the last l in fdiml stands for long double. These prefix/postfix letters are commonly used in the standard libs.

Title: What does the fdim acronym stand for?


问:
Error using spyOn in a @ViewChild variable
I have a component that uses

```<code>@ViewChild(NgbDropdown) public dropdown: NgbDropdown;

this.dropdown.isOpen();
</code>```

In my spec file, I need to mock the isOpen() result to true but I can't seem to spy on it.

Getting this error:

```<code> Error: <spyOn> : could not find an object to spy upon for isOpen()
        Usage: spyOn(<object>, <methodName>)
</code>```

Thanks in advance!

答:
This has something to do with the linter

This is how it should be mocked

```<code>component.dropdown  = jasmine.createSpyObj(['isOpen']);

(component.dropdown as SpyObj<NgbDropdown>).isOpen.and.returnValue(true);
</code>```

Thanks!

Body:
I have a component that uses

@ViewChild(NgbDropdown) public dropdown: NgbDropdown;

this.dropdown.isOpen();

In my spec file, I need to mock the isOpen() result to true but I can't seem to spy on it.

Getting this error:

 Error: <spyOn> : could not find an object to spy upon for isOpen()
        Usage: spyOn(<object>, <methodName>)

Thanks in advance!

Body:
This has something to do with the linter

This is how it should be mocked

component.dropdown  = jasmine.createSpyObj(['isOpen']);

(component.dropdown as SpyObj<NgbDropdown>).isOpen.and.returnValue(true);

Thanks!


问:
Infinite recursion using React Hooks
I am using React's State Hook in a functional component for getting therapist from database. From which I seen, in useEffect() where setTherapists([therapists].concat(therapists)); is, the list is called in an infinite recursion. I can't see where the problems is, or how do I need to proper call the list.

After I correct get the therapists array I need to render all the therapist. This is how I thought about, but I don't know exactly how to write with Hooks State:

```<code>function renderTherapists()  {
    const items = this.state.therapists.map( (t, idx) => (
        <TherapistCard therapist={t} key={idx} />
    ))

    return (
        <div ref={0} className="therapist-list">
            { items }
        </div>
    )
}
</code>```

My current functional component:

```<code>function TypeArticleOne(props) {

const [ therapists, setTherapists ]= useState([]);
const [speciality, setSpeciality]= useState('ABA');
const [pageLoading, setPageLoading]= useState(true);

const topProfilesUrl = 'therapists/top/profiles'

useEffect(() => {
    console.log(speciality);
    getTopTherapists();
    window.scrollTo(0, 0);

}, []);

const getTopTherapists = () => {
    setPageLoading(true);
    loadTopTherapists();

};

const loadTopTherapists = () => {
    console.log("second");
    props.actions.reqGetTherapistsTopProfiles({
        body: {},
        headers: null,
        resource: `${topProfilesUrl}`
    })
};

useEffect(() => {
        let apiData = props.apiData;

    if (apiData.topProfiles && apiData.topProfiles.success) {
        const therapists = apiData.topProfiles.therapists;
        setPageLoading(false);
        setTherapists([therapists].concat(therapists));

    }

    }, [pageLoading, therapists]);
</code>```

答:
You need to pass the Therapists coming in the props to the default value of your useState declaration:

```<code>const [ therapists, setTherapists ] = useState(apiData.topProfiles.therapists);
</code>```

So when it's re-rendered, it doesn't get called again in a loop.

The constant therapists is shadowing the therapist list from your outer scope.

```<code>if (apiData.topProfiles && apiData.topProfiles.success) {
    const therapists = apiData.topProfiles.therapists;
    setPageLoading(false);
    setTherapists([therapists].concat(therapists));

}
</code>```

Also, as it's already an array, you can call the concat method without put the list within brackets [].

Like:

```<code>const loadedTherapists = apiData.topProfiles.therapists;
setPageLoading(false);
setTherapists(therapists.concat(loadedTherapists));
</code>```

Title: Infinite recursion using React Hooks

Body:
I am using React's State Hook in a functional component for getting therapist from database. From which I seen, in useEffect() where setTherapists([therapists].concat(therapists)); is, the list is called in an infinite recursion. I can't see where the problems is, or how do I need to proper call the list.

After I correct get the therapists array I need to render all the therapist. This is how I thought about, but I don't know exactly how to write with Hooks State:

function renderTherapists()  {
    const items = this.state.therapists.map( (t, idx) => (
        <TherapistCard therapist={t} key={idx} />
    ))

    return (

            { items }

    )
}

My current functional component:

function TypeArticleOne(props) {

const [ therapists, setTherapists ]= useState([]);
const [speciality, setSpeciality]= useState('ABA');
const [pageLoading, setPageLoading]= useState(true);

const topProfilesUrl = 'therapists/top/profiles'

useEffect(() => {
    console.log(speciality);
    getTopTherapists();
    window.scrollTo(0, 0);

}, []);

const getTopTherapists = () => {
    setPageLoading(true);
    loadTopTherapists();

};

const loadTopTherapists = () => {
    console.log("second");
    props.actions.reqGetTherapistsTopProfiles({
        body: {},
        headers: null,
        resource: `${topProfilesUrl}`
    })
};

useEffect(() => {
        let apiData = props.apiData;

    if (apiData.topProfiles && apiData.topProfiles.success) {
        const therapists = apiData.topProfiles.therapists;
        setPageLoading(false);
        setTherapists([therapists].concat(therapists));

    }

    }, [pageLoading, therapists]);

Body:
You need to pass the Therapists coming in the props to the default value of your useState declaration:

const [ therapists, setTherapists ] = useState(apiData.topProfiles.therapists);

So when it's re-rendered, it doesn't get called again in a loop.

The constant therapists is shadowing the therapist list from your outer scope.

if (apiData.topProfiles && apiData.topProfiles.success) {
    const therapists = apiData.topProfiles.therapists;
    setPageLoading(false);
    setTherapists([therapists].concat(therapists));

}

Also, as it's already an array, you can call the concat method without put the list within brackets [].

Like:

const loadedTherapists = apiData.topProfiles.therapists;
setPageLoading(false);
setTherapists(therapists.concat(loadedTherapists));


问:
Using a MEDIAN IF function in Excel as an index?
So I have my Median If function as
=MEDIAN(IF($A$6:$A$200=$L$5,D6:D200))
and I want to know if I can wrap this in an INDEX function to return a value on the row of the calculated median, but in a different column (probably using MATCH I guess)? I've looked at a couple of sources online but I'm struggling to come up with a formula to do this.

The A column is a list of organisations, and the D column is a cumulative frequency that the median would be found in (or rather the range it would be found in so wouldn't be an exact match). I then want when my index has found the value in the D column, to retrieve the corresponding value in that row but from the B column. Thanks in advance!

答:
Yes use MATCH to return the relative location:

```<code> =INDEX($B$6:$B$200,MATCH(MEDIAN(IF($A$6:$A$200=$L$5,D6:D200)),D6:D200,0))
</code>```

Depending on ones version of Excel this formula may need to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.

Body:
Yes use MATCH to return the relative location:

 =INDEX($B$6:$B$200,MATCH(MEDIAN(IF($A$6:$A$200=$L$5,D6:D200)),D6:D200,0))

Depending on ones version of Excel this formula may need to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.


问:
A button is inside the navigation bar, but the btn doesnt belong in the div class of the nav bar
So I made a post similar to this one, since I didn't get a precise answer and didn't understand the instructions. So I am once again asking for your support.

There are a couple of issues regarding my nav bar that I am unable to fix. One of them is a button sticking inside of the nav bar, but it doesn't even belong in the div class.

Navigation Bar

The second issue is that I can't line the logo/text [SINUS] and the links together in one line.
Any help would be appreciated!

/*====================
   The CSS File
     Section 1:
      Buttons
=====================*/

button {
  background-color: #358cf0;
  border: none;
  border-radius: 18px;
  text-align: center;
  text-decoration: none;
  opacity: 0.8;
  font-size: 14px;
  color: rgb(255, 255, 255);
  padding: 12px 48px;
  transition: 0.3s;
  outline: none;
}

button:hover {
  opacity: 1;
}

ul li {
  display: inline-block;
  padding: 10px;
  font-size: 20px;
  font-family: raleway;
}

ul li:hover {
  color: orange;
}

/*====================
   The CSS File
     Section 2:
      Alerts
=====================*/

.container {
  position: fixed;
  top: 74%;
  right: 0;
  left: 77%;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: basic;
}

.modal {
  width: 40%;
  min-width: 20rem;
  background-color: #ffffff;
  border-radius: 12px;
}

.modal-header {
  display: flex;
  align-items: center;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  background-color: #358cf0;
  padding: 8px 10px;
  color: #fff;
  font-size: 110%;
  font-weight: 600;
  font-family: basic;
}

.modal-content {
  padding: 1rem;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.modal-footer {
  text-align: center;
}

/*====================
   The CSS File
     Section 3:
      Body etc.
=====================*/

body {
  background-color: #252036;
}

#navigation-container {
  width: 1200px;
  margin: 0 auto;
  height: 70%;
}

.navigation-bar {
  background-color: #1c172c;
  position: fixed;
  width: 100%;
  left: 0;
  top: 0;
  text-align: right;
}

.navigation-bar ul {
  padding: 0px;
  margin: 0px;
  text-align: right;
  display: inline-block;
  vertical-align: top;
}

.navigation-bar li {
  list-style-type: none;
  padding: 0px;
  display: inline;
  text-align: right;
}

.navigation-bar li a {
  color: black;
  font-size: 16px;
  font-family: basic;
  text-decoration: none;
  line-height: 70px;
  padding: 5px 15px;
  opacity: 0.7;
}

#menu {
  float: right;
}

/*====================
   The CSS File
     Section 4:
        Text
=====================*/

@font-face {
  font-family: basic;
  src: url(Helmet-Regular.ttf);
}

h1 {
  font-family: basic;
  color: white;
  font-size: 390%;
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" type="text/css" href="sccp.css">
  <title>Sinus - 【Home】</title>
  <link rel="icon" href="titl.ico">
  <link rel="apple-touch-icon" href="titl.ico" />
</head>

<body>
  <div class="navigation-bar">
    <div id="navigation-container">
      <h1>SINUS</h1>
      <ul>
        <li>Home</li>
      </ul>
    </div>
  </div>
  <button>Download</button>
  <div class="container" role="alert">

    <div class="modal">
      <div class="modal-header">
        UPDATE! Sinus 1.0v
      </div>
      <div class="modal-content">
        Here new stuff go gogogo
        <br>Read more...
      </div>
      <div class="modal-footer">

      </div>
    </div>

  </div>

</body>

</html></code>```

答:
To align the logo and links, use flex on the #navigation-container:

```<code>#navigation-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</code>```

justify-content: space-between will put the maximum space between the contents - in this case your logo and ul that contain the links. align-items:center lines them up vertically.

https://codepen.io/doughballs/pen/RwPrYoX

Not sure what your issue with the button is but because your nav has position:fixed, it is being taken out of the flow of the page, so the button doesn't 'know' it is there. If you wanted it to sit under the nav, you need to add a container with margin-top to push it down. But I'm not sure what your issue is with it, clarify and I'll amend the codepen.

Body:
So I made a post similar to this one, since I didn't get a precise answer and didn't understand the instructions. So I am once again asking for your support.

There are a couple of issues regarding my nav bar that I am unable to fix. One of them is a button sticking inside of the nav bar, but it doesn't even belong in the div class.

Navigation Bar

The second issue is that I can't line the logo/text [SINUS] and the links together in one line.
Any help would be appreciated!

/*====================
   The CSS File
     Section 1:
      Buttons
=====================*/

button {
  background-color: #358cf0;
  border: none;
  border-radius: 18px;
  text-align: center;
  text-decoration: none;
  opacity: 0.8;
  font-size: 14px;
  color: rgb(255, 255, 255);
  padding: 12px 48px;
  transition: 0.3s;
  outline: none;
}

button:hover {
  opacity: 1;
}

ul li {
  display: inline-block;
  padding: 10px;
  font-size: 20px;
  font-family: raleway;
}

ul li:hover {
  color: orange;
}

/*====================
   The CSS File
     Section 2:
      Alerts
=====================*/

.container {
  position: fixed;
  top: 74%;
  right: 0;
  left: 77%;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: basic;
}

.modal {
  width: 40%;
  min-width: 20rem;
  background-color: #ffffff;
  border-radius: 12px;
}

.modal-header {
  display: flex;
  align-items: center;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  background-color: #358cf0;
  padding: 8px 10px;
  color: #fff;
  font-size: 110%;
  font-weight: 600;
  font-family: basic;
}

.modal-content {
  padding: 1rem;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.modal-footer {
  text-align: center;
}

/*====================
   The CSS File
     Section 3:
      Body etc.
=====================*/

body {
  background-color: #252036;
}

#navigation-container {
  width: 1200px;
  margin: 0 auto;
  height: 70%;
}

.navigation-bar {
  background-color: #1c172c;
  position: fixed;
  width: 100%;
  left: 0;
  top: 0;
  text-align: right;
}

.navigation-bar ul {
  padding: 0px;
  margin: 0px;
  text-align: right;
  display: inline-block;
  vertical-align: top;
}

.navigation-bar li {
  list-style-type: none;
  padding: 0px;
  display: inline;
  text-align: right;
}

.navigation-bar li a {
  color: black;
  font-size: 16px;
  font-family: basic;
  text-decoration: none;
  line-height: 70px;
  padding: 5px 15px;
  opacity: 0.7;
}

#menu {
  float: right;
}

/*====================
   The CSS File
     Section 4:
        Text
=====================*/

@font-face {
  font-family: basic;
  src: url(Helmet-Regular.ttf);
}

h1 {
  font-family: basic;
  color: white;
  font-size: 390%;
  text-align: left;
}

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="sccp.css">
  <title>Sinus - 【Home】</title>
  <link rel="icon" href="titl.ico">
  <link rel="apple-touch-icon" href="titl.ico" />

SINUS

Home

  <button>Download</button>

        UPDATE! Sinus 1.0v

        Here new stuff go gogogo

Read more...

Body:
To align the logo and links, use flex on the #navigation-container:

#navigation-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

justify-content: space-between will put the maximum space between the contents - in this case your logo and ul that contain the links. align-items:center lines them up vertically.

https://codepen.io/doughballs/pen/RwPrYoX

Not sure what your issue with the button is but because your nav has position:fixed, it is being taken out of the flow of the page, so the button doesn't 'know' it is there. If you wanted it to sit under the nav, you need to add a container with margin-top to push it down. But I'm not sure what your issue is with it, clarify and I'll amend the codepen.


问:
Automatically update the input field within a form, vue.js
I want to search for elements using an input field within a form. I am passing a value from a component to another and the content changes but only after pressing enter. Is there a way to automatically update the list, after every new letter is typed?
Here is my code:

Parent(App):

```<code><template>
  <div id="app">
    <Header v-on:phrase-search="passPhrase" />
  </div>
</template>

<script>
import Header from ...

export default {
  name: "App",
  components: {
    Header,
  },
  data() {
    return {
      posts: [],
      searchedPhrase: ""
    };
  }
  computed: {
    filteredPosts() {
      let temp_text = this.searchedPhrase;
      temp_text.trim().toLowerCase();

      return this.posts.filter(post => {
        return post.name.toLowerCase().match(temp_text);
      });
    }
  },
  methods: {
    passPhrase(phrase) {
      this.searchedPhrase = phrase;
    }
  }
};
</script>
</code>```

Child(Header):

```<code><template>
<div class="child">
  <p>Search:</p>
    <form @submit.prevent="phrasePassed">
      <input type="text" v-model="phrase" />
    </form>
</div>
</template>

<script>
export default {
  name: "search",
  data() {
    return {
      phrase: ""
    };
  },
  methods: {
    phrasePassed() {
      this.$emit("phrase-search", this.phrase);
    }
  }
};
</script>
</code>```

passPhrase() brings the value from the child to the parent and then filteredPosts() find appropriate elements. I suspect that the form might be guilty of this issue but I do not know precisely how to get rid of it and still be able to pass the value to the parent.

Thanks

答:
in the child you use submit event which called on enter. you should use @input on the input itself. and btw you didnt need even to declare pharse in the data because you didnt use it in the child. you just pass it up

you it like so

```<code><template>
  <div class="child">
    <p>Search:</p>
    <form>
      <input type="text" @input="phrasePassed">
    </form>
  </div>
</template>

<script>
export default {
  name: "search",
  methods: {
    phrasePassed(e) {
      this.$emit("phrase-search", e.target.value);
    }
  }
};
</script>
</code>```

Body:
I want to search for elements using an input field within a form. I am passing a value from a component to another and the content changes but only after pressing enter. Is there a way to automatically update the list, after every new letter is typed?
Here is my code:

Parent(App):

<template>

</template>

Child(Header):

<template>

Search:

    <form @submit.prevent="phrasePassed">
      <input type="text" v-model="phrase" />
    </form>

</template>

passPhrase() brings the value from the child to the parent and then filteredPosts() find appropriate elements. I suspect that the form might be guilty of this issue but I do not know precisely how to get rid of it and still be able to pass the value to the parent.

Thanks

Body:
in the child you use submit event which called on enter. you should use @input on the input itself. and btw you didnt need even to declare pharse in the data because you didnt use it in the child. you just pass it up

you it like so

<template>
  <div class="child">
    <p>Search:</p>
    <form>
      <input type="text" @input="phrasePassed">
    </form>
  </div>
</template>

<script>
export default {
  name: "search",
  methods: {
    phrasePassed(e) {
      this.$emit("phrase-search", e.target.value);
    }
  }
};
</script>


问:
Python: Removing list element while iterating over list
I'm iterating over a list of elements in Python, do some action on it, and then remove them if they meet certain criteria.

```<code>for element in somelist:
    do_action(element)
    if check(element):
        remove_element_from_list
</code>```

What should I use in place of remove_element?
I have seen similar questions asked, but notice the presence of the do_action part that is to be executed for all elements and thus eliminates the solution of using filters.

答:
You could always iterate over a copy of the list, leaving you free to modify the original:</p>

```<code>for item in list(somelist):
  ...
  somelist.remove(item)
</code>```

Body:
I'm iterating over a list of elements in Python, do some action on it, and then remove them if they meet certain criteria.

for element in somelist:
    do_action(element)
    if check(element):
        remove_element_from_list

What should I use in place of remove_element?
I have seen similar questions asked, but notice the presence of the do_action part that is to be executed for all elements and thus eliminates the solution of using filters.

Body:
You could always iterate over a copy of the list, leaving you free to modify the original:

for item in list(somelist):
  ...
  somelist.remove(item)


问:
How can I do a sequence-to-sequence model (RNN / LSTM) with Keras with fixed length data?
What I'm trying to do seems so simple, but I can't find any examples online. First, I'm not working in language, so all of the embedding stuff adds needless complexity to my task.

I have input, in the form of a (1, 1000) vector. They are time-series data, so I'll have 10 of them in sequence. Which, if I understand tensors correctly, gives me something of shape (10, 1, 1000), right?

I want to pass this through an RNN/LSTM and the output should be also of the same shape (10, 1, 1000). Namely, 10 vectors of 1000 dimensions each.

答:
If you only want a LSTM model that takes an input of shape (nb_seq, 1, 1000) (with nb_seq beeing your number of sequences, 10 in your case) and outputs the same shape, here is a basic model that you can adapt :

```<code>input_x = Input(shape=(1, 1000))
x = LSTM(64, return_sequences=True)(input_x)
x = LSTM(64, return_sequences=True)(x)
x = Dense(1000)(x)

Model(inputs=input_x, outputs=x)
</code>```

The LSTM layer with return_sequence=True, will return a tensor of shape (nb_seq, 1, 64) (with 64 beeing the number of neurones of your LSTM layer), so in order to find the original shape you can either pass this tensor throught a Dense layer that will give you a shape of (nb_seq, 1, 1000) or you can directly have 1000 neurones on your last LSTM layer ( i don't recommand because it will generate many parameters).

You can modify this as you wish.

EDIT after precisions

As keras LSTM takes only 3D input you can trick it by passing a Timedistributed flatten layer at the begining like this :

```<code>input_x = Input(shape=(10, 1, 1000))
x = TimeDistributed(Flatten())(input_x)
x = LSTM(64, return_sequences=True)(x)
x = LSTM(64, return_sequences=True)(x)
x = Dense(1000)(x)
x = Reshape(target_shape=(10, 1, 1000))(x)

Model(inputs=input_x, outputs=x)
</code>```

That gives you this summary :

Body:
If you only want a LSTM model that takes an input of shape (nb_seq, 1, 1000) (with nb_seq beeing your number of sequences, 10 in your case) and outputs the same shape, here is a basic model that you can adapt :

input_x = Input(shape=(1, 1000))
x = LSTM(64, return_sequences=True)(input_x)
x = LSTM(64, return_sequences=True)(x)
x = Dense(1000)(x)

Model(inputs=input_x, outputs=x)

The LSTM layer with return_sequence=True, will return a tensor of shape (nb_seq, 1, 64) (with 64 beeing the number of neurones of your LSTM layer), so in order to find the original shape you can either pass this tensor throught a Dense layer that will give you a shape of (nb_seq, 1, 1000) or you can directly have 1000 neurones on your last LSTM layer ( i don't recommand because it will generate many parameters).

You can modify this as you wish.

EDIT after precisions

As keras LSTM takes only 3D input you can trick it by passing a Timedistributed flatten layer at the begining like this :

input_x = Input(shape=(10, 1, 1000))
x = TimeDistributed(Flatten())(input_x)
x = LSTM(64, return_sequences=True)(x)
x = LSTM(64, return_sequences=True)(x)
x = Dense(1000)(x)
x = Reshape(target_shape=(10, 1, 1000))(x)

Model(inputs=input_x, outputs=x)

That gives you this summary :


问:
Why this code not works ? Nothing happens after running ? I would like to have validation error in my view
such code I have in the view

```<code><TextBox
        Text="{Binding MiejsceWykonaniaNadgodzin,  UpdateSourceTrigger=PropertyChanged}"
        Name="MiejsceWykonaniaNadgodzinText" Margin="50 50 50 50">
    <Validation.ErrorTemplate>
        <ControlTemplate>
            <StackPanel>
                <!-- Placeholder for the TextBox itself -->
                <AdornedElementPlaceholder x:Name="textBox"/>
                <TextBlock Text="{Binding [0].ErrorContent}" Foreground="Red"/>
            </StackPanel>
        </ControlTemplate>
    </Validation.ErrorTemplate>
</TextBox>
</code>```

and such code in the model

```<code>public string MiejsceWykonaniaNadgodzin
{
    get { return miejsceWykonaniaNadgodzin; }

    set
    {
        this.miejsceWykonaniaNadgodzin = "aaa";

        OnPropertyChanged();
    }
}

public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged( string miejsceWykonaniaNadgodzin = null)
{
    PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(miejsceWykonaniaNadgodzin));
}
</code>```

I have written digits for example 2222 in my textbox in view and an error doesn't show there.

答:
```<code><TextBox Name="MiejsceWykonaniaNadgodzinText" Margin="50 50 50 50">
    <TextBox.Text>
       <Binding Path="MiejsceWykonaniaNadgodzin"  UpdateSourceTrigger="PropertyChanged" >
             <Binding.ValidationRules>
                  <local:MiejsceWykonaniaNadgodzinTextRule />
             </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
    <Validation.ErrorTemplate>
        <ControlTemplate>
            <StackPanel>
                <!-- Placeholder for the TextBox itself -->
                <AdornedElementPlaceholder x:Name="textBox"/>
                <TextBlock Text="{Binding [0].ErrorContent}" Foreground="Red"/>
            </StackPanel>
        </ControlTemplate>
    </Validation.ErrorTemplate>
</TextBox>
</code>```

and

```<code>public class MiejsceWykonaniaNadgodzinTextRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        //example test
        if(value.ToString() == "aaa")
            return new ValidationResult(false, $"Error: value = aaa");
        return ValidationResult.ValidResult;
    }
}
</code>```

don't forget to modify

```<code>public string MiejsceWykonaniaNadgodzin
{
    get => miejsceWykonaniaNadgodzin;
    set
    {
        this.miejsceWykonaniaNadgodzin = value;//"aaa";

        OnPropertyChanged(nameof(MiejsceWykonaniaNadgodzin));
    }
}
</code>```

Body:
such code I have in the view

<TextBox
        Text="{Binding MiejsceWykonaniaNadgodzin,  UpdateSourceTrigger=PropertyChanged}"
        Name="MiejsceWykonaniaNadgodzinText" Margin="50 50 50 50">
    <Validation.ErrorTemplate>
        <ControlTemplate>
            <StackPanel>

                <AdornedElementPlaceholder x:Name="textBox"/>
                <TextBlock Text="{Binding [0].ErrorContent}" Foreground="Red"/>
            </StackPanel>
        </ControlTemplate>
    </Validation.ErrorTemplate>
</TextBox>

and such code in the model

public string MiejsceWykonaniaNadgodzin
{
    get { return miejsceWykonaniaNadgodzin; }

    set
    {
        this.miejsceWykonaniaNadgodzin = "aaa";

        OnPropertyChanged();
    }
}

public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged( string miejsceWykonaniaNadgodzin = null)
{
    PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(miejsceWykonaniaNadgodzin));
}

I have written digits for example 2222 in my textbox in view and an error doesn't show there.

Body:
<TextBox Name="MiejsceWykonaniaNadgodzinText" Margin="50 50 50 50">
    <TextBox.Text>
       <Binding Path="MiejsceWykonaniaNadgodzin"  UpdateSourceTrigger="PropertyChanged" >
             <Binding.ValidationRules>
                  <local:MiejsceWykonaniaNadgodzinTextRule />
             </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
    <Validation.ErrorTemplate>
        <ControlTemplate>
            <StackPanel>
                <!-- Placeholder for the TextBox itself -->
                <AdornedElementPlaceholder x:Name="textBox"/>
                <TextBlock Text="{Binding [0].ErrorContent}" Foreground="Red"/>
            </StackPanel>
        </ControlTemplate>
    </Validation.ErrorTemplate>
</TextBox>

and

public class MiejsceWykonaniaNadgodzinTextRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        //example test
        if(value.ToString() == "aaa")
            return new ValidationResult(false, $"Error: value = aaa");
        return ValidationResult.ValidResult;
    }
}

don't forget to modify

public string MiejsceWykonaniaNadgodzin
{
    get => miejsceWykonaniaNadgodzin;
    set
    {
        this.miejsceWykonaniaNadgodzin = value;//"aaa";

        OnPropertyChanged(nameof(MiejsceWykonaniaNadgodzin));
    }
}


问:
Run thread with derived method from base class without using templates
I'd like to achieve non-templated class just like commented one. Uncommented class will results in an compilation error error: invalid use of non-static member function 'virtual void BaseThread::worker()

```<code>#include <iostream>
#include <thread>

/*
class BaseThread
{
public:
    void start()
    {
// error: invalid use of non-static member function 'virtual void BaseThread::worker()'
        thread_ = std::thread(worker);
    }

private:
    virtual void worker() = 0;

    std::thread thread_;
};
*/

template <typename Derived>
class BaseThread
{
public:
    void start()
    {
        thread_ = std::thread(Derived::worker);
    }

private:
    virtual void worker() = 0;

    std::thread thread_;
};

class DerivedThread : public BaseThread<DerivedThread>
{
private:
    void worker()
    {
        std::cout << "Derived\n";
    }
};

int main()
{
    DerivedThread dt;
}
</code>```

答:
Why does this not compile? The point is that you simply didn't get the syntax right, that's all. You can not call a memberfunction without an object. A simple way to pass these to std::thread like this:

```<code>std::thread th{&ThreadBase::worker, this}
</code>```

However, you have picked an unfortunate abstraction, which is to create a "thread" class in the first place, which requires you to derive from. Don't do that, because it mixes two concerns, which are the code being called and the thread. To some extent, this is similar to creating a file baseclass which you derive from for different file formats. The indicator for this flawed approach is that in both cases, the instance of the thread or file is not a thread or file! Think about that, an instance of std::thread is not a thread and an instance of std::fstream is not a file. Rather, these objects are objects that you can use to interact with a thread or a file, similar to how a database client is used to interact with a database.

In summary, instead of writing a class that is derived from your BaseThread, just write a class that does something. Don't let this class worry about whether its code is called in a thread. If you want to do that, just use std::thread which you already did under the hood.

Body:
I'd like to achieve non-templated class just like commented one. Uncommented class will results in an compilation error error: invalid use of non-static member function 'virtual void BaseThread::worker()

#include <iostream>
#include <thread>

/*
class BaseThread
{
public:
    void start()
    {
// error: invalid use of non-static member function 'virtual void BaseThread::worker()'
        thread_ = std::thread(worker);
    }

private:
    virtual void worker() = 0;

    std::thread thread_;
};
*/

template <typename Derived>
class BaseThread
{
public:
    void start()
    {
        thread_ = std::thread(Derived::worker);
    }

private:
    virtual void worker() = 0;

    std::thread thread_;
};

class DerivedThread : public BaseThread<DerivedThread>
{
private:
    void worker()
    {
        std::cout << "Derived\n";
    }
};

int main()
{
    DerivedThread dt;
}

Body:
Why does this not compile? The point is that you simply didn't get the syntax right, that's all. You can not call a memberfunction without an object. A simple way to pass these to std::thread like this:

std::thread th{&ThreadBase::worker, this}

However, you have picked an unfortunate abstraction, which is to create a "thread" class in the first place, which requires you to derive from. Don't do that, because it mixes two concerns, which are the code being called and the thread. To some extent, this is similar to creating a file baseclass which you derive from for different file formats. The indicator for this flawed approach is that in both cases, the instance of the thread or file is not a thread or file! Think about that, an instance of std::thread is not a thread and an instance of std::fstream is not a file. Rather, these objects are objects that you can use to interact with a thread or a file, similar to how a database client is used to interact with a database.

In summary, instead of writing a class that is derived from your BaseThread, just write a class that does something. Don't let this class worry about whether its code is called in a thread. If you want to do that, just use std::thread which you already did under the hood.


问:
Is there a C snippet that computes overflow-safe addition efficiently without using compiler builtins?
Here is a C function that adds an int to another, failing if overflow would happen:

```<code>int safe_add(int *value, int delta) {
        if (*value >= 0) {
                if (delta > INT_MAX - *value) {
                        return -1;
                }
        } else {
                if (delta < INT_MIN - *value) {
                        return -1;
                }
        }

        *value += delta;
        return 0;
}
</code>```

Unfortunately it is not optimized well by GCC or Clang:

```<code>safe_add(int*, int):
        movl    (%rdi), %eax
        testl   %eax, %eax
        js      .L2
        movl    $2147483647, %edx
        subl    %eax, %edx
        cmpl    %esi, %edx
        jl      .L6
.L4:
        addl    %esi, %eax
        movl    %eax, (%rdi)
        xorl    %eax, %eax
        ret
.L2:
        movl    $-2147483648, %edx
        subl    %eax, %edx
        cmpl    %esi, %edx
        jle     .L4
.L6:
        movl    $-1, %eax
        ret
</code>```

This version with __builtin_add_overflow()

```<code>int safe_add(int *value, int delta) {
        int result;
        if (__builtin_add_overflow(*value, delta, &result)) {
                return -1;
        } else {
                *value = result;
                return 0;
        }
}
</code>```

is optimized better:

```<code>safe_add(int*, int):
        xorl    %eax, %eax
        addl    (%rdi), %esi
        seto    %al
        jo      .L5
        movl    %esi, (%rdi)
        ret
.L5:
        movl    $-1, %eax
        ret
</code>```

but I'm curious if there's a way without using builtins that will get pattern-matched by GCC or Clang.

答:
I could get the compiler to use the sign flag by assuming (and asserting) a two’s complement representation without padding bytes. Such implementations should yield the required behaviour in the line annotated by a comment, although I can’t find a positive formal confirmation of this requirement in the standard (and there probably isn’t any).

Note that the following code only handles positive integer addition, but can be extended.

```<code>int safe_add(int* lhs, int rhs) {
    _Static_assert(-1 == ~0, "integers are not two's complement");
    _Static_assert(
        1u << (sizeof(int) * CHAR_BIT - 1) == (unsigned) INT_MIN,
        "integers have padding bytes"
    );
    unsigned value = *lhs;
    value += rhs;
    if ((int) value < 0) return -1; // impl. def., 6.3.1.3/3
    *lhs = value;
    return 0;
}
</code>```

This yields on both clang and GCC:

```<code>safe_add:
        add     esi, DWORD PTR [rdi]
        js      .L3
        mov     DWORD PTR [rdi], esi
        xor     eax, eax
        ret
.L3:
        mov     eax, -1
        ret
</code>```

Body:
Here is a C function that adds an int to another, failing if overflow would happen:

int safe_add(int *value, int delta) {
        if (*value >= 0) {
                if (delta > INT_MAX - *value) {
                        return -1;
                }
        } else {
                if (delta < INT_MIN - *value) {
                        return -1;
                }
        }

        *value += delta;
        return 0;
}

Unfortunately it is not optimized well by GCC or Clang:

safe_add(int*, int):
        movl    (%rdi), %eax
        testl   %eax, %eax
        js      .L2
        movl    $2147483647, %edx
        subl    %eax, %edx
        cmpl    %esi, %edx
        jl      .L6
.L4:
        addl    %esi, %eax
        movl    %eax, (%rdi)
        xorl    %eax, %eax
        ret
.L2:
        movl    $-2147483648, %edx
        subl    %eax, %edx
        cmpl    %esi, %edx
        jle     .L4
.L6:
        movl    $-1, %eax
        ret

This version with __builtin_add_overflow()

int safe_add(int *value, int delta) {
        int result;
        if (__builtin_add_overflow(*value, delta, &result)) {
                return -1;
        } else {
                *value = result;
                return 0;
        }
}

is optimized better:

safe_add(int*, int):
        xorl    %eax, %eax
        addl    (%rdi), %esi
        seto    %al
        jo      .L5
        movl    %esi, (%rdi)
        ret
.L5:
        movl    $-1, %eax
        ret

but I'm curious if there's a way without using builtins that will get pattern-matched by GCC or Clang.

Body:
I could get the compiler to use the sign flag by assuming (and asserting) a two’s complement representation without padding bytes. Such implementations should yield the required behaviour in the line annotated by a comment, although I can’t find a positive formal confirmation of this requirement in the standard (and there probably isn’t any).

Note that the following code only handles positive integer addition, but can be extended.

int safe_add(int* lhs, int rhs) {
    _Static_assert(-1 == ~0, "integers are not two's complement");
    _Static_assert(
        1u << (sizeof(int) * CHAR_BIT - 1) == (unsigned) INT_MIN,
        "integers have padding bytes"
    );
    unsigned value = *lhs;
    value += rhs;
    if ((int) value < 0) return -1; // impl. def., 6.3.1.3/3
    *lhs = value;
    return 0;
}

This yields on both clang and GCC:

safe_add:
        add     esi, DWORD PTR [rdi]
        js      .L3
        mov     DWORD PTR [rdi], esi
        xor     eax, eax
        ret
.L3:
        mov     eax, -1
        ret