问:
DataTables Loading and Rendering Delay
I am using DataTables with Bootstrap 4 and client side processing. Displaying around 2,000 records.

The loading time is acceptable, however I notice that when I reload the page (F5) I can see an un-formatted DataTable for a split second. It's almost as if DataTables is the last thing to load, and it's quite obvious.

If you look at their 'Zero configuration' example you can see what I mean. When reloading the page you can actually see all the table records for a split second (you have to be quick!).

There is a 'Bootstrap 4' example, also noticeable on that page.

I have a few questions;

Why does this happen?

Is there anything I can do to prevent it?

I have tried re-ordering my JS and CSS files (I only have a few) however it has made no difference. My concern is that as I add more records the loading time will increase and the un-formatted DataTable will be more obvious on each page load.

答:
The hint is in the code of the Bootstrap 4 example you linked.

```<code>$(document).ready(function() {
    $('#example').DataTable();
} );
</code>```

This code states that when the document is ready (it has finished rendering HTML and CSS), take the element with the id example and turn it into a DataTable.

To prevent this you could set the style of of the table to display: hidden.

Then you can add $('#example').show() to the code to display the table again after it has been made into a DataTable

```<code>$(document).ready(function() {
    $('#example').DataTable();
    $('#example').show();
} );
</code>```

Title: DataTables Loading and Rendering Delay

Body:
The hint is in the code of the Bootstrap 4 example you linked.

$(document).ready(function() {
    $('#example').DataTable();
} );

This code states that when the document is ready (it has finished rendering HTML and CSS), take the element with the id example and turn it into a DataTable.

To prevent this you could set the style of of the table to display: hidden.

Then you can add $('#example').show() to the code to display the table again after it has been made into a DataTable

$(document).ready(function() {
    $('#example').DataTable();
    $('#example').show();
} );


来源: stackexchange

问:
template overload of trigonometric functions
I am developing a larger library, where I would like to be able to change the floating point precision used. Trigonometric functions are used in a number of places, so I decided to include templated wrappers for e.g. sine and cosine.

I have made the following simple example, which gives a stack corruption and I cannot figure out why. Any hints

```<code>#include <cmath>
#include <iostream>

namespace sps {
template <typename T>
inline T sin(const T& v) { return sin(v); }

template <typename T>
inline T cos(const T& v) { return cos(v); }

template <>
inline float sin<float>(const float& v) { return sinf(v); }

template <>
inline float cos<float>(const float& v) { return cosf(v); }
}  // namespace sps

template float sps::sin(const float& v);
template float sps::cos(const float& v);
template double sps::sin(const double& v);
template double sps::cos(const double& v);

int main()
{
  double d = 2.0;
  std::cout << sps::sin(d) << std::endl; /* (*) */
  float f = 2.0f;
  std::cout << sps::sin(f) << std::endl;
  return 0;
}
</code>```

If I explicitly state, which functions to use, e.g. sps::sin(f), I still get a stack corruption. The stack corruption is thrown in the line with the asterisk (*). If I omit the explicit instantiations, the stack corruption still occurs. I tried changing the inputs to by-value, but this has no effect either.

I get the same error using gcc 6.3.0 and MSCV 2017.

Thanks in advance
Jens

答:
You are getting an infinit recursion:

```<code>template <typename T>
inline T sin(const T& v) { return sin(v); }  // keep calling sin
</code>```

what you need is to change the return value to:

```<code>template <typename T>
inline T sin(const T& v) { return std::sin(v); }
                                  ^^^
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am developing a larger library, where I would like to be able to change the floating point precision used. Trigonometric functions are used in a number of places, so I decided to include templated wrappers for e.g. sine and cosine.

I have made the following simple example, which gives a stack corruption and I cannot figure out why. Any hints

#include <cmath>
#include <iostream>

namespace sps {
template <typename T>
inline T sin(const T& v) { return sin(v); }

template <typename T>
inline T cos(const T& v) { return cos(v); }

template <>
inline float sin<float>(const float& v) { return sinf(v); }

template <>
inline float cos<float>(const float& v) { return cosf(v); }
}  // namespace sps

template float sps::sin(const float& v);
template float sps::cos(const float& v);
template double sps::sin(const double& v);
template double sps::cos(const double& v);

int main()
{
  double d = 2.0;
  std::cout << sps::sin(d) << std::endl; /* (*) */
  float f = 2.0f;
  std::cout << sps::sin(f) << std::endl;
  return 0;
}

If I explicitly state, which functions to use, e.g. sps::sin(f), I still get a stack corruption. The stack corruption is thrown in the line with the asterisk (*). If I omit the explicit instantiations, the stack corruption still occurs. I tried changing the inputs to by-value, but this has no effect either.

I get the same error using gcc 6.3.0 and MSCV 2017.

Thanks in advance
Jens

Body:
You are getting an infinit recursion:

template <typename T>
inline T sin(const T& v) { return sin(v); }  // keep calling sin

what you need is to change the return value to:

template <typename T>
inline T sin(const T& v) { return std::sin(v); }
                                  ^^^


问:
What is the proper use of async EventEmitters?
I noticed that an EventEmitter can be configured to emit events asynchronously.

constructor(isAsync: boolean = false)

  Creates an instance of EventEmitter, which depending on isAsync, delivers events synchronously or asynchronously.

(taken from https://angular.io/api/core/EventEmitter)

When should my component deliver events asynchronously instead of using the default behavior?

答:
When you are using the isAsync option then every event emitted from EventEmitter gets wrapped in setTimeout making it async.

This is excerpt from the EventEmitter source code:

```<code>this.__isAsync ?
  (value: any) => { setTimeout(() => generatorOrNext.next(value)); } :
  (value: any) => { generatorOrNext.next(value); };
</code>```

What value does it add to you? Probably none.
Zone's checks will happen before your code receives event, and then again once your event has been processed creating more work for the CPUs. Theoretically you could squeeze some custom stuff in between, but even angular team does not recommend it.

Read more on reasoning here: https://github.com/angular/angular/issues/6311

Hope that helps

Body:
When you are using the isAsync option then every event emitted from EventEmitter gets wrapped in setTimeout making it async.

This is excerpt from the EventEmitter source code:

this.__isAsync ?
  (value: any) => { setTimeout(() => generatorOrNext.next(value)); } :
  (value: any) => { generatorOrNext.next(value); };

What value does it add to you? Probably none.
Zone's checks will happen before your code receives event, and then again once your event has been processed creating more work for the CPUs. Theoretically you could squeeze some custom stuff in between, but even angular team does not recommend it.

Read more on reasoning here: https://github.com/angular/angular/issues/6311

Hope that helps

ContentLicense: CC BY-SA 4.0


问:
unable to perform correct assertion for each cost in a json
I am trying to perform an assertion where if each cost = 25, the assertion should pass, else fail. I thought I got it to work but I can see the assertion passes even if the cost is not 25.

I think this line is incorrect:

```<code>assert json.cost.flatten().collect { new BigDecimal(it)}.collect{it == processonecost}
</code>```

I have three costs in the json that is 26 but yet I have processidonecost = 25

Below is the code:

```<code>def response = messageExchange.response.responseContent
def json =  new JsonSlurper().parseText(response)
def processonecost = 25

assert json.cost.flatten().collect { new BigDecimal(it)}.collect{it == processonecost}
</code>```

The json output is simply:

```<code>{
cost: 26
cost: 26
cost: 26
}
</code>```

I don't want to implement processonecost = [25,25,25] by the way

答: .collect{it == processonecost} will result in [false, false, false] which is true. It is true because it is a list that is not empty. What you actually wanted to do is .every{it == processonecost} which returns true if all elements fulfill the predicate and false otherwise.

Body:
I am trying to perform an assertion where if each cost = 25, the assertion should pass, else fail. I thought I got it to work but I can see the assertion passes even if the cost is not 25.

I think this line is incorrect:

assert json.cost.flatten().collect { new BigDecimal(it)}.collect{it == processonecost}

I have three costs in the json that is 26 but yet I have processidonecost = 25

Below is the code:

def response = messageExchange.response.responseContent
def json =  new JsonSlurper().parseText(response)
def processonecost = 25

assert json.cost.flatten().collect { new BigDecimal(it)}.collect{it == processonecost}

The json output is simply:

{
cost: 26
cost: 26
cost: 26
}

I don't want to implement processonecost = [25,25,25] by the way


问:
Is it possible to trigger a downstream job name based on a variable?
I've created a Jenkins job which queries AWS CLI and populates a variable with some data.

It then triggers a downstream project and injects the variable from the parent job to the downstream job as a parameter for a CloudFormation stack creation (the parameter value is the name of the latest RDS snapshot ID).

I wanted to know if it's possible to trigger different downstream projects based on some choice parameter?

For example, let's say that the parent job has a choice parameter setup with different AWS regions.

The user which starts the build will choose the correct region, and then, based on his selection, the downstream project which will be triggered is the one that matches the region.

Is that even possible? (It's a freestyle project by the way)

答:
2 ways to do.

1 - Use Parameterized Trigger plugin

Create a job with multiple configurations.
Set the matrix configuration in the job (this will be the downstream job). I this case the second job (let's call job B) have multiple configurations that match every scenario you want.

In post build choose "Trigger Parameterized build on other project" (in main job, let's call job A). Then "Add Parameter" and "Restric matrix execution to a subset" here your put you var that is the reference of the group of config in job B.

2 Use Conditional Build Step plugin

In build add "Conditional Steps(multiple)". Set "Run?" to string match. In string 1 put the var ($var1) in the string 2 put the word to match (jobB).

In steps to run, choose "Trigger/call builds on other projects"


问:
Creating a linked-list of variable length
I have a list of ((a)(b)(f(x))). What i would like to get is a linked list structure of((a)(b)(f(x1))(a)(b)(f(x2))(a)(b)(f(x3)))). That is, repeatively appending the list the on the basis of requirement of the user and the value of the variable is chaning so that its value will be unique from each other. How can i implement it in LISP?

答:
```<code>? (let ((list '((a) (b) (f (x))))
        (n 3))
    (flet ((copier (l n)
             (setf l (copy-tree l))
             (let ((sym (first (second (third l)))))
               (setf (first (second (third l)))
                     (intern (format nil "~a~a"
                                     (symbol-name sym)
                                     n))))
             l))
      (loop for i from 1 upto n
        nconc (copier list i))))

((A) (B) (F (X1)) (A) (B) (F (X2)) (A) (B) (F (X3)))
</code>```

ContentLicense: CC BY-SA 2.5


问:
Remove primary key and auto-increment in database using migration in laravel
I have table with primary key and auto-increment field, I want make new migration to drop primary key index and also remove the auto increment field. How can i achieve this.

I created new migration as

```<code>public function up()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

        $table->dropPrimary('message_id');
        $table->unsignedInteger('message_id');
    });
}
</code>```

It gave me error in command as [Illuminate\Database\QueryException]

  SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'message _id' (SQL: alter table tbl_'message_read_state' add 'message_id' int unsigned not null)

Whats Wrong ?????

答:
The dropPrimary method only removed the primary key, not the column. You would have to do:

```<code>    /**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

        $table->dropPrimary('message_id');
        $table->dropColumn('message_id');
        $table->unsignedInteger('message_id');
    });
}
</code>```

Or instead of dropping and re-creating the column, you can use change in Laravel 5.

```<code>/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

        $table->dropPrimary('message_id');
        $table->integer('message_id')->unsigned()->change();
    });
}
</code>```

Body:
I have table with primary key and auto-increment field, I want make new migration to drop primary key index and also remove the auto increment field. How can i achieve this.

I created new migration as

public function up()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

        $table->dropPrimary('message_id');
        $table->unsignedInteger('message_id');
    });
}

It gave me error in command as [Illuminate\Database\QueryException]

  SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'message _id' (SQL: alter table tbl_'message_read_state' add 'message_id' int unsigned not null)

Whats Wrong ?????

Body:
The dropPrimary method only removed the primary key, not the column. You would have to do:

    /**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

        $table->dropPrimary('message_id');
        $table->dropColumn('message_id');
        $table->unsignedInteger('message_id');
    });
}

Or instead of dropping and re-creating the column, you can use change in Laravel 5.

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

        $table->dropPrimary('message_id');
        $table->integer('message_id')->unsigned()->change();
    });
}


问:
Correctly parsing through a JSON array with multiple objects using Alamofire and SwiftyJSON
I am able to print out the response. However I am unable to loop through the array and initialise it. This is how I am requesting the data:

```<code>Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default).responseJSON { (response) in

    print(response.value!)

    guard let data = response.data else { return }
    let json = JSON(data: data)

    for r in json.arrayValue {
        let person = Person(json: r)
    }
}
</code>```

I have added breakpoints but I am unable to understand as to why the loop does not happen?

Update:

response.value! example:

```<code>{
  "pagination": {
    "object_count": 1,
    "page_number": 1
  },
  "attendees": [
    {
      "id": "818060297",
      "quantity": 1,
      "profile": {
        "first_name": "John",
        "last_name": "Doe",
        "company": "Apple",
        "name": "John Doe",
        "email": "john_doe@testmail.com",
        "job_title": "CEO"
      },
      "status": "Attending"
    }
  ]
}
</code>```

Update 2

Here is my AttendeesProfile class:

```<code>class AttendeesProfile {

    var name: String?

    init(json: JSON) {
        self.name = json["name"].stringValue
    }

}
</code>```

Now I am not sure how to get the Attendee class to work properly:

```<code>class Attendees {

    var attendees = [String]()
    var attendeesProfile: AttendeesProfile!

    init(json: JSON) {
        // Something here
    }
}
</code>```

答:
You have to cast your response data. You can not walk on an unknown array
I suggest you to use ObjectMapper library. It can parse your data to your willing model and if received data is nil or is not your wanted model you can find out easily. Do not forget to print response.data to ensure what data exactly is.
https://github.com/Hearst-DD/ObjectMapper</p>

Body:
I am able to print out the response. However I am unable to loop through the array and initialise it. This is how I am requesting the data:

Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default).responseJSON { (response) in

    print(response.value!)

    guard let data = response.data else { return }
    let json = JSON(data: data)

    for r in json.arrayValue {
        let person = Person(json: r)
    }
}

I have added breakpoints but I am unable to understand as to why the loop does not happen?

Update:

response.value! example:

{
  "pagination": {
    "object_count": 1,
    "page_number": 1
  },
  "attendees": [
    {
      "id": "818060297",
      "quantity": 1,
      "profile": {
        "first_name": "John",
        "last_name": "Doe",
        "company": "Apple",
        "name": "John Doe",
        "email": "john_doe@testmail.com",
        "job_title": "CEO"
      },
      "status": "Attending"
    }
  ]
}

Update 2

Here is my AttendeesProfile class:

class AttendeesProfile {

    var name: String?

    init(json: JSON) {
        self.name = json["name"].stringValue
    }

}

Now I am not sure how to get the Attendee class to work properly:

class Attendees {

    var attendees = [String]()
    var attendeesProfile: AttendeesProfile!

    init(json: JSON) {
        // Something here
    }
}


问:
Error while pushing Google Chrome Puppeteer app to Predix
I am trying to use Google Chrome Puppeteer in the predix-web-starter app. When I run the code locally on Windows, it runs flawlessly. After I push it to Predix, and when I run the part containing the Puppeteer code, it results in an error. There seems to be some missing library issues (not sure what).
In short, how can I get Puppeteer to run on Predix?

Predix-web-starter: https://github.com/PredixDev/predix-webapp-starter
Puppeteer: https://www.npmjs.com/package/puppeteer

Puppeteer code:

```<code>const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://news.ycombinator.com', {waitUntil: 'networkidle'});
await page.pdf({path: 'hn.pdf', format: 'A4'});
await browser.close();
})();
</code>```

Logs:

```<code>2017-11-07T12:40:16.19+0530 [App/0] ERR /home/vcap/app/node_modules/puppeteer/.local-chromium/linux-508693/chrome-linux/chrome: error while loading shared libraries: libX11-xcb.so.1: cannot open shared object file: No such file or directory
2017-11-07T12:40:16.19+0530 [App/0] ERR TROUBLESHOOTING: https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md
2017-11-07T12:40:16.19+0530 [App/0] ERR     at Interface.close (readline.js:319:8)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at endReadableNT (_stream_readable.js:974:12)
2017-11-07T12:40:16.19+0530 [App/0] ERR Potentially unhandled rejection [3] Error: Failed to launch chrome!
2017-11-07T12:40:16.19+0530 [App/0] ERR     at onClose (/home/vcap/app/node_modules/puppeteer/node6/Launcher.js:262:14)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at emitNone (events.js:91:20)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at Interface.emit (events.js:186:7)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at _combinedTickCallback (internal/process/next_tick.js:74:11)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at Interface.helper.addEventListener (/home/vcap/app/node_modules/puppeteer/node6/Launcher.js:251:50)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at Socket.onend (readline.js:106:10)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at emitNone (events.js:91:20)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at Socket.emit (events.js:186:7)
2017-11-07T12:41:15.21+0530 [RTR/2] OUT puppeter-arjun-app.run.aws-usw02-pr.ice.predix.io - [2017-11-07T07:10:16.196+0000] "GET /puppeteer HTTP/1.1" 502 0 67 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36" "10.72.11.93:2263" "10.72.2.213:61322" x_forwarded_for:"-" x_forwarded_proto:"http" vcap_request_id:"7d0f3007-914a-42d4-536d-b94eb8d2fb6c" response_time:59.022647288 app_id:"02063159-96d9-43c5-a3e9-77f4e72339f4" app_index:"-" x_b3_traceid:"4f11f468be4b6817" x_b3_spanid:"4f11f468be4b6817" x_b3_parentspanid:"-"
2017-11-07T12:41:15.21+0530 [RTR/2] OUT
</code>```

答:
Looks like puppeteer is trying to use a "shared library" which is missing or you don't have access to.  In the Predix Cloud Foundry environment, your access to the server OS is very limited.  You're only allowed to use resources inside the container, which allows scaling to happen easily.

What's your goal?  Trying to run browser tests?  You might try selenium with Sauce Labs, or Travis.

Body:
I am trying to use Google Chrome Puppeteer in the predix-web-starter app. When I run the code locally on Windows, it runs flawlessly. After I push it to Predix, and when I run the part containing the Puppeteer code, it results in an error. There seems to be some missing library issues (not sure what).
In short, how can I get Puppeteer to run on Predix?

Predix-web-starter: https://github.com/PredixDev/predix-webapp-starter
Puppeteer: https://www.npmjs.com/package/puppeteer

Puppeteer code:

const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://news.ycombinator.com', {waitUntil: 'networkidle'});
await page.pdf({path: 'hn.pdf', format: 'A4'});
await browser.close();
})();

Logs:

2017-11-07T12:40:16.19+0530 [App/0] ERR /home/vcap/app/node_modules/puppeteer/.local-chromium/linux-508693/chrome-linux/chrome: error while loading shared libraries: libX11-xcb.so.1: cannot open shared object file: No such file or directory
2017-11-07T12:40:16.19+0530 [App/0] ERR TROUBLESHOOTING: https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md
2017-11-07T12:40:16.19+0530 [App/0] ERR     at Interface.close (readline.js:319:8)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at endReadableNT (_stream_readable.js:974:12)
2017-11-07T12:40:16.19+0530 [App/0] ERR Potentially unhandled rejection [3] Error: Failed to launch chrome!
2017-11-07T12:40:16.19+0530 [App/0] ERR     at onClose (/home/vcap/app/node_modules/puppeteer/node6/Launcher.js:262:14)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at emitNone (events.js:91:20)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at Interface.emit (events.js:186:7)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at _combinedTickCallback (internal/process/next_tick.js:74:11)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at Interface.helper.addEventListener (/home/vcap/app/node_modules/puppeteer/node6/Launcher.js:251:50)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at Socket.onend (readline.js:106:10)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at emitNone (events.js:91:20)
2017-11-07T12:40:16.19+0530 [App/0] ERR     at Socket.emit (events.js:186:7)
2017-11-07T12:41:15.21+0530 [RTR/2] OUT puppeter-arjun-app.run.aws-usw02-pr.ice.predix.io - [2017-11-07T07:10:16.196+0000] "GET /puppeteer HTTP/1.1" 502 0 67 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36" "10.72.11.93:2263" "10.72.2.213:61322" x_forwarded_for:"-" x_forwarded_proto:"http" vcap_request_id:"7d0f3007-914a-42d4-536d-b94eb8d2fb6c" response_time:59.022647288 app_id:"02063159-96d9-43c5-a3e9-77f4e72339f4" app_index:"-" x_b3_traceid:"4f11f468be4b6817" x_b3_spanid:"4f11f468be4b6817" x_b3_parentspanid:"-"
2017-11-07T12:41:15.21+0530 [RTR/2] OUT


问:
Python, api requests
I have a following question. Is there any possibility to enlarge the speed of sending the single api request. I want to send request and obtain json as a result. When i use requests.get(url) the time is about 150ms.
I would like to make this time lower. My aim is to speed up single request. Is there any possibility to do this?

答:
Well according to benchmarks, urllib2 tends to be the fastest. So if you wanted to speed up your code, you could do the following:

Python 2.x:

```<code>import urllib2
urllib2.urlopen(url).read()
</code>```

Python 3.x:

```<code>import urllib.request
urllib.request.urlopen(url).read()
</code>```

But as others have pointed out, this will largely depend on server and your own network.

Title: Python, api requests

Body:
Well according to benchmarks, urllib2 tends to be the fastest. So if you wanted to speed up your code, you could do the following:

Python 2.x:

import urllib2
urllib2.urlopen(url).read()

Python 3.x:

import urllib.request
urllib.request.urlopen(url).read()

But as others have pointed out, this will largely depend on server and your own network.


问:
Xslt - Move node to one "level" up
I want an xml attribute one level up in an xml structure.
As for requested I show a more detailed example:

```<code><items>
  <kitchen>
    <furnitures>
      <chairs type="wood">
        <chair_1 color="green" legs="4"/>
      </chairs>
      <tables type="stone">
      </tables>
    </furnitures>
  </kitchen>
</items>
</code>```

And I want to output this:

```<code><items>
  <kitchen>
    <furnitures>
      <chairs type="wood"/>
      <chair_1 color="green" legs="4"/>
      <tables type="stone">
      </tables>
    </furnitures>
  </kitchen>
</items>
</code>```

As you see I move char_1 to under  from under

```<code><xsl:template match="node()">
  <xls:copy>
    <xsl:apply-templates select="@*"/>
    <xsl:apply-templates select="*"/>
    <xsl:apply-templates select="text()">
  </xsl:copy>
</xsl:template>

<xsl:template match="/items/kitchen/furnitures/chairs">
  <xsl:choose>
    <xsl:when test="chair_1">
      <xsl:copy>
      <xsl:apply-templates select="child::node()[not(self:chair_1)]|@*|text()"/>
      </xsl:copy>
    <xsl:apply-templates select="chair_1"/>
    </xsl:when>
     <!----- edit -->
      <xsl:otherwise>
        <xsl:copy>
          <xls:apply-templates select ="@*|node()"/>
        </xsl:copy>
       <xsl:apply-templates select="settings"/>
       <xsl:text>
       </xsl:text>
       <chair_1 color="green" legs="4"/>
    </xls:otherwise>
  </xls:choose>
</xsl:template>
</code>```

So, my main problem is, that my copy don't contain line-breaks.
Please keep in mind, I am using PHP:Xsltproc, on my dev-comp the indentation works fine, but with PHP's xsltproc it isn't fine, and drops the line breaks.
so the output like this:

```<code><items>
  <kitchen>
    <furnitures>
      <chairs type="wood"/><chair_1 color="green" legs="4"/>
      <tables type="stone">
      </tables>
    </furnitures>
  </kitchen>
</items>
</code>```

Which is fine, but not correctly indented.
(Disclaimer: there could be some typos, as this is not the original XML, and of course I am using the required stylsheet, version, phpversion, xml version tags, and of course my output method is xml and indent="yes" )

UPDATE:
when I have the second "WHEN", (in case there is no chair_1) I want to "paste" it into the code. But the indentation fails, it makes the whole copy into one line. What could be the problem?

答:
The templates you present do not effect the transformation you say they do, at least not by themselves.  In fact, they are not even valid XSL.

After the obvious syntax errors are corrected, the resulting template matching node() explicitly rearranges whitespace around elements (where it is not stripped) and does nothing effective at preserving attributes.  You seem to intend for it to be an identity transform, but the conventional identity transform goes like this:

```<code><xsl:template match="node()|@*">
  <xsl:copy>
    <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
</xsl:template>
</code>```

Observe in particular that the node() test matches both elements and text nodes (and comments and processing instructions), but not attributes, and that if you do not want to rearrange an element's text nodes relative to its child elements then you must transform them all via the same xsl:apply-templates directive.

Additionally, do note that in many XML applications, whitespace-only runs of text separating tags are insignificant.  I don't see any reason to think that your particular application is among the exceptions, so you really ought to ask yourself is "does it matter?"

Supposing that it does matter -- e.g. because you want improved human readability even though the XML is primarily meant to be consumed by a computer program that doesn't care about the indentation -- you should consider letting your XSL processor provide indentation for you.  To do this, start by stripping all the insignificant whitespace from the input document:

```<code><xsl:strip-space elements="*"/>
</code>```

and follow up by asking the processor to provide hierarchical indentation for you:

```<code><xsl:output method="xml" indent="yes" omit-xml-declaration="yes" />
</code>```

Both of those directives have global effect, and they need to appear as direct children of the xsl:stylesheet or xsl:transform element.  Here's the cleaned up and updated version:

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

  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="/items/kitchen/furnitures/chairs">
    <xsl:choose>
      <xsl:when test="chair_1">
        <xsl:copy>
          <!-- also simplified the 'select' expression below: -->
          <xsl:apply-templates select="node()[not(self::chair_1)]|@*"/>
        </xsl:copy>
        <xsl:apply-templates select="chair_1"/>
      </xsl:when>
      <xsl:otherwise>
        BUNCH of code there if we don't have chair_1
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

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

Title: Xslt - Move node to one "level" up

Body:
I want an xml attribute one level up in an xml structure.
As for requested I show a more detailed example:

<items>
  <kitchen>
    <furnitures>
      <chairs type="wood">
        <chair_1 color="green" legs="4"/>
      </chairs>
      <tables type="stone">
      </tables>
    </furnitures>
  </kitchen>
</items>

And I want to output this:

<items>
  <kitchen>
    <furnitures>
      <chairs type="wood"/>
      <chair_1 color="green" legs="4"/>
      <tables type="stone">
      </tables>
    </furnitures>
  </kitchen>
</items>

As you see I move char_1 to under  from under

<xsl:template match="node()">
  <xls:copy>
    <xsl:apply-templates select="@*"/>
    <xsl:apply-templates select="*"/>
    <xsl:apply-templates select="text()">
  </xsl:copy>
</xsl:template>

<xsl:template match="/items/kitchen/furnitures/chairs">
  <xsl:choose>
    <xsl:when test="chair_1">
      <xsl:copy>
      <xsl:apply-templates select="child::node()[not(self:chair_1)]|@*|text()"/>
      </xsl:copy>
    <xsl:apply-templates select="chair_1"/>
    </xsl:when>

      <xsl:otherwise>
        <xsl:copy>
          <xls:apply-templates select ="@*|node()"/>
        </xsl:copy>
       <xsl:apply-templates select="settings"/>
       <xsl:text>
       </xsl:text>
       <chair_1 color="green" legs="4"/>
    </xls:otherwise>
  </xls:choose>
</xsl:template>

So, my main problem is, that my copy don't contain line-breaks.
Please keep in mind, I am using PHP:Xsltproc, on my dev-comp the indentation works fine, but with PHP's xsltproc it isn't fine, and drops the line breaks.
so the output like this:

<items>
  <kitchen>
    <furnitures>
      <chairs type="wood"/><chair_1 color="green" legs="4"/>
      <tables type="stone">
      </tables>
    </furnitures>
  </kitchen>
</items>

Which is fine, but not correctly indented.
(Disclaimer: there could be some typos, as this is not the original XML, and of course I am using the required stylsheet, version, phpversion, xml version tags, and of course my output method is xml and indent="yes" )

UPDATE:
when I have the second "WHEN", (in case there is no chair_1) I want to "paste" it into the code. But the indentation fails, it makes the whole copy into one line. What could be the problem?

Body:
The templates you present do not effect the transformation you say they do, at least not by themselves.  In fact, they are not even valid XSL.

After the obvious syntax errors are corrected, the resulting template matching node() explicitly rearranges whitespace around elements (where it is not stripped) and does nothing effective at preserving attributes.  You seem to intend for it to be an identity transform, but the conventional identity transform goes like this:

<xsl:template match="node()|@*">
  <xsl:copy>
    <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
</xsl:template>

Observe in particular that the node() test matches both elements and text nodes (and comments and processing instructions), but not attributes, and that if you do not want to rearrange an element's text nodes relative to its child elements then you must transform them all via the same xsl:apply-templates directive.

Additionally, do note that in many XML applications, whitespace-only runs of text separating tags are insignificant.  I don't see any reason to think that your particular application is among the exceptions, so you really ought to ask yourself is "does it matter?"

Supposing that it does matter -- e.g. because you want improved human readability even though the XML is primarily meant to be consumed by a computer program that doesn't care about the indentation -- you should consider letting your XSL processor provide indentation for you.  To do this, start by stripping all the insignificant whitespace from the input document:

<xsl:strip-space elements="*"/>

and follow up by asking the processor to provide hierarchical indentation for you:

<xsl:output method="xml" indent="yes" omit-xml-declaration="yes" />

Both of those directives have global effect, and they need to appear as direct children of the xsl:stylesheet or xsl:transform element.  Here's the cleaned up and updated version:

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

  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="/items/kitchen/furnitures/chairs">
    <xsl:choose>
      <xsl:when test="chair_1">
        <xsl:copy>
          <!-- also simplified the 'select' expression below: -->
          <xsl:apply-templates select="node()[not(self::chair_1)]|@*"/>
        </xsl:copy>
        <xsl:apply-templates select="chair_1"/>
      </xsl:when>
      <xsl:otherwise>
        BUNCH of code there if we don't have chair_1
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>


问:
Post request in VueJs with undefined response
I am a beginner in VueJs and Expressjs. I am trying to make frontend side by Vuejs and backend by ExpressJs. I send a post request to the backend (expressJs) and :

1- Response is undefined
2- At the same time I can see 2 requests in chrome development tools. One is Option and another one is Post.
3- With postman there is no problem at all.

Here is the code of app.js in express

console.log('Server is running')

const express = require('express'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    morgan = require('morgan');

app = new express();

//Setup middleware
app.use(cors());
app.use(morgan('combined'))
app.use(bodyParser.json())

app.post('/register', (req, res, next) => {
    res.send({
        message: `Hello ${req.body.email}! your user was registered!`
    })
});

app.listen(8081);```
</div>
</div>
</p>

<p>And here is the code in VueJs :</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-js lang-js prettyprint-override"><code>// Api Setting

import axios from 'axios'

export const HTTP = axios.create({
    baseURL: `http://localhost:8081`
  });

// AuthenticationService

import { HTTP } from '../services/Api'

export default {

  register(credentials) {
     HTTP.post('register', credentials);
  }
}

// Register Component
export default {
  data() {
    return {
      email: '',
      password: ''
    };
  },
  methods: {

   async register() {
        const response = await AuthenticationService.register({
        email: this.email,
        password: this.password
      });

      console.log(response);  // the value is undefined
    }
  }
};</code>```

I really don't know what I missed here that I get an undefined response and 2 requests at the same time. I appreciate any hint.

Whole code on github repo  : here

答:
Maybe. Authentication.register is not returning anything or more specifically a Promise which should be used to populate const response in the await call.

Try returning something like so: return HTTP.post('register', credentials); inside register.

For this to work though, HTTP.post('register', credentials) should also return something.

Body:
I am a beginner in VueJs and Expressjs. I am trying to make frontend side by Vuejs and backend by ExpressJs. I send a post request to the backend (expressJs) and :

1- Response is undefined
2- At the same time I can see 2 requests in chrome development tools. One is Option and another one is Post.
3- With postman there is no problem at all.

Here is the code of app.js in express

console.log('Server is running')

const express = require('express'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    morgan = require('morgan');

app = new express();

//Setup middleware
app.use(cors());
app.use(morgan('combined'))
app.use(bodyParser.json())

app.post('/register', (req, res, next) => {
    res.send({
        message: `Hello ${req.body.email}! your user was registered!`
    })
});

app.listen(8081);

And here is the code in VueJs :

// Api Setting

import axios from 'axios'

export const HTTP = axios.create({
    baseURL: `http://localhost:8081`
  });

// AuthenticationService

import { HTTP } from '../services/Api'

export default {

  register(credentials) {
     HTTP.post('register', credentials);
  }
}

// Register Component
export default {
  data() {
    return {
      email: '',
      password: ''
    };
  },
  methods: {

   async register() {
        const response = await AuthenticationService.register({
        email: this.email,
        password: this.password
      });

      console.log(response);  // the value is undefined
    }
  }
};

I really don't know what I missed here that I get an undefined response and 2 requests at the same time. I appreciate any hint.

Whole code on github repo  : here


问:
CombineReducers with Typescript returns error "Argument of type is not assignable to parameter of type 'ReducersMapObject'"
I'm trying to setup a front-end environment with react + redux + typescript, but I am struggling to get it work with combineReducers.
I get an error: Argument of type is not assignable to parameter of type 'ReducersMapObject'. See the full error message below the code.

STATE: (types/index.tsx)

```<code>export namespace StoreState {

  export type Enthusiasm = {
    languageName: string;
    enthusiasmLevel: number;
  }

  export type All = {
    enthusiasm: Enthusiasm
  }
}
</code>```

STORE: (store.tsx)

```<code>import { createStore } from 'redux';
import reducers from './reducers/index';
import { StoreState } from './types/index';

let devtools: any = window['devToolsExtension'] ? window['devToolsExtension']() : (f:any)=>f;

const Store = createStore<StoreState.All>(reducers, devtools);
export default Store;
</code>```

REDUCER: (/reducers/HelloReducer.tsx)

```<code>    import { EnthusiasmAction } from '../actions';
    import { StoreState } from '../types/index';
    import { INCREMENT_ENTHUSIASM, DECREMENT_ENTHUSIASM } from '../constants/index';

    export const enthusiasm = (state: StoreState.Enthusiasm,
action: EnthusiasmAction): StoreState.Enthusiasm => {
      switch (action.type) {
        case INCREMENT_ENTHUSIASM:
            return { ...state, enthusiasmLevel: state.enthusiasmLevel + 1 };
        case DECREMENT_ENTHUSIASM:
            return { ...state, enthusiasmLevel: Math.max(1, state.enthusiasmLevel - 1) };
        default:
            return state;
     }
   }
</code>```

COMBINE REDUCERS (/reducers/index.tsx)

```<code>import { StoreState } from '../types/index';
import * as enthusiasmReducer from './HelloReducer';

import { combineReducers } from 'redux';

const reducer = combineReducers<StoreState.All>({
    enthusiasm: enthusiasmReducer
});

export default reducer;
</code>```

答:
You're passing the object with all of HelloReducer's exports instead of just the reducer. There's a couple of ways to fix it. You can select the reducer:

```<code>const reducer = combineReducers<StoreState.All>({
    enthusiasm: enthusiasmReducer.enthusiasm
});
</code>```

or import only the reducer:

```<code>import {enthusiasm} from './HelloReducer';
..
const reducer = combineReducers({enthusiasm});
</code>```

or add export default enthusiasm; to HelloReducer.tsx and change the import to

```<code>import enthusiasmReducer from './HelloReducer';
</code>```

Body:
I'm trying to setup a front-end environment with react + redux + typescript, but I am struggling to get it work with combineReducers.
I get an error: Argument of type is not assignable to parameter of type 'ReducersMapObject'. See the full error message below the code.

STATE: (types/index.tsx)

export namespace StoreState {

  export type Enthusiasm = {
    languageName: string;
    enthusiasmLevel: number;
  }

  export type All = {
    enthusiasm: Enthusiasm
  }
}

STORE: (store.tsx)

import { createStore } from 'redux';
import reducers from './reducers/index';
import { StoreState } from './types/index';

let devtools: any = window['devToolsExtension'] ? window['devToolsExtension']() : (f:any)=>f;

const Store = createStore<StoreState.All>(reducers, devtools);
export default Store;

REDUCER: (/reducers/HelloReducer.tsx)

    import { EnthusiasmAction } from '../actions';
    import { StoreState } from '../types/index';
    import { INCREMENT_ENTHUSIASM, DECREMENT_ENTHUSIASM } from '../constants/index';

    export const enthusiasm = (state: StoreState.Enthusiasm,
action: EnthusiasmAction): StoreState.Enthusiasm => {
      switch (action.type) {
        case INCREMENT_ENTHUSIASM:
            return { ...state, enthusiasmLevel: state.enthusiasmLevel + 1 };
        case DECREMENT_ENTHUSIASM:
            return { ...state, enthusiasmLevel: Math.max(1, state.enthusiasmLevel - 1) };
        default:
            return state;
     }
   }

COMBINE REDUCERS (/reducers/index.tsx)

import { StoreState } from '../types/index';
import * as enthusiasmReducer from './HelloReducer';

import { combineReducers } from 'redux';

const reducer = combineReducers<StoreState.All>({
    enthusiasm: enthusiasmReducer
});

export default reducer;

Body:
You're passing the object with all of HelloReducer's exports instead of just the reducer. There's a couple of ways to fix it. You can select the reducer:

const reducer = combineReducers<StoreState.All>({
    enthusiasm: enthusiasmReducer.enthusiasm
});

or import only the reducer:

import {enthusiasm} from './HelloReducer';
..
const reducer = combineReducers({enthusiasm});

or add export default enthusiasm; to HelloReducer.tsx and change the import to

import enthusiasmReducer from './HelloReducer';


问:
Lost connection to MySQL server at 'handshake: waiting for inital communication packet', system error: 138
Anyone knows what this error can be?
It happens when I try to connect to an instance.
MySQL is on.

Thank you very much.

答:
Make sure that your firewall is not blocking anything regarding MySQL. Try to do what you are doing by shutting down your antivirus for 5 minutes. It can simply be your firewall.
To interpret the error you are getting, it simply means that your MySQL client not getting to connect to the MySQL server engine.

Another possibility:
Open your mySQL Client and verify that it si set to use the default port number which is 3306. Another thing to lookup would be the bind-address in my.cnf.  Set it with the following bind-address = 0.0.0.0 in mysql/my.cnf


问:
Using Javascript to play sounds on buttons
Hi I want to use click to play audio I managed to use Javascript for playing one audio but I need for playing different audios on clicking a particular button.

I am able to play first one but the second one is also playing same audio. I am new in Javascript

function play() {
  var audio = document.getElementById("sound1");
  audio.play();
}

function play2() {
  var audio2 = document.getElementById("sound2");
  audio.play();
}
```

<pre class="lang-html prettyprint-override"><code><audio id="sound1" src="https://feeds.soundcloud.com/stream/303404685-hopperkremer-w1-1.mp3"></audio>
<audio id="sound2" src="http://feeds.soundcloud.com/stream/303404681-hopperkremer-w4-1.mp3"></audio>

<input type="button" value="play" onclick="play()">
<input type="button" value="play2" onclick="play()">
</code>```

(codepen)

答:
Change to this:

```<code><input type="button" value="play" onclick="play()">
<input type="button" value="play2" onclick="play2()">
</code>```

Also change audio.play() to audio2.play():

```<code>function play() {
  var audio = document.getElementById("sound1");
  audio.play();
}

function play2() {
  var audio2 = document.getElementById("sound2");
  audio2.play();
}
</code>```

Body:
Hi I want to use click to play audio I managed to use Javascript for playing one audio but I need for playing different audios on clicking a particular button.

I am able to play first one but the second one is also playing same audio. I am new in Javascript

function play() {
  var audio = document.getElementById("sound1");
  audio.play();
}

function play2() {
  var audio2 = document.getElementById("sound2");
  audio.play();
}

<audio id="sound1" src="https://feeds.soundcloud.com/stream/303404685-hopperkremer-w1-1.mp3"></audio>
<audio id="sound2" src="http://feeds.soundcloud.com/stream/303404681-hopperkremer-w4-1.mp3"></audio>

<input type="button" value="play" onclick="play()">
<input type="button" value="play2" onclick="play()">

(codepen)

Body:
Change to this:

<input type="button" value="play" onclick="play()">
<input type="button" value="play2" onclick="play2()">

Also change audio.play() to audio2.play():

function play() {
  var audio = document.getElementById("sound1");
  audio.play();
}

function play2() {
  var audio2 = document.getElementById("sound2");
  audio2.play();
}


问:
Jstack fails after two weeks of normal work
I have dockerized tomcat 7.0.73 based on java:7-jdk docker image.

I have a job that every 5 minutes does thread dump with command jstack 1. It works for about two weeks normally and after that crashes with message:

Unable to open socket file: target process not responding or HotSpot VM not loaded. The -F option can be used when the target process is not responding
Exit code is 1.

What can be the cause of this behavior?

JVM keeps working okay. Space looks correct too.

java -version
java version "1.7.0_111"
OpenJDK Runtime Environment (IcedTea 2.6.7) (7u111-2.6.7-2~deb8u1)
OpenJDK 64-Bit Server VM (build 24.111-b01, mixed mode)

Filesystem                     Size  Used Avail Use% Mounted on
/dev/mapper/docker-202:1-xxx   10G 1013M  9.1G  10% /
tmpfs                          3.9G     0  3.9G   0% /dev
tmpfs                          3.9G     0  3.9G   0% /sys/fs/cgroup
/dev/xvda1                     99G   68G   31G  69% /tmp
shm                            64M     0   64M   0% /dev/shm

答: I suspect that a process may be clearing out old files in /tmp, and it's taking the relevant /tmp/.java_pid socket file with it (which is required by utilities such as jstack.) Next time it happens look to see if the relevant file is still there - if not, then that's your issue.


问:
Bash/sed: No such file or directory
I have a script called script.sh:

```<code>FILE=$1
sed -i.bak "s|needle|pin|g" $FILE
</code>```

If I run it like this:

```<code>bash ./script.sh /var/www/path/to/file
</code>```

I get this response:

```<code>: No such file or directoryth/to/file
</code>```

If I run sed by itself, passing in the same path:

```<code>sed -i.bak "s|needle|pin|g" "/var/www/path/to/file"
</code>```

It works fine (even substituting the values correctly).

What am I doing wrong?

Bonus observation: I'm assuming it's telling me the entry path is wrong but it's hard to tell because it says ": No such file or directoryth/to/file", which indicates to me that something else is wrong. Maybe something carriage-return related?

答:
there must have some unprintable control character in your path string variable, you could print the content of it with declare -p:

```<code>FILE=$1
declare -p FILE
</code>```

Title: Bash/sed: No such file or directory

Body:
I have a script called script.sh:

FILE=$1
sed -i.bak "s|needle|pin|g" $FILE

If I run it like this:

bash ./script.sh /var/www/path/to/file

I get this response:

: No such file or directoryth/to/file

If I run sed by itself, passing in the same path:

sed -i.bak "s|needle|pin|g" "/var/www/path/to/file"

It works fine (even substituting the values correctly).

What am I doing wrong?

Bonus observation: I'm assuming it's telling me the entry path is wrong but it's hard to tell because it says ": No such file or directoryth/to/file", which indicates to me that something else is wrong. Maybe something carriage-return related?

Body:
there must have some unprintable control character in your path string variable, you could print the content of it with declare -p:

FILE=$1
declare -p FILE


问:
Can I combine private publishers and public subscribers?
Is it possible to configure Google Cloud Pub/Sub so that you can have any number of anonymous subscribers to a topic reading messages while the content of the published messages is controlled by an authorized publisher with an account on Google Cloud?

For example, let's say I'm building an application that publishes GOOG stock ticker price every second. I want anyone on the internet to be able to subscribe to my application to get the stock price. However, no applications except my own should be allowed to publish the price. I need to understand if this is possible.

答:
It is possible to setup this kind of message distribution scenario using Google Cloud Identity and Access Management (IAM). Once the topic is created (e.g. /topics/goog), the topic needs to be setup with IAM roles/pubsub.publisher permission for your application's account. This can also be a IAM service account for your application.

Next, you will need to create a subscription for the /topics/goog topic (e.g. /subscriptions/goog) and configure the IAM permissions for the subscription. You should give IAM allUsers permission to the /subscriptions/goog topic.

Once this configuration is setup, then only the authorized account will be allowed to publish to /topics/goog and any internet connected user will be allowed to pull messages from /subscriptions/goog


问:
Acestramengine issue - related with __m2crypto
I have Arch linux. When I try to open acestreamengine, I got this error:

```<code>$ sudo acestreamengine --client-console
2017-07-15 10:36:06,535|MainThread|acestream|error during startup
Traceback (most recent call last):
   File "core.c", line 1590, in
   File "core.c", line 144, in
   File "core.c", line 2, in

ImportError: cannot import name __m2crypto
</code>```

Currently I have version m2crypto-26-0

Someone can help me? I can not start the engine.
Thanks
Best regards.

答:
Try to use an earlier version of M2Crypto.
Version 0.23 works just fine.
I'm using Slackware 14.2</p>

Body:
I have Arch linux. When I try to open acestreamengine, I got this error:

$ sudo acestreamengine --client-console
2017-07-15 10:36:06,535|MainThread|acestream|error during startup
Traceback (most recent call last):
   File "core.c", line 1590, in
   File "core.c", line 144, in
   File "core.c", line 2, in

ImportError: cannot import name __m2crypto

Currently I have version m2crypto-26-0

Someone can help me? I can not start the engine.
Thanks
Best regards.


问:
Error:Some file crunching failed, see logs for details afer update gradle
Afer update gradle version to classpath 'com.android.tools.build:gradle:2.3.0' I got this error.

```<code>Error:Some file crunching failed, see logs for details
Error:Execution failed for task ':app:mergeDebugResources'.
> Error: Some file crunching failed, see logs for details

AAPT err(Facade for 596378712): \\?\C:\Users\Я\.android\build-cache\2fe51ff37440fab8f5f875609a799aebf31c9e02\output\res\drawable-xxxhdpi-v4\abc_ic_menu_share_mtrl_alpha.png ERROR: Unable to open PNG file
AAPT err(Facade for 596378712): \\?\C:\Users\Я\.android\build-cache\2fe51ff37440fab8f5f875609a799aebf31c9e02\output\res\drawable-xxxhdpi-v4\abc_tab_indicator_mtrl_alpha.9.png ERROR: Unable to open PNG file
AAPT err(Facade for 596378712): \\?\C:\Users\Я\.android\build-cache\2fe51ff37440fab8f5f875609a799aebf31c9e02\output\res\drawable-hdpi-v4\abc_btn_radio_to_on_mtrl_015.png ERROR: Unable to open PNG file
</code>```

I'm not using 9.png files. How can I fix it?

答:
The problem is related to 1 corrupted image file in drawable.
I changed it and the problem was solved very quickly.
The answer is very simple, but the error message is rather ambiguous.
I changed the gradle and android studio, but the solution was very simple than what I thought.

Body:
Afer update gradle version to classpath 'com.android.tools.build:gradle:2.3.0' I got this error.

Error:Some file crunching failed, see logs for details
Error:Execution failed for task ':app:mergeDebugResources'.
> Error: Some file crunching failed, see logs for details

AAPT err(Facade for 596378712): \\?\C:\Users\Я\.android\build-cache\2fe51ff37440fab8f5f875609a799aebf31c9e02\output\res\drawable-xxxhdpi-v4\abc_ic_menu_share_mtrl_alpha.png ERROR: Unable to open PNG file
AAPT err(Facade for 596378712): \\?\C:\Users\Я\.android\build-cache\2fe51ff37440fab8f5f875609a799aebf31c9e02\output\res\drawable-xxxhdpi-v4\abc_tab_indicator_mtrl_alpha.9.png ERROR: Unable to open PNG file
AAPT err(Facade for 596378712): \\?\C:\Users\Я\.android\build-cache\2fe51ff37440fab8f5f875609a799aebf31c9e02\output\res\drawable-hdpi-v4\abc_btn_radio_to_on_mtrl_015.png ERROR: Unable to open PNG file

I'm not using 9.png files. How can I fix it?


问:
MySQL LEFT JOIN 2 queries from different databases
I have 2 separate MySQL queries, each working with a different database, from the same server.

query using database1:

```<code>$result1 = mysqli_query($db_connection1, "
SELECT p.id, p.identifier, u.star_total FROM pages AS p
    LEFT JOIN (
        SELECT page_id, AVG(rating) star_total FROM (
            SELECT page_id, rating FROM comments WHERE comments.is_approved = '1' AND comments.rating != '0'
            UNION ALL
            SELECT page_id, rating FROM ratings) d
            GROUP BY page_id
    ) AS u ON p.id = u.id
");
</code>```

query using database2:

```<code>$result2 = mysqli_query($db_connection2, "
SELECT
    cas.id, cas.casino,
    t2.amount, t2.match,
    t3.bonus_id, t3.bonus_type
FROM (SELECT * FROM casinos $query) AS cas
LEFT JOIN (
        bonus AS t2
    INNER JOIN
        bonus_type_lookup AS t3 ON t2.bonus_type = t3.bonus_id
)
ON cas.id = t2.id AND t2.bonus_type = '$bonus_typeNo'
AND (
    t2.amount = (
        SELECT
            CASE WHEN MAX(t2.amount) > MAX(t2.match) OR (MAX(t2.match) IS NULL) THEN MAX(t2.amount)
            ELSE MAX(t2.match)
            END
        FROM bonus AS t2
        WHERE cas.id = t2.id AND t2.bonus_type = '$bonus_typeNo'
    )
    OR t2.match = (
        SELECT
            CASE WHEN MAX(t2.amount) > MAX(t2.match)
            THEN MAX(t2.amount)
            ELSE MAX(t2.match)
            END
        FROM bonus AS t2
        WHERE cas.id = t2.id AND t2.bonus_type = '$bonus_typeNo'
    )
)
ORDER BY $order_by $order $limit
");
</code>```

Both queries work fine by themselves. Now I want to LEFT JOIN those 2 queries. My current attempt (see below) produces this error: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given, which referes to this line: $numrows = mysqli_num_rows($result);

```<code>$result = mysqli_query($db_connection2, "
SELECT
    cas.id, cas.casino,
    t2.amount, t2.match,
    t3.bonus_id, t3.bonus_type,
    **j.identifier, j.star_total**
FROM (SELECT * FROM database2.casinos $query) AS cas
LEFT JOIN (
        database2.bonus AS t2
    INNER JOIN
        database2.bonus_type_lookup AS t3 ON t2.bonus_type = t3.bonus_id
)
ON cas.id = t2.id AND t2.bonus_type = '$bonus_typeNo'
AND (
    t2.amount = (
        SELECT
            CASE WHEN MAX(t2.amount) > MAX(t2.match) OR (MAX(t2.match) IS NULL) THEN MAX(t2.amount)
            ELSE MAX(t2.match)
            END
        FROM database2.bonus AS t2
        WHERE cas.id = t2.id AND t2.bonus_type = '$bonus_typeNo'
    )
    OR t2.match = (
        SELECT
            CASE WHEN MAX(t2.amount) > MAX(t2.match)
            THEN MAX(t2.amount)
            ELSE MAX(t2.match)
            END
        FROM database2.bonus AS t2
        WHERE cas.id = t2.id AND t2.bonus_type = '$bonus_typeNo'
    )
)

LEFT JOIN (
    SELECT
        p.id,
        p.identifier,
        q.star_total
    FROM database1.pages p
    LEFT JOIN (
        SELECT
            t.page_id,
            AVG(t.rating) star_total
        FROM (
            SELECT
                c.page_id AS page_id,
                c.rating AS rating
            FROM database1.comments c
            WHERE c.is_approved = '1' AND c.rating != '0'
            UNION ALL
            SELECT
                r.page_id AS page_id,
                r.rating AS rating
            FROM database1.ratings r
        ) t
        GROUP BY t.page_id
    ) q ON q.page_id = p.id
) **j ON cas.id = j.identifier**

ORDER BY $order_by $order $limit
");
$numrows = mysqli_num_rows($result);
</code>```

I am not sure whether the error arises from the wrong usage of LEFT JOIN or if this is a database problem, or both. "$db_connection2" uses database2. Not sure at what stage it connects to database1, and how it gets the connection details that enable it to connect to database1. I tried to use fully qualified names for each table and database, but no success.

Any help would be great. Thank you in advance!

答:
You got this error message:

Every derived table must have its own alias

The error message means that using a subquery in the FROM clause requires that you give the subquery a table alias:

```<code>SELECT ... FROM ( ...subquery...) AS t1 ...
</code>```

This is so you can reference columns of the subquery like t1.column1.

It's documented here:
https://dev.mysql.com/doc/refman/5.7/en/derived-tables.html

The [AS] tbl_name clause is mandatory because every table in a FROM clause must have a name.

Body:
I have 2 separate MySQL queries, each working with a different database, from the same server.

query using database1:

$result1 = mysqli_query($db_connection1, "
SELECT p.id, p.identifier, u.star_total FROM pages AS p
    LEFT JOIN (
        SELECT page_id, AVG(rating) star_total FROM (
            SELECT page_id, rating FROM comments WHERE comments.is_approved = '1' AND comments.rating != '0'
            UNION ALL
            SELECT page_id, rating FROM ratings) d
            GROUP BY page_id
    ) AS u ON p.id = u.id
");

query using database2:

$result2 = mysqli_query($db_connection2, "
SELECT
    cas.id, cas.casino,
    t2.amount, t2.match,
    t3.bonus_id, t3.bonus_type
FROM (SELECT * FROM casinos $query) AS cas
LEFT JOIN (
        bonus AS t2
    INNER JOIN
        bonus_type_lookup AS t3 ON t2.bonus_type = t3.bonus_id
)
ON cas.id = t2.id AND t2.bonus_type = '$bonus_typeNo'
AND (
    t2.amount = (
        SELECT
            CASE WHEN MAX(t2.amount) > MAX(t2.match) OR (MAX(t2.match) IS NULL) THEN MAX(t2.amount)
            ELSE MAX(t2.match)
            END
        FROM bonus AS t2
        WHERE cas.id = t2.id AND t2.bonus_type = '$bonus_typeNo'
    )
    OR t2.match = (
        SELECT
            CASE WHEN MAX(t2.amount) > MAX(t2.match)
            THEN MAX(t2.amount)
            ELSE MAX(t2.match)
            END
        FROM bonus AS t2
        WHERE cas.id = t2.id AND t2.bonus_type = '$bonus_typeNo'
    )
)
ORDER BY $order_by $order $limit
");

Both queries work fine by themselves. Now I want to LEFT JOIN those 2 queries. My current attempt (see below) produces this error: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given, which referes to this line: $numrows = mysqli_num_rows($result);

$result = mysqli_query($db_connection2, "
SELECT
    cas.id, cas.casino,
    t2.amount, t2.match,
    t3.bonus_id, t3.bonus_type,
    **j.identifier, j.star_total**
FROM (SELECT * FROM database2.casinos $query) AS cas
LEFT JOIN (
        database2.bonus AS t2
    INNER JOIN
        database2.bonus_type_lookup AS t3 ON t2.bonus_type = t3.bonus_id
)
ON cas.id = t2.id AND t2.bonus_type = '$bonus_typeNo'
AND (
    t2.amount = (
        SELECT
            CASE WHEN MAX(t2.amount) > MAX(t2.match) OR (MAX(t2.match) IS NULL) THEN MAX(t2.amount)
            ELSE MAX(t2.match)
            END
        FROM database2.bonus AS t2
        WHERE cas.id = t2.id AND t2.bonus_type = '$bonus_typeNo'
    )
    OR t2.match = (
        SELECT
            CASE WHEN MAX(t2.amount) > MAX(t2.match)
            THEN MAX(t2.amount)
            ELSE MAX(t2.match)
            END
        FROM database2.bonus AS t2
        WHERE cas.id = t2.id AND t2.bonus_type = '$bonus_typeNo'
    )
)

LEFT JOIN (
    SELECT
        p.id,
        p.identifier,
        q.star_total
    FROM database1.pages p
    LEFT JOIN (
        SELECT
            t.page_id,
            AVG(t.rating) star_total
        FROM (
            SELECT
                c.page_id AS page_id,
                c.rating AS rating
            FROM database1.comments c
            WHERE c.is_approved = '1' AND c.rating != '0'
            UNION ALL
            SELECT
                r.page_id AS page_id,
                r.rating AS rating
            FROM database1.ratings r
        ) t
        GROUP BY t.page_id
    ) q ON q.page_id = p.id
) **j ON cas.id = j.identifier**

ORDER BY $order_by $order $limit
");
$numrows = mysqli_num_rows($result);

I am not sure whether the error arises from the wrong usage of LEFT JOIN or if this is a database problem, or both. "$db_connection2" uses database2. Not sure at what stage it connects to database1, and how it gets the connection details that enable it to connect to database1. I tried to use fully qualified names for each table and database, but no success.

Any help would be great. Thank you in advance!

Body:
You got this error message:

Every derived table must have its own alias

The error message means that using a subquery in the FROM clause requires that you give the subquery a table alias:

SELECT ... FROM ( ...subquery...) AS t1 ...

This is so you can reference columns of the subquery like t1.column1.

It's documented here:
https://dev.mysql.com/doc/refman/5.7/en/derived-tables.html

The [AS] tbl_name clause is mandatory because every table in a FROM clause must have a name.


问:
Elixir Get Map containing maximum values of specific field
I'm a beginner in Elixir programming language.

I have an object something like this:

```<code>{
  id: uuid,
  created_at: DateTime.t,
  updated_at: DateTime.t,
  type: my_type
}
</code>```

let's say my_type is one of ~w[A B C D]

I want to write a function which takes a list of these objects and returns a following map:

```<code>%{
  A: 120,
  B: 220,
  C: 560,
  D: 0,
  any: 560
}
</code>```

The values here has to be the MAXIMUM difference between updated_at and created_at columns(Timex.diff(updated_at, created_at, :seconds)) per my_type + any in addition.
In case of any the my_type is not considered and takes the maximum among all objects in the list.

What is the best way to do it in Elixir? Thanks.

答:
The following will group the list by its type, then calculate the max difference for each group, and finally result in a map containing each type as the key and max difference as the value.

```<code>map = list
|> Enum.group_by(& &1.type)
|> Enum.map(fn {type, values} ->
  max =
    values
    |> Enum.map(fn %{created_at: created_at, updated_at: updated_at} ->
      # return the difference here
    end)
    |> Enum.max
  {type, max}
end)
|> Map.new
</code>```

This should give you something like:

```<code>%{
  A: 120,
  B: 220,
  C: 560,
  D: 0
}
</code>```

You can calculate the value for any now by doing map |> Map.values |> Enum.max.

Body:
I'm a beginner in Elixir programming language.

I have an object something like this:

{
  id: uuid,
  created_at: DateTime.t,
  updated_at: DateTime.t,
  type: my_type
}

let's say my_type is one of ~w[A B C D]

I want to write a function which takes a list of these objects and returns a following map:

%{
  A: 120,
  B: 220,
  C: 560,
  D: 0,
  any: 560
}

The values here has to be the MAXIMUM difference between updated_at and created_at columns(Timex.diff(updated_at, created_at, :seconds)) per my_type + any in addition.
In case of any the my_type is not considered and takes the maximum among all objects in the list.

What is the best way to do it in Elixir? Thanks.

Body:
The following will group the list by its type, then calculate the max difference for each group, and finally result in a map containing each type as the key and max difference as the value.

map = list
|> Enum.group_by(& &1.type)
|> Enum.map(fn {type, values} ->
  max =
    values
    |> Enum.map(fn %{created_at: created_at, updated_at: updated_at} ->
      # return the difference here
    end)
    |> Enum.max
  {type, max}
end)
|> Map.new

This should give you something like:

%{
  A: 120,
  B: 220,
  C: 560,
  D: 0
}

You can calculate the value for any now by doing map |> Map.values |> Enum.max.


问:
Wait verify using "ExpectedConditions" does not work
UPDATED VERSION

I'm trying to find a more dynamic way to wait for elements instead of using static wait functions like Task.Event(2000).Wait();

The solution to this seems to be this:

```<code>WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
    wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[2]/div/input")));
</code>```

But when I use this function, the "ExpectedConditions" always lights up red indicating that it: "does not exist in the current context".

I've placed the function in one of my testcases:

(I am using C#/Visual Studios, Project type: Classlibrary)

```<code>using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

    namespace ClassLibrary1
    {
        public class MyFirstTest
        {
            IWebDriver driver = new FirefoxDriver();

            [Test]
            public void WaitverifyTest()
            {
                driver.Navigate().GoToUrl("https://www.google.se/");
                driver.Manage().Window.Maximize();

                Task.Delay(4000).Wait();

                driver.FindElement(By.XPath("//div[2]/div/input")).SendKeys("Selenium");

                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
                IWebElement element = wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[2]/div/input")));
                element.Click();

                driver.FindElement(By.XPath("//center/input")).Click();
            }
       }
   }
</code>```

(The xpath is a location type xpath, it is valid and works in both Selenium IDE and in Visual Studios.)

Anyone has any idea what I'm doing wrong?

I have two suspicions:

My version of selenium could be too new (3.6.0.0)

According to selenium.io , ExpectedCondition was last updated in 3.1.0. Maybe it is no longer vaild. Is there someway to check this?

Maybe my project type is not compatible with ExpectedCondition, and therefore does not recognize it?

答:
I don't understand this line:

```<code>IWebElement element = wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[2]/div/input")));
</code>```

How are you able to cast Until to an IWebElement since it returns bool? I might be missing something.

But you might be able to bypass the error if you don't use ExpectedConditions, like so:

```<code>wait().Until( foo => driver.FindElement(By.XPath("//div[2]/div/input")).Enabled);
</code>```

WebDriverWait takes as a parameter a function that returns a bool. You can create one within the parameters with the above code, that will return true when the element is enabled.

Body:
UPDATED VERSION

I'm trying to find a more dynamic way to wait for elements instead of using static wait functions like Task.Event(2000).Wait();

The solution to this seems to be this:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
    wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[2]/div/input")));

But when I use this function, the "ExpectedConditions" always lights up red indicating that it: "does not exist in the current context".

I've placed the function in one of my testcases:

(I am using C#/Visual Studios, Project type: Classlibrary)

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

    namespace ClassLibrary1
    {
        public class MyFirstTest
        {
            IWebDriver driver = new FirefoxDriver();

            [Test]
            public void WaitverifyTest()
            {
                driver.Navigate().GoToUrl("https://www.google.se/");
                driver.Manage().Window.Maximize();

                Task.Delay(4000).Wait();

                driver.FindElement(By.XPath("//div[2]/div/input")).SendKeys("Selenium");

                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
                IWebElement element = wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[2]/div/input")));
                element.Click();

                driver.FindElement(By.XPath("//center/input")).Click();
            }
       }
   }

(The xpath is a location type xpath, it is valid and works in both Selenium IDE and in Visual Studios.)

Anyone has any idea what I'm doing wrong?

I have two suspicions:

My version of selenium could be too new (3.6.0.0)

According to selenium.io , ExpectedCondition was last updated in 3.1.0. Maybe it is no longer vaild. Is there someway to check this?

Maybe my project type is not compatible with ExpectedCondition, and therefore does not recognize it?

Body:
I don't understand this line:

IWebElement element = wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[2]/div/input")));

How are you able to cast Until to an IWebElement since it returns bool? I might be missing something.

But you might be able to bypass the error if you don't use ExpectedConditions, like so:

wait().Until( foo => driver.FindElement(By.XPath("//div[2]/div/input")).Enabled);

WebDriverWait takes as a parameter a function that returns a bool. You can create one within the parameters with the above code, that will return true when the element is enabled.


问:
Changing the margin property on flex boxes
I am making a "rock, paper, sciccors"-game for a school project. So far, I have just done the html-part, and I am now working on the css-part, before I move on to javascript. Anyways, my problem is that I am trying to make captions underneath the four pictures I have put in, but the display: flex, and flex: 1 0 auto; tag - that I use to make spaces between words in the same p-tag - doesen't give me the wanted amount of pixels between the words. How do I customize the margin between the flex boxes?

body {
  background-color: #aa99ff;
  font-family: 'Exo 2', sans-serif;
}

img {
  border: 5px dotted black;
  margin: 10px;
  margin-bottom: 0;
}

.caption {
  margin-left: 10px;
  margin-top: 0;
  display: inline;
  flex: 1 0 auto;
}

p {
  margin-left: 10px;
}

#innpakning {
  width: 980px;
  height: 700px;
}

#tekst {
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?family=Exo+2" rel="stylesheet">

<div id="innpakning">
  <p id="spillerPoeng"> <b>Spiller:</b> 0 </p>
  <p id="maskinPoeng"> <b>Maskin:</b> 0 </p>
  <img src="stein.png"
  alt="spiller stein" id="stein" width="150" height="200">
  <img src="saks.png"
  alt="spiller saks" id="saks" width="150" height="200">
  <img src="papir.png"
  alt="spiller papir" id="papir" width="150" height="200">
  <img src="ukjent.png"
  alt="spiller stein" id="stein" width="150" height="200">
  <br>
  <div id="tekst">
    <p class="caption"> Stein</p>
    <p class="caption"> Saks</p>
    <p class="caption"> Papir</p>
    <p class="caption"> Maskin</p>
  </div>
  <p id="info"></p>
</div></code>```

答:
If you are open to changing your HTML, I would suggest wrapping each img and caption in a container.

example:

body {
  background-color: #aa99ff;
  font-family: 'Exo 2', sans-serif;
}

#innpakning {
  height: 700px;
}

.content {
  display: flex;
  padding-top: 15px;
}

.box:not(:last-of-type) {
  margin-right: 15px;
}

img {
  border: 5px dotted black;
}

.caption {
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?family=Exo+2" rel="stylesheet">

<div id="innpakning">
  <p id="spillerPoeng"> <b>Spiller:</b> 0 </p>
  <p id="maskinPoeng"> <b>Maskin:</b> 0 </p>
  <div class="content">
    <div class="box">
      <img src="stein.png" alt="spiller stein" id="stein" width="150" height="200">
      <p class="caption"> Stein</p>
    </div>
    <div class="box">
      <img src="stein.png" alt="spiller stein" id="stein" width="150" height="200">
      <p class="caption"> Stein</p>
    </div>
    <div class="box">
      <img src="stein.png" alt="spiller stein" id="stein" width="150" height="200">
      <p class="caption"> Stein</p>
    </div>
    <div class="box">
      <img src="stein.png" alt="spiller stein" id="stein" width="150" height="200">
      <p class="caption"> Stein</p>
    </div>
  </div>

  <p id="info"></p>
</div></code>```

Body:
I am making a "rock, paper, sciccors"-game for a school project. So far, I have just done the html-part, and I am now working on the css-part, before I move on to javascript. Anyways, my problem is that I am trying to make captions underneath the four pictures I have put in, but the display: flex, and flex: 1 0 auto; tag - that I use to make spaces between words in the same p-tag - doesen't give me the wanted amount of pixels between the words. How do I customize the margin between the flex boxes?

body {
  background-color: #aa99ff;
  font-family: 'Exo 2', sans-serif;
}

img {
  border: 5px dotted black;
  margin: 10px;
  margin-bottom: 0;
}

.caption {
  margin-left: 10px;
  margin-top: 0;
  display: inline;
  flex: 1 0 auto;
}

p {
  margin-left: 10px;
}

#innpakning {
  width: 980px;
  height: 700px;
}

#tekst {
  display: flex;
}

<link href="https://fonts.googleapis.com/css?family=Exo+2" rel="stylesheet">

 Spiller: 0

 Maskin: 0

 Stein

 Saks

 Papir

 Maskin

Body:
If you are open to changing your HTML, I would suggest wrapping each img and caption in a container.

example:

body {
  background-color: #aa99ff;
  font-family: 'Exo 2', sans-serif;
}

#innpakning {
  height: 700px;
}

.content {
  display: flex;
  padding-top: 15px;
}

.box:not(:last-of-type) {
  margin-right: 15px;
}

img {
  border: 5px dotted black;
}

.caption {
  margin: 0;
}

<link href="https://fonts.googleapis.com/css?family=Exo+2" rel="stylesheet">

<div id="innpakning">
  <p id="spillerPoeng"> <b>Spiller:</b> 0 </p>
  <p id="maskinPoeng"> <b>Maskin:</b> 0 </p>
  <div class="content">
    <div class="box">
      <img src="stein.png" alt="spiller stein" id="stein" width="150" height="200">
      <p class="caption"> Stein</p>
    </div>
    <div class="box">
      <img src="stein.png" alt="spiller stein" id="stein" width="150" height="200">
      <p class="caption"> Stein</p>
    </div>
    <div class="box">
      <img src="stein.png" alt="spiller stein" id="stein" width="150" height="200">
      <p class="caption"> Stein</p>
    </div>
    <div class="box">
      <img src="stein.png" alt="spiller stein" id="stein" width="150" height="200">
      <p class="caption"> Stein</p>
    </div>
  </div>

  <p id="info"></p>
</div>


问:
How can I handle new DB Versions? (not code first)
I am working on a C# winformsapp and I have an SQLite db that I access using Entity Framework. I am about to release v1.0 of the software.

My question is: when I am developing v1.1, I may need to add new fields to the database. Of course, I want users to be able to copy their data over from v1.0, but if they just copied over the database file, EF would surely give an exception when it tries to access the new fields that don't exist.

Do I have to create an 'Import database from v1.0' function that copies the data from the old database and inserts into the new database? I feel like this would take too long. Can I just create a function that modifies the old database directly, using EF or otherwise?

答:
Typically, the way I've done this...

Create a copy of your existing database. Make this your "dev" database

Change your database as needed and complete version 1.1 of your program, using this "dev" database.

When you are ready, use a database differencing tool, such as SqlDiff or SQL Compare, to create differencing scripts.

Backup your live database.

Run these differencing scripts against your live database. This should add your new fields, tables, views, etc, to the live database.

You're good to go


问:
how to plot histogram of maximum values of a dataframe
I have a dataframe with 3 columns df=["a", "b", "value"]. (Actually this is a snippet, the solution should be able to handle n variables, like "a", "b", "c", "d"...) In this case, the "value" column has been generated depending on the "a" and "b" value, doing something like:

```<code>        for a in range(1,10):
            for b in range (1,10):
                generate_value(a,b)
</code>```

The resulting data is similar to:

```<code>  a b value
0 1 1 0.23
1 1 2 6.34
2 1 3 0.25
3 1 4 2.17
4 1 5 5.97
[...]
</code>```

I want to know the statistical better combinations of "a" and "b" that gives me the bigger "value". So I want to draw some kind of histogram that shows me which values of "a" and "b" statistically generates bigger "value". I tried with something like:

```<code>fig = plot.figure()
ax=fig.add_subplot(111)
ax.hist(df["a"],bins=50, normed=True)
</code>```

or:

```<code> plot.plot(df["a"].values, df["value"].values, "o")
</code>```

But the results are not good. I think that I should use some kind of histogram or gauss bell curve, but I'm not sure how to plot it.

So, how to plot the statistically better "a" and "b" to get maximum "value"?

Note: the answer 1 is perfect for two variables a and b, but the problem is that the correct answer would need to work for multiple variables, a, b, c, d...

Edit 1: Please note that although I'm asking about two variables, the solution can't be to bound "a" to axis x and "b" to axis y, as there may be more variables. So if we have "a", "b", "c", "d", "e", the solution should be valid

Edit 2: Trying to explain it better: Lets take the following dataframe:

```<code>  a b c d value
0 1 6 9 7 0.23
1 5 2 3 5 11.34
2 6 7 8 4 0.25
3 1 4 9 3 2.17
4 1 5 9 1 4.97
5 6 6 4 7 25.9
6 3 5 5 2 10.37
7 1 5 1 2 7.87
8 2 5 3 3 8.12
9 1 5 2 1 2.97
10 7 5 4 9 5.97
11 3 5 2 3 9.92
[...]
</code>```

The row 5 clearly is the winner, with a 25.9 value, so the supposedly better values of a,b,c,d are: 6 6 4 7 . But we can see that statistically it is a strange result, it is the only one so high with those values of a,b,c,d, so it is very unlikely that we're going to get, in the future, a high value choosing those values for a,b,c,d. Instead, seems much more safe to choose numbers that have generated "value" between 8 and 11. Although a 8 to 11 gain is less than 25.9, the probability that the values of a,b,c,d (5,2,3,3) generate this higher "value" is bigger

Edit 3: Although a,b,c,d are discrete, the combination/order of them will generate different results. I mean, there is a function that will return a value inside a small range, like: value=func(a,b,c,d). That value will depend not only on the values of a,b,c,d, but also on some random things. So, for instance, func(5,2,3,5) could return a value of 11.34, but it also could return a similar value, like 10.8, 9.5 or something like that (a range value between 8 and 11). Also, func(1,6,9,7) will return 0.23, or it could return 2.7, but probably it won't return 10.1 as it is also very far from its range.

Following the the example, I'm trying to get the numbers that most probably will generate something in the range of 8-11 (well, the maximum). Probably the numbers I want to visualize somehow will be some kind of combination of numbers 3,5 and 2. But probably there won't be any 6,7,4 numbers, as they usually generate smaller "value" results

答:
This problem seems to be very complicated to solve it by one built-in function.

I think it should be solved in this way:

exclude outliers from data

select n largest values

summarize results with bar plot or any other

Clean data from outliers

We might choose any appropriate method for outliers detection e.g. 3*sigma, 1.5*IQR etc. I used 1.5*IQR in the example bellow.

```<code>cleaned_data = data[data['value'] < 1.5 * stats.iqr(data['value'])]
</code>```

Select n largest values

Pandas provides method nlargest, so you can use it to select n largest values:

```<code>largest_values = cleaned_data.nlargest(5, 'value')
</code>```

or you can use interval of values

```<code>largest_values = cleaned_data[cleaned_data['value'] > cleaned_data['value'].max() - 3]
</code>```

Summarize results

Here we should count ocurrences of values in each column and then plot this data.

```<code>melted = pd.melt(largest_values['here you should select columns with explanatory variables'])
table = pd.crosstab(melted['variable'], melted['value'])
table.plot.bar()
</code>```

example of resulting plot

Body:
I have a dataframe with 3 columns df=["a", "b", "value"]. (Actually this is a snippet, the solution should be able to handle n variables, like "a", "b", "c", "d"...) In this case, the "value" column has been generated depending on the "a" and "b" value, doing something like:

        for a in range(1,10):
            for b in range (1,10):
                generate_value(a,b)

The resulting data is similar to:

  a b value
0 1 1 0.23
1 1 2 6.34
2 1 3 0.25
3 1 4 2.17
4 1 5 5.97
[...]

I want to know the statistical better combinations of "a" and "b" that gives me the bigger "value". So I want to draw some kind of histogram that shows me which values of "a" and "b" statistically generates bigger "value". I tried with something like:

fig = plot.figure()
ax=fig.add_subplot(111)
ax.hist(df["a"],bins=50, normed=True)

or:

 plot.plot(df["a"].values, df["value"].values, "o")

But the results are not good. I think that I should use some kind of histogram or gauss bell curve, but I'm not sure how to plot it.

So, how to plot the statistically better "a" and "b" to get maximum "value"?

Note: the answer 1 is perfect for two variables a and b, but the problem is that the correct answer would need to work for multiple variables, a, b, c, d...

Edit 1: Please note that although I'm asking about two variables, the solution can't be to bound "a" to axis x and "b" to axis y, as there may be more variables. So if we have "a", "b", "c", "d", "e", the solution should be valid

Edit 2: Trying to explain it better: Lets take the following dataframe:

  a b c d value
0 1 6 9 7 0.23
1 5 2 3 5 11.34
2 6 7 8 4 0.25
3 1 4 9 3 2.17
4 1 5 9 1 4.97
5 6 6 4 7 25.9
6 3 5 5 2 10.37
7 1 5 1 2 7.87
8 2 5 3 3 8.12
9 1 5 2 1 2.97
10 7 5 4 9 5.97
11 3 5 2 3 9.92
[...]

The row 5 clearly is the winner, with a 25.9 value, so the supposedly better values of a,b,c,d are: 6 6 4 7 . But we can see that statistically it is a strange result, it is the only one so high with those values of a,b,c,d, so it is very unlikely that we're going to get, in the future, a high value choosing those values for a,b,c,d. Instead, seems much more safe to choose numbers that have generated "value" between 8 and 11. Although a 8 to 11 gain is less than 25.9, the probability that the values of a,b,c,d (5,2,3,3) generate this higher "value" is bigger

Edit 3: Although a,b,c,d are discrete, the combination/order of them will generate different results. I mean, there is a function that will return a value inside a small range, like: value=func(a,b,c,d). That value will depend not only on the values of a,b,c,d, but also on some random things. So, for instance, func(5,2,3,5) could return a value of 11.34, but it also could return a similar value, like 10.8, 9.5 or something like that (a range value between 8 and 11). Also, func(1,6,9,7) will return 0.23, or it could return 2.7, but probably it won't return 10.1 as it is also very far from its range.

Following the the example, I'm trying to get the numbers that most probably will generate something in the range of 8-11 (well, the maximum). Probably the numbers I want to visualize somehow will be some kind of combination of numbers 3,5 and 2. But probably there won't be any 6,7,4 numbers, as they usually generate smaller "value" results

Body:
This problem seems to be very complicated to solve it by one built-in function.

I think it should be solved in this way:

exclude outliers from data

select n largest values

summarize results with bar plot or any other

Clean data from outliers

We might choose any appropriate method for outliers detection e.g. 3*sigma, 1.5*IQR etc. I used 1.5*IQR in the example bellow.

cleaned_data = data[data['value'] < 1.5 * stats.iqr(data['value'])]

Select n largest values

Pandas provides method nlargest, so you can use it to select n largest values:

largest_values = cleaned_data.nlargest(5, 'value')

or you can use interval of values

largest_values = cleaned_data[cleaned_data['value'] > cleaned_data['value'].max() - 3]

Summarize results

Here we should count ocurrences of values in each column and then plot this data.

melted = pd.melt(largest_values['here you should select columns with explanatory variables'])
table = pd.crosstab(melted['variable'], melted['value'])
table.plot.bar()

example of resulting plot


问:
Laravel routing error 404
In my laravel project routing isn't working correctly. When I go to /exchange, I get error 404. Redictering works good.

```<code><?php
Route::group(['middleware' => ['web']], function () {

Route::get('/', function() {
    return redirect('exchange');
});
Route::get('exchange', function() {
    return view('exchange');
});

Route::get('tos', function() {
    return view('tos');
});
Route::get('contact', function() {
    return view('contact');
});

Route::controller('admin', 'AdminController');

});
</code>```

And my .htaccess file:

```<code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
</code>```

What I have to do to repair my project?

答:
You Have To add :-

AllowOverride All to etc/apache2  apache2.conf file

```<code><Directory /usr/share>

AllowOverride All
    Require all granted
</Directory>

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>
</code>```

It will handle routing error.

Title: Laravel routing error 404

Body:
In my laravel project routing isn't working correctly. When I go to /exchange, I get error 404. Redictering works good.

<?php
Route::group(['middleware' => ['web']], function () {

Route::get('/', function() {
    return redirect('exchange');
});
Route::get('exchange', function() {
    return view('exchange');
});

Route::get('tos', function() {
    return view('tos');
});
Route::get('contact', function() {
    return view('contact');
});

Route::controller('admin', 'AdminController');

});

And my .htaccess file:

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

What I have to do to repair my project?

Body:
You Have To add :-

AllowOverride All to etc/apache2  apache2.conf file

<Directory /usr/share>

AllowOverride All
    Require all granted
</Directory>

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

It will handle routing error.


问:
Are all objects returned by value rather than by reference?
I am coding in Python trying to decide whether I should return a numpy array (the result of a diff on some other array) or return numpy.where(diff)[0], which is a smaller array but requires that little extra work to create. Let's call the method where this happens methodB.

I call methodB from methodA. The rub is that I won't necessarily always need the where() result in methodA, but I might. So is it worth doing this work inside methodB, or should I pass back the (much larger memory-wise) diff itself and then only process it further in methodA if needed? That would be the more efficient choice assuming methodA just gets a reference to the result.

So, are function results ever not copied when they are passed back the the code that called that function?

I believe that when methodB finishes, all the memory in its frame will be reclaimed by the system, so methodA has to actually copy anything returned by methodB in to its own frame in order to be able to use it. I would call this "return by value". Is this correct?

答: I see what I missed now: Objects are created on the heap, but function frames are on the stack. So when methodB finishes, its frame will be reclaimed, but that object will still exist on the heap, and methodA can access it with a simple reference.


答:
For a fast solution put the .caption inside a div with the img

body {
  background-color: #aa99ff;
  font-family: 'Exo 2', sans-serif;
}

img {
  border: 5px dotted black;
  margin: 10px;
  margin-bottom: 0;
}

.caption {
  margin-left: 10px;
  margin-top: 0;
  display: inline;
}

p {
  margin-left: 10px;
}

#innpakning {
  width: 980px;
  height: 700px;
}

#tekst {
  display: flex;
}

.gameOption{
  float: left;
  display: table;
}
.gameOption img{
  display: table-row;
}
.gameOption .caption{
font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?family=Exo+2" rel="stylesheet">

<div id="innpakning">
  <p id="spillerPoeng"> <b>Spiller:</b> 0 </p>
  <p id="maskinPoeng"> <b>Maskin:</b> 0 </p>
  <div class="gameOption">
    <img src="stein.png"
  alt="spiller stein" id="stein" width="150" height="200">
     <p class="caption">Stein</p>
  </div>
  <div class="gameOption">
    <img src="saks.png"
    alt="spiller saks" id="saks" width="150" height="200">
     <p class="caption">Saks</p>
  </div>
  <div class="gameOption">
    <img src="papir.png"
    alt="spiller papir" id="papir" width="150" height="200">
    <p class="caption">Papir</p>
  </div>
  <div class="gameOption">
    <img src="ukjent.png"
    alt="spiller stein" id="stein" width="150" height="200">
    <p class="caption">Maskin</p>
  </div>
  <br>
  <div id="tekst">
  </div>
  <p id="info"></p>
</div></code>```

Title: Changing the margin property on flex boxes

Body:
For a fast solution put the .caption inside a div with the img

body {
  background-color: #aa99ff;
  font-family: 'Exo 2', sans-serif;
}

img {
  border: 5px dotted black;
  margin: 10px;
  margin-bottom: 0;
}

.caption {
  margin-left: 10px;
  margin-top: 0;
  display: inline;
}

p {
  margin-left: 10px;
}

#innpakning {
  width: 980px;
  height: 700px;
}

#tekst {
  display: flex;
}

.gameOption{
  float: left;
  display: table;
}
.gameOption img{
  display: table-row;
}
.gameOption .caption{
font-weight: bold;
}

<link href="https://fonts.googleapis.com/css?family=Exo+2" rel="stylesheet">

<div id="innpakning">
  <p id="spillerPoeng"> <b>Spiller:</b> 0 </p>
  <p id="maskinPoeng"> <b>Maskin:</b> 0 </p>
  <div class="gameOption">
    <img src="stein.png"
  alt="spiller stein" id="stein" width="150" height="200">
     <p class="caption">Stein</p>
  </div>
  <div class="gameOption">
    <img src="saks.png"
    alt="spiller saks" id="saks" width="150" height="200">
     <p class="caption">Saks</p>
  </div>
  <div class="gameOption">
    <img src="papir.png"
    alt="spiller papir" id="papir" width="150" height="200">
    <p class="caption">Papir</p>
  </div>
  <div class="gameOption">
    <img src="ukjent.png"
    alt="spiller stein" id="stein" width="150" height="200">
    <p class="caption">Maskin</p>
  </div>
  <br>
  <div id="tekst">
  </div>
  <p id="info"></p>
</div>


答:
play() is being called in second button, change it to play2()

```<code><input type="button" value="play" onclick="play()">
<input type="button" value="play2" onclick="play2()">
</code>```

Title: Using Javascript to play sounds on buttons

Body:
Hi I want to use click to play audio I managed to use Javascript for playing one audio but I need for playing different audios on clicking a particular button.

I am able to play first one but the second one is also playing same audio. I am new in Javascript

function play() {
  var audio = document.getElementById("sound1");
  audio.play();
}

function play2() {
  var audio2 = document.getElementById("sound2");
  audio.play();
}

<audio id="sound1" src="https://feeds.soundcloud.com/stream/303404685-hopperkremer-w1-1.mp3"></audio>
<audio id="sound2" src="http://feeds.soundcloud.com/stream/303404681-hopperkremer-w4-1.mp3"></audio>

<input type="button" value="play" onclick="play()">
<input type="button" value="play2" onclick="play()">

(codepen)

Body:
play() is being called in second button, change it to play2()

<input type="button" value="play" onclick="play()">
<input type="button" value="play2" onclick="play2()">