问:
how can do left join with lambda expression in c# using EF?
I want to do left join with lambda expression. But I don't know how can I do that. I have tried many LINQ queries, but haven't gotten proper query. I am a new to the Entity Framework. So any one who know how I can do that, please let me know.

Here below i have try this query :

```<code>var query = UsersContext.Users.OrderBy(a => a.Email).Skip(skip).Take(pageSize).ToList();
var result = (from u in db.Notification
              join c in query on u.id equals c.Id into j1
              from j2 in j1.DefaultIfEmpty()
              select new { u, j2 }).OrderByDescending(a => a.u.datetime).Take(3).ToList();
</code>```

This is my query. I want to left it join with notification table and get only the last 3 notifications.

答:
```<code>var query = UsersContext.Users.Blah().Blah().ToList();
 // It's a non-complete List of Users....  (all we care about)

 var ids = query.Select(u=>u.Id).ToArray();
 // get an array of needed Users.

var notes = (from u in db.Notification
              where ids.Contains(u.id)
              select u).ToList();

var results = from u in notes
          join c in query on u.id equals c.Id into j1
          from j2 in j1.DefaultIfEmpty()
          select new { u, j2 }).OrderByDescending(a => a.u.datetime).Take(3).ToList();
</code>```

Body:
I want to do left join with lambda expression. But I don't know how can I do that. I have tried many LINQ queries, but haven't gotten proper query. I am a new to the Entity Framework. So any one who know how I can do that, please let me know.

Here below i have try this query :

var query = UsersContext.Users.OrderBy(a => a.Email).Skip(skip).Take(pageSize).ToList();
var result = (from u in db.Notification
              join c in query on u.id equals c.Id into j1
              from j2 in j1.DefaultIfEmpty()
              select new { u, j2 }).OrderByDescending(a => a.u.datetime).Take(3).ToList();

This is my query. I want to left it join with notification table and get only the last 3 notifications.


来源: stackexchange

问:
CDATA using FOR XML PATH ('Category'), ROOT('Categories')
I don't know if it's possible... I 've read that I have to use XML EXPLICIT... but I need to insert CDATA TAG into 2 column XML result.

Now I'm using this script:

```<code>SELECT
ExternalId,
ParentExternalId,
Name,
CategoryPageUrl,
ImageUrl
FROM Cestino.acap.Servizio_03
WHERE ExternalId = 5763
FOR XML PATH ('Category'), ROOT('Categories')

<Categories>
<Category>
<ExternalId>5763</ExternalId>
<Name>Audio Video Elettronica</Name>
<CategoryPageUrl>https://www.url.it/s/audio</CategoryPageUrl>
<ImageUrl>https://images.url.it/n4897203.jpg</ImageUrl>
</Category>
</code>```

I need CDATA inside field: CategoryPageUrl and ImageUrl.

Someone can explain me the right syntax to USE?
Thanks ALEN, ITALY

答:
Resolved.

SELECT DISTINCT
    1 as Tag,
    NULL as Parent,
    NULL AS [Brands!1], -- empty root element
    NULL AS [Brand!2!ExternalId!element],
    NULL AS [Brand!2!Name!cdata]
UNION ALL
SELECT DISTINCT
    2 AS Tag,
    1 AS Parent,
    NULL,
    REPLACE(rtrim(ltrim(BrandExternalId)),'/','_') AS BrandExternalId,
    rtrim(ltrim(BrandExternalId)) AS Name
FROM Cestino.acap.Bazaar_Servizio_00
WHERE externalid IN('100926550','100929174')
ORDER BY 3, Parent
FOR XML EXPLICIT

ContentLicense: CC BY-SA 3.0

Body:
I don't know if it's possible... I 've read that I have to use XML EXPLICIT... but I need to insert CDATA TAG into 2 column XML result.

Now I'm using this script:

SELECT
ExternalId,
ParentExternalId,
Name,
CategoryPageUrl,
ImageUrl
FROM Cestino.acap.Servizio_03
WHERE ExternalId = 5763
FOR XML PATH ('Category'), ROOT('Categories')

<Categories>
<Category>
<ExternalId>5763</ExternalId>
<Name>Audio Video Elettronica</Name>
<CategoryPageUrl>https://www.url.it/s/audio</CategoryPageUrl>
<ImageUrl>https://images.url.it/n4897203.jpg</ImageUrl>
</Category>

I need CDATA inside field: CategoryPageUrl and ImageUrl.

Someone can explain me the right syntax to USE?
Thanks ALEN, ITALY


问:
How to make a CakePHP3 login with username only
So i wanted to do a very basic authentication , and by following the Blog tutorial on https://book.cakephp.org/3.0/en/tutorials-and-examples/blog-auth-example/auth.html i tried to make it only use Username to log in, but the login system doesn't work because

```<code>$user = $this->Auth->identify();
</code>```

Always returns false, I have searched cake's documentation on Authentication but can't find anything to help me.
Can someone tell me how do to make a costum login authentication.

Current login action:

```<code>  public function login()
  {
      if ($this->request->is('post')) {
          $user = $this->Auth->identify();
          if ($user) {
              $this->Auth->setUser($user);
              return $this->redirect($this->Auth->redirectUrl());
          }
          $this->Flash->error(__('Invalid username, try again'));
      }
  }
</code>```

And its View:

```<code><div class="users form">
<?= $this->Flash->render() ?>
<?= $this->Form->create() ?>
    <fieldset>
        <legend><?= __('Please enter your username') ?></legend>
        <?= $this->Form->control('username') ?>
    </fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
</div>
</code>```

AuthComponent Init:

```<code>  public function initialize(array $config)
{
    $controller = $this->_registry->getController();
    $this->eventManager($controller->eventManager());
    $this->response =& $controller->response;
    $this->session = $controller->request->session();
}
</code>```

答:
After a few trial and error I managed to make my own login with username only that gets all usernames from a column in Database and stores them in an Iterator with

```<code>$usernames = $this->UsersTable->find()->extract('username');
</code>```

and then I convert to an array of strings with

```<code>$usernamesArray= iterator_to_array($usernames);
</code>```

I check if the requested data is Post and I do a loop to check all usernames, after that i trim both the input which is $user and the $usernameArray to ensure they are equal and if it is I authenticate my user and redirect him to my main page again.

```<code>$usernames = $this->Table->find()->extract('username');
    $usernamesArray= iterator_to_array($usernames);
    $user = $this->request->getData('username');
    if ($this->request->is('post')) {
        for($i = 0 ; $i < count($usernamesArray) ; $i++ ){
          if(trim($user) == trim($usernamesArray[$i])){
            $this->redirect(['action' => 'index']);
            $this->Auth->setUser($user);
            return;
          }
        }
        $this->Flash->error(__('Invalid username or password, try again'));
    }
  }
</code>```

Body:
So i wanted to do a very basic authentication , and by following the Blog tutorial on https://book.cakephp.org/3.0/en/tutorials-and-examples/blog-auth-example/auth.html i tried to make it only use Username to log in, but the login system doesn't work because

$user = $this->Auth->identify();

Always returns false, I have searched cake's documentation on Authentication but can't find anything to help me.
Can someone tell me how do to make a costum login authentication.

Current login action:

  public function login()
  {
      if ($this->request->is('post')) {
          $user = $this->Auth->identify();
          if ($user) {
              $this->Auth->setUser($user);
              return $this->redirect($this->Auth->redirectUrl());
          }
          $this->Flash->error(__('Invalid username, try again'));
      }
  }

And its View:

<?= $this->Flash->render() ?>
<?= $this->Form->create() ?>
    <fieldset>
        <legend><?= __('Please enter your username') ?></legend>
        <?= $this->Form->control('username') ?>
    </fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>

AuthComponent Init:

  public function initialize(array $config)
{
    $controller = $this->_registry->getController();
    $this->eventManager($controller->eventManager());
    $this->response =& $controller->response;
    $this->session = $controller->request->session();
}

Body:
After a few trial and error I managed to make my own login with username only that gets all usernames from a column in Database and stores them in an Iterator with

$usernames = $this->UsersTable->find()->extract('username');

and then I convert to an array of strings with

$usernamesArray= iterator_to_array($usernames);

I check if the requested data is Post and I do a loop to check all usernames, after that i trim both the input which is $user and the $usernameArray to ensure they are equal and if it is I authenticate my user and redirect him to my main page again.

$usernames = $this->Table->find()->extract('username');
    $usernamesArray= iterator_to_array($usernames);
    $user = $this->request->getData('username');
    if ($this->request->is('post')) {
        for($i = 0 ; $i < count($usernamesArray) ; $i++ ){
          if(trim($user) == trim($usernamesArray[$i])){
            $this->redirect(['action' => 'index']);
            $this->Auth->setUser($user);
            return;
          }
        }
        $this->Flash->error(__('Invalid username or password, try again'));
    }
  }


问:
Automating click to image-mapped actions/links using Node/Nightwatch
How does one use NightwatchJs to automate clicking a specific part of an image? My naive approach is to select the coords attribute that matches the specific area of the image I'd like to trigger; but it doesn't work.

```<code><img src="..." usemap="#example">
<map name="example" id="example">
    <area shape="rect" coords="336,10,401,32" href="...">
    <area shape="rect" coords="25,171,97,198" href="...">
    ...
</map>
</code>```

Anyone encounter this issue or know of a work around? Thanks!

答:
If I were you, I would play with the position of area elements inside the map element using CSS selectors like :first-child or :first-of-type. Here is a minimal working example:

PNG (map.png)

HTML/JS (index.html)

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Nightwatch</title>
</head>
<body>
  <img src="map.png" usemap="#map">
  <map name="map">
    <area shape="circle" coords="51,51,29">
  </map>
  <script>
    // When the red area is clicked, we should display an alert.
    var area = document.querySelector('area');
    area.addEventListener('click', function () {
      alert('OK');
    }, false);
  </script>
</body>
</html>
</code>```

Nightwatch (script.js)

```<code>module.exports = {
  'Clickable image map': function (browser) {
    browser
      .url('http://localhost:8000/index.html')
      .waitForElementPresent('map', 1000)
      .click('map > area:first-child');
      // ...
  },
};
</code>```

Command

If your environment is properly set up, you can run the script with nightwatch -t tests/script.js. You will see the alert, meaning that the red area has been clicked by Nightwatch.

Body:
How does one use NightwatchJs to automate clicking a specific part of an image? My naive approach is to select the coords attribute that matches the specific area of the image I'd like to trigger; but it doesn't work.

<map name="example" id="example">
    <area shape="rect" coords="336,10,401,32" href="...">
    <area shape="rect" coords="25,171,97,198" href="...">
    ...
</map>

Anyone encounter this issue or know of a work around? Thanks!

Body:
If I were you, I would play with the position of area elements inside the map element using CSS selectors like :first-child or :first-of-type. Here is a minimal working example:

PNG (map.png)

HTML/JS (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Nightwatch</title>
</head>
<body>
  <img src="map.png" usemap="#map">
  <map name="map">
    <area shape="circle" coords="51,51,29">
  </map>
  <script>
    // When the red area is clicked, we should display an alert.
    var area = document.querySelector('area');
    area.addEventListener('click', function () {
      alert('OK');
    }, false);
  </script>
</body>
</html>

Nightwatch (script.js)

module.exports = {
  'Clickable image map': function (browser) {
    browser
      .url('http://localhost:8000/index.html')
      .waitForElementPresent('map', 1000)
      .click('map > area:first-child');
      // ...
  },
};

Command

If your environment is properly set up, you can run the script with nightwatch -t tests/script.js. You will see the alert, meaning that the red area has been clicked by Nightwatch.


问:
Why is waiting for a thread delaying updates to swing components?
I'm having trouble trying to understand why manipulating a swing component, namely a JProgressBar, just before waiting for a parallel task to finish.

In the following example, the progressBar will only activate its indeterminate mode after the thread finishes waiting for the result of a Callable, even though (I expect) that the call for setIndeterminate(true) happens before the waiting. Can someone explain why this happens?

```<code>private void thisDoesntWork(JProgressBar p){
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<String> jobResult = executor.submit(() -> aLengthyJob());

    // This happens only after the button finishes waiting. (future.get())
    // I want to know why. Shouldn't this line happen before the thread blocks?
    p.setIndeterminate(true);

    try {
        System.out.println(jobResult.get());
    } catch (InterruptedException | ExecutionException ex) {}
}

public void createAndShowGUI(){
    JFrame frame = new JFrame("This progress bar wont work");
    JPanel panel = new JPanel();
    JButton button = new JButton("Start");
    JProgressBar progressBar = new JProgressBar();
    frame.setSize(500, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

    // Problem happens withing this button's action
    button.addActionListener((e)->{
        thisDoesntWork(progressBar);
    });

    panel.add(button);
    panel.add(progressBar);
    frame.add(panel);
    frame.setVisible(true);

}

private String aLengthyJob(){
    try {
        Thread.sleep(10000);
    } catch (InterruptedException ex) {}
    return "Done";
}

public static void main(String[] args) {
    new Test().createAndShowGUI();
}
</code>```

If the waiting happens in another thread, it works as expected.

```<code>// Waiting in a third thread works fine
private void thisWorks(JButton b, JProgressBar p) {
    p.setIndeterminate(true);
    b.setEnabled(false);

    ExecutorService executor = Executors.newFixedThreadPool(2);
    Future<String> jobResult;

    jobResult = executor.submit(() -> aLengthyJob());
    executor.execute(() -> {
        try {
            System.out.println(jobResult.get());
            p.setIndeterminate(false);
            b.setEnabled(true);
        } catch (InterruptedException | ExecutionException ex) {}
    });
}
</code>```

Imports:

```<code>import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
</code>```

答:
jobResult.get() waits for the end of the other thread inside the EDT, blocking it.

Maybe you want to at least link to some background on edt.– GhostCat

here are some resouces to read about the EDT:

https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html

What is the event dispatching thread?

Body:
I'm having trouble trying to understand why manipulating a swing component, namely a JProgressBar, just before waiting for a parallel task to finish.

In the following example, the progressBar will only activate its indeterminate mode after the thread finishes waiting for the result of a Callable, even though (I expect) that the call for setIndeterminate(true) happens before the waiting. Can someone explain why this happens?

private void thisDoesntWork(JProgressBar p){
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<String> jobResult = executor.submit(() -> aLengthyJob());

    // This happens only after the button finishes waiting. (future.get())
    // I want to know why. Shouldn't this line happen before the thread blocks?
    p.setIndeterminate(true);

    try {
        System.out.println(jobResult.get());
    } catch (InterruptedException | ExecutionException ex) {}
}

public void createAndShowGUI(){
    JFrame frame = new JFrame("This progress bar wont work");
    JPanel panel = new JPanel();
    JButton button = new JButton("Start");
    JProgressBar progressBar = new JProgressBar();
    frame.setSize(500, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

    // Problem happens withing this button's action
    button.addActionListener((e)->{
        thisDoesntWork(progressBar);
    });

    panel.add(button);
    panel.add(progressBar);
    frame.add(panel);
    frame.setVisible(true);

}

private String aLengthyJob(){
    try {
        Thread.sleep(10000);
    } catch (InterruptedException ex) {}
    return "Done";
}

public static void main(String[] args) {
    new Test().createAndShowGUI();
}

If the waiting happens in another thread, it works as expected.

// Waiting in a third thread works fine
private void thisWorks(JButton b, JProgressBar p) {
    p.setIndeterminate(true);
    b.setEnabled(false);

    ExecutorService executor = Executors.newFixedThreadPool(2);
    Future<String> jobResult;

    jobResult = executor.submit(() -> aLengthyJob());
    executor.execute(() -> {
        try {
            System.out.println(jobResult.get());
            p.setIndeterminate(false);
            b.setEnabled(true);
        } catch (InterruptedException | ExecutionException ex) {}
    });
}

Imports:

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;


问:
VB.NET to C# Linq
I have the following LINQ

```<code>            Dim z = (From d In db.GPSdevice
                     Where d.CompanyId = currentuser.CompanyId And d.Type = "Truck" Or d.Type = "Trailer"
                     Order By d.ListOrder Descending
                     Group d By d.Driver Into g = Group
                     Select g.FirstOrDefault())
</code>```

I try to convert it to c#

```<code>        var z = db.GPSdevices
            .Where(p => p.CompanyId == companyID && p.Type == "Truck" || p.Type == "Trailer")
            .OrderByDescending(p => p.ListOrder)
            .GroupBy(p => p.Driver)
            .Select(g => new { Group = g });
</code>```

but not sure, how to convert Select g.FirstOrDefault()...

答:
You can use the query syntax in C# too, no need to rewrite using the extension methods directly:</p>

```<code>var z = (from d In db.GPSdevice
        where (d.CompanyId == currentuser.CompanyId) && (d.Type == "Truck") || (d.Type == "Trailer")
        orderby d.ListOrder descending
        group d by d.Driver into g = group
        select g.FirstOrDefault())
</code>```

Title: VB.NET to C# Linq

Body:
I have the following LINQ

            Dim z = (From d In db.GPSdevice
                     Where d.CompanyId = currentuser.CompanyId And d.Type = "Truck" Or d.Type = "Trailer"
                     Order By d.ListOrder Descending
                     Group d By d.Driver Into g = Group
                     Select g.FirstOrDefault())

I try to convert it to c#

        var z = db.GPSdevices
            .Where(p => p.CompanyId == companyID && p.Type == "Truck" || p.Type == "Trailer")
            .OrderByDescending(p => p.ListOrder)
            .GroupBy(p => p.Driver)
            .Select(g => new { Group = g });

but not sure, how to convert Select g.FirstOrDefault()...

Body:
You can use the query syntax in C# too, no need to rewrite using the extension methods directly:

var z = (from d In db.GPSdevice
        where (d.CompanyId == currentuser.CompanyId) && (d.Type == "Truck") || (d.Type == "Trailer")
        orderby d.ListOrder descending
        group d by d.Driver into g = group
        select g.FirstOrDefault())


问:
Is this-> mandatory to access Base<T> identifiers from derived classes?
This code compiles with MSVC 2015, but doesn't compile with Clang 5.0.0 (trunk 304874):

```<code>template <typename T>
struct Base
{
  T data;
};

template <typename T>
struct Derived : Base<T>
{
  auto getData() const
  {
    return data;
  }
};
</code>```

Replacing data with this->data in Derived::getdata() makes Clang happy.

Which compiler is correct according to the C++ standard?

Must this-> be used in template code to access an identifier of a base class?

答:
Yes, it is. Basically data depends on T.

There is a mechanism called two-phase lookup. Non-(template)dependent names are resolved immediately - at the point of definition. Your data does not exist yet, because Base<T> does not exist yet, as it was not instantiated. Thus, it complains that data is not found.

You need to hint compiler that data depends on the template, and the name lookup should be performed in the second phase, after template parameters are substituted, i.e. template class was instantiated. This can be done by using this or providing template dependent scope.

So, either this->f() or Base<T>::f() will work.

Body:
This code compiles with MSVC 2015, but doesn't compile with Clang 5.0.0 (trunk 304874):

template <typename T>
struct Base
{
  T data;
};

template <typename T>
struct Derived : Base<T>
{
  auto getData() const
  {
    return data;
  }
};

Replacing data with this->data in Derived::getdata() makes Clang happy.

Which compiler is correct according to the C++ standard?

Must this-> be used in template code to access an identifier of a base class?


问:
List of dates for given day of the week Swift
I need to get the List of dates for the given date of the week.

As an example :
If user select the random date from picker Like 2017-6-7,
I needs to get and display the dates of the week.
[2017-6-4, 2017-6-5, 2017-6-6, 2017-6-7, 2017-6-8, 2017-6-9, 2017-6-10]

I couldn't find any solution on the internet.

Thank you

答:
Try this:

```<code>let dateInWeek = Date()//7th June 2017

let calendar = Calendar.current
let dayOfWeek = calendar.component(.weekday, from: dateInWeek)
let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: dateInWeek)!
let days = (weekdays.lowerBound ..< weekdays.upperBound)
    .compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: dateInWeek) }

print(days)
</code>```

It will give you this:

4 June 2017(Sunday)

  5 June 2017

  6 June 2017

  7 June 2017

  8 June 2017

  9 June 2017

  10 June 2017(Saturday)

Start fromMonday

The above is default behavior for my calendar that's why it is starting from Sunday.

If you want start from Monday then do this change:

```<code>let dayOfWeek = calendar.component(.weekday, from: dateInWeek) - 1
</code>```

It depends on which locale your calendar is in.

Body:
Try this:

let dateInWeek = Date()//7th June 2017

let calendar = Calendar.current
let dayOfWeek = calendar.component(.weekday, from: dateInWeek)
let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: dateInWeek)!
let days = (weekdays.lowerBound ..< weekdays.upperBound)
    .compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: dateInWeek) }

print(days)

It will give you this:

4 June 2017(Sunday)

  5 June 2017

  6 June 2017

  7 June 2017

  8 June 2017

  9 June 2017

  10 June 2017(Saturday)

Start fromMonday

The above is default behavior for my calendar that's why it is starting from Sunday.

If you want start from Monday then do this change:

let dayOfWeek = calendar.component(.weekday, from: dateInWeek) - 1

It depends on which locale your calendar is in.

ContentLicense: CC BY-SA 4.0


问:
Android DDMS and allocation tracking - Identifying what is causing the GC to trigger and why
Good afternoon.

I have been making a small openGL based app for android that loops at the normal 60 fps and does various wondrous things.

I have been keeping an eye on my frame rate and trying to optimise where possible as I am going along. I recently noticed that whilst my program is running sometimes there will be a slight pause. I immediatly suspected that it might be the Garbage Collector running and looking in LogCat there were a few suspect GC's appearing around the times of the dips in fps.

However I am unsure if it is my app that is causing the collects.

So these are my questions about the GC:

1) When I get logging from LogCat it contains a PID (process id?) and here is an example of a typical GC i receive:

```<code>12-14 14:52:40.647: DEBUG/dalvikvm(492): GC_EXPLICIT freed 3831 objects / 203576 bytes in 32ms
</code>```

The 492 is the PID. Is this PID going to be of the process that performs the GC? Or is it a process running on the phone that is also needing a GC?

For example from the same session here is a log from my app using Log.debug:

```<code>12-14 13:50:42.717: DEBUG/Curve(2298): LIFECYCLE - OnStart
</code>```

The PID for my app is not 492, it is 2298. Does this mean the GC was not due to my app?

Using the allocation tracker I have very few allocations occuring. A few lines of logging causing some strings to be generated and the occasional Rect being generated on a user press (I have fixed this so it will only be allocated once now...) So I cannot see how my app itself will be generating the need for GC's.

2) If it is not my app allocating away and is simply some other process that is eating into memory happily should it affect my app at all?

3) Could the very fact I am using the ddms be causing GC's?

4) When I look in to the allocation tracker there are some entries which do not come from any code that I am running / going through myself. One of which was related to thread stats, could this be the ddms?

Sorry if this is really several questions but it is all related to really whether the GC logs I see in my Logcat are actually from my application or not.

Bearing in mind that at the moment my phone is sat not running my app and I am still getting small GC's 5 - 15 seconds. These normally run for 33ms and seems quite small amounts of memory. So I guess this means they are not due to me. - Again basically about the PID and what that shows.

答:
You are correct on 1). Only a subset of the GC logs ing Logcat belong to your app, and those have your app's pid.

Most likely the hiccups are due to background services requesting small allocations. I'd suggest you apply a low-pass filter to the delta time between frames in your game or cap the maximum FPS for an overall smoother experience. Even on iOS it's extremelly difficult to have your game running at 60FPS without eventual hiccups.

ContentLicense: CC BY-SA 2.5

Body:
Good afternoon.

I have been making a small openGL based app for android that loops at the normal 60 fps and does various wondrous things.

I have been keeping an eye on my frame rate and trying to optimise where possible as I am going along. I recently noticed that whilst my program is running sometimes there will be a slight pause. I immediatly suspected that it might be the Garbage Collector running and looking in LogCat there were a few suspect GC's appearing around the times of the dips in fps.

However I am unsure if it is my app that is causing the collects.

So these are my questions about the GC:

1) When I get logging from LogCat it contains a PID (process id?) and here is an example of a typical GC i receive:

12-14 14:52:40.647: DEBUG/dalvikvm(492): GC_EXPLICIT freed 3831 objects / 203576 bytes in 32ms

The 492 is the PID. Is this PID going to be of the process that performs the GC? Or is it a process running on the phone that is also needing a GC?

For example from the same session here is a log from my app using Log.debug:

12-14 13:50:42.717: DEBUG/Curve(2298): LIFECYCLE - OnStart

The PID for my app is not 492, it is 2298. Does this mean the GC was not due to my app?

Using the allocation tracker I have very few allocations occuring. A few lines of logging causing some strings to be generated and the occasional Rect being generated on a user press (I have fixed this so it will only be allocated once now...) So I cannot see how my app itself will be generating the need for GC's.

2) If it is not my app allocating away and is simply some other process that is eating into memory happily should it affect my app at all?

3) Could the very fact I am using the ddms be causing GC's?

4) When I look in to the allocation tracker there are some entries which do not come from any code that I am running / going through myself. One of which was related to thread stats, could this be the ddms?

Sorry if this is really several questions but it is all related to really whether the GC logs I see in my Logcat are actually from my application or not.

Bearing in mind that at the moment my phone is sat not running my app and I am still getting small GC's 5 - 15 seconds. These normally run for 33ms and seems quite small amounts of memory. So I guess this means they are not due to me. - Again basically about the PID and what that shows.


问:
How to slide in text and push another text to the right (CSS)
I'm trying to make the > move in from the side and push the "Lorem" to the right. I'm trying to make it within my CSS.

答:
You can use a pseudo element and transition: max-width

* {
  line-height: 1;
}
span:before {
  max-width: 0;
  overflow: hidden;
  transition: max-width .5s;
  content: '>';
  display: inline-block;
}
span:hover:before {
  max-width: 2em;
}
span {
  display: flex;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span>Lorem</span></code>```

Body:
You can use a pseudo element and transition: max-width

* {
  line-height: 1;
}
span:before {
  max-width: 0;
  overflow: hidden;
  transition: max-width .5s;
  content: '>';
  display: inline-block;
}
span:hover:before {
  max-width: 2em;
}
span {
  display: flex;
  align-items: center;
}

<span>Lorem</span>


问:
Web link to local file
I've got a web page on our corporate intranet.

On this page, we (want to) have download links.  These links (should) point to files in a DFS share.

The client has access to the DFS share (\domain\share\file.exe) but creating a link directly to file:\domain\share\file is blocked by the browser because it's the webpage trying to access a 'local' file.

Edit:  To be clear, the file we want to link to is on a completely different server than the website and is only accessible to the user via a UNC path (it's not a mapped drive or anything).

Without changing the browser settings, how can I make this work?

I'm willing to have some sort of 'pass-thru' php scrip (like this non-working option: PHP - Link to local file) or whatever works.  In the end, telling the user to "copy and paste this url into your windows explorer address bar" isn't really a good option.

答:
To allow links to local files, these files must be under the DocumentRoot of your site, and you should link them from the Documentroot instead of a full local path.

For example, if your DocumentRoot is at c:\www\mysite, your files should be at a subfolder of c:\www\mysite, for example c:\www\mysite\sharedfiles. And then you have to link them from that folder, for example href="/sharedfiles/file.exe">.

If your server is a linux server you could create a symlink from your DocumentRoot to the shared folder. And depending of your server configuration it would work.

Another otpion is to have a PHP file for example that receives a path as a parameter and does a readfile operation, but this is dangerous.

Title: Web link to local file

Body:
To allow links to local files, these files must be under the DocumentRoot of your site, and you should link them from the Documentroot instead of a full local path.

For example, if your DocumentRoot is at c:\www\mysite, your files should be at a subfolder of c:\www\mysite, for example c:\www\mysite\sharedfiles. And then you have to link them from that folder, for example <a href="/sharedfiles/file.exe">.

If your server is a linux server you could create a symlink from your DocumentRoot to the shared folder. And depending of your server configuration it would work.

Another otpion is to have a PHP file for example that receives a path as a parameter and does a readfile operation, but this is dangerous.


问:
Symfony 3 FormType - Entity through options array
I would like to know how to pass my entity correctly and another variable in my createForm function ?

Let me explain, I would like to do this:

```<code>$repo = $em->getRepository('ProjectBundle:Organisation\Organisation');
            $list = $repo->children($this->getUser()->getOrganisation());
            $form = $this->createForm('ProjectBundle\Form\Robot\RobotType', array($entity,$list));
</code>```

I need to pass to my FormType another variable, so I use a array directly.

My FormType:

```<code><?php

namespace ProjectBundle\Form\Robot;

use ProjectBundle\Entity\Robot\Robot;
use ProjectBundle\Form\User\UserType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RobotType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('serial_number')
            ->add('shell_color',ChoiceType::class,array(
                'choices' => Robot::getArrayShellColor()
            ))
            ->add('tray1Color',ChoiceType::class,array(
                'choices' => Robot::getTrayColor()
            ))
            ->add('tray2Color',ChoiceType::class,array(
                'choices' => Robot::getTrayColor()
            ))
            ->add('tray3Color',ChoiceType::class,array(
                'choices' => Robot::getTrayColor()
            ))
            ->add('hasBattery')
            ->add('volume')
            ->add('organisation',null,array('choices' => $options['data'][1]));
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'ProjectBundle\Entity\Robot\Robot'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'projectbundle_robot_new';
    }

}
</code>```

Here I need to get my variable $list, for the organisation field, so it's $options['data'][1].

But I have a mistake, which I understand but I do not know how to correct:

```<code>The form's view data is expected to be an instance of class ProjectBundle\Entity\Robot\Robot, but is a(n) array. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) array to an instance of ProjectBundle\Entity\Robot\Robot.
</code>```

This is normal because now I pass it in an array, it's my variable $options['data'][0] that contains my object now.

How to do ?
Thank you

答:
You should pass ProjectBundle\Entity\Robot\Robot entity to the createForm method as a second parameter and an options array as a third parameter.</p>

```<code>$form = $this->createForm('ProjectBundle\Form\Robot\RobotType', $entity, array($list));
</code>```

Body:
I would like to know how to pass my entity correctly and another variable in my createForm function ?

Let me explain, I would like to do this:

$repo = $em->getRepository('ProjectBundle:Organisation\Organisation');
            $list = $repo->children($this->getUser()->getOrganisation());
            $form = $this->createForm('ProjectBundle\Form\Robot\RobotType', array($entity,$list));

I need to pass to my FormType another variable, so I use a array directly.

My FormType:

<?php

namespace ProjectBundle\Form\Robot;

use ProjectBundle\Entity\Robot\Robot;
use ProjectBundle\Form\User\UserType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RobotType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('serial_number')
            ->add('shell_color',ChoiceType::class,array(
                'choices' => Robot::getArrayShellColor()
            ))
            ->add('tray1Color',ChoiceType::class,array(
                'choices' => Robot::getTrayColor()
            ))
            ->add('tray2Color',ChoiceType::class,array(
                'choices' => Robot::getTrayColor()
            ))
            ->add('tray3Color',ChoiceType::class,array(
                'choices' => Robot::getTrayColor()
            ))
            ->add('hasBattery')
            ->add('volume')
            ->add('organisation',null,array('choices' => $options['data'][1]));
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'ProjectBundle\Entity\Robot\Robot'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'projectbundle_robot_new';
    }

}

Here I need to get my variable $list, for the organisation field, so it's $options['data'][1].

But I have a mistake, which I understand but I do not know how to correct:

The form's view data is expected to be an instance of class ProjectBundle\Entity\Robot\Robot, but is a(n) array. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) array to an instance of ProjectBundle\Entity\Robot\Robot.

This is normal because now I pass it in an array, it's my variable $options['data'][0] that contains my object now.

How to do ?
Thank you

Body:
You should pass ProjectBundle\Entity\Robot\Robot entity to the createForm method as a second parameter and an options array as a third parameter.

$form = $this->createForm('ProjectBundle\Form\Robot\RobotType', $entity, array($list));


问:
How can I translate a perl script to Java?

Possible Duplicate:

  How can I convert OO Perl to Java?

Hello.

I have a perl script and I want to translate it to Java.

Is there any translator/conversor from perl script to Java?

By the way, I'm developing an Android 2.2 application.

EDIT

I have closed the question. Stop downvoting me!!!!!! And if you downvote tell us why!!

Thanks.

答: No. There's the JPL project from the 90's that might've been a workaround, but I'm pretty sure it fell apart along the road.</p>


问:
Azure Search - Additional Stop Words
When creating an index definition in Azure Search, is there any way to add additional stop words just for that index. For example if you are indexing street names one would like to strip out Road, Close, Avenue etc.

And if one makes the field non-searchable i.e. the whole thing is indexed as one term, then what happens to something like Birken Court Road. Would the term being indexed be Birken Court.
Many thanks

答:
You can define an additional set of stopwords using a custom analyzer.
For example,

```<code>{
 "name":"myindex",
 "fields":[
    {
       "name":"id",
       "type":"Edm.String",
       "key":true,
       "searchable":false
    },
    {
       "name":"text",
       "type":"Edm.String",
       "searchable":true,
       "analyzer":"my_analyzer"
    }
 ],
 "analyzers":[
    {
       "name":"my_analyzer",
       "@odata.type":"#Microsoft.Azure.Search.CustomAnalyzer",
       "tokenizer":"standard_v2",
       "tokenFilters":[
          "lowercase",
          "english_stopwords",
          "my_stopwords"
       ]
    }
 ],
 "tokenFilters":[
    {
       "name":"english_stopwords",
       "@odata.type":"#Microsoft.Azure.Search.StopwordsTokenFilter",
       "stopwordsList":"english"
    },
    {
       "name":"my_stopwords",
       "@odata.type":"#Microsoft.Azure.Search.StopwordsTokenFilter",
       "stopwords": ["road", "avenue"]
    }
 ]
}
</code>```

In this index definition I'm setting a custom analyzer on the text field that used the standard tokenizer, lowercase token filter and two stopwords token filters, one for standard english stopwords and one for the additional set of stopwords. You can test the behavior of your custom analyzer with the Analyze API, for example:

request:

```<code>{
   "text":"going up the road",
   "analyzer": "my_analyzer"
}
</code>```

response:

```<code>{
  "tokens": [
    {
      "token": "going",
      "startOffset": 0,
      "endOffset": 5,
      "position": 0
    },
    {
      "token": "up",
      "startOffset": 6,
      "endOffset": 8,
      "position": 1
    }
  ]
}
</code>```

Analyzers are not applied to non-searchable fields, therefore the stopword in your example would not be removed. To learn more about query and document processing see: How full text search works in Azure Search.

Title: Azure Search - Additional Stop Words

Body:
You can define an additional set of stopwords using a custom analyzer.
For example,

{
 "name":"myindex",
 "fields":[
    {
       "name":"id",
       "type":"Edm.String",
       "key":true,
       "searchable":false
    },
    {
       "name":"text",
       "type":"Edm.String",
       "searchable":true,
       "analyzer":"my_analyzer"
    }
 ],
 "analyzers":[
    {
       "name":"my_analyzer",
       "@odata.type":"#Microsoft.Azure.Search.CustomAnalyzer",
       "tokenizer":"standard_v2",
       "tokenFilters":[
          "lowercase",
          "english_stopwords",
          "my_stopwords"
       ]
    }
 ],
 "tokenFilters":[
    {
       "name":"english_stopwords",
       "@odata.type":"#Microsoft.Azure.Search.StopwordsTokenFilter",
       "stopwordsList":"english"
    },
    {
       "name":"my_stopwords",
       "@odata.type":"#Microsoft.Azure.Search.StopwordsTokenFilter",
       "stopwords": ["road", "avenue"]
    }
 ]
}

In this index definition I'm setting a custom analyzer on the text field that used the standard tokenizer, lowercase token filter and two stopwords token filters, one for standard english stopwords and one for the additional set of stopwords. You can test the behavior of your custom analyzer with the Analyze API, for example:

request:

{
   "text":"going up the road",
   "analyzer": "my_analyzer"
}

response:

{
  "tokens": [
    {
      "token": "going",
      "startOffset": 0,
      "endOffset": 5,
      "position": 0
    },
    {
      "token": "up",
      "startOffset": 6,
      "endOffset": 8,
      "position": 1
    }
  ]
}

Analyzers are not applied to non-searchable fields, therefore the stopword in your example would not be removed. To learn more about query and document processing see: How full text search works in Azure Search.


问:
Get Woocommerce Cart Product Image Url So I can use it as background image instead
In cart.php we have:

```<code><td class="product-thumbnail" style='background:url(<?php ?>)'>
                            <?php
                                $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );

                                if ( ! $product_permalink ) {
                                    echo $thumbnail;
                                } else {
                                    printf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $thumbnail );
                                }
                            ?>
                        </td>
</code>```

Is there a way to get the url from that so I can use a background image on the td element instead of the image tag inside?

答:
Was able to get it to work using

```<code><?php echo get_the_post_thumbnail_url($product_id);?>
</code>```

If for whatever reason, this isn't the best way to solve this problem, please share.

Thanks.

Body:
In cart.php we have:

<td class="product-thumbnail" style='background:url(<?php ?>)'>
                            <?php
                                $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );

                                if ( ! $product_permalink ) {
                                    echo $thumbnail;
                                } else {
                                    printf( '%s', esc_url( $product_permalink ), $thumbnail );
                                }
                            ?>

Is there a way to get the url from that so I can use a background image on the td element instead of the image tag inside?

Body:
Was able to get it to work using

<?php echo get_the_post_thumbnail_url($product_id);?>

If for whatever reason, this isn't the best way to solve this problem, please share.

Thanks.


问:
Cannot Perform Operation: The resource is not on the build path of a Java project
I am having problems using Eclipse IDE features. When trying to find all references to a method within a project (by right clicking a method and choosing References -> Project) I get the error "The resource is not on the build path of a Java project".

Additionally, I have another (probably related) error described here Eclipse Open declaration in Java project. I think these issues have to do with the way I imported the project or a lack of some software/plugin in Eclipse. I imported the project using File -> Import -> Existing Maven Projects after I git cloned the repository from Github.

Some of the things I have found on the internet about how to fix this problem involves modifying the Build Path or Facets properties of the project but I don't have either of these options:

What needs to be done to allow reference searching and other IDE features?

答:
You need to convert your Eclipse project to Maven Project:

1) Right click on the project,

2) Configure,

3) Convert to Maven Project

==> This will re-organize your project to a common Maven project structure.


答:
Clang is correct.

$17.6.2/3 Dependent names [temp.dep]

In the definition of a class or class template, the scope of a dependent base class is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.

For return data;, data is unqualified, then unqualified name lookup will be employed. This means the name in the base class Base<T> (which is a dependent base class because it depends on the template parameter T) shouldn't be found; i.e. the non-dependent names are not looked up in dependent base classes.

this->data or Base<T>::data makes it qualified. This means the name will be looked up at the time of instantiation, and at that time the exact base specialization that must be explored will be known.

Title: Is this-> mandatory to access Base<T> identifiers from derived classes?


问:
Bitmap rotation in Xamarin.Android
How do you rotate Bitmap by 90 degrees in Xamarin.Android? I am using ZXing.Net.Mobile, C#/.NET Barcode Scanning Library and would like to print barcode vertically. Thanks in advance.</p>

答:
Once you have the barcode bitmap:

```<code>var barcodeWriter = new ZXing.Mobile.BarcodeWriter
{
    Format = ZXing.BarcodeFormat.CODE_128,
    Options = new ZXing.Common.EncodingOptions
    {
        Width = 300,
        Height = 300
    }
};

var barcode = barcodeWriter.Write("ZXing.Net.Mobile");
</code>```

You can rotate it with this:

```<code>var barcodeRotated = RotateImage(barcode, 90);
</code>```

Here's the function:

```<code>private Bitmap RotateImage(Bitmap src, float degrees)
{
    var matrix = new Matrix();

    matrix.PostRotate(degrees);

    return Bitmap.CreateBitmap(src, 0, 0, src.Width, src.Height, matrix, true);
}
</code>```

Result:

Hope this helps!

Title: Bitmap rotation in Xamarin.Android

Body:
Once you have the barcode bitmap:

var barcodeWriter = new ZXing.Mobile.BarcodeWriter
{
    Format = ZXing.BarcodeFormat.CODE_128,
    Options = new ZXing.Common.EncodingOptions
    {
        Width = 300,
        Height = 300
    }
};

var barcode = barcodeWriter.Write("ZXing.Net.Mobile");

You can rotate it with this:

var barcodeRotated = RotateImage(barcode, 90);

Here's the function:

private Bitmap RotateImage(Bitmap src, float degrees)
{
    var matrix = new Matrix();

    matrix.PostRotate(degrees);

    return Bitmap.CreateBitmap(src, 0, 0, src.Width, src.Height, matrix, true);
}

Result:

Hope this helps!


问:
PHP Error - 'Can't use function return value in write context'
So, I just got this error on a page that is meant to show some product categories:

Fatal error: Can't use function return value in write context in /home/name/public_html/wp-content/themes/name/taxonomy-prodcat.php on line 37

On line 37 is this code:

```<code><?php if(!empty(get_field('product_size', get_the_ID()))): ?>
                                            <p class="producttext"><span class="boldproduct">Size -</span> <?php echo get_field('product_size', get_the_ID()); ?></p>
                                        <?php endif; ?>
</code>```

PHP Version 5.6.30
MySQL Version   5.6.35

I really cant find the problem. Any help ?

答:
```<code><?php
$values = get_field( 'product_size' , get_the_ID());
if ( $values ) { ?>
    <p class="producttext"><span class="boldproduct">Size -</span> <?php echo get_field('product_size', get_the_ID()); ?></p>
<?php
} ?>
</code>```

Body:
So, I just got this error on a page that is meant to show some product categories:

Fatal error: Can't use function return value in write context in /home/name/public_html/wp-content/themes/name/taxonomy-prodcat.php on line 37

On line 37 is this code:

<?php if(!empty(get_field('product_size', get_the_ID()))): ?>

Size - <?php echo get_field('product_size', get_the_ID()); ?>

                                        <?php endif; ?>

PHP Version 5.6.30
MySQL Version   5.6.35

I really cant find the problem. Any help ?


问:
Problems css height and positioning of text fields in form
I'm having a problem with a textarea and submitbuttons in my form.

Here's a first screenshot of a seemingly normal situation:

And here's what happens if I set the textarea to have 30 columns:

The textarea just went right over the buttons. I'd expect the buttons to be pushed down. Or anything below it, for that matter. What do I need to set to make this happen?

答:
Most likely (and you should show more CSS code to be sure) you have your labels/fields floated inside an element with fixed height..

Use an element with clear:both after the textarea..


问:
SmartCard - It seems that Card Manager doesn't exist
I have a processor card (Oberthur COSMO), the ATR is 3B 04 68 EA 90 00, but I am unable to select card manager by APDU, I have tried a lot of AID but unsuccessfully. I also tried to select master file but I got the same result.
My question is, Is card manager installed by manufacturer or we can download and install it and how can we install it?</p>

Body: Try A0 00 00 00 77 01 00 70 0A 10 00 F1 00 00 01 00 as a cardmanager AID.


问:
Sort columns in a matrix
I have a matrix (or a multidimensional array) of non unique values like this one:

```<code>var matrix = [
                [1, 3, 2, 4, 1],
                [2, 4, 1, 3, 2],
                [4, 3, 2, 1, 4]
             ]
</code>```

I want to sort a row of this matrix but the others rows should reorder the same in order to keep the column like organization.

```<code>//matrix sorted by the row 0
var sorted_matrix = [
                      [1, 1, 2, 3, 4],
                      [2, 2, 1, 4, 3],
                      [4, 4, 2, 3, 1]
                    ]
</code>```

I would prefer a lodash solution if possible.

答:
Using lodash you could transpose the matrix with zip, sort it with sortBy by a given row number, and then transpose it back:

```<code>_.zip.apply(_, _.sortBy(_.zip.apply(_, matrix), row))
</code>```

var matrix = [
    [1, 3, 2, 4, 1],
    [2, 4, 1, 3, 2],
    [4, 3, 2, 1, 4]
];
var row = 0;

result = _.zip.apply(_, _.sortBy(_.zip.apply(_, matrix), row));

console.log(result.join('\n'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script></code>```

With the rest parameter syntax you can also write this as:

```<code>_.zip(..._.sortBy(_.zip(...matrix), row));
</code>```

Title: Sort columns in a matrix

Body:
I have a matrix (or a multidimensional array) of non unique values like this one:

var matrix = [
                [1, 3, 2, 4, 1],
                [2, 4, 1, 3, 2],
                [4, 3, 2, 1, 4]
             ]

I want to sort a row of this matrix but the others rows should reorder the same in order to keep the column like organization.

//matrix sorted by the row 0
var sorted_matrix = [
                      [1, 1, 2, 3, 4],
                      [2, 2, 1, 4, 3],
                      [4, 4, 2, 3, 1]
                    ]

I would prefer a lodash solution if possible.

Body:
Using lodash you could transpose the matrix with zip, sort it with sortBy by a given row number, and then transpose it back:

_.zip.apply(_, _.sortBy(_.zip.apply(_, matrix), row))

var matrix = [
    [1, 3, 2, 4, 1],
    [2, 4, 1, 3, 2],
    [4, 3, 2, 1, 4]
];
var row = 0;

result = _.zip.apply(_, _.sortBy(_.zip.apply(_, matrix), row));

console.log(result.join('\n'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

With the rest parameter syntax you can also write this as:

_.zip(..._.sortBy(_.zip(...matrix), row));


问:
fmt.Sscanf for structs
I have data which was previously serialized as fmt.Sprintf("%+v", d), d being a struct instance. Is there a way to scan it back? My naive attempt of using fmt.Sscanf() below is failing (Go Playground).

```<code>package main

import (
    "fmt"
)

type data struct {
    f int
}

func main() {
    x := data{1}
    s := fmt.Sprintf("%+v", x)
    var y data
    n, err := fmt.Sscanf(s, "%+v", &y)
    fmt.Printf("s=%s, n=%d, err=%+v, y=%+v\n", s, n, err, y)
}
</code>```

The output is:

```<code>s={f:1}, n=0, err=can't scan type: *main.data, y={f:0}
</code>```

Is there a way to scan the struct back?

答:
Unfortunately the fmt package doesn't produce strictly parseable output. Thankfully go has other packages for marshaling data which should be just as easy to use.

I'd recommend json for something simple:

```<code>s, err := json.Marshal(data)
// Check err
err = json.Unmarshal(s, data)
</code>```

json will produce output which is somewhat similar to printf, but conforming to a standard which ensures it can be parsed. If your goal is to parse data that exists only in Printf'd form you may be out of luck.

Title: fmt.Sscanf for structs

Body:
I have data which was previously serialized as fmt.Sprintf("%+v", d), d being a struct instance. Is there a way to scan it back? My naive attempt of using fmt.Sscanf() below is failing (Go Playground).

package main

import (
    "fmt"
)

type data struct {
    f int
}

func main() {
    x := data{1}
    s := fmt.Sprintf("%+v", x)
    var y data
    n, err := fmt.Sscanf(s, "%+v", &y)
    fmt.Printf("s=%s, n=%d, err=%+v, y=%+v\n", s, n, err, y)
}

The output is:

s={f:1}, n=0, err=can't scan type: *main.data, y={f:0}

Is there a way to scan the struct back?

Body:
Unfortunately the fmt package doesn't produce strictly parseable output. Thankfully go has other packages for marshaling data which should be just as easy to use.

I'd recommend json for something simple:

s, err := json.Marshal(data)
// Check err
err = json.Unmarshal(s, data)

json will produce output which is somewhat similar to printf, but conforming to a standard which ensures it can be parsed. If your goal is to parse data that exists only in Printf'd form you may be out of luck.


问:
How can I list the taints on Kubernetes nodes?
The docs are great about explaining how to set a taint on a node, or remove one. And I can use kubectl describe node to get a verbose description of one node, including its taints. But what if I've forgotten the name of the taint I created, or which nodes I set it on? Can I list all of my nodes, with any taints that exist on them?

答:
In Kubernetes 1.6.x the node taints have moved into the spec. Therefore the above answer by jaxxstorm will not work. Instead, you can use the following template.

{{printf "%-50s %-12s\n" "Node" "Taint"}}
{{- range .items}}
    {{- if $taint := (index .spec "taints") }}
        {{- .metadata.name }}{{ "\t" }}
        {{- range $taint }}
            {{- .key }}={{ .value }}:{{ .effect }}{{ "\t" }}
        {{- end }}
        {{- "\n" }}
    {{- end}}
{{- end}}
```

<p>I have that saved into a file and then reference it like so:</p>

```kubectl get nodes -o go-template-file="./nodes-taints.tmpl"
```

<p>You'll get output like so:</p>

```Node                                            Taint
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=etcd:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=jenkins:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=etcd:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=containerlinux-canary-channel-workers:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=jenkins:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=etcd:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=etcd:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=etcd:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=jenkins:NoSchedule
```

<p>I'm not a huge go template user so I'm sure there are some things I could have done better but it is what it is.</p>

<hr>

<p>Same as above but all in one line:</p>

```kubectl get nodes -o go-template='{{printf "%-50s %-12s\n" "Node" "Taint"}}{{- range .items}}{{- if $taint := (index .spec "taints") }}{{- .metadata.name }}{{ "\t" }}{{- range $taint }}{{- .key }}={{ .value }}:{{ .effect }}{{ "\t" }}{{- end }}{{- "\n" }}{{- end}}{{- end}}'
```

Body:
In Kubernetes 1.6.x the node taints have moved into the spec. Therefore the above answer by jaxxstorm will not work. Instead, you can use the following template.

{{printf "%-50s %-12s\n" "Node" "Taint"}}
{{- range .items}}
    {{- if $taint := (index .spec "taints") }}
        {{- .metadata.name }}{{ "\t" }}
        {{- range $taint }}
            {{- .key }}={{ .value }}:{{ .effect }}{{ "\t" }}
        {{- end }}
        {{- "\n" }}
    {{- end}}
{{- end}}

I have that saved into a file and then reference it like so:

kubectl get nodes -o go-template-file="./nodes-taints.tmpl"

You'll get output like so:

Node                                            Taint
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=etcd:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=jenkins:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=etcd:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=containerlinux-canary-channel-workers:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=jenkins:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=etcd:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=etcd:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=etcd:NoSchedule
ip-xxx-xxx-xxx-xxx.us-west-2.compute.internal   dedicate=jenkins:NoSchedule

I'm not a huge go template user so I'm sure there are some things I could have done better but it is what it is.

Same as above but all in one line:

kubectl get nodes -o go-template='{{printf "%-50s %-12s\n" "Node" "Taint"}}{{- range .items}}{{- if $taint := (index .spec "taints") }}{{- .metadata.name }}{{ "\t" }}{{- range $taint }}{{- .key }}={{ .value }}:{{ .effect }}{{ "\t" }}{{- end }}{{- "\n" }}{{- end}}{{- end}}'


问:
Python and Selenium with PhantomJS gives empty page
I'm using Python with Selenium and PhantomJS.

When I try to visit webpages with Socks4 or Socks5 proxy, I get an empty page.

```<code>phantomjs_path = '/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs'
service_args = [
    '--proxy=209.141.36.93:1080',
    '--proxy-type=socks4',
    '--ignore-ssl-errors=true',
    '--ssl-protocol=any',
]
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (
    "Mozilla/5.0 (Linux; Android 6.0.1; SM-G920V Build/MMB29K) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36"
)

driver = webdriver.PhantomJS(desired_capabilities=dcap,
                             service_args=service_args,
                             executable_path=phantomjs_path)

driver.get("http://2ip.ru")
time.sleep(10)
print driver.current_url
print driver.page_source
</code>```

Result:

```<code>about:blank
<html><head></head><body></body></html>
</code>```

Help please.

答:
So I think this is related to the SSL encryption of the https sites so adding explicit waits isn't going to help.

From a previous post I noted that the following worked, call the PhantomJS driver as:

```<code>driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true', '--ssl-protocol=TLSv1'])
</code>```

Body:
I'm using Python with Selenium and PhantomJS.

When I try to visit webpages with Socks4 or Socks5 proxy, I get an empty page.

phantomjs_path = '/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs'
service_args = [
    '--proxy=209.141.36.93:1080',
    '--proxy-type=socks4',
    '--ignore-ssl-errors=true',
    '--ssl-protocol=any',
]
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (
    "Mozilla/5.0 (Linux; Android 6.0.1; SM-G920V Build/MMB29K) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36"
)

driver = webdriver.PhantomJS(desired_capabilities=dcap,
                             service_args=service_args,
                             executable_path=phantomjs_path)

driver.get("http://2ip.ru")
time.sleep(10)
print driver.current_url
print driver.page_source

Result:

about:blank

Help please.

Body:
So I think this is related to the SSL encryption of the https sites so adding explicit waits isn't going to help.

From a previous post I noted that the following worked, call the PhantomJS driver as:

driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true', '--ssl-protocol=TLSv1'])


问:
C# program calling to directory on my (developer) computer when running on other's
So I've just made my first C# program on Visual Studio. I then copied everything from the release folder (including 1 .exe file, dll files, 1 config file and 1 pdb file) then sent it to another computer. The problem here is that the exe file works fine on my computer, but on the others they crash when it run the first command that requires the dll file, and on the error message that I catch it says that problem is on line xx of "my computer's path to the file", even though it's running on the other's.

Source code of where the crash happens:

```<code>Console.WriteLine("Enter file path (Example: C:\\Benchmarking.xlsx)");
string fileName = Console.ReadLine();
FileInfo xlFile = new FileInfo(@fileName);
ExcelPackage package = new ExcelPackage(xlFile);
</code>```

Error: System.NullReferenceException:Object reference not set to an instance of an object.

This is using EPPLUS to read excel files

答: You are using a debug build which includes .PDB files.  PDB files point to the paths on the machine on which the code was compiled.  When an exception is thrown, you'll see the old paths.</p>

Body:
So I've just made my first C# program on Visual Studio. I then copied everything from the release folder (including 1 .exe file, dll files, 1 config file and 1 pdb file) then sent it to another computer. The problem here is that the exe file works fine on my computer, but on the others they crash when it run the first command that requires the dll file, and on the error message that I catch it says that problem is on line xx of "my computer's path to the file", even though it's running on the other's.

Source code of where the crash happens:

Console.WriteLine("Enter file path (Example: C:\\Benchmarking.xlsx)");
string fileName = Console.ReadLine();
FileInfo xlFile = new FileInfo(@fileName);
ExcelPackage package = new ExcelPackage(xlFile);

Error: System.NullReferenceException:Object reference not set to an instance of an object.

This is using EPPLUS to read excel files


问:
Password-checker JavaScript and HTML <form>
I am trying to have a website display different messages depending on whether the password entered is correct or not (correct password is thePassword). So far, no luck.

According to Chrome, the error is in this line (first line of the function):

if (document.getElementById("psw") = "thePassword") {

JSFiddle: https://jsfiddle.net/5grtmxd4/

Thanks in advance!

```<code><!DOCTYPE html>
<html>
<head>
</head>
<body>
  <form>
    Password<br>
    <input id="psw" type="password" name="password" size="45" autofocus></input><br><br>
    <input type="submit" value="Submit" onclick="message();"></input>
  </form>
<script>
function message () {
  if (document.getElementById("psw") = "thePassword") {
    document.getElementById("display").innerHTML = "Logged in";
  } else {
    document.getElementById("display").innerHTML = "Try again!";
  }}
</script>
<p id="display"></p>
</body>
</html>
</code>```

EDIT: I would appreciate that instead of trying to rewrite the entire code, only neccessary changes are made. Thanks!

答:
There are several things wrong with your code:

Compare .value, not the element itself

Comparing is (at least) == instead of = (assignment)

Do not use a submit button as a trigger, since this will reset the page right after clicking the button

Please find an updated version at https://jsfiddle.net/5grtmxd4/1/

```<code>function message() {
    if (document.getElementById("psw").value == "thePassword") {
        document.getElementById("display").innerHTML = "Logged in";
    } else {
        document.getElementById("display").innerHTML = "Try again!";
    }
}
</code>```

Body:
I am trying to have a website display different messages depending on whether the password entered is correct or not (correct password is thePassword). So far, no luck.

According to Chrome, the error is in this line (first line of the function):

if (document.getElementById("psw") = "thePassword") {

JSFiddle: https://jsfiddle.net/5grtmxd4/

Thanks in advance!

<!DOCTYPE html>

  <form>
    Password

    <input id="psw" type="password" name="password" size="45" autofocus></input>

    <input type="submit" value="Submit" onclick="message();"></input>
  </form>

EDIT: I would appreciate that instead of trying to rewrite the entire code, only neccessary changes are made. Thanks!

Body:
There are several things wrong with your code:

Compare .value, not the element itself

Comparing is (at least) == instead of = (assignment)

Do not use a submit button as a trigger, since this will reset the page right after clicking the button

Please find an updated version at https://jsfiddle.net/5grtmxd4/1/

function message() {
    if (document.getElementById("psw").value == "thePassword") {
        document.getElementById("display").innerHTML = "Logged in";
    } else {
        document.getElementById("display").innerHTML = "Try again!";
    }
}


问:
afnetworking can't send body to node.js server, how use?
AFNetworking set the http body, but my node.js server can't recv the body.

Use the NSURLConnection can work.

```<code>    //第一步，创建URL
NSURL *testurl = [NSURL URLWithString:@"http://192.168.1.7:1111/xx/xx/xxx"];
//第二步，创建请求
NSMutableURLRequest *testrequest = [[NSMutableURLRequest alloc]initWithURL:testurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
[testrequest setHTTPMethod:@"POST"];//设置请求方式为POST，默认为GET
NSString *str = @"{'body':{'command':'xxxxx'}}";//设置参数
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[testrequest setHTTPBody:data];
//第三步，连接服务器

NSData *received = [NSURLConnection sendSynchronousRequest:testrequest returningResponse:nil error:nil];

NSString *str1 = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];

NSLog(@"%@",str1);
</code>```

afnetworking  body not work for node.js

```<code>NSDictionary *body =  @{ @"body": @{ @"command": @"xxxx"} };
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

AFURLSessionManager *afmanager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"http://192.168.1.7:1111/xx/xx/xxx"] parameters:nil error:nil];

req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

[[afmanager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

    if (!error) {
        NSLog(@"Reply JSON: %@", responseObject);

        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            //blah blah
        }
    } else {
        NSLog(@"Error: %@, %@, %@", error, response, responseObject);
    }
}] resume];
</code>```

Node.js server, use express.

```<code>req.on('data', function (chunk) {
    body.push(chunk);
});
</code>```

This image is charles captured data.  Seems like same, and I can't capture the hex value to compare they are really different！！！！

答:
On the node.js side if you are using body-parser's JSON request parsing middleware and an 'application/json' request is detected, then the parsed contents of the request will be available on req.body and no data will be emitted from req (because the middleware already consumed it).

For any other type of request not handled by any middleware you're using, data should be available on req as expected.

Body:
AFNetworking set the http body, but my node.js server can't recv the body.

Use the NSURLConnection can work.

    //第一步，创建URL
NSURL *testurl = [NSURL URLWithString:@"http://192.168.1.7:1111/xx/xx/xxx"];
//第二步，创建请求
NSMutableURLRequest *testrequest = [[NSMutableURLRequest alloc]initWithURL:testurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
[testrequest setHTTPMethod:@"POST"];//设置请求方式为POST，默认为GET
NSString *str = @"{'body':{'command':'xxxxx'}}";//设置参数
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[testrequest setHTTPBody:data];
//第三步，连接服务器

NSData *received = [NSURLConnection sendSynchronousRequest:testrequest returningResponse:nil error:nil];

NSString *str1 = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];

NSLog(@"%@",str1);

afnetworking  body not work for node.js

NSDictionary *body =  @{ @"body": @{ @"command": @"xxxx"} };
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

AFURLSessionManager *afmanager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"http://192.168.1.7:1111/xx/xx/xxx"] parameters:nil error:nil];

req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

[[afmanager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

    if (!error) {
        NSLog(@"Reply JSON: %@", responseObject);

        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            //blah blah
        }
    } else {
        NSLog(@"Error: %@, %@, %@", error, response, responseObject);
    }
}] resume];

Node.js server, use express.

req.on('data', function (chunk) {
    body.push(chunk);
});

This image is charles captured data.  Seems like same, and I can't capture the hex value to compare they are really different！！！！


问:
git bash how to enable quick edit mode?
(my OS is win 10) I can't find option to enable QuickEdit mode?

when I select block with left click, git bash copy(extend from win 10 command line) by execute Ctrl + C automatically. So it terminate process as the following picture.
How can I do?

PS: Ctrl-C is not my action,but by terminal automatically when I release left mouse clicking for selecting text

答:
You're not using the Windows Console; you're using a terminal built for cygwin, a unix emulation environment. The usual default behaviour for unix terminals is to place text in the clipboard as soon as you select it. You don't need to press Ctrl-C or any other key. </p>

<p>(I don't have your terminal, so I can't verify that this will help, but there's a very good chance that this will address your issue.)</p>

Title: git bash how to enable quick edit mode?

Body:
You're not using the Windows Console; you're using a terminal built for cygwin, a unix emulation environment. The usual default behaviour for unix terminals is to place text in the clipboard as soon as you select it. You don't need to press Ctrl-C or any other key.

(I don't have your terminal, so I can't verify that this will help, but there's a very good chance that this will address your issue.)


问:
How to properly structure this query?
How can I structure a query in Google Sheets that will combine cells with the same text (name 1, name 2, etc) and then sum their associated numeric values in column B (sale 1, sale 2, etc) and sort in descending order?  The end goal is to use this to create a labeled by name but sorted by largest to smallest sale number as it seems you cannot edit the table itself without changing the data it is drawing data from.

I have a table with a lot of different data corresponding to sales made by various people and am looking to make a chart that shows total amount of sales per person. I am still new to queries so feel like I am missing a simple solution to this.

答:
Try this:</p>

```<code>=Query(A2:B,"select A, sum(B) group by A order by sum(B) desc label sum(B) ''")
</code>```

Title: How to properly structure this query?

Body:
Try this:

=Query(A2:B,"select A, sum(B) group by A order by sum(B) desc label sum(B) ''")


问:
Meteor - synchronizing meteor packages among developer's machines
I'm actually not doing this but planning to do it in the future.

I know that you can recreate a meteor project in another developer's PC by pushing it to github and checking the .meteor directory (although not the local sub directory). That way, when another developer clones it to her PC and do:

meteor npm install

meteor run

Every package, meteor and npm, is going to be installed along with the specific version of meteor release (which is in .meteor/release).

Now, my question is:
after adding, upgrading, removing some meteor packages and pushing .meteor directory changes to github, are other developer's meteor packages going to synchronize accordingly, after doing meteor run? I mean all his/her meteor packages are going to be added, upgraded, removed to be exactly as you originally did?

Is this the way to have the exact meteor environment (meteor packages) in every meteor developer's machine?

Many thanks for your help and bye ...

答:
Well, as I can see, meteor really synchronizes everything when it encounters changes in .meteor files, for example packages or versions.

So, the idea, as meteor experts say all the time, is to check this folder to github to, kind of, propagate the changes your project has received.

I don't know for sure if the meteor version is also synchronized in other PC's when meteor finds a new version in .meteor/release. For example, imagine you upgrade your version from 1.4 to 1.5. I suppose meteor will update this new version to .meteor/release. Then it is going to go to github repo and other programmers will pull the file. Then the question is: is meteor going to upgrade itself in response to this change? I suppose it will.

Thanks and bye ...


问:
How to SELECT top different value using order by matrics
i have a table like this

i want to get the row of each table that have min responsetime

i have tried this query :

```<code>select tablename,
       index1,
       index2,
       min(responsetime)
from   tableconf
group by tablename
order by responsetime asc
</code>```

but it doesn't give what i want

the output that i want is

```<code>+------------------+------------------+--------+--------------+
|    tablename     |     index1       | index2 | responsetime |
+------------------+------------------+--------+--------------+
| salesorderheader | TotalDue         | NULL   |       6.1555 |
| salesterritory   | Name             | NULL   |     11.66667 |
| store            | BusinessEntityId | Name   |       3.6222 |
| previous         | previous         | NULL   |      5.03333 |
| NONE             | NONE             | NULL   |          5.6 |
+------------------+------------------+--------+--------------+
</code>```

what query i should use for get the output that i want

答:
(Edited from previous answer)

I don't know if all SQL syntax accept a comma separated where parameter. Another option building off of the highest voted answer right now utilizes a join:

```<code>select *
from tableconf t
inner join (
           select tablename, min(responsetime) min_rt
           from tableconf t2
           group by tablename
           ) t3 on t.tablename = t2.tablename and t.responsetime = t2.min_rt
</code>```

Body:
i have a table like this

i want to get the row of each table that have min responsetime

i have tried this query :

select tablename,
       index1,
       index2,
       min(responsetime)
from   tableconf
group by tablename
order by responsetime asc

but it doesn't give what i want

the output that i want is

+------------------+------------------+--------+--------------+
|    tablename     |     index1       | index2 | responsetime |
+------------------+------------------+--------+--------------+
| salesorderheader | TotalDue         | NULL   |       6.1555 |
| salesterritory   | Name             | NULL   |     11.66667 |
| store            | BusinessEntityId | Name   |       3.6222 |
| previous         | previous         | NULL   |      5.03333 |
| NONE             | NONE             | NULL   |          5.6 |
+------------------+------------------+--------+--------------+

what query i should use for get the output that i want

Body:
(Edited from previous answer)

I don't know if all SQL syntax accept a comma separated where parameter. Another option building off of the highest voted answer right now utilizes a join:

select *
from tableconf t
inner join (
           select tablename, min(responsetime) min_rt
           from tableconf t2
           group by tablename
           ) t3 on t.tablename = t2.tablename and t.responsetime = t2.min_rt


问:
django change font size and font family in tinymce
I have this script in my base file...

```<code><script src="//tinymce.cachefly.net/4.1/tinymce.min.js"></script>
<script>
tinymce.init({selector:'textarea',
plugins: [
    "advlist autolink lists link image charmap print preview hr anchor pagebreak",
    "searchreplace wordcount visualblocks visualchars code fullscreen",
    "insertdatetime media nonbreaking save table contextmenu directionality",
    "emoticons template paste textcolor colorpicker textpattern"
    ],
});
</script>
</code>```

In my tinymce text editor I see font of size I guess 10 px but I want to change it to 16 px and also want to change the font family..

Any help ??

答:
Please see the settings.py config that worked for me:

```<code>TINYMCE_DEFAULT_CONFIG = {
'theme': "advanced", # default value
'relative_urls': False, # default value
'plugins': 'table,spellchecker,paste,searchreplace',
'theme_advanced_buttons1': 'bold,italic,underline,bullist,numlist,link,unlink,styleselect,fontselect,fontsizeselect',
'width': '100%',
'height': 300,
'paste_text_sticky': True,
'paste_text_sticky_default': True,
'valid_styles': 'font-weight,font-style,text-decoration',
'fontsize_formats': "8pt 10pt 11pt 12pt 13pt 14pt 16pt 18pt 20pt 24pt 36pt",
'font_formats': "Andale Mono=andale mono,times;" +
    "Arial=arial,helvetica,sans-serif;" +
    "Arial Black=arial black,avant garde;" +
    "Book Antiqua=book antiqua,palatino;" +
    "Comic Sans MS=comic sans ms,sans-serif;" +
    "Courier New=courier new,courier;" +
    "Georgia=georgia,palatino;" +
    "Helvetica=helvetica;" +
    "Impact=impact,chicago;" +
    "Symbol=symbol;" +
    "Tahoma=tahoma,arial,helvetica,sans-serif;" +
    "Terminal=terminal,monaco;" +
    "Times New Roman=times new roman,times;" +
    "Trebuchet MS=trebuchet ms,geneva;" +
    "Verdana=verdana,geneva;" +
    "Webdings=webdings;" +
    "Wingdings=wingdings,zapf dingbats",}
TINYMCE_SPELLCHECKER = True
TINYMCE_COMPRESSOR = True
</code>```

Here is a screenshot:

Body:
I have this script in my base file...

In my tinymce text editor I see font of size I guess 10 px but I want to change it to 16 px and also want to change the font family..

Any help ??

Body:
Please see the settings.py config that worked for me:

TINYMCE_DEFAULT_CONFIG = {
'theme': "advanced", # default value
'relative_urls': False, # default value
'plugins': 'table,spellchecker,paste,searchreplace',
'theme_advanced_buttons1': 'bold,italic,underline,bullist,numlist,link,unlink,styleselect,fontselect,fontsizeselect',
'width': '100%',
'height': 300,
'paste_text_sticky': True,
'paste_text_sticky_default': True,
'valid_styles': 'font-weight,font-style,text-decoration',
'fontsize_formats': "8pt 10pt 11pt 12pt 13pt 14pt 16pt 18pt 20pt 24pt 36pt",
'font_formats': "Andale Mono=andale mono,times;" +
    "Arial=arial,helvetica,sans-serif;" +
    "Arial Black=arial black,avant garde;" +
    "Book Antiqua=book antiqua,palatino;" +
    "Comic Sans MS=comic sans ms,sans-serif;" +
    "Courier New=courier new,courier;" +
    "Georgia=georgia,palatino;" +
    "Helvetica=helvetica;" +
    "Impact=impact,chicago;" +
    "Symbol=symbol;" +
    "Tahoma=tahoma,arial,helvetica,sans-serif;" +
    "Terminal=terminal,monaco;" +
    "Times New Roman=times new roman,times;" +
    "Trebuchet MS=trebuchet ms,geneva;" +
    "Verdana=verdana,geneva;" +
    "Webdings=webdings;" +
    "Wingdings=wingdings,zapf dingbats",}
TINYMCE_SPELLCHECKER = True
TINYMCE_COMPRESSOR = True

Here is a screenshot:


问:
Double check my IF AND OR statement
is this logical... If $dirchk1 and $dirchk2 exist or if just $dirchk1 exist continue processing. But if only $dirchk2 exist then process else statement. Thanks in advance

```<code>$dirchk1 = "/temp/files/" . $data[0] . ".doc";
$dirchk2 = "/temp/files/" . $data[1] . ".doc";
    if (is_file($dirchk1) && is_file($dirchk2)) || (is_file($dirchk1)) {
//.. do code
    } else {
    ...// only $dirchk2 exist
    }
</code>```

EDIT: sorry I failed to mention that if $dirchk1 and $dirchk2 DO NOT exist then the else statement should process.

答:
If it doesn't matter whether or not $dirchk2 exists then just pull it from the condition.

```<code>    if (is_file($dirchk1)) {
</code>```

Title: Double check my IF AND OR statement

Body:
is this logical... If $dirchk1 and $dirchk2 exist or if just $dirchk1 exist continue processing. But if only $dirchk2 exist then process else statement. Thanks in advance

$dirchk1 = "/temp/files/" . $data[0] . ".doc";
$dirchk2 = "/temp/files/" . $data[1] . ".doc";
    if (is_file($dirchk1) && is_file($dirchk2)) || (is_file($dirchk1)) {
//.. do code
    } else {
    ...// only $dirchk2 exist
    }

EDIT: sorry I failed to mention that if $dirchk1 and $dirchk2 DO NOT exist then the else statement should process.

Body:
If it doesn't matter whether or not $dirchk2 exists then just pull it from the condition.

    if (is_file($dirchk1)) {


问:
React Redux Components Communication Pattern
I am looking for a good code pattern to allow some communication between components, when using React & Redux.

Most likely this communication should be done via redux, like many articles suggest. (like this one, for example).

However, there are some situations when using the store would be a bit of a hack rather then using it for state management. These special cases are usually when you need to give a command to a component, like show or hide.

I will give an example:

Lets say that we have a <Tooltip /> component which all it does is render some help icon, that when clicked, opens a tooltip popup.
And lets say that we have more than one in a page, but we want to make sure that only one is open at a given time. So if tooltip A is open, and the user clicks on tooltip B, then B should open and A should close.

Here are some patterns that I thought might be relevant to implement this requirement:

Using Redux: We could have in the store some state for these tooltips:

```<code>{
  showTooltip: "A" // the ID of the tooltip to show
}
</code>```

This means that we have to connect the tooltips to the redux store, and check for each tooltip if it's ID is the one that should be opened, and when the user clicks on the tooltip icon, we dispatch an action to set the opened tooltip.

Using additional event mechanism: We can use an additional event mechanism to Redux, like emitter.

In this case we can fire an event whenever a tooltip is about to be opened, and all other tooltips can listen and hide themselves once they get such an event.

I have to say that it seems to me that maybe having two event mechanisms in the app seems a bit redundant, but on the other hand, using redux store to communicate with components seems a bit overkill.

Would love to hear some opinions about this issue.

答:
The React and Redux world generally encourages representing your app's behavior as state.  For example, rather than an imperative $("#someModal").show() command, you might save a flag value somewhere that says {modalVisible : true}.

There's numerous examples of using state to drive modals and popups.  A typical implementation would store the values for a single modal or a list of modals in state somewhere (either in a parent component or in Redux), and then render modal components as appropriate based on those values, such as: {type : "notificationPopup", level : "warning", message : "Something happened!"}.  The basic approach works whether you're storing the data in React, Redux, MobX, or something else.

For specific examples, see Dan Abramov's answer to "How can I display a modal dialog in Redux?", Dave Ceddia's article "Modal Dialogs in React", the article "Scalable Modals with React and Redux".  I also have other articles that demonstrate modal management in the React Component Patterns#Modal Dialogs and Redux Techniques#UI and Widget Implementations sections of my React/Redux links list.

Body:
I am looking for a good code pattern to allow some communication between components, when using React & Redux.

Most likely this communication should be done via redux, like many articles suggest. (like this one, for example).

However, there are some situations when using the store would be a bit of a hack rather then using it for state management. These special cases are usually when you need to give a command to a component, like show or hide.

I will give an example:

Lets say that we have a <Tooltip /> component which all it does is render some help icon, that when clicked, opens a tooltip popup.
And lets say that we have more than one in a page, but we want to make sure that only one is open at a given time. So if tooltip A is open, and the user clicks on tooltip B, then B should open and A should close.

Here are some patterns that I thought might be relevant to implement this requirement:

Using Redux: We could have in the store some state for these tooltips:

{
  showTooltip: "A" // the ID of the tooltip to show
}

This means that we have to connect the tooltips to the redux store, and check for each tooltip if it's ID is the one that should be opened, and when the user clicks on the tooltip icon, we dispatch an action to set the opened tooltip.

Using additional event mechanism: We can use an additional event mechanism to Redux, like emitter.

In this case we can fire an event whenever a tooltip is about to be opened, and all other tooltips can listen and hide themselves once they get such an event.

I have to say that it seems to me that maybe having two event mechanisms in the app seems a bit redundant, but on the other hand, using redux store to communicate with components seems a bit overkill.

Would love to hear some opinions about this issue.


问:
Writing a list comprehension to flatten a nested list
I have a nested list mixed with list and numbers.

```<code>nested = [[1, 2, 3], [4, 5, 6], [7, 8], [9], 10, 11]
</code>```

The nested lists only contain numbers, they'll never contain more lists.

Is it possible to write a list comprehension to make new list from the 'nested' list, producing the following output?

```<code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
</code>```

This was my attempt( code is not working)

```<code>[num if isinstance(item, list) for num in item else item for item in nested]
</code>```

答:
You need to put your instance test in a loop, so you can extract the elements from a nested list:

```<code>[num for item in nested for num in (item if isinstance(item, list) else (item,))]
</code>```

Demo:

```<code>>>> nested = nested = [[1, 2, 3], [4, 5, 6], [7, 8], [9], 10, 11]
>>> [num for item in nested for num in (item if isinstance(item, list) else (item,))]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
</code>```

It helps if you first express this as a set of for loops; your attempt essentially did this:

```<code>for item in nested:
    _element = num if isinstance(item, list) for num in item else item
    result.append(_element)
</code>```

which is not really valid Python.

My list comprehension above instead does this:

```<code>for item in nested:
    _iterable = item if isinstance(item, list) else (item,)
    for num in _iterable:
        _element = num
        result.append(_element)
</code>```

Body:
I have a nested list mixed with list and numbers.

nested = [[1, 2, 3], [4, 5, 6], [7, 8], [9], 10, 11]

The nested lists only contain numbers, they'll never contain more lists.

Is it possible to write a list comprehension to make new list from the 'nested' list, producing the following output?

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

This was my attempt( code is not working)

[num if isinstance(item, list) for num in item else item for item in nested]

Body:
You need to put your instance test in a loop, so you can extract the elements from a nested list:

[num for item in nested for num in (item if isinstance(item, list) else (item,))]

Demo:

>>> nested = nested = [[1, 2, 3], [4, 5, 6], [7, 8], [9], 10, 11]
>>> [num for item in nested for num in (item if isinstance(item, list) else (item,))]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

It helps if you first express this as a set of for loops; your attempt essentially did this:

for item in nested:
    _element = num if isinstance(item, list) for num in item else item
    result.append(_element)

which is not really valid Python.

My list comprehension above instead does this:

for item in nested:
    _iterable = item if isinstance(item, list) else (item,)
    for num in _iterable:
        _element = num
        result.append(_element)


问:
InvalidCastException in constructor when passing the right parameters
So I've got this method that creates an object fom a DataRow:

```<code>public Comment CreateComment(DataRow row)
{
    if (row == null) return null;
    var id = (int) row["CommentPk"];
    var song = (int) row["SongFk"];
    var user = (int) row["AuthorFk"];
    var text = (string) row["Content"];
    var parent = (int?) row["ParentFk"];
    return new Comment(_provider, id, song, user, text, parent);
}
</code>```

And the constructor of Comment is:

```<code>public Comment(Provider provider, int id, int songid, int userid, string content, int? parentId)
</code>```

It does crash on the constructor line. I can step (F11) to it:

答:
I handle this situation by using an extension method to check for null/DBNull</p>

```<code>int? i = row["CommentPk"].ToNullableInt();

public static int? ToNullableInt(this object value)
{
    if (value == null || value == DBNull.Value)
        return null;

    return Convert.ToInt32(value);
}
</code>```

Body:
So I've got this method that creates an object fom a DataRow:

public Comment CreateComment(DataRow row)
{
    if (row == null) return null;
    var id = (int) row["CommentPk"];
    var song = (int) row["SongFk"];
    var user = (int) row["AuthorFk"];
    var text = (string) row["Content"];
    var parent = (int?) row["ParentFk"];
    return new Comment(_provider, id, song, user, text, parent);
}

And the constructor of Comment is:

public Comment(Provider provider, int id, int songid, int userid, string content, int? parentId)

It does crash on the constructor line. I can step (F11) to it:

Body:
I handle this situation by using an extension method to check for null/DBNull

int? i = row["CommentPk"].ToNullableInt();

public static int? ToNullableInt(this object value)
{
    if (value == null || value == DBNull.Value)
        return null;

    return Convert.ToInt32(value);
}


问:
MS-SQL 2000: Turn off logging during stored procedure
Here's my scenario:

I have a simple stored procedure that removes a specific set of rows from a table (we'll say about 30k rows), and then inserts about the same amount of rows.  This generally should only take a few seconds; however, the table has a trigger on it that watches for inserts/deletes, and tries to mimic what happened to a linked table on another server.

This process in turn is unbareably slow due to the trigger, and the table is also locked during this process.  So here are my two questions:

I'm guessing a decent part of the slowdown is due to the transaction log.  Is there a way for me to specify in my stored procedure that I do not want what's in the procedure to be logged?

Is there a way for me to do my 'DELETE FROM' and 'INSERT INTO' commands without me locking the table during the entire process?

Thanks!

edit - Thanks for the answers; I figured it was the case (not being able to do either of the above), but wanted to make sure.  The trigger was created a long time ago, and doesn't look very effecient, so it looks like my next step will be to go in to that and find out what's needed and how it can be improved.  Thanks!

答:
You can temporarily disable the trigger, run your proc, then do whatever the trigger was doing in a more efficient manner.</p>

```<code>-- disable trigger
ALTER TABLE [Table] DISABLE TRIGGER [Trigger]
GO

-- execute your proc
EXEC spProc
GO

-- do more stuff to clean up / sync with other server
GO

-- enable trigger
ALTER TABLE [Table] ENABLE TRIGGER [Trigger]
GO
</code>```

OwnerDisplayName: John

LastEditorDisplayName: CodeSlave

Body:
You can temporarily disable the trigger, run your proc, then do whatever the trigger was doing in a more efficient manner.

-- disable trigger
ALTER TABLE [Table] DISABLE TRIGGER [Trigger]
GO

-- execute your proc
EXEC spProc
GO

-- do more stuff to clean up / sync with other server
GO

-- enable trigger
ALTER TABLE [Table] ENABLE TRIGGER [Trigger]
GO

OwnerDisplayName: DJ