问:
c++ - NRVO and move
I have read a few posts about move functions (http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html for example), and I wanted to observe move operators in action. So I tried the following code:

```<code>#include <vector>
#include <cassert>
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std;

vector<double> operator+(const vector<double>& a, const vector<double>& b){
  assert(a.size()==b.size());
  vector<double> result(a.size(),0);
    transform (a.begin(), a.end(), b.begin(), result.begin(), std::plus<double>());
  cout<<&result<<endl;
  return result;
}

int main(int argc, char const *argv[]) {
  vector<double> a,b;
  for (int i=0;i<10;i++){
    a.push_back(i);
    b.push_back(1);
  }
  std::vector<double> c=a+b;
  cout<<&c<<endl;
  return 0;
}
</code>```

I was expecting to obtain the same address for the local variable result and c since move operators are implemented for vector. And I obtained exactly that, but with and without the flag -std=c++11. That is when I learned about NRVO (c++11 Return value optimization or move?), so I disabled it with the flag -fno-elide-constructors and now the address is different, even with the flag -std=c++11. Is there an issue with my code or did I understand something wrong about move operators ?

From what I understood, returning by value should be enough for the move operator to kick in (C++11 rvalues and move semantics confusion (return statement)).

PS: I tried with GCC 6.3.0_1 and Apple LLVM version 8.1.0 .

EDIT

As pointed out, I should have checked result.data() instead of &result (see below). But in that case, I always found the same address, even without std=c++11 and with -fno-elide-constructors. See accepted answer and its comment section.

答:
Think of a move as an optimized copy. It is still a copy, so it is still a different vector but it has "moved" the underlying data from one vector to the other. You can see that by comparing the address of the data:

```<code>cout<<result.data()<<endl;
</code>```

and

```<code>cout<<c.data()<<endl;
</code>```

Copy elision on the other hand eliminates the copy entirely.

Title: c++ - NRVO and move

Body:
I have read a few posts about move functions (http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html for example), and I wanted to observe move operators in action. So I tried the following code:

#include <vector>
#include <cassert>
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std;

vector<double> operator+(const vector<double>& a, const vector<double>& b){
  assert(a.size()==b.size());
  vector<double> result(a.size(),0);
    transform (a.begin(), a.end(), b.begin(), result.begin(), std::plus<double>());
  cout<<&result<<endl;
  return result;
}

int main(int argc, char const *argv[]) {
  vector<double> a,b;
  for (int i=0;i<10;i++){
    a.push_back(i);
    b.push_back(1);
  }
  std::vector<double> c=a+b;
  cout<<&c<<endl;
  return 0;
}

I was expecting to obtain the same address for the local variable result and c since move operators are implemented for vector. And I obtained exactly that, but with and without the flag -std=c++11. That is when I learned about NRVO (c++11 Return value optimization or move?), so I disabled it with the flag -fno-elide-constructors and now the address is different, even with the flag -std=c++11. Is there an issue with my code or did I understand something wrong about move operators ?

From what I understood, returning by value should be enough for the move operator to kick in (C++11 rvalues and move semantics confusion (return statement)).

PS: I tried with GCC 6.3.0_1 and Apple LLVM version 8.1.0 .

EDIT

As pointed out, I should have checked result.data() instead of &result (see below). But in that case, I always found the same address, even without std=c++11 and with -fno-elide-constructors. See accepted answer and its comment section.

Body:
Think of a move as an optimized copy. It is still a copy, so it is still a different vector but it has "moved" the underlying data from one vector to the other. You can see that by comparing the address of the data:

cout<<result.data()<<endl;

and

cout<<c.data()<<endl;

Copy elision on the other hand eliminates the copy entirely.


来源: stackexchange

问:
character limit in a word inside a textarea dynamically
i am trying to put a limit on number of characters in a word. i am successful to find, if someone is entering more then 15 character.i am displaying a message right now. what i want to do is, if some one enter more then 15 characters ... the java script display a alert and then delete all letters leaving first 14 characters in that word. i tried to find some helpful functions but never found something useful.
i want to check for the character limit dynamically when the user is still entering.
my code is half complete but it has one flaw. it is displaying the message when a count is reaching more then 15 it displays a alert. now user can still save that string that has more than 15 char in a word. hope i explained it all.thanks to all,for everyone that is gonna put some effort in advance.</p>

```<code><textarea id="txt" name="area" onclick="checkcharactercount()"></textarea>

function checkcharactercount(){
  document.body.addEventListener('keyup', function(e) {
      var val = document.getElementById("txt").value;
      var string = val.split(" ");
      for(i=0;i<string.length; i++) {
        len = string[i].length;
        if (len >= 15) {
          alert('you have exceeded the maximum number of charaters in a word!!!');
          break;
        }
      }
  });
}
</code>```

答:
Does this work like you want it to?

var textArea = document.getElementById('txt');
textArea.addEventListener('keyup', function () {
  var val = textArea.value;
  var words = val.split(' ');
  for (var i = 0; i < words.length; i++) {
    if (words[i].length > 14) {
      // the word is longer than 14 characters, use only the first 14
      words[i] = words[i].slice(0, 14);
    }
  }

  // join the words together again and put them into the text area
  textArea.value = words.join(' ');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="txt" name="area"></textarea></code>```

ContentLicense: CC BY-SA 3.0

Body:
i am trying to put a limit on number of characters in a word. i am successful to find, if someone is entering more then 15 character.i am displaying a message right now. what i want to do is, if some one enter more then 15 characters ... the java script display a alert and then delete all letters leaving first 14 characters in that word. i tried to find some helpful functions but never found something useful.
i want to check for the character limit dynamically when the user is still entering.
my code is half complete but it has one flaw. it is displaying the message when a count is reaching more then 15 it displays a alert. now user can still save that string that has more than 15 char in a word. hope i explained it all.thanks to all,for everyone that is gonna put some effort in advance.

<textarea id="txt" name="area" onclick="checkcharactercount()"></textarea>

function checkcharactercount(){
  document.body.addEventListener('keyup', function(e) {
      var val = document.getElementById("txt").value;
      var string = val.split(" ");
      for(i=0;i<string.length; i++) {
        len = string[i].length;
        if (len >= 15) {
          alert('you have exceeded the maximum number of charaters in a word!!!');
          break;
        }
      }
  });
}

Body:
Does this work like you want it to?

var textArea = document.getElementById('txt');
textArea.addEventListener('keyup', function () {
  var val = textArea.value;
  var words = val.split(' ');
  for (var i = 0; i < words.length; i++) {
    if (words[i].length > 14) {
      // the word is longer than 14 characters, use only the first 14
      words[i] = words[i].slice(0, 14);
    }
  }

  // join the words together again and put them into the text area
  textArea.value = words.join(' ');
});

<textarea id="txt" name="area"></textarea>


问:
Updating data from Vuex get a infinite loop in watcher
I have a "dumb" component that just get props from a parent. The user can change a selector which fires an action (using Vuex) to get new data. When this new data has been received I want to pass it to the child and re-render that component with the new data. Unfortutalely I keep getting this warning in my watcher. Please help :slight_smile:

```<code>export default {
  name: 'bubbles',
  props: {
    awesomeData: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      title: 'Best component ever'
    }
  },
  watch: {
    awesomeData (newData) {
      console.log('hello world')
      this.refreshSomethingAwesome(newData)
    }
  },
  methods: {
    refreshSomethingAwesome (newData) {}
  }
}
</code>```

s

```<code>101 hello world
[Vue warn]: You may have an infinite update loop in watcher with expression "awesomeData"
</code>```

I'm trying a solution pretty much exactly the same as this: Vuex Examples
But can't seem to get it working... hmmm

答:
Found out the reason I was getting the loop was because I was actually trying to sort mutable data from the property (thought it was immutable)

```<code>let options = {
 children: newData.sort((a, b) => a.value - b.value)
}
</code>```

I changed it to something like:

```<code>const sortedNewData = [...newData].sort((a, b) => a.value - b.value)

let options = {
 children: sortedNewData
}
</code>```

Note: To prevent this across my app, I might wrap my initial state in a Map from immutable.js

```<code>import { Map, fromJS } from 'immutable'

const initialState = Map({
 awesomeData: fromJS([])
})
</code>```

Helpful article: alligator.io

Body:
I have a "dumb" component that just get props from a parent. The user can change a selector which fires an action (using Vuex) to get new data. When this new data has been received I want to pass it to the child and re-render that component with the new data. Unfortutalely I keep getting this warning in my watcher. Please help :slight_smile:

export default {
  name: 'bubbles',
  props: {
    awesomeData: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      title: 'Best component ever'
    }
  },
  watch: {
    awesomeData (newData) {
      console.log('hello world')
      this.refreshSomethingAwesome(newData)
    }
  },
  methods: {
    refreshSomethingAwesome (newData) {}
  }
}

s

101 hello world
[Vue warn]: You may have an infinite update loop in watcher with expression "awesomeData"

I'm trying a solution pretty much exactly the same as this: Vuex Examples
But can't seem to get it working... hmmm

Body:
Found out the reason I was getting the loop was because I was actually trying to sort mutable data from the property (thought it was immutable)

let options = {
 children: newData.sort((a, b) => a.value - b.value)
}

I changed it to something like:

const sortedNewData = [...newData].sort((a, b) => a.value - b.value)

let options = {
 children: sortedNewData
}

Note: To prevent this across my app, I might wrap my initial state in a Map from immutable.js

import { Map, fromJS } from 'immutable'

const initialState = Map({
 awesomeData: fromJS([])
})

Helpful article: alligator.io


问:
iOS App Crashes in release mode "undefined is not an object (evaluating 'e.propTypes.children')"
Crashes only in release mode. Then, in Schema setting, for release mode, I enabled the "debug executable" and ran and got the following error. I have no clue where this error is coming from. There is no stacktrace. How do I proceed further? Please help me.

[error][tid:com.facebook.react.JavaScript] undefined is not an object
  (evaluating 'e.propTypes.children')

Full System log below

```<code>Jun 10 10:03:03 My-MacBook-Pro assertiond[2748]: Submitted job with label: UIKitApplication:com.testdomian.testapp[0x894c][2748]
Jun 10 10:03:03 My-MacBook-Pro SpringBoard[2743]: [com.testdomian.testapp] Bootstrap complete with label: UIKitApplication:com.testdomian.testapp[0x894c][2748]
Jun 10 10:03:03 My-MacBook-Pro watchlistd[2807]: Now playing app did change to '(null)' (playing: 0) from '(null)'
Jun 10 10:03:03 My-MacBook-Pro watchlistd[2807]: WLKPlaybackSummary - Parameter failed validation bundleID. It is nil
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: assertion failed: 16F73 14E269: libxpc.dylib + 64131 [624BAF4F-2E03-34F8-ACBA-970B04637786]: 0x7d
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: Falling back to loading access token from NSUserDefaults because of simulator bug
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: Falling back to storing access token in NSUserDefaults because of simulator bug
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: Falling back to loading access token from NSUserDefaults because of simulator bug
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: Falling back to storing access token in NSUserDefaults because of simulator bug
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: Falling back to loading access token from NSUserDefaults because of simulator bug
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: Falling back to storing access token in NSUserDefaults because of simulator bug
Jun 10 10:03:03 My-MacBook-Pro assertiond[2748]: client <BSProcessHandle: 0x7fa250c05f10; testapp:5211; valid: YES> HWM increased to 1 because of <BKProcessAssertion: 0x7fa250c0b380; "FIRClearcutLogger.sendLogs" (finishTask:180s); id:…6CB5E848CE25>
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: [Firebase/Analytics][I-ACS023007] Firebase Analytics v.3700000 started
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled ()
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: *** -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: [Firebase/Analytics][I-ACS003007] Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: [Firebase/Analytics][I-ACS005000] The AdSupport Framework is not currently linked. Some features will not function properly.
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: [Firebase/Analytics][I-ACS023012] Firebase Analytics enabled
Jun 10 10:03:04 My-MacBook-Pro pasted[2756]: BundleID com.testdomian.testapp from team F9477J636M is requesting pasteboard fb_app_attribution
Jun 10 10:03:04 My-MacBook-Pro pasted[2756]: ...requesting pasteboard fb_app_attribution completed. Error: (null)
Jun 10 10:03:04 My-MacBook-Pro testapp[5211]: Normal message received by listener connection. Ignoring.
Jun 10 10:03:04 My-MacBook-Pro testapp[5211]: Could not successfully update network info during initialization.
Jun 10 10:03:04 My-MacBook-Pro testapp[5211]: undefined is not an object (evaluating 'e.propTypes.children')
Jun 10 10:03:04 My-MacBook-Pro testapp[5211]: Unhandled JS Exception: undefined is not an object (evaluating 'e.propTypes.children')
Jun 10 10:03:04 My-MacBook-Pro testapp[5211]: Module AppRegistry is not a registered callable module (calling runApplication)
Jun 10 10:03:04 My-MacBook-Pro testapp[5211]: *** Terminating app due to uncaught exception 'RCTFatalException: Unhandled JS Exception: undefined is not an object (evaluating 'e.propTypes.children')', reason: 'Unhandled JS Exception: undefined is not an object (evaluating 'e.propTypes..., stack:
    p@642:1226
    <unknown>@642:1289
    o@2:553
    <unknown>@482:671
    o@2:553
    <unknown>@430:226
    o@2:553
    <unknown>@429:79
    o@2:553
    <unknown>@428:79
    o@2:553
    <unknown>@43:176
    o@2:553
    <unknown>@13:72
    o@2:553
    <unknown>@12:30
    o@2:553
    i@2:266
    global code@1271:9
    '
    *** First throw call stack:
    (
        0   CoreFoundation                      0x000000010494cb0b __exceptionPreprocess + 171
        1   libobjc.A.dylib                     0x0000000103802141 objc_exception_throw + 48
        2   CoreFoundation                      0x00000001049b5625 +[NSException raise:format:] + 197
        3   testapp                            0x0000000102902670 RCTFatal + 393
        4   testapp                            0x00000001028fbb7d -[RCTExceptionsManager reportFatalException:stack:exceptionId:] + 507
        5   CoreFoundation                      0x00000001048d4c6c __invoking___ + 140
        6   CoreFoundation                      0x00000001048d4b40 -[NSInvocation invoke] + 320
        7   CoreFoundation                      0x00000001048ec956 -[NSInvocation invokeWithTarget:] + 54
        8   testapp                            0x00000001028ff6ab -[RCTModuleMethod invokeWithBridge:module:arguments:] + 551
        9   testapp                            0x0000000102926985 -[RCTBatchedBridge callNativeModule:method:params:] + 229
        10  testapp                            0x0000000102926223 __33-[RCTBatchedBridge handleBuffer:]_block_invoke.352 + 509
        11  libdispatch.dylib                   0x0000000106c3e585 _dispatch_call_block_and_release + 12
        12  libdispatch.dylib                   0x0000000106c5f792 _dispatch_client_callout + 8
        13  libdispatch.dylib                   0x0000000106c45237 _dispatch_queue_serial_drain + 1022
        14  libdispatch.dylib                   0x0000000106c4598f _dispatch_queue_invoke + 1053
        15  libdispatch.dylib                   0x0000000106c45d31 _dispatch_queue_override_invoke + 374
        16  libdispatch.dylib                   0x0000000106c47899 _dispatch_root_queue_drain + 813
        17  libdispatch.dylib                   0x0000000106c4750d _dispatch_worker_thread3 + 113
        18  libsystem_pthread.dylib             0x000000010890a5a2 _pthread_wqthread + 1299
        19  libsystem_pthread.dylib             0x000000010890a07d start_wqthread + 13
    )
Jun 10 10:03:04 My-MacBook-Pro SpringBoard[2743]: [KeyboardArbiter] HW kbd: Failed to set (null) as keyboard focus
Jun 10 10:03:04 My-MacBook-Pro SpringBoard[2743]: UNSUserNotificationServerConnectionListener connection invalidated
Jun 10 10:03:04 My-MacBook-Pro com.apple.CoreSimulator.SimDevice.C3124FEB-FBFB-4DF6-9906-6E7CEF350078.launchd_sim[2726] (UIKitApplication:com.testdomian.testapp[0x894c][2748][5211]): Service exited due to Abort trap: 6
Jun 10 10:03:04 My-MacBook-Pro backboardd[2744]: [Common] Unable to get short BSD proc info for 5211: No such process
Jun 10 10:03:04 My-MacBook-Pro backboardd[2744]: [Common] Unable to get proc info for 5211: Undefined error: 0
Jun 10 10:03:04 My-MacBook-Pro assertiond[2748]: Deleted job with label: UIKitApplication:com.testdomian.testapp[0x894c][2748]
Jun 10 10:03:04 My-MacBook-Pro watchlistd[2807]: Now playing app did change to '(null)' (playing: 0) from '(null)'
Jun 10 10:03:04 My-MacBook-Pro watchlistd[2807]: WLKPlaybackSummary - Parameter failed validation bundleID. It is nil
</code>```

答:
Check what is the different in your schemas Debug Vs Release.
Ex: Optimization Level in build settings.</p>

Body:
Crashes only in release mode. Then, in Schema setting, for release mode, I enabled the "debug executable" and ran and got the following error. I have no clue where this error is coming from. There is no stacktrace. How do I proceed further? Please help me.

[error][tid:com.facebook.react.JavaScript] undefined is not an object
  (evaluating 'e.propTypes.children')

Full System log below

Jun 10 10:03:03 My-MacBook-Pro assertiond[2748]: Submitted job with label: UIKitApplication:com.testdomian.testapp[0x894c][2748]
Jun 10 10:03:03 My-MacBook-Pro SpringBoard[2743]: [com.testdomian.testapp] Bootstrap complete with label: UIKitApplication:com.testdomian.testapp[0x894c][2748]
Jun 10 10:03:03 My-MacBook-Pro watchlistd[2807]: Now playing app did change to '(null)' (playing: 0) from '(null)'
Jun 10 10:03:03 My-MacBook-Pro watchlistd[2807]: WLKPlaybackSummary - Parameter failed validation bundleID. It is nil
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: assertion failed: 16F73 14E269: libxpc.dylib + 64131 [624BAF4F-2E03-34F8-ACBA-970B04637786]: 0x7d
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: Falling back to loading access token from NSUserDefaults because of simulator bug
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: Falling back to storing access token in NSUserDefaults because of simulator bug
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: Falling back to loading access token from NSUserDefaults because of simulator bug
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: Falling back to storing access token in NSUserDefaults because of simulator bug
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: Falling back to loading access token from NSUserDefaults because of simulator bug
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: Falling back to storing access token in NSUserDefaults because of simulator bug
Jun 10 10:03:03 My-MacBook-Pro assertiond[2748]: client <BSProcessHandle: 0x7fa250c05f10; testapp:5211; valid: YES> HWM increased to 1 because of <BKProcessAssertion: 0x7fa250c0b380; "FIRClearcutLogger.sendLogs" (finishTask:180s); id:…6CB5E848CE25>
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: [Firebase/Analytics][I-ACS023007] Firebase Analytics v.3700000 started
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled ()
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: *** -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: [Firebase/Analytics][I-ACS003007] Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: [Firebase/Analytics][I-ACS005000] The AdSupport Framework is not currently linked. Some features will not function properly.
Jun 10 10:03:03 My-MacBook-Pro testapp[5211]: [Firebase/Analytics][I-ACS023012] Firebase Analytics enabled
Jun 10 10:03:04 My-MacBook-Pro pasted[2756]: BundleID com.testdomian.testapp from team F9477J636M is requesting pasteboard fb_app_attribution
Jun 10 10:03:04 My-MacBook-Pro pasted[2756]: ...requesting pasteboard fb_app_attribution completed. Error: (null)
Jun 10 10:03:04 My-MacBook-Pro testapp[5211]: Normal message received by listener connection. Ignoring.
Jun 10 10:03:04 My-MacBook-Pro testapp[5211]: Could not successfully update network info during initialization.
Jun 10 10:03:04 My-MacBook-Pro testapp[5211]: undefined is not an object (evaluating 'e.propTypes.children')
Jun 10 10:03:04 My-MacBook-Pro testapp[5211]: Unhandled JS Exception: undefined is not an object (evaluating 'e.propTypes.children')
Jun 10 10:03:04 My-MacBook-Pro testapp[5211]: Module AppRegistry is not a registered callable module (calling runApplication)
Jun 10 10:03:04 My-MacBook-Pro testapp[5211]: *** Terminating app due to uncaught exception 'RCTFatalException: Unhandled JS Exception: undefined is not an object (evaluating 'e.propTypes.children')', reason: 'Unhandled JS Exception: undefined is not an object (evaluating 'e.propTypes..., stack:
    p@642:1226
    <unknown>@642:1289
    o@2:553
    <unknown>@482:671
    o@2:553
    <unknown>@430:226
    o@2:553
    <unknown>@429:79
    o@2:553
    <unknown>@428:79
    o@2:553
    <unknown>@43:176
    o@2:553
    <unknown>@13:72
    o@2:553
    <unknown>@12:30
    o@2:553
    i@2:266
    global code@1271:9
    '
    *** First throw call stack:
    (
        0   CoreFoundation                      0x000000010494cb0b __exceptionPreprocess + 171
        1   libobjc.A.dylib                     0x0000000103802141 objc_exception_throw + 48
        2   CoreFoundation                      0x00000001049b5625 +[NSException raise:format:] + 197
        3   testapp                            0x0000000102902670 RCTFatal + 393
        4   testapp                            0x00000001028fbb7d -[RCTExceptionsManager reportFatalException:stack:exceptionId:] + 507
        5   CoreFoundation                      0x00000001048d4c6c __invoking___ + 140
        6   CoreFoundation                      0x00000001048d4b40 -[NSInvocation invoke] + 320
        7   CoreFoundation                      0x00000001048ec956 -[NSInvocation invokeWithTarget:] + 54
        8   testapp                            0x00000001028ff6ab -[RCTModuleMethod invokeWithBridge:module:arguments:] + 551
        9   testapp                            0x0000000102926985 -[RCTBatchedBridge callNativeModule:method:params:] + 229
        10  testapp                            0x0000000102926223 __33-[RCTBatchedBridge handleBuffer:]_block_invoke.352 + 509
        11  libdispatch.dylib                   0x0000000106c3e585 _dispatch_call_block_and_release + 12
        12  libdispatch.dylib                   0x0000000106c5f792 _dispatch_client_callout + 8
        13  libdispatch.dylib                   0x0000000106c45237 _dispatch_queue_serial_drain + 1022
        14  libdispatch.dylib                   0x0000000106c4598f _dispatch_queue_invoke + 1053
        15  libdispatch.dylib                   0x0000000106c45d31 _dispatch_queue_override_invoke + 374
        16  libdispatch.dylib                   0x0000000106c47899 _dispatch_root_queue_drain + 813
        17  libdispatch.dylib                   0x0000000106c4750d _dispatch_worker_thread3 + 113
        18  libsystem_pthread.dylib             0x000000010890a5a2 _pthread_wqthread + 1299
        19  libsystem_pthread.dylib             0x000000010890a07d start_wqthread + 13
    )
Jun 10 10:03:04 My-MacBook-Pro SpringBoard[2743]: [KeyboardArbiter] HW kbd: Failed to set (null) as keyboard focus
Jun 10 10:03:04 My-MacBook-Pro SpringBoard[2743]: UNSUserNotificationServerConnectionListener connection invalidated
Jun 10 10:03:04 My-MacBook-Pro com.apple.CoreSimulator.SimDevice.C3124FEB-FBFB-4DF6-9906-6E7CEF350078.launchd_sim[2726] (UIKitApplication:com.testdomian.testapp[0x894c][2748][5211]): Service exited due to Abort trap: 6
Jun 10 10:03:04 My-MacBook-Pro backboardd[2744]: [Common] Unable to get short BSD proc info for 5211: No such process
Jun 10 10:03:04 My-MacBook-Pro backboardd[2744]: [Common] Unable to get proc info for 5211: Undefined error: 0
Jun 10 10:03:04 My-MacBook-Pro assertiond[2748]: Deleted job with label: UIKitApplication:com.testdomian.testapp[0x894c][2748]
Jun 10 10:03:04 My-MacBook-Pro watchlistd[2807]: Now playing app did change to '(null)' (playing: 0) from '(null)'
Jun 10 10:03:04 My-MacBook-Pro watchlistd[2807]: WLKPlaybackSummary - Parameter failed validation bundleID. It is nil


问:
only the first email is being sent in a For Loop of a Window Service
I want to send an email to more than 2 people using my own database.
So I use for loop to send an email. But it is just sent it to a first person.
I also check that the email_data has more than 2, and I bring the email data well.
Here is my code.</p>

```<code>    private void Email()
    {
        DataTable email_data = GetEmailData();
           .....
                String from = "aa@gmail.com";

                for (int i = 0; i <= email_data.Rows.Count; i++)
                {
                    String to = email_data.Rows[i][0].ToString();

                    using (MailMessage mm = new MailMessage(from, to))
                    {

                        SmtpClient smtp = new SmtpClient();
                        mm.Subject = "List";
                        mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "List.xlsx"));
                        mm.IsBodyHtml = true;

                        smtp.Host = "smtp.gmail.com";
                        smtp.EnableSsl = true;
                        System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
                        credentials.UserName = "aa@gmail.com";
                        credentials.Password = "aa";
                        smtp.UseDefaultCredentials = true;
                        smtp.Credentials = credentials;
                        smtp.Port = 587;
   //works well in the first loop, but stops here in the second loop
                        smtp.Send(mm);
                    }
                }
        }
</code>```

答:
I tried to run your code on my computer (I just replaced credentials with my private gmail account credentials) and it worked without any problem - emails was successfully sent to 3 different email addresses. So problem might be related to your computer. So here are a few ideas what you can try:

run your program on different computer to see if it works there (for
comparison, I run it successfully on Windows 10 Home, Visual Studio 2017 CE, Console Application targeting .NET Framework 4.7)

check your antivirus and firewall if they are not somehow blocking mass email sending.

try to debug source code of SmtpClient.Send() method to see where
exactly execution stops, which should give you a hint what is wrong
and how to fix it.

in app.config enable detailed logging of network communication and see if there isn't some problem when connecting to SMTP server.

BTW there is probably bug: for (int i = 0; i <= email_data.Rows.Count; i++) should be for (int i = 0; i < email_data.Rows.Count; i++)

Body:
I want to send an email to more than 2 people using my own database.
So I use for loop to send an email. But it is just sent it to a first person.
I also check that the email_data has more than 2, and I bring the email data well.
Here is my code.

    private void Email()
    {
        DataTable email_data = GetEmailData();
           .....
                String from = "aa@gmail.com";

                for (int i = 0; i <= email_data.Rows.Count; i++)
                {
                    String to = email_data.Rows[i][0].ToString();

                    using (MailMessage mm = new MailMessage(from, to))
                    {

                        SmtpClient smtp = new SmtpClient();
                        mm.Subject = "List";
                        mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "List.xlsx"));
                        mm.IsBodyHtml = true;

                        smtp.Host = "smtp.gmail.com";
                        smtp.EnableSsl = true;
                        System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
                        credentials.UserName = "aa@gmail.com";
                        credentials.Password = "aa";
                        smtp.UseDefaultCredentials = true;
                        smtp.Credentials = credentials;
                        smtp.Port = 587;
   //works well in the first loop, but stops here in the second loop
                        smtp.Send(mm);
                    }
                }
        }


问:
javax.servlet.jsp.JspException: No collection found
```<code>This is my arraylist for index 17
</code>```

    In this code may have data list or may not. Data is dispay when there are records. Not handled for no records

Java code:

```<code> //To avoid arrayindexoutofbound exception length checked
    if (resultList.length >17) {
    statisticsDetails.setqNames(resultList[17]);
    //System.out.println(resultList[17]);
    String[]  qName=resultList[17].split("\\^");

   List<StatisticsDetails> statisticsDetailsList = new ArrayList<StatisticsDetails>();
    for (String queueName:qName  ){
    StatisticsDetails  details = new StatisticsDetails();
    String[] splitQueues = queueName.split("=");
    details.setqKey(splitQueues[0]);
    details.setqCount(splitQueues[1]);
    statisticsDetailsList.add(details);
    }
    statisticsDetails.setqNamesList(statisticsDetailsList);
    }
</code>```

Jsp  code:

```<code><logic:iterate id="iteratorId" name="statistics.statisticsDetails" property="qNamesList">
<tr>
<td class="col-sm-6 col-md-6 col-lg-6"><bean:write name="iteratorId" property="qKey" /></td>
<td class="col-sm-6 col-md-6 col-lg-6"><bean:write name="iteratorId" property="qCount" /></td>
</tr>
</logic:iterate>
</code>```

how to avoid arraybound error and JSP to handle  when no data found

答:
Use a null check using JSTL(Do not forget to import the tag library):
 import core library:
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
and then use:

<c:if test="${not empty statistics.statisticsDetails}">
        //keep your code here to iterate the list
 </c:if>

Or use:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
and then:

<c:if test="${fn:length(statistics.statisticsDetails) > 0}">
  //keep your code here to iterate the list
</c:if>

Body:
This is my arraylist for index 17

    In this code may have data list or may not. Data is dispay when there are records. Not handled for no records

Java code:

 //To avoid arrayindexoutofbound exception length checked
    if (resultList.length >17) {
    statisticsDetails.setqNames(resultList[17]);
    //System.out.println(resultList[17]);
    String[]  qName=resultList[17].split("\\^");

   List<StatisticsDetails> statisticsDetailsList = new ArrayList<StatisticsDetails>();
    for (String queueName:qName  ){
    StatisticsDetails  details = new StatisticsDetails();
    String[] splitQueues = queueName.split("=");
    details.setqKey(splitQueues[0]);
    details.setqCount(splitQueues[1]);
    statisticsDetailsList.add(details);
    }
    statisticsDetails.setqNamesList(statisticsDetailsList);
    }

Jsp  code:

<logic:iterate id="iteratorId" name="statistics.statisticsDetails" property="qNamesList">

<bean:write name="iteratorId" property="qKey" />
<bean:write name="iteratorId" property="qCount" />

</logic:iterate>

how to avoid arraybound error and JSP to handle  when no data found


问:
Does  have significance to search engines?
The corporate guidlines at my company stipulate that our product names are written in a strange and "wonderful" way [oh how we all love Marketing departments!].

A product name such as "iPhone" is written with the "i" as bold and italic. E.g.

iPhone

I don't want search engines to segment the context of the bold/italic text - for example the above should just be read by a search engine as "iPhone", and not !! I !! Phone.

Just want to check if anyone knows for sure that

```<code><span class="branding">i</span>Phone
</code>```

Would not apply any additional significance to the "i"?

Many thanks

答: <span> is an inline formatting element, and thus has no SEO value at all. HTML tags like <strong> on the other hand have some but very very little SEO significance. Anyway, the crawler will know exactly that you mean iPhone even with the 'i' being between a <span> tag.</p>

ContentLicense: CC BY-SA 2.5

Title: Does <span> have significance to search engines?

Body:
The corporate guidlines at my company stipulate that our product names are written in a strange and "wonderful" way [oh how we all love Marketing departments!].

A product name such as "iPhone" is written with the "i" as bold and italic. E.g.

iPhone

I don't want search engines to segment the context of the bold/italic text - for example the above should just be read by a search engine as "iPhone", and not !! I !! Phone.

Just want to check if anyone knows for sure that

iPhone

Would not apply any additional significance to the "i"?

Many thanks


问:
Eclipse C problems with including .h files
I am trying to compile a code. I have the following Structure

```<code>RLW/RLW.c (inside a folder)
RLW/RLW.h
main.c
</code>```

In the main.c if I have the following line

```<code>#include "RLW.h"
</code>```

It does NOT COMPILE and the line has the error RLW.h no such file or directory

if I put the following line in main.c

```<code>#include "RLW/RLW.h"
</code>```

The  code COMPILES but there is still the error RLW.h no such file or directory.

I have added the path to the RLW Folder in

Properties->C/C++ General -> Paths and Symbols -> Includes -> GNU C

Any help on how to fix the error?

答: You have mentioned that inside folder RLW, RLW.h file is available. main.c is present in current working directory(CWD). So to include the folders present in CWD you need to give path as "./folder/xyz.c".Hence giving the include line as #include "./RLW/RLW.h" will solve your problem

Body:
I am trying to compile a code. I have the following Structure

RLW/RLW.c (inside a folder)
RLW/RLW.h
main.c

In the main.c if I have the following line

#include "RLW.h"

It does NOT COMPILE and the line has the error RLW.h no such file or directory

if I put the following line in main.c

#include "RLW/RLW.h"

The  code COMPILES but there is still the error RLW.h no such file or directory.

I have added the path to the RLW Folder in

Properties->C/C++ General -> Paths and Symbols -> Includes -> GNU C

Any help on how to fix the error?


问:
Setting a relative path to sqlite database with Delphi and Firedac
In replacement of my previous question which was confusing and poorly formulated, here is the "real" question.

I would like to known how to set, with Firedac, at runtime, a relative path to a sqlite database located in a subfolder of my application folder.

As Jerry Dodge stated :

Any application should never rely on writable data in the same directory anyway. Also, even if you did, you should make sure all your paths are relative to the application at least.

At the moment, the application I have in mind is portable and I would like the database file to be stored in a sub-folder of the main exe folder.

On the Form.Create event of my main form, is used first

```<code>path := ExtractFilePath(Application.ExeName);
</code>```

And in then for FDConnection :

```<code>with FDConnection1 do begin
  Close;
  with Params do begin
    Clear;
    Add('DriverID=SQLite');
    Add('Database='+path+'Data\sqlite.db');
  end;
  Open;
end;
</code>```

I keep on getting an error saying "unable to open database file".

I don't want to set the path to the database file in the FiredDac Connection Editor because then it would be absolute and bound to my machine, right ?

How could I set this path to the database file so that it would work in any configuration, wherever the user puts the application folder ?

Thank you all in advance

Math

答:
Introduction

IMHO

Database path and server name  should not be hardcoded in applivcation.

Why ?

When you work on a project, you need to do many things on database connection, setting datasets, query etc. Usualy this is done on working database. Then server name and database path are different from those of the real database.

You should be able to set up server name and path to database easy and without to compile the project. This allows to set properly database connection params on a random computer.

Solution :

Setup the database connection component on design time, do not create it in runtime. Setup all parameters including server name , database path, charset etc. to your working copy of database. This will allow you to set up the other components associated with this database on design time.
(In your answer I see you have done almost the same.)

Save server name, database path and any other parameter you want, to an exterrnal resource, ini file, windows registry or something else. Then get these parameters when application started or before connect to database.

In your case, you use local server and  the same path as application, so you don't need to store nothing.

Regarding the question

The code :

```<code>with FDConnection1 do begin
  Close;
  with Params do begin
    Clear;  <-- this removes all parameters
    Add('DriverID=SQLite');
    Add('Database='+path+'Data\sqlite.db');
  end;
  Open;
end;
</code>```

removes all other parameters except DriverID and Database. Probably the error arise from that.

If you already setting all parameters in FDConnection:

Do not use:

```<code>FDConnection.Params.Add('Database='+path+'Data\sqlite.db');
</code>```

This will add new parameter with the same name,  but connection will use the first one.

This explains why everything works in your answer, because you did not set a parameter 'Database' on design time:

THIRD STEP was to drop a FDConnection on the datamodule and set all
  parameters EXCEPT database file.

Instead use :

```<code>FDConnection.Params.Database := 'Database='+path+'Data\sqlite.db';
</code>```

You may use this for example in
  OnDataModuleCreate or FDConnectionBeforeConnect events

I hope this will be useful.

Body:
In replacement of my previous question which was confusing and poorly formulated, here is the "real" question.

I would like to known how to set, with Firedac, at runtime, a relative path to a sqlite database located in a subfolder of my application folder.

As Jerry Dodge stated :

Any application should never rely on writable data in the same directory anyway. Also, even if you did, you should make sure all your paths are relative to the application at least.

At the moment, the application I have in mind is portable and I would like the database file to be stored in a sub-folder of the main exe folder.

On the Form.Create event of my main form, is used first

path := ExtractFilePath(Application.ExeName);

And in then for FDConnection :

with FDConnection1 do begin
  Close;
  with Params do begin
    Clear;
    Add('DriverID=SQLite');
    Add('Database='+path+'Data\sqlite.db');
  end;
  Open;
end;

I keep on getting an error saying "unable to open database file".

I don't want to set the path to the database file in the FiredDac Connection Editor because then it would be absolute and bound to my machine, right ?

How could I set this path to the database file so that it would work in any configuration, wherever the user puts the application folder ?

Thank you all in advance

Math

Body:
Introduction

IMHO

Database path and server name  should not be hardcoded in applivcation.

Why ?

When you work on a project, you need to do many things on database connection, setting datasets, query etc. Usualy this is done on working database. Then server name and database path are different from those of the real database.

You should be able to set up server name and path to database easy and without to compile the project. This allows to set properly database connection params on a random computer.

Solution :

Setup the database connection component on design time, do not create it in runtime. Setup all parameters including server name , database path, charset etc. to your working copy of database. This will allow you to set up the other components associated with this database on design time.
(In your answer I see you have done almost the same.)

Save server name, database path and any other parameter you want, to an exterrnal resource, ini file, windows registry or something else. Then get these parameters when application started or before connect to database.

In your case, you use local server and  the same path as application, so you don't need to store nothing.

Regarding the question

The code :

with FDConnection1 do begin
  Close;
  with Params do begin
    Clear;  <-- this removes all parameters
    Add('DriverID=SQLite');
    Add('Database='+path+'Data\sqlite.db');
  end;
  Open;
end;

removes all other parameters except DriverID and Database. Probably the error arise from that.

If you already setting all parameters in FDConnection:

Do not use:

FDConnection.Params.Add('Database='+path+'Data\sqlite.db');

This will add new parameter with the same name,  but connection will use the first one.

This explains why everything works in your answer, because you did not set a parameter 'Database' on design time:

THIRD STEP was to drop a FDConnection on the datamodule and set all
  parameters EXCEPT database file.

Instead use :

FDConnection.Params.Database := 'Database='+path+'Data\sqlite.db';

You may use this for example in
  OnDataModuleCreate or FDConnectionBeforeConnect events

I hope this will be useful.


问:
Is it necessary to remove the installed version before installing another version of the same package in R?
Say I want to install dev version of data.table, the recommended command is:

```<code>remove.packages("data.table")
install.packages("data.table", type = "source",
    repos = "http://Rdatatable.github.io/data.table")
</code>```

My question is: Is it necessary to remove the currently installed version first? Is there any danger if I install the new version without removing exisiting version?

答:
If you install a package into the default library, a new version completely replaces the old version. You don't need to remove the old version manually.

Of course, this requires the package to not be loaded when you install the new version.

Body:
Say I want to install dev version of data.table, the recommended command is:

remove.packages("data.table")
install.packages("data.table", type = "source",
    repos = "http://Rdatatable.github.io/data.table")

My question is: Is it necessary to remove the currently installed version first? Is there any danger if I install the new version without removing exisiting version?


问:
String concatenation without strcat in C
I am having trouble concatenating strings in C, without strcat library function. Here is my code

```<code>#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
  char *a1=(char*)malloc(100);
  strcpy(a1,"Vivek");
  char *b1=(char*)malloc(100);
  strcpy(b1,"Ratnavel");
  int i;
  int len=strlen(a1);

  for(i=0;i<strlen(b1);i++)
  {
     a1[i+len]=b1[i];
  }

  a1[i+len]='\0';
  printf("\n\n A: %s",a1);

  return 0;
}
</code>```

I made corrections to the code. This is working. Now can I do it without strcpy?

答:
Problems:

length isn't a function. strlen is, but you probably shouldn't call it in a loop - b1's length won't change on us, will it? Also, it returns a size_t, which may be the same size as int on your platform but will be unsigned. This can (but usually won't) cause errors, but you should do it right anyway.

a1 only has enough space for the first string, because the compiler doesn't know to allocate extra stack space for the rest of the string since. If you provide an explicit size, like [100], that should be enough for your purposes. If you need robust code that doesn't make assumptions about what is "enough", you should look into malloc and friends, though that may be a lesson for another day.

Your loop stops too early. i < b1_len (assuming you have a variable, b1_len, that was set to the length of b1 before the loop began) would be sufficient - strlen doesn't count the '\0' at the end.

But speaking of counting the '\0' at the end, a slightly more efficient implementation could use sizeof a1 - 1 instead of strlen(a1) in this case, since a1 (and b1) are declared as arrays, not pointers. It's your choice, but remember that sizeof won't work for pointers, so don't get them mixed up.

EDIT: New problems:

char *p = malloc(/*some*/); p = /* something */ is a problem. = with pointers doesn't copy contents, it copies the value, so you're throwing away the old pointer value you got from malloc. To copy the contents of a string into a char * (or a char [] for that matter) you'd need to use strcpy, strncpy, or (my preference) memcpy. (Or just a loop, but that's rather silly. Then again, it may be good practice if you're writing your own strcat.)

Unless you're using C++, I wouldn't cast the return value of malloc, but that's a religious war and we don't need one of those.

If you have strdup, use it. If you don't, here is a working implementation:

```<code>char *strdup(const char *c)
{
    size_t l = strlen(c);
    char *d = malloc(l + 1);
    if(d) memcpy(d, c, l + 1);
    return d;
}
</code>```

It is one of the most useful functions not in the C standard library.

Body:
I am having trouble concatenating strings in C, without strcat library function. Here is my code

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
  char *a1=(char*)malloc(100);
  strcpy(a1,"Vivek");
  char *b1=(char*)malloc(100);
  strcpy(b1,"Ratnavel");
  int i;
  int len=strlen(a1);

  for(i=0;i<strlen(b1);i++)
  {
     a1[i+len]=b1[i];
  }

  a1[i+len]='\0';
  printf("\n\n A: %s",a1);

  return 0;
}

I made corrections to the code. This is working. Now can I do it without strcpy?

Body:
Problems:

length isn't a function. strlen is, but you probably shouldn't call it in a loop - b1's length won't change on us, will it? Also, it returns a size_t, which may be the same size as int on your platform but will be unsigned. This can (but usually won't) cause errors, but you should do it right anyway.

a1 only has enough space for the first string, because the compiler doesn't know to allocate extra stack space for the rest of the string since. If you provide an explicit size, like [100], that should be enough for your purposes. If you need robust code that doesn't make assumptions about what is "enough", you should look into malloc and friends, though that may be a lesson for another day.

Your loop stops too early. i < b1_len (assuming you have a variable, b1_len, that was set to the length of b1 before the loop began) would be sufficient - strlen doesn't count the '\0' at the end.

But speaking of counting the '\0' at the end, a slightly more efficient implementation could use sizeof a1 - 1 instead of strlen(a1) in this case, since a1 (and b1) are declared as arrays, not pointers. It's your choice, but remember that sizeof won't work for pointers, so don't get them mixed up.

EDIT: New problems:

char *p = malloc(/*some*/); p = /* something */ is a problem. = with pointers doesn't copy contents, it copies the value, so you're throwing away the old pointer value you got from malloc. To copy the contents of a string into a char * (or a char [] for that matter) you'd need to use strcpy, strncpy, or (my preference) memcpy. (Or just a loop, but that's rather silly. Then again, it may be good practice if you're writing your own strcat.)

Unless you're using C++, I wouldn't cast the return value of malloc, but that's a religious war and we don't need one of those.

If you have strdup, use it. If you don't, here is a working implementation:

char *strdup(const char *c)
{
    size_t l = strlen(c);
    char *d = malloc(l + 1);
    if(d) memcpy(d, c, l + 1);
    return d;
}

It is one of the most useful functions not in the C standard library.


问:
CoreNFC for card emulation?
CoreNFC is introduced in iOS 11 SDK. can CoreNFC be used for Smart Card emulation on iOS?
Apple Documentation of CoreNFC</p>

答:
For Smart Card Emulation we need to send card's data (like PAN, CVV2, ...) through NFC module.
According to Apple's Documentation CoreNFC only allows NFC module to read Near Field Communication (NFC) tags of types 1 through 5 that contain data in the NFC Data Exchange Format (NDEF).

So it seems the answer is NO at the moment.

Your app can read tags to give users more information about their physical environment and the real-world objects in it. For example, your app might give users information about products they find in a store or exhibits they visit in a museum.

Using Core NFC, you can read Near Field Communication (NFC) tags of types 1 through 5 that contain data in the NFC Data Exchange Format (NDEF). To read a tag, your app creates an NFC NDEF reader session and provides a delegate. A running reader session polls for NFC tags and calls the delegate when it finds tags that contain NDEF messages, passing the messages to the delegate. The delegate can read the messages and handle conditions that can cause a session to become invalid.

Apple's CoreNFC Documentation

Title: CoreNFC for card emulation?


问:
What does require('express')() do in NodeJS
As far as I understand, require('express')() doesn't create a server, it just bundles the functions together. But if so, how does the following code run without server?

```<code>const express = require('express')
const app = express()

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})
</code>```

Also, if it does create a server, why do I need to import http module and manually create a server in the following example?

```<code>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});
</code>```

I am very confused. Thanks in advance.

答:
require('express')() creates an instance of an Express application.

It's short for this:

```<code>var express = require('express');
var app     = express();
</code>```

You don't need to explicitly use http if you want to create an HTTP server, because Express will create one for you if you call app.listen().

If you need that server for something else, for instance, to attach a socket.io instance to, you can use this:

```<code>var express = require('express');
var app     = express();
var server  = app.listen(3000, ...); // returns an `http.Server` instance
var io      = require('socket.io')(server);
</code>```

Body:
As far as I understand, require('express')() doesn't create a server, it just bundles the functions together. But if so, how does the following code run without server?

const express = require('express')
const app = express()

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

Also, if it does create a server, why do I need to import http module and manually create a server in the following example?

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

I am very confused. Thanks in advance.

Body:
require('express')() creates an instance of an Express application.

It's short for this:

var express = require('express');
var app     = express();

You don't need to explicitly use http if you want to create an HTTP server, because Express will create one for you if you call app.listen().

If you need that server for something else, for instance, to attach a socket.io instance to, you can use this:

var express = require('express');
var app     = express();
var server  = app.listen(3000, ...); // returns an `http.Server` instance
var io      = require('socket.io')(server);


问:
MySQL-Can we use range for text which has numbers?
In the table 'DailyStatus' one the column value text is like 'taskRead2017ww23.3','taskWrite2017ww45.5', etc

That means all the column values has year and work week as string.

How can I get the data if we want as work week ranges.?

For ex. I want all records in the ranges between 2017ww23.3 to 2017ww25.4

I tried with RLIKE and '|' but i need to pass every single work week value to the query like below

```<code>select *
  from dailystatus
 where taskname rlike '.*(*ww23.3 |*ww23.4 | *ww23.3 | .......|25.4 )'
</code>```

The above method seems very difficult if the range increases.

Is there any optimized way to achieve this?

答:
You could try to use DATE_FORMAT / STR_TO_DATE for that:

```<code>STR_TO_DATE(taskname, "taskRead%Yww%d.%m") BETWEEN '2017-03-23 00:00:00' AND '2017-04-25 23:59:59'
</code>```

But definitely, the optimized way would be to instantiate a date from the field as a separate column.

Body:
In the table 'DailyStatus' one the column value text is like 'taskRead2017ww23.3','taskWrite2017ww45.5', etc

That means all the column values has year and work week as string.

How can I get the data if we want as work week ranges.?

For ex. I want all records in the ranges between 2017ww23.3 to 2017ww25.4

I tried with RLIKE and '|' but i need to pass every single work week value to the query like below

select *
  from dailystatus
 where taskname rlike '.*(*ww23.3 |*ww23.4 | *ww23.3 | .......|25.4 )'

The above method seems very difficult if the range increases.

Is there any optimized way to achieve this?

Body:
You could try to use DATE_FORMAT / STR_TO_DATE for that:

STR_TO_DATE(taskname, "taskRead%Yww%d.%m") BETWEEN '2017-03-23 00:00:00' AND '2017-04-25 23:59:59'

But definitely, the optimized way would be to instantiate a date from the field as a separate column.


问:
How to get post data from flask
I cant figure out how to get post data from flask.

Below is my content-type

```<code>'Content-Type': 'application/x-www-form-urlencoded'
</code>```

Here is what I see from flask so I know the data is there.  I just cant access it.

```<code>request.values -> CombinedMultiDict([ImmutableMultiDict([]), ImmutableMultiDict([('{"email":"david","password":"FU"}', u'')])])
</code>```

So...how do I get email and password?

```<code>email = request.?????
</code>```

答:
You can force Flask to treat the data as JSON using request.get_json() setting the force argument to True</p>

```<code>data = request.get_json(force=True)
</code>```

Title: How to get post data from flask

Body:
I cant figure out how to get post data from flask.

Below is my content-type

'Content-Type': 'application/x-www-form-urlencoded'

Here is what I see from flask so I know the data is there.  I just cant access it.

request.values -> CombinedMultiDict([ImmutableMultiDict([]), ImmutableMultiDict([('{"email":"david","password":"FU"}', u'')])])

So...how do I get email and password?

email = request.?????

Body:
You can force Flask to treat the data as JSON using request.get_json() setting the force argument to True

data = request.get_json(force=True)


问:
div grid tab not in content
I use a php function to put my page content in the index.php, but when I use a grid (tab) in the content it goes out of the content borders.

I put a little bit of the code underneath, you can see the site here: (link deleted > problem solved)

答:
it all happens because of the float:left you used on the .tab3 . you either use display:inline-block instead of float:left or you use float:left on the content

not working ( as it is on your site )

body {
  background-color: #fff;
  background-image: url(img/bg.png);
  background-attachment: fixed;
  margin: 0;
  padding: 0;
  font-family: "Ubuntu Light", Ubuntu, sans-serif;
  font-size: 14px;
  overflow-x: hidden;
}

.main {
  width: 676px;
  float: left;
  margin-right: 20px;
}

.content {
  background-color: #fff;
  border-radius: 4px 4px 4px 4px;
  box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
  padding: 15px;
  margin-bottom: 20px;
  clear: both;
}

.tab3 {
  width: calc(100%/ 3);
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
  <div class="clearfix"></div>
  <div class="side-heading">Habbo</div>
  Op deze pagina vind je de ins en outs van Habbo (Hotel) en Sulake. We bieden je gidsen aan waarin uitleg staat over de talentenmeter, de catalogus, de (oude) Habbo Staff en Moderators, Habbo Club en ga zo maar verder. Ook vind je hier de geschiedenis
  van Habbo. En informatie over het bedrijf achter Habbo, namelijk Sulake. Mis je iets op deze pagina? Neem dan contact op met de webmaster.
  <div class="space"></div>

    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Burgerschap</div>
        <div class="blockimage" style="background-image:url(img/content/habbo_burgerschap.png)"></div>
      </div>
    </div>

    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Archievements</div>
        <div class="blockimage" style="background-image:url(img/bg.png)"></div>
      </div>
    </div>

    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Regels</div>
        <div class="blockimage" style="background-image:url(img/bg.png)"></div>
      </div>
    </div>

    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Games</div>
        <div class="blockimage" style="background-image:url(img/content/habbo_games.png)"></div>
      </div>
    </div>

</div></code>```

solution 1. inline-block

body {
  background-color: #fff;
  background-image: url(img/bg.png);
  background-attachment: fixed;
  margin: 0;
  padding: 0;
  font-family: "Ubuntu Light", Ubuntu, sans-serif;
  font-size: 14px;
  overflow-x: hidden;
}

.main {
  width: 676px;
  float: left;
  margin-right: 20px;
}

.content {
  background-color: #fff;
  border-radius: 4px 4px 4px 4px;
  box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
  padding: 15px;
  margin-bottom: 20px;
  clear: both;
}

.tab3 {
  width: calc(100%/ 3);
  display:inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
  <div class="clearfix"></div>
  <div class="side-heading">Habbo</div>
  Op deze pagina vind je de ins en outs van Habbo (Hotel) en Sulake. We bieden je gidsen aan waarin uitleg staat over de talentenmeter, de catalogus, de (oude) Habbo Staff en Moderators, Habbo Club en ga zo maar verder. Ook vind je hier de geschiedenis
  van Habbo. En informatie over het bedrijf achter Habbo, namelijk Sulake. Mis je iets op deze pagina? Neem dan contact op met de webmaster.
  <div class="space"></div>

    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Burgerschap</div>
        <div class="blockimage" style="background-image:url(img/content/habbo_burgerschap.png)"></div>
      </div>
    </div>

    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Archievements</div>
        <div class="blockimage" style="background-image:url(img/bg.png)"></div>
      </div>
    </div>

    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Regels</div>
        <div class="blockimage" style="background-image:url(img/bg.png)"></div>
      </div>
    </div>

    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Games</div>
        <div class="blockimage" style="background-image:url(img/content/habbo_games.png)"></div>
      </div>
    </div>

</div></code>```

solution2 . float:left on content

body {
  background-color: #fff;
  background-image: url(img/bg.png);
  background-attachment: fixed;
  margin: 0;
  padding: 0;
  font-family: "Ubuntu Light", Ubuntu, sans-serif;
  font-size: 14px;
  overflow-x: hidden;
}

.main {
  width: 676px;
  float: left;
  margin-right: 20px;
}

.content {
  background-color: #fff;
  border-radius: 4px 4px 4px 4px;
  box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
  padding: 15px;
  margin-bottom: 20px;
  clear: both;
  float: left;
}

.tab3 {
  width: calc(100%/ 3);
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
  <div class="clearfix"></div>
  <div class="side-heading">Habbo</div>
  Op deze pagina vind je de ins en outs van Habbo (Hotel) en Sulake. We bieden je gidsen aan waarin uitleg staat over de talentenmeter, de catalogus, de (oude) Habbo Staff en Moderators, Habbo Club en ga zo maar verder. Ook vind je hier de geschiedenis
  van Habbo. En informatie over het bedrijf achter Habbo, namelijk Sulake. Mis je iets op deze pagina? Neem dan contact op met de webmaster.
  <div class="space"></div>

    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Burgerschap</div>
        <div class="blockimage" style="background-image:url(img/content/habbo_burgerschap.png)"></div>
      </div>
    </div>

    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Archievements</div>
        <div class="blockimage" style="background-image:url(img/bg.png)"></div>
      </div>
    </div>

    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Regels</div>
        <div class="blockimage" style="background-image:url(img/bg.png)"></div>
      </div>
    </div>

    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Games</div>
        <div class="blockimage" style="background-image:url(img/content/habbo_games.png)"></div>
      </div>
    </div>

</div></code>```

let me know if one of these 2 solutions worked for you

Title: div grid tab not in content

Body:
it all happens because of the float:left you used on the .tab3 . you either use display:inline-block instead of float:left or you use float:left on the content

not working ( as it is on your site )

body {
  background-color: #fff;
  background-image: url(img/bg.png);
  background-attachment: fixed;
  margin: 0;
  padding: 0;
  font-family: "Ubuntu Light", Ubuntu, sans-serif;
  font-size: 14px;
  overflow-x: hidden;
}

.main {
  width: 676px;
  float: left;
  margin-right: 20px;
}

.content {
  background-color: #fff;
  border-radius: 4px 4px 4px 4px;
  box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
  padding: 15px;
  margin-bottom: 20px;
  clear: both;
}

.tab3 {
  width: calc(100%/ 3);
  float: left;
}

<div class="content">
  <div class="clearfix"></div>
  <div class="side-heading">Habbo</div>
  Op deze pagina vind je de ins en outs van Habbo (Hotel) en Sulake. We bieden je gidsen aan waarin uitleg staat over de talentenmeter, de catalogus, de (oude) Habbo Staff en Moderators, Habbo Club en ga zo maar verder. Ook vind je hier de geschiedenis
  van Habbo. En informatie over het bedrijf achter Habbo, namelijk Sulake. Mis je iets op deze pagina? Neem dan contact op met de webmaster.
  <div class="space"></div>
  <a href="?page=habbo_burgerschap">
    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Burgerschap</div>
        <div class="blockimage" style="background-image:url(img/content/habbo_burgerschap.png)"></div>
      </div>
    </div>
  </a>
  <a href="#">
    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Archievements</div>
        <div class="blockimage" style="background-image:url(img/bg.png)"></div>
      </div>
    </div>
  </a>
  <a href="#">
    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Regels</div>
        <div class="blockimage" style="background-image:url(img/bg.png)"></div>
      </div>
    </div>
  </a>
  <a href="#">
    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Games</div>
        <div class="blockimage" style="background-image:url(img/content/habbo_games.png)"></div>
      </div>
    </div>
  </a>
</div>

solution 1. inline-block

body {
  background-color: #fff;
  background-image: url(img/bg.png);
  background-attachment: fixed;
  margin: 0;
  padding: 0;
  font-family: "Ubuntu Light", Ubuntu, sans-serif;
  font-size: 14px;
  overflow-x: hidden;
}

.main {
  width: 676px;
  float: left;
  margin-right: 20px;
}

.content {
  background-color: #fff;
  border-radius: 4px 4px 4px 4px;
  box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
  padding: 15px;
  margin-bottom: 20px;
  clear: both;
}

.tab3 {
  width: calc(100%/ 3);
  display:inline-block;
}

<div class="content">
  <div class="clearfix"></div>
  <div class="side-heading">Habbo</div>
  Op deze pagina vind je de ins en outs van Habbo (Hotel) en Sulake. We bieden je gidsen aan waarin uitleg staat over de talentenmeter, de catalogus, de (oude) Habbo Staff en Moderators, Habbo Club en ga zo maar verder. Ook vind je hier de geschiedenis
  van Habbo. En informatie over het bedrijf achter Habbo, namelijk Sulake. Mis je iets op deze pagina? Neem dan contact op met de webmaster.
  <div class="space"></div>
  <a href="?page=habbo_burgerschap">
    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Burgerschap</div>
        <div class="blockimage" style="background-image:url(img/content/habbo_burgerschap.png)"></div>
      </div>
    </div>
  </a>
  <a href="#">
    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Archievements</div>
        <div class="blockimage" style="background-image:url(img/bg.png)"></div>
      </div>
    </div>
  </a>
  <a href="#">
    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Regels</div>
        <div class="blockimage" style="background-image:url(img/bg.png)"></div>
      </div>
    </div>
  </a>
  <a href="#">
    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Games</div>
        <div class="blockimage" style="background-image:url(img/content/habbo_games.png)"></div>
      </div>
    </div>
  </a>
</div>

solution2 . float:left on content

body {
  background-color: #fff;
  background-image: url(img/bg.png);
  background-attachment: fixed;
  margin: 0;
  padding: 0;
  font-family: "Ubuntu Light", Ubuntu, sans-serif;
  font-size: 14px;
  overflow-x: hidden;
}

.main {
  width: 676px;
  float: left;
  margin-right: 20px;
}

.content {
  background-color: #fff;
  border-radius: 4px 4px 4px 4px;
  box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
  padding: 15px;
  margin-bottom: 20px;
  clear: both;
  float: left;
}

.tab3 {
  width: calc(100%/ 3);
  float: left;
}

<div class="content">
  <div class="clearfix"></div>
  <div class="side-heading">Habbo</div>
  Op deze pagina vind je de ins en outs van Habbo (Hotel) en Sulake. We bieden je gidsen aan waarin uitleg staat over de talentenmeter, de catalogus, de (oude) Habbo Staff en Moderators, Habbo Club en ga zo maar verder. Ook vind je hier de geschiedenis
  van Habbo. En informatie over het bedrijf achter Habbo, namelijk Sulake. Mis je iets op deze pagina? Neem dan contact op met de webmaster.
  <div class="space"></div>
  <a href="?page=habbo_burgerschap">
    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Burgerschap</div>
        <div class="blockimage" style="background-image:url(img/content/habbo_burgerschap.png)"></div>
      </div>
    </div>
  </a>
  <a href="#">
    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Archievements</div>
        <div class="blockimage" style="background-image:url(img/bg.png)"></div>
      </div>
    </div>
  </a>
  <a href="#">
    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Regels</div>
        <div class="blockimage" style="background-image:url(img/bg.png)"></div>
      </div>
    </div>
  </a>
  <a href="#">
    <div class="tab3">
      <div class="block">
        <div class="blocktitle">Habbo Games</div>
        <div class="blockimage" style="background-image:url(img/content/habbo_games.png)"></div>
      </div>
    </div>
  </a>
</div>

let me know if one of these 2 solutions worked for you


答:
Afaik, the  tag is ignored by most search engines, as is .

But you could also use the CSS:first-letter pseudo-element. This allows you to style the first letter of a text, so you could write iPhone</span, and then write a css like .branding:first-letter { font-weight: bold; font-style: italic; }. This way you got even less risk of search engine problems, and that will make your marketeers happy. :)

See: http://www.w3schools.com/CSS/pr_pseudo_first-letter.asp

Body:
Afaik, the <i> tag is ignored by most search engines, as is <span>.

But you could also use the CSS:first-letter pseudo-element. This allows you to style the first letter of a text, so you could write <span class="branding">iPhone</span, and then write a css like .branding:first-letter { font-weight: bold; font-style: italic; }. This way you got even less risk of search engine problems, and that will make your marketeers happy. :)

See: http://www.w3schools.com/CSS/pr_pseudo_first-letter.asp


问:
Build Objective-C Library with CMake with ARC enabled
I am trying to build an Objective-C ARC enabled library using CMake. When using the "Unix Makefiles" generator I run into a warning:

method possibly missing a [super dealloc] call

I don't run into this warning when using the XCode generator. Is there a flag I can pass to CMake to make sure that the command line build also recognizes this to be an ARC build and not have that warning generated?

Thanks

答:
XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC works for me. See https://github.com/forexample/testapp/blob/master/CMakeLists.txt</p>

```<code>set_target_properties(
    ${APP_NAME}
    PROPERTIES
    MACOSX_BUNDLE YES
    XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC YES
)
</code>```

Body:
XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC works for me. See https://github.com/forexample/testapp/blob/master/CMakeLists.txt

set_target_properties(
    ${APP_NAME}
    PROPERTIES
    MACOSX_BUNDLE YES
    XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC YES
)


问:
Some times Toast is not visible in activity or inside fragment when added inside handler
Requirement is that toast will be show some delay in fragment  so add inside the handler.
But sometime that toast is not visible. There are some loader operations and fragment transaction action before toast.</p>

```<code>final Handler handler = new Handler(getMainLooper());
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            //Do something after 100ms\
        Toast.makeText(getActivity,message,Toast.LENGTH_SHORT).show();

        }
    }, 100);
</code>```

答:
You can achieve this using Handler, Timer Task, CountDownTimer, and using for loop too. My favorite is CountDownTimer which is very easy and fast solution.

```<code>    private long duration = 30000; // 30 seconds
    private long interval = 1000; // 1 seconds

    CountDownTimer cd = new CountDownTimer(duration, interval) {
        @Override
        public void onTick(long l) {
          // This method call every seconds.
        }

        @Override
        public void onFinish() {
          // When 30 seconds completed this method is called.
            Toast.makeText(Activity.this, "Hello", Toast.LENGTH_SHORT).show();
        }
    };
    cd.start();
</code>```

You can change duration and interval according to your need.

Body:
Requirement is that toast will be show some delay in fragment  so add inside the handler.
But sometime that toast is not visible. There are some loader operations and fragment transaction action before toast.

final Handler handler = new Handler(getMainLooper());
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            //Do something after 100ms\
        Toast.makeText(getActivity,message,Toast.LENGTH_SHORT).show();

        }
    }, 100);

Body:
You can achieve this using Handler, Timer Task, CountDownTimer, and using for loop too. My favorite is CountDownTimer which is very easy and fast solution.

    private long duration = 30000; // 30 seconds
    private long interval = 1000; // 1 seconds

    CountDownTimer cd = new CountDownTimer(duration, interval) {
        @Override
        public void onTick(long l) {
          // This method call every seconds.
        }

        @Override
        public void onFinish() {
          // When 30 seconds completed this method is called.
            Toast.makeText(Activity.this, "Hello", Toast.LENGTH_SHORT).show();
        }
    };
    cd.start();

You can change duration and interval according to your need.


问:
QT3D QML RenderPassFilter with several key seems bugged
I just started using QML to create a QT3D scene.
I would like to filter which elements of my scene are rendered using a RenderPassFilter.
Here is my really simple renderer:

```<code>import Qt3D.Core 2.0
import Qt3D.Render 2.0

Viewport {
  id: root
  property color clearColor: Qt.rgba(0, 0, 0.2, 1)
  property Camera mainCamera

  RenderSurfaceSelector {
    id: surfaceSelector

    // Clear Buffer
    ClearBuffers {
      buffers: ClearBuffers.ColorDepthBuffer
      clearColor: root.clearColor
      NoDraw {}
    }

    RenderPassFilter {
      matchAny: [FilterKey{name: "type"; value: "filter1"}] // <-- THIS LINE IS THE FILTER

      CameraSelector {
        id: selector
        camera: mainCamera
      }
    }
  }
}
</code>```

This properly displays all elements (and only those) that contains a FilterKey{name: "type"; value: "filter1"}

Replacing this with another filter works just fine:

```<code>RenderPassFilter {
  matchAny: [FilterKey{name: "type"; value: "filter2"}] // <-- THIS LINE IS THE FILTER

  CameraSelector {
    id: selector
    camera: mainCamera
  }
}
</code>```

will display the set of object with the filter value filter2 instead of filter1

Now my problem is that the matchAny field is a list, so I would excpect it to be able to take several elements. Unfortunately the following doesn't display any element at all

```<code>RenderPassFilter {
  matchAny: [FilterKey{name: "type"; value: "filter1"}, FilterKey{name: "type"; value: "filter2"}] // <-- THIS LINE IS THE FILTER

  CameraSelector {
    id: selector
    camera: mainCamera
  }
}
</code>```

I would expect this to render all elements with either value filter1 or value filter2. What is the way to achieve this?

EDIT: I just realised while posting this that matchAny could mean the opposite of what I though: any filter key in an element has to match what is int the matchAny list (but all the list must be matched)... if that makes sense. Anyway, the question remains: How can I use a RenderPassFilter to allow elements that contain either filter1 or filter2?

答:
Ok, so after many trials, I what I got is:

1) What I wrote in the question's edit is correct: using

```<code>RenderPassFilter {
  matchAny: [FilterKey{name: "type"; value: "filter1"}]
  // ... stuff
}
</code>```

means that a render pass will be exectued if it contains at least the filter FilterKey{name: "type"; value: "filter1"}

2) The only way to test if a pass has type filter1 or filter2 is to create two different renderPassFilters:

```<code>RenderPassFilter {
  matchAny: [FilterKey{name: "type"; value: "filter1"}]
  // ... stuff
}
RenderPassFilter {
  matchAny: [FilterKey{name: "type"; value: "filter2"}]
  // ... stuff
}
</code>```

Body:
I just started using QML to create a QT3D scene.
I would like to filter which elements of my scene are rendered using a RenderPassFilter.
Here is my really simple renderer:

import Qt3D.Core 2.0
import Qt3D.Render 2.0

Viewport {
  id: root
  property color clearColor: Qt.rgba(0, 0, 0.2, 1)
  property Camera mainCamera

  RenderSurfaceSelector {
    id: surfaceSelector

    // Clear Buffer
    ClearBuffers {
      buffers: ClearBuffers.ColorDepthBuffer
      clearColor: root.clearColor
      NoDraw {}
    }

    RenderPassFilter {
      matchAny: [FilterKey{name: "type"; value: "filter1"}] // <-- THIS LINE IS THE FILTER

      CameraSelector {
        id: selector
        camera: mainCamera
      }
    }
  }
}

This properly displays all elements (and only those) that contains a FilterKey{name: "type"; value: "filter1"}

Replacing this with another filter works just fine:

RenderPassFilter {
  matchAny: [FilterKey{name: "type"; value: "filter2"}] // <-- THIS LINE IS THE FILTER

  CameraSelector {
    id: selector
    camera: mainCamera
  }
}

will display the set of object with the filter value filter2 instead of filter1

Now my problem is that the matchAny field is a list, so I would excpect it to be able to take several elements. Unfortunately the following doesn't display any element at all

RenderPassFilter {
  matchAny: [FilterKey{name: "type"; value: "filter1"}, FilterKey{name: "type"; value: "filter2"}] // <-- THIS LINE IS THE FILTER

  CameraSelector {
    id: selector
    camera: mainCamera
  }
}

I would expect this to render all elements with either value filter1 or value filter2. What is the way to achieve this?

EDIT: I just realised while posting this that matchAny could mean the opposite of what I though: any filter key in an element has to match what is int the matchAny list (but all the list must be matched)... if that makes sense. Anyway, the question remains: How can I use a RenderPassFilter to allow elements that contain either filter1 or filter2?

Body:
Ok, so after many trials, I what I got is:

1) What I wrote in the question's edit is correct: using

RenderPassFilter {
  matchAny: [FilterKey{name: "type"; value: "filter1"}]
  // ... stuff
}

means that a render pass will be exectued if it contains at least the filter FilterKey{name: "type"; value: "filter1"}

2) The only way to test if a pass has type filter1 or filter2 is to create two different renderPassFilters:

RenderPassFilter {
  matchAny: [FilterKey{name: "type"; value: "filter1"}]
  // ... stuff
}
RenderPassFilter {
  matchAny: [FilterKey{name: "type"; value: "filter2"}]
  // ... stuff
}

ContentLicense: CC BY-SA 4.0


问:
How to retrieve high quality compass orientation (as in Google Maps)?
All of the guides to getting compass orientation in Android I've found have a bug: when you hold the phone in portrait mode and "look" above the horizon, the compass arrow turns 180 degrees from the correct direction.

Google Maps orientation indicator doesn't have this problem.

Another nice thing that Google Maps have is that they somehow estimate compass accuracy. Any idea how they do this?

答:
bug when looking above the horizon.

There is some tricky parts when you work with compass.
The compass orientation depends on magnetic fields and phone orientation, so, in order to correct deviation you need to do some matrix operations.

Check this article, it provides a simple example  -> https://www.journal.deviantdev.com/android-compass-azimuth-calculating/

Paraphrasing the article: "So if the device is not holding flat (∓45° deviation) you have to use remapCoordinateSystem() in a useful way to get correct results."

accuracy.

First of all, accuracy rely on physical components present in the device. Fragmentation is a common problem here. Samsung magnetometers are different from LG's, and Android System is not going to abstract you from this.

On the other hand, devices could rely on different type of sensors: harward or sensor fusion. So you're going to experiment differences between one device and other.

So this is a mess. But it exists some techniques you could apply in order to get accuracy and uniformed data from sensors (not only for compass, probably GPS too).

Some people discard the first few seconds of sensor data. Some time is needed in order to calibrate the signal, so the first data retrieved use to have some deviation. The time you need to discard depends on manufacturer again, buy I'd try with 5 seconds or so.

Use Interpolators and Extrapolators. Many sensors in android provide you a way to retrieve data each certain milliseconds. But this is the abstraction provided by Android. Harward sensors have its own timing and they update the signal when they they think it is necessary. The rest of the time, when Android ask the sensor for signal data the sensor returns the last value or maybe some kind of operation of the last signal data provided by manufacturer (again).

So, it is interesting to have some abstraction layer (interpolator / extrapolator) which receive the data from Android system each 20, 50, 1000... This layer make some operations in order to have some uniformity, and then communicates the data to your app.

The operation here could be some kind of average between current and last value, accumulated average or maybe another kind of normalization.


问:
How are Exrin services registered to their appropriate models?
After creating a service for a model, how do I tell the model to use that service?

Within the sample Tesla app, there exists constructors which call for a service as an argument:

```<code>private readonly IClimateService _service;

public ClimateModel(IExrinContainer exrinContainer, IAuthModel authModel, IClimateService service)
        : base(exrinContainer, new ClimateModelState())
    { _service = service; }
</code>```

I searched but never found where the model receives the service, but I did find this:

```<code>protected override void InitServices()
{
    RegisterTypeAssembly(typeof(IService), new AssemblyName(nameof(TeslaService)));
        base.InitServices();
}
</code>```

答:
Exrin automatically loads Services, via reflection, if they inherit from</p>

```<code>Exrin.Abstraction.IService
</code>```

Body:
After creating a service for a model, how do I tell the model to use that service?

Within the sample Tesla app, there exists constructors which call for a service as an argument:

private readonly IClimateService _service;

public ClimateModel(IExrinContainer exrinContainer, IAuthModel authModel, IClimateService service)
        : base(exrinContainer, new ClimateModelState())
    { _service = service; }

I searched but never found where the model receives the service, but I did find this:

protected override void InitServices()
{
    RegisterTypeAssembly(typeof(IService), new AssemblyName(nameof(TeslaService)));
        base.InitServices();
}

Body:
Exrin automatically loads Services, via reflection, if they inherit from

Exrin.Abstraction.IService


问:
Difference between LinkedList<?> and LinkedList<Object>
Is there any difference between LinkedList< ? > and LinkedList< Object > in Java?

答:
This passes compilation:

```<code>LinkedList<?> list1 = new LinkedList<String> ();
</code>```

This doesn't:

```<code>LinkedList<Object> list2 = new LinkedList<String> ();
</code>```

i.e. a LinkedList<?> variable can be assigned any LinkedList<SomeType>. A LinkedList<Object> variable can only be assigned a LinkedList<Object> (or a raw LinkedList, which is not advised to use).

On the other hand the following add:

```<code>LinkedList<?> list1 = new LinkedList<String> ();
list1.add("x");
</code>```

doesn't pass compilation, while the following does:

```<code>LinkedList<Object> list2 = new LinkedList<Object> ();
list2.add("x");
</code>```

Body:
This passes compilation:

LinkedList<?> list1 = new LinkedList<String> ();

This doesn't:

LinkedList<Object> list2 = new LinkedList<String> ();

i.e. a LinkedList<?> variable can be assigned any LinkedList<SomeType>. A LinkedList<Object> variable can only be assigned a LinkedList<Object> (or a raw LinkedList, which is not advised to use).

On the other hand the following add:

LinkedList<?> list1 = new LinkedList<String> ();
list1.add("x");

doesn't pass compilation, while the following does:

LinkedList<Object> list2 = new LinkedList<Object> ();
list2.add("x");


问:
display dropdown list on alert (or on dialog box) in html
My project requirement is to display alert or dialog box on click of button, on that alert, display drop down list with some values, select the drop down list value and save it in array list using HTML.
i have tried this    but it not working.
alert dialog should like below image.

<img src="https://i.stack.imgur.com/1mkZ5.png" alt="

答:
hi try using http://bootboxjs.com/

Bootbox comes with a Modal With Select Dropdown try using it.

Hope this helps


问:
Storing actively updated fields in the database
I have a database with one of the table storing articles. For every article I need to store the number of times it was viewed. Now, my idea is to store this value in the database and update it every time someone visits the page with that article and I am considering two alternatives now:

Create a column views in the table articles and update it.

Create a separate table view_count with FK pointer to the article and the number views for that article.

My question is: is there any difference between these two approaches in terms of speed and why? Are there any better alternatives?

The database I use is PostgreSQL.

Note, that I am not considering the different ways of accumulating those values in separate files, outside of database and later inserting because i) we do not get as many hits ii) the feature in minor and if it would require such a hassle we would rather abandon it and use some other service for that.

答:
If the articles table gets a lot of writes than updating the column might be a bit slower because of the table locks while writing.

Using a separate table is only a little bit slower/heavier to read but is lightest in terms of updates. But after loads of writes you can easily rebuild the table without much performance penalty since it will be quite a light table.

If your database doesn't have a high load than I would take the easy option of adding a column though.


问:
Phonegap Build: Access origin doesn't appear to work for subdomains
In Phonegap I need to display some images from a CDN which uses multiple subdomains. For example:

```<code><img src="http://a1.mzstatic.com/.....75.jpg">
<img src="http://a2.mzstatic.com/.....75.jpg">
<img src="http://a3.mzstatic.com/.....75.jpg">
<img src="http://a4.mzstatic.com/.....75.jpg">
</code>```

Because these are external resources on multiple subdomains I set the following in my config.xml :

<access origin="http://mzstatic.com*" subdomains="true" />

However all the images display broken as if it can't make the call to the server. I added:

<access origin="http://a1.mzstatic.com*" />

and images on that domain start to work.

Am I doing something wrong?

To demonstrate this and eliminate all other factors I've forked the phonegap-start project to here https://github.com/SeanBannister/phonegap-start which demonstrates my problem, I've just added my images elements and the access origin to the config.

Update The CDN has an unlimited number of subdomains so I can't just list them all.

答:
you need to try this:

```<code><access origin="http://*.mzstatic.com/*" subdomains="true" />
</code>```

first * will allow any character before the host/domain name
& second * will allow any character after "/"

This should work.

Body:
In Phonegap I need to display some images from a CDN which uses multiple subdomains. For example:

Because these are external resources on multiple subdomains I set the following in my config.xml :

<access origin="http://mzstatic.com*" subdomains="true" />

However all the images display broken as if it can't make the call to the server. I added:

<access origin="http://a1.mzstatic.com*" />

and images on that domain start to work.

Am I doing something wrong?

To demonstrate this and eliminate all other factors I've forked the phonegap-start project to here https://github.com/SeanBannister/phonegap-start which demonstrates my problem, I've just added my images elements and the access origin to the config.

Update The CDN has an unlimited number of subdomains so I can't just list them all.

Body:
you need to try this:

<access origin="http://*.mzstatic.com/*" subdomains="true" />

first * will allow any character before the host/domain name
& second * will allow any character after "/"

This should work.


答: Basically when you do require('express'), it imports a function. The following () calls the function as well. Basically it instantiates an express app.

Title: What does require('express')() do in NodeJS

Body:
As far as I understand, require('express')() doesn't create a server, it just bundles the functions together. But if so, how does the following code run without server?

const express = require('express')
const app = express()

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

Also, if it does create a server, why do I need to import http module and manually create a server in the following example?

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

I am very confused. Thanks in advance.


问:
docker build error in Dockerfile
When I try to run 'docker build .' or 'docker build - < Dockerfile', errors appeared as below:

```<code>[root@VM_60_90_centos dtask-ctrip-train-domestic]# docker build .
Sending build context to Docker daemon 38.98 MB
Step 1 : FROM ubuntu:14.04  ---> 132b7427a3b4
Step 2 : MAINTAINER Ke Peng<ke.peng@jingli365.com>  ---> Using cache  --->
         db9529465f77
Step 3: WORKDIR /opt/app  ---> Using cache  ---> 3122f40a8e56
Step 4 :COPY . ./  ---> 4d67a5fbf128 Removing intermediate container
c2d83602f613
Step 5 : RUN npm  install  ---> Running in 67680232cbdf

/bin/sh: 1: npm: not found The command '/bin/sh -c npm  install'
returned a non-zero code: 127
</code>```

and my Dockerfile like this:

```<code>FROM ubuntu:14.04
MAINTAINER Ke Peng <ke.peng@jingli365.com>
WORKDIR /opt/app
COPY . ./
RUN npm  install
COPY dist/ /opt/app/
CMD node ./index.js < test.json
</code>```

Can anyone have similar experience and give me an solution. Very appreciated!

答:
I would like to modify from this:

```<code>RUN sudo apt-get update
RUN sudo -y apt-get install nodejs
RUN sudo -y apt-get install npm
</code>```

to this:

```<code>RUN sudo apt-get update && apt-get install -y nodejs npm
</code>```

and as whole it looks like this:

```<code>FROM ubuntu:14.04
MAINTAINER Ke Peng <ke.peng@jingli365.com>
RUN sudo apt-get update && apt-get install -y nodejs npm
WORKDIR /opt/app
COPY . ./
RUN npm  install
COPY dist/ /opt/app/
CMD node ./index.js < test.json
</code>```

As a best practice for Dockerfiles, you need to build/install packages in a single layer.

This will help the Image to be formed using minimal layers which will reduce the overall size of the Image.

Hope this helps.

Title: docker build error in Dockerfile

Body:
When I try to run 'docker build .' or 'docker build - < Dockerfile', errors appeared as below:

[root@VM_60_90_centos dtask-ctrip-train-domestic]# docker build .
Sending build context to Docker daemon 38.98 MB
Step 1 : FROM ubuntu:14.04  ---> 132b7427a3b4
Step 2 : MAINTAINER Ke Peng<ke.peng@jingli365.com>  ---> Using cache  --->
         db9529465f77
Step 3: WORKDIR /opt/app  ---> Using cache  ---> 3122f40a8e56
Step 4 :COPY . ./  ---> 4d67a5fbf128 Removing intermediate container
c2d83602f613
Step 5 : RUN npm  install  ---> Running in 67680232cbdf

/bin/sh: 1: npm: not found The command '/bin/sh -c npm  install'
returned a non-zero code: 127

and my Dockerfile like this:

FROM ubuntu:14.04
MAINTAINER Ke Peng <ke.peng@jingli365.com>
WORKDIR /opt/app
COPY . ./
RUN npm  install
COPY dist/ /opt/app/
CMD node ./index.js < test.json

Can anyone have similar experience and give me an solution. Very appreciated!

Body:
I would like to modify from this:

RUN sudo apt-get update
RUN sudo -y apt-get install nodejs
RUN sudo -y apt-get install npm

to this:

RUN sudo apt-get update && apt-get install -y nodejs npm

and as whole it looks like this:

FROM ubuntu:14.04
MAINTAINER Ke Peng <ke.peng@jingli365.com>
RUN sudo apt-get update && apt-get install -y nodejs npm
WORKDIR /opt/app
COPY . ./
RUN npm  install
COPY dist/ /opt/app/
CMD node ./index.js < test.json

As a best practice for Dockerfiles, you need to build/install packages in a single layer.

This will help the Image to be formed using minimal layers which will reduce the overall size of the Image.

Hope this helps.


问:
Hyperlink a HTML file inside another HTML file
I'm a bit of a noob when it comes to HTML, but I would like to hyperlink a word to open another html file. I have an understanding of linking to another website, just not to another file on my computer. Can someone help? Cheers.</p>

答:
suppose your file directory looks like this:

```<code>-- index.html
|
-- Some_folder
       |
       -- file1.html
       |
       -- file2.html
</code>```

try this:

```<code><a href="path/to/file">word</a>
</code>```

for using the above mentioned directory from index.html:

```<code><a href="Some_folder/file2.html">word</a>
</code>```

Body:
suppose your file directory looks like this:

-- index.html
|
-- Some_folder
       |
       -- file1.html
       |
       -- file2.html

try this:

<a href="path/to/file">word</a>

for using the above mentioned directory from index.html:

<a href="Some_folder/file2.html">word</a>


问:
Can I add a bean validation annotation with group?
I want to build a NotNull check that only work on Create group, so I can write like this

```<code>@Data
public static class TestDto {

    @NotNullOnCreate
    // @NotNull(groups = Create.class) // instead of this
    private String id;
}
</code>```

I create the NotNullOnCreate like this

```<code>@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@Repeatable(NotNullOnCreate.List.class)
@ReportAsSingleViolation
@Constraint(validatedBy = {})
@NotNull(groups = Create.class)
@interface NotNullOnCreate {

    String message() default "{javax.validation.constraints.NotNull.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
    @Retention(RUNTIME)
    @Documented
    @interface List {

        NotNullOnCreate[] value();
    }
}
</code>```

This doesn't work, because composing constraint annotation's (see ConstraintDescriptorImpl#createComposingConstraintDescriptor) group will be set to host annotation's group('Default').

I also tried this Class<?>[] groups() default {Create.class};, but this is not allowed, the default group must empty.

How can I achieve this ? I don't want to write the group everywhere.

EDIT

Create HV-1355 Constraint annotation with explicit groups

Wrote a workable demo project hv-annotation-with-group

答: This is not possible at the moment. If you like, open an issue in the Hibernate Validator issue tracker and we can explore this feature.</p>

Body:
I want to build a NotNull check that only work on Create group, so I can write like this

@Data
public static class TestDto {

    @NotNullOnCreate
    // @NotNull(groups = Create.class) // instead of this
    private String id;
}

I create the NotNullOnCreate like this

@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@Repeatable(NotNullOnCreate.List.class)
@ReportAsSingleViolation
@Constraint(validatedBy = {})
@NotNull(groups = Create.class)
@interface NotNullOnCreate {

    String message() default "{javax.validation.constraints.NotNull.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
    @Retention(RUNTIME)
    @Documented
    @interface List {

        NotNullOnCreate[] value();
    }
}

This doesn't work, because composing constraint annotation's (see ConstraintDescriptorImpl#createComposingConstraintDescriptor) group will be set to host annotation's group('Default').

I also tried this Class<?>[] groups() default {Create.class};, but this is not allowed, the default group must empty.

How can I achieve this ? I don't want to write the group everywhere.

EDIT

Create HV-1355 Constraint annotation with explicit groups

Wrote a workable demo project hv-annotation-with-group