问:
Selenium Webdriver runtime Exception: unexpected alert "Please close other open tabs of the application and re-open this activity"
Selenium Webdriver runtime Exception: unexpected alert "Please close other open tabs of the application and re-open this activity", even though there are no other tabs open.
The Automation scripts were working fine, but recently I am getting the above exception.The Screenshot of the Alert:

I tried with different versions of chrome, selenium stand alone driver, but the issue still exist. Why is this alert coming, even though the application is not open in any of the tabs or browsers other than the one execution through online?

答:
If this pop up is coming at some specific location every time then you can simply accept it by writing below lines :

```<code>WebDriver wb=new ChromeDriver();
wb.switchTo().alert().accept();
</code>```

Else if any unexpected pop up is coming ,while initializing the driver then you can use the below code :

```<code>ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_settings.popups", 0);
String path=new GetBasePath().getPath_XML()+dir;
prefs.put("download.default_directory", path);
options.addArguments("disable-extensions");
prefs.put("credentials_enable_service", false);
prefs.put("password_manager_enabled", false);
options.setExperimentalOption("prefs", prefs);

options.addArguments("chrome.switches","--disable-extensions");

options.addArguments("--test-type");
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, options);
cap.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);
System.setProperty("webdriver.chrome.driver",**path to chromedriver.exe**"));
WebDriver wb= new ChromeDriver(cap);
</code>```

My personal opinion , use both.

Body:
If this pop up is coming at some specific location every time then you can simply accept it by writing below lines :

WebDriver wb=new ChromeDriver();
wb.switchTo().alert().accept();

Else if any unexpected pop up is coming ,while initializing the driver then you can use the below code :

ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_settings.popups", 0);
String path=new GetBasePath().getPath_XML()+dir;
prefs.put("download.default_directory", path);
options.addArguments("disable-extensions");
prefs.put("credentials_enable_service", false);
prefs.put("password_manager_enabled", false);
options.setExperimentalOption("prefs", prefs);

options.addArguments("chrome.switches","--disable-extensions");

options.addArguments("--test-type");
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, options);
cap.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);
System.setProperty("webdriver.chrome.driver",**path to chromedriver.exe**"));
WebDriver wb= new ChromeDriver(cap);

My personal opinion , use both.


来源: stackexchange

问:
Auto switch between sentences
I would like my joomla site to automatically change which sentence it will echo to the user, so I wrote 3 different sentences:

```<code>$sentence1 = "Everything okay?";
$sentence2 = "Have a good day";
$sentence3 = "What are you doing today?";
</code>```

I would like it to switch between the sentences, so I'm aware I can't just put $sentence1 in the echo but I don't know how to write it then. I have the echo line like this:

```<code>echo "Hey {user->name}." . "<br />" . $sentence1
</code>```

By the way, the {user->name} is from Joomla's own "codes" so that worked fine :)

答:
random greetings:</p>

```<code>$sentence[1] = "Everything okay?";
$sentence[2] = "Have a good day";
$sentence[3] = "What are you doing today?";

echo "Hey {user->name}." . "<br />" . $sentence[rand(1,3)]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Auto switch between sentences

Body:
I would like my joomla site to automatically change which sentence it will echo to the user, so I wrote 3 different sentences:

$sentence1 = "Everything okay?";
$sentence2 = "Have a good day";
$sentence3 = "What are you doing today?";

I would like it to switch between the sentences, so I'm aware I can't just put $sentence1 in the echo but I don't know how to write it then. I have the echo line like this:

echo "Hey {user->name}." . "
" . $sentence1

By the way, the {user->name} is from Joomla's own "codes" so that worked fine :)

Body:
random greetings:

$sentence[1] = "Everything okay?";
$sentence[2] = "Have a good day";
$sentence[3] = "What are you doing today?";

echo "Hey {user->name}." . "<br />" . $sentence[rand(1,3)]


问:
peerDependencies and npm install
I would like to configure my own Angular seed which will be include Angular and Angular material. Problem is when I want run npm install from package.json which have :

```<code>"peerDependencies": {
    "angular": "@>=1.3 <1.6",
    "angular-animate": "^@>=1.3 <1.6",
    "angular-aria": "@>=1.3 <1.6",
    "angular-messages": "@>=1.3 <1.6"
},
"dependencies": {
},
</code>```

I get an error from console like pm WARN material-start@0.0.4 requires a peer of angular@@>=1.3 <1.6 but none was installed.

Where is the problem?

答:
I think you don't understand what peerDependencies mean.

Peer dependances aren't installed by npm itself. Npm just fires an error when you try to install this packgaje to environment which doesn't satisfy it's peerDependances.

I recommend you to use dependances in your package.json for angular and other packgajes required by material. So npm could install them automatically, before material installation.

Title: peerDependencies and npm install

Body:
I would like to configure my own Angular seed which will be include Angular and Angular material. Problem is when I want run npm install from package.json which have :

"peerDependencies": {
    "angular": "@>=1.3 <1.6",
    "angular-animate": "^@>=1.3 <1.6",
    "angular-aria": "@>=1.3 <1.6",
    "angular-messages": "@>=1.3 <1.6"
},
"dependencies": {
},

I get an error from console like pm WARN material-start@0.0.4 requires a peer of angular@@>=1.3 <1.6 but none was installed.

Where is the problem?


问:
CQRS + ES: Can you process multiple commands in parallel?
I can see how commands can be executed in a strict one at a time sequence with the CQRS + ES pattern. Having multiple commands executing in parallel would significantly increase the throughput of the system and make use of all the cores I have on the server. But surely this risks concurrency issues?

Take a simple example, two users update the customers name and submit the commands at the same time. In parallel two processes replay previous events to get aggregates into the latest state and then both determine everything is valid. Both then save a new update event. Whichever one saves last would seem to be the winner because any future replay would result in that last update being the customers name.

What if the result of the command is to send an email to the customer. Now we send two emails instead of the expected one. What if the command results in creating a new aggregate that gets attached to the customer using a customer property, we end up with two new aggregates created but one is a zombie because it is never referenced by the customer because the other aggregate has been saved as the reference instead.

It feels like you would need to implement your own transaction locking capability to ensure you never get overwrites and that is a complex solution I would rather avoid!

UPDATE:

My example was a little too simple. Imagine we have an Invoice and Item entries that go into an Invoice. After adding/changing/removing an Item from the Invoice we need to find the new total and set it into the Invoice.Total property field.

If in parallel two users both add a new Item then the total would be wrong with no explicit locking mechanism. Both recreate the Invoice aggregate and the existing list of Item child aggregates for that Invoice. In parallel both create a new Item and then add up the new total and set it to the Invoice.Total property.

Both then save events for these actions. But now we have an error because whichever command finished last will have a total that does not include the new item from the instance that finished first. This has nothing to do with pessimistic/optimistic concurrency but with transactional locking.

答:
If two commands are executed on different instances of the aggregate - the answer is trivial, of course you can. Each aggregate is a transactional boundary of its own.

If two commands are executed on the same instance, you have three options to
handle concurrency:

Optimistic concurrency - each command message holds the expected version of the aggregate (the one that was displayed to the user). If the expected version is different from the actual one, an exception is raised and the user is asked to refresh the view. This is the easiest solution.

Optimistic concurrency on steroids - Event Sourcing gives you the ability to raise concurrency error only if at least one of the events, that were appended to the aggregate after the expected version, actually conflicts with the command that was submitted by the user. This is best solution from the user interface perspective.

Pessimistic concurrency - Here you do lock the aggregate's instance to allow only one user to execute commands on it. In the vast majority of the cases - do go there. This is the most error prone solution, and usually the need for Pessimistic Concurrency is dictated by the business domain.


问:
creating HTML content on server side using templates
What is the possible solution of creating the HTML content on the server side from a template(.eex).</p>

答: It is possible and quite easy, Phoenix.View module provides a number of functions that do exactly that.


问:
How to read from JSON in protractor test?
I would like to read groups_id_ss for specific id.

How to do that in this json?

I successfully read response.docs , but then can't reach id and groups_id_ss.

```<code>{
 "responseHeader":{
      "status":0,
      "QTime":0,
      "params":{
         "q":"object_type_s:USER",
         "indent":"true",
         "wt":"json"
      }
   },
   "response":{
      "numFound":13,
      "start":0,
      "docs":[
         {
            "id":"sanja",
            "groups_id_ss":[
               "COORDINATION AO",
               "ACM_INVESTIGATOR_DEV"
            ]
         },
         {
            "id":"sanjaseconduser",
            "groups_id_ss":[
               "ACM_SUPERVISOR_DEV",
               "CHAIRMAN",
               "ACM_ADMINISTRATOR_DEV",
               "CPC INITIATOR",
               "COORDINATION AO",
               "ACM_INVESTIGATOR_DEV"
            ]
         }
      ]
   }
}
</code>```

答:
Since you are using the values in separate file, you can use like this.
I am assuming the file is stored as .json
For example, your json values are in response.json

You can write code like this in your spec file:

```<code>var responseData =  require('../../response.json');

describe('some function description', function(){
   var groupID = responseData.response.docs[0].groupid_ss[0];
   var groupID = responseData.response.docs[0].groupid_ss[0]

});
</code>```

Since that is json array, we have to give the index of the array in that.
Hope this would work for you.

Body:
I would like to read groups_id_ss for specific id.

How to do that in this json?

I successfully read response.docs , but then can't reach id and groups_id_ss.

{
 "responseHeader":{
      "status":0,
      "QTime":0,
      "params":{
         "q":"object_type_s:USER",
         "indent":"true",
         "wt":"json"
      }
   },
   "response":{
      "numFound":13,
      "start":0,
      "docs":[
         {
            "id":"sanja",
            "groups_id_ss":[
               "COORDINATION AO",
               "ACM_INVESTIGATOR_DEV"
            ]
         },
         {
            "id":"sanjaseconduser",
            "groups_id_ss":[
               "ACM_SUPERVISOR_DEV",
               "CHAIRMAN",
               "ACM_ADMINISTRATOR_DEV",
               "CPC INITIATOR",
               "COORDINATION AO",
               "ACM_INVESTIGATOR_DEV"
            ]
         }
      ]
   }
}

Body:
Since you are using the values in separate file, you can use like this.
I am assuming the file is stored as .json
For example, your json values are in response.json

You can write code like this in your spec file:

var responseData =  require('../../response.json');

describe('some function description', function(){
   var groupID = responseData.response.docs[0].groupid_ss[0];
   var groupID = responseData.response.docs[0].groupid_ss[0]

});

Since that is json array, we have to give the index of the array in that.
Hope this would work for you.


问:
Unity Debug log not showing in iOS build
guys I've been struggling with the following issue for couple of days and hope that somebody could help me.

I want to get my app logs from running iOS device. If I run the app from the Xcode, then I see my logs in debug view as expected.

However, when I download a build from my testflight app I'm not able to access the logs anymore. Google suggest that I use Xcode -> Devices -> Log of a device, but there are only system events log and no messages from my app.

Running Unity 5.5.2.p2, Xcode 8.2.1. with ios 10 and 9 tested.

Would appreciate any help, because this issue is really exhausting.

答:
Archiving for TestFlight means Build Configuration is release.

SO you won't be able to see the dubug log on testflight build.

Follow this link to make a debuggable TestFlight build.

Or simply add DEBUG=1 on Release section under Preprocessor Macros


问:
is there any way to pass the values betwn the htmls without using any other language
is there any way to pass and get the values betwn the htmls without using any other language like js, jsp, php and others , only html.</p>

答:
simple answer NO

HTML is a markup language is only to create a view
nothing else

ContentLicense: CC BY-SA 2.5


问:
Passing context from one view to the other
I am attempting to pass a URL parameter to another view within my app. I currently have a function (EntryListView) that identifies what month you select, and then only shows the contents for that month. However, I would like the month to also be shown in the detail URL. This will enable a "go-back" button to navigate back to the month's page, as opposed to erroring out or navigating back to the landing page.

urls.py As Is:

```<code>url(r'entry/list/(?P<month>\w+)$', views.EntryListView.as_view(), name='entry-list'),

url(r'entry/detail/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
</code>```

views.py

```<code>class DetailView(generic.DetailView):
    model = Entry
    template_name = 'argent/detail.html'

class EntryListView(generic.ListView):
    template_name = 'argent/index_list.html'
    queryset = Entry.objects.all()

    def get_context_data(self, **kwargs):
        month = self.kwargs.get('month')
        ctx = super(EntryListView, self).get_context_data(**kwargs)

        # January
        if month == 'January':
            ctx['January17_qs'] = Entry.objects.filter(date__range=('2017-1-1', '2017-1-31'))

        # February17
        elif month == 'February':
        ctx['February17_qs'] = Entry.objects.filter(date__range=('2017-2-1', '2017-2-28'))

        # March
        elif month == 'March':
        ctx['March17_qs'] = Entry.objects.filter(date__range=('2017-3-1', '2017-3-31'))

        return ctx
</code>```

template

```<code><a href="{% url 'argent:entry-list' %}">
                        <button type="button" class="btn btn-primary">Go Back
                    </button>
            </a>
</code>```

I currently get this error when using {% url 'argent:entry-list' %}:

Reverse for 'entry-list' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['tracker/entry/list/(?P<month>\\w+)$']

Thanks in advance for your help!

答:
You can pass the details's month to the url template tag as kwarg. Something like this should work.

```<code>class DetailView(generic.DetailView):
    model = Entry
    template_name = 'argent/detail.html'

    def get_context_data(self, **kwargs):
        ctx = super(DetailView, self).get_context_data(**kwargs)
        ctx['current_month'] = self.get_object().date.strftime("%B")
        return ctx
</code>```

template.html

```<code><a href="{% url 'argent:entry-list' current_month %}">
     <button type="button" class="btn btn-primary">Go Back</button>
</a>
</code>```

Body:
I am attempting to pass a URL parameter to another view within my app. I currently have a function (EntryListView) that identifies what month you select, and then only shows the contents for that month. However, I would like the month to also be shown in the detail URL. This will enable a "go-back" button to navigate back to the month's page, as opposed to erroring out or navigating back to the landing page.

urls.py As Is:

url(r'entry/list/(?P<month>\w+)$', views.EntryListView.as_view(), name='entry-list'),

url(r'entry/detail/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),

views.py

class DetailView(generic.DetailView):
    model = Entry
    template_name = 'argent/detail.html'

class EntryListView(generic.ListView):
    template_name = 'argent/index_list.html'
    queryset = Entry.objects.all()

    def get_context_data(self, **kwargs):
        month = self.kwargs.get('month')
        ctx = super(EntryListView, self).get_context_data(**kwargs)

        # January
        if month == 'January':
            ctx['January17_qs'] = Entry.objects.filter(date__range=('2017-1-1', '2017-1-31'))

        # February17
        elif month == 'February':
        ctx['February17_qs'] = Entry.objects.filter(date__range=('2017-2-1', '2017-2-28'))

        # March
        elif month == 'March':
        ctx['March17_qs'] = Entry.objects.filter(date__range=('2017-3-1', '2017-3-31'))

        return ctx

template

                        <button type="button" class="btn btn-primary">Go Back
                    </button>

I currently get this error when using {% url 'argent:entry-list' %}:

Reverse for 'entry-list' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['tracker/entry/list/(?P<month>\\w+)$']

Thanks in advance for your help!

Body:
You can pass the details's month to the url template tag as kwarg. Something like this should work.

class DetailView(generic.DetailView):
    model = Entry
    template_name = 'argent/detail.html'

    def get_context_data(self, **kwargs):
        ctx = super(DetailView, self).get_context_data(**kwargs)
        ctx['current_month'] = self.get_object().date.strftime("%B")
        return ctx

template.html

<a href="{% url 'argent:entry-list' current_month %}">
     <button type="button" class="btn btn-primary">Go Back</button>
</a>


问:
Class level locking - how efficient?
I am a bit confused here when we have to use class level locking for synchronization of static variables using synchronized(X.class).Here what I understand when a thread acquires a lock, no other thread will be able to access any other non-synchronized blocks as well which may incur a performance bottleneck. If there is a performance bottleneck what's the best way to deal with this problem.eg

```<code>class A {
    static int A = 0;

    public static synchorized func1() {
    }

    public synchorized func2() {
    }

    public synchorized func3() {
    }

    public synchorized func4() {
    }
}
</code>```

In this case if a thread accesses func1(), no other thread will be able to access even other functions like func2(),func3(),func4()-if I am correct.

答:
this is a question about class locking vs instance locking.

```<code> public static synchronized test(){

 }

 public synchronized test2(){

 }
</code>```

These two methods are equivalent to:

```<code> public static test(){
       synchronized(MyClass.class) {

       }
 }

 public static test2(){
       synchronized(this) {

       }
 }
</code>```

They lock on different locks and thus do not block each other.

Your assumption that if a Thread calls func1; no other Thread can call func2 and so-on is wrong, since they do use different locks.

On the other hand (considering we are talking about the same instance being called upon) if ThreadA calls func2, then another ThreadB can not call func3 until ThreadA is done. This does not mean that it will for sure get the lock next - since there might be other threads waiting for that lock - and which one gets it is not guaranteed.

Title: Class level locking - how efficient?

Body:
I am a bit confused here when we have to use class level locking for synchronization of static variables using synchronized(X.class).Here what I understand when a thread acquires a lock, no other thread will be able to access any other non-synchronized blocks as well which may incur a performance bottleneck. If there is a performance bottleneck what's the best way to deal with this problem.eg

class A {
    static int A = 0;

    public static synchorized func1() {
    }

    public synchorized func2() {
    }

    public synchorized func3() {
    }

    public synchorized func4() {
    }
}

In this case if a thread accesses func1(), no other thread will be able to access even other functions like func2(),func3(),func4()-if I am correct.

Body:
this is a question about class locking vs instance locking.

 public static synchronized test(){

 }

 public synchronized test2(){

 }

These two methods are equivalent to:

 public static test(){
       synchronized(MyClass.class) {

       }
 }

 public static test2(){
       synchronized(this) {

       }
 }

They lock on different locks and thus do not block each other.

Your assumption that if a Thread calls func1; no other Thread can call func2 and so-on is wrong, since they do use different locks.

On the other hand (considering we are talking about the same instance being called upon) if ThreadA calls func2, then another ThreadB can not call func3 until ThreadA is done. This does not mean that it will for sure get the lock next - since there might be other threads waiting for that lock - and which one gets it is not guaranteed.


问:
Python+ Raspi: change LED color based on # of button presses
I wrote the following code to change the color of an LED on my breadboard from blue to violet to red, and then flash. When the program is run, the LED turns on and stays blue the entire time, regardless of the button presses.

```<code>import RPi.GPIO as GPIO
import time

limit = 10
GPIO.setmode(GPIO.BOARD)
GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP)

Rpin = 11
Bpin = 13
flow = 0

try:
    while True:
        if GPIO.input(15) == False:
            flow += 1
            print flow
            time.sleep(0.1)
        if flow >= limit:
            False
        if flow < 6*limit//10:
            print("blue")
            GPIO.setup(Bpin, GPIO.OUT)
            GPIO.output(Bpin, GPIO.HIGH)

        elif flow in range(6*limit//10, 8*limit//10):
            print("violet")
            GPIO.setup(Rpin, GPIO.OUT)
            GPIO.output(Rpin, GPIO.HIGH)

        elif flow in range(8*limit//10, limit):
            print("red")
            GPIO.output(Bpin, GPIO.LOW)

        else:
            print("flashing red...")
            GPIO.output(Rpin, GPIO.LOW)
            time.sleep(.2)
            GPIO.output(Rpin, GPIO.HIGH)
            time.sleep(.2)
            GPIO.output(Rpin, GPIO.LOW)
            time.sleep(.2)
            GPIO.output(Rpin, GPIO.HIGH)
            time.sleep(.2)
            GPIO.output(Rpin, GPIO.LOW)
            break

except KeyboardInterrupt:
        GPIO.output(Rpin, GPIO.LOW)
        GPIO.output(Bpin, GPIO.LOW)
        GPIO.cleanup()
</code>```

I can make the LED work correctly with key presses, and can count the button presses and print that value, but the two do not work in conjunction. I'm fairly certain that this is not a wiring issue, as other code can make these parts work on their own. I have read related posts on Stack and other websites and haven't found any code similar to mine, where an increment changes the color of the LED. As a relatively new python user, I suspect there is a problem in the code. Any help is greatly appreciated!

```<code>import RPi.GPIO as GPIO
import time #added for sleep mode

GPIO.setmode(GPIO.BOARD)
GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP)

Rpin = 11
Bpin = 13
flow = 0

GPIO.setup(Bpin, GPIO.OUT)
GPIO.setup(Rpin, GPIO.OUT)

GPIO.output(Rpin, GPIO.LOW)
GPIO.output(Bpin, GPIO.LOW)

limit = int(raw_input("How many gallons of water would you like to use                    for your shower?  "))
print("You may begin showering")
print limit

def flowmeter(f, l):
    if f == 0:
        print("off")
        GPIO.output(Rpin, GPIO.LOW)
        GPIO.output(Bpin, GPIO.LOW)
        GPIO.cleanup()
    if f < 6*l//10:
        print("blue")
        GPIO.output(Bpin, GPIO.HIGH)
    elif f in range(6*l//10, 8*l//10):
        print("violet")
        GPIO.output(Rpin, GPIO.HIGH)
    elif f in range(8*l//10, l):
        print("red")
        GPIO.output(Bpin, GPIO.LOW)
    else:
        print("flashing red... time's up!")
        GPIO.output(Rpin, GPIO.LOW)
        time.sleep(.5)
        GPIO.output(Rpin, GPIO.HIGH)
        time.sleep(.5)
        GPIO.output(Rpin, GPIO.LOW)
        time.sleep(.5)
        GPIO.output(Rpin, GPIO.HIGH)
        time.sleep(.5)
        GPIO.output(Rpin, GPIO.LOW)
        print("cleaning GPIO")
        GPIO.output(Rpin, GPIO.LOW)
        GPIO.output(Bpin, GPIO.LOW)
        GPIO.cleanup()
while True:
    if GPIO.input(15) == False:
        flow += 1
        print("flow = %s" %flow)
        time.sleep(0.1) #prevents infinite pushes if held down for a few seconds
        flowmeter(flow,limit)
</code>```

答:
A debugging tip: if your code is never executing the code in an if statement, it's because the if test is always evaluating to false, and that's what you should investigate.

You need to read the python docs about the built-in range() function - it doesn't do what you are trying to do.

Instead of:

```<code>f in range(6*l//10, 8*l//10):
</code>```

use comparisons e.g.

```<code>f >= 6*l//10 and f < 8*l//10
</code>```

Body:
I wrote the following code to change the color of an LED on my breadboard from blue to violet to red, and then flash. When the program is run, the LED turns on and stays blue the entire time, regardless of the button presses.

import RPi.GPIO as GPIO
import time

limit = 10
GPIO.setmode(GPIO.BOARD)
GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP)

Rpin = 11
Bpin = 13
flow = 0

try:
    while True:
        if GPIO.input(15) == False:
            flow += 1
            print flow
            time.sleep(0.1)
        if flow >= limit:
            False
        if flow < 6*limit//10:
            print("blue")
            GPIO.setup(Bpin, GPIO.OUT)
            GPIO.output(Bpin, GPIO.HIGH)

        elif flow in range(6*limit//10, 8*limit//10):
            print("violet")
            GPIO.setup(Rpin, GPIO.OUT)
            GPIO.output(Rpin, GPIO.HIGH)

        elif flow in range(8*limit//10, limit):
            print("red")
            GPIO.output(Bpin, GPIO.LOW)

        else:
            print("flashing red...")
            GPIO.output(Rpin, GPIO.LOW)
            time.sleep(.2)
            GPIO.output(Rpin, GPIO.HIGH)
            time.sleep(.2)
            GPIO.output(Rpin, GPIO.LOW)
            time.sleep(.2)
            GPIO.output(Rpin, GPIO.HIGH)
            time.sleep(.2)
            GPIO.output(Rpin, GPIO.LOW)
            break

except KeyboardInterrupt:
        GPIO.output(Rpin, GPIO.LOW)
        GPIO.output(Bpin, GPIO.LOW)
        GPIO.cleanup()

I can make the LED work correctly with key presses, and can count the button presses and print that value, but the two do not work in conjunction. I'm fairly certain that this is not a wiring issue, as other code can make these parts work on their own. I have read related posts on Stack and other websites and haven't found any code similar to mine, where an increment changes the color of the LED. As a relatively new python user, I suspect there is a problem in the code. Any help is greatly appreciated!

import RPi.GPIO as GPIO
import time #added for sleep mode

GPIO.setmode(GPIO.BOARD)
GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP)

Rpin = 11
Bpin = 13
flow = 0

GPIO.setup(Bpin, GPIO.OUT)
GPIO.setup(Rpin, GPIO.OUT)

GPIO.output(Rpin, GPIO.LOW)
GPIO.output(Bpin, GPIO.LOW)

limit = int(raw_input("How many gallons of water would you like to use                    for your shower?  "))
print("You may begin showering")
print limit

def flowmeter(f, l):
    if f == 0:
        print("off")
        GPIO.output(Rpin, GPIO.LOW)
        GPIO.output(Bpin, GPIO.LOW)
        GPIO.cleanup()
    if f < 6*l//10:
        print("blue")
        GPIO.output(Bpin, GPIO.HIGH)
    elif f in range(6*l//10, 8*l//10):
        print("violet")
        GPIO.output(Rpin, GPIO.HIGH)
    elif f in range(8*l//10, l):
        print("red")
        GPIO.output(Bpin, GPIO.LOW)
    else:
        print("flashing red... time's up!")
        GPIO.output(Rpin, GPIO.LOW)
        time.sleep(.5)
        GPIO.output(Rpin, GPIO.HIGH)
        time.sleep(.5)
        GPIO.output(Rpin, GPIO.LOW)
        time.sleep(.5)
        GPIO.output(Rpin, GPIO.HIGH)
        time.sleep(.5)
        GPIO.output(Rpin, GPIO.LOW)
        print("cleaning GPIO")
        GPIO.output(Rpin, GPIO.LOW)
        GPIO.output(Bpin, GPIO.LOW)
        GPIO.cleanup()
while True:
    if GPIO.input(15) == False:
        flow += 1
        print("flow = %s" %flow)
        time.sleep(0.1) #prevents infinite pushes if held down for a few seconds
        flowmeter(flow,limit)

Body:
A debugging tip: if your code is never executing the code in an if statement, it's because the if test is always evaluating to false, and that's what you should investigate.

You need to read the python docs about the built-in range() function - it doesn't do what you are trying to do.

Instead of:

f in range(6*l//10, 8*l//10):

use comparisons e.g.

f >= 6*l//10 and f < 8*l//10


问:
Cropping Image view
i M passing a bitmap from one activity to other, after taking the screen shot </p>

```<code>                Bitmap bitmap;
                bitmap = takeScreenshot();
            try {
                //Write file
                String filename = "bitmap.png";
                FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

                //Cleanup
                stream.close();
                bitmap.recycle();

                //Pop intent
                Intent in1 = new Intent(this, FinalImageShare.class);
                in1.putExtra("image", filename);
                startActivity(in1);
            } catch (Exception e) {
                e.printStackTrace();
            }
</code>```

<p>here i am getting the image in other activity , the problem is that the tool bar height is also coming (i m hiding the toool bar by setVisibility, )i want to crop the image so that toolbar height wont come.TIA </p>

```<code>     imageView=(ImageView)findViewById(R.id.imageView);

    String filename = getIntent().getStringExtra("image");
    try {
        FileInputStream is = this.openFileInput(filename);
        bmp = BitmapFactory.decodeStream(is);

        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

答:
You can use createBitmap method, like so:

```<code>resizedbitmap = Bitmap.createBitmap(bitmap, 0, 0, yourwidth, yourheight);
</code>```

Where bitmap is the bitmap you create, and resizedbitmap is the cropped one.

createBitmap() method takes as parameter in this case: bitmap, start X, start Y, width and height.

You can use those two methods to get your width and height:

```<code>bitmap.getWidth(), bitmap.getHeight()
</code>```

Check also this link to learn about the createBitmap method:

Developer site

Or you can use the drawing cache property for this, like this :

```<code>View main = findViewById(R.id.view);
Bitmap screenshot;
main.setDrawingCacheEnabled(true);
screenshot = Bitmap.createBitmap(main.getDrawingCache());
main.setDrawingCacheEnabled(false);
</code>```

Or similar to the last one, ctx.getWindow().getDecorView() View to get full screen bitmap cache:

```<code>View view = ctx.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);

Bitmap bmap = view.getDrawingCache();

int contentViewTop = ctx.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); /* skip status bar in screenshot */
Storage.shareBitmapInfo = Bitmap.createBitmap(bmap, 0, contentViewTop, bmap.getWidth(), bmap.getHeight() - contentViewTop, null, true);

view.setDrawingCacheEnabled(false);
</code>```

Hope this helps!

Title: Cropping Image view

Body:
i M passing a bitmap from one activity to other, after taking the screen shot

                Bitmap bitmap;
                bitmap = takeScreenshot();
            try {
                //Write file
                String filename = "bitmap.png";
                FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

                //Cleanup
                stream.close();
                bitmap.recycle();

                //Pop intent
                Intent in1 = new Intent(this, FinalImageShare.class);
                in1.putExtra("image", filename);
                startActivity(in1);
            } catch (Exception e) {
                e.printStackTrace();
            }

here i am getting the image in other activity , the problem is that the tool bar height is also coming (i m hiding the toool bar by setVisibility, )i want to crop the image so that toolbar height wont come.TIA

     imageView=(ImageView)findViewById(R.id.imageView);

    String filename = getIntent().getStringExtra("image");
    try {
        FileInputStream is = this.openFileInput(filename);
        bmp = BitmapFactory.decodeStream(is);

        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

Body:
You can use createBitmap method, like so:

resizedbitmap = Bitmap.createBitmap(bitmap, 0, 0, yourwidth, yourheight);

Where bitmap is the bitmap you create, and resizedbitmap is the cropped one.

createBitmap() method takes as parameter in this case: bitmap, start X, start Y, width and height.

You can use those two methods to get your width and height:

bitmap.getWidth(), bitmap.getHeight()

Check also this link to learn about the createBitmap method:

Developer site

Or you can use the drawing cache property for this, like this :

View main = findViewById(R.id.view);
Bitmap screenshot;
main.setDrawingCacheEnabled(true);
screenshot = Bitmap.createBitmap(main.getDrawingCache());
main.setDrawingCacheEnabled(false);

Or similar to the last one, ctx.getWindow().getDecorView() View to get full screen bitmap cache:

View view = ctx.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);

Bitmap bmap = view.getDrawingCache();

int contentViewTop = ctx.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); /* skip status bar in screenshot */
Storage.shareBitmapInfo = Bitmap.createBitmap(bmap, 0, contentViewTop, bmap.getWidth(), bmap.getHeight() - contentViewTop, null, true);

view.setDrawingCacheEnabled(false);

Hope this helps!


问:
Count the exact number of children with jQuery
Im trying to find count the exact number of a child and then add a class to another element matching that class, in this example the parent (it wont be the direct parent where I'm trying to achieve this).

$(".test").each(function(index, elem) {
  var countchild = $(this).find(".child");
  if (countchild.length > 4) {
    $(".test").addClass("four")
  } else {}
});```
<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>
<div class="test">
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
</div></code>```

答:
To achieve this you could store the appropriate class names in an array. You can then access the right class by its index based on the number of found children, something like this:

var classArr = ['foo', 'bar', 'fizz', 'buzz'];

$(".test").each(function(index, elem) {
  $(this).addClass(classArr[$(this).find('.child').length - 1]);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bar { color: #0C0; }
.buzz { color: #C00; }</code>```

1

2

3

4

1

2

```

Body:
Im trying to find count the exact number of a child and then add a class to another element matching that class, in this example the parent (it wont be the direct parent where I'm trying to achieve this).

$(".test").each(function(index, elem) {
  var countchild = $(this).find(".child");
  if (countchild.length > 4) {
    $(".test").addClass("four")
  } else {}
});

1

2

3

4

Body:
To achieve this you could store the appropriate class names in an array. You can then access the right class by its index based on the number of found children, something like this:

var classArr = ['foo', 'bar', 'fizz', 'buzz'];

$(".test").each(function(index, elem) {
  $(this).addClass(classArr[$(this).find('.child').length - 1]);
});

.bar { color: #0C0; }
.buzz { color: #C00; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
</div>
<div class="test">
  <div class="child">1</div>
  <div class="child">2</div>
</div>


问:
Python: How to increment a special-purpose string?
Consider a special-purpose string of length 8, say "A00000XY". The string has following restrictions.

Length = 8.

Last two chars have special meaning and should remain as it is.

A-Z and 0-9 are only valid characters. Thus the regular expression "^[A-Z0-9]{6}XY$" defines the string.

How can I implement a function, say increment, that when called increments the string by one. Thus subsequent calls should look like following:

```<code>>>> A = "A00000XY"
>>> print increment(A)
"A00000XY"
>>> print increment(A)
"A00001XY"
>>> print increment(A)
"A00002XY"
...
>>> print increment(A)
"A00009XY"
>>> print increment(A)
"A0000AXY"
>>> print increment(A)
"A0000BXY"
...
>>> print increment(A)
"A0000YXY"
>>> print increment(A)
"A0000ZXY"
>>> print increment(A)
"A00010XY"
>>> print increment(A)
"A00011XY"
...
>>> print increment(A)
"ZZZZZZXY"
</code>```

答:
Inspired from @avysk response.

The @avysk reply has two issues.

Handling for ZZZZZZXY. It should wrap around and return 000000XY. It shouldn't overflow. However I missed covering this part in my question itself.

000000XY isn't handled properly to return 000001XY. It instead
returns 1XY.

Fixing these issue in following code that borrows most from @avysk's response.

```<code>digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def digit_helper(num):
  while num > 0:
    yield Tape.digits[num % 36]
    num = num / 36

# This function, using the utility digit_helper, increments the string by 1.
# It produces string in following order:
#     "A00000XY", "A00000XY", "A00001XY", "A00002XY", ...,
#     "A00009XY", "A0000AXY", "A0000BXY", ...,
#     "A0000YXY", "A0000ZXY", "A00010XY", "A00011XY", ...,
#     "ZZZZZZXY", "000000XY", "000001XY", ...
# Logic:
# 1. Strip the string of last two chars.
# 2. Convert to base 36 equivalent integer and increment by one.
# 3. Convert back to Base 36 representation of incremented value.
#   3.1. [0:6] handles the overflow. Overflow happens after "ZZZZZZXY" and produces "1000000XY".
#   3.2. [::-1] reverses the string.
#   3.3. zfill(6) handles underflow, like converting integer 1 to "000001XY".
def increment(string):
  incremented = int(string[:-2], base=36) + 1
  return "".join(Tape.digit_helper(incremented))[0:6][::-1].zfill(6) + string[-2:]
</code>```

Body:
Consider a special-purpose string of length 8, say "A00000XY". The string has following restrictions.

Length = 8.

Last two chars have special meaning and should remain as it is.

A-Z and 0-9 are only valid characters. Thus the regular expression "^[A-Z0-9]{6}XY$" defines the string.

How can I implement a function, say increment, that when called increments the string by one. Thus subsequent calls should look like following:

>>> A = "A00000XY"
>>> print increment(A)
"A00000XY"
>>> print increment(A)
"A00001XY"
>>> print increment(A)
"A00002XY"
...
>>> print increment(A)
"A00009XY"
>>> print increment(A)
"A0000AXY"
>>> print increment(A)
"A0000BXY"
...
>>> print increment(A)
"A0000YXY"
>>> print increment(A)
"A0000ZXY"
>>> print increment(A)
"A00010XY"
>>> print increment(A)
"A00011XY"
...
>>> print increment(A)
"ZZZZZZXY"

Body:
Inspired from @avysk response.

The @avysk reply has two issues.

Handling for ZZZZZZXY. It should wrap around and return 000000XY. It shouldn't overflow. However I missed covering this part in my question itself.

000000XY isn't handled properly to return 000001XY. It instead
returns 1XY.

Fixing these issue in following code that borrows most from @avysk's response.

digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def digit_helper(num):
  while num > 0:
    yield Tape.digits[num % 36]
    num = num / 36

# This function, using the utility digit_helper, increments the string by 1.
# It produces string in following order:
#     "A00000XY", "A00000XY", "A00001XY", "A00002XY", ...,
#     "A00009XY", "A0000AXY", "A0000BXY", ...,
#     "A0000YXY", "A0000ZXY", "A00010XY", "A00011XY", ...,
#     "ZZZZZZXY", "000000XY", "000001XY", ...
# Logic:
# 1. Strip the string of last two chars.
# 2. Convert to base 36 equivalent integer and increment by one.
# 3. Convert back to Base 36 representation of incremented value.
#   3.1. [0:6] handles the overflow. Overflow happens after "ZZZZZZXY" and produces "1000000XY".
#   3.2. [::-1] reverses the string.
#   3.3. zfill(6) handles underflow, like converting integer 1 to "000001XY".
def increment(string):
  incremented = int(string[:-2], base=36) + 1
  return "".join(Tape.digit_helper(incremented))[0:6][::-1].zfill(6) + string[-2:]


问:
Remove first character from list of names and rename
I have a list of users whose names start with the old naming convention which is first character and surname i.e ASmith, BJones, CGrayson etc and I need to remove the first character, so that I'm just left with surname, which I will then query AD with to extract first and lastname, however I was unable to rename the list. I tried this code, but can't see where I'm going wrong.</p>

```<code>$name = get-content c:\tempfiles\list.txt
foreach ($name in $names)
{
  $th = $name.substring(1);
  rename-item $name -newname $th
} | export-csv C:\TempFiles\New.csv
</code>```

答:
There's a typo in the first line of your code (you want the collection of names to go in to $names and then analyze each one in to the variable $name as part of your loop):

```<code>$names = get-content c:\tempfiles\list.txt
</code>```

However in order for ForEach to support the pipeline you need to use ForEach-Object instead so the next section should be:

```<code>$names | ForEach-Object {
  $th = $_.substring(1);
  write-output $th
} | Set-content c:\tempfiles\newfile.txt
</code>```

You also don't need to use Rename-Item, that's for renaming a file or other object retrieved via a namespace provider. Just output the new string with write-output and then use the pipeline to output it to a new text file.

If you want the result to go to a CSV file, and you want that file to also contain the old name, you could do something like this:

```<code>$names | ForEach-Object {

    $Properties = [ordered]@{
        'oldname' = $_
        'newname' = $_.substring(1)
    }

    New-Object -Property $Properties -TypeName PSCustomObject

} | export-csv New.csv -NoTypeInformation
</code>```

In this example we build a hashtable that has two properties (oldname and newname) and then create an object that has those properties which is then passed through the pipeline to export-csv.

Body:
I have a list of users whose names start with the old naming convention which is first character and surname i.e ASmith, BJones, CGrayson etc and I need to remove the first character, so that I'm just left with surname, which I will then query AD with to extract first and lastname, however I was unable to rename the list. I tried this code, but can't see where I'm going wrong.

$name = get-content c:\tempfiles\list.txt
foreach ($name in $names)
{
  $th = $name.substring(1);
  rename-item $name -newname $th
} | export-csv C:\TempFiles\New.csv

Body:
There's a typo in the first line of your code (you want the collection of names to go in to $names and then analyze each one in to the variable $name as part of your loop):

$names = get-content c:\tempfiles\list.txt

However in order for ForEach to support the pipeline you need to use ForEach-Object instead so the next section should be:

$names | ForEach-Object {
  $th = $_.substring(1);
  write-output $th
} | Set-content c:\tempfiles\newfile.txt

You also don't need to use Rename-Item, that's for renaming a file or other object retrieved via a namespace provider. Just output the new string with write-output and then use the pipeline to output it to a new text file.

If you want the result to go to a CSV file, and you want that file to also contain the old name, you could do something like this:

$names | ForEach-Object {

    $Properties = [ordered]@{
        'oldname' = $_
        'newname' = $_.substring(1)
    }

    New-Object -Property $Properties -TypeName PSCustomObject

} | export-csv New.csv -NoTypeInformation

In this example we build a hashtable that has two properties (oldname and newname) and then create an object that has those properties which is then passed through the pipeline to export-csv.


问:
Best practice boolean logic multiple not equal to
When writing a boolean statement with multiple 'not equal to' clauses I believe there are two potential syntaxes for achieving this, both of which are functionally equivalent. c# example:

1.

```<code>x != 1 && y != 1
</code>```

2.

```<code>!(x == 1 || y == 1)
</code>```

For the sake of being consistent and deciding on a best practice, are there any clear advantages/disadvantages to either?

Thanks

答:
There is no best practice for your question, your example is simple Boolean algebra task, changing logical conjunction with logical disjunction expression.
In real life, in application development especially in team projects, developers use predefined conventions, for example if expression can be modified, but it becomes hard readable, they use the syntax which is most suitable for real conditional expression, if condition sounds like "if not A and not B" they wrote !A && !B.
  On the other hand, if there is critical algorithm with sensibility to performance, you should remember about rule of logical expressions shortest execution way. For example, in мost progaramming languages, in your example the expression
!(x == 1 || y == 1) will always calculate operators x == 1 and y == 1, vs the x != 1 && y != 1 , there, if x != 1 satisfies the condition, then the y != 1 won't be calculated.

Body:
When writing a boolean statement with multiple 'not equal to' clauses I believe there are two potential syntaxes for achieving this, both of which are functionally equivalent. c# example:

1.

x != 1 && y != 1

2.

!(x == 1 || y == 1)

For the sake of being consistent and deciding on a best practice, are there any clear advantages/disadvantages to either?

Thanks


问:
for_in loop for nested object javascript don't return expected values
I am trying to walk through a JS object, with the for_in loop.
That seems to be returning the found value (contentCard1) as plain text.
I can't get it to print val.text

```<code>var contentCards = {
    contentCard1: {text: "text in here", date: "date in here"}
}

for(var val in contentCards) {
    console.log(val.text);
}
</code>```

Logging val.text gives me undefined, and logging just val gives me contentCard1.

Thanks for helping.

答:
Used this:</p>

```<code> var contentCards = {
            contentCard1: { text: "text in here", date: "date in here" }
        }

     alert(contentCards.contentCard1.text);
</code>```

Body:
I am trying to walk through a JS object, with the for_in loop.
That seems to be returning the found value (contentCard1) as plain text.
I can't get it to print val.text

var contentCards = {
    contentCard1: {text: "text in here", date: "date in here"}
}

for(var val in contentCards) {
    console.log(val.text);
}

Logging val.text gives me undefined, and logging just val gives me contentCard1.

Thanks for helping.

Body:
Used this:

 var contentCards = {
            contentCard1: { text: "text in here", date: "date in here" }
        }

     alert(contentCards.contentCard1.text);


问:
pjsip2 issue during build
I'm trying to use pjsip library for sip telephony in an android device for different architectures on a MAC.

I have downloaded 2.5.5 from http://svn.pjsip.org/repos/pjproject/tags/2.5.5 which is build fine for armabi architectures with the corresponding libpjsua2.so.

I'm trying to build it for other architectures as well but with no much lack on it. I have followed the instructions from https://trac.pjsip.org/repos/wiki/Getting-Started/Android but I have different errors.

For instance having TARGET_ABI=armeabi-v7a ./configure-android --use-ndk-cflags I was getting at the beginning:

/Users/*****/Library/Android/sdk/ndk-bundle/samples/hello-jni: No such file or directory.  Stop.
configure-android error: failed to run ndk-build, check ANDROID_NDK_ROOT env var

I downloaded the samples from github (as suggested in Android NDK) and now I get another error:

Users/iu/Library/Android/sdk/ndk-bundle/build/core/build-local.mk:151:
  *** Android NDK: Aborting    .  Stop. ./configure-android: line 72: test: argument expected configure-android error: compiler not found,
  please check environment settings (TARGET_ABI, etc)

Any suggestions?
Thanks

答:
Just in case somebody has a similar issue. The way I solved it is by building it on a linux machine as described in

https://github.com/VoiSmart/pjsip-android-builder

Title: pjsip2 issue during build


问:
Can't name column in SQL Server after merge
I cannot save my results from the below (in the form of a view) as the second column has no name and I cannot add a "as" name to it or it no longer works.

The statement below is merging like rows and concatenating the different values where there are multiple results, regarding the bank details.

```<code>select [Pers#No#],
        stuff(( Select distinct ', ' +
                        cast( [Bank Account] as varchar(20) ) +  ' ' +
                        cast( [Bank Keys] as varchar(20) )
                FROM     [DATA].[dbo].[PA0009]                  as      S
                where   S.[Pers#No#] = T.[Pers#No#]
                For     XML PATH('')),1,1,''    )
from    [DATA].[dbo].[PA0009]
group by [Pers#No#]
</code>```

答:
Just saw I needed to move my "As" to after the XML PATH.....
So I was putting it too early and not naming it after the real end of the column... Thanks guys. I can maybe even delete this post if it doesn't seem valuable for others... I completely missed that.</p>

```<code> select [Pers#No#],
  (
 stuff(( Select distinct ', ' + cast( [Bank Account] as varchar(20) ) +  ' '      + cast( [Bank Keys] as varchar(20) )

                        FROM [DATA].[dbo].[PA0009]          as      S

                     where          S.[Pers#No#] = T.[Pers#No#]

                     For            XML PATH('')),1,1,''    )     ) as           [Concatenate_Details]
 from [DATA].[dbo].[PA0009]       T
 group by [Pers#No#]
</code>```

Body:
I cannot save my results from the below (in the form of a view) as the second column has no name and I cannot add a "as" name to it or it no longer works.

The statement below is merging like rows and concatenating the different values where there are multiple results, regarding the bank details.

select [Pers#No#],
        stuff(( Select distinct ', ' +
                        cast( [Bank Account] as varchar(20) ) +  ' ' +
                        cast( [Bank Keys] as varchar(20) )
                FROM     [DATA].[dbo].[PA0009]                  as      S
                where   S.[Pers#No#] = T.[Pers#No#]
                For     XML PATH('')),1,1,''    )
from    [DATA].[dbo].[PA0009]
group by [Pers#No#]

Body:
Just saw I needed to move my "As" to after the XML PATH.....
So I was putting it too early and not naming it after the real end of the column... Thanks guys. I can maybe even delete this post if it doesn't seem valuable for others... I completely missed that.

 select [Pers#No#],
  (
 stuff(( Select distinct ', ' + cast( [Bank Account] as varchar(20) ) +  ' '      + cast( [Bank Keys] as varchar(20) )

                        FROM [DATA].[dbo].[PA0009]          as      S

                     where          S.[Pers#No#] = T.[Pers#No#]

                     For            XML PATH('')),1,1,''    )     ) as           [Concatenate_Details]
 from [DATA].[dbo].[PA0009]       T
 group by [Pers#No#]


问:
Webpage won't parse PHP code
I'm trying to add some of my own PHP to a nearly-unreadable template file on a forum system. I know it all works perfectly as far as the server config, etc. goes, but PHP simply doesn't parse on this page. JS works fine. Any ideas? It's a simple .html page.</p>

答:
Try adding this to your .htaccess (or creating a new one in the appropriate directory):</p>

```<code>AddType application/x-httpd-php .php .html
</code>```

Title: Webpage won't parse PHP code

Body:
Try adding this to your .htaccess (or creating a new one in the appropriate directory):

AddType application/x-httpd-php .php .html


问:
Finding a controversy parameter from aggregated votes
I made a survey where users could vote on a subject. They were allowed to either yay it (+1) , nay it (–1) or don't care (0).

I only have the aggregate results in Google Sheets like

```<code>            yay   nay   dontcare
Option A:    32    14     23
Option B:    12    37     20
Option C:    40    17     12
Option D:    64     3      2
</code>```

The number of votes are always the same on every option.

Now I need to find out how controversial the answers are. I thought about STDEVP, but I do not have a list of cells, just the aggregates.

How do I find the standard deviation here with Google Sheets?

答:
Assuming you ignore don't care's you can just take the prevalence of yay's and use sd=sqrt(p(1-p))

so if yay's are in column B, nays in C you use

```<code>=SQRT(B2/SUM(B2:C2) * (C2/SUM(B2:C2)))
</code>```

Note that this is the standard deviation for a population.

If you want to include them you can use calculate the mean in E2 with

```<code>=SUMPRODUCT(B2:D2, {1, -1, 0}) / SUM(B2:D2)
</code>```

Then you can calculate variance like this in F2

```<code>=SUMPRODUCT(ArrayFormula({1, -1, 0}-E2)^2, B2:D2) / (SUM(B2:D2)-1)
</code>```

which is just taking every 1, -1, or 0 reduces by the mean, squares this deviation it and takes the average -1 degree of freedom (for the sample, leave the -1 out if you assume you have the population).

The Standard deviation is

```<code>=SQRT(F2)
</code>```

Body:
I made a survey where users could vote on a subject. They were allowed to either yay it (+1) , nay it (–1) or don't care (0).

I only have the aggregate results in Google Sheets like

            yay   nay   dontcare
Option A:    32    14     23
Option B:    12    37     20
Option C:    40    17     12
Option D:    64     3      2

The number of votes are always the same on every option.

Now I need to find out how controversial the answers are. I thought about STDEVP, but I do not have a list of cells, just the aggregates.

How do I find the standard deviation here with Google Sheets?

Body:
Assuming you ignore don't care's you can just take the prevalence of yay's and use sd=sqrt(p(1-p))

so if yay's are in column B, nays in C you use

=SQRT(B2/SUM(B2:C2) * (C2/SUM(B2:C2)))

Note that this is the standard deviation for a population.

If you want to include them you can use calculate the mean in E2 with

=SUMPRODUCT(B2:D2, {1, -1, 0}) / SUM(B2:D2)

Then you can calculate variance like this in F2

=SUMPRODUCT(ArrayFormula({1, -1, 0}-E2)^2, B2:D2) / (SUM(B2:D2)-1)

which is just taking every 1, -1, or 0 reduces by the mean, squares this deviation it and takes the average -1 degree of freedom (for the sample, leave the -1 out if you assume you have the population).

The Standard deviation is

=SQRT(F2)


问:
Prototypal inheritance with nested objects
I'm trying to get my head around prototype inheritance in Javascript. I think I got the basic concept, but when I was playing around with this I ran into the following which still has me puzzled.

There is a very similar question and answer here but it doesn't fully answer why this is happening, at least not for me.

I create a new object like this:

```<code>var User = {
  username: "",
  name: {
    first: "",
    last: ""
  }
}
</code>```

Next I create two "instances" of that object:

```<code>var user1 = Object.create(User);
var user2 = Object.create(User);
</code>```

Now I set the name property like so:

```<code>user1.name = { first: "John", last: "Jackson"}
user2.name = { first: "James", last: "Jameson"}
</code>```

Now I do

alert(user1.name.first) \\ -> John
alert(user2.name.first) \\ -> James

All as expected. So far so good.

However, if I set the name.first property like this:

```<code>user1.name.first = "John";
user2.name.first = "James";
</code>```

and I get

```<code>alert(user1.name.first) \\ -> James
alert(user2.name.first) \\ -> James
</code>```

Clearly now the property is being set on the prototype object User (or rather the contained name object) instead of overriding it in the current object user1. Why does that occur?

Further if I do

```<code>user1.name.middle = "Mortimer"
</code>```

I can now do

```<code>alert(User.name.middle) // -> Mortimer
</code>```

which is not what I would expect. Generally, whenever a property is set on a derived object, that object either already has that property as an ownProperty in which case the value is simply assigned, or the property is newly created as an ownProperty on the derived object, overriding the prototype property. Just like happens when I assign to user1.name.

So why does assigning to an object contained in the prototype object cause such (at least to me) unexpected and counter-intuitive behavior?

The way I understand it, when the assignment is made the first check is to see if user1 has an ownProperty called name, which it doesn't. If this were a read operation the prototype property would now be looked up and User checked to see if it has ownProperty name. But since this is a set operation why walk the prototype chain when usually a missing ownProperty is simply created?

答:
But since this is a set operation why walk the prototype chain when usually a missing ownProperty is simply created?

When you say user1.name.first = "John", the user1.name part has to be resolved before the .first property can be retrieved or set. And in your example the user1.name part only exists on the prototype object, so it is that object whose .first property you are setting.

Similarly, when you say user1.name.middle = "Mortimer", again the user1.name part resolves to the nested object from the prototype, so then you create a .middle property on that object, which is why User.name.middle also returns "Mortimer".

If you said user1.name.first and user1.name could not be resolved (on the current object or in its prototype chain) then you'd have a TypeError: Cannot set property 'first' of undefined. (You can try that concept with your existing code by saying user1.address.street = "something" - you'd get the TypeError, because user1.address doesn't exist on user1 or its prototype chain.)

Body:
I'm trying to get my head around prototype inheritance in Javascript. I think I got the basic concept, but when I was playing around with this I ran into the following which still has me puzzled.

There is a very similar question and answer here but it doesn't fully answer why this is happening, at least not for me.

I create a new object like this:

var User = {
  username: "",
  name: {
    first: "",
    last: ""
  }
}

Next I create two "instances" of that object:

var user1 = Object.create(User);
var user2 = Object.create(User);

Now I set the name property like so:

user1.name = { first: "John", last: "Jackson"}
user2.name = { first: "James", last: "Jameson"}

Now I do

alert(user1.name.first) \\ -> John
alert(user2.name.first) \\ -> James

All as expected. So far so good.

However, if I set the name.first property like this:

user1.name.first = "John";
user2.name.first = "James";

and I get

alert(user1.name.first) \\ -> James
alert(user2.name.first) \\ -> James

Clearly now the property is being set on the prototype object User (or rather the contained name object) instead of overriding it in the current object user1. Why does that occur?

Further if I do

user1.name.middle = "Mortimer"

I can now do

alert(User.name.middle) // -> Mortimer

which is not what I would expect. Generally, whenever a property is set on a derived object, that object either already has that property as an ownProperty in which case the value is simply assigned, or the property is newly created as an ownProperty on the derived object, overriding the prototype property. Just like happens when I assign to user1.name.

So why does assigning to an object contained in the prototype object cause such (at least to me) unexpected and counter-intuitive behavior?

The way I understand it, when the assignment is made the first check is to see if user1 has an ownProperty called name, which it doesn't. If this were a read operation the prototype property would now be looked up and User checked to see if it has ownProperty name. But since this is a set operation why walk the prototype chain when usually a missing ownProperty is simply created?


问:
sql split and replace string in table
I have data in table as below and trying to use Replace to do it, but I am ending up with either double semicolon ';;; or semicolon at end after using replace. Can I use split and replace to achieve this or any other ways??

```<code>    Test attempts;My attempts using operation;Additions, deletions, and modifications
    Test attempts;My attempts using operation
    Test attempts;access to information;attempts using nex;Additions, deletions, and modifications
    Test attempts;Changes to programs
</code>```

Replace 'My attempts using operation' with emptystring AND
    Replace 'attempts using nex' with 'attempts using imex' in above data column

```<code>    Result should be:

    Test attempts;Additions, deletions, and modifications
    Test attempts-- No semicolon should be there if it ends up at end with that after replace
    Test attempts;access to information;attempts using imex;Additions, deletions, and modifications

Test attempts;Changes to programs
</code>```

答:
Hope this helps. As per your request, the string will be split on the ; and reconstructed without the excluded string

```<code>DECLARE @RemoveString VARCHAR(8000) = 'My attempts using operation'

;WITH cte_TestData (StringValue)
AS (
    SELECT 'Test attempts;My attempts using operation;Additions, deletions, and modifications '
    UNION ALL
    SELECT 'Test attempts;My attempts using operation'
    UNION ALL
    SELECT 'Test attempts;access to information;attempts using nex;Additions, deletions, and modifications'
    UNION ALL
    SELECT 'Test attempts;Changes to programs'
    UNION ALL
    SELECT 'Test attempts'
    ),
cte_Sequencer
AS (
    SELECT ROW_NUMBER() OVER (
            ORDER BY (
                    SELECT NULL
                    )
            ) AS Id,
        StringValue
    FROM cte_TestData
    ),
cte_XMLBuilder
AS (
    SELECT Id,
        StringValue,
        CAST('<M>' + REPLACE(StringValue, ';', '</M><M>') + '</M>' AS XML) AS XMLData
    FROM cte_Sequencer
    ),
StringSplitter
AS (
    SELECT C1.Id,
        ROW_NUMBER() OVER (
            PARTITION BY C1.Id ORDER BY (
                    SELECT NULL
                    )
            ) AS SeqId,
        C2.StringValue,
        SPLITS.ABC.value('.', 'varchar(MAX)') AS Data
    FROM cte_XMLBuilder C2
    INNER JOIN cte_XMLBuilder C1
        ON C2.StringValue = C1.StringValue
    CROSS APPLY C1.XMLData.nodes('/M') AS SPLITS(ABC)
    )
SELECT DISTINCT ID,
    StringValue,
    STUFF((
            SELECT ';' + b.Data AS [text()]
            FROM StringSplitter b
            WHERE b.Id = a.Id
                AND Data != @RemoveString
            ORDER BY id,
                SeqId
            FOR XML PATH('')
            ), 1, 1, '') AS EditedString
FROM StringSplitter a
</code>```

Title: sql split and replace string in table

Body:
I have data in table as below and trying to use Replace to do it, but I am ending up with either double semicolon ';;; or semicolon at end after using replace. Can I use split and replace to achieve this or any other ways??

    Test attempts;My attempts using operation;Additions, deletions, and modifications
    Test attempts;My attempts using operation
    Test attempts;access to information;attempts using nex;Additions, deletions, and modifications
    Test attempts;Changes to programs

Replace 'My attempts using operation' with emptystring AND
    Replace 'attempts using nex' with 'attempts using imex' in above data column

    Result should be:

    Test attempts;Additions, deletions, and modifications
    Test attempts-- No semicolon should be there if it ends up at end with that after replace
    Test attempts;access to information;attempts using imex;Additions, deletions, and modifications

Test attempts;Changes to programs

Body:
Hope this helps. As per your request, the string will be split on the ; and reconstructed without the excluded string

DECLARE @RemoveString VARCHAR(8000) = 'My attempts using operation'

;WITH cte_TestData (StringValue)
AS (
    SELECT 'Test attempts;My attempts using operation;Additions, deletions, and modifications '
    UNION ALL
    SELECT 'Test attempts;My attempts using operation'
    UNION ALL
    SELECT 'Test attempts;access to information;attempts using nex;Additions, deletions, and modifications'
    UNION ALL
    SELECT 'Test attempts;Changes to programs'
    UNION ALL
    SELECT 'Test attempts'
    ),
cte_Sequencer
AS (
    SELECT ROW_NUMBER() OVER (
            ORDER BY (
                    SELECT NULL
                    )
            ) AS Id,
        StringValue
    FROM cte_TestData
    ),
cte_XMLBuilder
AS (
    SELECT Id,
        StringValue,
        CAST('<M>' + REPLACE(StringValue, ';', '</M><M>') + '</M>' AS XML) AS XMLData
    FROM cte_Sequencer
    ),
StringSplitter
AS (
    SELECT C1.Id,
        ROW_NUMBER() OVER (
            PARTITION BY C1.Id ORDER BY (
                    SELECT NULL
                    )
            ) AS SeqId,
        C2.StringValue,
        SPLITS.ABC.value('.', 'varchar(MAX)') AS Data
    FROM cte_XMLBuilder C2
    INNER JOIN cte_XMLBuilder C1
        ON C2.StringValue = C1.StringValue
    CROSS APPLY C1.XMLData.nodes('/M') AS SPLITS(ABC)
    )
SELECT DISTINCT ID,
    StringValue,
    STUFF((
            SELECT ';' + b.Data AS [text()]
            FROM StringSplitter b
            WHERE b.Id = a.Id
                AND Data != @RemoveString
            ORDER BY id,
                SeqId
            FOR XML PATH('')
            ), 1, 1, '') AS EditedString
FROM StringSplitter a


问:
Visual Studio 2015 “non-standard syntax; use '&' to create pointer for member”
While creating thread using CreateThread() in Win32 Application , I am getting this error .
In CreateThread(NULL,0,pSample->Resize(),NULL,0,NULL);  It shows error in function calling .

I do have several files as :

Main.cpp

```<code>WinMain()
 {
   //Create sample
    return Win32Appliaction::Run(&sample);
  }
</code>```

Win32Application.cpp

```<code>int Win32Application::Run(DXSample* pSample)
  {
     //Create Window
     pSample->Init();
     pSample->Render();
     CreateThread(NULL,0,pSample->Resize,NULL,0,NULL);//error occurs
     pSample->Destroy();
  }
</code>```

DXSample.h

```<code>class DXSample
   {
     public:
           virtual void Init() =0; //and rest all functions
   };
</code>```

HelloTexture.h

```<code> class HelloTexture:public DXSample
   {
       public :
             virtual void Init();//all other functions similarly
    }
</code>```

HelloTexture.cpp

```<code>void Hellotexture::Init()
 { //code
  }
 void Hellotexture::Resize()
 {
    //code
  }
</code>```

答: Parameter #2 of the CreateThread must be a pointer to function matching ThreadProc signature. You can not pass result of pSample->Resize() (which is void) or a pointer to Resize function itself (because this is a non-static class member function). Also you may want to use ::std::thread instead of calling WinApi directly.</p>

Body:
While creating thread using CreateThread() in Win32 Application , I am getting this error .
In CreateThread(NULL,0,pSample->Resize(),NULL,0,NULL);  It shows error in function calling .

I do have several files as :

Main.cpp

WinMain()
 {
   //Create sample
    return Win32Appliaction::Run(&sample);
  }

Win32Application.cpp

int Win32Application::Run(DXSample* pSample)
  {
     //Create Window
     pSample->Init();
     pSample->Render();
     CreateThread(NULL,0,pSample->Resize,NULL,0,NULL);//error occurs
     pSample->Destroy();
  }

DXSample.h

class DXSample
   {
     public:
           virtual void Init() =0; //and rest all functions
   };

HelloTexture.h

 class HelloTexture:public DXSample
   {
       public :
             virtual void Init();//all other functions similarly
    }

HelloTexture.cpp

void Hellotexture::Init()
 { //code
  }
 void Hellotexture::Resize()
 {
    //code
  }


问:
How to sanitize data received from WYSIWYG Editor?
I have a typical WYSIWYG editor for a blog, which has the ability to embed youtube videos and videos from some other commonly known sources. the editor is JavaScript based. And it adds too much of html tags and java-script in the content that I receive. As i have to store this data received from the editor in my MySQL database. I want to sanitize it. What is the best way to sanitize this data and make it safe to store in the database and further deal with it?</p>

答:
Do not try to re-invent the wheel.
An adequate class to achieve this is htmlpurifier</p>


问:
Did Facebook change their App developers API on March 2017?
Well, I am a new guy who is trying to develop a web application whose user are will be authenticated through Facebook.  I am developing the application in MVC 4 .Net Framework. As it's internal programs are already done so I need not to do much coding. I have just put the API ID and Secret Key in the scope

```<code>OAuthWebSecurity.RegisterFacebookClient(
                appId: "750397051803327",
                appSecret: "**************************");
</code>```

And here is my Application http://imgur.com/a/k4Vd0
My Application is taking properly the user permission from the user perfectly. http://imgur.com/a/bqzj5 but after taking permission it is not providing the login state of the user by showing such exception http://imgur.com/a/h81Oh login failed. I debugged form the code end and I observed that it is sending isLoggedin as false http://imgur.com/a/UuLIe therefore my I am not getting the access.

However 2 days before I am not getting such exception. I was getting data simply fine. Here is a snapshot of my previous data. http://imgur.com/a/Bc49F

I need that data again, but how? Is there anything need to change in my application dashboard? Possibly I have changed something in application dashboard. if yes then what is particularly that?
Another things I'm confused that what is the need for PRODUCTS? Do I need anything from the products for this special reason to get the data. If yes then which one shall I need and how to configure it to get back my previous systematic process in which I was getting data smoothly.

If I add App Center from the PRODUCTS I am obtaining two other secret keys like Account Kit App Secret and Account Kit Client Token Is that I need to use these keys for my requested case. For such login approval specific which Products are need or nothing need at all from PRODUCTS. I am so confused about it how to configure an application.

Please suggest me how to solve this problem in addition how to configure my application API. Thank you.

答:
Yes!!!!
I got the solution of my own problem. According to Facebook developers bug report all Facebook log is not working from 28th March 2017. They also let us know through their developers Facebook group. The post link is here.

According to one of the Developer teams had said  we're finding that
  facebook authentication just stopped working (2pm EST) across multiple
  apps that we manage. apps haven't changed, apps haven't been
  suspended..... not sure where to report this since "status" is all
  good......

Body:
Well, I am a new guy who is trying to develop a web application whose user are will be authenticated through Facebook.  I am developing the application in MVC 4 .Net Framework. As it's internal programs are already done so I need not to do much coding. I have just put the API ID and Secret Key in the scope

OAuthWebSecurity.RegisterFacebookClient(
                appId: "750397051803327",
                appSecret: "**************************");

And here is my Application http://imgur.com/a/k4Vd0
My Application is taking properly the user permission from the user perfectly. http://imgur.com/a/bqzj5 but after taking permission it is not providing the login state of the user by showing such exception http://imgur.com/a/h81Oh login failed. I debugged form the code end and I observed that it is sending isLoggedin as false http://imgur.com/a/UuLIe therefore my I am not getting the access.

However 2 days before I am not getting such exception. I was getting data simply fine. Here is a snapshot of my previous data. http://imgur.com/a/Bc49F

I need that data again, but how? Is there anything need to change in my application dashboard? Possibly I have changed something in application dashboard. if yes then what is particularly that?
Another things I'm confused that what is the need for PRODUCTS? Do I need anything from the products for this special reason to get the data. If yes then which one shall I need and how to configure it to get back my previous systematic process in which I was getting data smoothly.

If I add App Center from the PRODUCTS I am obtaining two other secret keys like Account Kit App Secret and Account Kit Client Token Is that I need to use these keys for my requested case. For such login approval specific which Products are need or nothing need at all from PRODUCTS. I am so confused about it how to configure an application.

Please suggest me how to solve this problem in addition how to configure my application API. Thank you.


问:
Javascript - Change event trigger multiple times
I have the following table.

```<code><table class="table invoice-items-table">
    <thead>
        <tr>
            <th>Item</th>
            <th>Quantity</th>
            <th>Price</th>
            <th>Amount</th>
        </tr>
    </thead>
    <tbody>
        <tr class="invoice-item-row">
            <td>
                <select class="selectpicker invoice-item-select" title="Select an Item">
                    <option value="1">PHP Development</option>
                </select>
            </td>
            <td class="text-right">
                <input class="form-control invoice-item-quantity" value="1" type="text">
            </td>
            <td class="text-right">
                <input class="form-control invoice-item-price" value="0.00" type="text">
            </td>
            <td class="text-right" style="padding-top:18px!important;">
                <span class="invoice-item-amount">0 </span>
                <span class="invoice-currency">₹</span>
            </td>
        </tr>
        <tr class="invoice-item-add-row">
            <td colspan="7">
                <a href="#" class="link invoice-item-add text-center">
                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
                    Add an Item
                </a>
            </td>
        </tr>
    </tbody>
</table>
</code>```

For on-click event of a.invoice-item-add I append more table rows tr to the table, here is the code for that.

```<code>$('.invoice-item-add').on('click', function() {
    var itemRowClone = $('.invoice-item-row').last().clone();
    itemRowClone.find('input, textarea').val('');
    itemRowClone.find('.bootstrap-select').replaceWith(function() { return $('select', this); });
    itemRowClone.find('.selectpicker').selectpicker();
    $('.invoice-item-add-row').before(itemRowClone);
    return false;
});
</code>```

This works perfectly fine, until I want to trigger select.invoice-item-select, here is how I trigger it.

```<code>$(document).on('change', '.invoice-item-select', function() {
    // Code here...
});
</code>```

my problem is, this on-change gets fired multiple times based on the number of elements added dynamically, if there is one tr.invoice-item-row it gets fired twice, if there are two tr.invoice-item-row it gets fired four times, basically it fires times two.

I understand that the tr.invoice-item-row are added dynamically and we are using $(document).on('change', '.invoice-item-select', function()... to listen to the trigger.

How do I make sure this on-change event is fired only once?

Thanks.

答:
$(document).on('change') event should called once on page load. No need to add document change on row add.

OR

You can first unbind event then bind again like

```<code>$(document).off('change','.invoice-item-select').on('change', '.invoice-item-select', function() {
    // Code here...
});
</code>```

Body:
I have the following table.

            Item
            Quantity
            Price
            Amount

                <select class="selectpicker invoice-item-select" title="Select an Item">
                    <option value="1">PHP Development</option>
                </select>

                <input class="form-control invoice-item-quantity" value="1" type="text">

                <input class="form-control invoice-item-price" value="0.00" type="text">

                0
                ₹

                    Add an Item

For on-click event of a.invoice-item-add I append more table rows tr to the table, here is the code for that.

$('.invoice-item-add').on('click', function() {
    var itemRowClone = $('.invoice-item-row').last().clone();
    itemRowClone.find('input, textarea').val('');
    itemRowClone.find('.bootstrap-select').replaceWith(function() { return $('select', this); });
    itemRowClone.find('.selectpicker').selectpicker();
    $('.invoice-item-add-row').before(itemRowClone);
    return false;
});

This works perfectly fine, until I want to trigger select.invoice-item-select, here is how I trigger it.

$(document).on('change', '.invoice-item-select', function() {
    // Code here...
});

my problem is, this on-change gets fired multiple times based on the number of elements added dynamically, if there is one tr.invoice-item-row it gets fired twice, if there are two tr.invoice-item-row it gets fired four times, basically it fires times two.

I understand that the tr.invoice-item-row are added dynamically and we are using $(document).on('change', '.invoice-item-select', function()... to listen to the trigger.

How do I make sure this on-change event is fired only once?

Thanks.

Body:
$(document).on('change') event should called once on page load. No need to add document change on row add.

OR

You can first unbind event then bind again like

$(document).off('change','.invoice-item-select').on('change', '.invoice-item-select', function() {
    // Code here...
});


问:
Put html table data in google spreadsheet
Hey guy's I am trying to send table information to google spreadsheet.

I have tried:

This worked (but i need table data instead of input)

Is there a way to fix it without using google-script.
just pure javascript ?

```<code><table>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>John</td>
    <td>Wick</td>
    <td>33</td>
  </tr>
  <tr>
    <td>Jeff</td>
    <td>AndersOn</td>
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>33</td>
  </tr>
</table>

    <button type="submit" onclick="test()" >Verzenden</button>
</code>```

答:
Try using Sheets API:

The Google Sheets API lets you read and modify any aspect of a spreadsheet. Spreadsheets have many settings that let you craft beautiful and functional sheets, so the API has many settings too. The API offers two main ways to interact with the spreadsheet:

Reading/writing cell values only (via the spreadsheets.values collection).

Reading/writing any aspect of the spreadsheet (via the spreadsheets collection).

There is a JavaScript Quickstart that makes requests to the Google Sheets API. You can use this to familiarize yourself with the functions and code implementation.

Hope this helps.

Body:
Hey guy's I am trying to send table information to google spreadsheet.

I have tried:

This worked (but i need table data instead of input)

Is there a way to fix it without using google-script.
just pure javascript ?

    Firstname
    Lastname
    Age

    John
    Wick
    33

    Jeff
    AndersOn
    94

    John
    Doe
    33

    <button type="submit" onclick="test()" >Verzenden</button>


答:
You can define which tags you would like to allow and then filter out the other tags in p easily:</p>

```<code> $allowedTags='<p><strong><em><u><h1><h2><h3><h4><h5><h6><img>';
 $allowedTags.='<li><ol><ul><span><div><br><ins><del>';
 $receivedData = $_POST['textFromEditor'];
 $sContent = strip_tags(stripslashes($receivedData),$allowedTags);
</code>```

Title: How to sanitize data received from WYSIWYG Editor?

Body: I have a typical WYSIWYG editor for a blog, which has the ability to embed youtube videos and videos from some other commonly known sources. the editor is JavaScript based. And it adds too much of html tags and java-script in the content that I receive. As i have to store this data received from the editor in my MySQL database. I want to sanitize it. What is the best way to sanitize this data and make it safe to store in the database and further deal with it?

Body:
You can define which tags you would like to allow and then filter out the other tags in p easily:

 $allowedTags='<p><strong><em><u><h1><h2><h3><h4><h5><h6><img>';
 $allowedTags.='<li><ol><ul><span><div><br><ins><del>';
 $receivedData = $_POST['textFromEditor'];
 $sContent = strip_tags(stripslashes($receivedData),$allowedTags);


问:
Is api key needed in SafetyNet attestation?
I've successfully created backend service and Android client for SafetyNet attestation.
When I send jws token to my server and try to validate it's certificate it turns out that there is no certificate that signed it.

Should I add api key to my Android app?

My attestation result:

```<code>eyJhbGciOiJSUzI1NiIsIng1YyI6WyJNSUlFaURDQ0EzQ2dBd0lCQWdJSWNkK3ZTTGZWdWxrd0RRWUpLb1pJaHZjTkFRRUxCUUF3U1RFTE1Ba0dBMVVFQmhNQ1ZWTXhFekFSQmdOVkJBb1RDa2R2YjJkc1pTQkpibU14SlRBakJnTlZCQU1USEVkdmIyZHNaU0JKYm5SbGNtNWxkQ0J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CRDlyZm96YnF6ZWU0ZlpPT2FXclpoc2NvPSJdLCJiYXNpY0ludGVncml0eSI6dHJ1ZX0.JXOvgIx0PufdyJ72Vo-FvTb_6Dwj7gcSxlXWHt8siVrgK2eMQA3V_eYbXS7NYkNUEXLLMNIfm8qEIwJQGYLUKE9GyaHjjuFt_YOkQMOzC8hh9VpIekS8bc_eRfvVajXzrFSRAigOnfVBrMGrVVpxsqtjqz1Y9ochGHwrjO2b8oZyw06HjzsnuT9YpLXakBg1azOYx9KP-_XkDaKW6_Lkfn6Rmo8hpatadIF5qn54W_UkXvvsG7d4P8h_7uvO66rRhK1OXg3Qhazta3B_XFtiLcmusaqmglopEW1hI07FAvrqzemuY-_4EcvReLKfo84rl_BuJmLFVtQtDyAHtzngxw
</code>```

答:
I think you missed some details, based on the documentation - Validating the response with Google APIs:

Note: You need an API key to access the Android Device Verification API, and the API is rate-limited. For these reasons, you should use the API only for testing during the initial development stage. You shouldn't use this verification API in a production scenario.

Try adding the API key and check if the behavior change.

Hope this helps.

Body:
I've successfully created backend service and Android client for SafetyNet attestation.
When I send jws token to my server and try to validate it's certificate it turns out that there is no certificate that signed it.

Should I add api key to my Android app?

My attestation result:

[encoded data, 4806 characters]


问:
creating HTML content on server side using templates
What is the possible solution of creating the HTML content on the server side from a template(.eex).</p>

答:
```<code>html= Phoenix.View.render_to_string(MyAPP.Web.DefaultView,"template.html", %{details: somedetails_details})
</code>```


问:
When use image in tk Button, Button disappear
Here is my code, you can ignore most of them but only see the last part which have #

```<code>import tkinter as tk
from PIL import ImageTk, Image

def bresize_and_load(path):
    global bwidth, bheight
    im = Image.open(path)
    bwidth,bheight = im.size
    resized = bresizemode(im, bwidth, bheight)
    width,height = resized.size
    return ImageTk.PhotoImage(resized)

def bresizemode(im, width, height):
    if height / width >= ratio:
        return im.resize((int(round((width / height) * usable_height)), usable_height),
                  Image.ANTIALIAS)

    if height / width < ratio:
        return im.resize((usable_width, (int(round((height / width) * usable_width)))),
                  Image.ANTIALIAS)

root = tk.Tk()
root.state("zoomed")
root.resizable(width=False, height=False)

frame = tk.Frame(root)

frame.grid(row = 0, column = 0, sticky = 'nsew')

tk.Grid.rowconfigure(root, 0, weight=1)
tk.Grid.columnconfigure(root, 0, weight=1)

row = 4
column = 5
for ro in range(row):
    tk.Grid.rowconfigure(frame, ro, weight=1)
for co in range(column):
    tk.Grid.columnconfigure(frame, co, weight=1)

root.update()
f_width  = frame.winfo_width()
f_height = frame.winfo_height()

booklistbutton = []
for i in range(row):
    for e in range(column):
        bbutton = tk.Button(frame, height = int(f_height / row),
                            width = int(f_width / column))
        bbutton.grid(row = i, column = e)
        booklistbutton.append(bbutton)

root.update()
usable_width = booklistbutton[0].winfo_width()
usable_height = booklistbutton[0].winfo_height()
ratio = usable_height / usable_width

#here is image path
path = 'sample.jpg'
imm = []

#if it is range(20)(just = row * column) or less than column(here is 5), it work fine
for i in range(20):
    imm.append(bresize_and_load(path))
    booklistbutton[i].config(image = imm[i])

root.mainloop()
</code>```

My question is, if you load image in button, but the number of imaged buttons is not less than column or equal row * column, the imaged buttons will disappear.

When range equal row * column(20):

When range is 6:

This is weird for me, does anyone have any idea?

Also, if you do not set button's width and height, they won't disappear. But buttons will little bigger than images.

答:
(Posted solution on behalf of the OP).

I find the problem by myself, the problem is when I set the Buttons' size, it is chr size, but when I load a image, it change to pixel size, and at the same size number, chr size is bigger and bigger than pixel size, so the imaged button become too small to show.

ContentLicense: CC BY-SA 4.0

Body:
Here is my code, you can ignore most of them but only see the last part which have #

import tkinter as tk
from PIL import ImageTk, Image

def bresize_and_load(path):
    global bwidth, bheight
    im = Image.open(path)
    bwidth,bheight = im.size
    resized = bresizemode(im, bwidth, bheight)
    width,height = resized.size
    return ImageTk.PhotoImage(resized)

def bresizemode(im, width, height):
    if height / width >= ratio:
        return im.resize((int(round((width / height) * usable_height)), usable_height),
                  Image.ANTIALIAS)

    if height / width < ratio:
        return im.resize((usable_width, (int(round((height / width) * usable_width)))),
                  Image.ANTIALIAS)

root = tk.Tk()
root.state("zoomed")
root.resizable(width=False, height=False)

frame = tk.Frame(root)

frame.grid(row = 0, column = 0, sticky = 'nsew')

tk.Grid.rowconfigure(root, 0, weight=1)
tk.Grid.columnconfigure(root, 0, weight=1)

row = 4
column = 5
for ro in range(row):
    tk.Grid.rowconfigure(frame, ro, weight=1)
for co in range(column):
    tk.Grid.columnconfigure(frame, co, weight=1)

root.update()
f_width  = frame.winfo_width()
f_height = frame.winfo_height()

booklistbutton = []
for i in range(row):
    for e in range(column):
        bbutton = tk.Button(frame, height = int(f_height / row),
                            width = int(f_width / column))
        bbutton.grid(row = i, column = e)
        booklistbutton.append(bbutton)

root.update()
usable_width = booklistbutton[0].winfo_width()
usable_height = booklistbutton[0].winfo_height()
ratio = usable_height / usable_width

#here is image path
path = 'sample.jpg'
imm = []

#if it is range(20)(just = row * column) or less than column(here is 5), it work fine
for i in range(20):
    imm.append(bresize_and_load(path))
    booklistbutton[i].config(image = imm[i])

root.mainloop()

My question is, if you load image in button, but the number of imaged buttons is not less than column or equal row * column, the imaged buttons will disappear.

When range equal row * column(20):

When range is 6:

This is weird for me, does anyone have any idea?

Also, if you do not set button's width and height, they won't disappear. But buttons will little bigger than images.


问:
Spring context files organization and best practices
We have started using Spring framework in my project. After becoming acquainted with the basic features (IoC) we have started using spring aop and spring security as well.

The problem is that we now have more than 8 different context files and I feel we didn't give enough thought for the organization of those files and their roles. New files were introduced as the project evolved.
We have different context files for: metadata, aop, authorization, services, web resources (it's a RESTful application). So when a developer wants to add a new bean it's not always clear in which file he should add it. We need methodology.

The question:

Is there a best practice for spring files organization?

Should the context files encapsulate layers (DAL , Business Logic, Web) or use cases ? or Flows?

答:
Spring context files contain definitions of beans, so I think that it is best to follow OO principle and structure them the same way you structure your classes in packages. We usually create packages to encapsulate a set of classes that work together to solve a specific problem. A package usually encapsulates a horizontal layer (database layer, middleware, business logic or part of them). There are occasions that a package contain classes that correspond to a horizontal layer (use case or flow as you've mentioned). In general I would recommend to create one context file for every package or set of packages. When you add a new bean, add it to the context file that corresponds to the package of the class.

Of course this shouldn't be a very strict rule, as there might be cases that it would beneficial to follow another practice.

OwnerDisplayName: LiorH

OwnerDisplayName: kgiannakakis


问:
Background image that always scales so that any normal background color wouldn't appear
I wonder if there is a hack that would resize the image in the way that it would always cover the whole browser window. It should also keep the image´s aspect ratio.</p>

答:
this website http://css-tricks.com/how-to-resizeable-background-image/ has a great writeup on this.

Basically just use as the style for your bg

```<code>#bg {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
}
</code>```

About your requirement to maintain the aspect ration AT THE SAME TIME as make it cover the whole window, I don't think it's achievable, you either sacrifice aspect ratio or coverage

Body:
this website http://css-tricks.com/how-to-resizeable-background-image/ has a great writeup on this.

Basically just use as the style for your bg

#bg {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

About your requirement to maintain the aspect ration AT THE SAME TIME as make it cover the whole window, I don't think it's achievable, you either sacrifice aspect ratio or coverage