问:
CSS displaying one box incorrectly
We have a client whose website which has been working for a few years with no problem. Suddenly we have one block that is not displaying correctly, but only seems to affect Google Chrome: </p>

<p>I guess this is a CSS issue, but we can't figure our what the problem is. Any help would be much appreciated. </p>

答:
Try this,

```<code>.carContainer .mix {
    text-align: left;
    display: none;
    min-height: 350px;
}
</code>```

Some boxes are more than 262px height

Title: CSS displaying one box incorrectly

Body:
We have a client whose website which has been working for a few years with no problem. Suddenly we have one block that is not displaying correctly, but only seems to affect Google Chrome:

I guess this is a CSS issue, but we can't figure our what the problem is. Any help would be much appreciated.

Body:
Try this,

.carContainer .mix {
    text-align: left;
    display: none;
    min-height: 350px;
}

Some boxes are more than 262px height


来源: stackexchange

问:
Converting binary lists to values required for combinations based on index of list
I generated a list of binary numbers in python with itertools, of which I want to convert all the 1 to 'ALL' and all the 0 to correspond to the index of the attribs list, where the attribs list is [1, 2], with the measure value 10 appended at the end of each list.

In essence, the list of binary numbers is

```<code>[(0, 0), (0, 1), (1, 0), (1, 1)]
</code>```

I want to convert them to

```<code>[(1, 2), (1, 'ALL'), ('ALL', 2), ('ALL', 'ALL')]
</code>```

So that these will be a form of combinations for the list [1,2].

The final lists when printed should look like these:

```<code>[1, 2, 10]
[1, 'ALL', 10]
['ALL', 2, 10]
['ALL', 'ALL', 10]
</code>```

However, I'm currently getting the following:

```<code>[2, 2, 10]
[2, 'ALL', 10]
['ALL', 2, 10]
['ALL', 'ALL', 10]
</code>```

What am I doing wrong?

```<code>import itertools as it

measure = 10
attribs = [1, 2]

# generate binary table based on number of columns
outs = [i for i in it.product(range(2), repeat=(len(attribs)))]
print(outs)

for line in outs:
    line = list(line)

    # replace binary of 1 or 0 with 'ALL' or value from input
    for index, item in enumerate(line):
        print("index of line: " + str(index) + " with value: " + str(item))

        if (item == 1):
            line[index] = 'ALL'
        elif (item == 0):
            for i in range(len(attribs)):
                print("assigning element at line index " + str(index) + " to index of attribs: " + str(i) + " with value: " + str(attribs[i]))
                line[index] = attribs[i]

    line.append(measure)
    print(line)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I generated a list of binary numbers in python with itertools, of which I want to convert all the 1 to 'ALL' and all the 0 to correspond to the index of the attribs list, where the attribs list is [1, 2], with the measure value 10 appended at the end of each list.

In essence, the list of binary numbers is

[(0, 0), (0, 1), (1, 0), (1, 1)]

I want to convert them to

[(1, 2), (1, 'ALL'), ('ALL', 2), ('ALL', 'ALL')]

So that these will be a form of combinations for the list [1,2].

The final lists when printed should look like these:

[1, 2, 10]
[1, 'ALL', 10]
['ALL', 2, 10]
['ALL', 'ALL', 10]

However, I'm currently getting the following:

[2, 2, 10]
[2, 'ALL', 10]
['ALL', 2, 10]
['ALL', 'ALL', 10]

What am I doing wrong?

import itertools as it

measure = 10
attribs = [1, 2]

# generate binary table based on number of columns
outs = [i for i in it.product(range(2), repeat=(len(attribs)))]
print(outs)

for line in outs:
    line = list(line)

    # replace binary of 1 or 0 with 'ALL' or value from input
    for index, item in enumerate(line):
        print("index of line: " + str(index) + " with value: " + str(item))

        if (item == 1):
            line[index] = 'ALL'
        elif (item == 0):
            for i in range(len(attribs)):
                print("assigning element at line index " + str(index) + " to index of attribs: " + str(i) + " with value: " + str(attribs[i]))
                line[index] = attribs[i]

    line.append(measure)
    print(line)

Body:
Do it with list comprehension

data = [(0, 0), (0, 1), (1, 0), (1, 1)]
[(a==0 and 1 or 'ALL', b==0 and 2 or 'ALL') for (a, b) in data]

outputs:[(1, 2), (1, 'ALL'), ('ALL', 2), ('ALL', 'ALL')]


问:
Retrieve Urls from SQL Database and display the images in a repeater in ASP.NET
So basically Its a image uploader and Image viewer project.

I am able to upload the image to a local folder and just save the image url in database which looks like

Now next the user should be able to view the images based on the palbum and pcat selected. palbum = album names. pcat = Public,Private etc(ignore the first pcat being animal).

Now on Page 1 my code will be:

```<code>protected void btn_view_Click(object sender, EventArgs e)
    {

        Response.Redirect("viewimage.aspx?album='"+DropDownList_album.SelectedValue+"'&cat='"+DropDownList_category.SelectedValue+"'");
    }
</code>```

On Page 2 I have applied a repeater and want to display only those pictures based on the queries only.

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        string album = Request.QueryString["album"];
        string cat = Request.QueryString["cat"];

        SqlConnection con = new SqlConnection(" *hiding this* ");
        con.Open();

        string cmd = "select * from Pics where palbum='" + Request.QueryString["album"].ToString() + "' and pcat='" + Request.QueryString["cat"].ToString() +"'";     // have tried replacing select purl with select * but same problem.

        SqlDataAdapter adp = new SqlDataAdapter(cmd, con);

        DataTable dt = new DataTable();

        adp.Fill(dt);

        Repeater1.DataSource = dt;
        Repeater1.DataBind();
    }
</code>```

But everytime i try this with different syntax and what not I either get a blank screen with no images in the repeater or this error:

答: actually i forgot to put ItemTemplate tag inside the Repeater therefore i wasn't getting the output. sorry guys</p>

Body:
So basically Its a image uploader and Image viewer project.

I am able to upload the image to a local folder and just save the image url in database which looks like

Now next the user should be able to view the images based on the palbum and pcat selected. palbum = album names. pcat = Public,Private etc(ignore the first pcat being animal).

Now on Page 1 my code will be:

protected void btn_view_Click(object sender, EventArgs e)
    {

        Response.Redirect("viewimage.aspx?album='"+DropDownList_album.SelectedValue+"'&cat='"+DropDownList_category.SelectedValue+"'");
    }

On Page 2 I have applied a repeater and want to display only those pictures based on the queries only.

protected void Page_Load(object sender, EventArgs e)
    {
        string album = Request.QueryString["album"];
        string cat = Request.QueryString["cat"];

        SqlConnection con = new SqlConnection(" *hiding this* ");
        con.Open();

        string cmd = "select * from Pics where palbum='" + Request.QueryString["album"].ToString() + "' and pcat='" + Request.QueryString["cat"].ToString() +"'";     // have tried replacing select purl with select * but same problem.

        SqlDataAdapter adp = new SqlDataAdapter(cmd, con);

        DataTable dt = new DataTable();

        adp.Fill(dt);

        Repeater1.DataSource = dt;
        Repeater1.DataBind();
    }

But everytime i try this with different syntax and what not I either get a blank screen with no images in the repeater or this error:


问:
Underscore.js - Looping through Object Array
I have the following object array:

```<code>var products = [
    {
        id: 1,
        name: "Product 1",
        subTypes: [
            {
                id: 1,
                name: "Product 1 - Sub Type 1"
            },
            {
                id: 2,
                name: "Product 1 - Sub Type 2"
            }
        ]
    },
    {
        id: 2,
        name: "Product 2",
        subTypes: [
            {
                id: 1,
                name: "Product 2 - Sub Type 1"
            },
            {
                id: 2,
                name: "Product 2 - Sub Type 2"
            }
        ]
    }
];
</code>```

Using underscore.js why does the following dot notation not log anything to console:

```<code>_.each(products.subTypes, function(subType) {
       console.log(subType.name);
 });
</code>```

I can only get it to work by doing nesting the foreach loops as follows?

```<code>_.each(products, function (product) {
    _.each(product.subTypes, function (subType) {
        console.log(subType.name);
    });
});
</code>```

答:
If you would like to access product.subTypes you have to extract them from your objects first.

Here is how you do it. 3 example functions: pure javascript, ES6, underscoreJS.

// pure JS
function pureJsloop(data) {
  var result = [];

  for (i = 0; i < data.length; i++) {
    var product = data[i];

    result.push(product.subTypes);

  }

  return result[0];
}

// ES6
function ES6loop(data) {
  // We are returning reduced array
  return data.reduce((previous, product) => {
    return previous = [ ...previous, product.subTypes ];
  }, [])[0];
}

// Underscore
function underscoreLoop(data) {

  return _.reduce(data, function(previous, product){
    return previous = [ ...previous, product.subTypes ];
  }, [])[0];

}

var products = [
              {
                id: 1,
                name: "Product 1",
                subTypes: [
                  {
                    id: 1,
                    name: "Product 1 - Sub Type 1"
                  },
                  {
                    id: 2,
                    name: "Product 1 - Sub Type 2"
                  }
                ]
              },
              {
                id: 2,
                name: "Product 2",
                subTypes: [
                  {
                    id: 1,
                    name: "Product 2 - Sub Type 1"
                  },
                  {
                    id: 2,
                    name: "Product 2 - Sub Type 2"
                  }
                ]
              }];

//console.log(pureJsloop(products));
//console.log(ES6loop(products));
console.log(underscoreLoop(products));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script></code>```

Body:
I have the following object array:

var products = [
    {
        id: 1,
        name: "Product 1",
        subTypes: [
            {
                id: 1,
                name: "Product 1 - Sub Type 1"
            },
            {
                id: 2,
                name: "Product 1 - Sub Type 2"
            }
        ]
    },
    {
        id: 2,
        name: "Product 2",
        subTypes: [
            {
                id: 1,
                name: "Product 2 - Sub Type 1"
            },
            {
                id: 2,
                name: "Product 2 - Sub Type 2"
            }
        ]
    }
];

Using underscore.js why does the following dot notation not log anything to console:

_.each(products.subTypes, function(subType) {
       console.log(subType.name);
 });

I can only get it to work by doing nesting the foreach loops as follows?

_.each(products, function (product) {
    _.each(product.subTypes, function (subType) {
        console.log(subType.name);
    });
});

Body:
If you would like to access product.subTypes you have to extract them from your objects first.

Here is how you do it. 3 example functions: pure javascript, ES6, underscoreJS.

// pure JS
function pureJsloop(data) {
  var result = [];

  for (i = 0; i < data.length; i++) {
    var product = data[i];

    result.push(product.subTypes);

  }

  return result[0];
}

// ES6
function ES6loop(data) {
  // We are returning reduced array
  return data.reduce((previous, product) => {
    return previous = [ ...previous, product.subTypes ];
  }, [])[0];
}

// Underscore
function underscoreLoop(data) {

  return _.reduce(data, function(previous, product){
    return previous = [ ...previous, product.subTypes ];
  }, [])[0];

}

var products = [
              {
                id: 1,
                name: "Product 1",
                subTypes: [
                  {
                    id: 1,
                    name: "Product 1 - Sub Type 1"
                  },
                  {
                    id: 2,
                    name: "Product 1 - Sub Type 2"
                  }
                ]
              },
              {
                id: 2,
                name: "Product 2",
                subTypes: [
                  {
                    id: 1,
                    name: "Product 2 - Sub Type 1"
                  },
                  {
                    id: 2,
                    name: "Product 2 - Sub Type 2"
                  }
                ]
              }];

//console.log(pureJsloop(products));
//console.log(ES6loop(products));
console.log(underscoreLoop(products));

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>


问:
Prevent tooltip in converting HTML Entities

<input ng-model="test" placeholder="pre" type="text" title="PROJECT&GT" />```

The above code for tooltip displays "PROJECT>". But what I need is to display the text as is "PROJECT&GT"

Is there a way to do this? I'm using angular.

答:
You need to use the encoded string in the title. You can use online tools such as this one to do this.

<input ng-model="test" placeholder="pre" type="text" title="PROJECT&GT" />```

Body:
<input ng-model="test" placeholder="pre" type="text" title="PROJECT&GT" />

The above code for tooltip displays "PROJECT>". But what I need is to display the text as is "PROJECT&GT"

Is there a way to do this? I'm using angular.

Body:
You need to use the encoded string in the title. You can use online tools such as this one to do this.

<input ng-model="test" placeholder="pre" type="text" title="PROJECT&amp;GT" />


答:
.car-image-grid img {height: 215px;}

/* change min-height to height */

.carOverview {height: 95px;}

Title: CSS displaying one box incorrectly


问:
return observable to the caller function like returning promises
I am currently migrating to angular 2 from angular 1.x. The application currently follows John Papa's style guide Return a Promise from Data Calls.

activate();

function activate() {
    /**
     * Step 1
     * Ask the getAvengers function for the
     * avenger data and wait for the promise
     */
    return getAvengers().then(function() {
        /**
         * Step 4
         * Perform an action on resolve of final promise
         */
        logger.info('Activated Avengers View');
    });
}

function getAvengers() {
      /**
       * Step 2
       * Ask the data service for the data and wait
       * for the promise
       */
      return dataservice.getAvengers()
          .then(function(data) {
              /**
               * Step 3
               * set the data and resolve the promise
               */
              vm.avengers = data;
              return vm.avengers;
      });
}
```

How can I do the same thing with Observables? with promise, i can write .then() in multiple functions and return it so that the caller functions also will wait for the promise. But with observable, What is the correct thing to do?
Where exactly i should subscribe and where i should just map the values and return the observable?

答:
map should be used when you want to modify the data sent and, by doing so, create a new Observable.

Example:

getAvengers.map(avengers => avengers.forEach(a => a.kill)) will create an observable of dead avengers. Then you can subscribe on this observable to call methods with dead avengers.

subscribe is more like then since it'll simply wait for the data to call the method passed to it. But subscribe will trigger the observable, meaning that if you simply call getAvengers() (assuming that getAvengers returns an Observable) you'll get an Observable, to trigger the request you have to subscribe.

BE CAREFULL:

Calling subscribe twice will trigger the Observable twice, meaning that if you call subscribe on an Observable based on an http request, the request will be done twice.

Therefore you can hendle this using cache with observables, but the documentation will be able to guide you through this.

Body:
I am currently migrating to angular 2 from angular 1.x. The application currently follows John Papa's style guide Return a Promise from Data Calls.

activate();

function activate() {
    /**
     * Step 1
     * Ask the getAvengers function for the
     * avenger data and wait for the promise
     */
    return getAvengers().then(function() {
        /**
         * Step 4
         * Perform an action on resolve of final promise
         */
        logger.info('Activated Avengers View');
    });
}

function getAvengers() {
      /**
       * Step 2
       * Ask the data service for the data and wait
       * for the promise
       */
      return dataservice.getAvengers()
          .then(function(data) {
              /**
               * Step 3
               * set the data and resolve the promise
               */
              vm.avengers = data;
              return vm.avengers;
      });
}

How can I do the same thing with Observables? with promise, i can write .then() in multiple functions and return it so that the caller functions also will wait for the promise. But with observable, What is the correct thing to do?
Where exactly i should subscribe and where i should just map the values and return the observable?


问:
Object from NSUserDefaults releasing?
So I have a username saved in the UserDefaults.  For some reason, I am experiencing some strange behavior.

I have a data controller that goes and fetches some data from the server based on the user name.

```<code>NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSLog(@"NSUserDefaults dump: %@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);

userID = [prefs stringForKey:@"username"];
</code>```

This works fine for the first few times, but after I do some random stuff and go back to try and reload the views, it crashes.  It says:

```<code>-[CFString retain]: message sent to deallocated instance 0x4b18ff0
</code>```

This is strange because it is stopping on the NSLog line.  Has anyone seen this before or know why it may be happening??

答:
How you defined your userID? If it's a property with a retain attribute you should call

self.userID = [prefs stringForKey:@"username"];

this way your string will be retained automatically. The string that is returned from stringForKey is autoreleased.

ContentLicense: CC BY-SA 2.5

Title: Object from NSUserDefaults releasing?

Body:
So I have a username saved in the UserDefaults.  For some reason, I am experiencing some strange behavior.

I have a data controller that goes and fetches some data from the server based on the user name.

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSLog(@"NSUserDefaults dump: %@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);

userID = [prefs stringForKey:@"username"];

This works fine for the first few times, but after I do some random stuff and go back to try and reload the views, it crashes.  It says:

-[CFString retain]: message sent to deallocated instance 0x4b18ff0

This is strange because it is stopping on the NSLog line.  Has anyone seen this before or know why it may be happening??


问:
Merge multiple group ids to form a single consolidated group id?
I have following dataset in pandas Dataframe.

```
group_id sub_group_id
0           0
0           1
1           0
2           0
2           1
2           2
3           0
3           0
```

But the I want to those group ids and form a consolidated group id

```
group_id sub_group_id consolidated_group_id
0            0                    0
0            1                    1
1            0                    2
2            0                    3
2            1                    4
2            2                    5
2            2                    5
3            0                    6
3            0                    6
```

Is there any generic or mathematical way to do it?

答:
```<code>cols = ['group_id', 'sub_group_id']
df.assign(
    consolidated_group_id=pd.factorize(
        pd.Series(list(zip(*df[cols].values.T.tolist())))
    )[0]
)

   group_id  sub_group_id  consolidated_group_id
0         0             0                      0
1         0             1                      1
2         1             0                      2
3         2             0                      3
4         2             1                      4
5         2             2                      5
6         3             0                      6
7         3             0                      6
</code>```

Body:
I have following dataset in pandas Dataframe.

group_id sub_group_id
0           0
0           1
1           0
2           0
2           1
2           2
3           0
3           0

But the I want to those group ids and form a consolidated group id

group_id sub_group_id consolidated_group_id
0            0                    0
0            1                    1
1            0                    2
2            0                    3
2            1                    4
2            2                    5
2            2                    5
3            0                    6
3            0                    6

Is there any generic or mathematical way to do it?


问:
Row based Access control for Laravel Results
I'd like to setup a row based access control on my laravel application (currently 5.2, waiting for 5.5 lts). This could be done in the controller, but I was wondering if there is a way to do it a bit deeper in the framework.

Let's say there are these models:

```<code>P - project
U - user (assigned to many projects)
D - Device (assigned to one project)
F - FAQ document (assigned to one project)
</code>```

The currently logged in user should only see those devices and faq documents that belong to their projects.

My current attempt is to do this in the controller. Get the current user, check for a generic "access all project" permission and - if not present - join the project for the asked model to limit the result. This has to be replicated on all queries that are running for this model and I am feeling that this kind of redundancy is not perfect.

Is there a way to create something like a interface trait with a method withAccess() that forces those models (Device and FAQ Document in my example) to implement this method and do the query once on the model definition?

答:
One thing I can think off is to use a reusable scope for each model.

e.g.

In your controller:

```<code>$devices = Device::ViewableDevices()->get();
</code>```

and in your Device model:

```<code>public function scopeViewableDevices($query)
{

    return $query->whereHas('project', function($query) {
        $query->whereHas('user', function($query) {
            $query->where('user_id', Auth::user()->id);
        }
    });

}
</code>```

The query might be wrong compared to how your data is stored and the logic you are trying to achieve but what I am meaning in the scope is to find the project for the device, then find the user for the project and see if it belongs to the logged in user.

For this to work you'd need to setup a project relationship in the Device model and a user relationship in the Project model.

e.g.

```<code>// Device.php
public function project() {
    return $this->hasOne('App\Project', 'id', 'project_id');
}

// Project.php
public function user() {
    return $this->belongsTo('App\User', 'id', 'user_id');
}
</code>```

The relationships might be off, I always get the order mixed up but I generally use php artisan tinker to make sure that they work.

Scopes Docs

Relationship Docs

The only other thing I'd suggest is to make sure you have indexes (indices?) on your foreign key columns, e.g. project_id, user_id and any others, they will help to speed up your queries, especially if your tables are quite large.

Body:
I'd like to setup a row based access control on my laravel application (currently 5.2, waiting for 5.5 lts). This could be done in the controller, but I was wondering if there is a way to do it a bit deeper in the framework.

Let's say there are these models:

P - project
U - user (assigned to many projects)
D - Device (assigned to one project)
F - FAQ document (assigned to one project)

The currently logged in user should only see those devices and faq documents that belong to their projects.

My current attempt is to do this in the controller. Get the current user, check for a generic "access all project" permission and - if not present - join the project for the asked model to limit the result. This has to be replicated on all queries that are running for this model and I am feeling that this kind of redundancy is not perfect.

Is there a way to create something like a interface trait with a method withAccess() that forces those models (Device and FAQ Document in my example) to implement this method and do the query once on the model definition?

Body:
One thing I can think off is to use a reusable scope for each model.

e.g.

In your controller:

$devices = Device::ViewableDevices()->get();

and in your Device model:

public function scopeViewableDevices($query)
{

    return $query->whereHas('project', function($query) {
        $query->whereHas('user', function($query) {
            $query->where('user_id', Auth::user()->id);
        }
    });

}

The query might be wrong compared to how your data is stored and the logic you are trying to achieve but what I am meaning in the scope is to find the project for the device, then find the user for the project and see if it belongs to the logged in user.

For this to work you'd need to setup a project relationship in the Device model and a user relationship in the Project model.

e.g.

// Device.php
public function project() {
    return $this->hasOne('App\Project', 'id', 'project_id');
}

// Project.php
public function user() {
    return $this->belongsTo('App\User', 'id', 'user_id');
}

The relationships might be off, I always get the order mixed up but I generally use php artisan tinker to make sure that they work.

Scopes Docs

Relationship Docs

The only other thing I'd suggest is to make sure you have indexes (indices?) on your foreign key columns, e.g. project_id, user_id and any others, they will help to speed up your queries, especially if your tables are quite large.


问:
Mysql match against not working as expected
I want sort the mysql result with relevance.

The workflow is as follows:

I search resume with keywords Java, Php

And write query to calculate relevance.

```<code>$keyStr="Java PHP";
</code>```

res_id and res_keyskills in Resumes table loook like

```<code>1   Java,PHP
2   PHP,Java
3   Javascript, Java
4   Java
5   PHP
6   Python
7   PHP, C
</code>```

etc

```<code>SELECT *, match(res_keyskills) against ('".$keyStr."') AS relevance FROM Resumes
</code>```

Currently I am getting relevance greater than 0 for res_id  1, 3, 4

But the expected result is relevance greater than 0 for res_id 1,2 3, 4,5,7

Since the $keyStr is starts with Java, the relevance is set to the res_keyskills which are starts with Java.

But I need to set the relevance for res_keyskills  having Java or Php.

For this what change should I do in my query or should I change the input string format(currently seperated by space)

答:
You're specifying no operator in your query. When you do that you're saying:

Find rows that contain at least one of the two words.

Instead try to specify + operator and try. Which means:

Find rows that contain the first word, but rank rows higher if they also contain second word.

Something like:

```<code>SELECT *, match(res_keyskills) against ('+".$keyStr."') AS relevance FROM Resumes
</code>```

Reference

Body:
I want sort the mysql result with relevance.

The workflow is as follows:

I search resume with keywords Java, Php

And write query to calculate relevance.

$keyStr="Java PHP";

res_id and res_keyskills in Resumes table loook like

1   Java,PHP
2   PHP,Java
3   Javascript, Java
4   Java
5   PHP
6   Python
7   PHP, C

etc

SELECT *, match(res_keyskills) against ('".$keyStr."') AS relevance FROM Resumes

Currently I am getting relevance greater than 0 for res_id  1, 3, 4

But the expected result is relevance greater than 0 for res_id 1,2 3, 4,5,7

Since the $keyStr is starts with Java, the relevance is set to the res_keyskills which are starts with Java.

But I need to set the relevance for res_keyskills  having Java or Php.

For this what change should I do in my query or should I change the input string format(currently seperated by space)

Body:
You're specifying no operator in your query. When you do that you're saying:

Find rows that contain at least one of the two words.

Instead try to specify + operator and try. Which means:

Find rows that contain the first word, but rank rows higher if they also contain second word.

Something like:

SELECT *, match(res_keyskills) against ('+".$keyStr."') AS relevance FROM Resumes

Reference


问:
Can't remove the sidebar in SB Admin Bootstrap Template
I want to remove the sidebar, I tried deleting the nav content but still the sidebar is still there. The sidebar is under wrapper class and there is not separate class for sidebar.</p>

答:
Remove all sidebar components and then add the following to the css media:

margin-left: 0 to #page-wrapper


问:
How to load up documentation with Sphinx on a subfolder of Debian server
I'm quite new to Sphinx side. I have read some stuff about it on Sphinx official documentation site and I have follow these steps for install and configure it on my Debian Wheezy server:

First of all I have installed the Sphinx source on http://example.com/documentation-path/.

pip install sphinx

I have executed the script sphinx-quickstart for configuring the root directory and the conf.py.

sphinx-quickstart

I have executed the make html command for building HTML files in my directory path.

make html

I have installed the Sphinx autobuild for handle every
changes/updates of my documentation, as written in a post made by     @toast38coza.

pip install sphinx-autobuild

sphinx-autobuild source build/html

[What I have already fixed]

My first problem was that I couldn't get a correct view of the documentation index template since the server started watching changes on the documentation files at http://127.0.0.1:8000 (localhost at port 8000). So I get the same url path that I was expecting when I have installed it locally on my current PC. And as I said in the local version test it worked fine.

Since I was searching for something like that as URL path configuration (http://example.com), I decided to add arguments as -host and -port for let it works fine on Debian:

-p/--port option to specify the port on which the documentation shall be served (default 8000)
-H/--host option to specify the host on which the documentation shall be served (default 127.0.0.1)

Then I have configured it, launched it and it worked fine:

```<code>>> sphinx-autobuild source build/html --host http://example.com --port8000
</code>```

So now if I surf http://example.com:8000
I get the correct view of the documentation index template.

[My main question]

How can I launch this view on a different URL path, for example a subfolder like http://example.com/documentation-path/, even considering that the root path of the Sphinx installation was /documentation-path/?

[My secondary question]

How can I automate the process of visualizing the template view without writing every times the instruction sphinx-autobuild with --port and --host on Debian console?

[Important Notice]

The Debian server is configured at this moment with NGINX which is completely new for me.

答:
Finally I have solved the subfolder path problem by myself with the help of NGINX documentation.

```<code>location /documentation {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://localhost:8000;
    index index.php index.html index.htm;
}
</code>```

Regarding the autoload problem I have just switched from Sphinx to Markdown and after that I have used couscousPHP for generate a GitHub pages website from the markdown documentation.

This was for me the smarter way for provide static html files without autoload every time a source from the ssh console. In fact I can easily generate my conversion html file from .md file typing the command couscous generate.

ContentLicense: CC BY-SA 4.0

Body:
I'm quite new to Sphinx side. I have read some stuff about it on Sphinx official documentation site and I have follow these steps for install and configure it on my Debian Wheezy server:

First of all I have installed the Sphinx source on http://example.com/documentation-path/.

pip install sphinx

I have executed the script sphinx-quickstart for configuring the root directory and the conf.py.

sphinx-quickstart

I have executed the make html command for building HTML files in my directory path.

make html

I have installed the Sphinx autobuild for handle every
changes/updates of my documentation, as written in a post made by     @toast38coza.

pip install sphinx-autobuild

sphinx-autobuild source build/html

[What I have already fixed]

My first problem was that I couldn't get a correct view of the documentation index template since the server started watching changes on the documentation files at http://127.0.0.1:8000 (localhost at port 8000). So I get the same url path that I was expecting when I have installed it locally on my current PC. And as I said in the local version test it worked fine.

Since I was searching for something like that as URL path configuration (http://example.com), I decided to add arguments as -host and -port for let it works fine on Debian:

-p/--port option to specify the port on which the documentation shall be served (default 8000)
-H/--host option to specify the host on which the documentation shall be served (default 127.0.0.1)

Then I have configured it, launched it and it worked fine:

>> sphinx-autobuild source build/html --host http://example.com --port8000

So now if I surf http://example.com:8000
I get the correct view of the documentation index template.

[My main question]

How can I launch this view on a different URL path, for example a subfolder like http://example.com/documentation-path/, even considering that the root path of the Sphinx installation was /documentation-path/?

[My secondary question]

How can I automate the process of visualizing the template view without writing every times the instruction sphinx-autobuild with --port and --host on Debian console?

[Important Notice]

The Debian server is configured at this moment with NGINX which is completely new for me.

Body:
Finally I have solved the subfolder path problem by myself with the help of NGINX documentation.

location /documentation {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://localhost:8000;
    index index.php index.html index.htm;
}

Regarding the autoload problem I have just switched from Sphinx to Markdown and after that I have used couscousPHP for generate a GitHub pages website from the markdown documentation.

This was for me the smarter way for provide static html files without autoload every time a source from the ssh console. In fact I can easily generate my conversion html file from .md file typing the command couscous generate.


问:
How to read file from end to start (in reverse order) in TCL?
I have a very large text file from which I have to extract some data. I read the file line by line and look for keywords. As I know that the keywords I am looking for are much closer to the end of the file than to the beginning.
I tried tac keyword
set fh [open "|tac filename"]
I am getting error as : couldn't execute "tac": no such file or directory

My file size is big so i am not able to store the line in a loop and reverse it again. Please suggest some solution

答:
The cost of reversing a file is actually fairly high. The best option I can think of is to construct a list of file offsets of the starts of lines, and then to use a seek;gets pattern to go over that list.

```<code>set f [open $filename]

# Construct the list of indices
set indices {}
while {![eof $f]} {
    lappend indices [tell $f]
    gets $f
}

# Iterate backwards
foreach idx [lreverse $indices] {
    seek $f $idx
    set line [gets $f]

    DoStuffWithALine $line
}

close $f
</code>```

The cost of this approach is non-trivial (even if you happened to have a cache of the indices, you'd still have issues with it) as it doesn't work well with how the OS pre-fetches disk data.

Body:
The cost of reversing a file is actually fairly high. The best option I can think of is to construct a list of file offsets of the starts of lines, and then to use a seek;gets pattern to go over that list.

set f [open $filename]

# Construct the list of indices
set indices {}
while {![eof $f]} {
    lappend indices [tell $f]
    gets $f
}

# Iterate backwards
foreach idx [lreverse $indices] {
    seek $f $idx
    set line [gets $f]

    DoStuffWithALine $line
}

close $f

The cost of this approach is non-trivial (even if you happened to have a cache of the indices, you'd still have issues with it) as it doesn't work well with how the OS pre-fetches disk data.


问:
Passing cookies in NodeJs http request
I'm kind of a newbie in NodeJs. I'm trying to make an http request and pass a cookie. I've read all the threads on stackoverflow about it and made up a piece of code that should theoretically work. But, it doesn't.

What I'm trying to do is to send a cookie with the store code to one online-shop which will show me the information about this very shop. If there is no cookie it shows the default div asking to choose a shop.

Here is my code:

```<code>var request = require('request'),
    http = require('follow-redirects').http,
    request = request.defaults({
        jar: true
    });

var cookieString = 'MC_STORE_ID=66860; expires=' + new Date(new Date().getTime() + 86409000);
var str = '';
//var uri = 'example.de';

//var j = request.jar();
var cookie = request.cookie(cookieString);
j.setCookie(cookie, uri);

var options = {
    hostname: 'example.de',
    path: '/pathexample',
    method: 'GET',
    headers: {
        'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
            'Cookie': cookie,
            'Accept': '/',
            'Connection': 'keep-alive'
    }
    //,jar: j
};

http.request(options, function (resp) {
    resp.setEncoding('utf8');
    console.log(resp.headers);
    if (resp.statusCode) {
        resp.on('data', function (part) {
            str += part;
        });
        resp.on('end', function (part) {
            console.log(str);
        });

        resp.on('error', function (e) {
            console.log('Problem with request: ' + e.message);
        });
    }
}).end(str);
</code>```

I assume that the cookie will be sent and accepted with my request, but it isn't. I've also tried jar. I commented it out in the code. But, it seems not to work for me either. When I do console.log(resp.headers) I see the original cookies, but not mine. Can someone give me a hint?

The cookie structure is correct. When I run document.cookie=cookie; in google chrome console it is succsessfuly replaced.

答:
I had the same issue, @Ricardo helped me to figure out.
I have removed the jar key from header

```<code>//Set the cookie instead of setting into header
var cookie = request.cookie('MC_STORE_ID=66860');

// Set the headers for the request
var headers = {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(post_data),
    'Cookie': cookie
};
// Configure the request
var options = {
    url: requestObj["URL"],
    method: 'POST',
    headers: headers
};

// Start the request
request(options, function (error, response, body) {
    if (!error && response.statusCode === 200) {
        // Print out the response body
        cb(null, {status: 0, statusDsc: "success", data: body});
    } else {
        cb(error, {status: 2, statusDsc: JSON.stringify(error)});
    }
});
</code>```

This is kind of mix between your cookie data and my request function.

Title: Passing cookies in NodeJs http request

Body:
I'm kind of a newbie in NodeJs. I'm trying to make an http request and pass a cookie. I've read all the threads on stackoverflow about it and made up a piece of code that should theoretically work. But, it doesn't.

What I'm trying to do is to send a cookie with the store code to one online-shop which will show me the information about this very shop. If there is no cookie it shows the default div asking to choose a shop.

Here is my code:

var request = require('request'),
    http = require('follow-redirects').http,
    request = request.defaults({
        jar: true
    });

var cookieString = 'MC_STORE_ID=66860; expires=' + new Date(new Date().getTime() + 86409000);
var str = '';
//var uri = 'example.de';

//var j = request.jar();
var cookie = request.cookie(cookieString);
j.setCookie(cookie, uri);

var options = {
    hostname: 'example.de',
    path: '/pathexample',
    method: 'GET',
    headers: {
        'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
            'Cookie': cookie,
            'Accept': '/',
            'Connection': 'keep-alive'
    }
    //,jar: j
};

http.request(options, function (resp) {
    resp.setEncoding('utf8');
    console.log(resp.headers);
    if (resp.statusCode) {
        resp.on('data', function (part) {
            str += part;
        });
        resp.on('end', function (part) {
            console.log(str);
        });

        resp.on('error', function (e) {
            console.log('Problem with request: ' + e.message);
        });
    }
}).end(str);

I assume that the cookie will be sent and accepted with my request, but it isn't. I've also tried jar. I commented it out in the code. But, it seems not to work for me either. When I do console.log(resp.headers) I see the original cookies, but not mine. Can someone give me a hint?

The cookie structure is correct. When I run document.cookie=cookie; in google chrome console it is succsessfuly replaced.

Body:
I had the same issue, @Ricardo helped me to figure out.
I have removed the jar key from header

//Set the cookie instead of setting into header
var cookie = request.cookie('MC_STORE_ID=66860');

// Set the headers for the request
var headers = {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(post_data),
    'Cookie': cookie
};
// Configure the request
var options = {
    url: requestObj["URL"],
    method: 'POST',
    headers: headers
};

// Start the request
request(options, function (error, response, body) {
    if (!error && response.statusCode === 200) {
        // Print out the response body
        cb(null, {status: 0, statusDsc: "success", data: body});
    } else {
        cb(error, {status: 2, statusDsc: JSON.stringify(error)});
    }
});

This is kind of mix between your cookie data and my request function.


问:
Mass export all images as individual JPEGs in InDesign?
I am new to Indesign. I have a file that contains images with Photoshop clipping paths. I want to export all the clipped images in a folder. I have tried doing the "Copy Links To" and it successfully exported the original images. However, I do not want the original images but the clipped images instead. Is there a way for me to export all the clipped images as JPEG and not the original linked image? In short, I want to export the images without their background. I hope I'm making sense. I have about 800-1000 images so a batch processing method would be highly appreciated.

I found this script from one of the posts here and modified it a bit to suit my needs. It appears to work in most of my INDD documents, but it fails in others. I wonder why. I sometimes get the error message that
    Error string: null is not an object
    Source: fileName = File ( rect.graphics[0].itemLink.filePath ).name;

I also noticed that it skips some objects and won't download all of the images. I guess it skips those that are not in rectangles.

```<code>test();
function test()
{
var myDoc = app.activeDocument,
apis = myDoc.allPageItems, rect, fileName;

while ( rect = apis.pop() )
{
if ( !(rect instanceof Rectangle) || !rect.graphics[0].isValid ){ continue;}

fileName = File ( rect.graphics[0].itemLink.filePath ).name;
fileName = fileName.replace( /\.[a-z]{2,4}$/i, '.jpg' );

app.jpegExportPreferences.exportResolution = 2400;
app.jpegExportPreferences.jpegQuality = JPEGOptionsQuality.MAXIMUM;

//give it a unique name
var myFile = new File ("C:/Users/RANFacistol-Mata/Desktop/Image Trial/"+ fileName);

rect.exportFile(ExportFormat.JPG, myFile);
}
}
</code>```

Is there a way for me to modify this script such that instead of iterating through all the rectangles, I would iterate through all of the objects instead, much like clicking this next button

And then check if that object contains an image (jpg, tiff, psd, ai, eps). If it does, then I will export it as scripted above.

Thank you for your help!

答:
You can traverse the links present inside the document with the following snippet, this will take less time as taken by the snippet above...
You can also get the type of link ('eps' or ' pdf' etc) with linkType attribute and filePath with 'filePath' attribute of each link object..</p>

```<code>var theDoc = app.documents.item(0);
var theLinkLen = theDoc.links.length;
for(var i = 0; i < theLinkLen; ++i)
{
  var link = theDoc.links.item(i);
  alert("link name \"" + link.name + "\"" + " has type \"" + link.linkType  + "\""+ " with filePath \"" + link.filePath + "\"");
}
</code>```

Body:
I am new to Indesign. I have a file that contains images with Photoshop clipping paths. I want to export all the clipped images in a folder. I have tried doing the "Copy Links To" and it successfully exported the original images. However, I do not want the original images but the clipped images instead. Is there a way for me to export all the clipped images as JPEG and not the original linked image? In short, I want to export the images without their background. I hope I'm making sense. I have about 800-1000 images so a batch processing method would be highly appreciated.

I found this script from one of the posts here and modified it a bit to suit my needs. It appears to work in most of my INDD documents, but it fails in others. I wonder why. I sometimes get the error message that
    Error string: null is not an object
    Source: fileName = File ( rect.graphics[0].itemLink.filePath ).name;

I also noticed that it skips some objects and won't download all of the images. I guess it skips those that are not in rectangles.

test();
function test()
{
var myDoc = app.activeDocument,
apis = myDoc.allPageItems, rect, fileName;

while ( rect = apis.pop() )
{
if ( !(rect instanceof Rectangle) || !rect.graphics[0].isValid ){ continue;}

fileName = File ( rect.graphics[0].itemLink.filePath ).name;
fileName = fileName.replace( /\.[a-z]{2,4}$/i, '.jpg' );

app.jpegExportPreferences.exportResolution = 2400;
app.jpegExportPreferences.jpegQuality = JPEGOptionsQuality.MAXIMUM;

//give it a unique name
var myFile = new File ("C:/Users/RANFacistol-Mata/Desktop/Image Trial/"+ fileName);

rect.exportFile(ExportFormat.JPG, myFile);
}
}

Is there a way for me to modify this script such that instead of iterating through all the rectangles, I would iterate through all of the objects instead, much like clicking this next button

And then check if that object contains an image (jpg, tiff, psd, ai, eps). If it does, then I will export it as scripted above.

Thank you for your help!

Body:
You can traverse the links present inside the document with the following snippet, this will take less time as taken by the snippet above...
You can also get the type of link ('eps' or ' pdf' etc) with linkType attribute and filePath with 'filePath' attribute of each link object..

var theDoc = app.documents.item(0);
var theLinkLen = theDoc.links.length;
for(var i = 0; i < theLinkLen; ++i)
{
  var link = theDoc.links.item(i);
  alert("link name \"" + link.name + "\"" + " has type \"" + link.linkType  + "\""+ " with filePath \"" + link.filePath + "\"");
}


问:
How to install your custom flask extension
I'm trying create custom flask extension and use it within my application. I'm using below project structure.

```<code>ExapmpleProject
--> apps
--> extensions
   -->flask-customext
      -->__init__.py
      -->flask_customext.py
      -->setup.py
--> sample.py
</code>```

sample.py

```<code>from flask import Flask
from flask.ext import customext
app = Flask(__name__)

@app.route('/')
def hello_world():
    if customext.validate():
        return 'Hello World!'
    else:
        return 'not allowed!'

if __name__ == '__main__':
    app.run()
</code>```

I followed standard class based extension within flask-customext package as defined in the extention dev doc. How can I install this customext to be imported by from flask.ext import customext used in sample.py as any other flask-extensions does.

Not sure if this do the job but I tried python setup.py install. but it raised below error

```<code>error: package directory 'flask_customext' does not exist
</code>```

答:
The documentation says that

Extensions are all located in a package called flask_something

Whereas in your example the package is named flask-customext, so it should be flask_customext.

Also id the Extension Import Transition chapter it is recommended to use the new import convention:

```<code>import flask_something
</code>```

Instead of:

```<code>import flask.ext.something
</code>```

Body:
I'm trying create custom flask extension and use it within my application. I'm using below project structure.

ExapmpleProject
--> apps
--> extensions
   -->flask-customext
      -->__init__.py
      -->flask_customext.py
      -->setup.py
--> sample.py

sample.py

from flask import Flask
from flask.ext import customext
app = Flask(__name__)

@app.route('/')
def hello_world():
    if customext.validate():
        return 'Hello World!'
    else:
        return 'not allowed!'

if __name__ == '__main__':
    app.run()

I followed standard class based extension within flask-customext package as defined in the extention dev doc. How can I install this customext to be imported by from flask.ext import customext used in sample.py as any other flask-extensions does.

Not sure if this do the job but I tried python setup.py install. but it raised below error

error: package directory 'flask_customext' does not exist

Body:
The documentation says that

Extensions are all located in a package called flask_something

Whereas in your example the package is named flask-customext, so it should be flask_customext.

Also id the Extension Import Transition chapter it is recommended to use the new import convention:

import flask_something

Instead of:

import flask.ext.something


问:
Position of WHERE statement in left outer join
In the following query I am trying to first, filter all subscriptions that have a network_id = 24, and then join the column payment_plans.plan_type to subscriptions where the ids are the same.

I think there is a problem in the positioning of the WHERE statement but I am not sure where it is - the error shows that the there is a syntax error near the join statement

Any suggestions as to where the error might be?

```<code>SELECT DISTINCT subscriptions.user_id, subscriptions.payment_plan_id, payment_plans.plan_type
FROM subscriptions WHERE network_id = 24
LEFT OUTER JOIN payment_plans ON subscription.payment_plan_id = payment_plans.id

ERROR:  syntax error at or near "LEFT"
LINE 3: LEFT OUTER JOIN payment_plans ON subscription.payment_plan_i...
        ^
</code>```

答:
The SQL syntax is select ... from ... join .. on ..where.

```<code>SELECT DISTINCT subscriptions.user_id, subscriptions.payment_plan_id, payment_plans.plan_type
FROM subscriptions
LEFT OUTER JOIN payment_plans ON subscription.payment_plan_id = payment_plans.id
WHERE network_id = 24
</code>```

That is SQL standart and the same for all RDBMS.

Body:
In the following query I am trying to first, filter all subscriptions that have a network_id = 24, and then join the column payment_plans.plan_type to subscriptions where the ids are the same.

I think there is a problem in the positioning of the WHERE statement but I am not sure where it is - the error shows that the there is a syntax error near the join statement

Any suggestions as to where the error might be?

SELECT DISTINCT subscriptions.user_id, subscriptions.payment_plan_id, payment_plans.plan_type
FROM subscriptions WHERE network_id = 24
LEFT OUTER JOIN payment_plans ON subscription.payment_plan_id = payment_plans.id

ERROR:  syntax error at or near "LEFT"
LINE 3: LEFT OUTER JOIN payment_plans ON subscription.payment_plan_i...
        ^

Body:
The SQL syntax is select ... from ... join .. on ..where.

SELECT DISTINCT subscriptions.user_id, subscriptions.payment_plan_id, payment_plans.plan_type
FROM subscriptions
LEFT OUTER JOIN payment_plans ON subscription.payment_plan_id = payment_plans.id
WHERE network_id = 24

That is SQL standart and the same for all RDBMS.


问:
get data from last 7 days and get rows and data inserted count according to day
Here's my sqlite table:

```
TimeStamp | Counter
--------- | --------
(in ms)     ...
```

And I want result something like this

```
| Day | Sum(Counter) |
----------------------
|Monday|10          |
|Tuesday| 20         |
```

答:
Milliseconds is not one of SQLite's supported date formats, but it is possible to use Unix Time by multiplying/dividing by 1000 at the appropriate places.

In SQLite, a date function with these modifiers returns the start of the current day in the local time zone:

```<code>datetime('now', 'localtime', 'start of day')
</code>```

To convert this to milliseconds, use strftime instead:

```<code>SELECT ...
FROM MyTable
WHERE TimeStamp >= strftime('%s', 'now', 'localtime', 'start of day', '-7 days') * 1000
...
</code>```

To get the day of a timestamp, you have to use strftime again:

```<code>SELECT strftime('%w', TimeStamp / 1000, 'unixepoch', 'localtime') AS Day,
       sum(Counter)
FROM MyTable
WHERE TimeStamp >= strftime('%s', 'now', 'localtime', 'start of day', '-7 days') * 1000
GROUP BY 1;
</code>```

If you want to use day names instead of the day number, use a CASE expression:

```<code>SELECT CASE strftime('%w', TimeStamp / 1000, 'unixepoch', 'localtime')
         WHEN '0' THEN 'Sunday'
         WHEN '1' THEN 'Monday'
         ...
       END AS Day,
       sum(Counter)
...
</code>```

Body:
Here's my sqlite table:

TimeStamp | Counter
--------- | --------
(in ms)     ...

And I want result something like this

| Day | Sum(Counter) |
----------------------
|Monday|10          |
|Tuesday| 20         |

Body:
Milliseconds is not one of SQLite's supported date formats, but it is possible to use Unix Time by multiplying/dividing by 1000 at the appropriate places.

In SQLite, a date function with these modifiers returns the start of the current day in the local time zone:

datetime('now', 'localtime', 'start of day')

To convert this to milliseconds, use strftime instead:

SELECT ...
FROM MyTable
WHERE TimeStamp >= strftime('%s', 'now', 'localtime', 'start of day', '-7 days') * 1000
...

To get the day of a timestamp, you have to use strftime again:

SELECT strftime('%w', TimeStamp / 1000, 'unixepoch', 'localtime') AS Day,
       sum(Counter)
FROM MyTable
WHERE TimeStamp >= strftime('%s', 'now', 'localtime', 'start of day', '-7 days') * 1000
GROUP BY 1;

If you want to use day names instead of the day number, use a CASE expression:

SELECT CASE strftime('%w', TimeStamp / 1000, 'unixepoch', 'localtime')
         WHEN '0' THEN 'Sunday'
         WHEN '1' THEN 'Monday'
         ...
       END AS Day,
       sum(Counter)
...


问:
Transform palette file to html content with xslt
I want to transform an XML palette file of this type:

```<code><?xml version="1.0"?>
<?xml-stylesheet href="Palette.xsl" type="text/xsl"?>
<Palette Name="MyPalette">
  <PaletteEntry Color="#D0427B" Color2="#D0427B" />
  <PaletteEntry Color="#D55588" Color2="#D55588" />
  <PaletteEntry Color="#DA6895" Color2="#DA6895" />
</Palette>
</code>```

using this XSL transformation:

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

<xsl:template match="Palette">
<html>
    <head>
        <title>Palette {@Name}</title>
        <!--link rel="stylesheet" href="Palette.css" type="text/css"/-->
    </head>
    <body>
        <div class="palette">
            <xsl:apply-templates/>
        </div>
    </body>
</html>
</xsl:template>

<xsl:template match="PaletteEntry">
    <div class="palette-entry" style="width:40px;height:40px; margin:2px; float:left; background-color: {@Color}; border: 2px solid {@Color2};">
        <xsl:apply-templates select="@*"/>
    </div>
</xsl:template>

<xsl:template match="@Color">
    <xsl:copy-of select="."/>
</xsl:template>

<xsl:template match="@Color2">
    <xsl:copy-of select="."/>
</xsl:template>

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

The problem in the output is that the color attributes are rendered well when they are in an attribute but are not translated in content. Here is the HTML output:

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Palette {@Name}</title>

```
</div>
</div>
</p>

<p>How can I copy color values to content?</p>

<p>Expected output:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Palette "MyPalette"</title>
</head>

<body>
  <div class="palette">
    <div class="palette-entry" style="width:40px;height:40px; margin:2px; float:left; background-color: #495359; border: 2px solid #495359;">#495359<br/>#495359</div>
    <div class="palette-entry" style="width:40px;height:40px; margin:2px; float:left; background-color: #5B646A; border: 2px solid #5B646A;">#5B646A<br/>#5B646A</div>
  </div>
</body>

</html></code>```

答:
Color and Color2 are attributes in the XML, and so using xsl:copy will create an attribute in the result tree (although in the case of Color you are using xsl:attribute to create a new attribute first).

You only actually want to output the value of the attribute, so use xsl:value-of instead

```<code><xsl:template match="@Color">
    <xsl:value-of select="." />
    <br />
</xsl:template>

<xsl:template match="@Color2">
    <xsl:value-of select="." />
</xsl:template>
</code>```

Body:
I want to transform an XML palette file of this type:

<?xml version="1.0"?>
<?xml-stylesheet href="Palette.xsl" type="text/xsl"?>
<Palette Name="MyPalette">
  <PaletteEntry Color="#D0427B" Color2="#D0427B" />
  <PaletteEntry Color="#D55588" Color2="#D55588" />
  <PaletteEntry Color="#DA6895" Color2="#DA6895" />
</Palette>

using this XSL transformation:

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

<xsl:template match="Palette">

        <title>Palette {@Name}</title>

            <xsl:apply-templates/>

</xsl:template>

<xsl:template match="PaletteEntry">

        <xsl:apply-templates select="@*"/>

</xsl:template>

<xsl:template match="@Color">
    <xsl:copy-of select="."/>
</xsl:template>

<xsl:template match="@Color2">
    <xsl:copy-of select="."/>
</xsl:template>

</xsl:stylesheet>

The problem in the output is that the color attributes are rendered well when they are in an attribute but are not translated in content. Here is the HTML output:

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Palette {@Name}</title>

How can I copy color values to content?

Expected output:

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Palette "MyPalette"</title>

#495359
#495359

#5B646A
#5B646A

Body:
Color and Color2 are attributes in the XML, and so using xsl:copy will create an attribute in the result tree (although in the case of Color you are using xsl:attribute to create a new attribute first).

You only actually want to output the value of the attribute, so use xsl:value-of instead

<xsl:template match="@Color">
    <xsl:value-of select="." />
    <br />
</xsl:template>

<xsl:template match="@Color2">
    <xsl:value-of select="." />
</xsl:template>


问:
Clang-format plugin for visual studio 2017
I'm switching to visual studio 2017. The clang-format plugin does not seem to be compatible with this version yet.

Is there a way to force visual studio to use the old plugin anyway ? Is it compatible ?

Is there a not yet released version of the plugin that I can find somewhere or build myself ?

答:
Actually, you can

Download the latest Clang-format for visual studio 2013 and then

Unpackage the *.vsix file with 7-zip

Add one section like the section in the "extension.vsixmanifest" xml file to suuport VS2013 and change the version to "15.0"

Then re-package all the files to a zip archive with 7-zip and rename its extension to *.vsix.

Now you have a clang-format extension installation package supports VS2017.


问:
Displaying a Django query result in HTML - table, list, css divs?
I am working on an django application that will return what historically was a table of information:

```<code>ISSUE  DESCRIPTION  INITIATOR  INITIATEDDATE  ASSIGNEE  FORECASTDATE  STATUS  REMARKS
</code>```

That will be the entrance point for users to sort / filter, etc the list of issues.

The columns like ISSUE, DATES, NAMES are of relatively fixed width, but others can be a paragraph or more.

What is the best way to render this in HTML?  As HTML Tables, lists or with a lot of CSS spans/divs?

I eventually hope to make the issues list sortable or filterable with javascript as well.

答:
If the information you're trying to display is tabular (as it appears to be), then go with tables.

Also, see these questions for even more debate!

Tables instead of DIVs

Why not use tables for layout in HTML?

OwnerDisplayName: Technical Bard

Body:
I am working on an django application that will return what historically was a table of information:

ISSUE  DESCRIPTION  INITIATOR  INITIATEDDATE  ASSIGNEE  FORECASTDATE  STATUS  REMARKS

That will be the entrance point for users to sort / filter, etc the list of issues.

The columns like ISSUE, DATES, NAMES are of relatively fixed width, but others can be a paragraph or more.

What is the best way to render this in HTML?  As HTML Tables, lists or with a lot of CSS spans/divs?

I eventually hope to make the issues list sortable or filterable with javascript as well.

LastEditorDisplayName: Peter Hilton

OwnerDisplayName: Jarrod Dixon


问:
Branching in Mercurial
I have starting using Mercurial for my (our) versioning needs. I have now come to the point that I need to create a feature branch. However, now that I have started working on it -- and I try to push my changes, I keep getting a warning about new remote heads. That's stupid, I know that there will be new remote head(s) that's what a branch after all is?

How am I supposed to create branches and push them without this problem, without using force push as it is surely not the right way to go, right?

I thought about using separate repositories, but that feels just stupid especially for feature branches.

Any help welcome!

答:
To date, the best guide out there is Steve Losh's "A Guide to Branching in Mercurial".

Mercurial will always complain about creating new heads on the remote.  You must use either --force or --new-branch when creating a new head.

When using TortoiseHg, the same can be accomplished via the Synchronize view of the Workbench.  Click Options and then select the Allow push of a new branch or Force push or pull option, as needed.

The reason it behaves this is way is that the Mercurial developers wanted to make it a conscious decision to create a new head on the remote.  Their view is that typical workflows should merge changes prior to pushing.

Title: Branching in Mercurial


答:
Move your where after the join statement. Like this:</p>

```<code>SELECT DISTINCT subscriptions.user_id, subscriptions.payment_plan_id,
payment_plans.plan_type
FROM subscriptions
LEFT OUTER JOIN payment_plans ON subscription.payment_plan_id =
payment_plans.id
WHERE network_id = 24
</code>```

Title: Position of WHERE statement in left outer join

Body:
Move your where after the join statement. Like this:

SELECT DISTINCT subscriptions.user_id, subscriptions.payment_plan_id,
payment_plans.plan_type
FROM subscriptions
LEFT OUTER JOIN payment_plans ON subscription.payment_plan_id =
payment_plans.id
WHERE network_id = 24


问:
How do I set a special char as a mapleader in Vim?

Failed attempts

With quotes

let mapleader = "<Delete>"

Without quotes

let mapleader = <Delete>

E15: Invalid expression: <Delete>

Other keys

let mapleader = "<Escape>"

let mapleader = "<Insert>"

Baseline

Using a comma works.

let mapleader = ","

What I'm really trying to do

I'm trying to set Caps Lock as a mapleader in Vim. Using xmodmap, I can clear Caps Lock's functionality and assign it to a new key. I'd like to assign it to Insert, Delete, or Esc, and then assign one of those as a mapleader in Vim.

答:
Use an escape character

let mapleader = "\<Delete>"

let mapleader = "\<Esc>"

let mapleader = "\<Insert>"

More info: http://vimdoc.sourceforge.net/htmldoc/eval.html#expr-quote

Credit: https://stackoverflow.com/a/9578616/3822261


问:
OptaPlanner: Constraint matches do not update after problemfact changed
I have a UI that lets the user make changes to the problem facts before and after the solving process, i.e. I am doing repeated planning. However, the constraint matches do not get updated when I apply those changes to the score director.

My problem fact changes look something like this:

```<code>solutionBusiness.doProblemFactChange(scoreDirector -> {
    Patient p = patientAdmissionSchedule.getPatientList().get(0);
    scoreDirector.beforeProblemFactChanged(p);
    p.setPreferredRoomCapacity(2);
    scoreDirector.afterProblemFactChanged(p);
});
</code>```

In this case, the scoreDirector would still show me constraint matches with the old preferredRoomCapacity.

The constraint matches only get updated once I start the solving process again. Is there any way to trigger an update of the constraint matches other than starting the solving process?

答:
You need to use the working solution, so:

```<code>Patient p = ((MySchedule) scoreDirector.getWorkingSolution()).getPatientList().get(0);
</code>```

That's a different instance than your original one, see docs chapter "planning clone" etc.

Body:
I have a UI that lets the user make changes to the problem facts before and after the solving process, i.e. I am doing repeated planning. However, the constraint matches do not get updated when I apply those changes to the score director.

My problem fact changes look something like this:

solutionBusiness.doProblemFactChange(scoreDirector -> {
    Patient p = patientAdmissionSchedule.getPatientList().get(0);
    scoreDirector.beforeProblemFactChanged(p);
    p.setPreferredRoomCapacity(2);
    scoreDirector.afterProblemFactChanged(p);
});

In this case, the scoreDirector would still show me constraint matches with the old preferredRoomCapacity.

The constraint matches only get updated once I start the solving process again. Is there any way to trigger an update of the constraint matches other than starting the solving process?

Body:
You need to use the working solution, so:

Patient p = ((MySchedule) scoreDirector.getWorkingSolution()).getPatientList().get(0);

That's a different instance than your original one, see docs chapter "planning clone" etc.


问:
Laravel 5: Sessions on 404 route
This is driving me crazy for weeks now:
How can I make sessions available on the 404 page? I just
embed the 404 error page in my default template. It also shows the navbar
and the footer but how can I keep my user logged in when on a 404?

On a 404 Auth::check() always returns false and every else whats session specific is null or empty.

How to enable sessions on (404) error pages?

答:
Just to expand a bit on the existing answer: make sure to remove that middleware from $middlewareGroups if it's also there, so you don't apply the middleware twice.

You'll end up with something like this:

```<code>protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\Session\Middleware\AuthenticateSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
];

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        //\Illuminate\Session\Middleware\StartSession::class,
        //\Illuminate\Session\Middleware\AuthenticateSession::class,
        //\Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];
</code>```

As far as my understanding goes this was caused because the middleware that deals with the session, by being at the web group was being applied only to those pages routed on web.php. And since the default error handling does not redirect to a routed page we had no access to the session.

This way the middleware will be applied to all pages, and not only to those routed on web.php, including the error ones.

I originally found the soution here, but took me a while to understand why this was happening (thought i cold have gotten it all wrong, feel free to confirm or correct this please).

Hope it helps, it's working for me on Laravel 5.4

Title: Laravel 5: Sessions on 404 route

Body:
Just to expand a bit on the existing answer: make sure to remove that middleware from $middlewareGroups if it's also there, so you don't apply the middleware twice.

You'll end up with something like this:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\Session\Middleware\AuthenticateSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
];

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        //\Illuminate\Session\Middleware\StartSession::class,
        //\Illuminate\Session\Middleware\AuthenticateSession::class,
        //\Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

As far as my understanding goes this was caused because the middleware that deals with the session, by being at the web group was being applied only to those pages routed on web.php. And since the default error handling does not redirect to a routed page we had no access to the session.

This way the middleware will be applied to all pages, and not only to those routed on web.php, including the error ones.

I originally found the soution here, but took me a while to understand why this was happening (thought i cold have gotten it all wrong, feel free to confirm or correct this please).

Hope it helps, it's working for me on Laravel 5.4


问:
Predict an algorithm's theoretical average-case efficiency and order of growth using summation
I need to predict the algorithm's average case efficiency with respect to the size of its inputs using summation/sigma notation to arrive at the final answer. Many resources use summation to predict worst-case, and I couldn't find someone explaining how to predict average case so step-by-step answers are appreciated.

The algorithm contains a nested for loop, with the basic operation inside the innermost loop:

[code redacted]

EDIT: The execution of the basic operation it will always execute inside the second for loop if the second for loop has been entered, and has no break or return statements. HOWEVER: the end of the first for loop has the return statement which is dependent on the value produced in the basic operation, so the contents of the array do affect how many total times the basic operation will be executed for each run of the algorithm.

The array passed to the algorithm has randomly generated contents

I think the predicted average case efficiency is (n^2)/2, making it n^2 order of growth/big Theta of n^2, but I don't know how to theoretically prove this using summation.
Answers are very appreciated!

答:
TL;DR: Your code complexity in average case is Θ(n²) if "basic operation" complexity is Θ(1) and it has no return, break or goto operators.

Explanation: the average-case complexity is just an expectation of the number of operations in your code given the size of the input.

Let's say T(A, n) is a number of operations your code performs given array A of size n. It's easy to see that

```<code>T(A, n) = 1  +                // int k = ceil(size/2.0);
    n * 2 + 1 +               // for (int i = 0; i < size; i++){
    n * (n * 2 + 1) +         // for(int j = 0; j < size; j++){
    n * n * X +               // //Basic operation
    1                         // return (some int);
</code>```

Where X is a number of operations in your "basic operation". As we can see, T(A, n) does not depend on actual contents of the array A. Thus, the expected number of operations given size of the array (which is simply the arithmetical mean of T(A, n) for all possible A for given n) is exactly equal to each of them:

```<code>T(n) = T(A, n) = 3 + n * 2 + n * n * (2 + X)
</code>```

If we assume that X = Θ(1), this expression is Θ(n²).

Even without this assumption we can have an estimate: if X = Θ(f(n)), then your code complexity is T(n) = Θ(f(n)n²). For example, if X is Θ(log n), T(n) = Θ(n² log n)

Body:
TL;DR: Your code complexity in average case is Θ(n²) if "basic operation" complexity is Θ(1) and it has no return, break or goto operators.

Explanation: the average-case complexity is just an expectation of the number of operations in your code given the size of the input.

Let's say T(A, n) is a number of operations your code performs given array A of size n. It's easy to see that

T(A, n) = 1  +                // int k = ceil(size/2.0);
    n * 2 + 1 +               // for (int i = 0; i < size; i++){
    n * (n * 2 + 1) +         // for(int j = 0; j < size; j++){
    n * n * X +               // //Basic operation
    1                         // return (some int);

Where X is a number of operations in your "basic operation". As we can see, T(A, n) does not depend on actual contents of the array A. Thus, the expected number of operations given size of the array (which is simply the arithmetical mean of T(A, n) for all possible A for given n) is exactly equal to each of them:

T(n) = T(A, n) = 3 + n * 2 + n * n * (2 + X)

If we assume that X = Θ(1), this expression is Θ(n²).

Even without this assumption we can have an estimate: if X = Θ(f(n)), then your code complexity is T(n) = Θ(f(n)n²). For example, if X is Θ(log n), T(n) = Θ(n² log n)


问:
how to get all the languages array in yii1?
the directory structure is like this

```<code>modules/
       /module1
              /messages/
                       /en
                          /admin.php
                          /profile.php
                       /ru/
                          /admin.php
                          /profile.php

       /module2/
              /messages/
                       /en
                          /account.php
                          /stats.php
                       /ru
                          /account.php
                          /stats.php
</code>```

each of thos php files has a huge array inside where by the array contains a key value pair of the text strings like e.g

```<code>return array(
'hello' => 'aloha'
);
</code>```

so how to get the arrays in each files ?

答:
you may implement new method to achieve this using glob() php function

```<code>$language = 'en';

foreach (glob('modules/*/messages/' . $language . '/*') as $file) {
    echo "$file\n";
}
</code>```

Output :

```<code>modules/module1/messages/en/admin.php
modules/module1/messages/en/profile.php
modules/module2/messages/en/admin.php
modules/module2/messages/en/profile.php
</code>```

to return arrays from inside those files :

```<code>$language = 'en';
$arrays = [];
foreach (glob('modules/*/messages/' . $language . '/*') as $file) {
    $arrays[] = require_once "$file";
}

print_r($arrays);
</code>```

Body:
the directory structure is like this

modules/
       /module1
              /messages/
                       /en
                          /admin.php
                          /profile.php
                       /ru/
                          /admin.php
                          /profile.php

       /module2/
              /messages/
                       /en
                          /account.php
                          /stats.php
                       /ru
                          /account.php
                          /stats.php

each of thos php files has a huge array inside where by the array contains a key value pair of the text strings like e.g

return array(
'hello' => 'aloha'
);

so how to get the arrays in each files ?

Body:
you may implement new method to achieve this using glob() php function

$language = 'en';

foreach (glob('modules/*/messages/' . $language . '/*') as $file) {
    echo "$file\n";
}

Output :

modules/module1/messages/en/admin.php
modules/module1/messages/en/profile.php
modules/module2/messages/en/admin.php
modules/module2/messages/en/profile.php

to return arrays from inside those files :

$language = 'en';
$arrays = [];
foreach (glob('modules/*/messages/' . $language . '/*') as $file) {
    $arrays[] = require_once "$file";
}

print_r($arrays);


问:
Array AND() ? Logical ANDing of all elements
I have an array and I want to find out if there is at least one false value in it. I was thinking of creating an array_and() function, that just performs a logical AND on all the elements. It would return true if all values are true, otherwise false. Am I over-engineering?

答: you should be able to implement a small function that takes an array and iterates over it checking each member to see if it is false. Return a bool from the function based on the outcome of your checking....</p>


问:
Does Flink JobManager on Yarn need Zookeeper for HA setup
Flink documentation says "When running a highly available YARN cluster, we don’t run multiple JobManager (ApplicationMaster) instances, but only one, which is restarted by YARN on failures.". Then down below "high-availability: zookeeper".

I don't have experience with yarn, but why do we need to setup zookeeper if Yarn takes care of the restarts and we only have one JobManager? Or is this the zookeeper for resource manager(s)?

答:
To insure "high-availability", a Zookeeper-based implementation of YARN is often recommended. With YARN, only one instance of the RessourceManager runs, a Zookeeper based implementation provides high availibility to the RessourceManager, which allows a failover of the RessourceManager to another instance when the active one crashes.

This implementation works by storing the current internal state of the RessourceManager in Zookeeper.

Source : Apache Zookeeper Essentials, Saurav Haloi


答:
You can try this

SELECT DISTINCT subscriptions.user_id, subscriptions.payment_plan_id, payment_plans.plan_type
FROM subscriptions LEFT OUTER JOIN payment_plans ON subscription.payment_plan_id = payment_plans.id
WHERE subscriptions.network_id = 24


问:
Test the error code of a custom exception with JUnit 4
I would like to test the return code of an exception. Here is my production code:

```<code>class A {
  try {
    something...
  }
  catch (Exception e)
  {
    throw new MyExceptionClass(INTERNAL_ERROR_CODE, e);
  }
}
</code>```

And the corresponding exception:

```<code>class MyExceptionClass extends ... {
  private errorCode;

  public MyExceptionClass(int errorCode){
    this.errorCode = errorCode;
  }

  public getErrorCode(){
    return this.errorCode;
  }
}
</code>```

My unit test:

```<code>public class AUnitTests{
  @Rule
  public ExpectedException thrown= ExpectedException.none();

  @Test (expected = MyExceptionClass.class,
  public void whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode() throws Exception {
      thrown.expect(MyExceptionClass.class);
      ??? expected return code INTERNAL_ERROR_CODE ???

      something();
  }
}
</code>```

答:
Simple:

```<code> @Test
 public void whenSerialNumberIsEmpty_shouldThrowSerialNumberInvalid() throws Exception {
  try{
     whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode();
     fail("should have thrown");
  }
  catch (MyExceptionClass e){
     assertThat(e.getCode(), is(MyExceptionClass.INTERNAL_ERROR_CODE));
  }
</code>```

That is all you need here:

you don't want to expect that specific exception, as you want to check some properties of it

you know that you want to enter that specific catch block; thus you simply fail when the call doesn't throw

you don't need any other checking - when the method throws any other exception, JUnit will report that as error anyway

Body:
I would like to test the return code of an exception. Here is my production code:

class A {
  try {
    something...
  }
  catch (Exception e)
  {
    throw new MyExceptionClass(INTERNAL_ERROR_CODE, e);
  }
}

And the corresponding exception:

class MyExceptionClass extends ... {
  private errorCode;

  public MyExceptionClass(int errorCode){
    this.errorCode = errorCode;
  }

  public getErrorCode(){
    return this.errorCode;
  }
}

My unit test:

public class AUnitTests{
  @Rule
  public ExpectedException thrown= ExpectedException.none();

  @Test (expected = MyExceptionClass.class,
  public void whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode() throws Exception {
      thrown.expect(MyExceptionClass.class);
      ??? expected return code INTERNAL_ERROR_CODE ???

      something();
  }
}

Body:
Simple:

 @Test
 public void whenSerialNumberIsEmpty_shouldThrowSerialNumberInvalid() throws Exception {
  try{
     whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode();
     fail("should have thrown");
  }
  catch (MyExceptionClass e){
     assertThat(e.getCode(), is(MyExceptionClass.INTERNAL_ERROR_CODE));
  }

That is all you need here:

you don't want to expect that specific exception, as you want to check some properties of it

you know that you want to enter that specific catch block; thus you simply fail when the call doesn't throw

you don't need any other checking - when the method throws any other exception, JUnit will report that as error anyway


问:
Is there any way to know the RTT in datalink layer?
I'm trying to find a way to know RTT during my android phone and the router. I'm not sure whether there is a way to find that.
Dose anyone know some of this field knowledge?
Thank you.</p>

答:
I do not think, that there is a way to read the value from the link layer, but there is a WiFi standard 802.11mc, which includes some kind of rtt measurement.

Unfortunately, Android has only a hidden system api up to now and an app using this api has to be installed in priv-app folder which requires root.

More information can be found in this Github-project: Android RTTManagerCompat


问:
How to open and control a chrome window using nodejs?
I'm writing an application using node.js which requires me to open a window in a browser and fill a text field.
I have tried using opn. Fact is it just opens the tab but doesnt  allow me to control it.</p>

答:
these kinds of stuff mostly helpful for acceptence testing and you can do it using "selenium"

other wise if you just want to open a window and fill a text field.

I believe the page you are trying to open is already been generated. if yes, then why don't you modify that page to accept a query string e.g: "?q=some-text" and fill that text field if you find.

Let me know if you have any other question


问:
WebDriverWait.until no longer available in Selenium-java-3.2 and Selenium-java-3.3 releases
In Selenium-java-3.0.1, I can use WebDriverWait.until for explicit waits:

```<code>new WebDriverWait(myChromeDriver, 30).until((ExpectedCondition<Boolean>) wd -> ((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete"));
</code>```

Above code was running well in Selenium-java-3.0.1, until we upgraded to Selenium-java-3.2 where class WebDriverWait disappear from client-combined-3.3.0-nodeps.jar all together.

What is the corresponding method call in Selenium 3.2/3.3? Thanks in advance.

Stack trace is as below:

```<code>java.lang.NoSuchMethodError: org.openqa.selenium.support.ui.WebDriverWait.until(Lcom/google/common/base/Function;)Ljava/lang/Object;
    at au.com.testpro.rft2selenium.objects.TestObject.waitForLoad(Unknown Source)
    at au.com.testpro.rft2selenium.objects.TestObject.find(Unknown Source)
    at au.com.testpro.rft2selenium.objects.TestObject.find(Unknown Source)
    at test.ScriptSuperClass_JZ.findTestObject(ScriptSuperClass_JZ.java:65)
    at test.refData_Verify.execute(refData_Verify.java:102)
    at au.com.testpro.framework.java.superclasses.JavaFrameworkSuperClass.execute(Unknown Source)
    at au.com.testpro.framework.java.superclasses.JavaFrameworkSuperClass.executeCsv(Unknown Source)
    at test.refData_Verify.test(refData_Verify.java:486)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code>```

答: Please update the version of Guava jar that you are using to v-21, whenever there is a change in selenium-version, it is recommended to read the release notes, before start using the version.

Body:
In Selenium-java-3.0.1, I can use WebDriverWait.until for explicit waits:

new WebDriverWait(myChromeDriver, 30).until((ExpectedCondition<Boolean>) wd -> ((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete"));

Above code was running well in Selenium-java-3.0.1, until we upgraded to Selenium-java-3.2 where class WebDriverWait disappear from client-combined-3.3.0-nodeps.jar all together.

What is the corresponding method call in Selenium 3.2/3.3? Thanks in advance.

Stack trace is as below:

java.lang.NoSuchMethodError: org.openqa.selenium.support.ui.WebDriverWait.until(Lcom/google/common/base/Function;)Ljava/lang/Object;
    at au.com.testpro.rft2selenium.objects.TestObject.waitForLoad(Unknown Source)
    at au.com.testpro.rft2selenium.objects.TestObject.find(Unknown Source)
    at au.com.testpro.rft2selenium.objects.TestObject.find(Unknown Source)
    at test.ScriptSuperClass_JZ.findTestObject(ScriptSuperClass_JZ.java:65)
    at test.refData_Verify.execute(refData_Verify.java:102)
    at au.com.testpro.framework.java.superclasses.JavaFrameworkSuperClass.execute(Unknown Source)
    at au.com.testpro.framework.java.superclasses.JavaFrameworkSuperClass.executeCsv(Unknown Source)
    at test.refData_Verify.test(refData_Verify.java:486)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)


问:
how to do a query to select some selected datas on group by
I have a table like below structure:

```<code>ID|PrcessorID|BatchNO|NoOfTransaction|BatchCreatedDate
1 |20        |2      |3              |2017-03-28
2 |21        |3      |3              |2017-04-01
3 |21        |4      |7              |2017-04-01
4 |20        |5      |3              |2017-04-01
5 |21        |6      |2              |2017-04-02
6 |20        |7      |4              |2017-04-02
</code>```

and another table is like

```<code>ProcessorID|ProcessorName
20         |Payme
21         |Payany
</code>```

I have to get the data total no of transaction and count of the batch on each specific date by each specific processor of 3 days ago group by the processor so that I can get data like:

```<code>PrcessorName|Batchcount|TotNoOfTransaction|BatchCreatedDate

     Payany |2         |10                |2017-04-01
     Payme  |1         |3                 |2017-04-01
     Payany |1         |2                 |2017-04-02
      Payme |1         |4                 |2017-04-02
</code>```

What i am doin right now is:

```<code>Select a.ProcessorId As ProcessorID,b.ProcessorName As ProcessorName,BatchCreatedDate,Sum(NoofTRansaction) As TotNoofTransaction,Count(BatchNo) As BatchCountfrom TableA a innerjoin TableB b on a.ProcessorID=b.ProcessorID where BatchcreatedDate<GetDate() and BatchCreatedDate>GetDate()-4 groupby ProcessorName,BatchCreatedDate
</code>```

but this query is giving me result like

```<code>PrcessorName|Batchcount|TotNoOfTransaction|BatchCreatedDate

     Payany |1         |3                 |2017-04-01
     Payany |1         |7                 |2017-04-01
     Payme  |1         |3                 |2017-04-01
     Payany |1         |2                 |2017-04-02
      Payme |1         |4                 |2017-04-02
</code>```

答:
```<code>;WITH Cte1 (ID,ProcessorID,BatchNO,NoOfTransaction,BatchCreatedDate)
As
(
SELECT 1 ,20 ,2 ,3  ,'2017-03-28' UNION ALL
SELECT 2 ,21 ,3 ,3  ,'2017-04-01' UNION ALL
SELECT 3 ,21 ,4 ,7  ,'2017-04-01' UNION ALL
SELECT 4 ,20 ,5 ,3  ,'2017-04-01' UNION ALL
SELECT 5 ,21 ,6 ,2  ,'2017-04-02' UNION ALL
SELECT 6 ,20 ,7 ,4  ,'2017-04-02'
)
,cte2(ProcessorID,ProcessorName) AS (
        SELECT 20,'Payme'UNION ALL
        SELECT 21,'Payany'
        )

SELECT DISTINCT cte2.ProcessorName
    ,COUNT(BatchNO) OVER (
        PARTITION BY cte1.ProcessorID
        ,Cte1.BatchCreatedDate ORDER BY Cte1.BatchCreatedDate
        )As Batchcount
    ,SUM(NoOfTransaction) OVER (
        PARTITION BY Cte1.ProcessorID
        ,Cte1.BatchCreatedDate ORDER BY Cte1.BatchCreatedDate
        ) As TotNoOfTransaction
    ,cte1.BatchCreatedDate
FROM Cte1
INNER JOIN cte2 ON cte2.ProcessorID = Cte1.ProcessorID
ORDER BY cte1.BatchCreatedDate
</code>```

Body:
I have a table like below structure:

ID|PrcessorID|BatchNO|NoOfTransaction|BatchCreatedDate
1 |20        |2      |3              |2017-03-28
2 |21        |3      |3              |2017-04-01
3 |21        |4      |7              |2017-04-01
4 |20        |5      |3              |2017-04-01
5 |21        |6      |2              |2017-04-02
6 |20        |7      |4              |2017-04-02

and another table is like

ProcessorID|ProcessorName
20         |Payme
21         |Payany

I have to get the data total no of transaction and count of the batch on each specific date by each specific processor of 3 days ago group by the processor so that I can get data like:

PrcessorName|Batchcount|TotNoOfTransaction|BatchCreatedDate

     Payany |2         |10                |2017-04-01
     Payme  |1         |3                 |2017-04-01
     Payany |1         |2                 |2017-04-02
      Payme |1         |4                 |2017-04-02

What i am doin right now is:

Select a.ProcessorId As ProcessorID,b.ProcessorName As ProcessorName,BatchCreatedDate,Sum(NoofTRansaction) As TotNoofTransaction,Count(BatchNo) As BatchCountfrom TableA a innerjoin TableB b on a.ProcessorID=b.ProcessorID where BatchcreatedDate<GetDate() and BatchCreatedDate>GetDate()-4 groupby ProcessorName,BatchCreatedDate

but this query is giving me result like

PrcessorName|Batchcount|TotNoOfTransaction|BatchCreatedDate

     Payany |1         |3                 |2017-04-01
     Payany |1         |7                 |2017-04-01
     Payme  |1         |3                 |2017-04-01
     Payany |1         |2                 |2017-04-02
      Payme |1         |4                 |2017-04-02


问:
error while change the date format
For the dataset below, I want to change the date format to YYYY-mm-dd:

```<code>DATE          WT
30 Dec 2016   1150.9
29 Dec 2016   1157.67
28 Dec 2016   1141.03
27 Dec 2016   1138.49
26 Dec 2016   1132.72
23 Dec 2016   1133.57
</code>```

I am using as.Date(DATE, "%d.%m.%Y"), but it is not working.

Can there be other method?

答:
We need to use %b instead of %m

```<code>df1$DATE <- as.Date(df1$DATE, "%d %b %Y")
</code>```

Title: error while change the date format

Body:
For the dataset below, I want to change the date format to YYYY-mm-dd:

DATE          WT
30 Dec 2016   1150.9
29 Dec 2016   1157.67
28 Dec 2016   1141.03
27 Dec 2016   1138.49
26 Dec 2016   1132.72
23 Dec 2016   1133.57

I am using as.Date(DATE, "%d.%m.%Y"), but it is not working.

Can there be other method?

Body:
We need to use %b instead of %m

df1$DATE <- as.Date(df1$DATE, "%d %b %Y")