问:
Django search in multiple field with multiple value
I have a model which stores login logout time and date for users

```<code>class LoginLogout(models.Model):
    username = models.CharField(max_length=30, unique=True)
    date = models.DateField(auto_now_add=True)
    login_time = models.TimeField()
    logout_time = models.TimeField(null=True, blank=True)
</code>```

Now I need to search in this model by the field date and username. I have a form which takes date_from, date_to and username as input. Any field can be blank. If username is blank all results will be returned. Now what will be the queryset for achieving the desired queryset.

答:
you have to use many if else...

i just give you the query

```<code># Case 1: All res:
res = LoginLogout.objects.all()
# Case 2: date_to is blank:
res = LoginLogout.objects.filter(login_time__gt = date_from)
# Case 3: date_from is blank
res = LoginLogout.Objects.filter(logout_time__lt = date_to)
# Case 4: all value
res = LoginLogout.Objects.filter( Q(username= username) & Q(login_...) & Q(logout_...)
# Or:
res = LoginLogout.Objects.filter(username= username, login_time__gt = ...)
</code>```

Body:
I have a model which stores login logout time and date for users

class LoginLogout(models.Model):
    username = models.CharField(max_length=30, unique=True)
    date = models.DateField(auto_now_add=True)
    login_time = models.TimeField()
    logout_time = models.TimeField(null=True, blank=True)

Now I need to search in this model by the field date and username. I have a form which takes date_from, date_to and username as input. Any field can be blank. If username is blank all results will be returned. Now what will be the queryset for achieving the desired queryset.

Body:
you have to use many if else...

i just give you the query

# Case 1: All res:
res = LoginLogout.objects.all()
# Case 2: date_to is blank:
res = LoginLogout.objects.filter(login_time__gt = date_from)
# Case 3: date_from is blank
res = LoginLogout.Objects.filter(logout_time__lt = date_to)
# Case 4: all value
res = LoginLogout.Objects.filter( Q(username= username) & Q(login_...) & Q(logout_...)
# Or:
res = LoginLogout.Objects.filter(username= username, login_time__gt = ...)


来源: stackexchange

问:
stripping of white spaces from a string
I have the following string

```<code>argsStr = "server ('m1.labs.terada')ta.com') username ('user5') password('user)5') dbname ('default')";
</code>```

I want to extract the argument name i.e "server" "username" "password".

I am using the following regex to do that

```<code>boost::regex re1("\\(\'[!-~]+\'\\)");
boost::sregex_token_iterator x(argsStr.begin(), argsStr.end(), re1, -1),x1;   boost::sregex_token_iterator y;
std::copy(x, x1, std::back_inserter(v2));
</code>```

v2 is string vector, where I am extracting the tokens. However, The tokens I am getting are

```<code>"server "    INSTEAD of "server
" username "  INSTEAD of "username".
</code>```

How shall I remove these white spaces?

答:
You can remove white spaces from a string using this:</p>

```<code>#include <boost/algorithm/string/erase.hpp>

str.erase(remove_if(str.begin(), str.end(), ::isspace),str.end());
</code>```

ContentLicense: CC BY-SA 3.0

Title: stripping of white spaces from a string

Body:
I have the following string

argsStr = "server ('m1.labs.terada')ta.com') username ('user5') password('user)5') dbname ('default')";

I want to extract the argument name i.e "server" "username" "password".

I am using the following regex to do that

boost::regex re1("\\(\'[!-~]+\'\\)");
boost::sregex_token_iterator x(argsStr.begin(), argsStr.end(), re1, -1),x1;   boost::sregex_token_iterator y;
std::copy(x, x1, std::back_inserter(v2));

v2 is string vector, where I am extracting the tokens. However, The tokens I am getting are

"server "    INSTEAD of "server
" username "  INSTEAD of "username".

How shall I remove these white spaces?

Body:
You can remove white spaces from a string using this:

#include <boost/algorithm/string/erase.hpp>

str.erase(remove_if(str.begin(), str.end(), ::isspace),str.end());


问:
How to create a date range with php?
I tried to make time with PHP. start date of 2017-01-29 to 2017-12-29. But that happened I could not print in February because the month maximum of only 28 days. How to order printed anyway but with the February date up to 28.

my script:

```<code>date_default_timezone_set('UTC');

// Start date
$date = '2017-01-29';
// End date
$end_date = '2017-12-29';

while (strtotime($date) <= strtotime($end_date)) {
    echo "$date\n";
    echo "<br>";
    $date = date ("Y-m-d", strtotime("+1 month", strtotime($date)));
}
</code>```

Output:

答:
Use the DateTime class to find the last day of next month:

```<code>date_default_timezone_set('UTC');

// Start date
$date = '2017-01-29';
// End date
$end_date = '2017-12-29';

while (strtotime($date) <= strtotime($end_date)) {
            echo "$date\n";
            echo "<br>";
            $d = new DateTime( $date );
            $d->modify( 'last day of next month' );
            $date = $d->format( 'Y-m-d' );
}
</code>```

Now this may not be fully what you're interested in since you might want to try different start dates and have it not go to the end of the next month or you might want it to use 2/28 for the February date, but then go back to the 29th for each successive month. But this should get you closer to the logic you are needing. I think using DateTime will be part of your answer.

ContentLicense: CC BY-SA 4.0

Title: How to create a date range with php?

Body:
I tried to make time with PHP. start date of 2017-01-29 to 2017-12-29. But that happened I could not print in February because the month maximum of only 28 days. How to order printed anyway but with the February date up to 28.

my script:

date_default_timezone_set('UTC');

// Start date
$date = '2017-01-29';
// End date
$end_date = '2017-12-29';

while (strtotime($date) <= strtotime($end_date)) {
    echo "$date\n";
    echo "
";
    $date = date ("Y-m-d", strtotime("+1 month", strtotime($date)));
}

Output:

Body:
Use the DateTime class to find the last day of next month:

date_default_timezone_set('UTC');

// Start date
$date = '2017-01-29';
// End date
$end_date = '2017-12-29';

while (strtotime($date) <= strtotime($end_date)) {
            echo "$date\n";
            echo "<br>";
            $d = new DateTime( $date );
            $d->modify( 'last day of next month' );
            $date = $d->format( 'Y-m-d' );
}

Now this may not be fully what you're interested in since you might want to try different start dates and have it not go to the end of the next month or you might want it to use 2/28 for the February date, but then go back to the 29th for each successive month. But this should get you closer to the logic you are needing. I think using DateTime will be part of your answer.


问:
datatables.min.js how to sort records
I am using datatables.min.js to display my listing in wordpress. I want to display records such that latest entries should be display first (ORDER BY ID DESC). My query is correct but for some reasons it is not displaying as per my query order by clause (ORDER BY id DESC). It is displaying the oldest records first. Anybody can help how to fix this issue ?</p>

答:
Try this code

```<code>$(document).ready(function() {
    $('#example').DataTable( {
        "order": [[ 0, "desc" ]]
    } );
} );
</code>```

Default ordering (sorting) https://datatables.net/examples/basic_init/table_sorting.html

Title: datatables.min.js how to sort records

Body:
Try this code

$(document).ready(function() {
    $('#example').DataTable( {
        "order": [[ 0, "desc" ]]
    } );
} );

Default ordering (sorting) https://datatables.net/examples/basic_init/table_sorting.html


问:
getter always returns 0
I'm new to java coding, so sorry for the beginner question. I'm pretty sure I'm overlooking something easy but I couldn't find a solution in earlier topics.

I'm trying to build an object "computerDraw". When I create a new "computerDraw" I want the computer to decide whether he pulls 1, 2 or 3 numbers out of the int array. The numbers are pulled out random.

The numbers that are drawn should be stored in the variable "computerSumCards".

I created a getter to return computerSumCards but it returns "0" every time.

I can't figure out why that is. Thanks for the help!

```<code>public class computerDraw {
    int computerSumCards;
    int getAmountOfComputerCards;
    int randomCard;
    int draws = 0;

    private int[] possibleDraws = {1, 2, 3};
    int computerCanDraw = (possibleDraws[new Random().nextInt(possibleDraws.length)]);

    public void drawLoop() {
            while (draws < computerCanDraw) {
                    int[] cards = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};
                    randomCard = (cards[new Random().nextInt(cards.length)]);
                    computerSumCards += randomCard;

            }
    }

    public int getComputerSumCards() {
            return computerSumCards;
    }

    public int getAmountOfComputerCards() {
            getAmountOfComputerCards = draws;
            return getAmountOfComputerCards;
    }
}
</code>```

答: You need to call draw.drawLoop(); but even if you call your while loop is going in infinite loop. values for draws and computerCanDraw are never getting changes and draws remains always < computerCanDraw value. You should either change  draws value or proper implement the computerCanDraw.</p>

Title: getter always returns 0

Body:
I'm new to java coding, so sorry for the beginner question. I'm pretty sure I'm overlooking something easy but I couldn't find a solution in earlier topics.

I'm trying to build an object "computerDraw". When I create a new "computerDraw" I want the computer to decide whether he pulls 1, 2 or 3 numbers out of the int array. The numbers are pulled out random.

The numbers that are drawn should be stored in the variable "computerSumCards".

I created a getter to return computerSumCards but it returns "0" every time.

I can't figure out why that is. Thanks for the help!

public class computerDraw {
    int computerSumCards;
    int getAmountOfComputerCards;
    int randomCard;
    int draws = 0;

    private int[] possibleDraws = {1, 2, 3};
    int computerCanDraw = (possibleDraws[new Random().nextInt(possibleDraws.length)]);

    public void drawLoop() {
            while (draws < computerCanDraw) {
                    int[] cards = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};
                    randomCard = (cards[new Random().nextInt(cards.length)]);
                    computerSumCards += randomCard;

            }
    }

    public int getComputerSumCards() {
            return computerSumCards;
    }

    public int getAmountOfComputerCards() {
            getAmountOfComputerCards = draws;
            return getAmountOfComputerCards;
    }
}


问:
Magento: Tab click event
Anyone knows a way to listen for clicks on magento tabs with javascript on the backend, say you want to do something everytime someone clicks a tab on the edit customer page. adminhtml/tabs.js has this:

```<code>    tabMouseClick : function(event) {
    var tab = Event.findElement(event, 'a');

    // go directly to specified url or switch tab
    if ((tab.href.indexOf('#') != tab.href.length-1)
        && !(Element.hasClassName(tab, 'ajax'))
    ) {
        location.href = tab.href;
    }
    else {
        this.showTabContent(tab);
    }
    Event.stop(event);
},
</code>```

But no use, anyone has any idea? I also tried using standard prototype js observer:

```<code>Event.observe("product_info_tabs", "click", function ()
{ alert(1);
});
</code>```

Did not do anything either. The solution should not modify the core, since this would add many problems with upgrades and maybe future magento versions.

答:
Old answer, but since I am here:
Magento internals fire an event when teh tab is shown.
You can simply hook into that event.

```<code>varienGlobalEvents.attachEventHandler('showTab', function(arg){
            console.log(arg.tab);
        });
</code>```

Also not needed to inject via overriding controller.
Just add in yoru own custom layout directive, and load js accordingly.

Title: Magento: Tab click event

Body:
Anyone knows a way to listen for clicks on magento tabs with javascript on the backend, say you want to do something everytime someone clicks a tab on the edit customer page. adminhtml/tabs.js has this:

    tabMouseClick : function(event) {
    var tab = Event.findElement(event, 'a');

    // go directly to specified url or switch tab
    if ((tab.href.indexOf('#') != tab.href.length-1)
        && !(Element.hasClassName(tab, 'ajax'))
    ) {
        location.href = tab.href;
    }
    else {
        this.showTabContent(tab);
    }
    Event.stop(event);
},

But no use, anyone has any idea? I also tried using standard prototype js observer:

Event.observe("product_info_tabs", "click", function ()
{ alert(1);
});

Did not do anything either. The solution should not modify the core, since this would add many problems with upgrades and maybe future magento versions.

Body:
Old answer, but since I am here:
Magento internals fire an event when teh tab is shown.
You can simply hook into that event.

varienGlobalEvents.attachEventHandler('showTab', function(arg){
            console.log(arg.tab);
        });

Also not needed to inject via overriding controller.
Just add in yoru own custom layout directive, and load js accordingly.


问:
unable add required attribute to a ReactJS input component
I am attempting to add a required attribute to a react input component:

```<code>export default function UiInput() {
   render() {
   return (
    <input
     {...customAttributes}
     size={size ? size : null}
     value={inputValue}
     maxLength={maxLength}
     required={required}
    />
   )
</code>```

and when I am calling my component like so,

```<code><UiInput
   required={required}
  />
</code>```

I am not getting the red asterisk to render - not getting any errors when I pass in required to an input component, but no red asterisk is showing up, how can I make sure the asterisk renders for required inputs? Does ReactJS not support this?

答:
Remember that you are passing required down as a prop to UiInput.

The pattern you're using for your Component is a Stateless Functional Component, when you do this:

props gets passed through as a parameter.

You don't need to declare the render() method, just simply write your return statement.

You can declare your Component like so:

```<code>function UiInput(props) {
      return (
        <input
         size={props.size ? props.size : null}
         required={props.required}
        />
      )
    }
</code>```

And render it like so:

```<code><UiInput required="required" />
</code>```

You can see a JSFiddle here. Please be aware that I did remove some props for the purpose of this demo.

Here's the Component rendered, please ignore the data-reactroot attribute.

Body:
I am attempting to add a required attribute to a react input component:

export default function UiInput() {
   render() {
   return (
    <input
     {...customAttributes}
     size={size ? size : null}
     value={inputValue}
     maxLength={maxLength}
     required={required}
    />
   )

and when I am calling my component like so,

<UiInput
   required={required}
  />

I am not getting the red asterisk to render - not getting any errors when I pass in required to an input component, but no red asterisk is showing up, how can I make sure the asterisk renders for required inputs? Does ReactJS not support this?

Body:
Remember that you are passing required down as a prop to UiInput.

The pattern you're using for your Component is a Stateless Functional Component, when you do this:

props gets passed through as a parameter.

You don't need to declare the render() method, just simply write your return statement.

You can declare your Component like so:

function UiInput(props) {
      return (
        <input
         size={props.size ? props.size : null}
         required={props.required}
        />
      )
    }

And render it like so:

<UiInput required="required" />

You can see a JSFiddle here. Please be aware that I did remove some props for the purpose of this demo.

Here's the Component rendered, please ignore the data-reactroot attribute.


问:
Progress bar loading is not stopped when the activity is called second time
I have created a welcome page(launcher) and included a progress bar.next activity will be displayed after this progress bar loading(for few seconds).For the first time,when the app is run,after few seconds the next activity is displayed.Now,when i press back button,welcome activity is being displayed.But this time,after few seconds,it is now calling the next activity(using Intent) like the first time.How to resolve this?
The code is:</p>

```<code>import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ProgressBar;

public class WelcomeActivity extends AppCompatActivity {
    ProgressBar p;
    private boolean mbActive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        p = (ProgressBar) findViewById(R.id.progressBar);
        final Thread timerThread = new Thread() {
            @Override
            public void run() {
                mbActive = true;
                try {
                    int waited = 0;
                    while(mbActive && (waited < 1000)) {
                        sleep(200);
                        if(mbActive) {
                            waited += 200;
                            updateProgress(waited);
                        }
                    }
                } catch(InterruptedException e) {
                } finally {
                    onContinue();
                }
            }
        };
        timerThread.start();

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    public void updateProgress(final int timePassed) {
        if(null != p) {
            final int progress = p.getMax() * timePassed / 100;
            p.setProgress(progress);
        }
    }

    public void onContinue() {
        Intent intd=new Intent(this,MainActivity.class);
        startActivity(intd);
    }

}
</code>```

答:
Try this :---
i change the code on keep the progress show code in on resume</p>

```<code> public class WelcomeActivity extends AppCompatActivity {

    ProgressBar p;
    private boolean mbActive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_welcome);
    }

    public void updateProgress(final int timePassed) {
      if (null != p) {
        final int progress = p.getMax() * timePassed / 100;
        p.setProgress(progress);
      }
    }

    public void onContinue() {
      Intent intd = new Intent(this, MainActivity.class);
      startActivity(intd);
    }

    @Override
    protected void onResume() {
      super.onResume();
      showProgress();
    }

    private void showProgress() {
      p = (ProgressBar) findViewById(R.id.progressBar);
      final Thread timerThread = new Thread() {
        @Override
        public void run() {
          mbActive = true;
          try {
            int waited = 0;
            while (mbActive && (waited < 1000)) {
              sleep(200);
              if (mbActive) {
                waited += 200;
                updateProgress(waited);
              }
            }
          } catch (InterruptedException e) {
          } finally {
            onContinue();
          }
        }
      };
      timerThread.start();
    }

    @Override
    public void onDestroy() {
      super.onDestroy();
    }
  }
</code>```

Body:
I have created a welcome page(launcher) and included a progress bar.next activity will be displayed after this progress bar loading(for few seconds).For the first time,when the app is run,after few seconds the next activity is displayed.Now,when i press back button,welcome activity is being displayed.But this time,after few seconds,it is now calling the next activity(using Intent) like the first time.How to resolve this?
The code is:

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ProgressBar;

public class WelcomeActivity extends AppCompatActivity {
    ProgressBar p;
    private boolean mbActive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        p = (ProgressBar) findViewById(R.id.progressBar);
        final Thread timerThread = new Thread() {
            @Override
            public void run() {
                mbActive = true;
                try {
                    int waited = 0;
                    while(mbActive && (waited < 1000)) {
                        sleep(200);
                        if(mbActive) {
                            waited += 200;
                            updateProgress(waited);
                        }
                    }
                } catch(InterruptedException e) {
                } finally {
                    onContinue();
                }
            }
        };
        timerThread.start();

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    public void updateProgress(final int timePassed) {
        if(null != p) {
            final int progress = p.getMax() * timePassed / 100;
            p.setProgress(progress);
        }
    }

    public void onContinue() {
        Intent intd=new Intent(this,MainActivity.class);
        startActivity(intd);
    }

}

Body:
Try this :---
i change the code on keep the progress show code in on resume

 public class WelcomeActivity extends AppCompatActivity {

    ProgressBar p;
    private boolean mbActive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_welcome);
    }

    public void updateProgress(final int timePassed) {
      if (null != p) {
        final int progress = p.getMax() * timePassed / 100;
        p.setProgress(progress);
      }
    }

    public void onContinue() {
      Intent intd = new Intent(this, MainActivity.class);
      startActivity(intd);
    }

    @Override
    protected void onResume() {
      super.onResume();
      showProgress();
    }

    private void showProgress() {
      p = (ProgressBar) findViewById(R.id.progressBar);
      final Thread timerThread = new Thread() {
        @Override
        public void run() {
          mbActive = true;
          try {
            int waited = 0;
            while (mbActive && (waited < 1000)) {
              sleep(200);
              if (mbActive) {
                waited += 200;
                updateProgress(waited);
              }
            }
          } catch (InterruptedException e) {
          } finally {
            onContinue();
          }
        }
      };
      timerThread.start();
    }

    @Override
    public void onDestroy() {
      super.onDestroy();
    }
  }


问:
How to consider a response_column int or Enum type using Flows
Most of the algorithms in h2o have a constraint in the response_column. For some of them, it must be an Enum type variable only and for other ones an  int. I have uploaded a data set where my response_column has the values: 0,1, therefore it can be converted to Enum easily. Then due to this constraint for some algorithms, I can use my original type for the response_column but for testing other algorithms I need to convert it as Enum.

I was trying to create an additional column let's say outputAsEnum, but I didn't find a way how to create an additional column based on an existing one. I was trying to create a copy of my original data frame, but I didn't find the option for doing it.

Is there any simple way to have a Flow that allows considering several algorithms for the same output variable, but converting it properly before? (to Enum or to int)

I have noticed too, that in order balance the classes for the response_column, the column type has to be an Enum. Is there any way to circumvent this? Based on that, if I have imbalance data, I am forced to use only the algorithms that can work with Enum data type. This is just an example, there are other configuration parameters that would depend on the data type of the response_column.

答:
The first part would be easily doable using our Python/R APIs - Flow is more for trying out H2O, doing very basic operations - you'd have to prepare your dataset so it has the same column twice or upload the same dataset twice. This should only be a problem if you're running certain algorithms as regression problems and others as classification.

As for the second question - no, rebalancing is only supported for binomial/multinomial problems (we're achieving it via under/over sampling of certain classes).


问:
Why I get error when I upload zip file to phonegap service?
I try to create apk file using phonegap service.

Here is my config.xml file in my project:

```<code><?xml version='1.1' encoding='utf-8'?>
<widget id="il.co.geomind.gilgalplay" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>sites</name>
    <description>
        app for sites mapping
    </description>
    <author email="jacklondon@ddd.com" href="">

    </author>
    <content src="index.html" />
    <access origin="*" />
    <preference name="Orientation" value="portrait" />
    <preference name="permissions" value="none"/>

    <feature name="http://api.phonegap.com/1.0/camera"/>
    <feature name="http://api.phonegap.com/1.0/geolocation"/>

    <icon src="images/icons/ldpi.png" gap:platform="android" gap:qualifier="ldpi" />
    <icon src="images/icons/mdpi.png" gap:platform="android" gap:qualifier="mdpi" />
    <icon src="images/icons/hdpi.png" gap:platform="android" gap:qualifier="hdpi" />
    <icon src="images/icons/xhdpi.png" gap:platform="android" gap:qualifier="xhdpi" />
    <icon src="images/icons/xxhdpi.png" gap:platform="android" gap:qualifier="xxhdpi" />
    <icon src="images/icons/xxxhdpi.png" gap:platform="android" gap:qualifier="xxxhdpi" />

    <!-- iPhone / iPod Touch  -->
    <icon src="images/icons/mdpi.png" gap:platform="ios" width="60" height="60" />
    <icon src="images/icons/xhdpi.png" gap:platform="ios" width="120" height="120" />

    <!-- Settings Icon -->
    <icon src="images/icons/ldpi.png" gap:platform="ios" width="29" height="29" />
    <icon src="images/icons/mdpi.png" gap:platform="ios" width="58" height="58" />

    <!-- Spotlight Icon -->
    <icon src="images/icons/ldpi.png" gap:platform="ios" width="40" height="40" />
    <icon src="images/icons/mdpi.png" gap:platform="ios" width="80" height="80" />

  <gap:platform name="android" />

  <gap:splash src="images/icons/screen-xhdpi.png"/>

  <gap:plugin name="cordova-plugin-whitelist" source="npm" />
  <gap:plugin name="org.apache.cordova.camera" version="0.3.6" source="npm" />
  <gap:plugin name="org.apache.cordova.device" version="0.3.0" source="npm"/>
  <gap:plugin name="com.phonegap.plugins.pushplugin" version="2.5.0" source="npm"/>
  <gap:plugin name="org.apache.cordova.geolocation" version="0.3.12" source="npm"/>

</widget>
</code>```

I make zip file from the project and make upload to the phonegap service I get this error:

```<code>Error - The following plugin, plugin version or a dependancy of this plugin is not on npm: com.phonegap.plugins.pushplugin@2.5.0
</code>```

Any idea why I get error above and how to fix it?

答:
It looks like you are trying to use https://github.com/phonegap-build/PushPlugin, which appear to be deprecated and hasn't had a release in 2 years.

Looks like you should try https://github.com/phonegap/phonegap-plugin-push instead which is the replacement for it

Body:
I try to create apk file using phonegap service.

Here is my config.xml file in my project:

<?xml version='1.1' encoding='utf-8'?>
<widget id="il.co.geomind.gilgalplay" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>sites</name>
    <description>
        app for sites mapping
    </description>
    <author email="jacklondon@ddd.com" href="">

    </author>
    <content src="index.html" />
    <access origin="*" />
    <preference name="Orientation" value="portrait" />
    <preference name="permissions" value="none"/>

    <feature name="http://api.phonegap.com/1.0/camera"/>
    <feature name="http://api.phonegap.com/1.0/geolocation"/>

    <icon src="images/icons/ldpi.png" gap:platform="android" gap:qualifier="ldpi" />
    <icon src="images/icons/mdpi.png" gap:platform="android" gap:qualifier="mdpi" />
    <icon src="images/icons/hdpi.png" gap:platform="android" gap:qualifier="hdpi" />
    <icon src="images/icons/xhdpi.png" gap:platform="android" gap:qualifier="xhdpi" />
    <icon src="images/icons/xxhdpi.png" gap:platform="android" gap:qualifier="xxhdpi" />
    <icon src="images/icons/xxxhdpi.png" gap:platform="android" gap:qualifier="xxxhdpi" />

    <icon src="images/icons/mdpi.png" gap:platform="ios" width="60" height="60" />
    <icon src="images/icons/xhdpi.png" gap:platform="ios" width="120" height="120" />

    <icon src="images/icons/ldpi.png" gap:platform="ios" width="29" height="29" />
    <icon src="images/icons/mdpi.png" gap:platform="ios" width="58" height="58" />

    <icon src="images/icons/ldpi.png" gap:platform="ios" width="40" height="40" />
    <icon src="images/icons/mdpi.png" gap:platform="ios" width="80" height="80" />

  <gap:platform name="android" />

  <gap:splash src="images/icons/screen-xhdpi.png"/>

  <gap:plugin name="cordova-plugin-whitelist" source="npm" />
  <gap:plugin name="org.apache.cordova.camera" version="0.3.6" source="npm" />
  <gap:plugin name="org.apache.cordova.device" version="0.3.0" source="npm"/>
  <gap:plugin name="com.phonegap.plugins.pushplugin" version="2.5.0" source="npm"/>
  <gap:plugin name="org.apache.cordova.geolocation" version="0.3.12" source="npm"/>

</widget>

I make zip file from the project and make upload to the phonegap service I get this error:

Error - The following plugin, plugin version or a dependancy of this plugin is not on npm: com.phonegap.plugins.pushplugin@2.5.0

Any idea why I get error above and how to fix it?


问:
remove extra + from text SQL
this refers to a question asked by someone else previously
previous question

my question is how do I adapt this solution so that before any function/script is ran the name and value fields are stripped of any additional + and updated so no additional + remain.

For e.g.

```<code>Name     Value
A+B+C+   1+2+3+
A++B     1++2
</code>```

this should be updated to

```<code>   Name     Value
    A+B+C   1+2+3
    A+B     1+2
</code>```

once this update has taken place, I can run the solution provided in the previous question.

Thanks

答:
You could use something on the lines of:

```<code> Select substr('1+2+3+', 0, length('1+2+3+')-1) from dual ;
 Select replace('1++2', '++', '+') from dual;
</code>```

I'm assuming you have the output already present in a variable you can play with.

EDIT:
Here's a function that can solve the problem (You can call this function in your select clauses thereby solving the problem):

```<code>CREATE OR REPLACE Function ReplaceChars
    ( name_in IN varchar2 )
    RETURN varchar2
IS
    changed_string varchar2(20) ;
BEGIN

    changed_string:=replace(name_in, '++', '+') ;

    CASE WHEN substr(changed_string, -1) in ('+')
        then
            changed_string:=substr(changed_string,0, length(changed_string) - 1) ;
        else changed_string:=changed_string ;
    end CASE ;

    RETURN changed_string;
END;
</code>```

Title: remove extra + from text SQL

Body:
this refers to a question asked by someone else previously
previous question

my question is how do I adapt this solution so that before any function/script is ran the name and value fields are stripped of any additional + and updated so no additional + remain.

For e.g.

Name     Value
A+B+C+   1+2+3+
A++B     1++2

this should be updated to

   Name     Value
    A+B+C   1+2+3
    A+B     1+2

once this update has taken place, I can run the solution provided in the previous question.

Thanks

Body:
You could use something on the lines of:

 Select substr('1+2+3+', 0, length('1+2+3+')-1) from dual ;
 Select replace('1++2', '++', '+') from dual;

I'm assuming you have the output already present in a variable you can play with.

EDIT:
Here's a function that can solve the problem (You can call this function in your select clauses thereby solving the problem):

CREATE OR REPLACE Function ReplaceChars
    ( name_in IN varchar2 )
    RETURN varchar2
IS
    changed_string varchar2(20) ;
BEGIN

    changed_string:=replace(name_in, '++', '+') ;

    CASE WHEN substr(changed_string, -1) in ('+')
        then
            changed_string:=substr(changed_string,0, length(changed_string) - 1) ;
        else changed_string:=changed_string ;
    end CASE ;

    RETURN changed_string;
END;


问:
Update column from another table column value
I'm trying to update user_id column on comments table from comment_users table user_id column value whhich comment_id matches on comments table id columns.

comment_users table

```<code>id: 5 comment_id: 1, user_id: 20
</code>```

comments table

before

```<code>id:1 user_id: NULL
</code>```

after

```<code>id: 1 user_id: 20
</code>```

I executed sql below but it doesn't work.

```<code>UPDATE comments
  SET user_id = comment_users.user_id
  INNER JOIN comment_users ON comment_users.comment_id = comments.id
  WHERE comment_users.comment_id = comments.id

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN comment_users ON comment_users.comment_id = comment' at line 3:       UPDATE comments
      SET user_id = comment_users.user_id
      INNER JOIN comment_users ON comment_users.comment_id = comments.id
      WHERE comment_users.comment_id = comments.id
</code>```

I have no idea about what is wrong.

答:
you're missing the table name for comments?</p>

```<code>UPDATE comments
SET user_id = comment_users.user_id
FROM [table_name] comments
INNER JOIN comment_users ON comment_users.comment_id = comments.id
WHERE comment_users.comment_id = comments.id
</code>```

Body:
I'm trying to update user_id column on comments table from comment_users table user_id column value whhich comment_id matches on comments table id columns.

comment_users table

id: 5 comment_id: 1, user_id: 20

comments table

before

id:1 user_id: NULL

after

id: 1 user_id: 20

I executed sql below but it doesn't work.

UPDATE comments
  SET user_id = comment_users.user_id
  INNER JOIN comment_users ON comment_users.comment_id = comments.id
  WHERE comment_users.comment_id = comments.id

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN comment_users ON comment_users.comment_id = comment' at line 3:       UPDATE comments
      SET user_id = comment_users.user_id
      INNER JOIN comment_users ON comment_users.comment_id = comments.id
      WHERE comment_users.comment_id = comments.id

I have no idea about what is wrong.

Body:
you're missing the table name for comments?

UPDATE comments
SET user_id = comment_users.user_id
FROM [table_name] comments
INNER JOIN comment_users ON comment_users.comment_id = comments.id
WHERE comment_users.comment_id = comments.id


问:
Can we incorporate the Speech Recognition framework with Today Extension
I am trying to build a widget which has a speech button. When I press it , it should convert the speech uttered to text.
However when I try to record the voice , AVAudioEngine fails to start. Is it because AVAudioEngine is not allowed in Today Extension? </p>

答: Searching the internet I seem to have found my answer. The short answer is no, you can't record Audio in extension. </p>


问:
Pattern substitution in Python
Looking for some alternative to clean a tabular file containing informations between parenthesis.
It will be the first step to include in a pipeline and I need to remove every value inside parenthesis (parenthesis included).

What I have

```<code>> Otu00467  Bacteria(100);Gracilibacteria(99);unclassified(99);unclassified(99);unclassified(99);unclassified(99);
> Otu00469  Bacteria(100);Proteobacteria(96);unclassified(96);unclassified(96);unclassified(96);unclassified(96);
> Otu00470  Bacteria(100);Proteobacteria(100);Alphaproteobacteria(100);Rhodospirillales(100);Rhodospirillaceae(100);Azospirillum(54);
</code>```

What I desire:

```<code> Otu00467   Bacteria;Gracilibacteria;unclassified;unclassified;unclassified;unclassified;
 Otu00469   Bacteria;Proteobacteria;unclassified;unclassified;unclassified;unclassified;
 Otu00470   Bacteria;Proteobacteria;Alphaproteobacteria;Rhodospirillales;Rhodospirillaceae;Azospirillum;
</code>```

My first approach was to split the second column by ";" , "("  , ")" and further join everything. Not bad but too ugly.

Thank you.

答:
I would try regexp for it. Something like that:

```<code>pattern = re.compile('(\w+)\(\d+\);')
';'.join(re.findall(pattern, string))
</code>```

For each string

Title: Pattern substitution in Python

Body:
Looking for some alternative to clean a tabular file containing informations between parenthesis.
It will be the first step to include in a pipeline and I need to remove every value inside parenthesis (parenthesis included).

What I have

> Otu00467  Bacteria(100);Gracilibacteria(99);unclassified(99);unclassified(99);unclassified(99);unclassified(99);
> Otu00469  Bacteria(100);Proteobacteria(96);unclassified(96);unclassified(96);unclassified(96);unclassified(96);
> Otu00470  Bacteria(100);Proteobacteria(100);Alphaproteobacteria(100);Rhodospirillales(100);Rhodospirillaceae(100);Azospirillum(54);

What I desire:

 Otu00467   Bacteria;Gracilibacteria;unclassified;unclassified;unclassified;unclassified;
 Otu00469   Bacteria;Proteobacteria;unclassified;unclassified;unclassified;unclassified;
 Otu00470   Bacteria;Proteobacteria;Alphaproteobacteria;Rhodospirillales;Rhodospirillaceae;Azospirillum;

My first approach was to split the second column by ";" , "("  , ")" and further join everything. Not bad but too ugly.

Thank you.

Body:
I would try regexp for it. Something like that:

pattern = re.compile('(\w+)\(\d+\);')
';'.join(re.findall(pattern, string))

For each string


问:
How to connect one model variable to mutiple html elements using angularjs data binding?
I'm trying to write some application using ng-repeat and limitTo, but it seems that the input field and the buttons can't work together on the same model value.

The problem is that once I changed the value from the input field, the buttons won't work any more. could you tell me why?

angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        'Jani',
        'Carl',
        'Margareth',
        'Hege',
        'Joe',
        'Gustav',
        'Birgit',
        'Mary',
        'Kai'
    ];
    $scope.test = 3;
    $scope.dPlus = function(){
       $scope.test++;
    }
    $scope.dMinus = function(){
       $scope.test--;
    }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp" ng-controller="namesCtrl">

<div ng-if='true'>

<p>Type a number in the input field:</p>

<p><input type="number" ng-model="test"></p>
<input type="button" value="+" ng-click="dPlus()"/>
<input type="button" value="-" ng-click="dMinus()"/>
<div>{{ test }}</div>

<ul>
  <li ng-repeat="x in names | limitTo:test">
    {{ x }}
  </li>
</ul>

</div>

</body>
</html></code>```

答:
You should use controller as syntax and it works.

If the model is a primitive, the child scope will just create a new
  model. But if the change is to a property of a model object, the
  lookup on parent scopes will find the referenced object and change its
  actual property. Common Mistake #2: Not Having a Dot In There

Here is the working code:

angular.module('myApp', []).controller('namesCtrl', function() {

var vm = this;

vm.names = [
        'Jani',
        'Carl',
        'Margareth',
        'Hege',
        'Joe',
        'Gustav',
        'Birgit',
        'Mary',
        'Kai'
    ];
    vm.test = 3;

    vm.dPlus = function(){
       vm.test++;
    }
    vm.dMinus = function(){
       vm.test--;
    }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp" ng-controller="namesCtrl as vm">

<div ng-if='true'>

<p>Type a number in the input field:</p>

<p><input type="number" ng-model="vm.test"></p>
<input type="button" value="+" ng-click="vm.dPlus()"/>
<input type="button" value="-" ng-click="vm.dMinus()"/>
<div>{{ vm.test }}</div>

<ul>
  <li ng-repeat="x in vm.names | limitTo:vm.test">
    {{ x }}
  </li>
</ul>

</div>

<p>The list will only consists of names matching the filter.</p>

</body>
</html></code>```

Body:
I'm trying to write some application using ng-repeat and limitTo, but it seems that the input field and the buttons can't work together on the same model value.

The problem is that once I changed the value from the input field, the buttons won't work any more. could you tell me why?

angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        'Jani',
        'Carl',
        'Margareth',
        'Hege',
        'Joe',
        'Gustav',
        'Birgit',
        'Mary',
        'Kai'
    ];
    $scope.test = 3;
    $scope.dPlus = function(){
       $scope.test++;
    }
    $scope.dMinus = function(){
       $scope.test--;
    }

});

<!DOCTYPE html>

Type a number in the input field:

<input type="number" ng-model="test">

<input type="button" value="+" ng-click="dPlus()"/>
<input type="button" value="-" ng-click="dMinus()"/>

{{ test }}

    {{ x }}

Body:
You should use controller as syntax and it works.

If the model is a primitive, the child scope will just create a new
  model. But if the change is to a property of a model object, the
  lookup on parent scopes will find the referenced object and change its
  actual property. Common Mistake #2: Not Having a Dot In There

Here is the working code:

angular.module('myApp', []).controller('namesCtrl', function() {

var vm = this;

vm.names = [
        'Jani',
        'Carl',
        'Margareth',
        'Hege',
        'Joe',
        'Gustav',
        'Birgit',
        'Mary',
        'Kai'
    ];
    vm.test = 3;

    vm.dPlus = function(){
       vm.test++;
    }
    vm.dMinus = function(){
       vm.test--;
    }

});

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp" ng-controller="namesCtrl as vm">

<div ng-if='true'>

<p>Type a number in the input field:</p>

<p><input type="number" ng-model="vm.test"></p>
<input type="button" value="+" ng-click="vm.dPlus()"/>
<input type="button" value="-" ng-click="vm.dMinus()"/>
<div>{{ vm.test }}</div>

<ul>
  <li ng-repeat="x in vm.names | limitTo:vm.test">
    {{ x }}
  </li>
</ul>

</div>

<p>The list will only consists of names matching the filter.</p>

</body>
</html>


答:
```<code>#Use re module to use regex
import re

#Open file and read data in data variable
data = open('file.txt').read()

#Apply search and replace on data variable
data = re.sub('\(\d+\)', '', data)

#Print data to output.txt file
with open('output.txt', 'w') as out:
    out.write(data)
</code>```

Title: Pattern substitution in Python


问:
Symfony 2 - disable translations on certain paths/routes
I would like to disable translations or force using english ones for paths which starts with /admin.

Is there a way to approach it in config?

If not what would be the best practice? EventListener checking routes and forcing english translation no matter the locale set in request?

答:
Depending on how you import your routes you can also set the default locale on it and no other options to set it (example routing.yml):</p>

```<code>app:
  resource: '@AppBundle/Controller/'
  type: annotation

app.admin:
  resource: '@AppBundle/Controller/Admin/'
  type: annotation
  prefix: /admin
  defaults:
      _locale: nl
</code>```

Body:
Depending on how you import your routes you can also set the default locale on it and no other options to set it (example routing.yml):

app:
  resource: '@AppBundle/Controller/'
  type: annotation

app.admin:
  resource: '@AppBundle/Controller/Admin/'
  type: annotation
  prefix: /admin
  defaults:
      _locale: nl


问:
Disable vectorized looping in FORTRAN?
Is it possible to bypass loop vectorization in FORTRAN? I'm writing to F77 standards for a particular project, but the GNU gfortran compiles up through modern FORTRANs, such as F95. Does anyone know if certain FORTRAN standards avoided loop vectorization or if there are any flags/options in gfortran to turn this off?

UPDATE: So, I think the final solution to my specific problem has to "DO" with the FORTRAN DO loops not allowing the updating of the iteration variable. Mention of this can be found in @High Performance Mark's reply on this related thread... Loop vectorization and how to avoid it

[Into the FORT, RAN the noobs for shelter.]

答:
With most modern compilers, the command-line option -O0 should turn off all optimisations, including loop vectorisation.

I have sometimes found that this causes bugs to apparently disappear.  However usually this means that there is something wrong with my code so if this sort of thing is happening to you then you have almost certainly written a buggy program.

It is theoretically possible but much less likely that there is a bug in the compiler, you can easily check this by compiling your code in another fortran compiler. (e.g. gfortran or g95).

ContentLicense: CC BY-SA 2.5

Title: Disable vectorized looping in FORTRAN?


问:
Composer: file_put_contents(./composer.json): failed to open stream: Permission denied
I'm trying to install Prestissimo to an Ubuntu 16.04 server, but that leads to an error:

```<code>$ composer global require "hirak/prestissimo:^0.3"
Changed current directory to /home/kramer65/.composer

  [ErrorException]
  file_put_contents(./composer.json): failed to open stream: Permission denied

require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--] [<packages>]...
</code>```

I'm logged in as user kramer65, so I wouldn't know why it can't write to my home folder. My normal reaction to a permission denied is to use sudo, but composer then always says:

Do not run Composer as root/super user! See https://getcomposer.org/root for details

Any idea how I can solve this?

答:
To resolve this, you should open up a terminal window and type this command:

sudo chown -R user ~/.composer (with user being your current user, in your case, kramer65)

After you have ran this command, you should have permission to run your composer global require command.

You may also need to remove the .composer file from the current directory, to do this open up a terminal window and type this command:

sudo rm -rf .composer

Body:
I'm trying to install Prestissimo to an Ubuntu 16.04 server, but that leads to an error:

$ composer global require "hirak/prestissimo:^0.3"
Changed current directory to /home/kramer65/.composer

  [ErrorException]
  file_put_contents(./composer.json): failed to open stream: Permission denied

require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--] [<packages>]...

I'm logged in as user kramer65, so I wouldn't know why it can't write to my home folder. My normal reaction to a permission denied is to use sudo, but composer then always says:

Do not run Composer as root/super user! See https://getcomposer.org/root for details

Any idea how I can solve this?


问:
SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
After upgrading to PHP 5.6 I get an error when trying to connect to a server via fsockopen()..

The certificate on the server (host) is self-signed

PHP Warning:  fsockopen(): SSL operation failed with code 1. OpenSSL Error messages:
      error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

code

```<code>if($fp = fsockopen($host, $port, $errno, $errstr, 20)){
    $this->request = 'POST '.substr($this->url, strlen($this->host)).' HTTP/1.1'.$crlf
        .'Host: '.$this->host.$crlf
        .'Content-Length: '.$content_length.$crlf
        .'Connection: Close'.$crlf.$crlf
        .$body;
    fwrite($fp, $this->request);

    while($line = fgets($fp)){
        if($line !== false){
            $this->response .= $line;
        }
    }

    fclose($fp);
}
</code>```

Have tried

```<code># cd /etc/ssl/certs/
# wget http://curl.haxx.se/ca/cacert.pem
</code>```

php.ini

```<code>openssl.cafile = "/etc/ssl/certs/cacert.pem"
</code>```

But the script still fails to work

update

This works

```<code>echo file_get_contents("/etc/ssl/certs/cacert.pem");
</code>```

update 2

```<code>$contextOptions = array(
    'ssl' => array(
        'verify_peer' => true, // You could skip all of the trouble by changing this to false, but it's WAY uncool for security reasons.
        'cafile' => '/etc/ssl/certs/cacert.pem',
        //'CN_match' => 'example.com', // Change this to your certificates Common Name (or just comment this line out if not needed)
        'ciphers' => 'HIGH:!SSLv2:!SSLv3',
        'disable_compression' => true,
    )
);

$context = stream_context_create($contextOptions);

$fp = stream_socket_client("{$host}:{$port}", $errno, $errstr, 20, STREAM_CLIENT_CONNECT, $context);
</code>```

error

PHP Warning:  stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages:
      error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

答:
The problem is in new PHP Version in macOS Sierra

Please add

```<code>stream_context_set_option($ctx, 'ssl', 'verify_peer', false);
</code>```

Body:
After upgrading to PHP 5.6 I get an error when trying to connect to a server via fsockopen()..

The certificate on the server (host) is self-signed

PHP Warning:  fsockopen(): SSL operation failed with code 1. OpenSSL Error messages:
      error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

code

if($fp = fsockopen($host, $port, $errno, $errstr, 20)){
    $this->request = 'POST '.substr($this->url, strlen($this->host)).' HTTP/1.1'.$crlf
        .'Host: '.$this->host.$crlf
        .'Content-Length: '.$content_length.$crlf
        .'Connection: Close'.$crlf.$crlf
        .$body;
    fwrite($fp, $this->request);

    while($line = fgets($fp)){
        if($line !== false){
            $this->response .= $line;
        }
    }

    fclose($fp);
}

Have tried

# cd /etc/ssl/certs/
# wget http://curl.haxx.se/ca/cacert.pem

php.ini

openssl.cafile = "/etc/ssl/certs/cacert.pem"

But the script still fails to work

update

This works

echo file_get_contents("/etc/ssl/certs/cacert.pem");

update 2

$contextOptions = array(
    'ssl' => array(
        'verify_peer' => true, // You could skip all of the trouble by changing this to false, but it's WAY uncool for security reasons.
        'cafile' => '/etc/ssl/certs/cacert.pem',
        //'CN_match' => 'example.com', // Change this to your certificates Common Name (or just comment this line out if not needed)
        'ciphers' => 'HIGH:!SSLv2:!SSLv3',
        'disable_compression' => true,
    )
);

$context = stream_context_create($contextOptions);

$fp = stream_socket_client("{$host}:{$port}", $errno, $errstr, 20, STREAM_CLIENT_CONNECT, $context);

error

PHP Warning:  stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages:
      error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Body:
The problem is in new PHP Version in macOS Sierra

Please add

stream_context_set_option($ctx, 'ssl', 'verify_peer', false);


问:
How to add Service provider and Identity Provider in Wso2 IS configuration file for SSO?
We are using an automation process currently in our environment. And I have configured SSO manually from UI,
I have tried configuring Service Provider from sso-idp-config.xml but i dont see any entry in the database.The configuration i added as :

```<code><SSOIdentityProviderConfig>
<ServiceProvider>
    <Issuer>Application</Issuer>
    <AssertionConsumerService>https://<%= node[:carbon][:dns_esb_name] %>:9443/acs</AssertionConsumerService>
    <SignAssertion>true</SignAssertion>
    <SignResponse>true</SignResponse>
    <EnableAttributeProfile>true</EnableAttributeProfile>
    <IncludeAttributeByDefault>false</IncludeAttributeByDefault>
    <EnableAudienceRestriction>true</EnableAudienceRestriction>
    <AudiencesList>
        <Audience>https://<%= node[:carbon][:dns_elb_name] %>:9443/oauth/token</Audience>
    </AudiencesList>
    <EnableRecipientValidation>true</EnableRecipientValidation>
    <RecipientList>
        <Recipient>https://<%= node[:carbon][:dns_elb_name] %>:9443/oauth/token</Recipient>
    </RecipientList>
    <EnableSingleLogout>true</EnableSingleLogout>
    <SingleLogoutUrl></SingleLogoutUrl>
    <CallbackUrl>https://<%= node[:carbon][:dns_elb_name] %>:9443/carbon</CallbackUrl>
</ServiceProvider>
</SSOIdentityProviderConfig>
</code>```

Where to add Service Provider ID so that I can view in the database with its name.
Also please help me with the approach to automate Identity Provider.
Thanks in advance.

答: You can add any Identity provider into database by prefixing its name with "SHARED_". It worked for me for WSO2 IS 5.1.0</p>

Body:
We are using an automation process currently in our environment. And I have configured SSO manually from UI,
I have tried configuring Service Provider from sso-idp-config.xml but i dont see any entry in the database.The configuration i added as :

<SSOIdentityProviderConfig>
<ServiceProvider>
    <Issuer>Application</Issuer>
    <AssertionConsumerService>https://<%= node[:carbon][:dns_esb_name] %>:9443/acs</AssertionConsumerService>
    <SignAssertion>true</SignAssertion>
    <SignResponse>true</SignResponse>
    <EnableAttributeProfile>true</EnableAttributeProfile>
    <IncludeAttributeByDefault>false</IncludeAttributeByDefault>
    <EnableAudienceRestriction>true</EnableAudienceRestriction>
    <AudiencesList>
        <Audience>https://<%= node[:carbon][:dns_elb_name] %>:9443/oauth/token</Audience>
    </AudiencesList>
    <EnableRecipientValidation>true</EnableRecipientValidation>
    <RecipientList>
        <Recipient>https://<%= node[:carbon][:dns_elb_name] %>:9443/oauth/token</Recipient>
    </RecipientList>
    <EnableSingleLogout>true</EnableSingleLogout>
    <SingleLogoutUrl></SingleLogoutUrl>
    <CallbackUrl>https://<%= node[:carbon][:dns_elb_name] %>:9443/carbon</CallbackUrl>
</ServiceProvider>
</SSOIdentityProviderConfig>

Where to add Service Provider ID so that I can view in the database with its name.
Also please help me with the approach to automate Identity Provider.
Thanks in advance.


问:
Twilio SMS/Python, trying to capture the body of an SMS
This is my first post here so sorry if anything is not correct. I have been trying to retrieve the body of an SMS through twilio. The end goal is to have a basic chat-bot that I can use over text however I did not want to code everything within the one Python file. Thats the purpose for pulling it out.

I am looking for some guidance on where I should be heading next.
To start here is the error(s):

```<code>Traceback (most recent call last):
File "main.py", line 24, in <module>
print (sms_reply().message_body)
File "/home/pi/PythonScripts/BasicSMSBot/SMSIncoming.py", line 18, in
sms_reply
message_body = request.form['Body']
File "/usr/local/lib/python3.4/dist-packages/werkzeug/local.py", line 347,
in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/local/lib/python3.4/dist-packages/werkzeug/local.py", line 306,
in _get_current_object
return self.__local()
File "/usr/local/lib/python3.4/dist-packages/flask/globals.py", line 37, in
_lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.
</code>```

As it seams there is something wrong with the way I am wanting to pull the body out.

Here is the code currently in SMSIncoming:

```<code>#importing nessisary scripts and files
import os
#import SMSOutgoing
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse

#initilizing the global user variable
#glo_user_var = (' T ');

#initilizing app
app = Flask(__name__)

@app.route("/sms", methods=["GET", "POST"])
def sms_reply():
    resp = MessagingResponse()
    #body = request.values.get('Body', None)
    message_body = request.form['Body']
    #for debuging the SMS instercept
    #saveFile = open('bodyfile.txt', 'w')
    #saveFile.write(body)
    #saveFile.close()

    resp.message("Testting the SMS responce")
    return str(resp)
    return str(body)

    #lets main app process run
    if __name__ == "__main__":
           app.run(debug=True)
</code>```

Here is the code currently in main.py

```<code>   #place all imports and scripts to be run
   import os
   import SMSOutgoing
   from SMSIncoming import sms_reply
   #from SMSIncoming.py import app, sms_reply
   import time

   #call up ngrok and make server on port 5000
   #os.system("./ngrok http 5000");

   #start running the SMSIncoming app
   #if __name__ == "__main__":
   #       app.run(debug=True)

   #       have to start apps separately!  #

   #this block will handle incoming SMS (User Input)
   while True:
   #       global glo_user_var
          print (sms_reply().message_body)
          #file = open('test_user_input.txt', 'w')
          #file.write(glo_user_var)
          #file.close()
          time.sleep(1)
</code>```

Everything in main.py is either commented out or in place for testing.

The reason I want to print the body is to make sure that it is getting to where I want it to be. After that I would use it as the users input which would define the reply.

I am also using ngrok to be my http webhook.

答:
Twilio developer evangelist here.

First up, the problem that you are having is because you are breaking the flask app up into multiple files and attempting to call a function that is also a route once a second. So, you definitely need to drop the while True loop to start with.

Next, I understand that you can see that things might become overwhelming if you build the entire application in one file. However you are currently prematurely optimising. I recommend you get it working first in one file then refactor the application into more manageable chunks.

For the record, you are doing the right thing to get the SMS message's body. The Twilio message webhook will send the body as the form parameter Body so you will be able to get hold of that parameter within a response to that request using

```<code>message_body = request.form['Body']
</code>```

Once you get to that stage, take a look at this documentation from Flask on building larger applications and then the information on building modular applications with Blueprints.

Body:
This is my first post here so sorry if anything is not correct. I have been trying to retrieve the body of an SMS through twilio. The end goal is to have a basic chat-bot that I can use over text however I did not want to code everything within the one Python file. Thats the purpose for pulling it out.

I am looking for some guidance on where I should be heading next.
To start here is the error(s):

Traceback (most recent call last):
File "main.py", line 24, in <module>
print (sms_reply().message_body)
File "/home/pi/PythonScripts/BasicSMSBot/SMSIncoming.py", line 18, in
sms_reply
message_body = request.form['Body']
File "/usr/local/lib/python3.4/dist-packages/werkzeug/local.py", line 347,
in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/local/lib/python3.4/dist-packages/werkzeug/local.py", line 306,
in _get_current_object
return self.__local()
File "/usr/local/lib/python3.4/dist-packages/flask/globals.py", line 37, in
_lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.

As it seams there is something wrong with the way I am wanting to pull the body out.

Here is the code currently in SMSIncoming:

#importing nessisary scripts and files
import os
#import SMSOutgoing
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse

#initilizing the global user variable
#glo_user_var = (' T ');

#initilizing app
app = Flask(__name__)

@app.route("/sms", methods=["GET", "POST"])
def sms_reply():
    resp = MessagingResponse()
    #body = request.values.get('Body', None)
    message_body = request.form['Body']
    #for debuging the SMS instercept
    #saveFile = open('bodyfile.txt', 'w')
    #saveFile.write(body)
    #saveFile.close()

    resp.message("Testting the SMS responce")
    return str(resp)
    return str(body)

    #lets main app process run
    if __name__ == "__main__":
           app.run(debug=True)

Here is the code currently in main.py

   #place all imports and scripts to be run
   import os
   import SMSOutgoing
   from SMSIncoming import sms_reply
   #from SMSIncoming.py import app, sms_reply
   import time

   #call up ngrok and make server on port 5000
   #os.system("./ngrok http 5000");

   #start running the SMSIncoming app
   #if __name__ == "__main__":
   #       app.run(debug=True)

   #       have to start apps separately!  #

   #this block will handle incoming SMS (User Input)
   while True:
   #       global glo_user_var
          print (sms_reply().message_body)
          #file = open('test_user_input.txt', 'w')
          #file.write(glo_user_var)
          #file.close()
          time.sleep(1)

Everything in main.py is either commented out or in place for testing.

The reason I want to print the body is to make sure that it is getting to where I want it to be. After that I would use it as the users input which would define the reply.

I am also using ngrok to be my http webhook.

Body:
Twilio developer evangelist here.

First up, the problem that you are having is because you are breaking the flask app up into multiple files and attempting to call a function that is also a route once a second. So, you definitely need to drop the while True loop to start with.

Next, I understand that you can see that things might become overwhelming if you build the entire application in one file. However you are currently prematurely optimising. I recommend you get it working first in one file then refactor the application into more manageable chunks.

For the record, you are doing the right thing to get the SMS message's body. The Twilio message webhook will send the body as the form parameter Body so you will be able to get hold of that parameter within a response to that request using

message_body = request.form['Body']

Once you get to that stage, take a look at this documentation from Flask on building larger applications and then the information on building modular applications with Blueprints.


答:
When you print out a pointer, it's basically implicitly cast to an integer for display, using the byte address.

When you subtract pointers, the result is a ptrdiff_t, which is already an integral type. You can only subtract pointers of the same type, and the sizeof the type is factored into the calculation. The result is the number of elements between the two pointers,  not the number of bytes. (Keep in mind that if the two pointers are not pointing into the same array, the subtraction is undefined behaviour.)

In your case, the pointer type is "pointer to array of 3 ints", and your two pointers are to two adjacent elements in an array of 2 of those (array of 3 ints). They are 1 element apart, but 12 bytes apart.

Title: How to understand the output?

Body:
int a[2][3];
cout << a+1 << " " << a << " " << (a+1) - a << endl;

Output:

0029FAC0 0029FAB4 1

Shouldn't (a+1)-a be 0029FAC0-0029FAB4=12 ?


问:
Warning: array_push() expects parameter 1 to be array
This is my code, and when I run this function I get this :Warning: array_push() expects parameter 1 to be array  However I define $printed as an array prior to starting.

```<code>$printed = array();

function dayAdvance ($startDay, $endDay, $weekType){
         $newdateform = array(
                    'title' => date("M d", strtotime($startDay))."     to     ".date("M d", strtotime($endDay)). $type,
                    'start' => $startDay."T08:00:00Z",
                    'end' => $startDay."T16:00:00Z",
                    'url' => "http://aliahealthcareer.com/calendar/".$_GET['fetching']."/".$startDate);

                    array_push($printed, $newdateform);

        if ($weekType=="weekend"){
            $days="Saturday,Sunday";
        }
        if ($weekType=="day"){
            $days="Monday,Tuesday,Wednesday,Thuresday,Friday";
        }
        if ($weekType=="evening"){
            $days="Monday,Tuesday,Wednesday";
        }
        $start = $startDate;
        while($startDay <= $endDay) {
            $startDay = date('Y-m-d', strtotime($startDay. ' + 1 days'));
            $dayWeek = date("l", strtotime($startDay));
            $pos = strpos($dayWeek, $days);
            if ($pos !== false) {
                $newdateform = array(
                    'title' => date("M d", strtotime($start))."     to     ".date("M d", strtotime($endDate)). $type,
                    'start' => $startDate."T08:00:00Z",
                    'end' => $startDate."T16:00:00Z",
                    'url' => "http://aliahealthcareer.com/calendar/".$_GET['fetching']."/".$startDate);

                    array_push($printed, $newdateform);

            }

        }

    }
</code>```

答:
Instead of the function array_push() use $your_array[] = $element_to_be_added; when you want to add a single element to the array.

As mentioned in the docs, this creates a new array, if the array is null:

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

and:

Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.

from: http://php.net/manual/en/function.array-push.php

Body:
This is my code, and when I run this function I get this :Warning: array_push() expects parameter 1 to be array  However I define $printed as an array prior to starting.

$printed = array();

function dayAdvance ($startDay, $endDay, $weekType){
         $newdateform = array(
                    'title' => date("M d", strtotime($startDay))."     to     ".date("M d", strtotime($endDay)). $type,
                    'start' => $startDay."T08:00:00Z",
                    'end' => $startDay."T16:00:00Z",
                    'url' => "http://aliahealthcareer.com/calendar/".$_GET['fetching']."/".$startDate);

                    array_push($printed, $newdateform);

        if ($weekType=="weekend"){
            $days="Saturday,Sunday";
        }
        if ($weekType=="day"){
            $days="Monday,Tuesday,Wednesday,Thuresday,Friday";
        }
        if ($weekType=="evening"){
            $days="Monday,Tuesday,Wednesday";
        }
        $start = $startDate;
        while($startDay <= $endDay) {
            $startDay = date('Y-m-d', strtotime($startDay. ' + 1 days'));
            $dayWeek = date("l", strtotime($startDay));
            $pos = strpos($dayWeek, $days);
            if ($pos !== false) {
                $newdateform = array(
                    'title' => date("M d", strtotime($start))."     to     ".date("M d", strtotime($endDate)). $type,
                    'start' => $startDate."T08:00:00Z",
                    'end' => $startDate."T16:00:00Z",
                    'url' => "http://aliahealthcareer.com/calendar/".$_GET['fetching']."/".$startDate);

                    array_push($printed, $newdateform);

            }

        }

    }


问:
How to validate for checkbox selection if all checkbox have same name?
Hi All
I have a group of check box having same name so as to get the array of single variable when it is posted on serverside for exampleL

```<code><input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
</code>```

I need a javascript validation to check whether any checkbox is selected or not?

Thanks and Regards

NOTE: I need javascript validation

答:
```<code><form name="myform" method="POST" action="" onsubmit="return checkTheBox();">
  <input type="checkbox" name="midlevelusers[]" value="1" /> 1
  <input type="checkbox" name="midlevelusers[]" value="2" /> 2
  <input type="checkbox" name="midlevelusers[]" value="3" /> 3
  <input type="checkbox" name="midlevelusers[]" value="4" /> 4
  <input type="checkbox" name="midlevelusers[]" value="5" /> 5
  <input type="submit" value="Submit Form" />
</form>

<script type="text/javascript">
  function checkTheBox() {
    var flag = 0;
    for (var i = 0; i< 5; i++) {
      if(document.myform["midlevelusers[]"][i].checked){
        flag ++;
      }
    }
    if (flag != 1) {
      alert ("You must check one and only one checkbox!");
      return false;
    }
    return true;
  }
</script>
</code>```

Body:
Hi All
I have a group of check box having same name so as to get the array of single variable when it is posted on serverside for exampleL

<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">

I need a javascript validation to check whether any checkbox is selected or not?

Thanks and Regards

NOTE: I need javascript validation

Body:
<form name="myform" method="POST" action="" onsubmit="return checkTheBox();">
  <input type="checkbox" name="midlevelusers[]" value="1" /> 1 &nbsp;&nbsp;
  <input type="checkbox" name="midlevelusers[]" value="2" /> 2 &nbsp;&nbsp;
  <input type="checkbox" name="midlevelusers[]" value="3" /> 3 &nbsp;&nbsp;
  <input type="checkbox" name="midlevelusers[]" value="4" /> 4 &nbsp;&nbsp;
  <input type="checkbox" name="midlevelusers[]" value="5" /> 5 &nbsp;&nbsp;
  <input type="submit" value="Submit Form" />
</form>

<script type="text/javascript">
  function checkTheBox() {
    var flag = 0;
    for (var i = 0; i< 5; i++) {
      if(document.myform["midlevelusers[]"][i].checked){
        flag ++;
      }
    }
    if (flag != 1) {
      alert ("You must check one and only one checkbox!");
      return false;
    }
    return true;
  }
</script>


答:
This regex gets rid of parenthesized groups of digits, it also gets rid of any '>' characters, since it appears that you want to eliminate them as well.

```<code>import re

data = '''\
> Otu00467  Bacteria(100);Gracilibacteria(99);unclassified(99);>unclassified(99);unclassified(99);unclassified(99);
> Otu00469  Bacteria(100);Proteobacteria(96);unclassified(96);unclassified(96);unclassified(96);unclassified(96);
> Otu00470  Bacteria(100);Proteobacteria(100);Alphaproteobacteria(100);Rhodospirillales(100);Rhodospirillaceae(100);Azospirillum(54);
'''

data = re.sub(r'>|\(\d+\)', '', data)
print(data)
</code>```

output

```<code> Otu00467  Bacteria;Gracilibacteria;unclassified;unclassified;unclassified;unclassified;
 Otu00469  Bacteria;Proteobacteria;unclassified;unclassified;unclassified;unclassified;
 Otu00470  Bacteria;Proteobacteria;Alphaproteobacteria;Rhodospirillales;Rhodospirillaceae;Azospirillum;
</code>```

This code works on Python 2 & 3.

Title: Pattern substitution in Python

Body:
This regex gets rid of parenthesized groups of digits, it also gets rid of any '>' characters, since it appears that you want to eliminate them as well.

import re

data = '''\
> Otu00467  Bacteria(100);Gracilibacteria(99);unclassified(99);>unclassified(99);unclassified(99);unclassified(99);
> Otu00469  Bacteria(100);Proteobacteria(96);unclassified(96);unclassified(96);unclassified(96);unclassified(96);
> Otu00470  Bacteria(100);Proteobacteria(100);Alphaproteobacteria(100);Rhodospirillales(100);Rhodospirillaceae(100);Azospirillum(54);
'''

data = re.sub(r'>|\(\d+\)', '', data)
print(data)

output

 Otu00467  Bacteria;Gracilibacteria;unclassified;unclassified;unclassified;unclassified;
 Otu00469  Bacteria;Proteobacteria;unclassified;unclassified;unclassified;unclassified;
 Otu00470  Bacteria;Proteobacteria;Alphaproteobacteria;Rhodospirillales;Rhodospirillaceae;Azospirillum;

This code works on Python 2 & 3.


问:
AVAudioEngine with Today Extension
Hello I want to add the Speech framework to an iOS 10 Today Extension.

I try to use SpeakToMe sample https://developer.apple.com/library/content/samplecode/SpeakToMe/Introduction/Intro.html to record audio with AVAudioEngine.

But I get an exception when I try to start the audio engine

```<code>try audioEngine.start()

2016-10-04 22:21:24.658964 VoiceReco[4225:1230467] [aurioc] 1316: AUIOClient_StartIO failed (561145187)
2016-10-04 22:21:24.663743 VoiceReco[4225:1230467] [central] 54:   ERROR:    [0x1af158c40] >avae> AVAudioEngineGraph.mm:1175: Start: error 561145187
</code>```

The sample code from apple works fine if I use the normal view controller without my extension. Does anyone know a workaround for this?

答:
You can't record audio in an extension.
Check here</p>

Title: AVAudioEngine with Today Extension

Body:
Hello I want to add the Speech framework to an iOS 10 Today Extension.

I try to use SpeakToMe sample https://developer.apple.com/library/content/samplecode/SpeakToMe/Introduction/Intro.html to record audio with AVAudioEngine.

But I get an exception when I try to start the audio engine

try audioEngine.start()

2016-10-04 22:21:24.658964 VoiceReco[4225:1230467] [aurioc] 1316: AUIOClient_StartIO failed (561145187)
2016-10-04 22:21:24.663743 VoiceReco[4225:1230467] [central] 54:   ERROR:    [0x1af158c40] >avae> AVAudioEngineGraph.mm:1175: Start: error 561145187

The sample code from apple works fine if I use the normal view controller without my extension. Does anyone know a workaround for this?


问:
Proxy in package.json not affecting fetch request
I am trying to fetch some data from the development server using React.

I am running the client on localhost:3001 and the backend on port 3000.

The fetch request :

```<code> const users = fetch('/api/users');
    users.then((err,res) => {
      console.log(res);
    })
</code>```

When I run my development server and webpack-dev-server I get the following output:

```<code>GET http://localhost:3001/api/users 404 (Not Found)
</code>```

I tried specifying the proxy in the package.json so it would proxy the request to the API server, however nothing has changed.

Here is my package.json file:

.. and the webpack.config :

Please tell me, if you need to see anything else from my project. I apologies, if I'm missing something and not being thorough, I'm still quite new to using these technologies.

答: Webpack Dev Server uses devServer.proxy config in your Webpack config to control proxying requests.

Body:
I am trying to fetch some data from the development server using React.

I am running the client on localhost:3001 and the backend on port 3000.

The fetch request :

 const users = fetch('/api/users');
    users.then((err,res) => {
      console.log(res);
    })

When I run my development server and webpack-dev-server I get the following output:

GET http://localhost:3001/api/users 404 (Not Found)

I tried specifying the proxy in the package.json so it would proxy the request to the API server, however nothing has changed.

Here is my package.json file:

.. and the webpack.config :

Please tell me, if you need to see anything else from my project. I apologies, if I'm missing something and not being thorough, I'm still quite new to using these technologies.


问:
How would I use enum on my project?
I have a class with an instance field lockAction, value 1 is lock and 3 is unlock. I'd like to introduce enum on to my EJB project. How do I got about that?

```<code>public enum lockUnlock {
    LOCK, //1
    UNLOCK, //3
</code>```

}

答:
You could assign a value to the enum like so.</p>

```<code>public enum LockUnlock  {
    LOCK(1), UNLOCK(3);

    private final int value;
    private LockUnlock(int value) {
        this.value = value;
    }
    public int getValue() { return value; }
}
</code>```

Title: How would I use enum on my project?

Body:
I have a class with an instance field lockAction, value 1 is lock and 3 is unlock. I'd like to introduce enum on to my EJB project. How do I got about that?

public enum lockUnlock {
    LOCK, //1
    UNLOCK, //3

}

Body:
You could assign a value to the enum like so.

public enum LockUnlock  {
    LOCK(1), UNLOCK(3);

    private final int value;
    private LockUnlock(int value) {
        this.value = value;
    }
    public int getValue() { return value; }
}


问:
marker.iconView?.addSubview(UIButton) not clickable with Gmaps
hi i create my custom marker.iconview

```<code>marker.iconView = CustomMarkerView(frame: CGRect(x: 0, y: 0, width: 301, height: 36))
</code>```

here is my custom marker view

```<code>import UIKit

class CustomMarkerView: UIView {

var logo = UIImage()
var adress = UILabel()
var price = UILabel()
var icon_like = UIImage(named: "icon_like")
var icon_direction = UIImage(named: "icon_direction")

override init(frame: CGRect) {
    super.init(frame: frame)
    self.addCustomView()
}

init(frame: CGRect, adress: String, price: String, logo: String) {
    super.init(frame: frame)
    self.adress.text = adress
    self.price.text = price
    self.logo = UIImage(named: logo)!
    self.addCustomView()
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func addCustomView() {
    let layerBG = CALayer()
    layerBG.frame.size.width = 201
    layerBG.frame.size.height = 36
    layerBG.backgroundColor = UIColor(patternImage: UIImage(named: "bgMarkerView")!).cgColor
    layerBG.position = CGPoint(x: 201, y: 18)
    self.layer.addSublayer(layerBG)
}
</code>```

then i add more custom elements in this view in my view controller

```<code>func addInternalElements(adress: String, price: String, logo: String) {
    let logoView = UIView()

    let logoImg = UIImage(named: logo)
    let logoImage = UIImageView(image: logoImg)
    logoView.addSubview(logoImage)
    setMarkerLogoConstraint(logoView: logoView, logoImage: logoImage)

    let adressLabel = UILabel()
    adressLabel.font = UIFont(name: "helveticaneuecyr-roman", size: 9)!
    adressLabel.textColor = UIColor.white
    adressLabel.numberOfLines = 2
    adressLabel.text = adress

    let priceLabel = UILabel()
    priceLabel.font = UIFont(name: "helveticaneuecyr-roman", size: 11.2)!
    priceLabel.textColor = UIColor.white
    priceLabel.numberOfLines = 2
    priceLabel.text = price

    let icon_like = UIImage(named: "icon_like")
    let likeBtn = UIButton()
    likeBtn.setImage(icon_like, for: .normal)
    likeBtn.setImage(icon_like, for: .selected)
    likeBtn.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    likeBtn.tag = 5
    likeBtn.isMultipleTouchEnabled = true

    self.topBarView.addSubview(btnProfileTopBar)
    setProfileIconConstraints()

    self.marker.iconView?.addSubview(logoView)
    self.marker.iconView?.addSubview(adressLabel)
    self.marker.iconView?.addSubview(priceLabel)
    self.marker.iconView?.addSubview(likeBtn)
    self.marker.iconView?.isMultipleTouchEnabled = true

    setLogoViewMarkerConstraints(logoView: logoView)
    setAdressMarkerConstraints(label: adressLabel, logoView: logoView)
    setPriceMarkerConstraints(label: priceLabel, logoView: logoView)
    setLikeBtnMarkerConstraints(btn: likeBtn)
}
</code>```

all looks good but uibutton doesn't clickable(likeBtn.addTarget doesn't work), if i implement this method

```<code>func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {

    return false
}
</code>```

i don't understand how i understand that i click on correct button(there will be more buttons)

答: I had solved this problem created custom icon view across infoWindow</p>

Body:
hi i create my custom marker.iconview

marker.iconView = CustomMarkerView(frame: CGRect(x: 0, y: 0, width: 301, height: 36))

here is my custom marker view

import UIKit

class CustomMarkerView: UIView {

var logo = UIImage()
var adress = UILabel()
var price = UILabel()
var icon_like = UIImage(named: "icon_like")
var icon_direction = UIImage(named: "icon_direction")

override init(frame: CGRect) {
    super.init(frame: frame)
    self.addCustomView()
}

init(frame: CGRect, adress: String, price: String, logo: String) {
    super.init(frame: frame)
    self.adress.text = adress
    self.price.text = price
    self.logo = UIImage(named: logo)!
    self.addCustomView()
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func addCustomView() {
    let layerBG = CALayer()
    layerBG.frame.size.width = 201
    layerBG.frame.size.height = 36
    layerBG.backgroundColor = UIColor(patternImage: UIImage(named: "bgMarkerView")!).cgColor
    layerBG.position = CGPoint(x: 201, y: 18)
    self.layer.addSublayer(layerBG)
}

then i add more custom elements in this view in my view controller

func addInternalElements(adress: String, price: String, logo: String) {
    let logoView = UIView()

    let logoImg = UIImage(named: logo)
    let logoImage = UIImageView(image: logoImg)
    logoView.addSubview(logoImage)
    setMarkerLogoConstraint(logoView: logoView, logoImage: logoImage)

    let adressLabel = UILabel()
    adressLabel.font = UIFont(name: "helveticaneuecyr-roman", size: 9)!
    adressLabel.textColor = UIColor.white
    adressLabel.numberOfLines = 2
    adressLabel.text = adress

    let priceLabel = UILabel()
    priceLabel.font = UIFont(name: "helveticaneuecyr-roman", size: 11.2)!
    priceLabel.textColor = UIColor.white
    priceLabel.numberOfLines = 2
    priceLabel.text = price

    let icon_like = UIImage(named: "icon_like")
    let likeBtn = UIButton()
    likeBtn.setImage(icon_like, for: .normal)
    likeBtn.setImage(icon_like, for: .selected)
    likeBtn.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    likeBtn.tag = 5
    likeBtn.isMultipleTouchEnabled = true

    self.topBarView.addSubview(btnProfileTopBar)
    setProfileIconConstraints()

    self.marker.iconView?.addSubview(logoView)
    self.marker.iconView?.addSubview(adressLabel)
    self.marker.iconView?.addSubview(priceLabel)
    self.marker.iconView?.addSubview(likeBtn)
    self.marker.iconView?.isMultipleTouchEnabled = true

    setLogoViewMarkerConstraints(logoView: logoView)
    setAdressMarkerConstraints(label: adressLabel, logoView: logoView)
    setPriceMarkerConstraints(label: priceLabel, logoView: logoView)
    setLikeBtnMarkerConstraints(btn: likeBtn)
}

all looks good but uibutton doesn't clickable(likeBtn.addTarget doesn't work), if i implement this method

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {

    return false
}

i don't understand how i understand that i click on correct button(there will be more buttons)


问:
Alert Box is not closing
I have list of text boxes which contains Percentage values like 2.5% etc. There's one validation to check whether user has entered any special character or not. If so, alert box should pop up with proper alert message. But alert box is not closing whenever I am entering any invalid data. From Task Manager. I have to close IE. Any help will be appreciated.

JSP Code-

```<code><html:text property="manualValPctNum" name="manualValueInputPO"  styleId="manualValPctNum" size="25"  indexed="true" maxlength="25" onblur="javascript:formatValues('moduleForm', '${row.index}')" onfocus="javascript:removeValueFormat('moduleForm', '${row.index}')"/>
</code>```

JavaScript Code-

```<code>function formatValues(form, rowIndex){
    var beginElem = "manualValueInputPO[";
    var endElement = "]";
    var attributeName =beginElem+ rowIndex+endElement;
    formatPercentAmount(form,attributeName);
    value = "";
}

function formatPercentAmount(form, attributeName){
    var manualValueAmt = document.getElementsByName(attributeName+".manualValueAmt")[0];
    var manualValPctNum = document.getElementsByName(attributeName+".manualValPctNum")[0];
    var decimalForTabOut = document.getElementsByName(attributeName+".decimalForTabOut")[0];
    if(manualValPctNum.value != undefined && manualValPctNum.valu`enter code here`e != ''){
        if(isNaN(manualValPctNum.value)){
            alert("Enter numeric value only without entering any '$', comma, '( )', '%', or alphabets. Use '-' when entering a negative value.");
            value = "true";
            manualValPctNum.focus();
            manualValPctNumFlag = true;
            modifiedString = "";
            replacedChar = "";
        }else{
            var amt = manualValPctNum.value;
            amt = amt.toString();
            decimalForTabOut.value  = amt.indexOf('.');
            var indexPos = amt.indexOf('.');
            if(indexPos == -1){
                modifiedString = amt.concat("00");
                nonDecimalPoint = true;
            }else{
            var pctNumBeforeDecimal = amt.substring(0,indexPos);
            var pctNumAfterDecimal = amt.substring(indexPos + 1,amt.length);
            var modifiedIndexPos = indexPos + 2;
            var pctNum = pctNumBeforeDecimal.concat(pctNumAfterDecimal);
            for(var i = 0; i<pctNum.length; i++){
                if(i == modifiedIndexPos){
                    replacedChar = pctNum[i];
                    modifiedString = modifiedString.concat('.');
                    modifiedString = modifiedString.concat(replacedChar);
                }else{
                    if(modifiedString == undefined || modifiedString == ""){
                    modifiedString  = pctNum[i];
                }else{
                    modifiedString = modifiedString.concat(pctNum[i])
                }
            }
            }
            }
            manualValueAmt.value = modifiedString+"%";
            manualValPctNum.value = modifiedString+"%";
            modifiedString = "";
            replacedChar = "";
            manualValPctNumFlag = false;
        }
    }
}
</code>```

答:
please change onFocus event with onClick event,
with onFocus, it will call the function whenever you click on the free space on the browser</p>

Title: Alert Box is not closing

Body:
I have list of text boxes which contains Percentage values like 2.5% etc. There's one validation to check whether user has entered any special character or not. If so, alert box should pop up with proper alert message. But alert box is not closing whenever I am entering any invalid data. From Task Manager. I have to close IE. Any help will be appreciated.

JSP Code-

JavaScript Code-

function formatValues(form, rowIndex){
    var beginElem = "manualValueInputPO[";
    var endElement = "]";
    var attributeName =beginElem+ rowIndex+endElement;
    formatPercentAmount(form,attributeName);
    value = "";
}

function formatPercentAmount(form, attributeName){
    var manualValueAmt = document.getElementsByName(attributeName+".manualValueAmt")[0];
    var manualValPctNum = document.getElementsByName(attributeName+".manualValPctNum")[0];
    var decimalForTabOut = document.getElementsByName(attributeName+".decimalForTabOut")[0];
    if(manualValPctNum.value != undefined && manualValPctNum.valu`enter code here`e != ''){
        if(isNaN(manualValPctNum.value)){
            alert("Enter numeric value only without entering any '$', comma, '( )', '%', or alphabets. Use '-' when entering a negative value.");
            value = "true";
            manualValPctNum.focus();
            manualValPctNumFlag = true;
            modifiedString = "";
            replacedChar = "";
        }else{
            var amt = manualValPctNum.value;
            amt = amt.toString();
            decimalForTabOut.value  = amt.indexOf('.');
            var indexPos = amt.indexOf('.');
            if(indexPos == -1){
                modifiedString = amt.concat("00");
                nonDecimalPoint = true;
            }else{
            var pctNumBeforeDecimal = amt.substring(0,indexPos);
            var pctNumAfterDecimal = amt.substring(indexPos + 1,amt.length);
            var modifiedIndexPos = indexPos + 2;
            var pctNum = pctNumBeforeDecimal.concat(pctNumAfterDecimal);
            for(var i = 0; i<pctNum.length; i++){
                if(i == modifiedIndexPos){
                    replacedChar = pctNum[i];
                    modifiedString = modifiedString.concat('.');
                    modifiedString = modifiedString.concat(replacedChar);
                }else{
                    if(modifiedString == undefined || modifiedString == ""){
                    modifiedString  = pctNum[i];
                }else{
                    modifiedString = modifiedString.concat(pctNum[i])
                }
            }
            }
            }
            manualValueAmt.value = modifiedString+"%";
            manualValPctNum.value = modifiedString+"%";
            modifiedString = "";
            replacedChar = "";
            manualValPctNumFlag = false;
        }
    }
}


问:
Dataframe to text file in python
I am currently using this code:-

```<code>print(df.to_csv(r'tweets.txt', header=None, index=None, sep=' ', mode='a'))
</code>```

By this I am getting all the columns in the text file, but I only want a single column.Does anyone know how can I do it?
Thanks in advance

答:
just sub-select the col of interest:

```<code>print(df[col_of_interest].to_csv(r'tweets.txt', header=None, index=None, sep=' ', mode='a'))
</code>```

by doing df[col_of_interest] you only select that single column which will return a Series, if you want a dataframe use double square brackets:

```<code>print(df[[col_of_interest]].to_csv(r'tweets.txt', header=None, index=None, sep=' ', mode='a'))
</code>```

You can also pass a single list item to param columns:

```<code>print(df.to_csv(r'tweets.txt', header=None, index=None, sep=' ', mode='a', columns=['col_of_interest']))
</code>```

see the docs

Title: Dataframe to text file in python

Body:
I am currently using this code:-

print(df.to_csv(r'tweets.txt', header=None, index=None, sep=' ', mode='a'))

By this I am getting all the columns in the text file, but I only want a single column.Does anyone know how can I do it?
Thanks in advance

Body:
just sub-select the col of interest:

print(df[col_of_interest].to_csv(r'tweets.txt', header=None, index=None, sep=' ', mode='a'))

by doing df[col_of_interest] you only select that single column which will return a Series, if you want a dataframe use double square brackets:

print(df[[col_of_interest]].to_csv(r'tweets.txt', header=None, index=None, sep=' ', mode='a'))

You can also pass a single list item to param columns:

print(df.to_csv(r'tweets.txt', header=None, index=None, sep=' ', mode='a', columns=['col_of_interest']))

see the docs


问:
How can I fix this CrashlyticsMissingDependencyException?
I have been using the latest Crashlytics (Fabric integration) for a while. But recently I encountered the following crash error due to missing dependency although I didn't change anything about Crashlytics configurations.

any idea?

02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .     |  |
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .     |  |
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .     |  |
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .   \ |  | /
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .    \    /
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .     \  /
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .      \/
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ This app relies on Crashlytics. Please sign up for access at https://fabric.io/sign_up,
    install an Android build tool and ask a team member to invite you to this app's organization.
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .      /\
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .     /  \
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .    /    \
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .   / |  | \
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .     |  |
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .     |  |
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .     |  |
02-08 22:18:00.935  18887-18887/? E/Fabric﹕ .
02-08 22:18:00.935  18887-18887/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.android.staging, PID: 18887
    java.lang.RuntimeException: Unable to create application com.example.android.App: io.fabric.sdk.android.services.concurrency.UnmetDependencyException: com.crashlytics.android.CrashlyticsMissingDependencyException:
    This app relies on Crashlytics. Please sign up for access at https://fabric.io/sign_up,
    install an Android build tool and ask a team member to invite you to this app's organization.
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4734)
            at android.app.ActivityThread.access$1600(ActivityThread.java:171)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1357)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5506)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)
```

答:
The issue also occurs if you accidentally include the Crashlytics BuildConfig - very easy to do with Android Studio/IntelliJ auto-imports.

I'd imported

import com.crashlytics.android.core.BuildConfig;

Instead of my own

import <package_name>.BuildConfig;


问:
bitwise most significant set bit
I want to find the most significant bit that is set to 1. I have tried every possible way from & to ORing all of the bits from 1 to 31 and it doesn't work.

Like if 1000000 I would like to have 7.

答:
For Little Endian format:</p>

```<code>((yourByte & yourBitMask) >> msbIndex) && 0x01
</code>```

Title: bitwise most significant set bit

Body:
For Little Endian format:

((yourByte & yourBitMask) >> msbIndex) && 0x01


问:
Multiple forms with iput fields with the same name attribute
I have a form with multiple inputbox in it. And mutil clone with this form.

How can I insert all form into db with web py?

This is clone code:

```<code>function resetForm($$form) {
    $$form.find('input:text, input:password, input:file, select, textarea').val('');
    $$form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
}
var count = 0;
var $$clonedata = $$('.form_data').clone();
resetForm($$clonedata);
$$(document).on('click', '.Add', function(e) {
    e.preventDefault();
    count++;
    $$clonedata.clone().appendTo('#form_data').attr('id','form_data');
  });

$$('#form_data').on('click', '.Remove', function(e) {
    e.preventDefault();
    $$(this).closest('.form_data').remove();
});
</code>```

答:
Try this like,

$(function() {
  function resetForm($form) {
    $form.find('input:text, input:password, input:file, select, textarea').val('');
    $form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
  }
  var count = 0;
  var $clonedata = $('.form_data').clone();
  resetForm($clonedata);
  $('.Add').on('click', function(e) {
    e.preventDefault();
    count++;
    $clonedata.clone().appendTo('#form_data').attr('id', 'form_data');
  });

  $('#form_data').on('click', '.Remove', function(e) {
    e.preventDefault();
    $(this).closest('.form_data').remove();
  });

  $('.Save').on('click', function(e) {
    e.preventDefault();
    console.log($('form').serialize());
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Add
<div id="form_data">
  <div class="form_data" style="margin:5px"> <input type="text" name="name1[]" value="" /> <input type="text" name="name2[]" value="" /> <button class="Remove">Remove</button>
</div>
</div>
Save

</form></code>```

Body:
I have a form with multiple inputbox in it. And mutil clone with this form.

How can I insert all form into db with web py?

This is clone code:

function resetForm($$form) {
    $$form.find('input:text, input:password, input:file, select, textarea').val('');
    $$form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
}
var count = 0;
var $$clonedata = $$('.form_data').clone();
resetForm($$clonedata);
$$(document).on('click', '.Add', function(e) {
    e.preventDefault();
    count++;
    $$clonedata.clone().appendTo('#form_data').attr('id','form_data');
  });

$$('#form_data').on('click', '.Remove', function(e) {
    e.preventDefault();
    $$(this).closest('.form_data').remove();
});

Body:
Try this like,

$(function() {
  function resetForm($form) {
    $form.find('input:text, input:password, input:file, select, textarea').val('');
    $form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
  }
  var count = 0;
  var $clonedata = $('.form_data').clone();
  resetForm($clonedata);
  $('.Add').on('click', function(e) {
    e.preventDefault();
    count++;
    $clonedata.clone().appendTo('#form_data').attr('id', 'form_data');
  });

  $('#form_data').on('click', '.Remove', function(e) {
    e.preventDefault();
    $(this).closest('.form_data').remove();
  });

  $('.Save').on('click', function(e) {
    e.preventDefault();
    console.log($('form').serialize());
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<a class="Add" href="#">Add</a>
<div id="form_data">
  <div class="form_data" style="margin:5px"> <input type="text" name="name1[]" value="" /> <input type="text" name="name2[]" value="" /> <button class="Remove">Remove</button>
</div>
</div>
<a class="Save" href="#">Save</a>

</form>