问:
Is it possible to dynamically check if a string of text is a member inside of a given class in C++?
I am wondering if there is any way to check if a given class contains a given member, except that given member's name is supplied as an std::string. Here is an example of the situation I am in:

```<code>class MyClass {
public:
    int a;
    int b;
    int c;
    void Handle_Class(std::string prop) {
        if (this->prop) { //pseudo code of what I want to accomplish
            //do stuff
        };
    };
} my_class;

int main() {
    my_class.Handle_Class("a");
};
</code>```

I know Handle_Class is not the best name for a function like this, but it is basically supposed to check if the class has a member called prop.
I have no idea how to actually do this though. Essentially I am trying to dynamically check if a class has a given member.
I have a lot of experience in Lua, and you could easily accomplish this in Lua (although Lua is not object oriented, you could accomplish this using tables)

```<code>local my_table = {a = 123; b = 456; c = 789};
local function Handle_Table(prop)
    if my_table[prop] then
        print("property "..prop.." exists inside my_table!");
    end
end
</code>```

I would appreciate any help.
Thanks

答:
There is also a means of doing this at compile-time with templates, you cannot specify a dynamic string at runtime for the check, but consider:

How to detect whether there is a specific member variable in class?

Body:
I am wondering if there is any way to check if a given class contains a given member, except that given member's name is supplied as an std::string. Here is an example of the situation I am in:

class MyClass {
public:
    int a;
    int b;
    int c;
    void Handle_Class(std::string prop) {
        if (this->prop) { //pseudo code of what I want to accomplish
            //do stuff
        };
    };
} my_class;

int main() {
    my_class.Handle_Class("a");
};

I know Handle_Class is not the best name for a function like this, but it is basically supposed to check if the class has a member called prop.
I have no idea how to actually do this though. Essentially I am trying to dynamically check if a class has a given member.
I have a lot of experience in Lua, and you could easily accomplish this in Lua (although Lua is not object oriented, you could accomplish this using tables)

local my_table = {a = 123; b = 456; c = 789};
local function Handle_Table(prop)
    if my_table[prop] then
        print("property "..prop.." exists inside my_table!");
    end
end

I would appreciate any help.
Thanks


来源: stackexchange

问:
E: Unable to locate package libsystemd-dev
i am trying to install open-stack in my machine using dev-stack, but faced this problem :

```<code>E: Unable to locate package libsystemd-dev
+functions-common:apt_get:1                exit_trap
+./stack.sh:exit_trap:521                  local r=100
++./stack.sh:exit_trap:522                  jobs -p
+./stack.sh:exit_trap:522                  jobs=
+./stack.sh:exit_trap:525                  [[ -n '' ]]
+./stack.sh:exit_trap:531                  '[' -f '' ']'
+./stack.sh:exit_trap:536                  kill_spinner
+./stack.sh:kill_spinner:417               '[' '!' -z '' ']'
+./stack.sh:exit_trap:538                  [[ 100 -ne 0 ]]
+./stack.sh:exit_trap:539                  echo 'Error on exit'
Error on exit
+./stack.sh:exit_trap:540                  generate-subunit 1499398887 282 fail
./stack.sh: line 540: generate-subunit: command not found
</code>```

i have tried to install this package but failed:E: can't find libsystemd-dev

but i find this package here here with ubuntu version 16.04
my distribution is  14.04.
does this make difference？

thanks.

答:
The devstack link devstack_latest_docsays that the latest devstack supports Ubuntu 16.04/17.04.

Few packages which are available in 16.04 are not available in 14.04 or the names of the packages are different.

I see "libsystemd-dev" is available in 16.04 and the corresponding package in 14.04 is "libsystemd-daemon-dev"

ContentLicense: CC BY-SA 3.0

Body:
i am trying to install open-stack in my machine using dev-stack, but faced this problem :

E: Unable to locate package libsystemd-dev
+functions-common:apt_get:1                exit_trap
+./stack.sh:exit_trap:521                  local r=100
++./stack.sh:exit_trap:522                  jobs -p
+./stack.sh:exit_trap:522                  jobs=
+./stack.sh:exit_trap:525                  [[ -n '' ]]
+./stack.sh:exit_trap:531                  '[' -f '' ']'
+./stack.sh:exit_trap:536                  kill_spinner
+./stack.sh:kill_spinner:417               '[' '!' -z '' ']'
+./stack.sh:exit_trap:538                  [[ 100 -ne 0 ]]
+./stack.sh:exit_trap:539                  echo 'Error on exit'
Error on exit
+./stack.sh:exit_trap:540                  generate-subunit 1499398887 282 fail
./stack.sh: line 540: generate-subunit: command not found

i have tried to install this package but failed:E: can't find libsystemd-dev

but i find this package here here with ubuntu version 16.04
my distribution is  14.04.
does this make difference？

thanks.


问:
Make Bootstrap columns to take 100% of the row width
I think it is something simple, but as i'm new to bootstrap I don't know how to do it, I searched and didn't find anything about it.

I want the columns to take 100% the width of the row, I marked the row with a red border in the example below.

I know it's the padding of the columns that give this spacing but I have not figured out a way to remove the padding keeping the spacing between the columns and making them fill the row.

JSFiddle

.box {
  height: 100px;
  margin-bottom: 20px;
  border: 1px solid rgba(0,0,0,0.2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row" style="margin-top:40px;margin-bottom:40px;border-right: 1px solid red;border-left: 1px solid red;">
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
     </div>
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
    </div>
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
    </div>
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
    </div>
   </div>
  </div></code>```

答:
Try This
nest row inside row

HTML

```<code><div class="container">
 <div class="row">
  <div class="row">
     <div class="col-*-*">
      <div class="products">
        .......
       </div>
     </div>
  </div>
 </div>
</div>
</code>```

Link For reference

hope this helps..

Body:
I think it is something simple, but as i'm new to bootstrap I don't know how to do it, I searched and didn't find anything about it.

I want the columns to take 100% the width of the row, I marked the row with a red border in the example below.

I know it's the padding of the columns that give this spacing but I have not figured out a way to remove the padding keeping the spacing between the columns and making them fill the row.

JSFiddle

.box {
  height: 100px;
  margin-bottom: 20px;
  border: 1px solid rgba(0,0,0,0.2);
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

Body:
Try This
nest row inside row

HTML

<div class="container">
 <div class="row">
  <div class="row">
     <div class="col-*-*">
      <div class="products">
        .......
       </div>
     </div>
  </div>
 </div>
</div>

Link For reference

hope this helps..


问:
Jquery and twitter bootstrap make active tab doesnt work
In twitter bootstrap js tabs i have to add a class "active" to a li element.

I obtain the hash from the url. I apply the class active to the tab but it doesnt get the focus.

I want to make the second tab active when the url have a certain hash.

Source code:
http://jsfiddle.net/Chumillas/dU458/#example

答:
To make Bootstrap tabs work, there are two things you have to do to make a tab active:

Set the li element to active (class="active")

Set the tab div element to active (class="fade in active")


问:
Yahoo Finance Historical data downloader url is not working
I have used the following url to fetch the historical data from yahoo finance. From last 16th May, 2017 the url is not working.

http://real-chart.finance.yahoo.com/table.csv?s=AAL&a=04&b=01&c=2017&d=04&e=02&f=2017&g=d&ignore=.csv

Seems like they have changed the url and the new url is:

https://query1.finance.yahoo.com/v7/finance/download/AAL?period1=1494873000&period2=1494959400&interval=1d&events=history&crumb=l0aEtuOKocj

In the above changed URL has a session cookie which is crumb. Is there any idea how to get this cookie programmatically(in JAVA)?

答:
I have wrote a lightweight script that pulls together alot of the suggestions in this thread to fix this problem. https://github.com/AndrewRPorter/yahoo-historical

However, there are much better solutions such as, https://github.com/ranaroussi/fix-yahoo-finance

Hope these resources help!


问:
HttpResponseRedirect after login form not redirecting to profile
I'm trying to get a local copy of a Django site working. The production site works just fine on login, but my local instance doesn't redirect to the profile page after completing the login form.

This is the login_page view:

```<code>def login_page(request):
  profile_page = HttpResponseRedirect('profile')
  if request.user.is_authenticated():
    return profile_page
  form = LoginForm(request.POST or None)
  if request.POST and form.is_valid():
    user = form.login(request)

    if user:
      login(request, user)
      return profile_page

  return render(request, 'login.html', {'form': form})
</code>```

This is what the debug output of the server shows:

```<code>Performing system checks...

<function home_page at 0x7f77ad696c08>
System check identified no issues (0 silenced).
July 08, 2017 - 03:21:39
Django version 1.9.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[08/Jul/2017 03:21:49] "GET / HTTP/1.1" 200 3276
[08/Jul/2017 03:21:50] "GET /login HTTP/1.1" 200 2370
[08/Jul/2017 03:21:57] "POST /login HTTP/1.1" 302 0
[08/Jul/2017 03:21:57] "GET /profile HTTP/1.1" 302 0
[08/Jul/2017 03:21:57] "GET /login?next=/profile HTTP/1.1" 200 2370
</code>```

After the above, the browser is left at http://127.0.0.1:8000/login?next=/profile and just displays the standard login page.

Again, identical code is working on the same version of Django in production (though running through gunicorn/nginx instead of django-admin runserver), so it makes me think that there's something in my Django config that I'm missing rather than an actual code problem.

urls.py entries:

```<code>from accounts import urls as account_urls
...
  url(r'^', include(account_urls)),
</code>```

accounts/urls.py:

```<code>from django.conf.urls import url

import accounts.views

urlpatterns = [
  url(r'profile/?$', accounts.views.user_profile_page,
      name='user_profile_page'),
</code>```

Profile view (this never gets triggered AFICT - sticking a breakpoint in there doesn't help):

```<code>@login_required
def user_profile_page(request):
    """Returns user home page, with respective user status of surveys."""

    print "User profile accessed: %s" % request

    // user specific data here

    context = {'some': some, 'data': data,
               'here': here, }
    return render(request, 'accounts/profile.html', context)
</code>```

Also interesting: resolve_url doesn't seem to do the remapping like I would expect:

```<code>(Pdb) resolve_url('/profile')
'/profile'
</code>```

Shouldn't that point to acccounts/profile or 127.0.0.1:8000/profile or something like that?

This is the AUTHENTICATION_BACKEND's 'authenticate' method that is getting executed (not sure how this differs from standard Django). All of the answers here imply that authenticate needs to accept the request argument - can I update this method to append something here?:

```<code>def authenticate(self, username=None, password=None, **kwargs):
    UserModel = get_user_model()
    if username is None:
        username = kwargs.get(UserModel.USERNAME_FIELD)
    try:
      if username is not None:
        username = username.lower()

      user = UserModel._default_manager.get_by_natural_key(username)
      if user.check_password(password):
        return user
    except UserModel.DoesNotExist:
        # Run the default password hasher once to reduce the timing
        # difference between an existing and a non-existing user (#20760).
        UserModel().set_password(password)
</code>```

答:
try this</p>

```<code>from django.shorcuts import redirect
from django.contrib.auth import authenticate
def login_page(request):
  profile_page = HttpResponseRedirect('profile')
  if request.user.is_authenticated():
    return profile_page
  form = LoginForm(request.POST or None)
  if request.POST and form.is_valid():
    user = authenticate(request,username=form.cleaned_data['username'],password=form.cleaned_data['password'])

    if user:
      login(request, user)
      return redirect('profile')
</code>```

Body:
I'm trying to get a local copy of a Django site working. The production site works just fine on login, but my local instance doesn't redirect to the profile page after completing the login form.

This is the login_page view:

def login_page(request):
  profile_page = HttpResponseRedirect('profile')
  if request.user.is_authenticated():
    return profile_page
  form = LoginForm(request.POST or None)
  if request.POST and form.is_valid():
    user = form.login(request)

    if user:
      login(request, user)
      return profile_page

  return render(request, 'login.html', {'form': form})

This is what the debug output of the server shows:

Performing system checks...

<function home_page at 0x7f77ad696c08>
System check identified no issues (0 silenced).
July 08, 2017 - 03:21:39
Django version 1.9.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[08/Jul/2017 03:21:49] "GET / HTTP/1.1" 200 3276
[08/Jul/2017 03:21:50] "GET /login HTTP/1.1" 200 2370
[08/Jul/2017 03:21:57] "POST /login HTTP/1.1" 302 0
[08/Jul/2017 03:21:57] "GET /profile HTTP/1.1" 302 0
[08/Jul/2017 03:21:57] "GET /login?next=/profile HTTP/1.1" 200 2370

After the above, the browser is left at http://127.0.0.1:8000/login?next=/profile and just displays the standard login page.

Again, identical code is working on the same version of Django in production (though running through gunicorn/nginx instead of django-admin runserver), so it makes me think that there's something in my Django config that I'm missing rather than an actual code problem.

urls.py entries:

from accounts import urls as account_urls
...
  url(r'^', include(account_urls)),

accounts/urls.py:

from django.conf.urls import url

import accounts.views

urlpatterns = [
  url(r'profile/?$', accounts.views.user_profile_page,
      name='user_profile_page'),

Profile view (this never gets triggered AFICT - sticking a breakpoint in there doesn't help):

@login_required
def user_profile_page(request):
    """Returns user home page, with respective user status of surveys."""

    print "User profile accessed: %s" % request

    // user specific data here

    context = {'some': some, 'data': data,
               'here': here, }
    return render(request, 'accounts/profile.html', context)

Also interesting: resolve_url doesn't seem to do the remapping like I would expect:

(Pdb) resolve_url('/profile')
'/profile'

Shouldn't that point to acccounts/profile or 127.0.0.1:8000/profile or something like that?

This is the AUTHENTICATION_BACKEND's 'authenticate' method that is getting executed (not sure how this differs from standard Django). All of the answers here imply that authenticate needs to accept the request argument - can I update this method to append something here?:

def authenticate(self, username=None, password=None, **kwargs):
    UserModel = get_user_model()
    if username is None:
        username = kwargs.get(UserModel.USERNAME_FIELD)
    try:
      if username is not None:
        username = username.lower()

      user = UserModel._default_manager.get_by_natural_key(username)
      if user.check_password(password):
        return user
    except UserModel.DoesNotExist:
        # Run the default password hasher once to reduce the timing
        # difference between an existing and a non-existing user (#20760).
        UserModel().set_password(password)

Body:
try this

from django.shorcuts import redirect
from django.contrib.auth import authenticate
def login_page(request):
  profile_page = HttpResponseRedirect('profile')
  if request.user.is_authenticated():
    return profile_page
  form = LoginForm(request.POST or None)
  if request.POST and form.is_valid():
    user = authenticate(request,username=form.cleaned_data['username'],password=form.cleaned_data['password'])

    if user:
      login(request, user)
      return redirect('profile')


问:
How to return the instance name of a class?
I would like the getName() method of SomeClass to return the instance name. In this case "SomeInstance." Is this possible to do, and how?

```<code>class SomeClass {
  getName() {
    return this.constructor.name;
  }
}

var SomeInstance = new SomeClass();

document.write(SomeInstance.getName());
</code>```

Update

This does the trick.

```<code>getName() {
  for (var instance in window){
        if (window[instance] === this){
            return instance;
        }
    }
}
</code>```

答:
If your variable is in the window scope a working JS fiddle here: https://jsfiddle.net/gdxo0sjn/

Note: Embedded snippet wont work due to cross domain security errors on Stackoverflow (Snippets are hosted on another domain).

function getVariableName(instance)
{
  for(obj in window)
   if (window[obj]===instance) return obj;
  return undefined;
}

class SomeClass {
  getName() {
    return this.constructor.name;
  }
}

var SomeInstance = new SomeClass();
console.log(getVariableName(SomeInstance));```

Body:
I would like the getName() method of SomeClass to return the instance name. In this case "SomeInstance." Is this possible to do, and how?

class SomeClass {
  getName() {
    return this.constructor.name;
  }
}

var SomeInstance = new SomeClass();

document.write(SomeInstance.getName());

Update

This does the trick.

getName() {
  for (var instance in window){
        if (window[instance] === this){
            return instance;
        }
    }
}


问:
How to detect proxy requests?
I know it is popular question, and I read all topics about it. I want to put point for me in this question.

Goal: Detect proxy if user use it

Reason: If user use proxy does not show geo adv. I need to know bool result.

Decision:
 1. Use database of proxy IPs (for ex: MaxMind);
 2. Check header Connection: keep-alive because cheap proxy does not use persistent connection. But all modern browsers use it;
 3. Check other popular headers;
 4. Use JS to detect web-proxy by compare browser host and real host.

Questions:
 1. Advise database, I read about MaxMind, but some people wrote it is not effective.
 2. Check Connection-header. Is it okey?
 3. May be I missed something?

PS/ Sorry for my english... I learn it.

答:
Option 1 you suggested is the best option. Proxy detection can be time consuming and complicated.

As you mentioned maxmind and your concern for effectiveness, there are other APIs available like GetIPIntel. It's free and very simple to use. They go beyond simple blacklists and use machine learning and probability theory algorithms to determine a probability value and makes things very accurate.

Option 2 you mentioned doesn't hurt to implement unless you get a lot of false positives. Option 3-4 should not be used alone because it's very easy to get around it. All browser actions can be automated and just because someone is using a proxy, it does not mean they're not using a real browser.

Title: How to detect proxy requests?


问:
TypeError: undefined is not an object - reactjs
I am running some tests on components for a small project, and I keep getting the same error for the one component. When I run the project, everything operates as intended, however when I test I can't get rid of this TypeError: undefined is not an object(this.props.searchResults.map). I am confused by this because, as I said, it runs fine. Is it a problem with the way I'm writing my tests or is there an error in my code? The component is below:

```<code>class Results extends React.Component {
render(){
    const { handleEvent, searchResults } = this.props;
    return(
        <ul className="the-list">
            {this.props.searchResults.map((result, idx) =>
                <ResultItem
                    key={`${result.trackId}-${idx}`}
                    trackName={result.trackName}
                    track={result}
                    handleClick={handleEvent} />
                )};
        </ul>
    );
  }
}
</code>```

答:
I think it could be because you forget the constructor</p>

```<code>class Results extends React.Component {

  constructor(props) {
    super(props);
  }

render(){
    const { handleEvent, searchResults } = this.props;
    return(
        <ul className="the-list">
            {this.props.searchResults.map((result, idx) =>
                <ResultItem
                    key={`${result.trackId}-${idx}`}
                    trackName={result.trackName}
                    track={result}
                    handleClick={handleEvent} />
                )};
        </ul>
    );
  }
}
</code>```

Body:
I am running some tests on components for a small project, and I keep getting the same error for the one component. When I run the project, everything operates as intended, however when I test I can't get rid of this TypeError: undefined is not an object(this.props.searchResults.map). I am confused by this because, as I said, it runs fine. Is it a problem with the way I'm writing my tests or is there an error in my code? The component is below:

class Results extends React.Component {
render(){
    const { handleEvent, searchResults } = this.props;
    return(

            {this.props.searchResults.map((result, idx) =>
                <ResultItem
                    key={`${result.trackId}-${idx}`}
                    trackName={result.trackName}
                    track={result}
                    handleClick={handleEvent} />
                )};

    );
  }
}

Body:
I think it could be because you forget the constructor

class Results extends React.Component {

  constructor(props) {
    super(props);
  }

render(){
    const { handleEvent, searchResults } = this.props;
    return(
        <ul className="the-list">
            {this.props.searchResults.map((result, idx) =>
                <ResultItem
                    key={`${result.trackId}-${idx}`}
                    trackName={result.trackName}
                    track={result}
                    handleClick={handleEvent} />
                )};
        </ul>
    );
  }
}


问:
Android Studio is not generating zip aligned apk
I am using Android Studio 1.2.2

My sdk is well updated and build-tools version installed is 22.0.1

```<code>Build > Generate Signed Apk
</code>```

I only get app-release-unaligned.apk in (app/build/outputs/apk/)

I have already googled and tried:

Copy Pasting "zipalign.exe" from build-tools folder to : (i) sdk/tools/ (ii) sdk/platform-tools/

Adding "zipAlignEnabled true" under buildTypes in build.gradle

Gradle zipAlign task not working?

Please help solve this issue, I want to zipalign using Android Studio.

This is my first app i am trying to publish !!!

答:
You probably are generating it, but the release .apk file is placed in a different directory from the other .apk files.

On my system, for an app called TheApp, .apk files are usually placed in the build/outputs/apk directory:

```<code>TheApp/build/outputs/apk/TheApp-debug.apk
TheApp/build/outputs/apk/TheApp-debug-unaligned.apk
TheApp/build/outputs/apk/TheApp-release-unaligned.apk
</code>```

but the aligned release .apk file is placed directly in the app's root directory :

```<code>TheApp/TheApp-release.apk
</code>```

(This was already answered by @yushulx but I hope this shorter answer is clearer).

Body:
I am using Android Studio 1.2.2

My sdk is well updated and build-tools version installed is 22.0.1

Build > Generate Signed Apk

I only get app-release-unaligned.apk in (app/build/outputs/apk/)

I have already googled and tried:

Copy Pasting "zipalign.exe" from build-tools folder to : (i) sdk/tools/ (ii) sdk/platform-tools/

Adding "zipAlignEnabled true" under buildTypes in build.gradle

Gradle zipAlign task not working?

Please help solve this issue, I want to zipalign using Android Studio.

This is my first app i am trying to publish !!!

Body:
You probably are generating it, but the release .apk file is placed in a different directory from the other .apk files.

On my system, for an app called TheApp, .apk files are usually placed in the build/outputs/apk directory:

TheApp/build/outputs/apk/TheApp-debug.apk
TheApp/build/outputs/apk/TheApp-debug-unaligned.apk
TheApp/build/outputs/apk/TheApp-release-unaligned.apk

but the aligned release .apk file is placed directly in the app's root directory :

TheApp/TheApp-release.apk

(This was already answered by @yushulx but I hope this shorter answer is clearer).


问:
Deleting Rows in Google Sheets that Contain Values from Array or Second Spreadsheet
I am trying to create a script that lets me delete rows in a Google spreadsheet that contain specific text values. I am an extremely novice coder at best and tried modifying several similar scripts I found. The only one I can get to work is the following. However, my list of values will be long, potentially hundreds of terms, and the script I have here will be cumbersome to build out for this many values. I am guessing that having the values in an array or second spreadsheet would be much better. It is also case sensitive. I tried lifting code from other scripts to change to all lowercase but I can't get anything to work.

If you would be so kind as to share your collective knowledge, how can I modify this to achieve my goal?

```<code>    function readRows() {
 var sheet = SpreadsheetApp.getActiveSheet();
 var rows = sheet.getDataRange();
 var numRows = rows.getNumRows();
 var values = rows.getValues();

 var rowsDeleted = 0;
 for (var i = 0; i <= numRows - 1; i++) {

 var row = values[i];

   if (row[1].indexOf("test") > -1) {
 sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
 rowsDeleted++;
 }

 if (row[1].indexOf("TEST") > -1) {
 sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
 rowsDeleted++;
 }

 }
};
</code>```

答:
Try this.  If you delete rows, it's better to start from the bottom otherwise it messes with your indexing. DelA is the array of strings that you want to base your row removals on.  The indexOf function returns something > -1 if it finds the one of the strings.  Once it finds one it stops on that row after deleting it and moves up one.  The row number is i + 1. I did not assume that you had a header row. If you have a header row then adjust your stop condition to i > 0.

```<code>function deleteMyRows()
{
 var delA=['Test','Others'];
 var sht = SpreadsheetApp.getActiveSheet();
 var rng = sht.getDataRange();
 var values = rng.getValues();
 for (var i = values.length-1; i > -1; i--)
 {
   for(var j=0;j<values[i].length;j++)
   {
     for(var k=0;k<delA.length;k++)
     {
       if(values[i][j].indexOf(delA[k])>-1)
       {
         sht.deleteRow(i + 1);
         break;
       }
     }
   }
 }
}
</code>```

So maybe this is what you really need:

```<code> function deleteMyRows()
{
 var delA=['Test','Others'];
 var sht = SpreadsheetApp.getActiveSheet();
 var rng = sht.getDataRange();
 var values = rng.getValues();
 for (var i = values.length-1; i > -1; i--)
 {
   for(var j=0;j<values[i].length;j++)
   {
     for(var k=0;k<delA.length;k++)
     {
       var lcval=String(values[i][j]).toLowerCase();
       var lcdel=String(delA[k]).toLowerCase();
       if(lcval.indexOf(lcdel)>-1)
       {
         sht.deleteRow(i + 1);
         break;
       }
     }
   }
 }
}
</code>```

Body:
I am trying to create a script that lets me delete rows in a Google spreadsheet that contain specific text values. I am an extremely novice coder at best and tried modifying several similar scripts I found. The only one I can get to work is the following. However, my list of values will be long, potentially hundreds of terms, and the script I have here will be cumbersome to build out for this many values. I am guessing that having the values in an array or second spreadsheet would be much better. It is also case sensitive. I tried lifting code from other scripts to change to all lowercase but I can't get anything to work.

If you would be so kind as to share your collective knowledge, how can I modify this to achieve my goal?

    function readRows() {
 var sheet = SpreadsheetApp.getActiveSheet();
 var rows = sheet.getDataRange();
 var numRows = rows.getNumRows();
 var values = rows.getValues();

 var rowsDeleted = 0;
 for (var i = 0; i <= numRows - 1; i++) {

 var row = values[i];

   if (row[1].indexOf("test") > -1) {
 sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
 rowsDeleted++;
 }

 if (row[1].indexOf("TEST") > -1) {
 sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
 rowsDeleted++;
 }

 }
};

Body:
Try this.  If you delete rows, it's better to start from the bottom otherwise it messes with your indexing. DelA is the array of strings that you want to base your row removals on.  The indexOf function returns something > -1 if it finds the one of the strings.  Once it finds one it stops on that row after deleting it and moves up one.  The row number is i + 1. I did not assume that you had a header row. If you have a header row then adjust your stop condition to i > 0.

function deleteMyRows()
{
 var delA=['Test','Others'];
 var sht = SpreadsheetApp.getActiveSheet();
 var rng = sht.getDataRange();
 var values = rng.getValues();
 for (var i = values.length-1; i > -1; i--)
 {
   for(var j=0;j<values[i].length;j++)
   {
     for(var k=0;k<delA.length;k++)
     {
       if(values[i][j].indexOf(delA[k])>-1)
       {
         sht.deleteRow(i + 1);
         break;
       }
     }
   }
 }
}

So maybe this is what you really need:

 function deleteMyRows()
{
 var delA=['Test','Others'];
 var sht = SpreadsheetApp.getActiveSheet();
 var rng = sht.getDataRange();
 var values = rng.getValues();
 for (var i = values.length-1; i > -1; i--)
 {
   for(var j=0;j<values[i].length;j++)
   {
     for(var k=0;k<delA.length;k++)
     {
       var lcval=String(values[i][j]).toLowerCase();
       var lcdel=String(delA[k]).toLowerCase();
       if(lcval.indexOf(lcdel)>-1)
       {
         sht.deleteRow(i + 1);
         break;
       }
     }
   }
 }
}


问:
Image Fit and Positioning Compatibility Across Browsers
I have created an html/javascript/css page which displays photos in a "carousel", where the user can click the left and right arrows to change the photo.  The carousel itself, the parent/container, is 500px tall and 100% of its parent div wide.  The image inside of it should be at max 100% wide and at max 100% tall.  In other words, it will fit itself into the imgCarousel, regardless of aspect ratio.

This works in most browsers.  I have confirmed that it works in IE, Edge, Chrome, and Firefox.  However, it does not work in Safari.  I don't personally have access to a Mac, but I know it does not work in Safari because others have viewed the page before me.  It also does not work in some android mobile browsers (though it does work with Android Chrome).

It appears that in these browsers where it does not work, the top is not actually set to 50%, but that the transform is still working properly.  This is based on visual inspection.  In addition, it appears that the image is not being sized properly.  It is extending to the full width, and the height is extending beyond 100%;

Unfortunately, I cannot test with developer tools on any of these browsers, since I don't have access to a Mac, and I can't seem to find developer tools for mobile browsers that can be used in the same capacity.

I can link to the page in question if it is not a breach of protocol here.

I have done some research to see if there are any compatability issues/fixes, but I have not been successful in this research.  If anyone knows of any way I can include a compatibility fix, please let me know.

Thank you.

```<code>.imgCarousel {
    display: flex;
    justify-content: space-between;

    vertical-align: middle;

    height: 500px;
    background-color: black;
    text-align: center;
    margin: auto;
}

.imgCarousel img {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);

    max-height: 100%;
    max-width: 100%;
    object-fit: contain;

    cursor: pointer;

}
</code>```

答:
Try adding this list, including the opera prefix:</p>

```<code>    transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -o-transform: translateY(-50%);
</code>```

Body:
I have created an html/javascript/css page which displays photos in a "carousel", where the user can click the left and right arrows to change the photo.  The carousel itself, the parent/container, is 500px tall and 100% of its parent div wide.  The image inside of it should be at max 100% wide and at max 100% tall.  In other words, it will fit itself into the imgCarousel, regardless of aspect ratio.

This works in most browsers.  I have confirmed that it works in IE, Edge, Chrome, and Firefox.  However, it does not work in Safari.  I don't personally have access to a Mac, but I know it does not work in Safari because others have viewed the page before me.  It also does not work in some android mobile browsers (though it does work with Android Chrome).

It appears that in these browsers where it does not work, the top is not actually set to 50%, but that the transform is still working properly.  This is based on visual inspection.  In addition, it appears that the image is not being sized properly.  It is extending to the full width, and the height is extending beyond 100%;

Unfortunately, I cannot test with developer tools on any of these browsers, since I don't have access to a Mac, and I can't seem to find developer tools for mobile browsers that can be used in the same capacity.

I can link to the page in question if it is not a breach of protocol here.

I have done some research to see if there are any compatability issues/fixes, but I have not been successful in this research.  If anyone knows of any way I can include a compatibility fix, please let me know.

Thank you.

.imgCarousel {
    display: flex;
    justify-content: space-between;

    vertical-align: middle;

    height: 500px;
    background-color: black;
    text-align: center;
    margin: auto;
}

.imgCarousel img {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);

    max-height: 100%;
    max-width: 100%;
    object-fit: contain;

    cursor: pointer;

}

Body:
Try adding this list, including the opera prefix:

    transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -o-transform: translateY(-50%);


问:
find image src that :contains?
Morning all,

I have a list of images like so:

```<code><ul id="preload" style="display:none;">
<li><img src="afx4000z-navy-icon-1_thumb.jpg"/></li>
<li><img src="afx4000z-green-icon-1_thumb.jpg"/></li>
</ul>
</code>```

Using jQuery how find all image src's within ul#preload that contain a specific string eg."green"

something like...

```<code>var new_src = jQuery('#preload img').attr('src')*** that contains green ***;
</code>```

答:
You need to use the *= selector:

```<code>jQuery('#preload img[src*="green"]')
</code>```

If you want it to be case insensitive, it will be a bit more difficult:

```<code>var keyword = "green";
$("#preload img").filter(function(keyword) {
    return $(this).attr("src").toLowerCase().indexOf(keyword.toLowerCase()) != -1;
});
</code>```

ContentLicense: CC BY-SA 2.5

Title: find image src that :contains?

Body:
Morning all,

I have a list of images like so:

Using jQuery how find all image src's within ul#preload that contain a specific string eg."green"

something like...

var new_src = jQuery('#preload img').attr('src')*** that contains green ***;

Body:
You need to use the *= selector:

jQuery('#preload img[src*="green"]')

If you want it to be case insensitive, it will be a bit more difficult:

var keyword = "green";
$("#preload img").filter(function(keyword) {
    return $(this).attr("src").toLowerCase().indexOf(keyword.toLowerCase()) != -1;
});


问:
Redirect to homepage if route doesnt exist in Laravel 5
```<code>/** Redirect 404's to home
*****************************************/
App::missing(function($exception)
{
    // return Response::view('errors.missing', array(), 404);
    return Redirect::to('/');
});
</code>```

I have this code in my routes.php file.  I am wondering how to redirect back to the home page if there is a 404 error. Is this possible?

答:
I just want to add a suggestion for cleaning it up a bit more.  I'd like to credit the accepted answer for getting me started.  In my opinion however since every action in this function will return something, the switch and else statement create a bit of bloat.  So to clean it up just a tad, I'd do the following.</p>

```<code>public function render($request, Exception $e)
{
    if ($this->isHttpException($e))
    {
        if ($e->getStatusCode() == 404)
           return redirect()->guest('home');

        if ($e->getStatusCode() == 500)
           return redirect()->guest('home');
    }

    return parent::render($request, $e);
}
</code>```

Body:
/** Redirect 404's to home
*****************************************/
App::missing(function($exception)
{
    // return Response::view('errors.missing', array(), 404);
    return Redirect::to('/');
});

I have this code in my routes.php file.  I am wondering how to redirect back to the home page if there is a 404 error. Is this possible?

Body:
I just want to add a suggestion for cleaning it up a bit more.  I'd like to credit the accepted answer for getting me started.  In my opinion however since every action in this function will return something, the switch and else statement create a bit of bloat.  So to clean it up just a tad, I'd do the following.

public function render($request, Exception $e)
{
    if ($this->isHttpException($e))
    {
        if ($e->getStatusCode() == 404)
           return redirect()->guest('home');

        if ($e->getStatusCode() == 500)
           return redirect()->guest('home');
    }

    return parent::render($request, $e);
}

ContentLicense: CC BY-SA 4.0


问:
getting context in AsyncTask
I am trying to get the context in my AsyncTask of the class called Opciones(this class is the only one that call that task) but I don't know how to do it, I saw some code like this:

```<code>      protected void onPostExecute(Long result) {

    Toast.makeText(Opciones.this,"Subiendo la foto. ¡Tras ser moderada empezara a ser votada!: ", Toast.LENGTH_LONG).show();
}
</code>```

But it doesn't work for me it says: "No enclosing instance of the type Opciones in scope"

答:
Holding a weak reference to the host Activity will prevent memory leaks.</p>

```<code>static class MyTask extends AsyncTask<Void, Void, Void> {
    // Weak references will still allow the Activity to be garbage-collected
    private final WeakReference<Activity> weakActivity;

    MyTask(Activity myActivity) {
      this.weakActivity = new WeakReference<>(myActivity);
    }

    @Override
    public Void doInBackground(Void... params) {
      // do async stuff here
    }

    @Override
    public void onPostExecute(Void result) {
      // Re-acquire a strong reference to the activity, and verify
      // that it still exists and is active.
      Activity activity = weakActivity.get();
      if (activity == null
          || activity.isFinishing()
          || activity.isDestroyed()) {
        // activity is no longer valid, don't do anything!
        return;
      }

      // The activity is still valid, do main-thread stuff here
    }
  }
</code>```

Title: getting context in AsyncTask

Body:
I am trying to get the context in my AsyncTask of the class called Opciones(this class is the only one that call that task) but I don't know how to do it, I saw some code like this:

      protected void onPostExecute(Long result) {

    Toast.makeText(Opciones.this,"Subiendo la foto. ¡Tras ser moderada empezara a ser votada!: ", Toast.LENGTH_LONG).show();
}

But it doesn't work for me it says: "No enclosing instance of the type Opciones in scope"

Body:
Holding a weak reference to the host Activity will prevent memory leaks.

static class MyTask extends AsyncTask<Void, Void, Void> {
    // Weak references will still allow the Activity to be garbage-collected
    private final WeakReference<Activity> weakActivity;

    MyTask(Activity myActivity) {
      this.weakActivity = new WeakReference<>(myActivity);
    }

    @Override
    public Void doInBackground(Void... params) {
      // do async stuff here
    }

    @Override
    public void onPostExecute(Void result) {
      // Re-acquire a strong reference to the activity, and verify
      // that it still exists and is active.
      Activity activity = weakActivity.get();
      if (activity == null
          || activity.isFinishing()
          || activity.isDestroyed()) {
        // activity is no longer valid, don't do anything!
        return;
      }

      // The activity is still valid, do main-thread stuff here
    }
  }


问:
How to get version any app in phone
I want to check any app version in phone ( android studio )
and if the last version equal the version install in users phones app
How to get any app version installed on the phone by Android Studio?</p>

答:
Get all install app info:

```<code> List<PackageInfo> packList = getPackageManager().getInstalledPackages(0);
            for (int i=0; i < packList.size(); i++)
            {
                PackageInfo packInfo = packList.get(i);
                if (  (packInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)
                {
                    String appName = packInfo.applicationInfo.loadLabel(getPackageManager()).toString();
                    ;
                    Log.e("App " + Integer.toString(i), appName +"  ver: "+packInfo.versionCode);
                }
            }
</code>```

More info:Info

Title: How to get version any app in phone

Body:
Get all install app info:

 List<PackageInfo> packList = getPackageManager().getInstalledPackages(0);
            for (int i=0; i < packList.size(); i++)
            {
                PackageInfo packInfo = packList.get(i);
                if (  (packInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)
                {
                    String appName = packInfo.applicationInfo.loadLabel(getPackageManager()).toString();
                    ;
                    Log.e("App " + Integer.toString(i), appName +"  ver: "+packInfo.versionCode);
                }
            }

More info:Info


答:
You need to iterate all application installed the app, then get each of the package name to get the package info.. in packageInfo have infomation about those app

```<code>final PackageManager packageManager = getPackageManager();
List<ApplicationInfo> installedApplications = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);

List<String> vers = new ArrayList<>();

for (ApplicationInfo appInfo : installedApplications)
{
    PackageInfo packageInfo = getPackageManager().getPackageInfo(appInfo.packageName, 0);
    vers.add(packageInfo.versionName);
}

Log.i(TAG,vers.toString());
</code>```

Title: How to get version any app in phone

Body:
I want to check any app version in phone ( android studio )
and if the last version equal the version install in users phones app
How to get any app version installed on the phone by Android Studio?

Body:
You need to iterate all application installed the app, then get each of the package name to get the package info.. in packageInfo have infomation about those app

final PackageManager packageManager = getPackageManager();
List<ApplicationInfo> installedApplications = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);

List<String> vers = new ArrayList<>();

for (ApplicationInfo appInfo : installedApplications)
{
    PackageInfo packageInfo = getPackageManager().getPackageInfo(appInfo.packageName, 0);
    vers.add(packageInfo.versionName);
}

Log.i(TAG,vers.toString());


问:
multiple form actions in html page?
i currently worked with is code...i must insert data into a table in oracle databse 10g and the table name is REGISTER ..so i made register.html page like this and put the jsp file according to it and created validation page too ...wer do i add validation page in????

<marquee>
WELCOME FOR REGISTRATION
</marquee>

<form action="./register.jsp">

First Name:
<input type="text" name="fname" placeholder="Enter first Name" value="">

Last Name:
<input type="text" name="lname" placeholder="Enter Last Name" value="">

Contact:
<input type="text" name="contact" placeholder="Enter contact" value="">

Address:
<input type="text" name="address" placeholder="Enter address" value="">

Gender:
<input type="radio" name="gender" value="Male" checked="checked">Male
<input type="radio" name="gender" value="female">Female

Type Of User	<select name="user" >
<option value="technician">TECHNICIAN</option>
<option value="supervisor">SUPERVISOR</option>
<option value="client">CLIENT</option>
</select>

State:	 <select name="state">
<option value="Default">Select a State</option>
<optgroup label="INDIA">
<option value="karnataka">karnataka</option>
<option value="Telangana">Telangana</option>
<option value="Uttar Pradesh">Uttar Pradesh</option>
</optgroup>
</select>

City:	 <select name="city">
<option value="Default">Select a City</option>
<optgroup label="Andhra Pradesh">
<option value="Kakinada">Kakinada</option>
<option value="Vishakhapatnam">Vizag</option>
<option value="Vijaywada">Vijaywada</option>
</optgroup>
<optgroup label="Uttar Pradesh">
<option value="Mathura">Mathura</option>
<option value="Varanasi">Varanasi</option>
<option value="Lucknow">Lucknow</option>
</optgroup>
</select>

EmailID:
<input type="text" name="emailid" placeholder="Enter Email Here">

Password:
<input type="password" name="password" placeholder="Enter Password Here">

Confirm Password:
<input type="password" name="password1" placeholder="Enter password here">

Date Of Birth
<input type="date" name="dob" placeholder="Enter date" value="">

captcha

Enter captcha 	<input type="text" name="code">

<input type="submit" value="Register">
<input type="reset" value="Refresh">

</form>

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

<p>and the jsp file goes like</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><%@ page import="java.sql.*" session="true"%>
<%!
Connection con;
PreparedStatement ps;
String a,b,c,d,e,f,g,h,i,j,k;
int l,m;
%>

<%
a=request.getParameter("fname");
b=request.getParameter("lname");
c=request.getParameter("address");
d=request.getParameter("gender");
e=request.getParameter("user");
f=request.getParameter("state");
g=request.getParameter("city");
h=request.getParameter("emailid");
i=request.getParameter("password");
j=request.getParameter("password1");
k=request.getParameter("code");
l=Integer.parseInt(request.getParameter("contact"));
m=Integer.parseInt(request.getParameter("dob"));
session.setAttribute("aa",a);
session.setAttribute("bb",b);
session.setAttribute("cc",c);
session.setAttribute("dd",d);
session.setAttribute("ee",e);
session.setAttribute("ff",f);
session.setAttribute("gg",g);
session.setAttribute("hh",h);
session.setAttribute("ii",i);
session.setAttribute("jj",k);
session.setAttribute("ll",l);
session.setAttribute("mm",m);

try
{
 Class.forName("oracle.jdbc.driver.OracleDriver");
 con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","root");

    ps=con.prepareStatement("insert into register values(?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1,h);
ps.setString(2,a);
ps.setString(3,b);
ps.setString(4,l);
ps.setString(5,c);
ps.setString(6,d);
ps.setString(7,f);
ps.setString(8,g);
ps.setString(9,i);
ps.setString(10,m);
ps.setString(11,e);
ps.execute();
}
catch(Exception e)
{
}
%></code>```

答: You can use JQuery for validation. It validates the information on the client side, so you need not redirect to the next page unless the entered information is valid.</p>

Title: multiple form actions in html page?

Body:
i currently worked with is code...i must insert data into a table in oracle databse 10g and the table name is REGISTER ..so i made register.html page like this and put the jsp file according to it and created validation page too ...wer do i add validation page in????

<marquee>
WELCOME FOR REGISTRATION
</marquee>

<form action="./register.jsp">

First Name:
<input type="text" name="fname" placeholder="Enter first Name" value="">

Last Name:
<input type="text" name="lname" placeholder="Enter Last Name" value="">

Contact:
<input type="text" name="contact" placeholder="Enter contact" value="">

Address:
<input type="text" name="address" placeholder="Enter address" value="">

Gender:
<input type="radio" name="gender" value="Male" checked="checked">Male
<input type="radio" name="gender" value="female">Female

Type Of User	<select name="user" >
<option value="technician">TECHNICIAN</option>
<option value="supervisor">SUPERVISOR</option>
<option value="client">CLIENT</option>
</select>

State:	 <select name="state">
<option value="Default">Select a State</option>
<optgroup label="INDIA">
<option value="karnataka">karnataka</option>
<option value="Telangana">Telangana</option>
<option value="Uttar Pradesh">Uttar Pradesh</option>
</optgroup>
</select>

City:	 <select name="city">
<option value="Default">Select a City</option>
<optgroup label="Andhra Pradesh">
<option value="Kakinada">Kakinada</option>
<option value="Vishakhapatnam">Vizag</option>
<option value="Vijaywada">Vijaywada</option>
</optgroup>
<optgroup label="Uttar Pradesh">
<option value="Mathura">Mathura</option>
<option value="Varanasi">Varanasi</option>
<option value="Lucknow">Lucknow</option>
</optgroup>
</select>

EmailID:
<input type="text" name="emailid" placeholder="Enter Email Here">

Password:
<input type="password" name="password" placeholder="Enter Password Here">

Confirm Password:
<input type="password" name="password1" placeholder="Enter password here">

Date Of Birth
<input type="date" name="dob" placeholder="Enter date" value="">

captcha

Enter captcha 	<input type="text" name="code">

<input type="submit" value="Register">
<input type="reset" value="Refresh">

</form>

and the jsp file goes like

<%@ page import="java.sql.*" session="true"%>
<%!
Connection con;
PreparedStatement ps;
String a,b,c,d,e,f,g,h,i,j,k;
int l,m;
%>

<%
a=request.getParameter("fname");
b=request.getParameter("lname");
c=request.getParameter("address");
d=request.getParameter("gender");
e=request.getParameter("user");
f=request.getParameter("state");
g=request.getParameter("city");
h=request.getParameter("emailid");
i=request.getParameter("password");
j=request.getParameter("password1");
k=request.getParameter("code");
l=Integer.parseInt(request.getParameter("contact"));
m=Integer.parseInt(request.getParameter("dob"));
session.setAttribute("aa",a);
session.setAttribute("bb",b);
session.setAttribute("cc",c);
session.setAttribute("dd",d);
session.setAttribute("ee",e);
session.setAttribute("ff",f);
session.setAttribute("gg",g);
session.setAttribute("hh",h);
session.setAttribute("ii",i);
session.setAttribute("jj",k);
session.setAttribute("ll",l);
session.setAttribute("mm",m);

try
{
 Class.forName("oracle.jdbc.driver.OracleDriver");
 con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","root");

    ps=con.prepareStatement("insert into register values(?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1,h);
ps.setString(2,a);
ps.setString(3,b);
ps.setString(4,l);
ps.setString(5,c);
ps.setString(6,d);
ps.setString(7,f);
ps.setString(8,g);
ps.setString(9,i);
ps.setString(10,m);
ps.setString(11,e);
ps.execute();
}
catch(Exception e)
{
}
%>


问:
onKeyPress event in Firefox and IE8
I have the following Javascript code. Here I am using onKeyPress="someFunction( )" in the body tag to get the keyCode of the key that is pressed.

The code is working fine in IE8 but this is not working in Firefox.

Please give some solution to this.

```<code><html>
<head>
<title>onKeyPress( ) event not working in firefox..</title>
<script>
function printDiv()
{
  var divToPrint=document.getElementById('prnt');
  newWin=window.open(''+self.location,'PrintWin','left=50,top=20,width=590,height=840,toolbar=1,resizable=1,scrollbars=yes');
  newWin.document.write(divToPrint.outerHTML);
  newWin.print();
  //newWin.close();
}
</script>

<script>
function keypress()
{
  alert(event.keyCode);
  var key=event.keyCode;
  if(key==112 || key==80)
 printDiv();
  else if(key==101 || key==69)
    window.location="http://google.com";
  else if(key==114 || key==82)
    window.reset();
}
</script>
</head>
<body bgcolor="lightblue" onkeypress="keypress()">
</code>```

Here is the total code which is working fine in IE8 and not working in Firefox.

```<code><!DOCTYPE html>
<html>
    <head>
    <title>Please help me out</title>
    <script type="text/javascript">
    function printDiv()
    {
      var divToPrint=document.getElementById('prnt');
      newWin=window.open(''+self.location,'PrintWin','left=50,top=20,width=590,height=840,toolbar=1,resizable=1,scrollbars=yes');
      newWin.document.write(divToPrint.outerHTML);
      newWin.print();
    }
    </script>

    <script type="text/javascript">
    function keypress(val)
    {
      //-----------------------------------------------------
      //alert('nnnn');
      //alert(window.event ? event.keyCode : val.which);
      //if(val.which != 0 && val.charCode != 0)
      // alert('Firefox'+String.fromCharCode(val.which));
      //else
      // alert('IE');
      //-------------------------------------------------------
      var key=event.keyCode;
      if(key==112 || key==80 || val=="print")
        printDiv();
      else if(key==101 || key==69 || val=="exit")
        window.location="http://google.co.in";
      else if(key==114 || key==82 || val=="refresh")
        document.forms[0].reset();
      else
        event.returnValue=true;
    }
    </script>
</head>
<body bgcolor="lightblue" topmargin="0" leftmargin="0"marginwidth="0px" marginheight="0px" onkeypress="keypress(null)">
<table align="left" border="1" cellpadding="5" cellspacing="0" style="width: 100%;height:100%">
<tbody>
<tr><td width="20%" valign="top">ccccccccccc</td>
    <td width="80%" align="center">
        <table style="width: 100%" border="0" valign="top">
        <tr align="right">
        <td valign="top">
        <button value="refresh" accesskey="R" onclick="keypress(this.value)">
            <b><u>R</u></b>efresh
        </button>
        <button value="print" accesskey="P" onclick="keypress(this.value)">
              <b><u>P</u></b>rint
        </button>
        <button value="exit" accesskey="E" onclick="keypress(this.value)">
               <b><u>E</u></b>xit
        </button>
        </td></tr>
        </table>
        <h3>Press the letters P->Print , E->Exit etc....</h3>
        <h1>Just a test for keypress event</h1>
        <form action="http://google.co.in" method="Post">
            <div id="prnt">
                zzzzzzzzzzzzzzz
            </div>
        </form>
    </td>
</tr>
</tbody>
</table></body></html>
</code>```

答:
When problems like this show up, I start to use any kind of a JavaScript framework. Those frameworks are build to avoid problems with different browsers.

To catch all different keypress() apis, like the link from Emmett shows, can be very difficult.

Example:

In HTML head:

```<code><script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</code>```

In the JS tag:

```<code>$(document).keydown(function(event) {
 alert('You pressed '+event.keyCode);
 event.preventDefault();
});
</code>```

Title: onKeyPress event in Firefox and IE8

Body:
I have the following Javascript code. Here I am using onKeyPress="someFunction( )" in the body tag to get the keyCode of the key that is pressed.

The code is working fine in IE8 but this is not working in Firefox.

Please give some solution to this.

<title>onKeyPress( ) event not working in firefox..</title>

Here is the total code which is working fine in IE8 and not working in Firefox.

<!DOCTYPE html>

    <title>Please help me out</title>

ccccccccccc

        <button value="refresh" accesskey="R" onclick="keypress(this.value)">
            Refresh
        </button>
        <button value="print" accesskey="P" onclick="keypress(this.value)">
              Print
        </button>
        <button value="exit" accesskey="E" onclick="keypress(this.value)">
               Exit
        </button>

Press the letters P->Print , E->Exit etc....

Just a test for keypress event

        <form action="http://google.co.in" method="Post">

                zzzzzzzzzzzzzzz

        </form>

Body:
When problems like this show up, I start to use any kind of a JavaScript framework. Those frameworks are build to avoid problems with different browsers.

To catch all different keypress() apis, like the link from Emmett shows, can be very difficult.

Example:

In HTML head:

<script src="http://code.jquery.com/jquery-1.4.4.js"></script>

In the JS tag:

$(document).keydown(function(event) {
 alert('You pressed '+event.keyCode);
 event.preventDefault();
});


问:
Show Discord bot as online
I'm working on a custom Discord bot using their api. Sending HTTP requests work but the bot doesn't actually show itself as online. </p>

<p>Other bots such as Dynobot are able to show themselves as online, am I missing something or is it just a case of how many requests are sent? </p>

答:
Wait, are you working directly with the API, as in sending HTTP requests?

If so...there really is no need to do this. Instead, use a library to code your Discord bot. Here is a list of official libraries for the Discord API. Personally I recommend Discord.js, although I have heard that Discord.py and Discord.NET are also good.

If you want to keep using the API directly, which I do not recommend at all, I believe you can call /api/login. Have you tried that yet?

I hope this helped! :)

Title: Show Discord bot as online

Body:
I'm working on a custom Discord bot using their api. Sending HTTP requests work but the bot doesn't actually show itself as online.

Other bots such as Dynobot are able to show themselves as online, am I missing something or is it just a case of how many requests are sent?


问:
Make Bootstrap columns to take 100% of the row width
I think it is something simple, but as i'm new to bootstrap I don't know how to do it, I searched and didn't find anything about it.

I want the columns to take 100% the width of the row, I marked the row with a red border in the example below.

I know it's the padding of the columns that give this spacing but I have not figured out a way to remove the padding keeping the spacing between the columns and making them fill the row.

JSFiddle

.box {
  height: 100px;
  margin-bottom: 20px;
  border: 1px solid rgba(0,0,0,0.2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row" style="margin-top:40px;margin-bottom:40px;border-right: 1px solid red;border-left: 1px solid red;">
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
     </div>
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
    </div>
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
    </div>
    <div class="col-xl-3 col-md-4 col-sm-6">
      <div class="box"></div>
    </div>
   </div>
  </div></code>```

答: you should use 100% of all div width if problem solved well and good otherwise you can use left and right margins in (-) minus.

Body:
I think it is something simple, but as i'm new to bootstrap I don't know how to do it, I searched and didn't find anything about it.

I want the columns to take 100% the width of the row, I marked the row with a red border in the example below.

I know it's the padding of the columns that give this spacing but I have not figured out a way to remove the padding keeping the spacing between the columns and making them fill the row.

JSFiddle

.box {
  height: 100px;
  margin-bottom: 20px;
  border: 1px solid rgba(0,0,0,0.2);
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>


问:
Transaction replication not replicating one column value
One column of type varbinary(200) is not getting replicated to destination table from source table. I have tried updating the column value in main table again but still it is not getting replicated to destination table. Am not seeing any error in replication job and tried running snapshot too. But still no luck. What could be wrong?? Using SQL server 2012.

Replication script for this table: exec sp_addarticle @publication = N'CWT1200UAT', @article = N'usr_mast', @source_owner = N'dbo', @source_object = N'usr_mast', @type = N'logbased', @description = N'', @creation_script = N'', @pre_creation_cmd = N'drop', @schema_option = 0x000000000803509F, @identityrangemanagementoption = N'none', @destination_table = N'usr_mast', @destination_owner = N'dbo', @status = 24, @vertical_partition = N'false', @ins_cmd = N'CALL [sp_MSins_dbousr_mast]', @del_cmd = N'CALL [sp_MSdel_dbousr_mast]', @upd_cmd = N'SCALL [sp_MSupd_dbousr_mast]'

答:
The issue got resolved after performing following actions:
1. Remove the table which has the issue from replication.
2. Run the snapshot replication and wait for completion.
3. Add back the table into replication.
4. Run the snapshot replication and wait for completion.</p>


问:
Obj / Array element notation
I don’t know what it is called or I would look it up, but when acsessing an object or arrays element in jQuery what is the differance between Obj.element and Obj[”element”]?</p>

答:
```<code>Obj.element and Obj[”element”]
</code>```

Both these will access the same key element inside object Obj. Value against key name "element" will be returned.

Title: Obj / Array element notation

Body:
Obj.element and Obj[”element”]

Both these will access the same key element inside object Obj. Value against key name "element" will be returned.


问:
why isn't my if statement working?
I need user input to save to a database and then display on an app.
If the user's input is left blank, I need to display an error message.

I'm running into trouble with the error messages displaying at all.
When user input is blank, a blank post is saved to the db and then displayed with no content rather than displaying the error message.

I am using Python, Jinja2, Flask, HTML

Thanks!!

```<code>    if request.method == 'POST':

        blog_title = str(request.form['title'])
        blog_body = str(request.form['body'])

        title_error = ''
        body_error = ''

        if len(blog_title) == 0:
            title_error = 'Please give your blog a title'
            return title_error

        if len(blog_body) == 0:
            body_error = "Please give your blog some content"
            return body_error
        else:
            new_blog = Blog(blog_title, blog_body)
            db.session.add(new_blog)
            db.session.commit()

            blog_id = new_blog.id

            return redirect(url_for('blogs', id=blog_id))

    else:
        return render_template('/newpost_form.html')
</code>```

答:
you are reasinging the values of the variables, do the following:</p>

```<code>if request.method == 'POST':

    blog_title = str(request.form['title'])
    blog_body = str(request.form['body'])

    if len(blog_title) == 0:
        return 'Please give your blog a title'
    elif len(blog_body) == 0:
        return "Please give your blog some content"
    else:
        new_blog = Blog(blog_title, blog_body)
        db.session.add(new_blog)
        db.session.commit()

        blog_id = new_blog.id

        return redirect(url_for('blogs', id=blog_id))

else:
    return render_template('/newpost_form.html')
</code>```

Title: why isn't my if statement working?

Body:
I need user input to save to a database and then display on an app.
If the user's input is left blank, I need to display an error message.

I'm running into trouble with the error messages displaying at all.
When user input is blank, a blank post is saved to the db and then displayed with no content rather than displaying the error message.

I am using Python, Jinja2, Flask, HTML

Thanks!!

    if request.method == 'POST':

        blog_title = str(request.form['title'])
        blog_body = str(request.form['body'])

        title_error = ''
        body_error = ''

        if len(blog_title) == 0:
            title_error = 'Please give your blog a title'
            return title_error

        if len(blog_body) == 0:
            body_error = "Please give your blog some content"
            return body_error
        else:
            new_blog = Blog(blog_title, blog_body)
            db.session.add(new_blog)
            db.session.commit()

            blog_id = new_blog.id

            return redirect(url_for('blogs', id=blog_id))

    else:
        return render_template('/newpost_form.html')

Body:
you are reasinging the values of the variables, do the following:

if request.method == 'POST':

    blog_title = str(request.form['title'])
    blog_body = str(request.form['body'])

    if len(blog_title) == 0:
        return 'Please give your blog a title'
    elif len(blog_body) == 0:
        return "Please give your blog some content"
    else:
        new_blog = Blog(blog_title, blog_body)
        db.session.add(new_blog)
        db.session.commit()

        blog_id = new_blog.id

        return redirect(url_for('blogs', id=blog_id))

else:
    return render_template('/newpost_form.html')


问:
how can i make the View do NOT expand over its sibling View
I have a layout similiar to this:

```<code><RelativeLayout ...>
     <EditText android:id="@+id/editbox"
            android:layout_width="wrap_content" .../>
     <Button android:layout_right="@id/editbox"
            android:layout_width="wrap_content"
            android:text="Button" />
 </RelativeLayout>
</code>```

The button is at the right of the edit text. And the edit text is 'wrap_content'. When i type texts into the edit view, the view's width increase and will expand to my button. I want the two views (button and edit text) have their own area. How to configure this?

答:
Hi Keyin Lynx: Use minWidth and maxWidth attribute,For Instance:

android:minWidth="10dip", android:maxWidth="60dip", attributes.

Body:
I have a layout similiar to this:

<RelativeLayout ...>
     <EditText android:id="@+id/editbox"
            android:layout_width="wrap_content" .../>
     <Button android:layout_right="@id/editbox"
            android:layout_width="wrap_content"
            android:text="Button" />
 </RelativeLayout>

The button is at the right of the edit text. And the edit text is 'wrap_content'. When i type texts into the edit view, the view's width increase and will expand to my button. I want the two views (button and edit text) have their own area. How to configure this?


问:
Android alpha testing "Item not found"
I have published my app for alpha testing, but not able to download it from play store.

I have opened the url "https://play.google.com/apps/testing/com.*" and accepted to be a tester and now it shows me "you are a tester". But when I click on the link "download it from the Play Store", it shows me "Item not found" in my test device play store and "requested URL was not found" in desktop browser.

App is in published state for more than 48 hours.

App is published in all countries.

google groups for testers are added, I can see the group in manage testers tab. Tester account is added to the group ( triple checked it)

test device has only one tester account.

I can access the in-app purchases, which means the app is published properly. Google doesn't support draft mode anymore.

I went through some similar posts in stackoverflow, but there is no definite answer. Looks like for some people it resolved automatically and some people are not lucky enough.

答:
This can be due to a silly mistake where you aren't signed in with the appropriate Google Play account in your device's Google Play Store.

Sign in with the testing gmail account into Google Play and then click on the test-link

For more detail check Item not found

Title: Android alpha testing "Item not found"


问:
Performance decline after switching the MySql table engine from innoDB to NDB
I'm building a website based on WordPress 4.8. The default table engine is innoDB after going through the installation steps, and everything works fine. While my DBA asked me to change the table engine to NDB, for easy data replication. While after the change, the home pages loads very slowly. After some debugging, I found there are queries take over 10 seconds.

Although I will definitely add some caching mechanism when releasing the website, but I'd like to firstly figure out if there is something we can fix from the DB side, before I adding the cache or optimizing the query. As the query time is 0.4 seconds with innoDB, and my DBA told me NDB should have better performance.

Following is one query that takes 14 seconds for your references, please advice if you have any idea. Thanks!

```<code>SELECT SQL_CALC_FOUND_ROWS team_football_1001_posts.ID
FROM team_football_1001_posts
LEFT JOIN team_football_1001_postmeta
ON ( team_football_1001_posts.ID = team_football_1001_postmeta.post_id )
LEFT JOIN team_football_1001_postmeta AS mt1
ON ( team_football_1001_posts.ID = mt1.post_id )
LEFT JOIN team_football_1001_postmeta AS mt2
ON ( team_football_1001_posts.ID = mt2.post_id )
LEFT JOIN team_football_1001_postmeta AS mt3
ON (team_football_1001_posts.ID = mt3.post_id
AND mt3.meta_key = '_team_winner_id' )
WHERE 1=1
AND ( team_football_1001_postmeta.meta_key = '_date_start'
AND ( ( ( mt1.meta_key = '_date_start'
AND mt1.meta_value > '2017-07-07 06:48:49' )
OR ( ( mt2.meta_key = '_date_start'
AND mt2.meta_value < '2017-07-07 06:48:49' )
AND mt3.post_id IS NULL ) ) ) )
AND team_football_1001_posts.post_type = 'matches'
AND ((team_football_1001_posts.post_status = 'publish'))
GROUP BY team_football_1001_posts.ID
ORDER BY team_football_1001_postmeta.meta_value DESC
LIMIT 0, 3
</code>```

Attached the tables schemas for reference:

```<code>CREATE TABLE `team_football_1001_posts` (
  `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `post_author` bigint(20) unsigned NOT NULL DEFAULT '0',
  `post_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_date_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_content` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_title` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_excerpt` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'publish',
  `comment_status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'open',
  `ping_status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'open',
  `post_password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `post_name` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `to_ping` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `pinged` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_modified` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_modified_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_content_filtered` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_parent` bigint(20) unsigned NOT NULL DEFAULT '0',
  `guid` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `menu_order` int(11) NOT NULL DEFAULT '0',
  `post_type` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'post',
  `post_mime_type` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `comment_count` bigint(20) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ID`),
  KEY `post_name` (`post_name`(191)),
  KEY `type_status_date` (`post_type`,`post_status`,`post_date`,`ID`),
  KEY `post_parent` (`post_parent`),
  KEY `post_author` (`post_author`)
) ENGINE=InnoDB AUTO_INCREMENT=2200 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `team_football_1001_postmeta` (
  `meta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `post_id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `meta_key` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `meta_value` longtext COLLATE utf8mb4_unicode_ci,
  PRIMARY KEY (`meta_id`),
  KEY `post_id` (`post_id`),
  KEY `meta_key` (`meta_key`(191))
) ENGINE=InnoDB AUTO_INCREMENT=22648 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
</code>```

答:
Sorry to give you bad news after you undoubtedly invested a significant amount of time and capital in moving to NDB, but I would not have recommended using NDB. I would recommend to stay with InnoDB, at least for these tables. This query is never going to take advantage of NDB's strengths.

NDB is not a magical "everything goes fast now" technology. Like every other type of optimization, it improves certain queries—at the expense of other queries.

When I worked as a MySQL consultant, it was pretty common to see companies who tried to port their existing application to NDB after being promised that it would have better performance. But you need to design your application, database, and queries specifically to take advantage of NDB's storage architecture from the beginning. Porting any old application to NDB is pretty likely to result in worse performance.

I don't think your DBA understood (or else didn't make you understand) how distributed storage works in NDB, and how that affects database design and query design.

Your first table has an auto-increment primary key on ID, and your second table has its own auto-increment primary key meta_id. NDB spreads data around on its multiple storage nodes based on the modulus of each tables primary key. Since the primary key of your two tables is largely out of sync, every one of your queries has to search for data on all of your storage nodes.

If your primary key for team_football_1001_postmeta used the post_id as the left-most column, NDB would naturally store related data together on the same storage node. Then the joins you show would always search only one storage node for a given post ID.

But actually that won't help, because you're querying for many post ID's. So you're bound to search all the storage nodes anyway.

You're also using SQL_CALC_FOUND_ROWS which often causes a big penalty for performance. But I think the use of NDB with your many-way joins is probably a much worse problem.

Body:
I'm building a website based on WordPress 4.8. The default table engine is innoDB after going through the installation steps, and everything works fine. While my DBA asked me to change the table engine to NDB, for easy data replication. While after the change, the home pages loads very slowly. After some debugging, I found there are queries take over 10 seconds.

Although I will definitely add some caching mechanism when releasing the website, but I'd like to firstly figure out if there is something we can fix from the DB side, before I adding the cache or optimizing the query. As the query time is 0.4 seconds with innoDB, and my DBA told me NDB should have better performance.

Following is one query that takes 14 seconds for your references, please advice if you have any idea. Thanks!

SELECT SQL_CALC_FOUND_ROWS team_football_1001_posts.ID
FROM team_football_1001_posts
LEFT JOIN team_football_1001_postmeta
ON ( team_football_1001_posts.ID = team_football_1001_postmeta.post_id )
LEFT JOIN team_football_1001_postmeta AS mt1
ON ( team_football_1001_posts.ID = mt1.post_id )
LEFT JOIN team_football_1001_postmeta AS mt2
ON ( team_football_1001_posts.ID = mt2.post_id )
LEFT JOIN team_football_1001_postmeta AS mt3
ON (team_football_1001_posts.ID = mt3.post_id
AND mt3.meta_key = '_team_winner_id' )
WHERE 1=1
AND ( team_football_1001_postmeta.meta_key = '_date_start'
AND ( ( ( mt1.meta_key = '_date_start'
AND mt1.meta_value > '2017-07-07 06:48:49' )
OR ( ( mt2.meta_key = '_date_start'
AND mt2.meta_value < '2017-07-07 06:48:49' )
AND mt3.post_id IS NULL ) ) ) )
AND team_football_1001_posts.post_type = 'matches'
AND ((team_football_1001_posts.post_status = 'publish'))
GROUP BY team_football_1001_posts.ID
ORDER BY team_football_1001_postmeta.meta_value DESC
LIMIT 0, 3

Attached the tables schemas for reference:

CREATE TABLE `team_football_1001_posts` (
  `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `post_author` bigint(20) unsigned NOT NULL DEFAULT '0',
  `post_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_date_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_content` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_title` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_excerpt` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'publish',
  `comment_status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'open',
  `ping_status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'open',
  `post_password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `post_name` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `to_ping` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `pinged` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_modified` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_modified_gmt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `post_content_filtered` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
  `post_parent` bigint(20) unsigned NOT NULL DEFAULT '0',
  `guid` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `menu_order` int(11) NOT NULL DEFAULT '0',
  `post_type` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'post',
  `post_mime_type` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `comment_count` bigint(20) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ID`),
  KEY `post_name` (`post_name`(191)),
  KEY `type_status_date` (`post_type`,`post_status`,`post_date`,`ID`),
  KEY `post_parent` (`post_parent`),
  KEY `post_author` (`post_author`)
) ENGINE=InnoDB AUTO_INCREMENT=2200 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `team_football_1001_postmeta` (
  `meta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `post_id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `meta_key` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `meta_value` longtext COLLATE utf8mb4_unicode_ci,
  PRIMARY KEY (`meta_id`),
  KEY `post_id` (`post_id`),
  KEY `meta_key` (`meta_key`(191))
) ENGINE=InnoDB AUTO_INCREMENT=22648 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


问:
Exchange Strings with Numbers in R
I was just wondering if R has a way to convert a vector of strings into numbers which I define. For example, say we have a vector as follows:

```<code>vector <- c("ABC", "DEF", "GHI", "ABC", "GHI", "ABC")
</code>```

What I would like to do is rather than having the elements ABC, DEF, and GHI in the vector I would instead like to 'exchange' them with a user-defined number, such that rather than having ABC in the vector I have 1, instead of DEF I have 2, and instead of GHI I have 3, so the vector now becomes

```<code>vector <- c(1, 2, 3, 1, 3, 1)
</code>```

I know that there are functions which do something similar to this, but they don't quite do what I want. For instance, the function as.numeric(as.factor()) will convert a vector filled with string elements into numbers, which is what I want, but unfortunately it does not allow me to actually define what string value becomes what number, which would be a major problem when the dataset I'm using changes since the numbers would represent different strings.

Another alternative method is using the chartr(old = "ABC", new = "123", x) function (where x is your dataset) which is also good, but again the major problem behind it is the fact that the number of "old" characters must match the number of "new" characters but also the fact that every instance of a letter will be changed with a number, such that if we replace ABC with 123 then every time B occurs it will always be replaced with 2 which is not what I want.

Does R have a function which will allow me to swap strings in a vector with user-defined numbers?

EDIT: In particular (for anyone that wishes to do this in the future), I used the following function: levels(vector)[levels(vector)=="ABC"] <- "1" This allows you to swap individual string factor levels with a numerical value and vice versa

答:
1) subscripting This uses no packages.  Omit unname if you want the output to have the original character strings as names.

```<code>map <- c(ABC = 1, DEF = 2, GHI = 3)
unname(map[vector])
## [1] 1 2 3 1 3 1
</code>```

2) strapply

```<code>library(gsubfn)
strapply(vector, ".*", list(ABC = 1, DEF = 2, GHI = 3), simplify = TRUE)
## [1] 1 2 3 1 3 1
</code>```

3) factor  This does not involve any packages.

```<code>as.numeric(format(factor(vector, levels = c("ABC", "DEF", "GHI"), labels = 1:3)))
## [1] 1 2 3 1 3 1
</code>```

or if the numbers are always 1, 2, ... then it can be simplified to:

```<code>as.numeric(factor(vector, levels = c("ABC", "DEF", "GHI")))
## [1] 1 2 3 1 3 1
</code>```

If you leave out levels= then it will assign the alphabetically first to 1, etc. so if that assignment is OK then it further simplifies to:

```<code>as.numeric(factor(vector))
## [1] 1 2 3 1 3 1
</code>```

4) match This also uses no packages.

```<code>c(1, 2, 3)[match(vector, c("ABC", "DEF", "GHI"))]
## [1] 1 2 3 1 3 1
</code>```

If the numbers are always 1, 2, ... then it can be simplified to just:

```<code>match(vector, c("ABC", "DEF", "GHI"))
## [1] 1 2 3 1 3 1
</code>```

5) data.frame This one works with data frames. The first two lines create the data frames, the nxxt line does the lookups and the last line ensures that m is in the same order as DF.  The last line could be omitted if the order does not matter.  This uses no packages.

```<code>mapDF <- data.frame(let = c("ABC", "DEF", "GHI"), num = 1:3)
DF <- data.frame(let = vector, order = seq_along(vector))

m <- merge(DF, mapDF, all.x = TRUE, all.y = FALSE)
m[ order(m$order), ]
</code>```

There are several popular data frame oriented packages that could be used here in place of the last two lines above.  The order column is not used in these solutions and could be omitted from DF for the following.

```<code>library(dplyr)
DF %>% left_join(mapDF)

library(data.table)
data.table(mapDF)[DF, on = "let"]

library(sqldf)
sqldf("select * from DF left join mapDF using (let)")
</code>```

Title: Exchange Strings with Numbers in R

Body:
I was just wondering if R has a way to convert a vector of strings into numbers which I define. For example, say we have a vector as follows:

vector <- c("ABC", "DEF", "GHI", "ABC", "GHI", "ABC")

What I would like to do is rather than having the elements ABC, DEF, and GHI in the vector I would instead like to 'exchange' them with a user-defined number, such that rather than having ABC in the vector I have 1, instead of DEF I have 2, and instead of GHI I have 3, so the vector now becomes

vector <- c(1, 2, 3, 1, 3, 1)

I know that there are functions which do something similar to this, but they don't quite do what I want. For instance, the function as.numeric(as.factor()) will convert a vector filled with string elements into numbers, which is what I want, but unfortunately it does not allow me to actually define what string value becomes what number, which would be a major problem when the dataset I'm using changes since the numbers would represent different strings.

Another alternative method is using the chartr(old = "ABC", new = "123", x) function (where x is your dataset) which is also good, but again the major problem behind it is the fact that the number of "old" characters must match the number of "new" characters but also the fact that every instance of a letter will be changed with a number, such that if we replace ABC with 123 then every time B occurs it will always be replaced with 2 which is not what I want.

Does R have a function which will allow me to swap strings in a vector with user-defined numbers?

EDIT: In particular (for anyone that wishes to do this in the future), I used the following function: levels(vector)[levels(vector)=="ABC"] <- "1" This allows you to swap individual string factor levels with a numerical value and vice versa

Body:
1) subscripting This uses no packages.  Omit unname if you want the output to have the original character strings as names.

map <- c(ABC = 1, DEF = 2, GHI = 3)
unname(map[vector])
## [1] 1 2 3 1 3 1

2) strapply

library(gsubfn)
strapply(vector, ".*", list(ABC = 1, DEF = 2, GHI = 3), simplify = TRUE)
## [1] 1 2 3 1 3 1

3) factor  This does not involve any packages.

as.numeric(format(factor(vector, levels = c("ABC", "DEF", "GHI"), labels = 1:3)))
## [1] 1 2 3 1 3 1

or if the numbers are always 1, 2, ... then it can be simplified to:

as.numeric(factor(vector, levels = c("ABC", "DEF", "GHI")))
## [1] 1 2 3 1 3 1

If you leave out levels= then it will assign the alphabetically first to 1, etc. so if that assignment is OK then it further simplifies to:

as.numeric(factor(vector))
## [1] 1 2 3 1 3 1

4) match This also uses no packages.

c(1, 2, 3)[match(vector, c("ABC", "DEF", "GHI"))]
## [1] 1 2 3 1 3 1

If the numbers are always 1, 2, ... then it can be simplified to just:

match(vector, c("ABC", "DEF", "GHI"))
## [1] 1 2 3 1 3 1

5) data.frame This one works with data frames. The first two lines create the data frames, the nxxt line does the lookups and the last line ensures that m is in the same order as DF.  The last line could be omitted if the order does not matter.  This uses no packages.

mapDF <- data.frame(let = c("ABC", "DEF", "GHI"), num = 1:3)
DF <- data.frame(let = vector, order = seq_along(vector))

m <- merge(DF, mapDF, all.x = TRUE, all.y = FALSE)
m[ order(m$order), ]

There are several popular data frame oriented packages that could be used here in place of the last two lines above.  The order column is not used in these solutions and could be omitted from DF for the following.

library(dplyr)
DF %>% left_join(mapDF)

library(data.table)
data.table(mapDF)[DF, on = "let"]

library(sqldf)
sqldf("select * from DF left join mapDF using (let)")


问:
Problems with Weather API from APIXU
I am just starting to learn API requests and I am trying to display current weather in Toronto using APIXU api calls (here is the documentation: https://www.apixu.com/doc/current.aspx) and I am not sure what I am doing wrong.

Here is html:

```<code><div class="weather">
  <h3>Toronto Weather Forecast</h3>
  <ul style="margin: 0">
  </ul>
</div>
</code>```

Here is js:

```<code>        // Weather API
    function loadData() {
        var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=XXXXXXXXXXXXXXXXX&q=Toronto";
    $.getJSON(weatherAPIXU, function(data) {
        var list = $(".place ul");
        forecast = data.current;
        list.append('<li>Temp: ' + forecast.temp_c + '°C</li>');
    }).error(function(e) {
        $(".place").append('<p style="text-align: center;">Sorry!</p><p style="text-align: center;">Could Not Be Loaded</p>');
    });
};

$('.place').submit(loadData);
</code>```

Once I know how to implement it via JSON, I want to bind it with knockout.js as well

So, if you can give me recommendations on that as well, it would be greatly appreciated.

答:
I looked closer into it and I have found that I didn't load my API at all. So, here is a working solutions for those who might have similar problems. </p>

```<code>$(document).ready(function loadData() {
    var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=XXXXXXXXXXXX&q=Toronto";
    $.getJSON(weatherAPIXU, function(data) {
        var forecast = data.current.temp_c;
        var weather = $(".weather");
        weather.append(forecast + '° C');
    }).error(function(e) {
        $(".weather").append('Sorry! Not Loaded');
    });
    $('.weather').submit(loadData);
});
</code>```

Title: Problems with Weather API from APIXU

Body:
I am just starting to learn API requests and I am trying to display current weather in Toronto using APIXU api calls (here is the documentation: https://www.apixu.com/doc/current.aspx) and I am not sure what I am doing wrong.

Here is html:

Toronto Weather Forecast

Here is js:

        // Weather API
    function loadData() {
        var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=XXXXXXXXXXXXXXXXX&q=Toronto";
    $.getJSON(weatherAPIXU, function(data) {
        var list = $(".place ul");
        forecast = data.current;
        list.append('
Temp: ' + forecast.temp_c + '°C
');
    }).error(function(e) {
        $(".place").append('
Sorry!

Could Not Be Loaded
');
    });
};

$('.place').submit(loadData);

Once I know how to implement it via JSON, I want to bind it with knockout.js as well

So, if you can give me recommendations on that as well, it would be greatly appreciated.

Body:
I looked closer into it and I have found that I didn't load my API at all. So, here is a working solutions for those who might have similar problems.

$(document).ready(function loadData() {
    var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=XXXXXXXXXXXX&q=Toronto";
    $.getJSON(weatherAPIXU, function(data) {
        var forecast = data.current.temp_c;
        var weather = $(".weather");
        weather.append(forecast + '° C');
    }).error(function(e) {
        $(".weather").append('Sorry! Not Loaded');
    });
    $('.weather').submit(loadData);
});


问:
GPIO pins no errors but not getting the expected result?
Sorry I am a beginner to both Raspberry Pi and python. I am write a simple python program to use the pulse width modulator, Here is the code.

```<code>import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(12,GPIO.OUT)
pwm=GPIO.PWM(12,50)
pwm.start(0)
while True:
        for i in range(50):
                pwm.ChangeDutyCycle(i)
                time.sleep(0.05)
        for i in range(50,0,-1):
                pwm.ChangeDutyCycle(i)
                time.sleep(0.05)
</code>```

I connected the led between 12 and ground with the suitable resistor. But when I execute, I don't get any error but it wont work.

答:
I got the problem. I need to use the proper numbering. The reason for having two types of numbering is,

The GPIO.BOARD option specifies that you are referring to the pins by the number of the pin the the plug - i.e the numbers printed on the board (e.g. P1).

The GPIO.BCM option means that you are referring to the pins by the "Broadcom SOC channel" number.

I hope this helps anyone.

Body:
Sorry I am a beginner to both Raspberry Pi and python. I am write a simple python program to use the pulse width modulator, Here is the code.

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(12,GPIO.OUT)
pwm=GPIO.PWM(12,50)
pwm.start(0)
while True:
        for i in range(50):
                pwm.ChangeDutyCycle(i)
                time.sleep(0.05)
        for i in range(50,0,-1):
                pwm.ChangeDutyCycle(i)
                time.sleep(0.05)

I connected the led between 12 and ground with the suitable resistor. But when I execute, I don't get any error but it wont work.


问:
onClick event - Run a javascript AFTER previous one has finished in the same onClick event
Code looks like this (My PHP server generates this line replacing the %% variables):

```<code><button type="submit" id="buttons" name="add_to_inv" onclick="ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y');ShowFieldTotal('inv_items','iprice','sub-total',2);">+</button>;
</code>```

I want THIS

```<code>ShowFieldTotal('inv_items','iprice','sub-total',2);
</code>```

to run ONLY when the elements of the first script have been added on my webpage. Basically, it adds an item line in a table and, what I actually want it to do that I can't do, calculate the total of each items once their lines have been added to the table from the first script:

```<code>ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y')
</code>```

答: You can make another function which calls the two functions one after another and bind that function to the onclick event.</p>

Body:
Code looks like this (My PHP server generates this line replacing the %% variables):

<button type="submit" id="buttons" name="add_to_inv" onclick="ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y');ShowFieldTotal('inv_items','iprice','sub-total',2);">+</button>;

I want THIS

ShowFieldTotal('inv_items','iprice','sub-total',2);

to run ONLY when the elements of the first script have been added on my webpage. Basically, it adds an item line in a table and, what I actually want it to do that I can't do, calculate the total of each items once their lines have been added to the table from the first script:

ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y')


问:
Singleton instance declared as static variable of GetInstance method, is it thread-safe?
I've seen implementations of Singleton patterns where instance variable was declared as static variable in GetInstance method. Like this:

```<code>SomeBaseClass &SomeClass::GetInstance()
{
   static SomeClass instance;
   return instance;
}
</code>```

I see following positive sides of this approach:

The code is simpler, because it's compiler who responsible for creating this object only when GetInstance called for the first time.

The code is safer, because there is no other way to get reference to instance, but with GetInstance method and there is no other way to change instance, but inside GetInstance method.

What are the negative sides of this approach (except that this is not very OOP-ish) ? Is this thread-safe?

答:
In C++11 it is thread safe:

§6.7 [stmt.dcl] p4 If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.

In C++03:

Under g++ it is thread safe.

But this is because g++ explicitly adds code to guarantee it.

One problem is that if you have two singletons and they try and use each other during construction and destruction.

Read this:
Finding C++ static initialization order problems

A variation on this problem is if the singleton is accessed from the destructor of a global variable. In this situation the singleton has definitely been destroyed, but the get method will still return a reference to the destroyed object.

There are ways around this but they are messy and not worth doing. Just don't access a singleton from the destructor of a global variable.

A Safer definition but ugly:

I am sure you can add some appropriate macros to tidy this up

```<code>SomeBaseClass &SomeClass::GetInstance()
{
#ifdef _WIN32
Start Critical Section Here
#elif  defined(__GNUC__) && (__GNUC__ > 3)
// You are OK
#else
#error Add Critical Section for your platform
#endif

    static SomeClass instance;

#ifdef _WIN32
END Critical Section Here
#endif

    return instance;
}
</code>```

OwnerDisplayName: Dmitriy Matveev

Body:
I've seen implementations of Singleton patterns where instance variable was declared as static variable in GetInstance method. Like this:

SomeBaseClass &SomeClass::GetInstance()
{
   static SomeClass instance;
   return instance;
}

I see following positive sides of this approach:

The code is simpler, because it's compiler who responsible for creating this object only when GetInstance called for the first time.

The code is safer, because there is no other way to get reference to instance, but with GetInstance method and there is no other way to change instance, but inside GetInstance method.

What are the negative sides of this approach (except that this is not very OOP-ish) ? Is this thread-safe?

Body:
In C++11 it is thread safe:

§6.7 [stmt.dcl] p4 If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.

In C++03:

Under g++ it is thread safe.

But this is because g++ explicitly adds code to guarantee it.

One problem is that if you have two singletons and they try and use each other during construction and destruction.

Read this:
Finding C++ static initialization order problems

A variation on this problem is if the singleton is accessed from the destructor of a global variable. In this situation the singleton has definitely been destroyed, but the get method will still return a reference to the destroyed object.

There are ways around this but they are messy and not worth doing. Just don't access a singleton from the destructor of a global variable.

A Safer definition but ugly:

I am sure you can add some appropriate macros to tidy this up

SomeBaseClass &SomeClass::GetInstance()
{
#ifdef _WIN32
Start Critical Section Here
#elif  defined(__GNUC__) && (__GNUC__ > 3)
// You are OK
#else
#error Add Critical Section for your platform
#endif

    static SomeClass instance;

#ifdef _WIN32
END Critical Section Here
#endif

    return instance;
}

OwnerDisplayName: Martin York

LastEditorDisplayName: Martin York


问:
Create MS Excel Sheet
How can I create an MS Excel sheet and download it from a Moonlight/Silverlight app? Regards Lennie

Basically I want to run a report in the Siverlight client and allow the user to download the MS Excel report.

答: use npoi  to generate the excel in server temporarily , until it is downloaded by the user , then delete it .</p>

Title: Create MS Excel Sheet