问:
permanent notification does not show
I submitted my app at the end of 2017 in the play store and it worked.
Then it was built in Eclipse.

Now I run it in Android Studio and the same code doesn't show any notification.
It is a permanent notification which is present after I call the app's finish() method. (why I do this: see at the bottom if you want to know).

So I looked at all the examples and NONE of the work. No single notification is shown.

So I start an activity and in the activity I show the notification. Then I call finish().

This is my code:

```<code>Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                intent, 0);

        CharSequence connectedPart = getResources().getString(R.string.app_name);

        String melding = "";

        melding = getResources().getString(R.string.screentimeoutsetto) + " "  + newTimeString + ".";
        NotificationManager notificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Notification notification = new Notification.Builder(this)
                .setContentTitle(connectedPart)
                .setTicker(connectedPart)
                .setContentText(melding)
                .setSmallIcon(R.drawable.ic_stat_name)
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .build();
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        notification.flags |= Notification.FLAG_NO_CLEAR;
        notificationManager.notify(2, notification);
</code>```

dependencies:

```<code>dependencies{
    implementation "com.android.support:support-compat:26.1.0"
}
</code>```

Why I do this:
My app does 1 thing: toggle the screentimeout. So when you start it it sets the screentimeout to 30 minutes (starts, sets a notification, then finish()). Start again, it removes the notification and restore the original value for the screen timeout.

答:
Starting with Android Oreo, all notifications require a notification channel, otherwise the notification wont post and an error will appear in your logcat. Here's an example of how you can do it, lifted from one of my apps:</p>

```<code>private static void createNotificationChannel(Context ctx) {
    if(SDK_INT < O) return;

    final NotificationManager mgr = ctx.getSystemService(NotificationManager.class);
    if(mgr == null) return;

    final String name = ctx.getString(R.string.channel_name);
    if(mgr.getNotificationChannel(name) == null) {
        final NotificationChannel channel =
                new NotificationChannel(CHANNEL_ID, name, IMPORTANCE_DEFAULT);
        mgr.createNotificationChannel(channel);
    }
}

//Usage...
createNotificationChannel(context);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID);
builder.setSmallIcon(R.drawable.ic_alarm_white_24dp);
//etc...
manager.notify(id, builder.build());
</code>```

Title: permanent notification does not show

Body:
I submitted my app at the end of 2017 in the play store and it worked.
Then it was built in Eclipse.

Now I run it in Android Studio and the same code doesn't show any notification.
It is a permanent notification which is present after I call the app's finish() method. (why I do this: see at the bottom if you want to know).

So I looked at all the examples and NONE of the work. No single notification is shown.

So I start an activity and in the activity I show the notification. Then I call finish().

This is my code:

Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                intent, 0);

        CharSequence connectedPart = getResources().getString(R.string.app_name);

        String melding = "";

        melding = getResources().getString(R.string.screentimeoutsetto) + " "  + newTimeString + ".";
        NotificationManager notificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Notification notification = new Notification.Builder(this)
                .setContentTitle(connectedPart)
                .setTicker(connectedPart)
                .setContentText(melding)
                .setSmallIcon(R.drawable.ic_stat_name)
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .build();
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        notification.flags |= Notification.FLAG_NO_CLEAR;
        notificationManager.notify(2, notification);

dependencies:

dependencies{
    implementation "com.android.support:support-compat:26.1.0"
}

Why I do this:
My app does 1 thing: toggle the screentimeout. So when you start it it sets the screentimeout to 30 minutes (starts, sets a notification, then finish()). Start again, it removes the notification and restore the original value for the screen timeout.

Body:
Starting with Android Oreo, all notifications require a notification channel, otherwise the notification wont post and an error will appear in your logcat. Here's an example of how you can do it, lifted from one of my apps:

private static void createNotificationChannel(Context ctx) {
    if(SDK_INT < O) return;

    final NotificationManager mgr = ctx.getSystemService(NotificationManager.class);
    if(mgr == null) return;

    final String name = ctx.getString(R.string.channel_name);
    if(mgr.getNotificationChannel(name) == null) {
        final NotificationChannel channel =
                new NotificationChannel(CHANNEL_ID, name, IMPORTANCE_DEFAULT);
        mgr.createNotificationChannel(channel);
    }
}

//Usage...
createNotificationChannel(context);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID);
builder.setSmallIcon(R.drawable.ic_alarm_white_24dp);
//etc...
manager.notify(id, builder.build());


来源: stackexchange

问:
How to find closest lower value in array angular 6?
I have an array of objects where I need to find closest lower value from that array based on some value or current value in angular 6, I have already tried but its showing undefined.

app.component.html

```<code><button (click) ="getPrev()">Previous Value</button>
</code>```

app.component.ts

```<code>declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
    arrayVal:any;
    currentVal : any;
  title = 'projectchart';
  public array = [{"id":1},{"id":3},{"id":5}];

  getPrev(){
     this.currentVal = 5;
     this.arrayVal= this.array;
     let number = this.arrayVal.reverse().find(e => e <= this.currentVal);
     console.log(number);
  }
}
</code>```

答:
You have id in your array so this -

```<code> let number = this.arrayVal.reverse().find(e => e.id <= this.currentVal);
</code>```

will not be undefined

ContentLicense: CC BY-SA 4.0

Body:
I have an array of objects where I need to find closest lower value from that array based on some value or current value in angular 6, I have already tried but its showing undefined.

app.component.html

<button (click) ="getPrev()">Previous Value</button>

app.component.ts

declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
    arrayVal:any;
    currentVal : any;
  title = 'projectchart';
  public array = [{"id":1},{"id":3},{"id":5}];

  getPrev(){
     this.currentVal = 5;
     this.arrayVal= this.array;
     let number = this.arrayVal.reverse().find(e => e <= this.currentVal);
     console.log(number);
  }
}

Body:
You have id in your array so this -

 let number = this.arrayVal.reverse().find(e => e.id <= this.currentVal);

will not be undefined


问:
Specified cast is not valid?
I have a table created in ASP.net and I want to populate the table with information from the database once the page has been loaded. I'm getting an error that the specified cast is not valid. What am I doing wrong?  Heres my code

```<code>public string getData()
{
        string htmlStr = "";

        SqlConnection conn = new SqlConnection(connString);
        SqlCommand command = conn.CreateCommand();
        command.CommandText = "SELECT * from INFO";
        conn.Open();
        SqlDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            DateTime Date = reader.GetDateTime(0);
            DateTime Time = reader.GetDateTime(1);
            htmlStr += "<tr><td>" + Date + "</td><td>"  + Time + "</td></tr>";
        }

        conn.Close();

        return htmlStr;
}
</code>```

```<code><table style="width:100%">
                <caption>INFO</caption>
                <tr>
                    <td> Date </td>
                    <td> Time </td>
                </tr>
                    <%=getData()%>
                </table>
</code>```

This is my error:

It is throwing the exception on this line from the above code:

```<code>DateTime Date = reader.GetDateTime(0);
</code>```

答:
Try this:</p>

```<code>public void LoadData()
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
            SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            DataGridView1.Rows.Clear();

        foreach (DataRow item in dt.Rows)
        {
            int n = DataGridView1.Rows.Add();
            DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
            DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
            DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();
            if ((bool)item["productstatus"])
            {
                DataGridView1.Rows[n].Cells[3].Value = "Active";
            }
            else
            {
                DataGridView1.Rows[n].Cells[3].Value = "Deactive";
            }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Specified cast is not valid?

Body:
I have a table created in ASP.net and I want to populate the table with information from the database once the page has been loaded. I'm getting an error that the specified cast is not valid. What am I doing wrong?  Heres my code

public string getData()
{
        string htmlStr = "";

        SqlConnection conn = new SqlConnection(connString);
        SqlCommand command = conn.CreateCommand();
        command.CommandText = "SELECT * from INFO";
        conn.Open();
        SqlDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            DateTime Date = reader.GetDateTime(0);
            DateTime Time = reader.GetDateTime(1);
            htmlStr += "
" + Date + "	"  + Time + "
";
        }

        conn.Close();

        return htmlStr;
}

INFO

                     Date
                     Time

                    <%=getData()%>

This is my error:

It is throwing the exception on this line from the above code:

DateTime Date = reader.GetDateTime(0);

Body:
Try this:

public void LoadData()
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
            SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            DataGridView1.Rows.Clear();

        foreach (DataRow item in dt.Rows)
        {
            int n = DataGridView1.Rows.Add();
            DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
            DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
            DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();
            if ((bool)item["productstatus"])
            {
                DataGridView1.Rows[n].Cells[3].Value = "Active";
            }
            else
            {
                DataGridView1.Rows[n].Cells[3].Value = "Deactive";
            }


问:
How to include external javascript functions
I am trying to refer a external javascript file by calling a function in that file as

```<code><script type="text/javascript" src="external.js">
display('hell0');
</script>
</code>```

But this code is not working. If i refer the file in separdate script tag it works fine.

```<code>    <script type="text/javascript" src="external.js"></script>
   <script type="text/javascript">
    display('hell0');
    </script>
</code>```

Why the first case is not working?

答:
If you use the src attribute to specify an external javascript file to be included you cannot have contents to this script tag. The second case is the correct way.

Quote from the specification:

The script may be defined within the
  contents of the SCRIPT element or in
  an external file. If the src attribute
  is not set, user agents must interpret
  the contents of the element as the
  script. If the src has a URI value,
  user agents must ignore the element's
  contents and retrieve the script via
  the URI

Body:
I am trying to refer a external javascript file by calling a function in that file as

But this code is not working. If i refer the file in separdate script tag it works fine.

Why the first case is not working?


问:
Custom keybinding in VSCode not working but selection from drop down menu does
I've set up shift+enter in VSCode to send a selected line(s) to a Python terminal. No other command is set to use shift+enter as its keybinding.

If I highlight some lines, right click, and select Run Selection/Line in Python Terminal, everything operates successfully. But when I try to use the specified keybinding (here shift+enter), the selection is disappeared by enter. No custom keybinding seems to send the selection to the Python terminal.

I don't understand what's causing this behavior and my knowledge of VSCode as anything other than a user is fairly limited. The custom keybinding exists in my keybindings.json file as

```<code>{
        "key": "shift+enter",
        "command": "python.execSelectionInTerminal",
        "when": "editorFocus && !findInputFocussed && !python.datascience.ownsSelection && !replaceInputFocussed && editorLangId == 'python'"
    }
</code>```

答:
The entries into keybindings.json override the VS code defaults. Try deleting your entry and it should revert to the default behaviour, which does what you're looking for.

Due to the entries in your "when" key, it looks as though you're trying to do interactive data science. If that is your goal, instead/also try:

In VS Code Settings, find and enable:
Python > Data Science: Send Selection To Interactive Window

Determines if selected code in a python file will go to the terminal or the Python interactive window when hitting shift+enter

 Data Science: Send Selection To Interactive Window">

Body:
I've set up shift+enter in VSCode to send a selected line(s) to a Python terminal. No other command is set to use shift+enter as its keybinding.

If I highlight some lines, right click, and select Run Selection/Line in Python Terminal, everything operates successfully. But when I try to use the specified keybinding (here shift+enter), the selection is disappeared by enter. No custom keybinding seems to send the selection to the Python terminal.

I don't understand what's causing this behavior and my knowledge of VSCode as anything other than a user is fairly limited. The custom keybinding exists in my keybindings.json file as

{
        "key": "shift+enter",
        "command": "python.execSelectionInTerminal",
        "when": "editorFocus && !findInputFocussed && !python.datascience.ownsSelection && !replaceInputFocussed && editorLangId == 'python'"
    }


答:
Now from Android 8.0 and onward you need to create notification channel before showing notifications. Here is the Docs link

https://developer.android.com/training/notify-user/channels

Title: permanent notification does not show


问:
Eager Mode: Using Sequentials within tf.keras.Model
I am transitioning from Pytorch to TensorFlow 1.12 and would like to know whether it is possible to define tf.keras.Sequential classes within a tf.keras.Model and run those in eager mode.

I constructed this minimum non-working example and would be grateful if someone could advise where I am going wrong. I have also used tf.contrib.eager.Network classes (with more success) however, since they are scheduled for deprecation I tried avoiding those.

import numpy as np
import tensorflow as tf
import tensorflow.contrib.eager as tfe
from keras.models import Sequential
from keras.layers import Dense, Activation
from tensorflow.train import AdamOptimizer

tf.enable_eager_execution()

class MLP(tf.keras.Model):
    def __init__(self, in_dim, out_dim, hidden_dim, num_layers, activation):
        super(MLP, self).__init__()
        model = Sequential()
        in_features = in_dim
        for layer in range(num_layers):
            model.add(Dense(hidden_dim,))
            model.add(Activation(activation))
            in_features = hidden_dim
        model.add(Dense(out_dim, input_shape=(hidden_dim,)))
        self.model = model

    def call(self, inputs):
        return self.model(inputs)

model = MLP(10, 1, 20, 4, 'relu')

optim = AdamOptimizer(learning_rate=1e-4)

for v in model.variables:
    print(v)

z = tf.convert_to_tensor(np.random.randn(100, 10), dtype=tf.float32)
with tfe.GradientTape() as tape:
    tape.watch(z)
    u = model(z)
    loss = tf.reduce_mean(tf.abs(u))
grad = tape.gradient(loss, model.trainable_variables)
optim.apply_gradients(zip(grad, model.trainable_variables))
print(loss.numpy())
```

答:
Use

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation

instead of:

from keras.models import Sequential
from keras.layers import Dense, Activation


问:
How to fix: Doctrine not returning properly
I want to make dynamic delete posts function but the result is error because value is null.

Controller

```<code>/**
  * @Route("/posts/delete/{id}", name="delete_post", methods={"DELETE"})
  */
  public function deletePost($id, LoggerInterface $logger)
  {

    $post=$this->getDoctrine()->getRepository(Article::class)->find($id);

    if(!$post)
    {
        $this->addFlash(
            'notice',
            'Something went wrong'
        );
        $logger->info($id);
    }
    else
    {

        $entityManager=$this->getDoctrine()->getManager();
        $entityManager->remove($post);
        $entityManager->flush();
        $entityManager->clear();
    }

    $response=new Response();
    return($response);
  }
</code>```

JS

```<code>const articles = document.getElementById("articles");

if (articles) {
 articles.addEventListener("click", e => {
  if (e.target.className === "btn btn-danger delete-article") {
  if (confirm("Are you sure?")) {
    const id = e.target.getAttribute("data-id");

    fetch("/posts/delete/${id}", {
      method: "DELETE"
    }).then(res => window.location.reload());
  }
 }
 });
}
</code>```

Twig

```<code><table border="1" id="articles">
        <tr>
            <th class="pt">Post title</th>
            <th class="pe">Edit</th>
            <th class="pd">Delete</th>
        </tr>
        {% for article in articles %}
            <tr>
                <td class="title">{{ article.title }}</td>
                <td class="edit">
                    <a href="{{ path('posts_editor', {'id':article.id}) }}" class="btn btn-primary edit-article">
                        <img src="{{ asset('images/edit.png') }}" class="image">
                    </a>
                </td>
                <td class="delete">
                    <a href="#" class="btn btn-danger delete-article" data-id="{{article.id}}">
                        <img src="{{ asset('images/delete.png') }}" class="image">
                    </a>
                </td>
            </tr>
        {% endfor %}
    </table>
</code>```

I was doing it with video tutorial and I don't know what is wrong on video this code was working but when I wrote it I just got an error below

Error

EntityManager#remove() expects parameter 1 to be an entity object, NULL given.

Hope anyone can help me, I am really getting frustrated because of it is not working.

答:
It's clearly said that $post is null, so in this case, you can
dump this two variable and I hope you will figure it out what's going on

```<code>dump($id);
dump($post);
exit
</code>```

you can the see doc Doctrine Removing entities

updated:

in your code, you are always sending a response, you need to update response to specific with success or error code by default it is sending 200 code and also you to need to update your code

```<code>public function deletePost($id, LoggerInterface $logger)
{

$post=$this->getDoctrine()->getRepository(Article::class)->find($id);

    if(!$post)
    {
        $this->addFlash(
            'notice',
            'Something went wrong'
        );
        $logger->info($id);

        exit() your code here
        or throw an exception here
    }

    try {
        //remove entity here
        $response = new Response(
            'Content',
            Response::HTTP_OK,
            ['content-type' => 'text/html']
        );

        return $response;
    } catch (\Exception $exception) {
        $response = new Response(
            $exception->getMessage(),
            Response::HTTP_INTERNAL_SERVER_ERROR,
            ['content-type' => 'text/html']
            );
        return $response;
    }
}
</code>```

Body:
I want to make dynamic delete posts function but the result is error because value is null.

Controller

/**
  * @Route("/posts/delete/{id}", name="delete_post", methods={"DELETE"})
  */
  public function deletePost($id, LoggerInterface $logger)
  {

    $post=$this->getDoctrine()->getRepository(Article::class)->find($id);

    if(!$post)
    {
        $this->addFlash(
            'notice',
            'Something went wrong'
        );
        $logger->info($id);
    }
    else
    {

        $entityManager=$this->getDoctrine()->getManager();
        $entityManager->remove($post);
        $entityManager->flush();
        $entityManager->clear();
    }

    $response=new Response();
    return($response);
  }

JS

const articles = document.getElementById("articles");

if (articles) {
 articles.addEventListener("click", e => {
  if (e.target.className === "btn btn-danger delete-article") {
  if (confirm("Are you sure?")) {
    const id = e.target.getAttribute("data-id");

    fetch("/posts/delete/${id}", {
      method: "DELETE"
    }).then(res => window.location.reload());
  }
 }
 });
}

Twig

            Post title
            Edit
            Delete

        {% for article in articles %}

                {{ article.title }}

        {% endfor %}

I was doing it with video tutorial and I don't know what is wrong on video this code was working but when I wrote it I just got an error below

Error

EntityManager#remove() expects parameter 1 to be an entity object, NULL given.

Hope anyone can help me, I am really getting frustrated because of it is not working.

Body:
It's clearly said that $post is null, so in this case, you can
dump this two variable and I hope you will figure it out what's going on

dump($id);
dump($post);
exit

you can the see doc Doctrine Removing entities

updated:

in your code, you are always sending a response, you need to update response to specific with success or error code by default it is sending 200 code and also you to need to update your code

public function deletePost($id, LoggerInterface $logger)
{

$post=$this->getDoctrine()->getRepository(Article::class)->find($id);

    if(!$post)
    {
        $this->addFlash(
            'notice',
            'Something went wrong'
        );
        $logger->info($id);

        exit() your code here
        or throw an exception here
    }

    try {
        //remove entity here
        $response = new Response(
            'Content',
            Response::HTTP_OK,
            ['content-type' => 'text/html']
        );

        return $response;
    } catch (\Exception $exception) {
        $response = new Response(
            $exception->getMessage(),
            Response::HTTP_INTERNAL_SERVER_ERROR,
            ['content-type' => 'text/html']
            );
        return $response;
    }
}


问:
For a shared resource accessed by two threads, how to arrange priority?
Is there a way to give one thread priority over another when accessing the resource?</p>

答:
use the following code in thread class

```<code>Thread threadB = new Thread(makeRunnable(), "threadB");
threadB.setPriority(2);
</code>```

or visit link below
http://www.java2s.com/Code/Java/Threads/SetThreadPriority.htm

Body:
use the following code in thread class

Thread threadB = new Thread(makeRunnable(), "threadB");
threadB.setPriority(2);

or visit link below
http://www.java2s.com/Code/Java/Threads/SetThreadPriority.htm


问:
basinhopping_bounds() got an unexpected keyword argument 'f_new'
I'm getting this error when using basin-hopping:
basinhopping_bounds() got an unexpected keyword argument 'f_new'

I'm trying to implement the analysis of X,F models in Python to solving a DTLZ7 problem.

So, I've started with a problem with 4 linear FO, which the result I know. When trying to solve the problem using basin-hopping for global minimization, I'm getting the error above (scipy-1.2.1.). Does anybody knows what is going wrong?

Here follows part of the code:

f1 = f_linear([0.06, 0.53, 0.18, 0.18, 0.06], "max")
f2 = f_linear([25, 70, 60, 95, 45], "max")
f3 = f_linear([0, 32.5, 300, 120, 0], "min")
f4 = f_linear([0.1, 0.1, 0.11, 0.35, 0.33], "min")
```

<pre class="lang-py prettyprint-override"><code>A_eq = np.array([[1, 1, 1, 1, 1]])
b_eq = np.array([3000])
x0_bounds = (0, 850)
x1_bounds = (0, 220)
x2_bounds = (0, 1300)
x3_bounds = (0, 1615)
x4_bounds = (0, 700)
F = [f1, f2, f3, f4]
</code>```

def mu_D(x, F):
    x = np.array(x)
    return max([f_.mu(x) for f_ in F])
```

<pre class="lang-py prettyprint-override"><code>def basinhopping_bounds(x):
    resp = True
    if np.dot(x, A_eq[0]) != b_eq[0]:
        resp = False
    if x[0] < x0_bounds[0] or x[0] > x0_bounds[1]:
        resp = False
    if x[1] < x1_bounds[0] or x[1] > x1_bounds[1]:
        resp = False
    if x[2] < x2_bounds[0] or x[2] > x2_bounds[1]:
        resp = False
    if x[3] < x3_bounds[0] or x[3] > x3_bounds[1]:
        resp = False
    if x[4] < x4_bounds[0] or x[4] > x4_bounds[1]:
        resp = False
    return resp

cobyla_constraints = [
    {"type": "ineq", "fun": lambda x: x[0]},
    {"type": "ineq", "fun": lambda x: x0_bounds[1] - x[0]},
    {"type": "ineq", "fun": lambda x: x[1]},
    {"type": "ineq", "fun": lambda x: x1_bounds[1] - x[1]},
    {"type": "ineq", "fun": lambda x: x[2]},
    {"type": "ineq", "fun": lambda x: x2_bounds[1] - x[2]},
    {"type": "ineq", "fun": lambda x: x[3]},
    {"type": "ineq", "fun": lambda x: x3_bounds[1] - x[3]},
    {"type": "ineq", "fun": lambda x: x[4]},
    {"type": "ineq", "fun": lambda x: x4_bounds[1] - x[4]},
    {"type": "eq", "fun": lambda x: np.dot(x, A_eq[0]) - b_eq[0]},
]
</code>```

minimizer_kwargs = {"args": F, "method": "SLSQP", "constraints": cobyla_constraints}
opt.basinhopping(
    mu_D,
    f1.x_max,
    minimizer_kwargs=minimizer_kwargs,
    accept_test=basinhopping_bounds,
    disp=True,
)
```

```basinhopping step 0: f 1

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-ba4f3efaec5d> in <module>
      5     minimizer_kwargs=minimizer_kwargs,
      6     accept_test=basinhopping_bounds,
----> 7     disp=True,
      8 )

~/anaconda3/lib/python3.6/site-packages/scipy/optimize/_basinhopping.py in basinhopping(func, x0, niter, T, stepsize, minimizer_kwargs, take_step, accept_test, callback, interval, disp, niter_success, seed)
    674                " successfully"]
    675     for i in range(niter):
--> 676         new_global_min = bh.one_cycle()
    677
    678         if callable(callback):

~/anaconda3/lib/python3.6/site-packages/scipy/optimize/_basinhopping.py in one_cycle(self)
    152         new_global_min = False
    153
--> 154         accept, minres = self._monte_carlo_step()
    155
    156         if accept:

~/anaconda3/lib/python3.6/site-packages/scipy/optimize/_basinhopping.py in _monte_carlo_step(self)
    127         for test in self.accept_tests:
    128             testres = test(f_new=energy_after_quench, x_new=x_after_quench,
--> 129                            f_old=self.energy, x_old=self.x)
    130             if testres == 'force accept':
    131                 accept = True

TypeError: basinhopping_bounds() got an unexpected keyword argument 'f_new'

```

答:
Your bounds definition is incorrect. In basinhopping your bounds should be defined as a class instance. You should use the following:

import numpy as np
import scipy.optimize as opt

class MyBounds(object):
    '''
    bounds class to make sure your variable is with in the inspected bounds
    '''
    def __init__(self, xmin, xmax):
        self.xmax = np.array(xmax)
        self.xmin = np.array(xmin)

    def __call__(self, **kwargs):
        x = kwargs["x_new"]
        tmax = bool(np.all(x <= self.xmax))
        tmin = bool(np.all(x >= self.xmin))
        return tmax and tmin

# init bounds
lower_bounds = [  0,   0,    0,    0,   0]
upper_bounds = [850, 220, 1300, 1615, 700]
my_bounds    = MyBounds(lower_bounds, upper_bounds)

...

# optimize
result = opt.basinhopping(mu_D,
                          f1.x_max,
                          minimizer_kwargs = minimizer_kwargs,
                          accept_test      = my_bounds,
                          disp             = True)
```

Also consider merging your constraints. If you use arrays instead of element-wise constraints, you will only have three constraints. However, looking at your constraints (with exception to the last one) you are just defining your boundaries again.

Body:
I'm getting this error when using basin-hopping:
basinhopping_bounds() got an unexpected keyword argument 'f_new'

I'm trying to implement the analysis of X,F models in Python to solving a DTLZ7 problem.

So, I've started with a problem with 4 linear FO, which the result I know. When trying to solve the problem using basin-hopping for global minimization, I'm getting the error above (scipy-1.2.1.). Does anybody knows what is going wrong?

Here follows part of the code:

f1 = f_linear([0.06, 0.53, 0.18, 0.18, 0.06], "max")
f2 = f_linear([25, 70, 60, 95, 45], "max")
f3 = f_linear([0, 32.5, 300, 120, 0], "min")
f4 = f_linear([0.1, 0.1, 0.11, 0.35, 0.33], "min")

A_eq = np.array([[1, 1, 1, 1, 1]])
b_eq = np.array([3000])
x0_bounds = (0, 850)
x1_bounds = (0, 220)
x2_bounds = (0, 1300)
x3_bounds = (0, 1615)
x4_bounds = (0, 700)
F = [f1, f2, f3, f4]

def mu_D(x, F):
    x = np.array(x)
    return max([f_.mu(x) for f_ in F])

def basinhopping_bounds(x):
    resp = True
    if np.dot(x, A_eq[0]) != b_eq[0]:
        resp = False
    if x[0] < x0_bounds[0] or x[0] > x0_bounds[1]:
        resp = False
    if x[1] < x1_bounds[0] or x[1] > x1_bounds[1]:
        resp = False
    if x[2] < x2_bounds[0] or x[2] > x2_bounds[1]:
        resp = False
    if x[3] < x3_bounds[0] or x[3] > x3_bounds[1]:
        resp = False
    if x[4] < x4_bounds[0] or x[4] > x4_bounds[1]:
        resp = False
    return resp

cobyla_constraints = [
    {"type": "ineq", "fun": lambda x: x[0]},
    {"type": "ineq", "fun": lambda x: x0_bounds[1] - x[0]},
    {"type": "ineq", "fun": lambda x: x[1]},
    {"type": "ineq", "fun": lambda x: x1_bounds[1] - x[1]},
    {"type": "ineq", "fun": lambda x: x[2]},
    {"type": "ineq", "fun": lambda x: x2_bounds[1] - x[2]},
    {"type": "ineq", "fun": lambda x: x[3]},
    {"type": "ineq", "fun": lambda x: x3_bounds[1] - x[3]},
    {"type": "ineq", "fun": lambda x: x[4]},
    {"type": "ineq", "fun": lambda x: x4_bounds[1] - x[4]},
    {"type": "eq", "fun": lambda x: np.dot(x, A_eq[0]) - b_eq[0]},
]

minimizer_kwargs = {"args": F, "method": "SLSQP", "constraints": cobyla_constraints}
opt.basinhopping(
    mu_D,
    f1.x_max,
    minimizer_kwargs=minimizer_kwargs,
    accept_test=basinhopping_bounds,
    disp=True,
)

basinhopping step 0: f 1

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-ba4f3efaec5d> in <module>
      5     minimizer_kwargs=minimizer_kwargs,
      6     accept_test=basinhopping_bounds,
----> 7     disp=True,
      8 )

~/anaconda3/lib/python3.6/site-packages/scipy/optimize/_basinhopping.py in basinhopping(func, x0, niter, T, stepsize, minimizer_kwargs, take_step, accept_test, callback, interval, disp, niter_success, seed)
    674                " successfully"]
    675     for i in range(niter):
--> 676         new_global_min = bh.one_cycle()
    677
    678         if callable(callback):

~/anaconda3/lib/python3.6/site-packages/scipy/optimize/_basinhopping.py in one_cycle(self)
    152         new_global_min = False
    153
--> 154         accept, minres = self._monte_carlo_step()
    155
    156         if accept:

~/anaconda3/lib/python3.6/site-packages/scipy/optimize/_basinhopping.py in _monte_carlo_step(self)
    127         for test in self.accept_tests:
    128             testres = test(f_new=energy_after_quench, x_new=x_after_quench,
--> 129                            f_old=self.energy, x_old=self.x)
    130             if testres == 'force accept':
    131                 accept = True

TypeError: basinhopping_bounds() got an unexpected keyword argument 'f_new'

Body:
Your bounds definition is incorrect. In basinhopping your bounds should be defined as a class instance. You should use the following:

import numpy as np
import scipy.optimize as opt

class MyBounds(object):
    '''
    bounds class to make sure your variable is with in the inspected bounds
    '''
    def __init__(self, xmin, xmax):
        self.xmax = np.array(xmax)
        self.xmin = np.array(xmin)

    def __call__(self, **kwargs):
        x = kwargs["x_new"]
        tmax = bool(np.all(x <= self.xmax))
        tmin = bool(np.all(x >= self.xmin))
        return tmax and tmin

# init bounds
lower_bounds = [  0,   0,    0,    0,   0]
upper_bounds = [850, 220, 1300, 1615, 700]
my_bounds    = MyBounds(lower_bounds, upper_bounds)

...

# optimize
result = opt.basinhopping(mu_D,
                          f1.x_max,
                          minimizer_kwargs = minimizer_kwargs,
                          accept_test      = my_bounds,
                          disp             = True)

Also consider merging your constraints. If you use arrays instead of element-wise constraints, you will only have three constraints. However, looking at your constraints (with exception to the last one) you are just defining your boundaries again.


问:
Why is script.js in localhost different from the script.js in the root directory
I'm setting up a localhost server and I have 2 files in the root directory, script.js and padding.html. The html file directly references the script.js file. when i set up the localhost site with php -S localhost:8000 padding.html, the content of the script.js file becomes the content of the padding.html file.

I've tried re-saving my work in my code editor, resetting the server and reloading the page.

script.js

```<code>function getValue (id) {
    text = document.getElementById(id).value; //value of the text input
    alert(text);
    return false;
}
</code>```

padding.html

```<code><!DOCTYPE html>
<html>
    <title>javatest</title>
    <script src = script.js></script>
    <body>
        <div class="entry foreground-color">
            <form onsubmit="return getValue('commands')">
                <input type="text" name="commands" size="60"/>
            </form>
        </div>
    </body>

</html>
</code>```

run the server then go to inspect element then the console, and an error comes up saying Uncaught SyntaxError: Unexpected token <
clicking on it then brings you to the 'script.js' file, which is just a copy of the padding.html file with a different name. This file should be the script.js file shown above

答: In padding.html, you appear to have a syntax error that would cause that to appear in the console. Replace  with  (note the added quotation marks).

Body:
I'm setting up a localhost server and I have 2 files in the root directory, script.js and padding.html. The html file directly references the script.js file. when i set up the localhost site with php -S localhost:8000 padding.html, the content of the script.js file becomes the content of the padding.html file.

I've tried re-saving my work in my code editor, resetting the server and reloading the page.

script.js

function getValue (id) {
    text = document.getElementById(id).value; //value of the text input
    alert(text);
    return false;
}

padding.html

<!DOCTYPE html>

    <title>javatest</title>

            <form onsubmit="return getValue('commands')">
                <input type="text" name="commands" size="60"/>
            </form>

run the server then go to inspect element then the console, and an error comes up saying Uncaught SyntaxError: Unexpected token <
clicking on it then brings you to the 'script.js' file, which is just a copy of the padding.html file with a different name. This file should be the script.js file shown above

Body: In padding.html, you appear to have a syntax error that would cause that to appear in the console. Replace <script src = script.js></script> with <script src="script.js"></script> (note the added quotation marks).


问:
regarding two dimensional arrays
if i have created an array like
int marks[4][2];
then the name of the array must give me the address of the first element,as is in case of one dimensional array,but it is not so?
& also

printf("%d",marks[0]);
&
printf("%d",marks);
 yield the same result?????????

答:
In C , for example A 2D array is treated as a 1D array whose elements are 1D arrays.So if you want to get the address of any of the elements you will have to use

printf("%8u\n",&a[i][j]);

Both the print statements print the same result because both marks and marks[0] are pointing to the starting of the first row of the two dimensional array.

Title: regarding two dimensional arrays


问:
button href is ignoring everything after question mark
I have this button

```<code><button href="account.html?gto=4356">go to</button>
</code>```

On click it redirects to ./account.html?# though i was expecting ./account.html?gto=4356.

Why is it ignoring everything after the question mark and how can I make this work?

答:
You can do it with Javascript</p>

```<code><button onclick='goto()'>go to</button>
<script>
function goto(){
location.replace("account.html?gto=4356");
}
</script>
</code>```

Body:
I have this button

<button href="account.html?gto=4356">go to</button>

On click it redirects to ./account.html?# though i was expecting ./account.html?gto=4356.

Why is it ignoring everything after the question mark and how can I make this work?

Body:
You can do it with Javascript

<button onclick='goto()'>go to</button>
<script>
function goto(){
location.replace("account.html?gto=4356");
}
</script>


问:
How to set prefered view resolution when mixing GSP and JSON views
I'm maintaining a grails 3.3.8 app using the angularjs profile.

The REST API and angularjs assets are provided by the same grails application. For now I don't want to split the app into two applications.

The app uses JSON views to render the JSON response for the resources.
The app also uses the GSP view plugin to provide the initial index.gsp to serve the angularjs app.

Due to the usage of the GSP view plugin the app always renders the default gsp error views instead of using the JSON views in case of 500, 404, 401, ... errors.

When I remove the grails-gsp plugin, all request are served with a JSON response. Also in case of an error. But then the index.gsp can't be rendered.

Is it possible to tell the grails app that it should use the JSON views by default and just in case of the index it should use the gsp view?

Update:
I would like to render views directly from URLMapping without creating a controller.

答:
Is it possible to tell the grails app that it should use the JSON
  views by default and just in case of the index it should use the gsp
  view?

Yes.  You can serve many different view types from the same app, including GSON Views working along side GSP Views.

See the project at https://github.com/jeffbrown/webjsonviews.

If you run that app and send a request to http://localhost:8080/person/index with your browser, you will see HTML rendered which was server side rendered using GSP.

If you send a request to http://localhost:8080/person/index.json with your browser, you will see the JSON rendered using GSON Views.

This will render HTML:

```<code>curl http://localhost:8080/person/index
</code>```

This will render JSON:

```<code>curl http://localhost:8080/person/index.json
</code>```

This will render JSON:

```<code>curl -H "Accept: application/json" http://localhost:8080/person/index
</code>```

If you would like the default content type to be application/json, you can add the following to the PersonController:

```<code>static responseFormats = ['json', 'html']
</code>```

That will cause the following to return JSON instead of HTML:

```<code>curl http://localhost:8080/person/index
</code>```

I hope that helps.

Body:
Is it possible to tell the grails app that it should use the JSON
  views by default and just in case of the index it should use the gsp
  view?

Yes.  You can serve many different view types from the same app, including GSON Views working along side GSP Views.

See the project at https://github.com/jeffbrown/webjsonviews.

If you run that app and send a request to http://localhost:8080/person/index with your browser, you will see HTML rendered which was server side rendered using GSP.

If you send a request to http://localhost:8080/person/index.json with your browser, you will see the JSON rendered using GSON Views.

This will render HTML:

curl http://localhost:8080/person/index

This will render JSON:

curl http://localhost:8080/person/index.json

This will render JSON:

curl -H "Accept: application/json" http://localhost:8080/person/index

If you would like the default content type to be application/json, you can add the following to the PersonController:

static responseFormats = ['json', 'html']

That will cause the following to return JSON instead of HTML:

curl http://localhost:8080/person/index

I hope that helps.


问:
Problem of FATAL EXCEPTION: main in Android application when starting execution

android.view.InflateException: Binary XML file line #2

The error tells me that it is a fatal error in the main method but I have a splash and it runs perfect is until it enters the main and stops

Error Screenshot

This is the XML

```<code>    < ?xml version="1.0" encoding="utf-8"? >
    <androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android`="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/fondo"
    tools:context="menu.MainActivity">

<Button
    android:id="@+id/lisaid"
    android:layout_width="225dp"
    android:layout_height="63dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="100dp"
    android:background="@drawable/fondoet"
    android:onClick="listar"
    android:text="@string/listar"
    android:textColor="@color/colorPrimaryDark"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.588"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/listar" />

<Button
    android:id="@+id/consultar"
    android:layout_width="225dp"
    android:layout_height="63dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="32dp"
    android:background="@drawable/fondoet"
    android:onClick="consulta"
    android:text="@string/CONSULTA"
    android:textColor="@color/colorPrimaryDark"
    app:layout_constraintBottom_toTopOf="@+id/lisaid"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.588"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/CONSULTA" />

<Button
    android:id="@+id/crear"
    android:layout_width="225dp"
    android:layout_height="63dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="32dp"
    android:background="@drawable/fondoet"
    android:onClick="ejecucion"
    android:text="@string/CREAR"
    android:textColor="@color/colorPrimaryDark"
    app:layout_constraintBottom_toTopOf="@+id/consultar"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.588"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/CREAR" />

<TextView
    android:id="@+id/textView9"
    android:layout_width="338dp"
    android:layout_height="64dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/fondoet"
    android:gravity="center"
    android:text="@string/BIENVENIDO"
    android:textColor="@color/colorPrimaryDark"
    android:textColorHighlight="@color/colorPrimary"
    android:textSize="36sp"
    app:layout_constraintBottom_toTopOf="@+id/textView10"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:text="@string/BIENVENIDO" />

<TextView
    android:id="@+id/textView10"
    android:layout_width="322dp"
    android:layout_height="72dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="30dp"
    android:background="@drawable/fondoet"
    android:gravity="center"
    android:text="@string/datos"
    android:textColor="@color/colorPrimaryDark"
    android:textColorHighlight="@color/colorPrimary"
    android:textSize="18sp"
    app:layout_constraintBottom_toTopOf="@+id/crear"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.627"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/datos" />
</code>```

and here is the class

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

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

        AdminSQLiteOpenHelper conn=new AdminSQLiteOpenHelper(this,"bd_usuarios",null,1);
    }

    public void ejecucion (View view)
    {
        Intent miintent= null;
        switch(view.getId())
        {
            case R.id.crear:miintent=new Intent(MainActivity.this,Ejecucion.class);
            break;
        }
        if (miintent!=null)
        {
            startActivity(miintent);
        }

    }
    public void consulta (View view)
    {
        Intent miintent= null;
        switch(view.getId())
        {
            case R.id.consultar:miintent=new Intent(MainActivity.this,consulta1.class);
                break;
        }
        if (miintent!=null)
        {
            startActivity(miintent);
        }
    }
    public void listar (View view)
    {
        Intent miintent= null;
        switch(view.getId())
        {
            case R.id.lisaid:miintent=new Intent(MainActivity.this, listausuarios.class);

        }
        if (miintent!=null)
        {
            startActivity(miintent);
        }
    }
}
</code>```

I'm using a SQL database, but it was working well, I do not know what happens.

答:
Please change these first 2 lines to </p>

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
......
</code>```

Body:
android.view.InflateException: Binary XML file line #2

The error tells me that it is a fatal error in the main method but I have a splash and it runs perfect is until it enters the main and stops

Error Screenshot

This is the XML

    < ?xml version="1.0" encoding="utf-8"? >
    <androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android`="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/fondo"
    tools:context="menu.MainActivity">

<Button
    android:id="@+id/lisaid"
    android:layout_width="225dp"
    android:layout_height="63dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="100dp"
    android:background="@drawable/fondoet"
    android:onClick="listar"
    android:text="@string/listar"
    android:textColor="@color/colorPrimaryDark"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.588"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/listar" />

<Button
    android:id="@+id/consultar"
    android:layout_width="225dp"
    android:layout_height="63dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="32dp"
    android:background="@drawable/fondoet"
    android:onClick="consulta"
    android:text="@string/CONSULTA"
    android:textColor="@color/colorPrimaryDark"
    app:layout_constraintBottom_toTopOf="@+id/lisaid"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.588"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/CONSULTA" />

<Button
    android:id="@+id/crear"
    android:layout_width="225dp"
    android:layout_height="63dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="32dp"
    android:background="@drawable/fondoet"
    android:onClick="ejecucion"
    android:text="@string/CREAR"
    android:textColor="@color/colorPrimaryDark"
    app:layout_constraintBottom_toTopOf="@+id/consultar"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.588"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/CREAR" />

<TextView
    android:id="@+id/textView9"
    android:layout_width="338dp"
    android:layout_height="64dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/fondoet"
    android:gravity="center"
    android:text="@string/BIENVENIDO"
    android:textColor="@color/colorPrimaryDark"
    android:textColorHighlight="@color/colorPrimary"
    android:textSize="36sp"
    app:layout_constraintBottom_toTopOf="@+id/textView10"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:text="@string/BIENVENIDO" />

<TextView
    android:id="@+id/textView10"
    android:layout_width="322dp"
    android:layout_height="72dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="30dp"
    android:background="@drawable/fondoet"
    android:gravity="center"
    android:text="@string/datos"
    android:textColor="@color/colorPrimaryDark"
    android:textColorHighlight="@color/colorPrimary"
    android:textSize="18sp"
    app:layout_constraintBottom_toTopOf="@+id/crear"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.627"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/datos" />

and here is the class

    public class MainActivity extends AppCompatActivity
{

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

        AdminSQLiteOpenHelper conn=new AdminSQLiteOpenHelper(this,"bd_usuarios",null,1);
    }

    public void ejecucion (View view)
    {
        Intent miintent= null;
        switch(view.getId())
        {
            case R.id.crear:miintent=new Intent(MainActivity.this,Ejecucion.class);
            break;
        }
        if (miintent!=null)
        {
            startActivity(miintent);
        }

    }
    public void consulta (View view)
    {
        Intent miintent= null;
        switch(view.getId())
        {
            case R.id.consultar:miintent=new Intent(MainActivity.this,consulta1.class);
                break;
        }
        if (miintent!=null)
        {
            startActivity(miintent);
        }
    }
    public void listar (View view)
    {
        Intent miintent= null;
        switch(view.getId())
        {
            case R.id.lisaid:miintent=new Intent(MainActivity.this, listausuarios.class);

        }
        if (miintent!=null)
        {
            startActivity(miintent);
        }
    }
}

I'm using a SQL database, but it was working well, I do not know what happens.

Body:
Please change these first 2 lines to

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
......


问:
What is the most elegant way to cast a variable you just received as an argument?
More specifically, what's the most elegant way to cast the Graphics object in a paint() call up to a Graphics2D object?

```<code>public void paint(Graphics g) {
    // How do I convert/cast/etc the g variable to a Graphics2D object?
}
</code>```

Or am I missing the point here? Is there a better way to handle this in general?

答:
As far as I know, you can't do much in this situation.
You can validate that you actually got a Graphics2D object before casting. But, as far as I know, you can get anything else anyway.</p>

OwnerDisplayName: spligak

ContentLicense: CC BY-SA 2.5

Body:
More specifically, what's the most elegant way to cast the Graphics object in a paint() call up to a Graphics2D object?

public void paint(Graphics g) {
    // How do I convert/cast/etc the g variable to a Graphics2D object?
}

Or am I missing the point here? Is there a better way to handle this in general?

OwnerDisplayName: Untrots


问:
Calling procedure in function
Can you call a PL/SQL procedure from inside a function?

I haven't come across with the practical example.So if anyone has come across with this please share.

答:
Here you go:</p>

```<code>create or replace function demo
    return varchar2
as
begin
    dbms_output.put_line('Hello');
    return 1;
end demo;
</code>```

Title: Calling procedure in function

Body:
Here you go:

create or replace function demo
    return varchar2
as
begin
    dbms_output.put_line('Hello');
    return 1;
end demo;


问:
XSLT: What is the best way to apply a floating text that will display the full expression for acronyms from an external dictionary file?
I'm new to XSLT.

I need to apply floating text that displays a setting for acronyms, as soon as the mouse cursor hovers over a word that is abbreviated.

My input file is XML, and every word that should display acronyms is represented in the following format:

```<code>    <abbreviation Id="E.G."/>
</code>```

When the mouse cursor hovers over the word EG, the floating text will be displayed: "for example".

I thought to apply the floating text using the HTML abbr tag
And the code I wrote is:

```<code>    <xsl:template match="abbreviation">
        <abbr title="for example.">
            <xsl:value-of select="@Id"/>
        </abbr>
    </xsl:template>
</code>```

I want the "title" attribute to be given as a parameter the definition of the main boxes from an external file that will contain a dictionary of related abbreviations and explanations.

I would love to know how to apply my issue.

And also get ideas about the external dictionary file - what kind of file should you create? For example, I would like a good structure of the file.

Note:
I use OXYGEN EDITOR,
And I believe I can also get solutions in XSLT version 2 and 3

答:
Suppose your external dictionary looks like:

dict.xml

```<code><dictionary>
    <entry abbr="C.V.">course of life</entry>
    <entry abbr="E.G.">for example</entry>
    <entry abbr="N.B.">note well</entry>
</dictionary>
</code>```

You can then use a key to transform an input like:

XML

```<code><root>
    <abbreviation Id="E.G."/>
</root>
</code>```

using:

XSLT 2.0 (untested)

```<code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:param name="path-to-dictionary" select="'dict.xml'"/>
<xsl:key name="abbr-lookup" match="entry" use="@abbr" />

<xsl:template match="/root">
    <html>
        <body>
            <xsl:apply-templates/>
        </body>
    </html>
</xsl:template>

<xsl:template match="abbreviation">
    <abbr title="{key('abbr-lookup', @Id, document($path-to-dictionary))}">
        <xsl:value-of select="@Id"/>
    </abbr>
</xsl:template>

</xsl:stylesheet>
</code>```

to get:

Result

```<code><html>
    <body>
        <abbr title="for example">E.G.</abbr>
    </body>
</html>
</code>```

To understand the syntax used, read about Attribute Value Templates.

Body:
I'm new to XSLT.

I need to apply floating text that displays a setting for acronyms, as soon as the mouse cursor hovers over a word that is abbreviated.

My input file is XML, and every word that should display acronyms is represented in the following format:

    <abbreviation Id="E.G."/>

When the mouse cursor hovers over the word EG, the floating text will be displayed: "for example".

I thought to apply the floating text using the HTML abbr tag
And the code I wrote is:

    <xsl:template match="abbreviation">

            <xsl:value-of select="@Id"/>

    </xsl:template>

I want the "title" attribute to be given as a parameter the definition of the main boxes from an external file that will contain a dictionary of related abbreviations and explanations.

I would love to know how to apply my issue.

And also get ideas about the external dictionary file - what kind of file should you create? For example, I would like a good structure of the file.

Note:
I use OXYGEN EDITOR,
And I believe I can also get solutions in XSLT version 2 and 3

Body:
Suppose your external dictionary looks like:

dict.xml

<dictionary>
    <entry abbr="C.V.">course of life</entry>
    <entry abbr="E.G.">for example</entry>
    <entry abbr="N.B.">note well</entry>
</dictionary>

You can then use a key to transform an input like:

XML

<root>
    <abbreviation Id="E.G."/>
</root>

using:

XSLT 2.0 (untested)

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:param name="path-to-dictionary" select="'dict.xml'"/>
<xsl:key name="abbr-lookup" match="entry" use="@abbr" />

<xsl:template match="/root">
    <html>
        <body>
            <xsl:apply-templates/>
        </body>
    </html>
</xsl:template>

<xsl:template match="abbreviation">
    <abbr title="{key('abbr-lookup', @Id, document($path-to-dictionary))}">
        <xsl:value-of select="@Id"/>
    </abbr>
</xsl:template>

</xsl:stylesheet>

to get:

Result

<html>
    <body>
        <abbr title="for example">E.G.</abbr>
    </body>
</html>

To understand the syntax used, read about Attribute Value Templates.


答:
Well, XSLT does not float any text, it is a programming language to transform XML (or with XSLT 2 or 3, other input formats) to XML, (X)HTML, plain text. You seem to want to transform your XML to HTML in the hope the HTML user agent or browser displays a tooltip of the title attribute.

As for using an XML file as a secondary input file, if you have abbrvs.xml with

```<code><root><abbr key="E.G.">for example.</abbr>...</root>
</code>```

then in XSLT you can use

```<code><abbr title="{key('abbr', @Id, doc('abbrvs.xml'))}">
  <xsl:value-of select="@id"/>
</abbr>
</code>```

to pull that title attribute value from the secondary input file if the XSLT declares a key

```<code><xsl:key name="abbr" match="abbr" use="@key"/>
</code>```

Title: XSLT: What is the best way to apply a floating text that will display the full expression for acronyms from an external dictionary file?

Body:
Well, XSLT does not float any text, it is a programming language to transform XML (or with XSLT 2 or 3, other input formats) to XML, (X)HTML, plain text. You seem to want to transform your XML to HTML in the hope the HTML user agent or browser displays a tooltip of the title attribute.

As for using an XML file as a secondary input file, if you have abbrvs.xml with

<root><abbr key="E.G.">for example.</abbr>...</root>

then in XSLT you can use

<abbr title="{key('abbr', @Id, doc('abbrvs.xml'))}">
  <xsl:value-of select="@id"/>
</abbr>

to pull that title attribute value from the secondary input file if the XSLT declares a key

<xsl:key name="abbr" match="abbr" use="@key"/>


问:
How to find object in python list by attribute
If I have a list created like this:

```<code>list = [
    {
    "id": 1,
    "name": "something 1"
    },
    {
    "id": 2,
    "name": "something 2"
    }
]
</code>```

and I want to grab information from one of the list items, using the id from the url like this:

```<code>@route.app('item/<int:id>')
def item(id):
  name = ???
  return render_template('index.html', name=name)
</code>```

how would I get the name of the object in the list with the specific id from the url?

答:
A simple for loop will do your work:</p>

```<code>@route.app('item/<int:id>')
def item(id):
   some_list = [
    {
    "id": 1,
    "name": "something 1"
    },
    {
    "id": 2,
    "name": "something 2"
    }
   ]
  name = ""
  for obj in some_list:
    if obj['id'] == id:
          name = obj['name']
  return render_template('index.html', name=name)
</code>```

Body:
If I have a list created like this:

list = [
    {
    "id": 1,
    "name": "something 1"
    },
    {
    "id": 2,
    "name": "something 2"
    }
]

and I want to grab information from one of the list items, using the id from the url like this:

@route.app('item/<int:id>')
def item(id):
  name = ???
  return render_template('index.html', name=name)

how would I get the name of the object in the list with the specific id from the url?

Body:
A simple for loop will do your work:

@route.app('item/<int:id>')
def item(id):
   some_list = [
    {
    "id": 1,
    "name": "something 1"
    },
    {
    "id": 2,
    "name": "something 2"
    }
   ]
  name = ""
  for obj in some_list:
    if obj['id'] == id:
          name = obj['name']
  return render_template('index.html', name=name)


问:
Angular Material - Prevent mat-stepper from navigating between steps
I have a mat-horizontal-stepper where I set linear property as true. When all the steps are valid as of now I can navigate to previous steps by clicking the header or label. I don't want that property.

I need to navigate only through buttons.

I tried disabling pointer function with:

```<code>    .mat-horizontal-stepper-header{
       pointer-events: none;
     }
</code>```

but it didn't worked.

I need either to stop navigating by clicking header or fire a function on clicking the stepper header.

答:
.mat-stepper-horizontal {
  pointer-events: none;
}

Body:
I have a mat-horizontal-stepper where I set linear property as true. When all the steps are valid as of now I can navigate to previous steps by clicking the header or label. I don't want that property.

I need to navigate only through buttons.

I tried disabling pointer function with:

    .mat-horizontal-stepper-header{
       pointer-events: none;
     }

but it didn't worked.

I need either to stop navigating by clicking header or fire a function on clicking the stepper header.


问:
USB serial port garbage when the device resets
When I reset a USB device that is connected via USB serial it starts printing garbage.

If I close out the serial monitor (using Arduino's serial console but should not matter) and reopen, clean text starts printing.  Judging by the rate of transmission, the garbage is clearly caused by my device doing normal serial printing -- that is, it is not random garbage.

This is a homebrew USB serial device so the problem could very well be in there.  In fact, I can very easily change the code in USB serial device, but cannot do the same for the serial terminal program :-), so would prefer if the solution was there.

No, this is not an incorrect baud or parity setting so please don't suggest it! :-)

Thanks for any help/ideas!

答:
Is it printing garbage even when nothing is being (intentionally) transmitted?  If so, there is a hardware problem.  Either it resets into a "break" state, or it is jabbering.

If it happens only when data is written through it, then, when the device resets, what serial settings does it default to?  Almost certainly this is caused by a speed/data bits/stop bits problem.


问:
How to find closest lower value in array angular 6?
I have an array of objects where I need to find closest lower value from that array based on some value or current value in angular 6, I have already tried but its showing undefined.

app.component.html

```<code><button (click) ="getPrev()">Previous Value</button>
</code>```

app.component.ts

```<code>declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
    arrayVal:any;
    currentVal : any;
  title = 'projectchart';
  public array = [{"id":1},{"id":3},{"id":5}];

  getPrev(){
     this.currentVal = 5;
     this.arrayVal= this.array;
     let number = this.arrayVal.reverse().find(e => e <= this.currentVal);
     console.log(number);
  }
}
</code>```

答:
Change your function to:

```<code> getPrev(){
 this.currentVal = 5;
 this.arrayVal= this.array;
 let number = this.arrayVal.reverse().find(e => e.id <= this.currentVal);
 console.log(number);
</code>```

}

Body:
I have an array of objects where I need to find closest lower value from that array based on some value or current value in angular 6, I have already tried but its showing undefined.

app.component.html

<button (click) ="getPrev()">Previous Value</button>

app.component.ts

declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
    arrayVal:any;
    currentVal : any;
  title = 'projectchart';
  public array = [{"id":1},{"id":3},{"id":5}];

  getPrev(){
     this.currentVal = 5;
     this.arrayVal= this.array;
     let number = this.arrayVal.reverse().find(e => e <= this.currentVal);
     console.log(number);
  }
}

Body:
Change your function to:

 getPrev(){
 this.currentVal = 5;
 this.arrayVal= this.array;
 let number = this.arrayVal.reverse().find(e => e.id <= this.currentVal);
 console.log(number);

}


问:
Dart difference between = and : in named parameters
```<code>class Student {
  String name;
  int age;
  int id;

  Student({this.name, this.id = 101, this.age: 20});
}
</code>```

What is the difference between = and : in above constructor? Both seems to do the same job.

答:
From the documentation:

Deprecation note: Old code might use a colon (:) instead of = to set
  default values of named parameters. The reason is that originally,
  only : was supported for named parameters. That support is likely to
  be deprecated, so we recommend that you use = to specify default
  values.

Source:
https://dart.dev/guides/language/language-tour

Body:
class Student {
  String name;
  int age;
  int id;

  Student({this.name, this.id = 101, this.age: 20});
}

What is the difference between = and : in above constructor? Both seems to do the same job.


问:
Traversing an array to find the second largest element in linear time
Is there a way in linear time by which we can find which is the second largest element of an array ?
Array elements can be positive, negative or zero.
Elements can be repetitive.
No STLs allowed.
Python can be used.

Solution : Sort the array and take the second element but Sorting not allowed

Modification : By definition second largest element will be the one which is numerically smaller. Like if we have

Arr = {5,5,4,3,1}
Then second largest is 4

Addition
Lets say if i want to generalize the question to kth largest and complexity less than linear like nlogn, what can be the solution.

答:
If you want a true O(n) algorithm, and want to find nth largest element in array then you should use quickselect (it's basically quicksort where you throw out the partition that you're not interested in), and the below is a great writeup, with the runtime analysis:

http://pine.cs.yale.edu/pinewiki/QuickSelect


问:
FCM Custom Notification Icon not displayed
I have created white/transparent PNG notification icons and added them in application meta-data in AndroidManifest as per the manuals.

The strange thing is that the custom icon is displayed correctly on Samsung Mini (jelly bean) and Nexus 4 (API 27) emulator, but not on Samsung A6 (Oreo) and Huawei Honor Lite 9 (Oreo) devices where I see the default white droid on green background icon.

The notification is always displayed but on some devices the custom icon is not used.

I tried to implement it in AssetStudio and also implemented with and without Notification Builder but it had not effect.

答:
set this to your application tag in Manifest:</p>

```<code>        <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_your_default_logo" />
</code>```

Body:
set this to your application tag in Manifest:

        <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_your_default_logo" />


问:
LWC rules for folders
Is there anywhere a place where the rules regarding the folder structure is explained?

The most important one I understand, i.e. lwc must be the name of the parent folder of components, and can be referenced with c/.

Other than that, I don't know; there seem to be issues with having folders / files with the same name (I think) even when they belong to a different component.

I can't tell for sure because I'm having different compilation errors all the time.

I can't seem to reference subfolders properly without getting
  compilation errors.

Sometimes when I change the name, one file is fixed then the other breaks.

Have been spending all day trying to fix basic import issues, seems like that thing is completely broken and I strongly regret that I have to work with it.

It seems that they use the @Babel/traverse npm library to compile (while we can't use npm directly, another thing that makes me wonder what the hell they're doing).

Some help is appreciated, although I'm afraid the community is tiny.
Thanks.

答:
Knowing the following information will save you a LOT of trouble.
Not applying these rules will result in obscure compilation errors during the bundling process:

•   Components should all be stored below a folder named ‘lwc’, this will place the components directly under the namespace c/;

•   No duplicate component names should ever exist under the c/ namespace;

•   You should not use ‘-‘ in component names, only alphanumeric characters and underscores;

•   Component folder names should be unique, they should not correspond to folder names that are places directly in the root of the project;

Best is to deploy regularly and check if anything broke.

Personally I really don't like it because this is WAY too restrictive IMO.

But anyway, it works now.

Title: LWC rules for folders


问:
Query a list in mongo
I have a mongo collection 'Student' with below documents

```<code>{
    "_id" : ObjectId("5ccc2cded71acf061de1c2d8"),
    "studentId" : "123",
    "name" : "1",
    "age" : NumberLong(0),
    "section" : "A",
    "state" : "State1",
    "city" : "City1"
}
</code>```

I have 100 documents with the above structure. Now i have a list with below structure

```<code>[{
    "studentId": "123",
    "state": "state1"
},
{
    "studentId": "456",
    "state": "state2"
}]
</code>```

Is there any way in mongo that i can get the documents matching this list data in single db call. Iterating over list with criteria as studentId:123 and state:state1 will work but is how to get all list data without iterating in java?

答:
All you need is a simple find query:

```<code>db.collection.find({$or: arr});
</code>```

when arr is the sample array you showed.

You should note that mongo searches are case sensitive meaning with the sample array you gave no matches will be found since "state1" is not equal to "State1".

Title: Query a list in mongo

Body:
I have a mongo collection 'Student' with below documents

{
    "_id" : ObjectId("5ccc2cded71acf061de1c2d8"),
    "studentId" : "123",
    "name" : "1",
    "age" : NumberLong(0),
    "section" : "A",
    "state" : "State1",
    "city" : "City1"
}

I have 100 documents with the above structure. Now i have a list with below structure

[{
    "studentId": "123",
    "state": "state1"
},
{
    "studentId": "456",
    "state": "state2"
}]

Is there any way in mongo that i can get the documents matching this list data in single db call. Iterating over list with criteria as studentId:123 and state:state1 will work but is how to get all list data without iterating in java?

Body:
All you need is a simple find query:

db.collection.find({$or: arr});

when arr is the sample array you showed.

You should note that mongo searches are case sensitive meaning with the sample array you gave no matches will be found since "state1" is not equal to "State1".


问:
check whether date exists in database
I want to check if the entered date is taken or not.

I tried to fix it but it always indicates that a date has been taken even if it hasn't.

This is the DAO

```<code>public static String getDate(String date) throws SQLException, ClassNotFoundException {
    Connection cnx;
    String datee;
    cnx = Connect.getConnection();

    String req = "select date from examen where date=?";
    PreparedStatement st = cnx.prepareStatement(req);
    st.setString(1, date);
    ResultSet rs = st.executeQuery();
    if (rs.next()) {
        String laDate = rs.getString(date);

    }
    return date;

}
</code>```

and this is the servlet

```<code>String dd = ExamDAO.getDate(date);

if (dd != null) {
                        String datePrise = "la date est prise ";
                        request.getSession().setAttribute("datePrise", datePrise);
                        System.out.println("priiiiise ");
                        response.sendRedirect("examen.jsp");
                    } else {...}
</code>```

答:
You always return the same date as passed into the method. laDate isn't used so your method doesn't have any working logic in it.

Could be something like:

```<code>\\ I suggest a better query with another name for the 'date' column (needs db change), because using column
\\ names like date can cause problems (reserved keywords/functions in some databases)
"select registrationdate from examen where registrationdate = ?"
</code>```

```<code>String returnDate = inputDate; // inputDate = date argument from method with better name
ResultSet rs = st.executeQuery();
if (rs.next()) {
   returnDate = rs.getString("registrationdate");
}
return returnDate;
</code>```

or

```<code>Optional<String> returnValue = Optional.empty();
ResultSet rs = st.executeQuery();
if (rs.next()) {
   returnValue = Optional.of(rs.getString("registrationdate"));
}
return returnValue;
</code>```

Title: check whether date exists in database

Body:
I want to check if the entered date is taken or not.

I tried to fix it but it always indicates that a date has been taken even if it hasn't.

This is the DAO

public static String getDate(String date) throws SQLException, ClassNotFoundException {
    Connection cnx;
    String datee;
    cnx = Connect.getConnection();

    String req = "select date from examen where date=?";
    PreparedStatement st = cnx.prepareStatement(req);
    st.setString(1, date);
    ResultSet rs = st.executeQuery();
    if (rs.next()) {
        String laDate = rs.getString(date);

    }
    return date;

}

and this is the servlet

String dd = ExamDAO.getDate(date);

if (dd != null) {
                        String datePrise = "la date est prise ";
                        request.getSession().setAttribute("datePrise", datePrise);
                        System.out.println("priiiiise ");
                        response.sendRedirect("examen.jsp");
                    } else {...}

Body:
You always return the same date as passed into the method. laDate isn't used so your method doesn't have any working logic in it.

Could be something like:

\\ I suggest a better query with another name for the 'date' column (needs db change), because using column
\\ names like date can cause problems (reserved keywords/functions in some databases)
"select registrationdate from examen where registrationdate = ?"

String returnDate = inputDate; // inputDate = date argument from method with better name
ResultSet rs = st.executeQuery();
if (rs.next()) {
   returnDate = rs.getString("registrationdate");
}
return returnDate;

or

Optional<String> returnValue = Optional.empty();
ResultSet rs = st.executeQuery();
if (rs.next()) {
   returnValue = Optional.of(rs.getString("registrationdate"));
}
return returnValue;


问:
Retrieve an object from entityframework without ONE field
I'm using entity framework to connect with the database. I've one little problem:

I've one table which have one varbinary(MAX) column(with filestream).

I'm using SQL request to manage the "Data" part, but EF for the rest(metadata of the file).

I've one code which has to get all files id, filename, guid, modification date, ... of a file. This doesn't need at all the "Data" field.

Is there a way to retrieve a List but without this column filled?

Something like

```<code>context.Files.Where(f=>f.xyz).Exclude(f=>f.Data).ToList();
</code>```

??

I know I can create anonymous objects, but I need to transmit the result to a method, so no anonymous methods. And I don't want to put this in a list of anonymous type, and then create a list of my non-anonymous type(File).

The goal is to avoid this:

```<code>using(RsSolutionsEntities context = new RsSolutionsEntities())
{
    var file = context.Files
        .Where(f => f.Id == idFile)
        .Select(f => new {
            f.Id, f.MimeType, f.Size, f.FileName, f.DataType,
            f.DateModification, f.FileId
        }).FirstOrDefault();

    return new File() {
        DataType = file.DataType, DateModification = file.DateModification,
        FileId = file.FileId, FileName = file.FileName, Id = file.Id,
        MimeType = file.MimeType, Size = file.Size
    };
}
</code>```

(I'm using here the anonymous type because otherwise you will get a NotSupportedException: The entity or complex type 'ProjectName.File' cannot be constructed in a LINQ to Entities query.)

(e.g. this code throw the previous exception:

```<code>File file2 = context.Files.Where(f => f.Id == idFile)
  .Select(f => new File() {Id = f.Id, DataType = f.DataType}).FirstOrDefault();
</code>```

and "File" is the type I get with  a context.Files.ToList(). This is the good class:

```<code>using File = MyProjectNamespace.Common.Data.DataModel.File;
</code>```

File is a known class of my EF datacontext:

```<code>public ObjectSet<File> Files
{
    get { return _files  ?? (_files = CreateObjectSet<File>("Files")); }
}
private ObjectSet<File> _files;
</code>```

答:
For EF Core 2
I implemented a solution like this:

```<code>var files = context.Files.AsNoTracking()
                         .IgnoreProperty(f => f.Report)
                         .ToList();
</code>```

The base idea is to turn for example this query:

```<code>SELECT [f].[Id], [f].[Report], [f].[CreationDate]
FROM [File] AS [f]
</code>```

into this:

```<code>SELECT [f].[Id], '' as [Report], [f].[CreationDate]
FROM [File] AS [f]
</code>```

you can see the full source code in here:
https://github.com/aspnet/EntityFrameworkCore/issues/1387#issuecomment-495630292

Body:
I'm using entity framework to connect with the database. I've one little problem:

I've one table which have one varbinary(MAX) column(with filestream).

I'm using SQL request to manage the "Data" part, but EF for the rest(metadata of the file).

I've one code which has to get all files id, filename, guid, modification date, ... of a file. This doesn't need at all the "Data" field.

Is there a way to retrieve a List but without this column filled?

Something like

context.Files.Where(f=>f.xyz).Exclude(f=>f.Data).ToList();

??

I know I can create anonymous objects, but I need to transmit the result to a method, so no anonymous methods. And I don't want to put this in a list of anonymous type, and then create a list of my non-anonymous type(File).

The goal is to avoid this:

using(RsSolutionsEntities context = new RsSolutionsEntities())
{
    var file = context.Files
        .Where(f => f.Id == idFile)
        .Select(f => new {
            f.Id, f.MimeType, f.Size, f.FileName, f.DataType,
            f.DateModification, f.FileId
        }).FirstOrDefault();

    return new File() {
        DataType = file.DataType, DateModification = file.DateModification,
        FileId = file.FileId, FileName = file.FileName, Id = file.Id,
        MimeType = file.MimeType, Size = file.Size
    };
}

(I'm using here the anonymous type because otherwise you will get a NotSupportedException: The entity or complex type 'ProjectName.File' cannot be constructed in a LINQ to Entities query.)

(e.g. this code throw the previous exception:

File file2 = context.Files.Where(f => f.Id == idFile)
  .Select(f => new File() {Id = f.Id, DataType = f.DataType}).FirstOrDefault();

and "File" is the type I get with  a context.Files.ToList(). This is the good class:

using File = MyProjectNamespace.Common.Data.DataModel.File;

File is a known class of my EF datacontext:

public ObjectSet<File> Files
{
    get { return _files  ?? (_files = CreateObjectSet<File>("Files")); }
}
private ObjectSet<File> _files;

Body:
For EF Core 2
I implemented a solution like this:

var files = context.Files.AsNoTracking()
                         .IgnoreProperty(f => f.Report)
                         .ToList();

The base idea is to turn for example this query:

SELECT [f].[Id], [f].[Report], [f].[CreationDate]
FROM [File] AS [f]

into this:

SELECT [f].[Id], '' as [Report], [f].[CreationDate]
FROM [File] AS [f]

you can see the full source code in here:
https://github.com/aspnet/EntityFrameworkCore/issues/1387#issuecomment-495630292


问:
Rotation animation for the background gradient of the view
I want to add an animation to my app where I want the background gradient of my screen to rotate. I have tried a few things like ValueAnimator, PropertyAnimator etc but I am facing a problem.

When I run my animation the entire view starts rotating. It looks like the screen itself is rotating. Instead I want an effect where only the background gradient rotates not the entire screen.

What is the best way to get such effect?

Here is what I have so far

```<code>class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val view: ConstraintLayout = findViewById(R.id.animation_view)
        startAnimation(view)
    }

    private fun startAnimation(view: View) {
        view.startAnimation(
            AnimationUtils.loadAnimation(
                this, R.anim.rotation_clockwise
            )
        )
    }
}
</code>```

animation resource xml

```<code><rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="infinite"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="1200"/>
</code>```

layout file

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPurple_A400"
    tools:context=".MainActivity">

<androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/animation_view"
        android:background="@drawable/drawable_purple_gradient">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
Do you animate the root view of the activity or fragment?
If yes, that makes sense. The whole screen will be rotated.

If you want to animate the background of the view, you should add a new view which holds only the background then rotate it.

```<code><?xml version="1.0" encoding="utf-8"?>
  <androidx.constraintlayout.widget.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@color/colorPurple_A400"
  tools:context=".MainActivity">

  <View
    android:id="@+id/animation_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/drawable_purple_gradient"/>

  <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent"/>

  </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Body:
I want to add an animation to my app where I want the background gradient of my screen to rotate. I have tried a few things like ValueAnimator, PropertyAnimator etc but I am facing a problem.

When I run my animation the entire view starts rotating. It looks like the screen itself is rotating. Instead I want an effect where only the background gradient rotates not the entire screen.

What is the best way to get such effect?

Here is what I have so far

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val view: ConstraintLayout = findViewById(R.id.animation_view)
        startAnimation(view)
    }

    private fun startAnimation(view: View) {
        view.startAnimation(
            AnimationUtils.loadAnimation(
                this, R.anim.rotation_clockwise
            )
        )
    }
}

animation resource xml

<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="infinite"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="1200"/>

layout file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPurple_A400"
    tools:context=".MainActivity">

<androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/animation_view"
        android:background="@drawable/drawable_purple_gradient">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Body:
Do you animate the root view of the activity or fragment?
If yes, that makes sense. The whole screen will be rotated.

If you want to animate the background of the view, you should add a new view which holds only the background then rotate it.

<?xml version="1.0" encoding="utf-8"?>
  <androidx.constraintlayout.widget.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@color/colorPurple_A400"
  tools:context=".MainActivity">

  <View
    android:id="@+id/animation_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/drawable_purple_gradient"/>

  <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent"/>

  </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>


问:
How to pass a function pointer to a C code in Go
I want to write a small go application for processing videos and decided to use this library goav which is a FFmpeg binding for go. However, it does not support reading the video straightaway from memory. As a workaround, I decided to call the C function directly.

The signature of the function I want to call is as follows.

AVIOContext *avio_alloc_context(
                  unsigned char *buffer,
                  int buffer_size,
                  int write_flag,
                  void *opaque,
                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
                  int64_t (*seek)(void *opaque, int64_t offset, int whence));
```

<p>The go code I wrote to call this -</p>

<pre class="lang-golang prettyprint-override"><code>package video

// #include<libavformat/avio.h>
import "C"
import (
  "bytes"
  "github.com/giorgisio/goav/avformat"
  "github.com/giorgisio/goav/avutil"
  "unsafe"
)

func DecodeStream(data *bytes.Buffer) {
  bufferSize := 8192
  formatContext := avformat.AvformatAllocContext()
  buffer := (*C.uchar)(avutil.AvMalloc(uintptr(bufferSize)))
  ioContext := C.avio_alloc_context(
    buffer,
    C.int(bufferSize),
    C.int(0),
    unsafe.Pointer(data),
    &[0]byte{},
    &[0]byte{},
    &[0]byte{},
  )                                       // <- error in this line
  formatContext.SetPb((*avformat.AvIOContext)(unsafe.Pointer(ioContext)))
  if formatContext.AvformatFindStreamInfo(nil) < 0 {
    panic("Couldn't find stream info")
  }
  println("DURATION: ", formatContext.Duration())
}
</code>```

However, I am getting this error runtime error: cgo argument has Go pointer to Go pointer.

I tried replacing &[0]byte{} with nil too. Can't seem to get away!

答:
The runtime error is actually complaining about the unsafe.Pointer(data) argument. The bytes.Buffer type has internal (Go) pointers, and cgo doesn't allow passing pointers to C if those pointers point to Go objects that contain Go pointers themselves.

These rules are detailed in the cgo documentation here: https://golang.org/cmd/cgo/#hdr-Passing_pointers

The short summary is that the Go garbage collector needs to be aware when Go pointers are modified. The Go compilers make sure that compiled code appropriately informs the garbage collector, but C compilers don't know to do this. So to prevent GC problems, cgo simply doesn't allow passing pointers like this.

Body:
I want to write a small go application for processing videos and decided to use this library goav which is a FFmpeg binding for go. However, it does not support reading the video straightaway from memory. As a workaround, I decided to call the C function directly.

The signature of the function I want to call is as follows.

AVIOContext *avio_alloc_context(
                  unsigned char *buffer,
                  int buffer_size,
                  int write_flag,
                  void *opaque,
                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
                  int64_t (*seek)(void *opaque, int64_t offset, int whence));

The go code I wrote to call this -

package video

// #include<libavformat/avio.h>
import "C"
import (
  "bytes"
  "github.com/giorgisio/goav/avformat"
  "github.com/giorgisio/goav/avutil"
  "unsafe"
)

func DecodeStream(data *bytes.Buffer) {
  bufferSize := 8192
  formatContext := avformat.AvformatAllocContext()
  buffer := (*C.uchar)(avutil.AvMalloc(uintptr(bufferSize)))
  ioContext := C.avio_alloc_context(
    buffer,
    C.int(bufferSize),
    C.int(0),
    unsafe.Pointer(data),
    &[0]byte{},
    &[0]byte{},
    &[0]byte{},
  )                                       // <- error in this line
  formatContext.SetPb((*avformat.AvIOContext)(unsafe.Pointer(ioContext)))
  if formatContext.AvformatFindStreamInfo(nil) < 0 {
    panic("Couldn't find stream info")
  }
  println("DURATION: ", formatContext.Duration())
}

However, I am getting this error runtime error: cgo argument has Go pointer to Go pointer.

I tried replacing &[0]byte{} with nil too. Can't seem to get away!


问:
how to enforce duration or timeout on Ruby ssh exec on remote machine
Using ruby ssh to exec a shell process that runs continuously on a remote machine. How can I enforce a duration for the ssh process to run and then have this process killed, and ruby ssh call end, moving on to subsequent code?

Purpose: invoke tests on a remote machine using ruby ssh for a specific duration.

example:

```<code> Net::SSH.start( hostname.to_s, username.to_s, :password => pw.to_s ) do|ssh|
         output = ssh.exec("command line call that runs continuously")
         end
</code>```

The only things I can think of doing:
a) using Terminator to wrap around the ruby exec call for a duration of time
b) use a perl helper function around the command line call as shown here

There must be something simpler than this right?

答:
using a Watchdog / Terminator which sends a signal to the processes is the most common solution. Note that the remote process may have to be killed seperately!

Another way of doing this is to have both ends watch for a local "semaphore file" every X seconds... if the file is there with the correct PID in it, die gracefully!

So once your Watchdog timer expires,
you can sync that file to the remote machine via scp or rsync, and copy one locally.  and both jobs can look for them and terminate themselves..

of course you could also send a UNIX  signal like SIGUSER

Body:
Using ruby ssh to exec a shell process that runs continuously on a remote machine. How can I enforce a duration for the ssh process to run and then have this process killed, and ruby ssh call end, moving on to subsequent code?

Purpose: invoke tests on a remote machine using ruby ssh for a specific duration.

example:

 Net::SSH.start( hostname.to_s, username.to_s, :password => pw.to_s ) do|ssh|
         output = ssh.exec("command line call that runs continuously")
         end

The only things I can think of doing:
a) using Terminator to wrap around the ruby exec call for a duration of time
b) use a perl helper function around the command line call as shown here

There must be something simpler than this right?