问:
Jquery input type hidden value data toggle add/remove
Basically i have two buttons that insert dynamic data to the one input value:

```<code>    <button class="sunday">Sunday</button>
    <button class="monday">Monday</button>

    <input type="hidden" value="3/15/2017, 3/16/2017, 3/17/2017">
</code>```

Each button inserts 3 dates, so if you click both on sunday and monday for example you will get

```<code><input type="hidden" value="3/15/2017, 3/16/2017, 3/17/2017, 3/18/2017, 3/19/2017, 3/20/2017">
</code>```

What would be the best way to do this with JQuery but to be like a toggle, I want to add them but not to duplicate them.

答:
So, I looked at the code listed and based on the comments, I think this would be the a way of doing it.  To set the dates for each the checkboxes,  simply modify the hiddenDates attribute.

$(".checks button").click(function () {
  $(this).data("checked",true);
 newDates = [];
 $(".checks button").each(function () {
  if ($(this).data("checked"))
   newDates.push($(this).attr("hiddenDates"));
 });
 $("#hiddenArea").val(newDates.join(", "));
 console.log($("#hiddenArea").val());
});
$(".checks input:first").trigger("change");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label {
 display:block;
}</code>```

  <button hiddenDates="3/15/2017, 3/16/2017">Sunday</button>
  <button hiddenDates="4/15/2017">Monday</button>

<input id="hiddenArea" type="hidden" value="" />```

Body:
Basically i have two buttons that insert dynamic data to the one input value:

    <button class="sunday">Sunday</button>
    <button class="monday">Monday</button>

    <input type="hidden" value="3/15/2017, 3/16/2017, 3/17/2017">

Each button inserts 3 dates, so if you click both on sunday and monday for example you will get

<input type="hidden" value="3/15/2017, 3/16/2017, 3/17/2017, 3/18/2017, 3/19/2017, 3/20/2017">

What would be the best way to do this with JQuery but to be like a toggle, I want to add them but not to duplicate them.

Body:
So, I looked at the code listed and based on the comments, I think this would be the a way of doing it.  To set the dates for each the checkboxes,  simply modify the hiddenDates attribute.

$(".checks button").click(function () {
  $(this).data("checked",true);
 newDates = [];
 $(".checks button").each(function () {
  if ($(this).data("checked"))
   newDates.push($(this).attr("hiddenDates"));
 });
 $("#hiddenArea").val(newDates.join(", "));
 console.log($("#hiddenArea").val());
});
$(".checks input:first").trigger("change");

label {
 display:block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checks">
  <button hiddenDates="3/15/2017, 3/16/2017">Sunday</button>
  <button hiddenDates="4/15/2017">Monday</button>
</div>

<input id="hiddenArea" type="hidden" value="" />


来源: stackexchange

问:
Bootstrap 4 align elements right inside a col div
My question is pretty simple but I don't find a proper way (I mean not use absolute positionning of sub elements inside a relative position container) to achieve this in Bootstrap 4.

I have a row with a col-8 and a col-4. My content in col-4 must be right aligned so its content is at the right border.

```<code><h1 class="col-md-8">Applications portfolio</h1>

  <div class="btn-group col-md-4" role="group">
    <p class="float-right">
      <a class="btn btn-secondary btn-md" href="#">
        <i class="fa fa-plus" aria-hidden="true"></i> Creation</a>
      <a class="btn btn-md btn-secondary" href="#">
        <i class="fa fa-flag" aria-hidden="true"></i> Report</a>
    </p>
  </div>
</code>```

Here is a codepen:

https://codepen.io/anon/pen/QpzVgJ

I want my two buttons to right align within the col-4.

How in Bootstrap 4 to properly align right elements within a col?

答:
There a couple of issues with the markup provided that makes the layout look odd. @ZimSystem menioned the .container-fluid but also that you should always have a div.col inside a .row so that you get the same kind of padding on the edges.

You don't need a
 around the buttons. To get the alignment simply add .ml-auto to the first button like this:

```<code><div class="container-fluid">
<section class="row mb-2 mt-2">
  <h1 class="col-md-8">Applications portfolio</h1>

  <div class="btn-group col-md-4" role="group">
      <a class="btn btn-secondary btn-md ml-auto" href="#">
        <i class="fa fa-plus" aria-hidden="true"></i> Creation</a>
      <a class="btn btn-md btn-secondary" href="#">
        <i class="fa fa-flag" aria-hidden="true"></i> Report</a>
  </div>
</section>

<section class="row" style="background-color: grey; height: 50px; overflow:hidden;">
  <div class="col">
    <p>Just a simple reference block to see the 100% width</p>
  </div>
</section>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My question is pretty simple but I don't find a proper way (I mean not use absolute positionning of sub elements inside a relative position container) to achieve this in Bootstrap 4.

I have a row with a col-8 and a col-4. My content in col-4 must be right aligned so its content is at the right border.

Applications portfolio

         Creation

         Report

Here is a codepen:

https://codepen.io/anon/pen/QpzVgJ

I want my two buttons to right align within the col-4.

How in Bootstrap 4 to properly align right elements within a col?

Body:
There a couple of issues with the markup provided that makes the layout look odd. @ZimSystem menioned the .container-fluid but also that you should always have a div.col inside a .row so that you get the same kind of padding on the edges.

You don't need a <p> around the buttons. To get the alignment simply add .ml-auto to the first button like this:

<div class="container-fluid">
<section class="row mb-2 mt-2">
  <h1 class="col-md-8">Applications portfolio</h1>

  <div class="btn-group col-md-4" role="group">
      <a class="btn btn-secondary btn-md ml-auto" href="#">
        <i class="fa fa-plus" aria-hidden="true"></i> Creation</a>
      <a class="btn btn-md btn-secondary" href="#">
        <i class="fa fa-flag" aria-hidden="true"></i> Report</a>
  </div>
</section>

<section class="row" style="background-color: grey; height: 50px; overflow:hidden;">
  <div class="col">
    <p>Just a simple reference block to see the 100% width</p>
  </div>
</section>
</div>


问:
Installing perl DBD::mysql fails on Mac Sierra with mysql brew install
Trying to install DBD::mysql on my Mac Sierra computer running mysql v 5.7.17. Getting the following error when trying to install with cpanm install DBD::mysql:

Checking if libs are available for compiling...
Can't link/include C library 'ssl', 'crypto', aborting.

Other solutions I have found so far don't address this issue with Sierra.

答:
You can pass libs and cflags arg to help Makefile.PL find the libaries on the machine (in my case the openssl libraries were installed with homebrew):

cpanm  --configure-args="--libs='-L/usr/local/opt/openssl/lib -L/usr/local/Cellar/mysql/5.7.17/lib' --cflags='-I/usr/local/opt/openssl/include -I/usr/local/Cellar/mysql/5.7.17/include/mysql'" DBD::mysql


问:
How to find password protected pdf-files in a directory?
In a windows directory I have about 100 pdf-files, some are password protected, some are not. Is there an easy way (in the command-line or maybe with a freeware tool) to find the ones which are password protected without opening each of them in a pdf-reader?</p>

答: You could use the script of is it possible to check if pdf is password protected using ghostscript? and extend it to iterate over a bunch of files and eg. move all non-password protected files into a subdirectory.</p>


问:
Gradle Installation
I am following the below link to install/configure Gradle.
http://www.360logica.com/blog/2015/11/how-to-configure-gradle-on-windows-machine.html
I ended up downloading gradle in my V:\ drive instead of C:. As a result, in step 7, I put V:\gradle-2.8 as the variable path name. I am not sure what to do for steps 8 onwards (I don't see a PATH that starts with V:\ in the System Variables) because I didn't put this in my C drive. Thank you for your help</p>

答:
Your GRADLE_HOME is V:\gradle-2.8 , as opposed to C:\Program Files\gradle-2.8 in the tutorial. Thats perfectly alright.

In Step 8: do this

```<code>Variable name: GRADLE_HOME
Variable value: V:\gradle-2.8
</code>```

In Step 9: No change.

```<code>Select “path” variable under the “System Variables” section and click on “Edit” button.
</code>```

Step 10: No change.

```<code>Go to the end of variable value and add “;%GRADLE_HOME%\bin” and click on “OK” button.
</code>```

Why it works ?

When you give path variable as ;%GRADLE_HOME%\bin; Since you have already defined a variable called GRADLE_HOME =  V:\gradle-2.8 , the path variable will get substituted and resolved to V:\gradle-2.8\bin.

This can be verified by issuing echo %PATH% in cmd. You wont see GRADLE_HOME in the output because it was replaced with V:\gradle-2.8

What happens when your issue gradle in cmd ?

When you issue 'gradle' command in your windows commandline, it will look for a binary name 'gradle' in the paths defined by PATH , since there will be a binary named gradle.exe inside the V:\gradle-2.8\bin , it will be executed. In Linux the steps are similar conceptually.

Title: Gradle Installation

Body:
Your GRADLE_HOME is V:\gradle-2.8 , as opposed to C:\Program Files\gradle-2.8 in the tutorial. Thats perfectly alright.

In Step 8: do this

Variable name: GRADLE_HOME
Variable value: V:\gradle-2.8

In Step 9: No change.

Select “path” variable under the “System Variables” section and click on “Edit” button.

Step 10: No change.

Go to the end of variable value and add “;%GRADLE_HOME%\bin” and click on “OK” button.

Why it works ?

When you give path variable as ;%GRADLE_HOME%\bin; Since you have already defined a variable called GRADLE_HOME =  V:\gradle-2.8 , the path variable will get substituted and resolved to V:\gradle-2.8\bin.

This can be verified by issuing echo %PATH% in cmd. You wont see GRADLE_HOME in the output because it was replaced with V:\gradle-2.8

What happens when your issue gradle in cmd ?

When you issue 'gradle' command in your windows commandline, it will look for a binary name 'gradle' in the paths defined by PATH , since there will be a binary named gradle.exe inside the V:\gradle-2.8\bin , it will be executed. In Linux the steps are similar conceptually.


问:
Allow user to write access to gcp dataflow project
Following the quickstart for gcp dataflow here

I run into the following error when executing the example script here

using this command

```<code>declare -r PROJECT="beam-test"
declare -r BUCKET="gs://my-beam-test-bucket"

echo
set -v -e

python -m apache_beam.examples.wordcount \
  --project $PROJECT \
  --job_name $PROJECT-wordcount \
  --runner DataflowRunner \
  --staging_location $BUCKET/staging \
  --temp_location $BUCKET/temp \
  --output $BUCKET/output
</code>```

which results in this error:

```<code> http_response.request_url, method_config, request)
apitools.base.py.exceptions.HttpError: HttpError accessing <https://dataflow.googleapis.com/v1b3/projects/beam-test/locations/us-central1/jobs?alt=json>: response: <{'status': '403', 'content-length': '284', 'x-xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff', 'transfer-encoding': 'chunked', 'vary': 'Origin, X-Origin, Referer', 'server': 'ESF', '-content-encoding': 'gzip', 'cache-control': 'private', 'date': 'Fri, 31 Mar 2017 15:52:54 GMT', 'x-frame-options': 'SAMEORIGIN', 'alt-svc': 'quic=":443"; ma=2592000; v="37,36,35"', 'content-type': 'application/json; charset=UTF-8'}>, content <{
  "error": {
    "code": 403,
    "message": "(f010d95b3e221bbf): Could not create workflow; user does not have write access to project: beam-test Causes: (f010d95b3e221432): Permission 'dataflow.jobs.create' denied on project: 'beam-test'",
    "status": "PERMISSION_DENIED"
</code>```

I have already enabled the DataFlow api for the project. And I have authorized the gcloud cli with the  owner account of the project (which I assumes has full access).

How & where do I enable write permissions?

答:
Have you tried running gcloud auth login to make sure you have a valid credential?

If yes, your default cloud project might be different than the one you're running Dataflow with. To change the default project, you can run gcloud init.

Let me know if that doesn't solve it.

Body:
Following the quickstart for gcp dataflow here

I run into the following error when executing the example script here

using this command

declare -r PROJECT="beam-test"
declare -r BUCKET="gs://my-beam-test-bucket"

echo
set -v -e

python -m apache_beam.examples.wordcount \
  --project $PROJECT \
  --job_name $PROJECT-wordcount \
  --runner DataflowRunner \
  --staging_location $BUCKET/staging \
  --temp_location $BUCKET/temp \
  --output $BUCKET/output

which results in this error:

 http_response.request_url, method_config, request)
apitools.base.py.exceptions.HttpError: HttpError accessing <https://dataflow.googleapis.com/v1b3/projects/beam-test/locations/us-central1/jobs?alt=json>: response: <{'status': '403', 'content-length': '284', 'x-xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff', 'transfer-encoding': 'chunked', 'vary': 'Origin, X-Origin, Referer', 'server': 'ESF', '-content-encoding': 'gzip', 'cache-control': 'private', 'date': 'Fri, 31 Mar 2017 15:52:54 GMT', 'x-frame-options': 'SAMEORIGIN', 'alt-svc': 'quic=":443"; ma=2592000; v="37,36,35"', 'content-type': 'application/json; charset=UTF-8'}>, content <{
  "error": {
    "code": 403,
    "message": "(f010d95b3e221bbf): Could not create workflow; user does not have write access to project: beam-test Causes: (f010d95b3e221432): Permission 'dataflow.jobs.create' denied on project: 'beam-test'",
    "status": "PERMISSION_DENIED"

I have already enabled the DataFlow api for the project. And I have authorized the gcloud cli with the  owner account of the project (which I assumes has full access).

How & where do I enable write permissions?


问:
How to avoid deadlock when the called method uses the same lock that the caller already locked?
How to avoid deadlock when the called method uses the same lock that the caller already locked?

I have and method called closeUnusedConnections(), that creates a std::unique_lock but its caller already created a std::unique_lock with the same std::mutex: Foo::m_myMutex.

Do I have to release the lock before calling the subroutine?

Obs.: I can't integrate both methods because the  closeUnusedConnections is also called independently.

Some code:

```<code>void Foo::closeUnusedConnections()
{
   std::unique_lock< std::mutex > lock( m_mtx );
   // do stuff
}

Foo::CommNodePtr Foo::getConnection()
{
   std::unique_lock< std::mutex > lock( m_mtx );
   // do stuff
   if( true /*some condition*/ )
   {
      lock.unlock();     // The goal is to avoid this unlock
                         // someone could get the lock between
                         // this unlock until closeUnusedConnections's lock.
      closeUnusedConnections();
   }
   // etc
}
</code>```

答:
I believe it is quite dangerous to have an accessor to an object outside of a single owner thread it that object can be deleted, closed in your case, by other threads.  The mutex is supposed to prevent these things from happening while they are in possession of another thread.

nos's solution would work for you in what you describe but I feel you'll end up running into other problems down the road since nothing would stop one thread from closing the connection while it is being used by another thread after a call to getConnection.

I kind of wonder what you are attempting to accomplish by calling getConnection with the possibility that the call will actually return a connection that is closed.

My advice is to rethink your work flow so that only a single thread has access to your port at any given moment even if that means making it where only a single thread can ever use the port and other threads must make work requests.

Body:
How to avoid deadlock when the called method uses the same lock that the caller already locked?

I have and method called closeUnusedConnections(), that creates a std::unique_lock but its caller already created a std::unique_lock with the same std::mutex: Foo::m_myMutex.

Do I have to release the lock before calling the subroutine?

Obs.: I can't integrate both methods because the  closeUnusedConnections is also called independently.

Some code:

void Foo::closeUnusedConnections()
{
   std::unique_lock< std::mutex > lock( m_mtx );
   // do stuff
}

Foo::CommNodePtr Foo::getConnection()
{
   std::unique_lock< std::mutex > lock( m_mtx );
   // do stuff
   if( true /*some condition*/ )
   {
      lock.unlock();     // The goal is to avoid this unlock
                         // someone could get the lock between
                         // this unlock until closeUnusedConnections's lock.
      closeUnusedConnections();
   }
   // etc
}


问:
Where should I save the data?
I am trying to create an android app that will have approximately 10000 problems with each question having 4 options .I was thinking of creating an SQLiteDatabase for storing questions.But creating each entry /question inside an android app seems an hectic task ,but then I thought of creating the database outside the app and importing it but in both case the app size I think will be very large .I wanted to know is there a better way to deal with this problem ?</p>

答:
You can use Firebase as a backend for your application. The realtime database stores data in JSON format and has very easy to implement methods.

This way, you don't need to worry about the networking aspect of having an online database and you can store as much data as you want.

https://firebase.google.com/docs/database/android/start/

Title: Where should I save the data?


问:
Eclipse is freezing itself before getting started
I've been trying to open Eclipse to start my work today, and it freezes everytime during load.

My Eclipse is Helios. Someone told me I should remove a file called .lock from .metadata folder, but still didn't work.

Does anyone have any idea of how do I "melt" this thing up?

ps: I opened it yesterday with no problems.

答:
I have experienced something similar when launching Eclipse after having to force close it for some reason.
If it always hangs when loading the SVN plugin — like in your screenshot — it is likely to be related to that. In this case I suggest the following:

back up your current workspace

launch Eclipse with the -data command line argument to specify a different workspace folder

if Eclipse starts up successfully, try to import your projects from the original workspace or even better from SVN

ContentLicense: CC BY-SA 2.5


问:
Map properties to state in react-redux
I have a component that uses state to provide data to user. For example
this.state.variableInState
. This component can dispatch some method (for example on onClick action). I'm currently using react-redux an connect method to map store to props. Is there a way I can setState after dispatch?

```<code>// actions
export function executeAction() {
  return function (dispatch, getState) {
    dispatch({
      type: 'MY_ACTION',
      payload: axios.get('/some/url')
    });
  };
}
// reducer

export default function (state = {}, action) {
  switch (action.type) {
    case 'MY_ACTION_FULFILLED':
      return {...state, myVariable: action.payload.data}
  }
}
//component
class MyComponent extends Component {
  render() {
    (<div onClick={this.props.executeAction.bind(this)}>
      {this.state.variableInState}
      </div>)
  }

  someOtherMethod() {
    // I want to operate with state here, not with props
    // that's why my div gets state from this.state instead of this.props
    this.setState({variableInState: 'someValue'})
  }
}

export default connect((state, ownProperties) => {
  return {
    // So I want to change MyComponent.state.variableInState here
    // but this method updates MyComponent props only
    // What can I do?
    variableInProps: state.myVariable
  }
}, {executeAction})(MyComponent);
</code>```

答:
I think you're not supposed to directly change the state like this. why not call another action to perform what you want?

The state should be immutable when using Redux. You should dispatch an action. A Reducer should receive the action and the current state, and return a new state object that includes the changes you want to make.
Check this: http://redux.js.org/docs/introduction/ThreePrinciples.html#changes-are-made-with-pure-functions

Title: Map properties to state in react-redux

Body:
I have a component that uses state to provide data to user. For example
this.state.variableInState
. This component can dispatch some method (for example on onClick action). I'm currently using react-redux an connect method to map store to props. Is there a way I can setState after dispatch?

// actions
export function executeAction() {
  return function (dispatch, getState) {
    dispatch({
      type: 'MY_ACTION',
      payload: axios.get('/some/url')
    });
  };
}
// reducer

export default function (state = {}, action) {
  switch (action.type) {
    case 'MY_ACTION_FULFILLED':
      return {...state, myVariable: action.payload.data}
  }
}
//component
class MyComponent extends Component {
  render() {
    (

      {this.state.variableInState}

)
  }

  someOtherMethod() {
    // I want to operate with state here, not with props
    // that's why my div gets state from this.state instead of this.props
    this.setState({variableInState: 'someValue'})
  }
}

export default connect((state, ownProperties) => {
  return {
    // So I want to change MyComponent.state.variableInState here
    // but this method updates MyComponent props only
    // What can I do?
    variableInProps: state.myVariable
  }
}, {executeAction})(MyComponent);


问:
Service Method called 5 times from Angular Controller
This one has me confounded. I have looked far and wide and am out of ideas. In my searching, I discovered that one of the common reasons for multiple function calls on load is if you have a controller defined in routes and via the ngController directive. Checked this - I do not use ngController. I also checked my routes - seem in order. There are no $watch functions that could be causing $digest issues. This function is called one time, at the bottom of the function, and the console.log is logged out 5x...EVERY TIME. I have even set a $timer function and it still calls it 5x. Have tried creating a variable to only run if it hasn't been run before but it seems like it's all happening with the getQuotas() method. Any help would be greatly appreciated!</p>

```<code>function getQuotas ()
{
    console.log('getQuotas'); //This logs out 5x

    UserService.getQuotas()
    .then(function(res)
    {
        if (res.data.success)
        {
            quotaData = res.data.data;
            getQuotas_success();
            return true;
        }
        else
        {
            getQuotas_failure();
            return false;
        }
    }, function (err)
    {
        getQuotas_failure();
        return false;
    });

}
getQuotas(); //Function is called here.
</code>```

答: Solved it! I'm hopeful this will help others. There was a custom attribute directive on each of 4 input fields on this page. That particular directive was using the same controller as the page itself. So the controller was getting loaded a total of 5 times. Fortunately for me, this directive is now deprecated but I would probably redo it by either creating a directive-level controller and using the 'require' attribute in the directive's return object, pointing to the page-level controller, OR just have the data that needs to get passed between the page-level controller and the directive go through a service. </p>

Body:
This one has me confounded. I have looked far and wide and am out of ideas. In my searching, I discovered that one of the common reasons for multiple function calls on load is if you have a controller defined in routes and via the ngController directive. Checked this - I do not use ngController. I also checked my routes - seem in order. There are no $watch functions that could be causing $digest issues. This function is called one time, at the bottom of the function, and the console.log is logged out 5x...EVERY TIME. I have even set a $timer function and it still calls it 5x. Have tried creating a variable to only run if it hasn't been run before but it seems like it's all happening with the getQuotas() method. Any help would be greatly appreciated!

function getQuotas ()
{
    console.log('getQuotas'); //This logs out 5x

    UserService.getQuotas()
    .then(function(res)
    {
        if (res.data.success)
        {
            quotaData = res.data.data;
            getQuotas_success();
            return true;
        }
        else
        {
            getQuotas_failure();
            return false;
        }
    }, function (err)
    {
        getQuotas_failure();
        return false;
    });

}
getQuotas(); //Function is called here.


问:
.Net Multiline Regex expression to restrict to integers
I am having a problem with a very simple regular expression.

I want to restrict the entry in a multi-line TextBox to just integers. The regular expression I have works fine in single line mode (for a single line TextBox, not using multiline option), but allows alpha characters to creep in when in multiline mode, but only once a new line has been entered.

My code (C#) is something like:

```<code>Regex regExpr = new Regex("^(\d*)$", RegexOptions.Multiline)
return regExpr.IsMatch(testString);
</code>```

I want the following examples to be valid:

```<code>1

1\\n

1\\n2\\n3
</code>```

I want the following to be invalid

```<code>A

A1\\n2

1\\n2\\nA3
</code>```

Thanks in advance.

Body:
I am having a problem with a very simple regular expression.

I want to restrict the entry in a multi-line TextBox to just integers. The regular expression I have works fine in single line mode (for a single line TextBox, not using multiline option), but allows alpha characters to creep in when in multiline mode, but only once a new line has been entered.

My code (C#) is something like:

Regex regExpr = new Regex("^(\d*)$", RegexOptions.Multiline)
return regExpr.IsMatch(testString);

I want the following examples to be valid:

1

1\\n

1\\n2\\n3

I want the following to be invalid

A

A1\\n2

1\\n2\\nA3

Thanks in advance.

Body:
What about

(\d?\\n*)?


问:
C++ STL comparing maps cannot find (operator==)
I am trying to compare two std::map's and the compiler is rejecting it because it can't find an (==) operator.

1>C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\utility(275): error C2678: binary '==': no operator found which takes a left-hand operand of type 'const foo::Value' (or there is no acceptable conversion)

An example follows.

```<code>namespace foo {
    struct Key { int k; };
    struct Value { int val; };
    typedef std::map<Key*,Value> Map;
}

bool operator==(const foo::Value &v1, const foo::Value &v2)
{
    return v1.val == v2.val;
}
bool operator!=(const foo::Value &v1, const foo::Value &v2)
{
    return !(v1 == v2);
}

bool compare(foo::Map &to, const foo::Map &from)
{
    return to != from;
}
</code>```

If I rip out the namespaces, it works.

If define the == operator as a member, it works.

For example:

```<code>struct Value {
    int val;
    bool operator==(const Value &v) const { return val == v.val; }
    bool operator!=(const Value &v) const { return val != v.val; }
};
// elide the other == and !=
</code>```

What am I doing wrong?  For my case, I'd prefer the (==) functions be local to the compilation unit rather than in the interface.

答: If you put the operators inside namespace foo then it works.

Body:
I am trying to compare two std::map's and the compiler is rejecting it because it can't find an (==) operator.

1>C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\utility(275): error C2678: binary '==': no operator found which takes a left-hand operand of type 'const foo::Value' (or there is no acceptable conversion)

An example follows.

namespace foo {
    struct Key { int k; };
    struct Value { int val; };
    typedef std::map<Key*,Value> Map;
}

bool operator==(const foo::Value &v1, const foo::Value &v2)
{
    return v1.val == v2.val;
}
bool operator!=(const foo::Value &v1, const foo::Value &v2)
{
    return !(v1 == v2);
}

bool compare(foo::Map &to, const foo::Map &from)
{
    return to != from;
}

If I rip out the namespaces, it works.

If define the == operator as a member, it works.

For example:

struct Value {
    int val;
    bool operator==(const Value &v) const { return val == v.val; }
    bool operator!=(const Value &v) const { return val != v.val; }
};
// elide the other == and !=

What am I doing wrong?  For my case, I'd prefer the (==) functions be local to the compilation unit rather than in the interface.


问:
How do you programmatically change the alpha of a UIVisualEffectView in a NavigationBar?
I have a scroll view that I'm using to control the alpha of other elements depending on how far down the view the user scrolls.

First, I set up the blur view. Alpha here doesn't seem to take, firstly

```<code>var effect: UIBlurEffectStyle = .light
if #available(iOS 10.0, *) {
    effect = .prominent
}
let blurView = UIVisualEffectView(effect: UIBlurEffect(style: effect))
blurView.alpha = 0
if let navigationBar = navigationController?.navigationBar {
    blurView.frame = navigationBar.bounds
}
self.blurView = blurView
</code>```

Then in my UIScrollViewDelegate:

```<code>func scrollViewDidScroll(_ scrollView: UIScrollView) {
        var alpha = (scrollView.contentOffset.y / 200)
        alpha = alpha > 1.0 ? 1.0 : alpha

        blurView?.alpha = alpha
}
</code>```

This doesn't seem to be working either.

Any advice on how to achieve this effect? Thanks!

答:
Alpha blending of a UIVisualEffectView is broken as of iOS 10, along with layer masking, due to internal change to the implementation by Apple.

I'd suggest using a UIViewPropertyAnimator object to transition from the actual effect (.prominent, in your case) to nil, and then manually set the fractionComplete to be the alpha value. It will give you a much better effect and allow you to interactively change the effect.

Body:
I have a scroll view that I'm using to control the alpha of other elements depending on how far down the view the user scrolls.

First, I set up the blur view. Alpha here doesn't seem to take, firstly

var effect: UIBlurEffectStyle = .light
if #available(iOS 10.0, *) {
    effect = .prominent
}
let blurView = UIVisualEffectView(effect: UIBlurEffect(style: effect))
blurView.alpha = 0
if let navigationBar = navigationController?.navigationBar {
    blurView.frame = navigationBar.bounds
}
self.blurView = blurView

Then in my UIScrollViewDelegate:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
        var alpha = (scrollView.contentOffset.y / 200)
        alpha = alpha > 1.0 ? 1.0 : alpha

        blurView?.alpha = alpha
}

This doesn't seem to be working either.

Any advice on how to achieve this effect? Thanks!


问:
how to retrieve data from JSON into list?
I have a simple JSON with 4 items. I want to just import item 2,3,4 into li in html. With my code imported all items. I am new in JavaScript.

can you please give me some possible way to solve ?

item.json:

```<code>[
  {
    "content": "nopic",
  },
  {
    "content": "pic1.jpg",
  },
  {
    "content": "pic2.jpg",
  },
  {
    "content": "pic3.jpg",
  }
]
</code>```

HTML:

```<code><div>
    <ul>

    </ul>
</div>
</code>```

script:

```<code><script>
$(document).ready( function(){

        $.getJSON('item.json', function(data) {
            $.each(data, function (i, f) {
                $("ul").append("<li><img src=" + f.content + "/></li>");
            });
  });
});
</script>
</code>```

答:
If you whant to remove only the first you can use the Array.slice() function, like this:

```<code>$(document).ready( function(){
  $.getJSON('./item.json', function(data) {
    var dataWithoutFirst = data.slice(1);
    $.each(dataWithoutFirst, function (i, f) {
      $("ul").append("<li><img src=" + f.content + "/></li>");
    });
  });
});
</code>```

If you whant to remove all nopic you can do this:

```<code>$(document).ready( function(){
  $.getJSON('./item.json', function(data) {
    $.each(data, function (i, f) {
      if(f.content != "nopic"){
        $("ul").append("<li><img src=" + f.content + "/></li>");
      }
    });
  });
});
</code>```

See it executing here: https://plnkr.co/edit/WKYRZb0933rZBzKRyIzE

Body:
I have a simple JSON with 4 items. I want to just import item 2,3,4 into li in html. With my code imported all items. I am new in JavaScript.

can you please give me some possible way to solve ?

item.json:

[
  {
    "content": "nopic",
  },
  {
    "content": "pic1.jpg",
  },
  {
    "content": "pic2.jpg",
  },
  {
    "content": "pic3.jpg",
  }
]

HTML:

script:

Body:
If you whant to remove only the first you can use the Array.slice() function, like this:

$(document).ready( function(){
  $.getJSON('./item.json', function(data) {
    var dataWithoutFirst = data.slice(1);
    $.each(dataWithoutFirst, function (i, f) {
      $("ul").append("<li><img src=" + f.content + "/></li>");
    });
  });
});

If you whant to remove all nopic you can do this:

$(document).ready( function(){
  $.getJSON('./item.json', function(data) {
    $.each(data, function (i, f) {
      if(f.content != "nopic"){
        $("ul").append("<li><img src=" + f.content + "/></li>");
      }
    });
  });
});

See it executing here: https://plnkr.co/edit/WKYRZb0933rZBzKRyIzE


问:
Can't publish android library to bintray
I'm literally going crazy trying to publish a library to bintray.

I followed the official guide, as well as several tutorials, but my library was never uploaded to bintray.

The library itself is working fine (at least in my tests).

Here is the build.gradle file of the library module.

I ran the commands

```<code>./gradlew install
</code>```

and then

```<code>./gradlw bintrayUpload
</code>```

Both of them ends with a "BUILD SUCCESSFUL", but in bintray website nothing appear.

What am I doing wrong?

```<code>apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
apply plugin: 'com.jfrog.bintray'
//apply plugin: 'java'

def siteUrl = 'https://github.com/stefanosiano/PowerfulImageView'      // Homepage URL of the library
def gitUrl = 'https://github.com/stefanosiano/PowerfulImageView.git'   // Git repository URL
def libDescription = 'Custom Android ImageView with several added features.'
def gitTag = '0.1.1'
def pkgName = 'powerful-image-view'
def libGroupId = "com.stefanosiano"                                          // Maven Group ID for the artifact
def libArtifactId = "powerful-image-view"                                          // Maven Group ID for the artifact
def libName = "Powerful Image View"                                          // Maven Group ID for the artifact
def libVersion = "0.1.1"// This is the library version used when deploying the artifact

group = libGroupId //bintray org/group name
version = libVersion //version

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 12
        targetSdkVersion 25
        versionCode 1
        versionName libVersion
        consumerProguardFiles 'piv-proguard-rules.txt'

    }
}
dependencies {
    compile 'com.android.support:appcompat-v7:25.3.0'
}

install {
    repositories.mavenInstaller {
        // This generates POM.xml with proper parameters
        pom {
            project {
                packaging 'aar'
                groupId libGroupId
                artifactId libArtifactId

                // Add your description here
                name libName
                description libDescription
                url siteUrl

                // Set your license
                licenses {
                    license {
                        name 'MIT License'
                        url 'https://opensource.org/licenses/MIT'
                    }
                }
                developers {
                    developer {
                        id 'stefanosiano'
                        name 'Stefano Siano'
                        email 'stefano.siano91@gmail.com'
                    }
                }
                scm {
                    connection gitUrl
                    developerConnection gitUrl
                    url siteUrl

                }
            }
        }
    }
}

version = libVersion

if (project.hasProperty("android")) { // Android libraries
    task sourcesJar(type: Jar) {
        classifier = 'sources'
        from android.sourceSets.main.java.srcDirs
    }

    task javadoc(type: Javadoc) {
        source = android.sourceSets.main.java.srcDirs
        classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
    }
} else { // Java libraries
    task sourcesJar(type: Jar, dependsOn: classes) {
        classifier = 'sources'
        from sourceSets.main.allSource
    }
}

task javadocJar(type: Jar, dependsOn: javadoc) {
    classifier = 'javadoc'
    from javadoc.destinationDir
}

artifacts {
    archives javadocJar
    archives sourcesJar
}

// https://github.com/bintray/gradle-bintray-plugin
bintray {
    user = System.getenv('BINTRAY_USER')
    key = System.getenv('BINTRAY_KEY')

    configurations = ['archives']

    // Package info for BinTray
    pkg {
        repo = 'maven-repo'
        // it is the name that appears in bintray when logged
        name = pkgName
        desc = libDescription
        websiteUrl = siteUrl
        vcsUrl = gitUrl
        licenses = ['MIT']
        publish = true
        publicDownloadNumbers = true
        version {
            name = libVersion
            desc = libDescription
            released = new Date()
            vcsTag = gitTag
        }
    }
}
</code>```

Here is my project build.gradle file:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
// Plugin used to upload authenticated files to BinTray through Gradle
plugins {
    id "com.jfrog.bintray" version "1.7.3"
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Thanks for any help, because i'm trying from some day unsuccessfully :(

答:
Ok, for me the problem was that my Fedora lost my environment variables.

After exporting them again, everything worked fine.

I have my first library online! Yay!

Body:
I'm literally going crazy trying to publish a library to bintray.

I followed the official guide, as well as several tutorials, but my library was never uploaded to bintray.

The library itself is working fine (at least in my tests).

Here is the build.gradle file of the library module.

I ran the commands

./gradlew install

and then

./gradlw bintrayUpload

Both of them ends with a "BUILD SUCCESSFUL", but in bintray website nothing appear.

What am I doing wrong?

apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
apply plugin: 'com.jfrog.bintray'
//apply plugin: 'java'

def siteUrl = 'https://github.com/stefanosiano/PowerfulImageView'      // Homepage URL of the library
def gitUrl = 'https://github.com/stefanosiano/PowerfulImageView.git'   // Git repository URL
def libDescription = 'Custom Android ImageView with several added features.'
def gitTag = '0.1.1'
def pkgName = 'powerful-image-view'
def libGroupId = "com.stefanosiano"                                          // Maven Group ID for the artifact
def libArtifactId = "powerful-image-view"                                          // Maven Group ID for the artifact
def libName = "Powerful Image View"                                          // Maven Group ID for the artifact
def libVersion = "0.1.1"// This is the library version used when deploying the artifact

group = libGroupId //bintray org/group name
version = libVersion //version

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 12
        targetSdkVersion 25
        versionCode 1
        versionName libVersion
        consumerProguardFiles 'piv-proguard-rules.txt'

    }
}
dependencies {
    compile 'com.android.support:appcompat-v7:25.3.0'
}

install {
    repositories.mavenInstaller {
        // This generates POM.xml with proper parameters
        pom {
            project {
                packaging 'aar'
                groupId libGroupId
                artifactId libArtifactId

                // Add your description here
                name libName
                description libDescription
                url siteUrl

                // Set your license
                licenses {
                    license {
                        name 'MIT License'
                        url 'https://opensource.org/licenses/MIT'
                    }
                }
                developers {
                    developer {
                        id 'stefanosiano'
                        name 'Stefano Siano'
                        email 'stefano.siano91@gmail.com'
                    }
                }
                scm {
                    connection gitUrl
                    developerConnection gitUrl
                    url siteUrl

                }
            }
        }
    }
}

version = libVersion

if (project.hasProperty("android")) { // Android libraries
    task sourcesJar(type: Jar) {
        classifier = 'sources'
        from android.sourceSets.main.java.srcDirs
    }

    task javadoc(type: Javadoc) {
        source = android.sourceSets.main.java.srcDirs
        classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
    }
} else { // Java libraries
    task sourcesJar(type: Jar, dependsOn: classes) {
        classifier = 'sources'
        from sourceSets.main.allSource
    }
}

task javadocJar(type: Jar, dependsOn: javadoc) {
    classifier = 'javadoc'
    from javadoc.destinationDir
}

artifacts {
    archives javadocJar
    archives sourcesJar
}

// https://github.com/bintray/gradle-bintray-plugin
bintray {
    user = System.getenv('BINTRAY_USER')
    key = System.getenv('BINTRAY_KEY')

    configurations = ['archives']

    // Package info for BinTray
    pkg {
        repo = 'maven-repo'
        // it is the name that appears in bintray when logged
        name = pkgName
        desc = libDescription
        websiteUrl = siteUrl
        vcsUrl = gitUrl
        licenses = ['MIT']
        publish = true
        publicDownloadNumbers = true
        version {
            name = libVersion
            desc = libDescription
            released = new Date()
            vcsTag = gitTag
        }
    }
}

Here is my project build.gradle file:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
// Plugin used to upload authenticated files to BinTray through Gradle
plugins {
    id "com.jfrog.bintray" version "1.7.3"
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Thanks for any help, because i'm trying from some day unsuccessfully :(


问:
Convert text Amount to decimal - ssis
In my source file I have amount column with values

eg:

```<code>Amount
380.00
2,435.00
</code>```

So when I try to load this in to the destination, I wish to convert the value in to int(12).

How to do this conversion by removing . and , from the text and load in to the destination.

答:
Convert() or Try_Convert() to money will handle commas and $ as well.</p>

```<code>Select try_convert(money,'2,435.00')    -- 2435.00
Select try_convert(money,'$2,435.00')   -- 2435.00
</code>```

Title: Convert text Amount to decimal - ssis

Body:
In my source file I have amount column with values

eg:

Amount
380.00
2,435.00

So when I try to load this in to the destination, I wish to convert the value in to int(12).

How to do this conversion by removing . and , from the text and load in to the destination.

Body:
Convert() or Try_Convert() to money will handle commas and $ as well.

Select try_convert(money,'2,435.00')    -- 2435.00
Select try_convert(money,'$2,435.00')   -- 2435.00


问:
Php add calendar months to a date
I would like to add some calendar month to a date. I have done in javascript, but I would make the same function in Php (I'm newer).
This is javascript code:

var date = '2017-08-30';
var addMonth=6;
var arrDate = date.split("-");
var dateSrt = new Date(date);
var newSrvDate = new Date(dateSrt.getTime());

newSrvDate.setMonth(dateSrt.getMonth() + (addMonth), arrDate[2]);
if (newSrvDate.getMonth() > (dateSrt.getMonth() + (addMonth)) % 12) {
    newSrvDate.setDate(0);
}
srvDay = new Date(newSrvDate.getFullYear(), newSrvDate.getMonth() , newSrvDate.getDate());
alert("Start:"+dateSrt);
alert("End:"+srvDay);```

In this case if I add 6 months to 2017-08-30 will be 2018-02-30, but it doesn't exist, so it become 2018-03-02.
I would like that if the date exist ok, in other case the last day of the month...

I hope I'm clear... the code work perfectly in javascript, but I can not reproduce it in php

Any suggestions ere welcome

答:
It's easy using DateTimeand DateInterval PHP classes.

The following code will take a string formatted as "Y-m-d" (4 digits year, 2 digits month, 2 digits day, dash separated) convert it to a DateTime object, add 6 months, then turn back the DateTime into a string according to the original format.

The code is actually self explanatory...

```<code><?php
$dateStr = '2017-08-30';

$date = DateTime::createFromFormat( 'Y-m-d', $dateStr );
$interval = DateInterval::createFromDateString('6 months');
$date->add( $interval );

$dateStr = $date->format( 'Y-m-d' );

echo "$dateStr\n"; // outputs 2018-03-02
</code>```

For your reference:

http://php.net/manual/en/class.datetime.php

http://php.net/manual/en/datetime.createfromformat.php

http://php.net/manual/en/datetime.add.php

http://php.net/manual/en/dateinterval.createfromdatestring.php

Title: Php add calendar months to a date

Body:
I would like to add some calendar month to a date. I have done in javascript, but I would make the same function in Php (I'm newer).
This is javascript code:

var date = '2017-08-30';
var addMonth=6;
var arrDate = date.split("-");
var dateSrt = new Date(date);
var newSrvDate = new Date(dateSrt.getTime());

newSrvDate.setMonth(dateSrt.getMonth() + (addMonth), arrDate[2]);
if (newSrvDate.getMonth() > (dateSrt.getMonth() + (addMonth)) % 12) {
    newSrvDate.setDate(0);
}
srvDay = new Date(newSrvDate.getFullYear(), newSrvDate.getMonth() , newSrvDate.getDate());
alert("Start:"+dateSrt);
alert("End:"+srvDay);

In this case if I add 6 months to 2017-08-30 will be 2018-02-30, but it doesn't exist, so it become 2018-03-02.
I would like that if the date exist ok, in other case the last day of the month...

I hope I'm clear... the code work perfectly in javascript, but I can not reproduce it in php

Any suggestions ere welcome

Body:
It's easy using DateTimeand DateInterval PHP classes.

The following code will take a string formatted as "Y-m-d" (4 digits year, 2 digits month, 2 digits day, dash separated) convert it to a DateTime object, add 6 months, then turn back the DateTime into a string according to the original format.

The code is actually self explanatory...

<?php
$dateStr = '2017-08-30';

$date = DateTime::createFromFormat( 'Y-m-d', $dateStr );
$interval = DateInterval::createFromDateString('6 months');
$date->add( $interval );

$dateStr = $date->format( 'Y-m-d' );

echo "$dateStr\n"; // outputs 2018-03-02

For your reference:

http://php.net/manual/en/class.datetime.php

http://php.net/manual/en/datetime.createfromformat.php

http://php.net/manual/en/datetime.add.php

http://php.net/manual/en/dateinterval.createfromdatestring.php


问:
Distance between lat/long points using the haversine formula
I am trying to find the distance between two longitude and latitude points.  I am trying ot use the great circle distance.  This is the formula:

I am not sure why but my program is not working.  This is the result I am getting:

```<code>Change Angle: 0.00016244370761414
Earth Radius: 6371

RESULTS:
Correct  Distance: 24.883 km
Computed Distance: 1.0349288612097
</code>```

Source:

```<code>$latStart = 44.638;
$longStart = -63.587;

$latFinish = 44.644;
$longFinish = -63.597;

# Convert Input to Radians
$latStart = deg2Rad($latStart);
$longStart = deg2Rad($longStart);

$latFinish = deg2Rad($latFinish);
$longFinish = deg2Rad($longFinish);

# Because the Earth is not perfectly spherical, no single value serves as its
# natural radius. Distances from points on the surface to the center range from
# 6,353 km to 6,384 km (≈3,947–3,968 mi). Several different ways of modeling the
# Earth as a sphere each yield a convenient mean radius of 6371 km (≈3,959 mi).
# http://en.wikipedia.org/wiki/Earth_radius
$earthRadius = 6371;

# difference in Long/Lat
$latChange = $latFinish - $latStart;
$longChange = $longFinish - $longStart;

# haversine formula
# numerically stable for small distances
# http://en.wikipedia.org/wiki/Great-circle_distance
$changeAngle = 2 * asin(
                sqrt(
                        pow(sin($latChange/2),2) +
                        cos($latStart) * cos($latFinish) * pow(sin($longChange/2),2)
                )
        );

echo "Change Angle: $changeAngle\n";
echo "Earth Radius: $earthRadius\n";
</code>```

答:
Your approach is loosely based on Pythagoras' Theorem -- I've always done it the hard way, i.e. something like (In reality, I pre-calculate the values for the axis and store them in the database alongside the data):</p>

```<code>$startXAxis   = cos(deg2Rad($latStart)) * cos(deg2Rad($longStart));
$startYAxis   = cos(deg2Rad($latStart)) * sin(deg2Rad($longStart));
$startZAxis   = sin(deg2Rad($latStart));
$finishXAxis   = cos(deg2Rad($latFinish)) * cos(deg2Rad($longFinish));
$finishYAxis   = cos(deg2Rad($latFinish)) * sin(deg2Rad($longFinish));
$finishZAxis   = sin(deg2Rad($latFinish));

$changeAngle = acos($startXAxis * $finishXAxis + $startYAxis * $finishYAxis + $startZAxis * $finishZAxis);
</code>```

Body:
I am trying to find the distance between two longitude and latitude points.  I am trying ot use the great circle distance.  This is the formula:

I am not sure why but my program is not working.  This is the result I am getting:

Change Angle: 0.00016244370761414
Earth Radius: 6371

RESULTS:
Correct  Distance: 24.883 km
Computed Distance: 1.0349288612097

Source:

$latStart = 44.638;
$longStart = -63.587;

$latFinish = 44.644;
$longFinish = -63.597;

# Convert Input to Radians
$latStart = deg2Rad($latStart);
$longStart = deg2Rad($longStart);

$latFinish = deg2Rad($latFinish);
$longFinish = deg2Rad($longFinish);

# Because the Earth is not perfectly spherical, no single value serves as its
# natural radius. Distances from points on the surface to the center range from
# 6,353 km to 6,384 km (≈3,947–3,968 mi). Several different ways of modeling the
# Earth as a sphere each yield a convenient mean radius of 6371 km (≈3,959 mi).
# http://en.wikipedia.org/wiki/Earth_radius
$earthRadius = 6371;

# difference in Long/Lat
$latChange = $latFinish - $latStart;
$longChange = $longFinish - $longStart;

# haversine formula
# numerically stable for small distances
# http://en.wikipedia.org/wiki/Great-circle_distance
$changeAngle = 2 * asin(
                sqrt(
                        pow(sin($latChange/2),2) +
                        cos($latStart) * cos($latFinish) * pow(sin($longChange/2),2)
                )
        );

echo "Change Angle: $changeAngle\n";
echo "Earth Radius: $earthRadius\n";

Body:
Your approach is loosely based on Pythagoras' Theorem -- I've always done it the hard way, i.e. something like (In reality, I pre-calculate the values for the axis and store them in the database alongside the data):

$startXAxis   = cos(deg2Rad($latStart)) * cos(deg2Rad($longStart));
$startYAxis   = cos(deg2Rad($latStart)) * sin(deg2Rad($longStart));
$startZAxis   = sin(deg2Rad($latStart));
$finishXAxis   = cos(deg2Rad($latFinish)) * cos(deg2Rad($longFinish));
$finishYAxis   = cos(deg2Rad($latFinish)) * sin(deg2Rad($longFinish));
$finishZAxis   = sin(deg2Rad($latFinish));

$changeAngle = acos($startXAxis * $finishXAxis + $startYAxis * $finishYAxis + $startZAxis * $finishZAxis);


问:
WEKA software analysis for calculating total accuracy
Hi i am using WEKA to analyze some data. But i am having problem how to calculate the total accuracy from the output data.

The partial output is bellow

Detailed Accuracy By Class

```<code>           TP Rate   FP Rate   Precision   Recall  F-Measure   ROC Area  Class
             0.85      0.415      0.794     0.85      0.821      0.762    tested_negative
             0.585     0.15       0.676     0.585     0.627      0.762    tested_positive
</code>```

Weighted Avg.    0.758     0.323      0.753     0.758     0.754      0.762

From the above what will the total accuracy?

答: You can see the correctly classified instances reported in the summary part (a little bit above the part it's reporting the accuracy by class). in front of this part you can see a number (which indicates the number of instances) and a percentage (which is the accuracy).

Body:
Hi i am using WEKA to analyze some data. But i am having problem how to calculate the total accuracy from the output data.

The partial output is bellow

Detailed Accuracy By Class

           TP Rate   FP Rate   Precision   Recall  F-Measure   ROC Area  Class
             0.85      0.415      0.794     0.85      0.821      0.762    tested_negative
             0.585     0.15       0.676     0.585     0.627      0.762    tested_positive

Weighted Avg.    0.758     0.323      0.753     0.758     0.754      0.762

From the above what will the total accuracy?


问:
Python parser that makes parentheses according arithmetic priority
How to make a parser that will make parentheses according arithmetical priority in expressions using the pyparsing library?
for example * has higher priority than +.

It should do like this:

```<code>»> print(wholeexp.parseString('3+5-2'))
[[['3', '+', '5'], '-', '2']]
»> print(wholeexp.parseString('3+(5-2)'))
[['3', '+', ['5', '-', '2']]]
»> print(wholeexp.parseString('3+5-2*4'))
[[['3', '+', '5'], '-', ['2', '*', '4']]]
</code>```

I tried the following, but it doesn't work very well. How should we change expr here:

```<code>from pyparsing import *

numb = Word(nums)
leftpar = Suppress('(')
rightpar = Suppress(')')

expr = Forward()
expr << Or( [numb,
    Group(leftpar + expr + "+" + expr + rightpar),
    Group(leftpar + expr + "-" + expr + rightpar),
    Group(leftpar + expr + "*" + expr + rightpar)] )

wholeexp = expr + StringEnd()
</code>```

答:
This article seems promising: Simple Top-Down Parsing in Python
I know it's a lot but scroll to the bottom of the "Streamlining Token Class Generation" section and you will see it in action. I personally couldn't get it to work because of an error: AttributeError: 'generator' object has no attribute 'next' but I'm pretty sure it has to do with the fact that the next method was changed in python 3.0. The code's to complicated for me to understand and fix the problem but you might have better luck.

Edit: Just ran it in python 2.7 and it worked. You can either run it in an older version of python or go through the code and try to fix it.

Body:
How to make a parser that will make parentheses according arithmetical priority in expressions using the pyparsing library?
for example * has higher priority than +.

It should do like this:

»> print(wholeexp.parseString('3+5-2'))
[[['3', '+', '5'], '-', '2']]
»> print(wholeexp.parseString('3+(5-2)'))
[['3', '+', ['5', '-', '2']]]
»> print(wholeexp.parseString('3+5-2*4'))
[[['3', '+', '5'], '-', ['2', '*', '4']]]

I tried the following, but it doesn't work very well. How should we change expr here:

from pyparsing import *

numb = Word(nums)
leftpar = Suppress('(')
rightpar = Suppress(')')

expr = Forward()
expr << Or( [numb,
    Group(leftpar + expr + "+" + expr + rightpar),
    Group(leftpar + expr + "-" + expr + rightpar),
    Group(leftpar + expr + "*" + expr + rightpar)] )

wholeexp = expr + StringEnd()


问:
Java-Abstract method not overridden
Can you help with one of the true/false questions asked in my test today:

If an abstract method is inherited by a subclass but is not overridden the whole subclass becomes abstract. Would this be true or false?

答:
take a look at:

https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

It says:

When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.

Title: Java-Abstract method not overridden


问:
React Native to limit lines in TextInput
If set multiline as true, React Native will accept unlimited lines in TextInput, there has maxLength but it just limits the maximum number of characters, so how to set maximum lines on TextInput?</p>

答: It seems no props or packages to quickly implement checking number of lines, so I use javascript function match to get the number from TextInput, then if the number reach the max value, do something to limit it.


问:
Jquery's $.get call does not return data in Chrome
I have a simple code as follows which make a get call to a django backend to retrieve some string. However, the success function displays an empty string in Google Chrome. In Internet Explorer, the expected string is display.

```<code>$.get(url, function(data) {alert(data);} );
</code>```

Django class:

```<code>def lookup(request):
    message= "looking up"
    print message
    return HttpResponse("isss",mimetype="application/text")
</code>```

The Ajax is definitely successful in Chrome so I dont understand why it works in IE and not in Chrome? Could it be some security issue in Chrome?

Thanks in Advance!

答:
Your content type on your request should read 'text/plain'. This is the only part of your problem that would probably be browser based.

In addition, if your not already testing your ajax pieces in FireBug helps quite a lot. I am willing to bet FireBug would have showed you the full request/response.

Body:
I have a simple code as follows which make a get call to a django backend to retrieve some string. However, the success function displays an empty string in Google Chrome. In Internet Explorer, the expected string is display.

$.get(url, function(data) {alert(data);} );

Django class:

def lookup(request):
    message= "looking up"
    print message
    return HttpResponse("isss",mimetype="application/text")

The Ajax is definitely successful in Chrome so I dont understand why it works in IE and not in Chrome? Could it be some security issue in Chrome?

Thanks in Advance!


问:
JTabbedPane ArrayIndexOutOfBoundsException: 0
I am trying to create a tabbed pane in my Java Swing application, but it's not working.

When setting a JTabbedPane as the contentpane, everything goes fine. As soon as I try to add a tab, I get an ArrayIndexOutOfBoundsException: 0.

The component gets added to the pane nonetheless, it's just that this error is thrown. My code and the error are down below.

Code:

```<code>// This all happens in a class which extends JFrame

private JTabbedPane contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                ConfigBuilderWindow frame = new ConfigBuilderWindow();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public ConfigBuilderWindow() {
    setTitle("Config Builder");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 916, 617);
    contentPane = new JTabbedPane();
    contentPane.setBorder(new LineBorder(Color.BLUE, 4));
    contentPane.setLayout(new BorderLayout(0, 0));

    contentPane.addTab("Test1", new JButton("Test1"));
    contentPane.addTab("Test2", new JButton("Test2"));

    setContentPane(contentPane);
}
</code>```

Error:

```<code>Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
at javax.swing.plaf.basic.BasicTabbedPaneUI.paintTabArea(Unknown Source)
at javax.swing.plaf.basic.BasicTabbedPaneUI.paint(Unknown Source)
at javax.swing.plaf.metal.MetalTabbedPaneUI.paint(Unknown Source)
at javax.swing.plaf.metal.MetalTabbedPaneUI.update(Unknown Source)
at javax.swing.JComponent.paintComponent(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JLayeredPane.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at java.awt.GraphicsCallback$PaintCallback.run(Unknown Source)
at sun.awt.SunGraphicsCallback.runOneComponent(Unknown Source)
at sun.awt.SunGraphicsCallback.runComponents(Unknown Source)
at java.awt.Container.paint(Unknown Source)
at java.awt.Window.paint(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$1200(Unknown Source)
at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
</code>```

I hope anyone knows what's going on.

答:
I'm not sure why you're setting a BorderLayout to the contentPane, I recommend you to change the variable name to tabbedPane and remove this line:

```<code>tabbedPane.setLayout(new BorderLayout(0, 0));
</code>```

This fixes the error.

If you want to edit the layout of the tab, then create a JPanel with that layout and pass it as parameter instead of your JButtons.

Another thing to note is not calling setBounds but pack() and setLocation() or setLocationRelativeTo or setLocationByPlatform() methods instead

Now, as an aside note, don't extend JFrame, see The use of multiple JFrames, Good / Bad practice? (The general consensus says it's a bad practice). Also see Extends JFrame vs creating it inside of class

Body:
I am trying to create a tabbed pane in my Java Swing application, but it's not working.

When setting a JTabbedPane as the contentpane, everything goes fine. As soon as I try to add a tab, I get an ArrayIndexOutOfBoundsException: 0.

The component gets added to the pane nonetheless, it's just that this error is thrown. My code and the error are down below.

Code:

// This all happens in a class which extends JFrame

private JTabbedPane contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                ConfigBuilderWindow frame = new ConfigBuilderWindow();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public ConfigBuilderWindow() {
    setTitle("Config Builder");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 916, 617);
    contentPane = new JTabbedPane();
    contentPane.setBorder(new LineBorder(Color.BLUE, 4));
    contentPane.setLayout(new BorderLayout(0, 0));

    contentPane.addTab("Test1", new JButton("Test1"));
    contentPane.addTab("Test2", new JButton("Test2"));

    setContentPane(contentPane);
}

Error:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
at javax.swing.plaf.basic.BasicTabbedPaneUI.paintTabArea(Unknown Source)
at javax.swing.plaf.basic.BasicTabbedPaneUI.paint(Unknown Source)
at javax.swing.plaf.metal.MetalTabbedPaneUI.paint(Unknown Source)
at javax.swing.plaf.metal.MetalTabbedPaneUI.update(Unknown Source)
at javax.swing.JComponent.paintComponent(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JLayeredPane.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at java.awt.GraphicsCallback$PaintCallback.run(Unknown Source)
at sun.awt.SunGraphicsCallback.runOneComponent(Unknown Source)
at sun.awt.SunGraphicsCallback.runComponents(Unknown Source)
at java.awt.Container.paint(Unknown Source)
at java.awt.Window.paint(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$1200(Unknown Source)
at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

I hope anyone knows what's going on.

Body:
I'm not sure why you're setting a BorderLayout to the contentPane, I recommend you to change the variable name to tabbedPane and remove this line:

tabbedPane.setLayout(new BorderLayout(0, 0));

This fixes the error.

If you want to edit the layout of the tab, then create a JPanel with that layout and pass it as parameter instead of your JButtons.

Another thing to note is not calling setBounds but pack() and setLocation() or setLocationRelativeTo or setLocationByPlatform() methods instead

Now, as an aside note, don't extend JFrame, see The use of multiple JFrames, Good / Bad practice? (The general consensus says it's a bad practice). Also see Extends JFrame vs creating it inside of class


问:
XML Parsing - Erlang
I want to parse XML strings to erlang list and then to JSON.

Example Input :

```<code><?xml version="1.0" encoding="UTF-8"?>
<!--some message here-->
<start>
   <data>
      <number id="333">test message</number>
      <data>current date</data>
   </data>
   <mass>
      <client>35</client>
      <address>lattitude</address>
      <code>3454343</code>
      <foo tipo="casa">Some text message 2</foo>
      <product>TEST</product>
   </mass>
</start>
</code>```

Output should be:

```<code>{
  "start": {
    "data": {
      "number": {
        "@id": "333",
        "#text": "test message"
      },
      "data": "current date"
    },
    "mass": {
      "client": "35",
      "address": "lattitude",
      "code": "3454343",
      "foo": {
        "@tipo": "casa",
        "#text": "Some text message 2"
      },
      "product": "TEST"
    }
  }
}
</code>```

I am trying to use erlsom:simple_form(Xml).

and getting :

```<code>{ok,{"start",[],
     [{"data",[],
       [{"number",[{"id","333"}],["test message"]},
        {"data",[],["current date"]}]},
      {"mass",[],
       [{"client",[],["35"]},
        {"address",[],["lattitude"]},
        {"code",[],["3454343"]},
        {"foo",[{"tipo","casa"}],["Some text message 2"]},
        {"product",[],["TEST"]}]}]},
    []}
</code>```

Now I want to delete these empty attrs. Is there any simple way to do this?
thanks in advance.

UPDATE: Make it work w/ solution from
Erlang xml to tuples and lists

BUT Getting

```<code>{"start",
 [{"data",
   [{"number","test message"},{"data","current date"}]},
  {"mass",
   [{"client","35"},
    {"address","lattitude"},
    {"code","3454343"},
    {"foo","Some text message 2"},
    {"product","TEST"}]}]}
</code>```

there is no [{"id","333"}] & [{"tipo","casa"}] lists :(

答:
The output of your simple parsing is in a set format: {Node, Attributes, Children}, so you can write a simple parser that turns that structure you have into a nested proplist. With that, you can either use mochijson or jsx to turn that proplist into a JSON string.

```<code>-module(transform).

-export([test/0]).

test() -> parse(data()).

parse({Node, [], [Value]}) when is_list(Value) ->
    [{Node, Value}];
parse({Node, [], Children}) ->
    V = children_to_struct(Children, []),
    [{Node, V}];
parse({Node, Attributes, Children}) ->
    V = attributes_to_struct(Attributes, []) ++ children_to_struct(Children, []),
    [{Node, V}].

children_to_struct([], Acc) -> Acc;
children_to_struct([Value], Acc) when is_list(Value) ->
    Acc ++ [{"#text", Value}];
children_to_struct([Value | T], Acc) when is_tuple(Value) ->
    children_to_struct(T, Acc ++ parse(Value)).

attributes_to_struct([], Acc) -> Acc;
attributes_to_struct([{K, V}|T], Acc) ->
    attributes_to_struct(T, Acc ++ [{"@" ++ K, V}]).

data() ->
    {"start",[],
     [{"data",[],
       [{"number",[{"id","333"}],["test message"]},
        {"data",[],["current date"]}]},
      {"mass",[],
       [{"client",[],["35"]},
        {"address",[],["lattitude"]},
        {"code",[],["3454343"]},
        {"foo",[{"tipo","casa"}],["Some text message 2"]},
        {"product",[],["TEST"]}]}]}.
</code>```

Running it in the shell with mochijson:

```<code>Eshell V7.3  (abort with ^G)
1> c(transform).
{ok,transform}
2> T = transform:test().
[{"start",
  [{"data",
    [{"number",[{"@id","333"},{"#text","test message"}]},
     {"data","current date"}]},
   {"mass",
    [{"client","35"},
     {"address","lattitude"},
     {"code","3454343"},
     {"foo",[{"@tipo","casa"},{"#text","Some text message 2"}]},
     {"product","TEST"}]}]}]
3>
4> iolist_to_binary(mochijson2:encode(T)).
<<"{\"start\":{\"data\":{\"number\":{\"@id\":[51,51,51],\"#text\":[116,101,115,116,32,109,101,115,115,97,103,101]},\"data\":{\"#text"...>>
</code>```

Title: XML Parsing - Erlang

Body:
I want to parse XML strings to erlang list and then to JSON.

Example Input :

<?xml version="1.0" encoding="UTF-8"?>

<start>
   <data>
      <number id="333">test message</number>
      <data>current date</data>
   </data>
   <mass>
      <client>35</client>
      <address>lattitude</address>
      3454343
      <foo tipo="casa">Some text message 2</foo>
      <product>TEST</product>
   </mass>
</start>

Output should be:

{
  "start": {
    "data": {
      "number": {
        "@id": "333",
        "#text": "test message"
      },
      "data": "current date"
    },
    "mass": {
      "client": "35",
      "address": "lattitude",
      "code": "3454343",
      "foo": {
        "@tipo": "casa",
        "#text": "Some text message 2"
      },
      "product": "TEST"
    }
  }
}

I am trying to use erlsom:simple_form(Xml).

and getting :

{ok,{"start",[],
     [{"data",[],
       [{"number",[{"id","333"}],["test message"]},
        {"data",[],["current date"]}]},
      {"mass",[],
       [{"client",[],["35"]},
        {"address",[],["lattitude"]},
        {"code",[],["3454343"]},
        {"foo",[{"tipo","casa"}],["Some text message 2"]},
        {"product",[],["TEST"]}]}]},
    []}

Now I want to delete these empty attrs. Is there any simple way to do this?
thanks in advance.

UPDATE: Make it work w/ solution from
Erlang xml to tuples and lists

BUT Getting

{"start",
 [{"data",
   [{"number","test message"},{"data","current date"}]},
  {"mass",
   [{"client","35"},
    {"address","lattitude"},
    {"code","3454343"},
    {"foo","Some text message 2"},
    {"product","TEST"}]}]}

there is no [{"id","333"}] & [{"tipo","casa"}] lists :(

Body:
The output of your simple parsing is in a set format: {Node, Attributes, Children}, so you can write a simple parser that turns that structure you have into a nested proplist. With that, you can either use mochijson or jsx to turn that proplist into a JSON string.

-module(transform).

-export([test/0]).

test() -> parse(data()).

parse({Node, [], [Value]}) when is_list(Value) ->
    [{Node, Value}];
parse({Node, [], Children}) ->
    V = children_to_struct(Children, []),
    [{Node, V}];
parse({Node, Attributes, Children}) ->
    V = attributes_to_struct(Attributes, []) ++ children_to_struct(Children, []),
    [{Node, V}].

children_to_struct([], Acc) -> Acc;
children_to_struct([Value], Acc) when is_list(Value) ->
    Acc ++ [{"#text", Value}];
children_to_struct([Value | T], Acc) when is_tuple(Value) ->
    children_to_struct(T, Acc ++ parse(Value)).

attributes_to_struct([], Acc) -> Acc;
attributes_to_struct([{K, V}|T], Acc) ->
    attributes_to_struct(T, Acc ++ [{"@" ++ K, V}]).

data() ->
    {"start",[],
     [{"data",[],
       [{"number",[{"id","333"}],["test message"]},
        {"data",[],["current date"]}]},
      {"mass",[],
       [{"client",[],["35"]},
        {"address",[],["lattitude"]},
        {"code",[],["3454343"]},
        {"foo",[{"tipo","casa"}],["Some text message 2"]},
        {"product",[],["TEST"]}]}]}.

Running it in the shell with mochijson:

Eshell V7.3  (abort with ^G)
1> c(transform).
{ok,transform}
2> T = transform:test().
[{"start",
  [{"data",
    [{"number",[{"@id","333"},{"#text","test message"}]},
     {"data","current date"}]},
   {"mass",
    [{"client","35"},
     {"address","lattitude"},
     {"code","3454343"},
     {"foo",[{"@tipo","casa"},{"#text","Some text message 2"}]},
     {"product","TEST"}]}]}]
3>
4> iolist_to_binary(mochijson2:encode(T)).
<<"{\"start\":{\"data\":{\"number\":{\"@id\":[51,51,51],\"#text\":[116,101,115,116,32,109,101,115,115,97,103,101]},\"data\":{\"#text"...>>


问:
ASP.NET Validator with dynamic error text
I need some dynamic text in my validator ErrorMessage.

This is what I'm trying to do, but it doesn't work:

```<code><td>
  <asp:TextBox runat="server" ID="tbIncome_A_3" MaxLength="12"></asp:TextBox>
  <asp:CompareValidator ID="comvIncome_A_3" runat="server" ControlToValidate="tbIncome_A_3" Display="Dynamic" Operator="DataTypeCheck" Type="Currency"
    ErrorMessage="*Value entered for <%=DateTime.Today.Year - 3 %> Income must be a dollar value.">
    <span class="alert">*</span>
  </asp:CompareValidator>
</td>
...
<div>
  <asp:ValidationSummary ID="vs" runat="server" CssClass="alert alert-danger alert-dismissible" HeaderText="This page has been saved, but it's not complete." ForeColor="" EnableClientScript="false" EnableViewState="false" />
</div>
</code>```

I expect <%=DateTime.Today.Year - 3 %> to render as '2014' in the ValidationSummary, but it instead renders as plaintext.  I feel like I'm missing something very trivial to make this work.

答:
It can be done like this:

```<code>ErrorMessage='<%# "*Value entered for " + DateTime.Today.AddYears(-3).Year + " Income must be a dollar" %>'
</code>```

However you will need to call DataBind(); in the Page_Load of your page.
So since you do need to modify the code behind anyway, why not set the error message from there... (DataBind() not needed then)

```<code>tbIncome_A_3.ErrorMessage = "*Value entered for " + DateTime.Today.AddYears(-3).Year + " Income must be a dollar";
</code>```

Body:
I need some dynamic text in my validator ErrorMessage.

This is what I'm trying to do, but it doesn't work:

  <asp:TextBox runat="server" ID="tbIncome_A_3" MaxLength="12"></asp:TextBox>
  <asp:CompareValidator ID="comvIncome_A_3" runat="server" ControlToValidate="tbIncome_A_3" Display="Dynamic" Operator="DataTypeCheck" Type="Currency"
    ErrorMessage="*Value entered for <%=DateTime.Today.Year - 3 %> Income must be a dollar value.">
    *
  </asp:CompareValidator>

...

  <asp:ValidationSummary ID="vs" runat="server" CssClass="alert alert-danger alert-dismissible" HeaderText="This page has been saved, but it's not complete." ForeColor="" EnableClientScript="false" EnableViewState="false" />

I expect <%=DateTime.Today.Year - 3 %> to render as '2014' in the ValidationSummary, but it instead renders as plaintext.  I feel like I'm missing something very trivial to make this work.

Body:
It can be done like this:

ErrorMessage='<%# "*Value entered for " + DateTime.Today.AddYears(-3).Year + " Income must be a dollar" %>'

However you will need to call DataBind(); in the Page_Load of your page.
So since you do need to modify the code behind anyway, why not set the error message from there... (DataBind() not needed then)

tbIncome_A_3.ErrorMessage = "*Value entered for " + DateTime.Today.AddYears(-3).Year + " Income must be a dollar";


问:
Message error after deleting all rows (codeigniter)
I have made a program that fetch data from a database and show a table with different rows.

The problem is when i want to delete every single row in the table :/

After deleting all rows in a table i got this error:

Here is my home file:

```<code>    <tbody>
    <?php
        foreach($records as $record) {

            echo "<tr>
                      <td>".$record->id."</td>
                      <td>".$record->carrera."</td>
                      <td>".$record->nombre."</td>
                      <td>".$record->descripcion."</td>
                      <td>".$record->carga_horaria."</td>
                      <td align='center'>
                        <a href='".site_url('Home/edit')."/$record->id'>
                         <button type='button' class='btn btn-primary'>EDIT</button></a> |
                        <a href='".site_url('Home/delete')."/$record->id'>
                         <button type='button' class='btn btn-danger'>DELETE</button></a>

                  </tr>";
        }
    ?>

</tbody>
</code>```

Here is my controller file (with index and delete functions)

```<code>    class Home extends CI_Controller{

     public function __construct(){
         parent::__construct();

         $this->load->model("Crudmodel");

    }
    public function index(){

        $data['records'] = $this->Crudmodel->getRecords();

        $this->load->view('home', $data);

    }
    public function delete($id){

        $this->db->where('id',$id);
        $this->db->delete('materias');

        redirect('Home/index');

    }
</code>```

Model file:

Dont know what to do :S

答:
You need to check if you have $records before looping through them:

```<code>if (count($records) > 0 && $records != false) {

  foreach($records as $record) {

    // the rest of your code
  }

}
</code>```

Body:
I have made a program that fetch data from a database and show a table with different rows.

The problem is when i want to delete every single row in the table :/

After deleting all rows in a table i got this error:

Here is my home file:

    <?php
        foreach($records as $record) {

            echo "

                      ".$record->id."
                      ".$record->carrera."
                      ".$record->nombre."
                      ".$record->descripcion."
                      ".$record->carga_horaria."

                        id'>
                         <button type='button' class='btn btn-primary'>EDIT</button> |
                        id'>
                         <button type='button' class='btn btn-danger'>DELETE</button>

";
        }
    ?>

Here is my controller file (with index and delete functions)

    class Home extends CI_Controller{

     public function __construct(){
         parent::__construct();

         $this->load->model("Crudmodel");

    }
    public function index(){

        $data['records'] = $this->Crudmodel->getRecords();

        $this->load->view('home', $data);

    }
    public function delete($id){

        $this->db->where('id',$id);
        $this->db->delete('materias');

        redirect('Home/index');

    }

Model file:

Dont know what to do :S

Body:
You need to check if you have $records before looping through them:

if (count($records) > 0 && $records != false) {

  foreach($records as $record) {

    // the rest of your code
  }

}


问:
Why am I having so much trouble submitting my app to Apple?
This is my first time trying to submit an app to Apple, and I'm having a bunch of issues. I'm pretty sure I've generated all my certificates, AppID's, etc... I've been running the app on my phone just fine, then all of a sudden I started getting errors submitting. My first error was this:

But as you can see, the Bundle ID's are the same:

The ID in Xcode:

And the ID in iTunes Connect:

So I tried changing the Bundle ID, and made sure the Bundle ID's were the same across iTunes connect, Xcode, etc. I started out the project with a different name. Should I just start a new project with consistent naming?

Should the Bundle Identifier in Info read com.Kaen.M01eskin ?

It doesn't work with Application Loader either:

答: Make sure bundle id is same on your application & iTunes Connect.</p>


问:
Jquery Ajax is neither passing data to PHP nor returning anything on success()
I am trying to pass the jquery variable to PHP with Ajax but the receiving php file is returning error " Undefined index" Code is:

```<code>  <div class="img">
    <a href="ss.php">
       <img id="theme_bg" src="images/themes/theme1.jpg">
    </a></div>

$(document).ready(function($){
    $('.img').on('click','img',function(){
        var imgsrc = $(this).attr('src');
        alert(imgsrc);       //this is returning the img src correctly
$.ajax({
    type: "POST",
    url: 'ss.php',
    dataType: 'json',
    data: {imgpath:imgsrc },
    success: function(response) {
    content.html(response);    // i tried alert here but it shows nothing
    }
});
});});
</code>```

receiving PHP file code is:

```<code> <?php
    $imagepath = $_POST['imgpath'];
    echo $imagepath;
 ?>
</code>```

I tried it with GET also but same error.. I haven't used Ajax before this. I checked other responses here on similar questions but none of them was has anything majorly different from mine code. so dont know what's the error..

updated Screen shots of code both files

updated screen shots of output

答:
Why you wrote ss.php in anchor you dont need that that's why it redirecting ss.php on click and getting error undefined index.

Your html code should be like this:

```<code><form id="myForm" method="post" action="ss.php">
    <div class="img">
        <img id="theme_bg" src="images/themes/theme1.jpg">
        <input name="imgpath" id="imgpath" type="hidden"/>
    </div>
</form>
</code>```

Jquery code:

```<code>$(document).ready(function ($) {
        $('.img').on('click', 'img', function () {
            var imgsrc = $(this).attr('src');
            $("#imgpath").val(imgsrc);       //this is returning the img src correctly
            $("#myForm").submit();
        });
});
</code>```

ss.php

```<code> <?php
   $imagepath = $_POST['imgpath'];
   echo $imagepath;
?>
</code>```

Body:
I am trying to pass the jquery variable to PHP with Ajax but the receiving php file is returning error " Undefined index" Code is:

$(document).ready(function($){
    $('.img').on('click','img',function(){
        var imgsrc = $(this).attr('src');
        alert(imgsrc);       //this is returning the img src correctly
$.ajax({
    type: "POST",
    url: 'ss.php',
    dataType: 'json',
    data: {imgpath:imgsrc },
    success: function(response) {
    content.html(response);    // i tried alert here but it shows nothing
    }
});
});});

receiving PHP file code is:

 <?php
    $imagepath = $_POST['imgpath'];
    echo $imagepath;
 ?>

I tried it with GET also but same error.. I haven't used Ajax before this. I checked other responses here on similar questions but none of them was has anything majorly different from mine code. so dont know what's the error..

updated Screen shots of code both files

updated screen shots of output

Body:
Why you wrote ss.php in anchor you dont need that that's why it redirecting ss.php on click and getting error undefined index.

Your html code should be like this:

<form id="myForm" method="post" action="ss.php">
    <div class="img">
        <img id="theme_bg" src="images/themes/theme1.jpg">
        <input name="imgpath" id="imgpath" type="hidden"/>
    </div>
</form>

Jquery code:

$(document).ready(function ($) {
        $('.img').on('click', 'img', function () {
            var imgsrc = $(this).attr('src');
            $("#imgpath").val(imgsrc);       //this is returning the img src correctly
            $("#myForm").submit();
        });
});

ss.php

 <?php
   $imagepath = $_POST['imgpath'];
   echo $imagepath;
?>


问:
jQuery works 3/4 times the page is loaded
I have a jQuery function that takes a thumbnail tile generated by a plugin and then throw it elsewhere in the DOM. The function works half the time.

The reason I had to do it this way is because the plugin automatically renders half the HTML on page load AND because the CSS solution was terrible. I'd have to overflow containers into one another and it was just terrible hacky.

The plugin is a picture with thumbnails. Each time the thumbnails are clicked the corresponding photo is up in the main picture frame;

Code:

```<code>setTimeout(function(){
  $('ol').append('<li data-toggle="modal" id="thumb" class="yt-thumb" overflow-scroll="false" overflow-scroll="true" data-target="#youtubeModal"><img src="/images/dome-thumb.jpg" /></li> '); // add youtube to thumb slider
  $('ol').appendTo( $('#thumb-area') )
 }, 2000);
</code>```

The reason it is in a setTimout is it seems there is a delay in when the plugin generates the code. Unfortunately the plugin is part of an overall theme and I'm unable to post the code so vague ideas are welcome.

答:
I agree that the MutationObserver is probably the best approach.

Another way to handle it is to have a function that retries the transformation if the DOM isn't ready for you. Something like this:

```<code>function transformThumbnails(iteration) {
  if (iteration === undefined) {
    iteration = 0;
  }
  else if (iteration < 100) { // don’t retry forever
    var isReady = true; // TODO: test if DOM is ready for your transformation
     if (isReady) {
       $('ol').append('<li data-toggle="modal" id="thumb" class="yt-thumb" overflow-scroll="false" overflow-scroll="true" data-target="#youtubeModal"><img src="/images/dome-thumb.jpg" /></li> '); // add youtube to thumb slider
       $('ol').appendTo( $('#thumb-area') )
     }
     else {
       // not ready, so retry
       setTimeout(function(){transformThumbnails(iteration + 1);}, 100);
     }
  }
}
transformThumbnails(); // kick it off
</code>```

Body:
I have a jQuery function that takes a thumbnail tile generated by a plugin and then throw it elsewhere in the DOM. The function works half the time.

The reason I had to do it this way is because the plugin automatically renders half the HTML on page load AND because the CSS solution was terrible. I'd have to overflow containers into one another and it was just terrible hacky.

The plugin is a picture with thumbnails. Each time the thumbnails are clicked the corresponding photo is up in the main picture frame;

Code:

setTimeout(function(){
  $('ol').append('

 '); // add youtube to thumb slider
  $('ol').appendTo( $('#thumb-area') )
 }, 2000);

The reason it is in a setTimout is it seems there is a delay in when the plugin generates the code. Unfortunately the plugin is part of an overall theme and I'm unable to post the code so vague ideas are welcome.

Body:
I agree that the MutationObserver is probably the best approach.

Another way to handle it is to have a function that retries the transformation if the DOM isn't ready for you. Something like this:

function transformThumbnails(iteration) {
  if (iteration === undefined) {
    iteration = 0;
  }
  else if (iteration < 100) { // don’t retry forever
    var isReady = true; // TODO: test if DOM is ready for your transformation
     if (isReady) {
       $('ol').append('<li data-toggle="modal" id="thumb" class="yt-thumb" overflow-scroll="false" overflow-scroll="true" data-target="#youtubeModal"><img src="/images/dome-thumb.jpg" /></li> '); // add youtube to thumb slider
       $('ol').appendTo( $('#thumb-area') )
     }
     else {
       // not ready, so retry
       setTimeout(function(){transformThumbnails(iteration + 1);}, 100);
     }
  }
}
transformThumbnails(); // kick it off


问:
Javascript copy array of properties to another object (one-liner)
This is obviously straight-forward using traditional loops, but I'm curious if anyone can think of a nice, compact way of doing it with destructuring and the spread operator.

For example, let's say I have

```<code>const foo = { a: 1, b: 2, c: 3, d: 4 };
const list = ['a', 'd'];
</code>```

I'd like to create bar = { a: 1, d: 4 }.

You could do something like

```<code>const bar = {};
list.forEach((p) => { bar.p = list.p; });
</code>```

But I'm wondering if anyone has a slick one-liner using ES2015+. For example, you can do const { b, c, ...bar } = foo, but that's if you have the inverse known prior to runtime.

While the solution ideally would support a dynamic list of properties in an array, one with a statically known list is better than nothing. (For example, const bar = ({{ a, d }} = foo)

答:
The best I think you'll be able to do is with Array#reduce:

const foo = { a: 1, b: 2, c: 3, d: 4 };
const list = ['a', 'd'];

const bar = list.reduce((o, k) => (o[k] = foo[k], o), {})

console.log(bar)```

Body:
This is obviously straight-forward using traditional loops, but I'm curious if anyone can think of a nice, compact way of doing it with destructuring and the spread operator.

For example, let's say I have

const foo = { a: 1, b: 2, c: 3, d: 4 };
const list = ['a', 'd'];

I'd like to create bar = { a: 1, d: 4 }.

You could do something like

const bar = {};
list.forEach((p) => { bar.p = list.p; });

But I'm wondering if anyone has a slick one-liner using ES2015+. For example, you can do const { b, c, ...bar } = foo, but that's if you have the inverse known prior to runtime.

While the solution ideally would support a dynamic list of properties in an array, one with a statically known list is better than nothing. (For example, const bar = ({{ a, d }} = foo)


问:
Avoid setTimeout in ajax callback function
Is there any other way to do this that might prevent the setTimeout to be necessary?

```<code>function initialize(){

   $.get('test.xml', function(xml){

      //do some stuff with xml like...
      var icons = xml.documentElement.getElementsByTagName("icon");
        for(var i = 0; i < icons.length; i++) {
           var iconImage = icons[i].getAttribute("image"),
        }

      //do more things to create markers like...
      markers.push(marker);

      //try to add markers to map
      //this will give an error
      addMarkers(markers);

      //setTimeout makes it work
      setTimeout("addMarkers(markers)", 300);

      //is there any way to avoid the timeout?
   });

}
</code>```

答:
It is hard to tell what is wrong, since you aren't providing the error you get or the code that creates the marker. Trying to guess, the most probably thing happening is that the code you run to create the markers and perhaps to initialize the map doesn't  run synchronously, but asynchronously. This will be definitely the case if there are some ajax calls involved and it means that the map/manager system aren't ready by the time the last javascript line is called, but after some period of time and by sure after the function has exited.

In order to avoid the setTimeout, which among others will introduce an unnecessary delay and is very easy to break, should more time is needed in certain conditions, you need to look at the code that creates the markers and see if there is a callback/event defined, which marks the completion of the initialization procedure.

Body:
Is there any other way to do this that might prevent the setTimeout to be necessary?

function initialize(){

   $.get('test.xml', function(xml){

      //do some stuff with xml like...
      var icons = xml.documentElement.getElementsByTagName("icon");
        for(var i = 0; i < icons.length; i++) {
           var iconImage = icons[i].getAttribute("image"),
        }

      //do more things to create markers like...
      markers.push(marker);

      //try to add markers to map
      //this will give an error
      addMarkers(markers);

      //setTimeout makes it work
      setTimeout("addMarkers(markers)", 300);

      //is there any way to avoid the timeout?
   });

}


问:
how to remove whitespaces in HTML source code in Demandware?
I am working on demandware platform. I getting too much spaces in source code(HTML).
I dont have any idea how can i optimize it, please help me.

Thanks in advance

答:
Moku has successfully used the html-minifier package to compress template files to remove white space on sheplers.com. We added it to the gulp process that is based on Site Genesis's build scripts. (circa late 2015) Since we're using gulp we used the gulp wrapper package gulp-htmlmin. The gulp task looks like:

```<code>gulp.task('isml', function() {
    var htmlminOptions = {
    collapseWhitespace: true,
    includeAutoGeneratedTags: false
    };

    paths.isml.forEach(function(p) {
        gulp.src(path.join(rootPath, p), { base: './' })
            .pipe(htmlmin(htmlminOptions))
            .pipe(gulp.dest('./'));
    });
});
</code>```

The package.json paths directive for isml looks like the following. Note that you can add any ISML files that generate excessive whitespace to this list but we found that the majority of the offending whitespace was generated by this one file alone.

```<code>"isml" : [
  "app_storefront_core/cartridge/templates/default/util/modules.isml"
]
</code>```

Body:
Moku has successfully used the html-minifier package to compress template files to remove white space on sheplers.com. We added it to the gulp process that is based on Site Genesis's build scripts. (circa late 2015) Since we're using gulp we used the gulp wrapper package gulp-htmlmin. The gulp task looks like:

gulp.task('isml', function() {
    var htmlminOptions = {
    collapseWhitespace: true,
    includeAutoGeneratedTags: false
    };

    paths.isml.forEach(function(p) {
        gulp.src(path.join(rootPath, p), { base: './' })
            .pipe(htmlmin(htmlminOptions))
            .pipe(gulp.dest('./'));
    });
});

The package.json paths directive for isml looks like the following. Note that you can add any ISML files that generate excessive whitespace to this list but we found that the majority of the offending whitespace was generated by this one file alone.

"isml" : [
  "app_storefront_core/cartridge/templates/default/util/modules.isml"
]


问:
How to set up Browser Caching and Expiry Headers on the Phoenix Framework?
I just run my phoenix app/website through both Google Page Speed Insights and GTMetrix.com

They're both recommending to "Add Expiry Headers" to the Static Assets:

More specifically: to add a "far-future expiration date".

I looked through the Plug Documentation, and it seems to me that it was supposed to be working as is. I tried dabbling with the gzip :true option just for the sake of it.

Apparently ($ curl -vI https://liberty.ai/images/logo-liberty-app@1x.png) the Max-Age is set to four hours (14400/60*60), is there any way to change it?

```<code>< Cache-Control: public, max-age=14400
Cache-Control: public, max-age=14400
< Strict-Transport-Security: max-age=31536000
Strict-Transport-Security: max-age=31536000
< Etag: E640E7
Etag: E640E7
</code>```

答:
Turns out that CloudFlare's Caching options completely override the apps settings.

I was experimenting with those configurations when I made it work just by "switching" the default caching of 4 hours to whatever I wanted.

I'll let this be here in case anyone else faces the same issue...

Body:
I just run my phoenix app/website through both Google Page Speed Insights and GTMetrix.com

They're both recommending to "Add Expiry Headers" to the Static Assets:

More specifically: to add a "far-future expiration date".

I looked through the Plug Documentation, and it seems to me that it was supposed to be working as is. I tried dabbling with the gzip :true option just for the sake of it.

Apparently ($ curl -vI https://liberty.ai/images/logo-liberty-app@1x.png) the Max-Age is set to four hours (14400/60*60), is there any way to change it?

< Cache-Control: public, max-age=14400
Cache-Control: public, max-age=14400
< Strict-Transport-Security: max-age=31536000
Strict-Transport-Security: max-age=31536000
< Etag: E640E7
Etag: E640E7