问:
JavaScript comparing arrays failing when it shouldn't be
Problem:

Call two arms equally strong if the heaviest weights they each are able to lift are equal.

Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms.

Given your and your friend's arms' lifting capabilities find out if you two are equally strong.

Issue:

My solution keeps showing false when all numbers are equal. For example, when >you = [10, 15] and friend = [10, 15], I'm getting false when it should be true.
Sure it's user error over here. :)

function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {
    var you = [yourLeft, yourRight];
    var friend = [friendsLeft, friendsRight];
    you.sort(), friend.sort();
    console.log(you, friend)
    if(you === friend){
        return true;
    }else{
        return false;
    }
}```
</div>
</div>
</p>
<p>Fixed, thank  you!!</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>function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {
    var you = [yourLeft, yourRight];
    var friend = [friendsLeft, friendsRight];
    you.sort(), friend.sort();
    console.log(you, friend)
    for(var i = 0; i < you.length; i++) {
        if(you[i] !== friend[i])
            return false;
    }

    return true;
}</code>```

答:
You get 'false' result because arrays in JavaScript are compared by references but not by values. In order to find out if two arrays contain elements with the same values you should use the following approach.</p>

```<code>function areArraysEqual(array1, array2) {
  var result = true;
  var length1 = array1.length;
  var length2 = array2.length;
  if (length1 !== length2) {
    return false;
  }
  array1.sort();
  array2.sort();
  for (var i = 0; i < length1; i++) {
    if (array1[i] !== array2[i]) {
      result = false;
      break;
    }
  }
  return result;
}
</code>```

Body:
Problem:

Call two arms equally strong if the heaviest weights they each are able to lift are equal.

Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms.

Given your and your friend's arms' lifting capabilities find out if you two are equally strong.

Issue:

My solution keeps showing false when all numbers are equal. For example, when >you = [10, 15] and friend = [10, 15], I'm getting false when it should be true.
Sure it's user error over here. :)

function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {
    var you = [yourLeft, yourRight];
    var friend = [friendsLeft, friendsRight];
    you.sort(), friend.sort();
    console.log(you, friend)
    if(you === friend){
        return true;
    }else{
        return false;
    }
}

Fixed, thank  you!!

function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {
    var you = [yourLeft, yourRight];
    var friend = [friendsLeft, friendsRight];
    you.sort(), friend.sort();
    console.log(you, friend)
    for(var i = 0; i < you.length; i++) {
        if(you[i] !== friend[i])
            return false;
    }

    return true;
}

Body:
You get 'false' result because arrays in JavaScript are compared by references but not by values. In order to find out if two arrays contain elements with the same values you should use the following approach.

function areArraysEqual(array1, array2) {
  var result = true;
  var length1 = array1.length;
  var length2 = array2.length;
  if (length1 !== length2) {
    return false;
  }
  array1.sort();
  array2.sort();
  for (var i = 0; i < length1; i++) {
    if (array1[i] !== array2[i]) {
      result = false;
      break;
    }
  }
  return result;
}


来源: stackexchange

问:
How can an iOS native app like Vimeo set cookies to mobile Safari?
I find Vimeo iOS native app can set cookies to mobile Safari. How does it do?

Repo steps:

1, Install Vimeo iOS native app on an iOS device.

2, Open this Vimeo iOS native app and then sign in with your Vimeo account.

3, Open mobile Safari and then open web page "https://vimeo.com/". You find you are not signed in Vimeo.

4, Open Vimeo iOS native app and then click on the "Help (question mark)" icon in the left navigation bar. You will see that Vimeo's web page help center is opened via UIWebView. And then you can close this help center.

5, Open mobile Safari and then open web page "https://vimeo.com/". You find you are signed in Vimeo.

Thank you.

答:
This obviously wouldn't have applied at the time of the OP's question, but more recently cookies were shared between Safari and SFSafariViewController instances in iOS 9 and 10. Vimeo could have set a cookie via an invisible SFSafariViewController to achieve this result. However, this has changed in iOS 11. Going forward, every app (including Safari itself) will have a completely sandboxed data store. Official announcement here (at the 17:28 mark).

In iOS 11, behavior like this will no longer be possible (in fact, preventing it was the featured example in Apple's announcement about this change).

If you need a way to pass a guaranteed user match through from Safari to your app, you'll need to use an existing network of device matches, such as Branch.io (full disclosure: I'm on the Branch team). You can read about the techniques Branch uses instead of cookie passthrough here.

ContentLicense: CC BY-SA 3.0


问:
SAS EG: Prompts with Dynamic List on Metaserver
I'm trying to develop a SAS Prompt that has a drop down with values pulled from a field on a table I'm storing in the Work library.

When I click "Browse" in the "Data Source" area, I'm confined to my SAS Folders.

I'm on a metadata server and don't yet understand the limitations.

How would it be possible to store a table in the SAS "My Folder" folder?

I've created a static list from the data. Should I use this option instead? If so, is there a way to update the list using a SAS Script?

I'm new to SAS EG but not Base SAS. I'm not familiar with "Files" or the "Metadata Server". I typically just query data out of multiple libraries and store in in a work folder prior to export.

答:
The SAS Metadata Server stores metadata about your EG project in the metadata server repository. The actual project files are stored on the WebDAV server. Regular users do not need to know about the WebDAV server. The important part to know is that the metadata server repository in your case acts like a file system. On that file system, your system administrator must have granted rights (with ACTs and ACEs).

Since 2011, the recommended best practice from SAS is to DENY rights initially, and ALLOW rights on a basis of need.

SAS prompts consist of metadata only. They are read by the SAS Prompting Framework which take care of the user interface. As such, you do not need to store them in you WORK library. Instead, SAS EG jobs can take parameters from the Prompting Framework, and you can use the parameters as SAS Macro variables in your SAS EG code.

To use a table with EG you must have been granted to enterprise resources. If you want to use local resources, you must be able to import Excelsheets via the File menu.

The biggest difference between SAS Foundation and Enterprise Guide (with Metadata Server) is that

on SAS Foundation, you and your team can access everthing, and need to do every yourselves (including documentation)

and EG / MS tasks are split up in different interfaces to be more scalable over the entire Enterprise (company wise). All relations between entities are stored in the metadata server and are automatically documented / graphable. You as a developer are a bit more dependant of others, roles are split up, like with autorisation in your case. For larger organisations to be compliant this situation is generally considered an improvement.

For more information please see the SAS Intelligence Platform Overview documentation.

ContentLicense: CC BY-SA 4.0


问:
FabricJS SVG to canvas (using FileReader)
On my page, I have a button and a canvas with the following attributes -

```<code><button onclick="openSVG()">Open</button>
<canvas></canvas>
</code>```

On clicking the button, the openSVG() function is supposed to

Let the user select and open an SVG file from their local hard drive (previously created using FabricJS)

Read the contents of the SVG file using FileReader and storing it in a variable

Using that variable to populate the canvas using fabric.loadSVGFromString() method

Now clicking on Open button opens a file selection window but doesnt draw objects into canvas. Here's my openSVG() function -

```<code>function openSVG() {

// importing file
var input = $(document.createElement('input'));
input.attr("id", "mySVGFile")
input.attr("type", "file");
input.trigger('click');

//storing file contents in var using FileReader
var myInputFile = document.getElementById('mySVGFile');
var myFile = myInputFile.files[0];

var fr = new FileReader();
fr.onload = function(){

    var canvasD = this.result;

    //loading data from var to canvas
    fabric.loadSVGFromString(canvasD, function(objects, options) {
        var obj = fabric.util.groupSVGElements(objects, options);
        canvas.add(obj).renderAll();
    });
};

fr.readAsText(myFile); }
</code>```

I'm new to FileReader. There's no errors in console so I can't even tell where I'm going wrong.
Does my approach not work? Is there a better way to achieve what I want.

答:
Here is a much more easier and better approach using URL.createObjectURL() method ...

var canvas = new fabric.Canvas('c');

function openSVG(e) {
   var url = URL.createObjectURL(e.target.files[0]);
   fabric.loadSVGFromURL(url, function(objects, options) {
      objects.forEach(function(svg) {
         svg.set({
            top: 90,
            left: 90,
            originX: 'center',
            originY: 'center'
         });
         svg.scaleToWidth(50);
         svg.scaleToHeight(50);
         canvas.add(svg).renderAll();
      });
   });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas{margin-top:5px;border:1px solid #ccc}</code>```

<input type="file" onchange="openSVG(event)">
<canvas id="c" width="180" height="180"></canvas>```

Body:
On my page, I have a button and a canvas with the following attributes -

<button onclick="openSVG()">Open</button>
<canvas></canvas>

On clicking the button, the openSVG() function is supposed to

Let the user select and open an SVG file from their local hard drive (previously created using FabricJS)

Read the contents of the SVG file using FileReader and storing it in a variable

Using that variable to populate the canvas using fabric.loadSVGFromString() method

Now clicking on Open button opens a file selection window but doesnt draw objects into canvas. Here's my openSVG() function -

function openSVG() {

// importing file
var input = $(document.createElement('input'));
input.attr("id", "mySVGFile")
input.attr("type", "file");
input.trigger('click');

//storing file contents in var using FileReader
var myInputFile = document.getElementById('mySVGFile');
var myFile = myInputFile.files[0];

var fr = new FileReader();
fr.onload = function(){

    var canvasD = this.result;

    //loading data from var to canvas
    fabric.loadSVGFromString(canvasD, function(objects, options) {
        var obj = fabric.util.groupSVGElements(objects, options);
        canvas.add(obj).renderAll();
    });
};

fr.readAsText(myFile); }

I'm new to FileReader. There's no errors in console so I can't even tell where I'm going wrong.
Does my approach not work? Is there a better way to achieve what I want.

Body:
Here is a much more easier and better approach using URL.createObjectURL() method ...

var canvas = new fabric.Canvas('c');

function openSVG(e) {
   var url = URL.createObjectURL(e.target.files[0]);
   fabric.loadSVGFromURL(url, function(objects, options) {
      objects.forEach(function(svg) {
         svg.set({
            top: 90,
            left: 90,
            originX: 'center',
            originY: 'center'
         });
         svg.scaleToWidth(50);
         svg.scaleToHeight(50);
         canvas.add(svg).renderAll();
      });
   });
}

canvas{margin-top:5px;border:1px solid #ccc}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.11/fabric.min.js"></script>
<input type="file" onchange="openSVG(event)">
<canvas id="c" width="180" height="180"></canvas>


问:
Mobiscroll datepicker is hidden by jQuery Mobile modal
I have a jQuery Mobile site with some date inputs, I am using the Mobiscroll datepicker (in modal mode) for these. It works well on standard jQM pages, but it has a problem when I have a date input that is on a jQM modal.

The problem is the datepicker modal shows under the jQM modal and so the user can't see it, I want the datepicker to show over the top of the jQM modal. If I hide the jQM modal using Firebug, I can also see that the datepicker is under the jQM "dark" filter - where it makes everything dark except the jQM modal.

The code I'm using to setup the Mobiscroll datepicker is:

```<code>$('#mydate').scroller('destroy').scroller($.extend(
{
    preset : 'date',
    dateFormat: 'dd/mm/yyyy'
},
{
    display: 'modal',
    mode: 'scroller',
    theme: 'default',
    lang: 'en'
}));
</code>```

I have tried modifying the elements in Firebug to see if some CSS would fix it, I tried setting the datepicker to a high z-index and the jQM modal to a lower z-index, also tried forcing it with !important but this didn't change anything. The other Mobiscroll display options: top, bottom, bubble have the same problem.

How can I get the datepicker to display on top of the jQM modal?

jQM version: 1.2.0 (latest), with jQuery 1.8.2

Mobiscroll version: 2.4.4 (latest)

答:
I happened to have the same issue and here it my fix:
Check the css of the modal(the default z-index for jquery mobile modal is 1050).
Then go to mobicroller css and change the z-index to any value above it. As long as mobiscroller has a hinger z-index it should show on top modal without any problem.</p>

Body:
I have a jQuery Mobile site with some date inputs, I am using the Mobiscroll datepicker (in modal mode) for these. It works well on standard jQM pages, but it has a problem when I have a date input that is on a jQM modal.

The problem is the datepicker modal shows under the jQM modal and so the user can't see it, I want the datepicker to show over the top of the jQM modal. If I hide the jQM modal using Firebug, I can also see that the datepicker is under the jQM "dark" filter - where it makes everything dark except the jQM modal.

The code I'm using to setup the Mobiscroll datepicker is:

$('#mydate').scroller('destroy').scroller($.extend(
{
    preset : 'date',
    dateFormat: 'dd/mm/yyyy'
},
{
    display: 'modal',
    mode: 'scroller',
    theme: 'default',
    lang: 'en'
}));

I have tried modifying the elements in Firebug to see if some CSS would fix it, I tried setting the datepicker to a high z-index and the jQM modal to a lower z-index, also tried forcing it with !important but this didn't change anything. The other Mobiscroll display options: top, bottom, bubble have the same problem.

How can I get the datepicker to display on top of the jQM modal?

jQM version: 1.2.0 (latest), with jQuery 1.8.2

Mobiscroll version: 2.4.4 (latest)


问:
Rethinkdb getField() gives an error
This is the error:

toJSON` takes 0 argument, 1 provided after:\nr.table(\"users\").get(\"c62b27da-c0c2-4bfd-bd77-aaa95f215ec5\")(\"account\")"

This is my code:

```<code>`const userId = hook.params.user.id;
          const r = this.options.r;
          const accountId = r.table('users').get(userId).getField('account');
          if(accountId != null) {
            hook.data = Object.assign({}, hook.data, {
              createdBy: userId,
              account: accountId
            });
          }`
</code>```

This is part of the code, but I think it is showing what part of code is giving me error!

Please help!

答:
You're missing a call to .run(conn).

In your code, the constId constant does not contain an id, it contains an unevaluated ReQL query.

See https://rethinkdb.com/docs/introduction-to-reql/

Title: Rethinkdb getField() gives an error

Body:
This is the error:

toJSON` takes 0 argument, 1 provided after:\nr.table(\"users\").get(\"c62b27da-c0c2-4bfd-bd77-aaa95f215ec5\")(\"account\")"

This is my code:

`const userId = hook.params.user.id;
          const r = this.options.r;
          const accountId = r.table('users').get(userId).getField('account');
          if(accountId != null) {
            hook.data = Object.assign({}, hook.data, {
              createdBy: userId,
              account: accountId
            });
          }`

This is part of the code, but I think it is showing what part of code is giving me error!

Please help!


问:
How to see correct metrics for changes between two commits?
How properly use git diff   to count: added, modified, deleted and total lines of file for each file? Also, I need ignore blank and comments lines.</p>

答:
You can do that by:

```<code>git diff --stat <commit1> <commit2>
</code>```

And for a quick history overview:

```<code>git log --stat
</code>```

Body:
You can do that by:

git diff --stat <commit1> <commit2>

And for a quick history overview:

git log --stat


问:
Creating Actions for Personal use only
My house has an home automation system from the 1960's that I have managed to tap into.  I've been able to setup an interface which allows me to write adapters for various technologies such as Node Red, Alexa, and now Google Assistent.

Given that this will only ever work with my house, I see no reason to make public Smart Home Actions.  On Alexa's side, I can let these services stay in a Development state indefinitely which has worked great for the last 6 months.  On Google's side, however, the FAQ says (https://developers.google.com/actions/smarthome/faq):

Q: How often do I need to run gactions test?

A: gactions test needs be refreshed every 3 days. After 3 days the test agent will disappear from mobile-HomeControl settings. If you run into this, just run gaction test again.

Therefore, I was wondering what they best way is to make a PERSONAL Google Actions service?  Of course, the obvious method would be to script and schedule the gactions call to keep testing alive but I would hope there was a better way to support this!

Additional details:  I'm using Amazon's OAuth service for sign-in.  This way, I can validate the Amazon ClientID, UserID, etc. through the AccesssToken Google passes in for authorization.  Therefore, I could theoretically run this publicly without any issues but I would need to figure out how Google could review it for testing purposes!  I don't need some Google employee turning on and off my lights while the Google Maps car drive by to verify the change... ;)

答:
I would just use a script to call gaction periodically.
Publishing it would unnecessarily pollute the Actions directory. Also, they'll make you jump through hoops for "brand verification" and other restrictions they have for naming invocation terms.
If you did publish it, you give them a temporary account for verification purposes and disable the account when published. They would be randomly controlling the lights during the verification period though which can be up to a week!</p>

Title: Creating Actions for Personal use only


问:
Detect Chrome running in headless mode from JavaScript
With the release of Chrome 59, "headless" mode is now available in stable builds for Linux and macOS (and soon also Windows with Chrome 60). This allows us to run a full-featured version of Chrome without any visible UI, a great capability to have for automated testing. Here are examples.

chrome --headless --disable-gpu --dump-dom https://stackoverflow.com/
```

<p>In my JavaScript test runner, I like to record as much information as possible about the browser being used, to help isolate issues. For example, I record many of the properties of <code>navigator</code>, including the current browser plugins:</p>

<pre class="lang-js prettyprint-override"><code>JSON.stringify(Array.from(navigator.plugins).map(p => p.name))
</code>```

["Chrome PDF Viewer","Widevine Content Decryption Module","Shockwave Flash","Native Client","Chrome PDF Viewer"]
```

My understanding is that Chrome should behave identically in headless mode, but I have enough experience to be skeptical of a new feature that may significantly change the rendering pipeline.

For now, I am going to run tests in both modes. I would like to the test runner to record whether headless mode is being used. I could pass this information in the test configurations, but I'd rather have a pure JavaScript solution that I can build into the test runner itself. However, I haven't been able to find any browser interface that reveals whether headless mode is active.

Is there any way to detect if Chrome is running in headless mode from JavaScript?

答:
The user agent string includes HeadlessChrome instead of Chrome. This is probably the signal that you're intended to look for, so you could use:

```<code>/\bHeadlessChrome\//.test(navigator.userAgent)
</code>```

Other interesting signals include:

It looks like window.chrome is undefined when headless.

[innerWidth, innerHeight] is [800, 600] (hardcoded in headless_browser.cc), while [outerWidth, outerHeight] is [0, 0] (which shouldn't usually happen).

Body:
With the release of Chrome 59, "headless" mode is now available in stable builds for Linux and macOS (and soon also Windows with Chrome 60). This allows us to run a full-featured version of Chrome without any visible UI, a great capability to have for automated testing. Here are examples.

chrome --headless --disable-gpu --dump-dom https://stackoverflow.com/

In my JavaScript test runner, I like to record as much information as possible about the browser being used, to help isolate issues. For example, I record many of the properties of navigator, including the current browser plugins:

JSON.stringify(Array.from(navigator.plugins).map(p => p.name))

["Chrome PDF Viewer","Widevine Content Decryption Module","Shockwave Flash","Native Client","Chrome PDF Viewer"]

My understanding is that Chrome should behave identically in headless mode, but I have enough experience to be skeptical of a new feature that may significantly change the rendering pipeline.

For now, I am going to run tests in both modes. I would like to the test runner to record whether headless mode is being used. I could pass this information in the test configurations, but I'd rather have a pure JavaScript solution that I can build into the test runner itself. However, I haven't been able to find any browser interface that reveals whether headless mode is active.

Is there any way to detect if Chrome is running in headless mode from JavaScript?

Body:
The user agent string includes HeadlessChrome instead of Chrome. This is probably the signal that you're intended to look for, so you could use:

/\bHeadlessChrome\//.test(navigator.userAgent)

Other interesting signals include:

It looks like window.chrome is undefined when headless.

[innerWidth, innerHeight] is [800, 600] (hardcoded in headless_browser.cc), while [outerWidth, outerHeight] is [0, 0] (which shouldn't usually happen).


问:
How to configurate C3P0 to use datasource url for connection at the oracle database in jboss AS7
we are having trouble to configure c3p0 in jboss, there are 2 configurations files, and we don't know wich we have to change:

Jboss datasource app-ds.xml:

```<code><datasources>
    <datasource jta="false" jndi-name="java:/TestJNDI" pool-name="TestPool" use-ccm="false">
        <connection-url>jdbc:oracle:thin:@server_test:port:database</connection-url>
        <connection-property name="schema">schema</connection-property>
        <driver-class>oracle.jdbc.OracleDriver</driver-class>
        <driver>ojdbc6.jar</driver>
        <pool>
                <min-pool-size>20</min-pool-size>
                <max-pool-size>400</max-pool-size>
        </pool>
        <security>
            <user-name>user</user-name>
            <password>pass</password>
        </security>
        <validation>
            <validate-on-match>false</validate-on-match>
            <background-validation>false</background-validation>
        </validation>
        <statement>
            <share-prepared-statements>false</share-prepared-statements>
        </statement>
    </datasource>
</datasources>
</code>```

persistence.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
    <persistence-unit name="Oracle">
        <description>Oracle database connection</description>
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>entity1</class>
        <!-- entities -->
        <class>entityN</class>
        <properties>
            <property name="hibernate.show_sql" value="false"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.connection.datasource" value="java:/TestJNDI"/>
            <property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
            <property name="hibernate.generate_statistics" value="true"/>

            <!-- Important -->
            <property name="hibernate.connection.provider_class" value="org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" />
            <property name="hibernate.c3p0.max_size" value="100" />
            <property name="hibernate.c3p0.min_size" value="0" />
            <property name="hibernate.c3p0.acquire_increment" value="1" />
            <property name="hibernate.c3p0.idle_test_period" value="300" />
            <property name="hibernate.c3p0.max_statements" value="0" />
            <property name="hibernate.c3p0.timeout" value="100" />
        </properties>
    </persistence-unit>
</persistence>
</code>```

And the log:

```<code>INFO  [org.jboss.as.jpa] (MSC service thread 1-4) JBAS011401: Read persistence.xml for Oracle
WARN  [org.jboss.jaxrs] (MSC service thread 1-15) JBAS011204: resteasy.scan found and ignored in web.xml. This is not necessary, as Resteasy will use the container integration in the JAX-RS 1.1 specification in section 2.3.2
INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-15) JBAS010403: Deploying JDBC-compliant driver class oracle.jdbc.OracleDriver (version 11.2)
INFO  [org.jboss.as.jpa] (MSC service thread 1-8) JBAS011402: Starting Persistence Unit Service 'AppTestEAR.ear/AppTest.war#Oracle'
INFO  [org.hibernate.ejb.Ejb3Configuration] (MSC service thread 1-8) HHH000204: Processing PersistenceUnitInfo [
    name: Oracle
    ...]
INFO  [org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator] (MSC service thread 1-8) HHH000130: Instantiating explicit connection provider: org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider
INFO  [org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider] (MSC service thread 1-8) HHH010002: C3P0 using driver: oracle.jdbc.driver.OracleDriver at URL: null
INFO  [org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider] (MSC service thread 1-8) HHH000046: Connection properties: {autocommit=true, release_mode=auto}
INFO  [org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider] (MSC service thread 1-8) HHH000006: Autocommit mode: true
INFO  [com.mchange.v2.log.MLog] (MSC service thread 1-8) MLog clients using log4j logging.
INFO  [com.mchange.v2.c3p0.C3P0Registry] (MSC service thread 1-8) Initializing c3p0-0.9.1 [built 16-January-2007 14:46:42; debug? true; trace: 10]
INFO  [com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource] (MSC service thread 1-8) Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@20860e3b [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@8b71134e [ acquireIncrement -> 1, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 2zkodt9o11wh4uo1mijhxn|327556d1, idleConnectionTestPeriod -> 300, initialPoolSize -> 3, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 180, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 200, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 20, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@d6b12b99 [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 2zkodt9o11wh4uo1mijhxn|2c53cfe3, jdbcUrl -> null, properties -> {autocommit=true, release_mode=auto} ], preferredTestQuery -> null, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> 2zkodt9o11wh4uo1mijhxn|4fcb6c, numHelperThreads -> 3 ]
WARN  [com.mchange.v2.async.ThreadPoolAsynchronousRunner] (Timer-3) com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@1b6cdb87 -- APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks!
WARN  [com.mchange.v2.async.ThreadPoolAsynchronousRunner] (Timer-3) com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@1b6cdb87 -- APPARENT DEADLOCK!!! Complete Status:
</code>```

The problem is at:

```<code>HHH010002: C3P0 using driver: oracle.jdbc.driver.OracleDriver at URL: null
</code>```

We want use the credendials (the url) provided in the datasource in the jboss (bussiness requirement),

So the question is: How to configurate c3p0 to use datasource url for connection at the oracle database in jboss AS7?

答:
It looks like what's going on is that the DataSource is being constructed according to the config in persistence.xml and some of the JDBC-standard properties (e.g. minPoolSize, maxPoolSize) are being overridden by settings in app-ds.xml.

I think the main issue is that you do not configure the JDBC url in persistence.xml. (c3p0's jdbcUrl is not is JDBC-standard property, so app-ds.xmlis not setting it.) You should add to persistence.xml something like:

```<code><property name="hibernate.connection.url">jdbc:oracle:thin:@server_test:port:database</property>
</code>```

user and password also appear not to be set. Add to persistence.xml something like:

```<code><property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">pass</property>
</code>```

(To see what settings have and have not taken, scroll right to see the config information on the log line beginning Initializing c3p0 pool...)

I'd try removing as much as possible from the app-ds.xml, so you don't confusingly have config in two places. You might be able to get away with...

```<code><datasources>
    <datasource jta="false" jndi-name="java:/TestJNDI" pool-name="TestPool" use-ccm="false" />
</datasources>
</code>```

...but maybe not.

Body:
we are having trouble to configure c3p0 in jboss, there are 2 configurations files, and we don't know wich we have to change:

Jboss datasource app-ds.xml:

<datasources>
    <datasource jta="false" jndi-name="java:/TestJNDI" pool-name="TestPool" use-ccm="false">
        <connection-url>jdbc:oracle:thin:@server_test:port:database</connection-url>
        <connection-property name="schema">schema</connection-property>
        <driver-class>oracle.jdbc.OracleDriver</driver-class>
        <driver>ojdbc6.jar</driver>
        <pool>
                <min-pool-size>20</min-pool-size>
                <max-pool-size>400</max-pool-size>
        </pool>
        <security>
            <user-name>user</user-name>
            <password>pass</password>
        </security>
        <validation>
            <validate-on-match>false</validate-on-match>
            <background-validation>false</background-validation>
        </validation>
        <statement>
            <share-prepared-statements>false</share-prepared-statements>
        </statement>
    </datasource>
</datasources>

persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
    <persistence-unit name="Oracle">
        <description>Oracle database connection</description>
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>entity1</class>

        <class>entityN</class>
        <properties>
            <property name="hibernate.show_sql" value="false"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.connection.datasource" value="java:/TestJNDI"/>
            <property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
            <property name="hibernate.generate_statistics" value="true"/>

            <property name="hibernate.connection.provider_class" value="org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" />
            <property name="hibernate.c3p0.max_size" value="100" />
            <property name="hibernate.c3p0.min_size" value="0" />
            <property name="hibernate.c3p0.acquire_increment" value="1" />
            <property name="hibernate.c3p0.idle_test_period" value="300" />
            <property name="hibernate.c3p0.max_statements" value="0" />
            <property name="hibernate.c3p0.timeout" value="100" />
        </properties>
    </persistence-unit>
</persistence>

And the log:

INFO  [org.jboss.as.jpa] (MSC service thread 1-4) JBAS011401: Read persistence.xml for Oracle
WARN  [org.jboss.jaxrs] (MSC service thread 1-15) JBAS011204: resteasy.scan found and ignored in web.xml. This is not necessary, as Resteasy will use the container integration in the JAX-RS 1.1 specification in section 2.3.2
INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-15) JBAS010403: Deploying JDBC-compliant driver class oracle.jdbc.OracleDriver (version 11.2)
INFO  [org.jboss.as.jpa] (MSC service thread 1-8) JBAS011402: Starting Persistence Unit Service 'AppTestEAR.ear/AppTest.war#Oracle'
INFO  [org.hibernate.ejb.Ejb3Configuration] (MSC service thread 1-8) HHH000204: Processing PersistenceUnitInfo [
    name: Oracle
    ...]
INFO  [org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator] (MSC service thread 1-8) HHH000130: Instantiating explicit connection provider: org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider
INFO  [org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider] (MSC service thread 1-8) HHH010002: C3P0 using driver: oracle.jdbc.driver.OracleDriver at URL: null
INFO  [org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider] (MSC service thread 1-8) HHH000046: Connection properties: {autocommit=true, release_mode=auto}
INFO  [org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider] (MSC service thread 1-8) HHH000006: Autocommit mode: true
INFO  [com.mchange.v2.log.MLog] (MSC service thread 1-8) MLog clients using log4j logging.
INFO  [com.mchange.v2.c3p0.C3P0Registry] (MSC service thread 1-8) Initializing c3p0-0.9.1 [built 16-January-2007 14:46:42; debug? true; trace: 10]
INFO  [com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource] (MSC service thread 1-8) Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@20860e3b [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@8b71134e [ acquireIncrement -> 1, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 2zkodt9o11wh4uo1mijhxn|327556d1, idleConnectionTestPeriod -> 300, initialPoolSize -> 3, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 180, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 200, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 20, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@d6b12b99 [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 2zkodt9o11wh4uo1mijhxn|2c53cfe3, jdbcUrl -> null, properties -> {autocommit=true, release_mode=auto} ], preferredTestQuery -> null, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> 2zkodt9o11wh4uo1mijhxn|4fcb6c, numHelperThreads -> 3 ]
WARN  [com.mchange.v2.async.ThreadPoolAsynchronousRunner] (Timer-3) com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@1b6cdb87 -- APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks!
WARN  [com.mchange.v2.async.ThreadPoolAsynchronousRunner] (Timer-3) com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@1b6cdb87 -- APPARENT DEADLOCK!!! Complete Status:

The problem is at:

HHH010002: C3P0 using driver: oracle.jdbc.driver.OracleDriver at URL: null

We want use the credendials (the url) provided in the datasource in the jboss (bussiness requirement),

So the question is: How to configurate c3p0 to use datasource url for connection at the oracle database in jboss AS7?

Body:
It looks like what's going on is that the DataSource is being constructed according to the config in persistence.xml and some of the JDBC-standard properties (e.g. minPoolSize, maxPoolSize) are being overridden by settings in app-ds.xml.

I think the main issue is that you do not configure the JDBC url in persistence.xml. (c3p0's jdbcUrl is not is JDBC-standard property, so app-ds.xmlis not setting it.) You should add to persistence.xml something like:

<property name="hibernate.connection.url">jdbc:oracle:thin:@server_test:port:database</property>

user and password also appear not to be set. Add to persistence.xml something like:

<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">pass</property>

(To see what settings have and have not taken, scroll right to see the config information on the log line beginning Initializing c3p0 pool...)

I'd try removing as much as possible from the app-ds.xml, so you don't confusingly have config in two places. You might be able to get away with...

<datasources>
    <datasource jta="false" jndi-name="java:/TestJNDI" pool-name="TestPool" use-ccm="false" />
</datasources>

...but maybe not.


答:
Your issue is you are trying to compare a list of items against a another list of items without even reading the items in the list. When you do a === you are comparing the value of that item and this can not be a array as its not clever enough to loop through them all and compare (this is why for each exists ;) - so "10" === "10 = true but ["10"] === ["10"] = false

You have a array so you need to loop through and make sure every index of the element match.. i am assuming you will always have equal number in both arrays so you can do something like this:

```<code>function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {
    var you = [yourLeft, yourRight];
    var friend = [friendsLeft, friendsRight];
    you.sort(), friend.sort();
    console.log(you, friend)
    for(var i = 0; i < you.length; i++) {
        if(you[i] !== friend[i])
            return false;
    }

    return true;
}
</code>```

Title: JavaScript comparing arrays failing when it shouldn't be

Body:
Your issue is you are trying to compare a list of items against a another list of items without even reading the items in the list. When you do a === you are comparing the value of that item and this can not be a array as its not clever enough to loop through them all and compare (this is why for each exists ;) - so "10" === "10 = true but ["10"] === ["10"] = false

You have a array so you need to loop through and make sure every index of the element match.. i am assuming you will always have equal number in both arrays so you can do something like this:

function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {
    var you = [yourLeft, yourRight];
    var friend = [friendsLeft, friendsRight];
    you.sort(), friend.sort();
    console.log(you, friend)
    for(var i = 0; i < you.length; i++) {
        if(you[i] !== friend[i])
            return false;
    }

    return true;
}


问:
SQL_NO_CACHE per table
Over all most if not all of our tables greatly benefit from MySQL's query cache with the exception of one table. This table severely hampers the query cache to do the frequent updates. I know we can set SQL_NO_CACHE when doing a query but I wanted to know if there was a way to set it per table? Currently we are using MySQL 5.5 with plans to one day migrate to 5.6 or 5.7.</p>

答: After much research and speaking with lead MySQL devs they say there is currently no way of doing this.</p>

Title: SQL_NO_CACHE per table


问:
QtWebEngine to embedded linux cross-compilation fails
I'm trying to cross-compile my desktop project to a raspberry pi. My projects uses Qt 5.6, and QtWebEngine.
I followed this guide: RaspberryPi2EGLFS
It runs without the webengine-using parts, but I cannot use the WebEngine module because I cannot compile it. It gives me this:

```<code>gyp: Undefined variable clang_dir in /Users/aeron/raspi/qtwebengine/src/core/core_generated.gyp
gyp: Undefined variable clang_dir in /Users/aeron/raspi/qtwebengine/src/core/resources/resources.gyp
Project ERROR: -- running gyp_qtwebengine failed --
</code>```

I have already tried to manually insert an empty variable, but these two lines are just the tip of the iceberg.

I get to this error too when I grab the full qt5 repository and try to compile it.

Update

I made some progress. With editing qtwebengine/src/core/config/embedded_linux.pri I managed to solve the clang_dir problem. I've just added the line clang_dir=0 to the end of the list of the variables.

But there is another problem of the same kind:

```<code>gyp: Undefined variable c_sources in /Users/aeron/raspi/qtwebengine/src/3rdparty/chromium/third_party/ffmpeg/ffmpeg.gyp
Project ERROR: -- running gyp_qtwebengine failed --
</code>```

How can I resolve this? Or how can I turn off the ffmpeg part of the webengine, I don't have plans to use it anyway...

Update 2

Now it think I solved the ffmpeg problem. The way: in the file src/3rdparty/chromium/third_party/ffmpeg/ffmpeg.gyp I set the use_system_ffmpeg to 1.

Now I have a new problem:

```<code>Updating projects from gyp files...
gyp: Dependency '/Users/aeron/raspi/qtwebengine/src/3rdparty/chromium/base/base.gyp:symbolize#host' not found while trying to load target /Users/aeron/raspi/qtwebengine/src/3rdparty/chromium/base/base.gyp:base#host
Project ERROR: -- running gyp_qtwebengine failed --
</code>```

So it still does not compile.

答:
Probably not what you want to hear, but QWebEngine is not officially supported on the Pi.

From
https://doc.qt.io/qt-5/qtwebengine-platform-notes.html#all-platforms

"On Linux, Clang or GCC version 4.7 or later is required. Supported configurations are linux-g++ and linux-clang."

However, I know for a fact, it can be cross-compiled (I did it on Ubuntu 16) for Qt 5.7.1 and Qt5.8.0, but only if you configure for device "linux-rasp-pi2-g++" and not for "linux-rpi3-g++". It CANNOT be built for Qt5.9.0.

Note that Qt5.8.0 has bad OpenGL performance on the Pi. This issue is not present with Qt5.7 or 5.9.

Then again - it is probably too heavy for the Pi anyway.

Body:
I'm trying to cross-compile my desktop project to a raspberry pi. My projects uses Qt 5.6, and QtWebEngine.
I followed this guide: RaspberryPi2EGLFS
It runs without the webengine-using parts, but I cannot use the WebEngine module because I cannot compile it. It gives me this:

gyp: Undefined variable clang_dir in /Users/aeron/raspi/qtwebengine/src/core/core_generated.gyp
gyp: Undefined variable clang_dir in /Users/aeron/raspi/qtwebengine/src/core/resources/resources.gyp
Project ERROR: -- running gyp_qtwebengine failed --

I have already tried to manually insert an empty variable, but these two lines are just the tip of the iceberg.

I get to this error too when I grab the full qt5 repository and try to compile it.

Update

I made some progress. With editing qtwebengine/src/core/config/embedded_linux.pri I managed to solve the clang_dir problem. I've just added the line clang_dir=0 to the end of the list of the variables.

But there is another problem of the same kind:

gyp: Undefined variable c_sources in /Users/aeron/raspi/qtwebengine/src/3rdparty/chromium/third_party/ffmpeg/ffmpeg.gyp
Project ERROR: -- running gyp_qtwebengine failed --

How can I resolve this? Or how can I turn off the ffmpeg part of the webengine, I don't have plans to use it anyway...

Update 2

Now it think I solved the ffmpeg problem. The way: in the file src/3rdparty/chromium/third_party/ffmpeg/ffmpeg.gyp I set the use_system_ffmpeg to 1.

Now I have a new problem:

Updating projects from gyp files...
gyp: Dependency '/Users/aeron/raspi/qtwebengine/src/3rdparty/chromium/base/base.gyp:symbolize#host' not found while trying to load target /Users/aeron/raspi/qtwebengine/src/3rdparty/chromium/base/base.gyp:base#host
Project ERROR: -- running gyp_qtwebengine failed --

So it still does not compile.


问:
Auto Close Bootstrap-TimePicker?
I'm using bootstrap time picker, it works great but when I press tab between my fields the time picker remains open, so I have to click somewhere else to close it.

How can I make it close it self?
Using the time picker like this:

```<code><div class="form-group">
    <label class="col-md-4 control-label">Starttid:</label>
    <div class="col-md-7">
        @Html.TextBox("startTime", Model.Times.StartTime, new { @class = "form-control timepicker timepicker-24" })
    </div>
</div>
<div class="form-group">
    <label class="col-md-4 control-label">Sluttid:</label>
    <div class="col-md-7">
        @Html.TextBox("endTime", Model.Times.EndTime, new { @class = "form-control timepicker timepicker-24" })
    </div>
</div>
<div class="form-group">
    <label class="col-md-4 control-label">Rastlängd:</label>
    <div class="col-md-7">
        @Html.TextBox("breakTime", Model.Times.BreakTime, new { @class = "form-control timepicker timepicker-24" })
    </div>
</div>
</code>```

These are the settings for my timepicker:

```<code>    $.fn.timepicker.defaults = {
    defaultTime: 'current',
    disableFocus: false,
    disableMousewheel: true,
    isOpen: false,
    minuteStep: 15,
    modalBackdrop: true,
    orientation: { x: 'auto', y: 'auto'},
    secondStep: 15,
    showSeconds: false,
    showInputs: true,
    showMeridian: false,
    template: 'dropdown',
    appendWidgetTo: 'body',
    showWidgetOnAddonClick: true
  };
</code>```

答:
Super-Janky(tm)  hack:</p>

```<code>$("#precedingInput, #followingInput").on("focus", function(){
    $("timeInput").timepicker("hideWidget");
});
</code>```

Title: Auto Close Bootstrap-TimePicker?

Body:
I'm using bootstrap time picker, it works great but when I press tab between my fields the time picker remains open, so I have to click somewhere else to close it.

How can I make it close it self?
Using the time picker like this:

    Starttid:

        @Html.TextBox("startTime", Model.Times.StartTime, new { @class = "form-control timepicker timepicker-24" })

    Sluttid:

        @Html.TextBox("endTime", Model.Times.EndTime, new { @class = "form-control timepicker timepicker-24" })

    Rastlängd:

        @Html.TextBox("breakTime", Model.Times.BreakTime, new { @class = "form-control timepicker timepicker-24" })

These are the settings for my timepicker:

    $.fn.timepicker.defaults = {
    defaultTime: 'current',
    disableFocus: false,
    disableMousewheel: true,
    isOpen: false,
    minuteStep: 15,
    modalBackdrop: true,
    orientation: { x: 'auto', y: 'auto'},
    secondStep: 15,
    showSeconds: false,
    showInputs: true,
    showMeridian: false,
    template: 'dropdown',
    appendWidgetTo: 'body',
    showWidgetOnAddonClick: true
  };

Body:
Super-Janky(tm)  hack:

$("#precedingInput, #followingInput").on("focus", function(){
    $("timeInput").timepicker("hideWidget");
});


问:
Does a foreign key reduce redundancy if all the columns are referenced?
I've read that one of the benefits of normalization is to reduce redundancy in the DB. But I'm wondering, if you end up referencing all the columns in the target table?

For example, if I have a Video table that references a Genre table, the Genre table might very likely have a single column with a dozen fairly static values like 'Horror' 'Sci-Fi' 'Romance' etc.

In a case like this, does it save any space to separate the two, or is the only benefit making it so you can update all referencing rows from one place?

答:
Normalization has nothing to do with saving space. It's about eliminating potential anomalies that can occur as a result of certain kinds of redundancy. Since normalization defines the logical level only it would be quite possible for a normalized database to be physically larger or physically smaller than a denormalized or un-normalized one.

It is true that normalization generally makes designs that ought to translate efficiently into storage - but that's really down to the features of the DBMS rather than something implicit in normalization.

ContentLicense: CC BY-SA 2.5


答:
```<code>composer require --dev phpunit/phpunit
</code>```

This will install the latest PHPUnit, which currently is at version 6.x.

```<code>composer require --dev phpunit/phpunit-selenium
</code>```

This will then try to install the selenium extension, which cannot be installed because it requires PHPUnit 5.x, as you can see reading the output you get as "Problem 1".

Solution: Explicitly require PHPUnit 5, then require phpunit-selenium.

As a side note: You gave the wrong composer.json, it cannot be created by the command you mentioned. It should have listed PHPUnit unter "require-dev".

Title: Can't install phpunit and phpunit-selenium with composer

Body:
I'm trying to follow this guide https://www.sitepoint.com/using-selenium-with-phpunit/ so I can automate Chrome with PHP. I've already got this working in Python, but I'm just so much more familiar with PHP that I figured it'd be easier (maybe I'm wrong...)

Anyway, when I run

composer require --dev phpunit/phpunit
composer require --dev phpunit/phpunit-selenium

I got a whole ton of output from composer about how they both depend on different things that aren't possible to do at the same time (I think, I could be wrong here, too). My output:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - phpunit/phpunit-selenium 3.0.3 requires phpunit/phpunit ~5.0 -> satisfiable by phpunit/phpunit[5.0.0, 5.0.1, 5.0.10, 5.0.2, 5.0.3, 5.0.4, 5.0.5, 5.0.6, 5.0.7, 5.0.8, 5.0.9, 5.0.x-dev, 5.1.0, 5.1.1, 5.1.2, 5.1.3, 5.1.4, 5.1.5, 5.1.6, 5.1.7, 5.1.x-dev, 5.2.0, 5.2.1, 5.2.10, 5.2.11, 5.2.12, 5.2.2, 5.2.3, 5.2.4, 5.2.5, 5.2.6, 5.2.7, 5.2.8, 5.2.9, 5.2.x-dev, 5.3.0, 5.3.1, 5.3.2, 5.3.3, 5.3.4, 5.3.5, 5.3.x-dev, 5.4.0, 5.4.1, 5.4.2, 5.4.3, 5.4.4, 5.4.5, 5.4.6, 5.4.7, 5.4.8, 5.4.x-dev, 5.5.0, 5.5.1, 5.5.2, 5.5.3, 5.5.4, 5.5.5, 5.5.6, 5.5.7, 5.5.x-dev, 5.6.0, 5.6.1, 5.6.2, 5.6.3, 5.6.4, 5.6.5, 5.6.6, 5.6.7, 5.6.8, 5.6.x-dev, 5.7.0, 5.7.1, 5.7.10, 5.7.11, 5.7.12, 5.7.13, 5.7.14, 5.7.15, 5.7.16, 5.7.17, 5.7.18, 5.7.19, 5.7.2, 5.7.20, 5.7.3, 5.7.4, 5.7.5, 5.7.6, 5.7.7, 5.7.8, 5.7.9, 5.7.x-dev] but these conflict with your requirements or minimum-stability.
    - phpunit/phpunit-selenium 3.0.2 requires phpunit/phpunit ~5.0 -> satisfiable by phpunit/phpunit[5.0.0, 5.0.1, 5.0.10, 5.0.2, 5.0.3, 5.0.4, 5.0.5, 5.0.6, 5.0.7, 5.0.8, 5.0.9, 5.0.x-dev, 5.1.0, 5.1.1, 5.1.2, 5.1.3, 5.1.4, 5.1.5, 5.1.6, 5.1.7, 5.1.x-dev, 5.2.0, 5.2.1, 5.2.10, 5.2.11, 5.2.12, 5.2.2, 5.2.3, 5.2.4, 5.2.5, 5.2.6, 5.2.7, 5.2.8, 5.2.9, 5.2.x-dev, 5.3.0, 5.3.1, 5.3.2, 5.3.3, 5.3.4, 5.3.5, 5.3.x-dev, 5.4.0, 5.4.1, 5.4.2, 5.4.3, 5.4.4, 5.4.5, 5.4.6, 5.4.7, 5.4.8, 5.4.x-dev, 5.5.0, 5.5.1, 5.5.2, 5.5.3, 5.5.4, 5.5.5, 5.5.6, 5.5.7, 5.5.x-dev, 5.6.0, 5.6.1, 5.6.2, 5.6.3, 5.6.4, 5.6.5, 5.6.6, 5.6.7, 5.6.8, 5.6.x-dev, 5.7.0, 5.7.1, 5.7.10, 5.7.11, 5.7.12, 5.7.13, 5.7.14, 5.7.15, 5.7.16, 5.7.17, 5.7.18, 5.7.19, 5.7.2, 5.7.20, 5.7.3, 5.7.4, 5.7.5, 5.7.6, 5.7.7, 5.7.8, 5.7.9, 5.7.x-dev] but these conflict with your requirements or minimum-stability.
    - phpunit/phpunit-selenium 3.0.1 requires phpunit/phpunit ~5.0 -> satisfiable by phpunit/phpunit[5.0.0, 5.0.1, 5.0.10, 5.0.2, 5.0.3, 5.0.4, 5.0.5, 5.0.6, 5.0.7, 5.0.8, 5.0.9, 5.0.x-dev, 5.1.0, 5.1.1, 5.1.2, 5.1.3, 5.1.4, 5.1.5, 5.1.6, 5.1.7, 5.1.x-dev, 5.2.0, 5.2.1, 5.2.10, 5.2.11, 5.2.12, 5.2.2, 5.2.3, 5.2.4, 5.2.5, 5.2.6, 5.2.7, 5.2.8, 5.2.9, 5.2.x-dev, 5.3.0, 5.3.1, 5.3.2, 5.3.3, 5.3.4, 5.3.5, 5.3.x-dev, 5.4.0, 5.4.1, 5.4.2, 5.4.3, 5.4.4, 5.4.5, 5.4.6, 5.4.7, 5.4.8, 5.4.x-dev, 5.5.0, 5.5.1, 5.5.2, 5.5.3, 5.5.4, 5.5.5, 5.5.6, 5.5.7, 5.5.x-dev, 5.6.0, 5.6.1, 5.6.2, 5.6.3, 5.6.4, 5.6.5, 5.6.6, 5.6.7, 5.6.8, 5.6.x-dev, 5.7.0, 5.7.1, 5.7.10, 5.7.11, 5.7.12, 5.7.13, 5.7.14, 5.7.15, 5.7.16, 5.7.17, 5.7.18, 5.7.19, 5.7.2, 5.7.20, 5.7.3, 5.7.4, 5.7.5, 5.7.6, 5.7.7, 5.7.8, 5.7.9, 5.7.x-dev] but these conflict with your requirements or minimum-stability.
    - phpunit/phpunit-selenium 3.0.0 requires phpunit/phpunit ~5 -> satisfiable by phpunit/phpunit[5.0.0, 5.0.1, 5.0.10, 5.0.2, 5.0.3, 5.0.4, 5.0.5, 5.0.6, 5.0.7, 5.0.8, 5.0.9, 5.0.x-dev, 5.1.0, 5.1.1, 5.1.2, 5.1.3, 5.1.4, 5.1.5, 5.1.6, 5.1.7, 5.1.x-dev, 5.2.0, 5.2.1, 5.2.10, 5.2.11, 5.2.12, 5.2.2, 5.2.3, 5.2.4, 5.2.5, 5.2.6, 5.2.7, 5.2.8, 5.2.9, 5.2.x-dev, 5.3.0, 5.3.1, 5.3.2, 5.3.3, 5.3.4, 5.3.5, 5.3.x-dev, 5.4.0, 5.4.1, 5.4.2, 5.4.3, 5.4.4, 5.4.5, 5.4.6, 5.4.7, 5.4.8, 5.4.x-dev, 5.5.0, 5.5.1, 5.5.2, 5.5.3, 5.5.4, 5.5.5, 5.5.6, 5.5.7, 5.5.x-dev, 5.6.0, 5.6.1, 5.6.2, 5.6.3, 5.6.4, 5.6.5, 5.6.6, 5.6.7, 5.6.8, 5.6.x-dev, 5.7.0, 5.7.1, 5.7.10, 5.7.11, 5.7.12, 5.7.13, 5.7.14, 5.7.15, 5.7.16, 5.7.17, 5.7.18, 5.7.19, 5.7.2, 5.7.20, 5.7.3, 5.7.4, 5.7.5, 5.7.6, 5.7.7, 5.7.8, 5.7.9, 5.7.x-dev] but these conflict with your requirements or minimum-stability.
    - Installation request for phpunit/phpunit-selenium ^3.0 -> satisfiable by phpunit/phpunit-selenium[3.0.0, 3.0.1, 3.0.2, 3.0.3].

Installation failed, reverting ./composer.json to its original content.

And this is my composer.json contents

{
    "require": {
        "giggsey/libphonenumber-for-php": "~7.0",
        "firephp/firephp-core": "0.4.0",
        "aws/aws-sdk-php": "^3.3",
        "jdorn/sql-formatter": "^1.2",
                "piwik/device-detector": "3.5.0",
                "doctrine/cache": "1.6.0",
        "php-console/php-console": "~3.0",
        "gabrielbull/ups-api": "^0.7.3",
        "google/apiclient": "^2.0",
        "jeremeamia/superclosure": "^2.3",
        "commerceguys/addressing": "^0.8.4",
        "arcreative/php-address-format": "^0.0.2",
        "commerceguys/intl": "^0.7.4",
        "ramsey/uuid": "^3.6",
        "neitanod/forceutf8": "^2.0",
        "facebook/webdriver": "^1.4",
        "phpunit/phpunit": "^6.2"
    }
}

Body:
composer require --dev phpunit/phpunit

This will install the latest PHPUnit, which currently is at version 6.x.

composer require --dev phpunit/phpunit-selenium

This will then try to install the selenium extension, which cannot be installed because it requires PHPUnit 5.x, as you can see reading the output you get as "Problem 1".

Solution: Explicitly require PHPUnit 5, then require phpunit-selenium.

As a side note: You gave the wrong composer.json, it cannot be created by the command you mentioned. It should have listed PHPUnit unter "require-dev".


问:
Failed to create maven project: '.../pom.xml' already exists in VFS (IntelliJ)
When I would like to re-create a maven project with a name had been but have been deleted already, I receive the following error message:

Failed to create maven project: '.../pom.xml' already exists in VFS

答:
See Cleaning System Cache page.

Open any project in IntelliJ IDEA

Select "File > Invalidate Caches / Restart ..."

Click on "Invalidate and Restart"

WARNING

Cleaning out the system caches, keep in mind that:

It results in clearing the local history.

To avoid losing data, check in the changes to your version control system before invalidating caches.
Causes a complete rebuild of all the projects ever run in the current version of IntelliJ IDEA.


问:
How to disable Yii2 pjax asset loading automatically
How can I stop Yii2 from loading the pjax asset file automatically when I use the Pjax widget?  I want to load it myself from a CDN.  I've tried this:

```<code>        'assetManager' => [
            'bundles' => [
                'yii\web\PjaxAsset' => [
                    'js'=>[]
                ],
            ],
        ],
</code>```

But that doesn't do anything.  Any suggestions?

答:
Use</p>

```<code>'assetManager' => [
    'bundles' => [
        'yii\web\PjaxAsset' => [
            'sourcePath' => null,
            'js'=> ['//cdn.url.you/want/to/use']
        ],
    ],
],
</code>```

Body:
How can I stop Yii2 from loading the pjax asset file automatically when I use the Pjax widget?  I want to load it myself from a CDN.  I've tried this:

        'assetManager' => [
            'bundles' => [
                'yii\web\PjaxAsset' => [
                    'js'=>[]
                ],
            ],
        ],

But that doesn't do anything.  Any suggestions?

Body:
Use

'assetManager' => [
    'bundles' => [
        'yii\web\PjaxAsset' => [
            'sourcePath' => null,
            'js'=> ['//cdn.url.you/want/to/use']
        ],
    ],
],


问:
I need more than a row PostgreSQL
I need a PostgreSQL subquery that can return more than a row. Here's the piece of the query that I have so far:</p>

```<code>select (SELECT ARRAY[url, thumb_1, thumb_200, thumb_500]
                FROM "Image"
                LEFT JOIN "Product_Image"
                ON "Image".id = "Product_Image".image_id
                WHERE "Product_Image".product_id = 517
                ORDER BY "Product_Image".sort ASC) as images
</code>```

答:
Put the subquery in the FROM clause?

```<code>select vals
from (SELECT ARRAY[url, thumb_1, thumb_200, thumb_500] as vals
      FROM "Image" LEFT JOIN
           "Product_Image"
           ON "Image".id = "Product_Image".image_id
      WHERE "Product_Image".product_id = 517
     ) images
</code>```

Title: I need more than a row PostgreSQL

Body:
I need a PostgreSQL subquery that can return more than a row. Here's the piece of the query that I have so far:

select (SELECT ARRAY[url, thumb_1, thumb_200, thumb_500]
                FROM "Image"
                LEFT JOIN "Product_Image"
                ON "Image".id = "Product_Image".image_id
                WHERE "Product_Image".product_id = 517
                ORDER BY "Product_Image".sort ASC) as images

Body:
Put the subquery in the FROM clause?

select vals
from (SELECT ARRAY[url, thumb_1, thumb_200, thumb_500] as vals
      FROM "Image" LEFT JOIN
           "Product_Image"
           ON "Image".id = "Product_Image".image_id
      WHERE "Product_Image".product_id = 517
     ) images


问:
Open source CMS with REST based api support
Is there any open source CMS in a java/xml platform which supports REST based apis ?
Basically i like to deploy a CMS as well a widget like application  who can communicate each other via REST? Have tried openCms and couple of others too, but couldn't figure out a proper interface either via http or rest?</p>

答: I've never used it, however, https://getdirectus.com/ looks promising. I like the fact that it's built to be headless, meaning it's core function is to be a CMS with RESTful API, as opposed to the API being a secondary feature.</p>


问:
A web app with logins in a kiosk situation
We are looking at setting up an internal web application (ASP.NET MVC) as a kiosk for the employees that don't have a dedicated computer. We currently do not have this kiosk setup. Each employee will have their own login to look at some basic payroll information and request leaves of absence. This same web application will be used by the office workers with a dedicated PC at their desk.

I am going to go out on a limb and say that no matter how many times we tell the employees, the employees will not click log off when they walk away from the kiosk. What would you do to help prevent this from happening?

答: I found a jQuery version that seems to work quite well. I'll start by using that and see how that goes.</p>


问:
Using HTTP between CloudFront and EC2 for HTTPS site
Our application is currently running on EC2 instances, requiring HTTPS (and redirecting HTTP to HTTPS). We are now considering serving all requests via CloudFront and enforcing HTTPS through CloudFront. Our thought is that once we do that we would then block HTTP/HTTPS requests not coming from CloudFront and relax the HTTPS requirement. This way all requests to CloudFront would be via HTTPS, but CloudFront would retrieve the data from the EC2 origin via HTTP. This way we would a) reduce some server overhead since the server doesn't have to do the TLS encryption and b) eliminate the need to manage certificates for the EC2 instances.

Are there any security concerns with this or other reasons not to do this?

答:
To add additional security you can do the following.

Having a secret token header sent from CloudFront which is verified at the EC2 instance to serve the request.

Only allowing the IP address ranges of CloudFront, in EC2's or ELB's security group for inbound request.


问:
ordered list allign like the rest in css and html
I need 1.5.2.1 in the list also alligned like the rest, what am I doing wrong? Please help me to adjust the css code to align the ordered list indent as seen at 1.5.2.1, I dont know what im doing wrong.

ol {
 counter-reset: item;
 padding: 0;
 margin: 0;
 margin-left: 20px !ie7;
}

ul {
 margin: 0;
 padding: 0;
 list-style: none;
}

li span, li {
    display: block;
    overflow: hidden;
}

li:before {
 display: block;
 position: relative;
 content: counters(item, ".") ".";
 float: left;
}
ol > li {
 counter-increment: item;

}
ol li:before {

 width: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <ol>
  <li><strong>Introduction</strong>
    <ol>
      <li><span>This document...</span></li>
      <li><span>In the event...</span></li>
      <li><span>We...</span>
        <ol>
          <li><span>"Acknowledgment...</span>

            <li><span>"Deliver"/ "Delivered"/...</span>

              <ol>
                <li>where...</li>
              </ol>

            </li>
        </ol>
        </li>
    </ol>
    </li>
    <li>TITLE TWO
      <ol>
        <li>text 2 one</li>
        <li>text 2 two</li>
        <li>text 2 three</li>
        <li>text 2 four</li>
      </ol>
    </li>
    <li>TITLE THREE
      <ol>
        <li>text 3 one</li>
        <li>text 3 two</li>
        <li>text 3 three</li>
        <li>text 3 four</li>
        <li>text 3 five</li>
        <li>text 3 six</li>
      </ol>
    </li>
</ol></code>```

答:
You forgot your span tag inside ol and li tag

ol {
  counter-reset: item;
  padding: 0;
  margin: 0;
  margin-left: 20px !ie7;
}

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

li span,
li {
  display: block;
  overflow: hidden;
}

li:before {
  display: block;
  position: relative;
  content: counters(item, ".") ".";
  float: left;
}

ol>li {
  counter-increment: item;
}

ol li:before {
  width: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li><strong>Introduction</strong>
    <ol>
      <li><span>This document serves as an annexure to the Standard Terms and Conditions
and its sole purpose is to set out the specific conditions applicable to the type
of Finance Product you have selected to finance your Vehicle ("Annexure A").</span></li>
      <li><span>In the event of any inconsistency between the provisions of the Standard
Terms and Conditions and the provisions of this Annexure A, the provisions of
this Annexure A will prevail.</span></li>
      <li><span>We confirm that you have selected a CONTRACT PURCHASE Finance
Agreement for purposes of financing the Vehicle as described in the Schedule.</span></li>
      <li><span>Capitalised terms used, but not defined in this Annexure A shall have the same
meaning assigned to those terms as in the Standard Terms and Conditions.</span></li>
      <li><span>For purposes of this Annexure:</span>
        <ol>
          <li><span>"Acknowledgment of Receipt" means a written document acknowledging
receipt together with any inspection documents and Value Added Tax forms
issued by us when you Redeliver the Vehicle to us, which acknowledgement
confirms that you have relinquished possession of the Vehicle and have Retransferred
ownership of the Vehicle to us such that we become the owner of
the Vehicle (on the basis that we retain the Vehicle's registration papers in
the manner contemplated in this Agreement);</span>

            <li><span>"Deliver"/ "Delivered"/ "Delivery" means the delivery of the Vehicle by us
to you by either:</span>

              <ol>
                <li><span>where you are already in possession of the Vehicle, confirming our mutual
intention (as evidenced by a written Delivery Note which we will issue to you
and which must be signed and accepted by you) that you shall cease holding
the Vehicle in your possession for and on our behalf and retain possession of
the Vehicle with the intention of holding the Vehicle in your name on your
behalf as owner of the Vehicle; or</span></li>
              </ol>

            </li>
        </ol>
        </li>
    </ol>
    </li>
    <li>TITLE TWO
      <ol>
        <li>text 2 one</li>
        <li>text 2 two</li>
        <li>text 2 three</li>
        <li>text 2 four</li>
      </ol>
    </li>
    <li>TITLE THREE
      <ol>
        <li>text 3 one</li>
        <li>text 3 two</li>
        <li>text 3 three</li>
        <li>text 3 four</li>
        <li>text 3 five</li>
        <li>text 3 six</li>
      </ol>
    </li>
</ol></code>```

Body:
I need 1.5.2.1 in the list also alligned like the rest, what am I doing wrong? Please help me to adjust the css code to align the ordered list indent as seen at 1.5.2.1, I dont know what im doing wrong.

ol {
 counter-reset: item;
 padding: 0;
 margin: 0;
 margin-left: 20px !ie7;
}

ul {
 margin: 0;
 padding: 0;
 list-style: none;
}

li span, li {
    display: block;
    overflow: hidden;
}

li:before {
 display: block;
 position: relative;
 content: counters(item, ".") ".";
 float: left;
}
ol > li {
 counter-increment: item;

}
ol li:before {

 width: 50px;
}

Introduction

This document...

In the event...

We...

"Acknowledgment...

"Deliver"/ "Delivered"/...

where...

TITLE TWO

text 2 one

text 2 two

text 2 three

text 2 four

TITLE THREE

text 3 one

text 3 two

text 3 three

text 3 four

text 3 five

text 3 six

Body:
You forgot your span tag inside ol and li tag

ol {
  counter-reset: item;
  padding: 0;
  margin: 0;
  margin-left: 20px !ie7;
}

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

li span,
li {
  display: block;
  overflow: hidden;
}

li:before {
  display: block;
  position: relative;
  content: counters(item, ".") ".";
  float: left;
}

ol>li {
  counter-increment: item;
}

ol li:before {
  width: 50px;
}

<ol>
  <li><strong>Introduction</strong>
    <ol>
      <li><span>This document serves as an annexure to the Standard Terms and Conditions
and its sole purpose is to set out the specific conditions applicable to the type
of Finance Product you have selected to finance your Vehicle ("Annexure A").</span></li>
      <li><span>In the event of any inconsistency between the provisions of the Standard
Terms and Conditions and the provisions of this Annexure A, the provisions of
this Annexure A will prevail.</span></li>
      <li><span>We confirm that you have selected a CONTRACT PURCHASE Finance
Agreement for purposes of financing the Vehicle as described in the Schedule.</span></li>
      <li><span>Capitalised terms used, but not defined in this Annexure A shall have the same
meaning assigned to those terms as in the Standard Terms and Conditions.</span></li>
      <li><span>For purposes of this Annexure:</span>
        <ol>
          <li><span>"Acknowledgment of Receipt" means a written document acknowledging
receipt together with any inspection documents and Value Added Tax forms
issued by us when you Redeliver the Vehicle to us, which acknowledgement
confirms that you have relinquished possession of the Vehicle and have Retransferred
ownership of the Vehicle to us such that we become the owner of
the Vehicle (on the basis that we retain the Vehicle's registration papers in
the manner contemplated in this Agreement);</span>

            <li><span>"Deliver"/ "Delivered"/ "Delivery" means the delivery of the Vehicle by us
to you by either:</span>

              <ol>
                <li><span>where you are already in possession of the Vehicle, confirming our mutual
intention (as evidenced by a written Delivery Note which we will issue to you
and which must be signed and accepted by you) that you shall cease holding
the Vehicle in your possession for and on our behalf and retain possession of
the Vehicle with the intention of holding the Vehicle in your name on your
behalf as owner of the Vehicle; or</span></li>
              </ol>

            </li>
        </ol>
        </li>
    </ol>
    </li>
    <li>TITLE TWO
      <ol>
        <li>text 2 one</li>
        <li>text 2 two</li>
        <li>text 2 three</li>
        <li>text 2 four</li>
      </ol>
    </li>
    <li>TITLE THREE
      <ol>
        <li>text 3 one</li>
        <li>text 3 two</li>
        <li>text 3 three</li>
        <li>text 3 four</li>
        <li>text 3 five</li>
        <li>text 3 six</li>
      </ol>
    </li>
</ol>


问:
Persistent URL for GitHub wiki image across pushes
I am maintaining a page on a GitHub wiki. The page, which is in org-mode, embeds an image using the following syntax:

```<code>[[images/my-image.png]]
</code>```

I wanted to update the text and the image, so I performed these steps:

cloned that wiki from GitHub over SSH

changed some text elsewhere in the page

edited the image

staged the file for the page, and the image, in git

committed the staged files with git, and

pushed to GitHub over SSH.

No errors were reported, and the edits to the page show up. But the page still has the old image. And if I visit the URL for the image ( https://raw.githubusercontent.com/wiki/myuser/myrepo/images/git-flowchart.png ), I see the old image, not the new one, even if I refresh the tab in my browser.

Why isn't GitHub showing the new image, and what can I do about it? Is it at some commit-specific URL?

答:
It seems that this was due to some kind of caching problem or other lag.

After waiting for a few minutes and refreshing the browser tab again, the new image showed up.

Body:
I am maintaining a page on a GitHub wiki. The page, which is in org-mode, embeds an image using the following syntax:

[[images/my-image.png]]

I wanted to update the text and the image, so I performed these steps:

cloned that wiki from GitHub over SSH

changed some text elsewhere in the page

edited the image

staged the file for the page, and the image, in git

committed the staged files with git, and

pushed to GitHub over SSH.

No errors were reported, and the edits to the page show up. But the page still has the old image. And if I visit the URL for the image ( https://raw.githubusercontent.com/wiki/myuser/myrepo/images/git-flowchart.png ), I see the old image, not the new one, even if I refresh the tab in my browser.

Why isn't GitHub showing the new image, and what can I do about it? Is it at some commit-specific URL?


问:
How can i do a count of two columns in mysql?
i want to do a count of two columns in mysql. One of the columns is a string but another is a date like 06/08/2017 and when i do my query i get 0 results.

SELECT count(*) FROM `castigos` WHERE inicio_normal=05/06/2017 AND cod_emplazamiento=1```

I have entries of that data but its dont show me anything. Maybe the type of data in the date is wrong?

What should i do?

答:
WHERE inicio_normal=05/06/2017

If you divide 3 by 6 then by 2017 you get a very small value indeed. OTOH if you reformat this as a date (e.g. 20170605, if you gave us a European formatted date - dd/mm/yyyy) then your query will find the rows you showed us.

Body:
i want to do a count of two columns in mysql. One of the columns is a string but another is a date like 06/08/2017 and when i do my query i get 0 results.

SELECT count(*) FROM `castigos` WHERE inicio_normal=05/06/2017 AND cod_emplazamiento=1

I have entries of that data but its dont show me anything. Maybe the type of data in the date is wrong?

What should i do?


问:
IPN's/Ubercart and everything that comes with them: I want to make sure I have the money
Sorry if the title's a bit vaque, I promise I'll clear it up bellow:

First of all, a while ago I asked a question about selling serial keys :

How can I execute a custom script after purchase with Ubercart for Drupal

The information I posted there may help clear things up in this question but I doubt it much because this question is a  bit more general.

Basically, I don't want to execute my custom code until I know the payment  has been cleared and the moneys in my account. I was a bit unsure what the conditional action thats trigger is 'Customer completes check out' did though? When it says they completed checkout does it necessarily mean successfully and the money is in my account or not?

If not, how do I make Ubercart wait until it knows  I've got the money from any PSP (e.g. Google Checkout, PayPal, etc) to execute my custom code? I can't work it out, is it even possible?

答:
It's not documented or exposed as something that should be reliable but I think that using  the 'Customer completes check out' trigger is the way to go.

Bear in mind that the following applies to Ubercart 6.x-2.4. (Latest version as of today)

From what I looked at the code, it seems that the trigger is only executed on successful orders. Whether a successful order means that you have received payment, that depends a lot on your current configuration and the different payment gateways or method you are using, but in general situations and configuration.

That trigger is only launched from one function:

```<code>function uc_cart_complete_sale($order, $login = FALSE);
</code>```

If you do a module-wide search on when that function is executed, it should give you a rough idea on the different situations. Basically I found out that it's being executed from a few payment modules (paypal and 2checkout for example) as well as when you reach the cart/checkout/complete drupal page, which is generally on successful orders. The paypal module, which you specifically asked, seems to be calling that function when a 'Completed' IPN status is received.

It shouldn't be hard to try out a few purchases (right and wrong) and see if your trigger executes only when the order is properly charged.

Body:
It's not documented or exposed as something that should be reliable but I think that using  the 'Customer completes check out' trigger is the way to go.

Bear in mind that the following applies to Ubercart 6.x-2.4. (Latest version as of today)

From what I looked at the code, it seems that the trigger is only executed on successful orders. Whether a successful order means that you have received payment, that depends a lot on your current configuration and the different payment gateways or method you are using, but in general situations and configuration.

That trigger is only launched from one function:

function uc_cart_complete_sale($order, $login = FALSE);

If you do a module-wide search on when that function is executed, it should give you a rough idea on the different situations. Basically I found out that it's being executed from a few payment modules (paypal and 2checkout for example) as well as when you reach the cart/checkout/complete drupal page, which is generally on successful orders. The paypal module, which you specifically asked, seems to be calling that function when a 'Completed' IPN status is received.

It shouldn't be hard to try out a few purchases (right and wrong) and see if your trigger executes only when the order is properly charged.


问:
JavaScript comparing arrays failing when it shouldn't be
Problem:

Call two arms equally strong if the heaviest weights they each are able to lift are equal.

Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms.

Given your and your friend's arms' lifting capabilities find out if you two are equally strong.

Issue:

My solution keeps showing false when all numbers are equal. For example, when >you = [10, 15] and friend = [10, 15], I'm getting false when it should be true.
Sure it's user error over here. :)

function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {
    var you = [yourLeft, yourRight];
    var friend = [friendsLeft, friendsRight];
    you.sort(), friend.sort();
    console.log(you, friend)
    if(you === friend){
        return true;
    }else{
        return false;
    }
}```
</div>
</div>
</p>
<p>Fixed, thank  you!!</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>function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {
    var you = [yourLeft, yourRight];
    var friend = [friendsLeft, friendsRight];
    you.sort(), friend.sort();
    console.log(you, friend)
    for(var i = 0; i < you.length; i++) {
        if(you[i] !== friend[i])
            return false;
    }

    return true;
}</code>```

答:
One approach is converting the arrays to JSON objects. This one, works:</p>

```<code>function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {
var you = [yourLeft,yourRight];
var friend = [friendsLeft,friendsRight];
you.sort(), friend.sort();
you = JSON.stringify(you);
friend = JSON.stringify(friend);
console.log(you, friend)
if(you == friend){
    return true;
}else{
    return false;
}
}
</code>```

Body:
Problem:

Call two arms equally strong if the heaviest weights they each are able to lift are equal.

Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms.

Given your and your friend's arms' lifting capabilities find out if you two are equally strong.

Issue:

My solution keeps showing false when all numbers are equal. For example, when >you = [10, 15] and friend = [10, 15], I'm getting false when it should be true.
Sure it's user error over here. :)

function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {
    var you = [yourLeft, yourRight];
    var friend = [friendsLeft, friendsRight];
    you.sort(), friend.sort();
    console.log(you, friend)
    if(you === friend){
        return true;
    }else{
        return false;
    }
}

Fixed, thank  you!!

function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {
    var you = [yourLeft, yourRight];
    var friend = [friendsLeft, friendsRight];
    you.sort(), friend.sort();
    console.log(you, friend)
    for(var i = 0; i < you.length; i++) {
        if(you[i] !== friend[i])
            return false;
    }

    return true;
}

Body:
One approach is converting the arrays to JSON objects. This one, works:

function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {
var you = [yourLeft,yourRight];
var friend = [friendsLeft,friendsRight];
you.sort(), friend.sort();
you = JSON.stringify(you);
friend = JSON.stringify(friend);
console.log(you, friend)
if(you == friend){
    return true;
}else{
    return false;
}
}


问:
Nested Promise is not propagating error to parent Promise in Node.js?
I'm creating an API using Node.js/TypeScript running Express. Below is an excerpt from my get method. An error is being triggered in the format method, which throws an error that is caught by the promise, but not propagated to the parent promise after a throw:

```<code>            this.getModel(objectName).findAll(queryParameters).then(function(databaseObjects) {
                for (let databaseObject of databaseObjects) {
                    var jsonObject = {};
                    //console.log("Database object: ");
                    //console.log(databaseObject);
                    transform.baseFormat(databaseObject, jsonObject)
                    .then(() => transform.format(databaseObject, jsonObject))
                    .then(() => {
                        res.locals.retval.addData(jsonObject);
                    }).catch((e) => {
                        console.log("Caught error during format of existing object: ");
                        console.log(e);
                        throw e;
                    });
                }
            })
            .then(() => {
                if (metadata) {
                    this.metadata(objectName, false, transform, res.locals.retval);

                    delete queryParameters.limit;
                    delete queryParameters.offset;
                    console.log("RUNNING METADATA COUNT: ");
                    this.getModel(objectName).count(queryParameters).then(function(count) {
                        res.locals.retval.setMetadata("records", count);
                        return next();
                    }).catch(function(e) {
                        this.error(e, res);
                        return next();
                    });
                } else {
                    console.log("NO METADATA");
                    return next();
                }
            })
            .catch((e) => {
                // TODO: Move status into error() function
                console.log("500 Error on GET");
                console.error(e);
                res.locals.retval.addError(ErrorCode.InternalError, e);
                res.status(ErrorCode.InternalError).send(res.locals.retval);
                return next();
            });
</code>```

Here's the output:

```<code>(node:8277) Warning: a promise was created in a handler at /Library/WebServer/adstudio/dist/server.js:555:51 but was not returned from it, see
at Function.Promise.bind (/Library/WebServer/adstudio/node_modules/bluebird/js/release/bind.js:65:20)
Caught error during format of existing object:
Test Error
END FUNCTION HAS BEEN REACHED!
</code>```

Then the request fails to finish.

I've read a lot on Promises and I haven't been able to find an issue/solution similar to mine.

http://bluebirdjs.com/docs/warning-explanations.html

http://taoofcode.net/promise-anti-patterns/

https://www.reddit.com/r/javascript/comments/4bj6sm/am_i_wrong_to_be_annoyed_with_promise_error/

https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

Chained promises not passing on rejection

http://wiki.commonjs.org/wiki/Promises/A

https://promisesaplus.com/

答:
Running inside that for-loop is not asynchronous, so your promise is resolving basically as soon as the loop finishes, yet before all your formatting finishes.

Use a promise control flow, like bluebird's Promise.each which is serial or just Promise.all. Then any exceptions will be caught.

```<code>this.getModel(objectName).findAll(queryParameters).then(function (databaseObjects) {
  var promises = databaseObjects.map(databaseObject => {
    var jsonObject = {}
          // console.log("Database object: ");
          // console.log(databaseObject);
    return transform.baseFormat(databaseObject, jsonObject)
          .then(() => transform.format(databaseObject, jsonObject))
          .then(() => {
            res.locals.retval.addData(jsonObject)
          }).catch((e) => {
            console.log('Caught error during format of existing object: ')
            console.log(e)
            throw e
          })
  })
  return Promise.all(promises)
})
.catch((e) => {
    // TODO: Move status into error() function
  console.log('500 Error on GET')
  console.error(e)
  res.locals.retval.addError(ErrorCode.InternalError, e)
  res.status(ErrorCode.InternalError).send(res.locals.retval)
  return next()
})
</code>```

Body:
I'm creating an API using Node.js/TypeScript running Express. Below is an excerpt from my get method. An error is being triggered in the format method, which throws an error that is caught by the promise, but not propagated to the parent promise after a throw:

            this.getModel(objectName).findAll(queryParameters).then(function(databaseObjects) {
                for (let databaseObject of databaseObjects) {
                    var jsonObject = {};
                    //console.log("Database object: ");
                    //console.log(databaseObject);
                    transform.baseFormat(databaseObject, jsonObject)
                    .then(() => transform.format(databaseObject, jsonObject))
                    .then(() => {
                        res.locals.retval.addData(jsonObject);
                    }).catch((e) => {
                        console.log("Caught error during format of existing object: ");
                        console.log(e);
                        throw e;
                    });
                }
            })
            .then(() => {
                if (metadata) {
                    this.metadata(objectName, false, transform, res.locals.retval);

                    delete queryParameters.limit;
                    delete queryParameters.offset;
                    console.log("RUNNING METADATA COUNT: ");
                    this.getModel(objectName).count(queryParameters).then(function(count) {
                        res.locals.retval.setMetadata("records", count);
                        return next();
                    }).catch(function(e) {
                        this.error(e, res);
                        return next();
                    });
                } else {
                    console.log("NO METADATA");
                    return next();
                }
            })
            .catch((e) => {
                // TODO: Move status into error() function
                console.log("500 Error on GET");
                console.error(e);
                res.locals.retval.addError(ErrorCode.InternalError, e);
                res.status(ErrorCode.InternalError).send(res.locals.retval);
                return next();
            });

Here's the output:

(node:8277) Warning: a promise was created in a handler at /Library/WebServer/adstudio/dist/server.js:555:51 but was not returned from it, see
at Function.Promise.bind (/Library/WebServer/adstudio/node_modules/bluebird/js/release/bind.js:65:20)
Caught error during format of existing object:
Test Error
END FUNCTION HAS BEEN REACHED!

Then the request fails to finish.

I've read a lot on Promises and I haven't been able to find an issue/solution similar to mine.

http://bluebirdjs.com/docs/warning-explanations.html

http://taoofcode.net/promise-anti-patterns/

https://www.reddit.com/r/javascript/comments/4bj6sm/am_i_wrong_to_be_annoyed_with_promise_error/

https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

Chained promises not passing on rejection

http://wiki.commonjs.org/wiki/Promises/A

https://promisesaplus.com/

Body:
Running inside that for-loop is not asynchronous, so your promise is resolving basically as soon as the loop finishes, yet before all your formatting finishes.

Use a promise control flow, like bluebird's Promise.each which is serial or just Promise.all. Then any exceptions will be caught.

this.getModel(objectName).findAll(queryParameters).then(function (databaseObjects) {
  var promises = databaseObjects.map(databaseObject => {
    var jsonObject = {}
          // console.log("Database object: ");
          // console.log(databaseObject);
    return transform.baseFormat(databaseObject, jsonObject)
          .then(() => transform.format(databaseObject, jsonObject))
          .then(() => {
            res.locals.retval.addData(jsonObject)
          }).catch((e) => {
            console.log('Caught error during format of existing object: ')
            console.log(e)
            throw e
          })
  })
  return Promise.all(promises)
})
.catch((e) => {
    // TODO: Move status into error() function
  console.log('500 Error on GET')
  console.error(e)
  res.locals.retval.addError(ErrorCode.InternalError, e)
  res.status(ErrorCode.InternalError).send(res.locals.retval)
  return next()
})


问:
RethinkDB query filter against multiple values for single key
Heres my example db with 3 rows in it

```<code>{type:"a", info:""}
{type:"b", info:""}
{type:"c", info:""}
</code>```

Using rethink db how would i list all types of value a or b

// Here was my first solution but i can't dynamically build it

```<code>r.table("example").filter(r.row("type").eq("a").or("b")).run(conn, function(err, results){...});
</code>```

so if the next time i want types a and c i'm in trouble. I need a way to build a query. The cookbook example doesn't really make sense to me. Any ideas?

答:
You wrote r.row('type').eq('a').or('b'), but that doesn't do what you expect.

You probably want r.row('type').eq('a').or(r.row('type').eq('b'))

You could also write r.expr(['a', 'b']).contains(r.row('type'))

Body:
Heres my example db with 3 rows in it

{type:"a", info:""}
{type:"b", info:""}
{type:"c", info:""}

Using rethink db how would i list all types of value a or b

// Here was my first solution but i can't dynamically build it

r.table("example").filter(r.row("type").eq("a").or("b")).run(conn, function(err, results){...});

so if the next time i want types a and c i'm in trouble. I need a way to build a query. The cookbook example doesn't really make sense to me. Any ideas?


问:
Javascript and HTML5 Canvas
I am trying to make a drawing I made in the canvas change shape dynamically based on variables I pass in. what I have is that if want to change the shape of the monster or make it bigger, I have to change a lot of values to make it happen, how do I make all my number so that when I change it at 1 place, the change happens everywhere.
Here is the code on codepen

Javascript code

```<code>var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 0;
var width = 0;
var height = 0;
var radius = 0;

var squareLength = 450;

ctx.save();
ctx.beginPath();
ctx.fillStyle = '#33b262';
//Translate to the center of the canvas
ctx.translate(x+ 450, y+ 350);
ctx.rotate(Math.PI /4);
ctx.translate(x+ (-(squareLength / 2)), y+ (- (squareLength / 2)));
ctx.fillRect(x + 0,y+ 0,  width + squareLength, height+
squareLength);
ctx.restore();
ctx.closePath();

// eye
ctx.fillStyle = 'white';
ctx.beginPath();
ctx.arc(x + 450, y+ 210, radius+ 75, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fill();

// eye black filling
ctx.fillStyle = 'black';
ctx.beginPath();
ctx.arc(x + 450, y+ 210, radius+ 17, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fill();

//mouth
ctx.beginPath();
ctx.restore();
ctx.translate(x+ 250,y+ 100);
ctx.rect(x + 100,y+ 300, width + 200,height+ 70);
ctx.fillStyle = 'black';
ctx.fill();
ctx.closePath();

//left tooth
ctx.beginPath();
ctx.restore();
ctx.rect(x + 135,y+ 300, width + 30,height+ 30);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();

//right tooth
ctx.beginPath();
ctx.restore();
ctx.rect(x + 237,y+ 300, width + 30,height+ 30);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();

//bottom tooth
ctx.beginPath();
ctx.restore();
ctx.rect(x + 185,y+ 340, width + 30,height+ 30);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();

//left leg
ctx.beginPath();
ctx.fillStyle = '#800000';
ctx.moveTo(x + 303, y+ 465);
ctx.lineTo(x + 335, y+ 433);
ctx.lineTo(x + 335, y+ 615);
ctx.lineTo(x + 303, y+ 615);
ctx.fill();
ctx.closePath();

//right leg
ctx.beginPath();
ctx.fillStyle = '#800000';
ctx.moveTo(x + 97, y+ 465);
ctx.lineTo(x + 65, y+ 433);
ctx.lineTo(x + 65, y+ 615);
ctx.lineTo(x + 97, y+ 615);
ctx.fill();
ctx.closePath();

//right shoe
ctx.fillStyle = '#330000';
ctx.beginPath();
ctx.arc(x + 319, y+ 660, radius+ 65, 0, 1 * Math.PI, true);
ctx.closePath();
ctx.fill();

//right shoe
ctx.fillStyle = '#330000';
ctx.beginPath();
ctx.arc(x + 79, y+ 660, radius+ 65, 0, 1 * Math.PI, true);
ctx.closePath();
ctx.fill();
</code>```

答:
You can create a class for the drawing you are creating like VSO suggested like this..</p>

```<code>class Drawing {
    constructor(x, y, scale) {
        this.x = x;
        this.y = y;
        this.scale = scale;
    }

    get size() {
        return [Number(this.x) * Number(this.scale), Number(this.y) * Number(this.scale)];
    }

}
var draw = new Drawing(10, 15, 5);
document.write('(Scaled) X:' + draw.size[0] + ' Y:' + draw.size[1]);
</code>```

Title: Javascript and HTML5 Canvas

Body:
I am trying to make a drawing I made in the canvas change shape dynamically based on variables I pass in. what I have is that if want to change the shape of the monster or make it bigger, I have to change a lot of values to make it happen, how do I make all my number so that when I change it at 1 place, the change happens everywhere.
Here is the code on codepen

Javascript code

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 0;
var width = 0;
var height = 0;
var radius = 0;

var squareLength = 450;

ctx.save();
ctx.beginPath();
ctx.fillStyle = '#33b262';
//Translate to the center of the canvas
ctx.translate(x+ 450, y+ 350);
ctx.rotate(Math.PI /4);
ctx.translate(x+ (-(squareLength / 2)), y+ (- (squareLength / 2)));
ctx.fillRect(x + 0,y+ 0,  width + squareLength, height+
squareLength);
ctx.restore();
ctx.closePath();

// eye
ctx.fillStyle = 'white';
ctx.beginPath();
ctx.arc(x + 450, y+ 210, radius+ 75, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fill();

// eye black filling
ctx.fillStyle = 'black';
ctx.beginPath();
ctx.arc(x + 450, y+ 210, radius+ 17, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fill();

//mouth
ctx.beginPath();
ctx.restore();
ctx.translate(x+ 250,y+ 100);
ctx.rect(x + 100,y+ 300, width + 200,height+ 70);
ctx.fillStyle = 'black';
ctx.fill();
ctx.closePath();

//left tooth
ctx.beginPath();
ctx.restore();
ctx.rect(x + 135,y+ 300, width + 30,height+ 30);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();

//right tooth
ctx.beginPath();
ctx.restore();
ctx.rect(x + 237,y+ 300, width + 30,height+ 30);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();

//bottom tooth
ctx.beginPath();
ctx.restore();
ctx.rect(x + 185,y+ 340, width + 30,height+ 30);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();

//left leg
ctx.beginPath();
ctx.fillStyle = '#800000';
ctx.moveTo(x + 303, y+ 465);
ctx.lineTo(x + 335, y+ 433);
ctx.lineTo(x + 335, y+ 615);
ctx.lineTo(x + 303, y+ 615);
ctx.fill();
ctx.closePath();

//right leg
ctx.beginPath();
ctx.fillStyle = '#800000';
ctx.moveTo(x + 97, y+ 465);
ctx.lineTo(x + 65, y+ 433);
ctx.lineTo(x + 65, y+ 615);
ctx.lineTo(x + 97, y+ 615);
ctx.fill();
ctx.closePath();

//right shoe
ctx.fillStyle = '#330000';
ctx.beginPath();
ctx.arc(x + 319, y+ 660, radius+ 65, 0, 1 * Math.PI, true);
ctx.closePath();
ctx.fill();

//right shoe
ctx.fillStyle = '#330000';
ctx.beginPath();
ctx.arc(x + 79, y+ 660, radius+ 65, 0, 1 * Math.PI, true);
ctx.closePath();
ctx.fill();

Body:
You can create a class for the drawing you are creating like VSO suggested like this..

class Drawing {
    constructor(x, y, scale) {
        this.x = x;
        this.y = y;
        this.scale = scale;
    }

    get size() {
        return [Number(this.x) * Number(this.scale), Number(this.y) * Number(this.scale)];
    }

}
var draw = new Drawing(10, 15, 5);
document.write('(Scaled) X:' + draw.size[0] + ' Y:' + draw.size[1]);