问:
Failed to initialize end point associated with ProtocolHandler
Hello I have configurated tomcat Server on Windows without any security and it started fine.

When I migrated it to a Linux Server with SSL security, I reconfigured to SSL security but it has always given the follwing eror:

```<code>06-Oct-2017 10:45:34.858 SEVERE [main] org.apache.coyote.AbstractProtocol.init Failed to initialize end point associated with ProtocolHandler ["https-jsse-nio-443"]
     java.net.SocketException: Permission denied
        at sun.nio.ch.Net.bind0(Native Method)
        at sun.nio.ch.Net.bind(Net.java:433)
        at sun.nio.ch.Net.bind(Net.java:425)
        at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
        at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
        at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:210)
        at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:982)
        at org.apache.tomcat.util.net.AbstractJsseEndpoint.init(AbstractJsseEndpoint.java:244)
        at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:620)
        at org.apache.coyote.http11.AbstractHttp11Protocol.init(AbstractHttp11Protocol.java:66)
        at org.apache.catalina.connector.Connector.initInternal(Connector.java:997)
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
        at org.apache.catalina.core.StandardService.initInternal(StandardService.java:549)
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
        at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:875)
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
        at org.apache.catalina.startup.Catalina.load(Catalina.java:607)
        at org.apache.catalina.startup.Catalina.load(Catalina.java:630)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:311)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:494)
</code>```

This is my Server configuratiuon:

```<code><Connector port="443" maxHttpHeaderSize="8192"
     maxThreads="100" minSpareThreads="25" maxSpareThreads="50"
     enableLookups="true" disableUploadTimeout="true"
     acceptCount="50" scheme="https" secure="true"
     URIEncoding="UTF-8"
     connectionTimeout="20000"
     SSLEnabled="true"
     SSLPassword="hasanpass"
     keystorePass="hasanpass"
     SSLCertificateFile="/usr/local/tomcat/crypto/hasan1.crt"
     SSLCertificateKeyFile="/usr/local/tomcat/crypto/hasan.key"/>
</code>```

答:
I had the same issue. I referred to Starting Tomcat Failed to initialize end point associated with ProtocolHandler but no success. Try this first.If it does not do the following.

I ran tomcat on Ubuntu with one of my users with root permissions. Initially I ran the normal command ./startup.sh and I got this permission denied exception. Then I ran sudo ./startup.sh and it worked.

Hope it helps!!!

Body:
Hello I have configurated tomcat Server on Windows without any security and it started fine.

When I migrated it to a Linux Server with SSL security, I reconfigured to SSL security but it has always given the follwing eror:

06-Oct-2017 10:45:34.858 SEVERE [main] org.apache.coyote.AbstractProtocol.init Failed to initialize end point associated with ProtocolHandler ["https-jsse-nio-443"]
     java.net.SocketException: Permission denied
        at sun.nio.ch.Net.bind0(Native Method)
        at sun.nio.ch.Net.bind(Net.java:433)
        at sun.nio.ch.Net.bind(Net.java:425)
        at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
        at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
        at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:210)
        at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:982)
        at org.apache.tomcat.util.net.AbstractJsseEndpoint.init(AbstractJsseEndpoint.java:244)
        at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:620)
        at org.apache.coyote.http11.AbstractHttp11Protocol.init(AbstractHttp11Protocol.java:66)
        at org.apache.catalina.connector.Connector.initInternal(Connector.java:997)
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
        at org.apache.catalina.core.StandardService.initInternal(StandardService.java:549)
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
        at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:875)
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:107)
        at org.apache.catalina.startup.Catalina.load(Catalina.java:607)
        at org.apache.catalina.startup.Catalina.load(Catalina.java:630)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:311)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:494)

This is my Server configuratiuon:

<Connector port="443" maxHttpHeaderSize="8192"
     maxThreads="100" minSpareThreads="25" maxSpareThreads="50"
     enableLookups="true" disableUploadTimeout="true"
     acceptCount="50" scheme="https" secure="true"
     URIEncoding="UTF-8"
     connectionTimeout="20000"
     SSLEnabled="true"
     SSLPassword="hasanpass"
     keystorePass="hasanpass"
     SSLCertificateFile="/usr/local/tomcat/crypto/hasan1.crt"
     SSLCertificateKeyFile="/usr/local/tomcat/crypto/hasan.key"/>


来源: stackexchange

问:
Are indexes really required in the datastore?
I'm a bit confused by some of the GAE documentation.  While I intend to add indexes to optimize performance of my application, I wanted to get some clarification on if they are only suggested for this purpose or if they are truly required.

Queries can't find property values
  that aren't indexed. This includes
  properties that are marked as not
  indexed, as well as properties with
  values of the long text value type
  (Text) or the long binary value type
  (Blob).

A query with a filter or sort order on
  a property will never match an entity
  whose value for the property is a Text
  or Blob, or which was written with
  that property marked as not indexed.
  Properties with such values behave as
  if the property is not set with regard
  to query filters and sort orders.

from http://code.google.com/appengine/docs/java/datastore/queries.html#Introduction_to_Indexes

The first paragraph leads me to believe that you simply cannot sort or filter on unindexed properties.  However, the second paragraph makes me think that this limitation is only confined to Text or Blob properties or properties specifically annotated as unindexed.

I'm curious about the distinction because I have some numeric and string fields that I am currently sorting/filtering against in a production environment which are unindexed.  These queries are being run in a background task that mostly doesn't care about performance (would rather optimize for size/cost in this sitation). Am I somehow just lucky that these are returning the right data?

答:
In the GAE datastore, single property indexes are automatically created for all properties that are not unindexable (explicitly marked, or of those types).

The language in that doc, I suppose, is a tad confusing.

You only need to explicitly define indexes when you want to index by more than one property (say, for sorting by two different properties.)

ContentLicense: CC BY-SA 2.5


问:
Get a textbox to fill 100% of the width of its container div
I have a form, in which there's a textbox followed by a submit button in the same row.

I'd like the submit button to be a little small but the textbox to take up all of the remaining width.

So, I'd like to just stretch the textbox to fill all the width but for the width required by the button.

However, at present, my UI looks like so:

Notice all the empty horizontal space between the textbox and the button.

I have tried setting the width of the textbox to 100% in the CSS but nothing happens.

Below is my HTML.

```<code><div class="row" id="rowFormContainer">
    <form id="frm">
        <div id="divUserURLContainer" class="col-md-10">
            <input type="text"
                   id="txtUserURL"
                   placeholder="Stack Overflow URL" />
        </div>

        <div id="divGetButtonContainer" class="col-md-2">
            <input type="submit" value="Get" class="btn btn-success"/>
        </div>
    </form>

</div>
</code>```

As you may observe, I am using the bootstrap classes row and md-col-x in order to define the layout of the container divs. I'd like the input control that reresents my textbox to fill 100% of the width of its container div.

And this is my CSS:

```<code>#rowFormContainer {
    padding-left: 7px;
    padding-right: 7px;
    padding-bottom: 10px;

    border-width: 2px;
    border-style: dashed;
}

#divUserURLContainer {
    border-width: 2px;
    border-style: solid;
    border-color: red;

    padding: 0px;
}

#txtUserURL {
    font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
    color: cadetblue;
    font-size: 22px;

    padding-left: 7px;
    padding-right: 7px;
    padding-top: 4px;
    padding-bottom: 4px;

    border-radius: 7px;
    width: 100%;
}
</code>```

答:
You are not using the native bootstrap functionality correctly - by adding the class - "form-control" to your input you will achieve the full width input - without resorting to flex. Note that I have the .form-group wrapper and added a label - it is good practise to include a label with your inputs - and thee "control-label" class on that allows bootstrap to color it red if there is an error (and the ".has-error" class is applied to the form group.

I have added borders around the two divs. Not that there is padding within the div - because that is natural 15px padding of divs that bootstrap provides - not be cause the input does not extend the full width.

And following the craziness inspired by comments - I have removed padding to show the implications of such an action - simply by removing the left and right padding - I do not think this is very desirable - but I accept that the OP asked for the full width of the div. However crazy that is.

Note that due to the size of the nsnippet editor - i had to make it col-xs-10 / col-xs-2 - but the same premise holds up through the viewport breakpoints.

```<code>  <div id="divUserURLContainer" class="col-md-10">
    <div class="form-group">
      <label class="control-label" for="txtUserURL">Label text</label>
      <input type="text" class="form-control" id="txtUserURL" placeholder="Stack Overflow URL" >/>
    </div>
 </div>
</code>```

#divGetButtonContainer {
padding-top:24px;
padding-bottom: 16px;
}

#divUserURLContainer,
#divGetButtonContainer {
border: solid 1px red;
padding-left:0;
padding-right:0;
}

 #divGetButtonContainer{
border-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div id="divUserURLContainer" class="col-xs-10">
  <div class="form-group">
      <label class="control-label" for="txtUserURL">Label text</label>
      <input type="text" class="form-control" id="txtUserURL" placeholder="Stack Overflow URL"/ >
    </div>
  </div>
   <div id="divGetButtonContainer" class="col-xs-2">

      <input type="submit" value="Get" class="btn btn-success"/>
    </div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a form, in which there's a textbox followed by a submit button in the same row.

I'd like the submit button to be a little small but the textbox to take up all of the remaining width.

So, I'd like to just stretch the textbox to fill all the width but for the width required by the button.

However, at present, my UI looks like so:

Notice all the empty horizontal space between the textbox and the button.

I have tried setting the width of the textbox to 100% in the CSS but nothing happens.

Below is my HTML.

    <form id="frm">

            <input type="text"
                   id="txtUserURL"
                   placeholder="Stack Overflow URL" />

            <input type="submit" value="Get" class="btn btn-success"/>

    </form>

As you may observe, I am using the bootstrap classes row and md-col-x in order to define the layout of the container divs. I'd like the input control that reresents my textbox to fill 100% of the width of its container div.

And this is my CSS:

#rowFormContainer {
    padding-left: 7px;
    padding-right: 7px;
    padding-bottom: 10px;

    border-width: 2px;
    border-style: dashed;
}

#divUserURLContainer {
    border-width: 2px;
    border-style: solid;
    border-color: red;

    padding: 0px;
}

#txtUserURL {
    font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
    color: cadetblue;
    font-size: 22px;

    padding-left: 7px;
    padding-right: 7px;
    padding-top: 4px;
    padding-bottom: 4px;

    border-radius: 7px;
    width: 100%;
}

Body:
You are not using the native bootstrap functionality correctly - by adding the class - "form-control" to your input you will achieve the full width input - without resorting to flex. Note that I have the .form-group wrapper and added a label - it is good practise to include a label with your inputs - and thee "control-label" class on that allows bootstrap to color it red if there is an error (and the ".has-error" class is applied to the form group.

I have added borders around the two divs. Not that there is padding within the div - because that is natural 15px padding of divs that bootstrap provides - not be cause the input does not extend the full width.

And following the craziness inspired by comments - I have removed padding to show the implications of such an action - simply by removing the left and right padding - I do not think this is very desirable - but I accept that the OP asked for the full width of the div. However crazy that is.

Note that due to the size of the nsnippet editor - i had to make it col-xs-10 / col-xs-2 - but the same premise holds up through the viewport breakpoints.

  <div id="divUserURLContainer" class="col-md-10">
    <div class="form-group">
      <label class="control-label" for="txtUserURL">Label text</label>
      <input type="text" class="form-control" id="txtUserURL" placeholder="Stack Overflow URL" >/>
    </div>
 </div>

#divGetButtonContainer {
padding-top:24px;
padding-bottom: 16px;
}

#divUserURLContainer,
#divGetButtonContainer {
border: solid 1px red;
padding-left:0;
padding-right:0;
}

 #divGetButtonContainer{
border-color: blue;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div id="divUserURLContainer" class="col-xs-10">
  <div class="form-group">
      <label class="control-label" for="txtUserURL">Label text</label>
      <input type="text" class="form-control" id="txtUserURL" placeholder="Stack Overflow URL"/ >
    </div>
  </div>
   <div id="divGetButtonContainer" class="col-xs-2">

      <input type="submit" value="Get" class="btn btn-success"/>
    </div>


问:
What am I missing from my code to meet all the requirements of my program?
I have to design and implement a program that counts the number of integer values from user input. Produce a table listing the values you identify as integers from the input. Provide the sum and average of the numbers.This is what I have so far.</p>

```<code>public class Table {
public static void main(String [] strAng) {
    int sum = 0;
    double average;
    int min = 1;
    int max = 10;

    for(int number = min;
    number <= max; ++number) {
        sum += number;
    }

    System.out.print("Sum:" +sum);
    System.out.print("Average:" +average);
</code>```

答:
Im not sure if this is exactly what you are looking for but it could be. With this code you enter a string with integers "in it". The integers get extracted, counted and have sum & average operations performed on what is basically a bar graph. Hope this helps.

```<code>import java.util.*;
public class Table {
</code>```

This part is used to read ANY user input Strings included.

```<code>public static String getInput(){
    String outPut = "";
    System.out.println("Type something to parse: ");
    Scanner sc = new Scanner(System.in);
    if(sc.hasNextLine()) {
        outPut = sc.nextLine();
    }
    return outPut;
}
</code>```

Here we build our "bar graph":

```<code>public static Map<Long,Integer> makeTable(String input){

    Map<Long,Integer> table = new HashMap<>();

    long in = Long.parseLong(input);
    long lastDig = 0;
    int count = 1;
    while(in > 0){

    lastDig = in % 10;
    in /= 10;

    if(!table.containsKey(lastDig)) {
        table.put(lastDig, count);
    } else {
        table.replace(lastDig,count,count+1);
    }

    }

    return table;
}
</code>```

Here we calculate the sum:

```<code>public static int sum(Map<Long,Integer> table){
    int sum = 0;
    for (Long key: table.keySet()
         ) {
        sum += (key*table.get(key));
    }
    return sum;
}
</code>```

Here we get our average:

```<code>public static int average(Map<Long,Integer> table){
    int sum = 0;
    int divisor = 0;
    for (Long key: table.keySet()
            ) {
        sum += (key*table.get(key));
        divisor += table.get(key);
    }
    return sum/divisor;
}

public static void main(String[] args){

    int sum = 0;
    double average = 0;
    String input = "";
    input = getInput();
    System.out.println("Unsanitized In: " + input);
</code>```

Here the integer digits are extracted!

```<code>    input = input.replaceAll("[^\\d.]","");
    Long.parseLong(input);

    System.out.println("Sanitized In: " + input);

    Map<Long,Integer> myMap = makeTable(input);
    System.out.println(myMap);

    System.out.println("Sum:" +sum(myMap));
    System.out.print("Average:" + average(myMap));

}
</code>```

}

Our example output for: asdf45313ha is:

```<code> Unsanitized In: asdf45313ha
 Sanitized In: 45313
 {1=1, 3=2, 4=1, 5=1}
 Sum:16
 Average:3
</code>```

Body:
I have to design and implement a program that counts the number of integer values from user input. Produce a table listing the values you identify as integers from the input. Provide the sum and average of the numbers.This is what I have so far.

public class Table {
public static void main(String [] strAng) {
    int sum = 0;
    double average;
    int min = 1;
    int max = 10;

    for(int number = min;
    number <= max; ++number) {
        sum += number;
    }

    System.out.print("Sum:" +sum);
    System.out.print("Average:" +average);

Body:
Im not sure if this is exactly what you are looking for but it could be. With this code you enter a string with integers "in it". The integers get extracted, counted and have sum & average operations performed on what is basically a bar graph. Hope this helps.

import java.util.*;
public class Table {

This part is used to read ANY user input Strings included.

public static String getInput(){
    String outPut = "";
    System.out.println("Type something to parse: ");
    Scanner sc = new Scanner(System.in);
    if(sc.hasNextLine()) {
        outPut = sc.nextLine();
    }
    return outPut;
}

Here we build our "bar graph":

public static Map<Long,Integer> makeTable(String input){

    Map<Long,Integer> table = new HashMap<>();

    long in = Long.parseLong(input);
    long lastDig = 0;
    int count = 1;
    while(in > 0){

    lastDig = in % 10;
    in /= 10;

    if(!table.containsKey(lastDig)) {
        table.put(lastDig, count);
    } else {
        table.replace(lastDig,count,count+1);
    }

    }

    return table;
}

Here we calculate the sum:

public static int sum(Map<Long,Integer> table){
    int sum = 0;
    for (Long key: table.keySet()
         ) {
        sum += (key*table.get(key));
    }
    return sum;
}

Here we get our average:

public static int average(Map<Long,Integer> table){
    int sum = 0;
    int divisor = 0;
    for (Long key: table.keySet()
            ) {
        sum += (key*table.get(key));
        divisor += table.get(key);
    }
    return sum/divisor;
}

public static void main(String[] args){

    int sum = 0;
    double average = 0;
    String input = "";
    input = getInput();
    System.out.println("Unsanitized In: " + input);

Here the integer digits are extracted!

    input = input.replaceAll("[^\\d.]","");
    Long.parseLong(input);

    System.out.println("Sanitized In: " + input);

    Map<Long,Integer> myMap = makeTable(input);
    System.out.println(myMap);

    System.out.println("Sum:" +sum(myMap));
    System.out.print("Average:" + average(myMap));

}

}

Our example output for: asdf45313ha is:

 Unsanitized In: asdf45313ha
 Sanitized In: 45313
 {1=1, 3=2, 4=1, 5=1}
 Sum:16
 Average:3


问:
PG::UndefinedColumn: ERROR in case of same DB is used for two different projects which are connected with each other in Rails
I'm running two projects as a different repository with git. One is admit another one is Web in rails, both are connected with each other, Basically same database is used. I only made the migration on admin report and then cloned it into the web. The problem is, I'm deploying it on the server and test cases failed the error says

```<code>ActionView::Template::Error: PG::UndefinedColumn: ERROR:  column fees.discount does not exist
</code>```

I just don't understand why it has been happening, in admin I have that field presents.

I think schema.rb may playing role in this case. I'm not so sure about it.

Here is my migration,

```<code>class AddDiscountToFeel < ActiveRecord::Migration[5.0]
   def change
     add_column :fees, :discount, :integer, default: nil, null: true
   end
 end
</code>```

And here is my Model fields in development:

```<code> 2.3.1 :008 > Fee.column_names
 => ["id", "booth_id", "amount", "description", "created_at", "updated_at", "discount"]
</code>```

And here is my Model fields in test:

```<code>C238s-iMac:web c238$ RAILS_ENV=test rails c
Loading test environment (Rails 5.0.0.1)
2.3.1 :001 > Fee.column_names
 => ["id", "booth_id", "amount", "description", "created_at", "updated_at", "discount"]
</code>```

And here is my error's snap:

Any help will be appreciated.

答:
Can try to run to add discount to the table?

bundle exec rake db:migrate

if using heroku:

heroku run rake db:migrate

Body:
I'm running two projects as a different repository with git. One is admit another one is Web in rails, both are connected with each other, Basically same database is used. I only made the migration on admin report and then cloned it into the web. The problem is, I'm deploying it on the server and test cases failed the error says

ActionView::Template::Error: PG::UndefinedColumn: ERROR:  column fees.discount does not exist

I just don't understand why it has been happening, in admin I have that field presents.

I think schema.rb may playing role in this case. I'm not so sure about it.

Here is my migration,

class AddDiscountToFeel < ActiveRecord::Migration[5.0]
   def change
     add_column :fees, :discount, :integer, default: nil, null: true
   end
 end

And here is my Model fields in development:

 2.3.1 :008 > Fee.column_names
 => ["id", "booth_id", "amount", "description", "created_at", "updated_at", "discount"]

And here is my Model fields in test:

C238s-iMac:web c238$ RAILS_ENV=test rails c
Loading test environment (Rails 5.0.0.1)
2.3.1 :001 > Fee.column_names
 => ["id", "booth_id", "amount", "description", "created_at", "updated_at", "discount"]

And here is my error's snap:

Any help will be appreciated.


问:
Can jQuery UI 1.8.2 run on jquery 1.4.1?
It's that simple question.

Can jQuery UI 1.8.2 run on jquery 1.4.1?

答:
Probably.

Why don't you test it?

Also, why don't you upgrade to the latest versions of both?


问:
Admob interstitial with audio
I hope someone can give information about this.
I display interstitial ads with Admob. Some of them have music or sounds and my users get terrible annoyed because of this. So, does anyone know if there is a way to block ads with music or sound? Is there anyway to decline access to the loud speaker for the ads?
Thanks</p>

答:
to mute an ad, just call MobileAds.setAppmuted(true)

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    // Set app volume to be half of current device volume.
    MobileAds.setAppVolume(0.5f); // or setAppMuted(true); to mute
    ...
}
</code>```

from their forum page: https://groups.google.com/forum/#!topic/google-admob-ads-sdk/X7hQeehlJBI

The Google Mobile Ads SDK for Android has methods to set the current volume for incoming ads, based on the device's current volume level.

setAppVolume(float) - available in the Android AdMob SDK version 8.4
  and up. setAppMuted(boolean) - available in the Android AdMob SDK version 9.0 and up.

for further readings, refer to https://developers.google.com/admob/android/global-settings and  https://developers.google.com/android/reference/com/google/android/gms/ads/MobileAds

Title: Admob interstitial with audio

Body:
to mute an ad, just call MobileAds.setAppmuted(true)

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

    // Set app volume to be half of current device volume.
    MobileAds.setAppVolume(0.5f); // or setAppMuted(true); to mute
    ...
}

from their forum page: https://groups.google.com/forum/#!topic/google-admob-ads-sdk/X7hQeehlJBI

The Google Mobile Ads SDK for Android has methods to set the current volume for incoming ads, based on the device's current volume level.

setAppVolume(float) - available in the Android AdMob SDK version 8.4
  and up. setAppMuted(boolean) - available in the Android AdMob SDK version 9.0 and up.

for further readings, refer to https://developers.google.com/admob/android/global-settings and  https://developers.google.com/android/reference/com/google/android/gms/ads/MobileAds


问:
How to override Enter press on a button in xamarin pcl UWP?
Hy,

I'm working on a xamarin PCL project with a lot of entries and buttons for UWP. For the entries I have iplemented in a custom renderer a keydown and keyup function for detecting the Enter press. As result it goes to the next UI element.
For a button I need the same detection but in the renderer in doesn't goes to the function keyup or keydown.

So How can I make a button detect an Enter press before executing the original command?

Here is the code that I've implemented.

public class CustomButtonRenderer : ButtonRenderer
{
    public CustomButtonRenderer()
    {
    }

    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
    {
        Xamarin.Forms.Button appButton = (Xamarin.Forms.Button)Element;
        base.OnElementChanged(e);
        if (Control != null && appButton != null)
        {
            Control.KeyUp += Control_KeyUp;
            Control.KeyDown += Control_KeyDown;
        }
    }

    private void Control_KeyDown(object sender, KeyRoutedEventArgs e)
    {
    }
    private void Control_KeyUp(object sender, KeyRoutedEventArgs e)
    {
        Xamarin.Forms.Button appButton = (Xamarin.Forms.Button)Element;
        switch (e.Key)
        {
            case (Windows.System.VirtualKey.Enter):
                {
                    FocusManager.TryMoveFocus(FocusNavigationDirection.Next);
                    break;
                }
        }

    }
}
```

答:
You need to set the KeyRoutedEventArgs.Handled property to true. This should do what you asked:

private void Control_KeyDown(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == Windows.System.VirtualKey.Enter)
    {
        FocusManager.TryMoveFocus(FocusNavigationDirection.Next);
        e.Handled = true;
    }
}
```


问:
How to extract array of names from array of email ids
Given this input array:

```<code>var data = ["ramu@xerago.com","ravi@xerago.com","karthik@xerago.com"];
</code>```

I to output an array that looks like this:

```<code>["ramu","ravi","karthik"];
</code>```

I have tried this, but it doesn't produce the correct result:

```<code>names = data.map(s => s.split('@'));
</code>```

答:
below is the solution</p>

```<code>var names = data.map(email => email.split("@")[0] )
</code>```

Body:
Given this input array:

var data = ["ramu@xerago.com","ravi@xerago.com","karthik@xerago.com"];

I to output an array that looks like this:

["ramu","ravi","karthik"];

I have tried this, but it doesn't produce the correct result:

names = data.map(s => s.split('@'));

Body:
below is the solution

var names = data.map(email => email.split("@")[0] )


问:
Using Catch2 in Visual C++ 2015
I'm trying to make a Unit Testing project using the Catch framework, but am faced with Link errors.

I've set up the project as follows:

Create a Native Unit Test project

Add Catch to the include directories

Add #include <catch.hpp> to stdafx.h

Write the following simple source file

unittest.cpp:

```<code>#include "stdafx.h"
namespace Catch2_Test
{
  TEST_CASE("Y U no work")
  {
    REQUIRE(1);
  }
}
</code>```

答:
For integrating Catch into Visual Studio

refer the ACCU article Integrating the Catch Test Framework into Visual Studio, by Malcolm Noyes

For using Catch2 in pre-compiled headers,

refer Catch2 issue 1061, where horenmar gave an example. The changes have been released as part of v2.1.0

In summary, the solution given is:

```<code>// stdafx.h
#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

#define CATCH_CONFIG_ALL_PARTS
#include "catch.hpp"

// PCH-test.cpp:
#include "stdafx.h"

#undef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
#define CATCH_CONFIG_IMPL_ONLY
#define CATCH_CONFIG_MAIN
#include "catch.hpp"

// tests1.cpp:
#include "stdafx.h"

TEST_CASE("FooBarBaz") {
    REQUIRE(1 == 2);
}
</code>```

Title: Using Catch2 in Visual C++ 2015

Body:
I'm trying to make a Unit Testing project using the Catch framework, but am faced with Link errors.

I've set up the project as follows:

Create a Native Unit Test project

Add Catch to the include directories

Add #include <catch.hpp> to stdafx.h

Write the following simple source file

unittest.cpp:

#include "stdafx.h"
namespace Catch2_Test
{
  TEST_CASE("Y U no work")
  {
    REQUIRE(1);
  }
}

Body:
For integrating Catch into Visual Studio

refer the ACCU article Integrating the Catch Test Framework into Visual Studio, by Malcolm Noyes

For using Catch2 in pre-compiled headers,

refer Catch2 issue 1061, where horenmar gave an example. The changes have been released as part of v2.1.0

In summary, the solution given is:

// stdafx.h
#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

#define CATCH_CONFIG_ALL_PARTS
#include "catch.hpp"

// PCH-test.cpp:
#include "stdafx.h"

#undef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
#define CATCH_CONFIG_IMPL_ONLY
#define CATCH_CONFIG_MAIN
#include "catch.hpp"

// tests1.cpp:
#include "stdafx.h"

TEST_CASE("FooBarBaz") {
    REQUIRE(1 == 2);
}


问:
std::memcpy or explicit char value assignment - equal and legal in C++
In the following example the value-representation of an uint32_t is copied to an uint8_t array. This is done by std::memcpy. As I understand the C++ standard this is totally legal: we are accessing an object of type T via T* casted to a unsigned char*. No aliasing problem, no alignment problem.

The other way round is less obvious. We are accessing the object representation of T via unsigned char*, which is legal. But does the term accessing include changing?

Of course there are no aliasing and no aligment problems. There are however problems if the values in buffer s origin from a foreign source: we must ensure the right endianness and omit trap representations. The right endianness can be checked, so that can be solved.
But what about trap representations? How can we avoid that? Or do uint-types not have trap representations as opposed to say double?

I know that another (more compliant?) way would be shifting the uint8_t values into the uint_t object. We still have to obey the endianness but this should safely omit trap representations.

But shifts of large types on small µC (8-Bit) can be quite expensive!

The next question is if the second try (see below in the code) is equivalent to the memcpy approach with respect to legality and functionality? Well, it looks like the memcpy version is more optimizer friendly.

```<code>#include <cstdint>
#include <cstring>
#include <cassert>

typedef uint32_t utype;

constexpr utype value = 0x01020304;

int main() {
    utype a{value};
    utype b{0};
    uint8_t s[sizeof(utype)]{};

    // first
    std::memcpy(s, &a, sizeof(utype));
    assert(s[0] == (value & 0xff));

    std::memcpy(&b, s, sizeof(utype));
    assert(b == value);

    // second

    const uint8_t* ap = reinterpret_cast<const uint8_t*>(&a);
    s[0] = ap[0]; // explicitly legal in C++
    s[1] = ap[1];
    s[2] = ap[2];
    s[3] = ap[3];
    assert(s[0] == (value & 0xff));

    uint8_t* bp = reinterpret_cast<uint8_t*>(&b);
    bp[0] = s[0]; // same as memcpy or ist this UB ?
    bp[1] = s[1];
    bp[2] = s[2];
    bp[3] = s[3];
    assert(b == value);
}
</code>```

答:
But does the term accessing include changing?

Yes.

Note: In fact that's what memcpy does conceptionally. It modifies bytes as if they were narrow character objects.
 If this weren't possible, then memcpy couldn't be implemented in standard c++.

But what about trap representations? How can we avoid that?

This is quite tricky. If you know of a trap representation, then you would have to test for it using the narrow character view of the object, before trying to use the value in the type that has a trap representation. I don't know if there are any standard ways of dealing with trap representations.

Maybe there should be a std::is_trap<T>(void*) trait to solve this, but there isn't as far as I know.

I know that another (more compliant?) way would be shifting the uint8_t values into the uint_t object. We still have to obey the endianness but this should safely omit trap representations.

If the foreign value is a trap representation, then that value probably isn't representable anyway, so this shifting might have some other problem such as overflow in such case.

The difference between shifting and memcpy is that shifting allows converting known endianness to native endianness while memcpy works when the source already has native endianness.

If it were guaranteed that uint8_t were an alias of unsigned char, then the second snippet would be well defined and functionally equivalent to memcpy. I don't know if it is guaranteed, but it is certainly common. Only narrow character type has exceptions to pointer aliasing rules.

```<code>assert(s[0] == (value & 0xff));
</code>```

This assert relies on endianness of the cpu.

Body:
In the following example the value-representation of an uint32_t is copied to an uint8_t array. This is done by std::memcpy. As I understand the C++ standard this is totally legal: we are accessing an object of type T via T* casted to a unsigned char*. No aliasing problem, no alignment problem.

The other way round is less obvious. We are accessing the object representation of T via unsigned char*, which is legal. But does the term accessing include changing?

Of course there are no aliasing and no aligment problems. There are however problems if the values in buffer s origin from a foreign source: we must ensure the right endianness and omit trap representations. The right endianness can be checked, so that can be solved.
But what about trap representations? How can we avoid that? Or do uint-types not have trap representations as opposed to say double?

I know that another (more compliant?) way would be shifting the uint8_t values into the uint_t object. We still have to obey the endianness but this should safely omit trap representations.

But shifts of large types on small µC (8-Bit) can be quite expensive!

The next question is if the second try (see below in the code) is equivalent to the memcpy approach with respect to legality and functionality? Well, it looks like the memcpy version is more optimizer friendly.

#include <cstdint>
#include <cstring>
#include <cassert>

typedef uint32_t utype;

constexpr utype value = 0x01020304;

int main() {
    utype a{value};
    utype b{0};
    uint8_t s[sizeof(utype)]{};

    // first
    std::memcpy(s, &a, sizeof(utype));
    assert(s[0] == (value & 0xff));

    std::memcpy(&b, s, sizeof(utype));
    assert(b == value);

    // second

    const uint8_t* ap = reinterpret_cast<const uint8_t*>(&a);
    s[0] = ap[0]; // explicitly legal in C++
    s[1] = ap[1];
    s[2] = ap[2];
    s[3] = ap[3];
    assert(s[0] == (value & 0xff));

    uint8_t* bp = reinterpret_cast<uint8_t*>(&b);
    bp[0] = s[0]; // same as memcpy or ist this UB ?
    bp[1] = s[1];
    bp[2] = s[2];
    bp[3] = s[3];
    assert(b == value);
}

Body:
But does the term accessing include changing?

Yes.

Note: In fact that's what memcpy does conceptionally. It modifies bytes as if they were narrow character objects.
 If this weren't possible, then memcpy couldn't be implemented in standard c++.

But what about trap representations? How can we avoid that?

This is quite tricky. If you know of a trap representation, then you would have to test for it using the narrow character view of the object, before trying to use the value in the type that has a trap representation. I don't know if there are any standard ways of dealing with trap representations.

Maybe there should be a std::is_trap<T>(void*) trait to solve this, but there isn't as far as I know.

I know that another (more compliant?) way would be shifting the uint8_t values into the uint_t object. We still have to obey the endianness but this should safely omit trap representations.

If the foreign value is a trap representation, then that value probably isn't representable anyway, so this shifting might have some other problem such as overflow in such case.

The difference between shifting and memcpy is that shifting allows converting known endianness to native endianness while memcpy works when the source already has native endianness.

If it were guaranteed that uint8_t were an alias of unsigned char, then the second snippet would be well defined and functionally equivalent to memcpy. I don't know if it is guaranteed, but it is certainly common. Only narrow character type has exceptions to pointer aliasing rules.

assert(s[0] == (value & 0xff));

This assert relies on endianness of the cpu.


问:
Columns Layout export
Sparx Enterprise Architect offers the possibility to define custom layouts for list views in the package browser and to save these definitions. When exporting a Project file (*.eap) via xmi, these definitions are not included in the export-file and thus lost. I wonder whether there exists a way to transfer columns layout definitions between two EA-Projects.

Many thanks in advance for every hint!

Title: Columns Layout export

Body:
As Geert suggested the layout is stored in the registry.

[HKEY_CURRENT_USER\Software\Sparx Systems\EA400\EA\OPTIONS]

holds a key PKG_BRWSE_LAYOUTS with the comma separated list of profile names (so you better don't use comma in your profile name ;-).

The detailed information is stored in

[HKEY_CURRENT_USER\Software\Sparx Systems\EA400\EA\EA1200Workspace\BCGPGrids\EA_ELEMENT_LIST_<name>BCGPGrid-0]

where <name> is the according profile name.

For a sample layout here they looked like

"Columns"=hex:11,00,01,00,00,00,01,00,00,00,01,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,01,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,01,00,00,00,01,00,00,00,01,00,00,00,01,00,00,00
"ColumnWidth"=hex:11,00,16,00,00,00,04,01,00,00,50,00,00,00,50,00,00,00,50,00,\
  00,00,50,00,00,00,50,00,00,00,50,00,00,00,50,00,00,00,50,00,00,00,50,00,00,\
  00,50,00,00,00,50,00,00,00,50,00,00,00,50,00,00,00,50,00,00,00,50,00,00,00
"ColumnOrder"=hex:08,00,00,00,00,00,01,00,00,00,06,00,00,00,02,00,00,00,0d,00,\
  00,00,0e,00,00,00,0f,00,00,00,10,00,00,00
"Groupping"=hex:00,00
"LastFieldChooserPos"=hex:00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
"IsFieldChooserVisible"=dword:00000000
"IsFieldChooserThemed"=dword:00000001
"SortColumns"=hex:00,00

I have to leave that to you to decipher the coding used here. But for a pure ex-/import you probably don't need to do that.


问:
Plone: TinyMCE upload files
I'm trying to find a solution for files uploading directly with TinyMCE. Imagine creating a list of pdf files by uploading them using a custom button.

Is there something already done I can use? collective.clipboardupload seems to be a solution only for images.

答:
collective.quickupload serves us well for such purposes and has a very good UI.

You can add that gadget as a portlet and make it only visible in edit-mode via CSS.

In our case we assigned the portlet to a certain content-type ('Gallery') instead to a location.

Title: Plone: TinyMCE upload files


问:
HIghcharts column tickmarks not aligned to column
I have a column chart with 11 columns where I would like to have a tick mark with a label on the x-axis in the middle of each column. However, I can't get the tickmarks and labels to align with my columns. I have created a jsfiddle to illustrate my problem. I have set min, max and tickInterval on the x-axis but it doesn't seem to use the min and max value at all. Instead my start tick show 7.2 and the last 27. What am I doing wrong?

https://jsfiddle.net/LLExL/8218/

```<code>Highcharts.chart('container', {
    "chart": {
        "width": 850,
        "height": 450,
    type: 'column'
    },
  plotOptions: {
    column: {
      pointPlacement: 'between'
    }
  },
    "yAxis": [{
        "lineWidth": 1,
        "gridLineWidth": 1,
        "tickWidth": 1,
    }],
    "xAxis": [{
        "startOnTick": true,
        "endOnTick": true,
        "min": 8,
        "max": 26,
        "tickInterval": 1.8,
        "gridLineWidth": 1,
        "tickWidth": 1,
    tickmarkPlacement: 'on'
    }],
    "series": [{
        "data": [
            [8, 4.15],
            [9.8, 17.61],
            [11.6, 48.32],
            [13.4, 108.65],
            [15.2, 53.92],
            [17, 138.87],
            [18.8, 152.77],
            [20.6, 69.17],
            [22.4, 18.27],
            [24.2, 8.82],
            [26, 1.43]
        ],
        "name": "Test",
    "pointStart": 8,
    "pointInterval": 1.8
    }]
});
</code>```

答:
Using tickPositions you can put ticks wherever you may want them. So for example to fit with your columns, you can do:

```<code>xAxis: [{
  tickPositions: [8, 9.8, 11.6, 13.4...]
  ...
}]
</code>```

Working example: https://jsfiddle.net/ewolden/LLExL/8219/

API on xAxis.tickPositions: https://api.highcharts.com/highcharts/xAxis.tickPositions

Body:
I have a column chart with 11 columns where I would like to have a tick mark with a label on the x-axis in the middle of each column. However, I can't get the tickmarks and labels to align with my columns. I have created a jsfiddle to illustrate my problem. I have set min, max and tickInterval on the x-axis but it doesn't seem to use the min and max value at all. Instead my start tick show 7.2 and the last 27. What am I doing wrong?

https://jsfiddle.net/LLExL/8218/

Highcharts.chart('container', {
    "chart": {
        "width": 850,
        "height": 450,
    type: 'column'
    },
  plotOptions: {
    column: {
      pointPlacement: 'between'
    }
  },
    "yAxis": [{
        "lineWidth": 1,
        "gridLineWidth": 1,
        "tickWidth": 1,
    }],
    "xAxis": [{
        "startOnTick": true,
        "endOnTick": true,
        "min": 8,
        "max": 26,
        "tickInterval": 1.8,
        "gridLineWidth": 1,
        "tickWidth": 1,
    tickmarkPlacement: 'on'
    }],
    "series": [{
        "data": [
            [8, 4.15],
            [9.8, 17.61],
            [11.6, 48.32],
            [13.4, 108.65],
            [15.2, 53.92],
            [17, 138.87],
            [18.8, 152.77],
            [20.6, 69.17],
            [22.4, 18.27],
            [24.2, 8.82],
            [26, 1.43]
        ],
        "name": "Test",
    "pointStart": 8,
    "pointInterval": 1.8
    }]
});

Body:
Using tickPositions you can put ticks wherever you may want them. So for example to fit with your columns, you can do:

xAxis: [{
  tickPositions: [8, 9.8, 11.6, 13.4...]
  ...
}]

Working example: https://jsfiddle.net/ewolden/LLExL/8219/

API on xAxis.tickPositions: https://api.highcharts.com/highcharts/xAxis.tickPositions


问:
GWT Developer plugin For IE installation problem
I'm using a windows 7 (32 bit) box with IE8 and i'm having issues
installing GWT Developer plugin For IE.

I get the following error message: "Installer download failed. Error code = 0x80072efe "

the installer stays stuck at the "downloading plugin" stage.

i've made sure my windows 7 firewall is off and also turned off my antivirus program but still same problem.

Any ideas?

Thanks

答: Maybe it works if you do an offline installation using the MSI from here: http://ui-programming.blogspot.com/2009/12/update-your-application-to-gwt-20.html</p>


问:
How can I get Perl DBI's selectrow_hashref to return a new row each iteration?
I am trying to use DBI's selectrow_hashref instead of fetchrow_hashref in order to save a couple lines of code, but it keeps returning the same row of data over and over.

```<code>my $select="SELECT * FROM table";
while (my ($user_ref) = $dbh->selectrow_hashref()) {
    # $user_ref is the same each time!
}
</code>```

When I use fetchrow_hashref, everything is fine, and each iteration I get new data.

```<code>my $select="SELECT * FROM table";
my $sth = $dbh->prepare($select) || die "prepare: $select: $DBI::errstr";
$sth->execute() || die "execute: $select: $DBI::errstr";
while (my ($user_ref) = $sth->fetchrow_hashref()) {
    # works great, new data in $user_ref each iteration
}
</code>```

Pray tell, what am I doing wrong? Is selectrow_hashref only intended to retrieve a single record?  It doesn't seem that way in the doc.

答:
Is selectrow_hashref only intended to retrieve a single record?

Yes.

It doesn't seem that way in the doc.

Well, that documentation says:

It returns the first row of data from the statement.

Which seems pretty clear to me.

Are you looking for selectall_hashref instead?

Update: Actually, I think you want selectall_array:

```<code>my $select='SELECT * FROM table';
foreach my $user_ref ($dbh->selectall_array($select, { Slice => {} })) {
    # $user_ref is a hash ref
    say $user_ref->{some_column};
}
</code>```

Body:
I am trying to use DBI's selectrow_hashref instead of fetchrow_hashref in order to save a couple lines of code, but it keeps returning the same row of data over and over.

my $select="SELECT * FROM table";
while (my ($user_ref) = $dbh->selectrow_hashref()) {
    # $user_ref is the same each time!
}

When I use fetchrow_hashref, everything is fine, and each iteration I get new data.

my $select="SELECT * FROM table";
my $sth = $dbh->prepare($select) || die "prepare: $select: $DBI::errstr";
$sth->execute() || die "execute: $select: $DBI::errstr";
while (my ($user_ref) = $sth->fetchrow_hashref()) {
    # works great, new data in $user_ref each iteration
}

Pray tell, what am I doing wrong? Is selectrow_hashref only intended to retrieve a single record?  It doesn't seem that way in the doc.

Body:
Is selectrow_hashref only intended to retrieve a single record?

Yes.

It doesn't seem that way in the doc.

Well, that documentation says:

It returns the first row of data from the statement.

Which seems pretty clear to me.

Are you looking for selectall_hashref instead?

Update: Actually, I think you want selectall_array:

my $select='SELECT * FROM table';
foreach my $user_ref ($dbh->selectall_array($select, { Slice => {} })) {
    # $user_ref is a hash ref
    say $user_ref->{some_column};
}


问:
Dynamic variables in Clojure libraries
TL;DR: Is the following a good pattern for a library?

```<code>(def ^{:dynamic true} *var*)
(defn my-fn [{:keys [var]}]
  (do-smth (or var *var*)))
</code>```

--

Say I want to write a sentiment analysis library.

Is it good design in get-sentiment fn to accept optional sentiment labels but provide default one as dynamic var?

```<code>(def ^:dynamic *sentiment-level-labels*
  ["Very Negative" "Negative" "Neutral" "Positive" "Very Positive"])

;;...

(defn get-sentiment-scores
  "Takes text and gives back a 0 to 4 sentiment score for each sentences."
  [text]
  ;;...)

(defn get-sentiment
  "Gives back a sentiment map with sentences scores,
   average score, rounded score and labeled score.
   Can accepts custom sentiment level labels under :labels opt."
  [text & {:keys [labels]}]
  (let [scores (get-sentiment-scores text)
        average-score (get-average scores)
        rounded-score (Math/round average-score)
        label (get (or labels *sentiment-level-labels*) rounded-score)]
    {:scores scores
     :average-score average-score
     :rounded-score rounded-score
     :label label}))
</code>```

Clojure library coding standards official page says:

If you present an interface that implicitly passes a parameter via
  dynamic binding (e.g. db in sql), also provide an identical interface
  but with the parameter passed explicitly.

https://dev.clojure.org/display/community/Library+Coding+Standards

In my example, I provided only one interface but with opt argument.

Is this okay? Are there better ways to handle this?

Thank you!

答:
Dynamic vars are full or pitfalls. They push your API code towards implicit environmental coupling, and often force your calling code to add a lot of (binding ...) clauses, which kind of defeats the purpose of concision for using Dynamic vars in the first place. They also lead to tricky edge cases if control is passed from one thread to another.

In your case, I would recommend simply passing the labels in a params map argument:

```<code>(def default-sentiment-level-labels
  ["Very Negative" "Negative" "Neutral" "Positive" "Very Positive"])

(defn get-sentiment
  "Gives back a sentiment map with sentences scores,
   average score, rounded score and labeled score.
   Can accepts custom sentiment level labels under :labels opt."
  [text {:as params, :keys [labels] :or {labels default-sentiment-labels}}]
  ...))
</code>```

Note that the usage of a map can be interesting, because a map is opaque to intermediaries: you can have various components of your algorithm read only from the params map the keys that concern them.

Title: Dynamic variables in Clojure libraries

Body:
TL;DR: Is the following a good pattern for a library?

(def ^{:dynamic true} *var*)
(defn my-fn [{:keys [var]}]
  (do-smth (or var *var*)))

--

Say I want to write a sentiment analysis library.

Is it good design in get-sentiment fn to accept optional sentiment labels but provide default one as dynamic var?

(def ^:dynamic *sentiment-level-labels*
  ["Very Negative" "Negative" "Neutral" "Positive" "Very Positive"])

;;...

(defn get-sentiment-scores
  "Takes text and gives back a 0 to 4 sentiment score for each sentences."
  [text]
  ;;...)

(defn get-sentiment
  "Gives back a sentiment map with sentences scores,
   average score, rounded score and labeled score.
   Can accepts custom sentiment level labels under :labels opt."
  [text & {:keys [labels]}]
  (let [scores (get-sentiment-scores text)
        average-score (get-average scores)
        rounded-score (Math/round average-score)
        label (get (or labels *sentiment-level-labels*) rounded-score)]
    {:scores scores
     :average-score average-score
     :rounded-score rounded-score
     :label label}))

Clojure library coding standards official page says:

If you present an interface that implicitly passes a parameter via
  dynamic binding (e.g. db in sql), also provide an identical interface
  but with the parameter passed explicitly.

https://dev.clojure.org/display/community/Library+Coding+Standards

In my example, I provided only one interface but with opt argument.

Is this okay? Are there better ways to handle this?

Thank you!

Body:
Dynamic vars are full or pitfalls. They push your API code towards implicit environmental coupling, and often force your calling code to add a lot of (binding ...) clauses, which kind of defeats the purpose of concision for using Dynamic vars in the first place. They also lead to tricky edge cases if control is passed from one thread to another.

In your case, I would recommend simply passing the labels in a params map argument:

(def default-sentiment-level-labels
  ["Very Negative" "Negative" "Neutral" "Positive" "Very Positive"])

(defn get-sentiment
  "Gives back a sentiment map with sentences scores,
   average score, rounded score and labeled score.
   Can accepts custom sentiment level labels under :labels opt."
  [text {:as params, :keys [labels] :or {labels default-sentiment-labels}}]
  ...))

Note that the usage of a map can be interesting, because a map is opaque to intermediaries: you can have various components of your algorithm read only from the params map the keys that concern them.


问:
How can I vectorize an IF block using ARM Neon intrinsics?
I want to process a large array of floating-point numbers on the ARM processor,
using Neon technology to calculate them four at a time.  Everything's fine for operations like add and multiply, but what do I do if my calculation goes into an IF block?  Example:

```<code>// In the non-vectorized original code, A is an array of many floating-point
// numbers, which are calculated one at a time.  Now they're packed
// into a vector and processed four at a time

...calculate A...

if (A > 10.f)
{
    A = A+5.f;
}
else
{
    A = A+10.f;
}
</code>```

Now, which IF branch do I execute?  What if some of the values in the vector being processed are greater than 10 and some are less?  Is it even possible to vectorize code like this?

答:
If-else slaloms are a nightmare for virtually all CPUs, especially for vector machines such as NEON that doesn't have any conditional branch on its own.

Hence we apply "eager execution" on problems like this.

A boolean mask gets created

Both if and else blocks are computed

The "right" result gets selected by the mask

I think it won't be problem converting the aarch32 code below to intrinsics.

```<code>//aarch32
    vadd.f32    vecElse, vecA, vecTen // vecTen contains 10.0f
    vcgt.f32    vecMask, vecA, vecTen
    vadd.f32    vecA, vecA, vecFive
    vbif        vecA, vecElse, vecMask

//aarch64
    fadd    vecElse.4s, vecA.4s, vecTen.4s
    fcmgt   vecMask.4s, vecA.4s, vecTen.4s
    fadd    vecA.4s, vecA.4s, vecFive.4s
    bif     vecA.16b, vecElse.16b, vecMask.16b
</code>```

Body:
I want to process a large array of floating-point numbers on the ARM processor,
using Neon technology to calculate them four at a time.  Everything's fine for operations like add and multiply, but what do I do if my calculation goes into an IF block?  Example:

// In the non-vectorized original code, A is an array of many floating-point
// numbers, which are calculated one at a time.  Now they're packed
// into a vector and processed four at a time

...calculate A...

if (A > 10.f)
{
    A = A+5.f;
}
else
{
    A = A+10.f;
}

Now, which IF branch do I execute?  What if some of the values in the vector being processed are greater than 10 and some are less?  Is it even possible to vectorize code like this?

Body:
If-else slaloms are a nightmare for virtually all CPUs, especially for vector machines such as NEON that doesn't have any conditional branch on its own.

Hence we apply "eager execution" on problems like this.

A boolean mask gets created

Both if and else blocks are computed

The "right" result gets selected by the mask

I think it won't be problem converting the aarch32 code below to intrinsics.

//aarch32
    vadd.f32    vecElse, vecA, vecTen // vecTen contains 10.0f
    vcgt.f32    vecMask, vecA, vecTen
    vadd.f32    vecA, vecA, vecFive
    vbif        vecA, vecElse, vecMask

//aarch64
    fadd    vecElse.4s, vecA.4s, vecTen.4s
    fcmgt   vecMask.4s, vecA.4s, vecTen.4s
    fadd    vecA.4s, vecA.4s, vecFive.4s
    bif     vecA.16b, vecElse.16b, vecMask.16b


问:
Xamarin.iOS : Native Linking Error: Is there a limit on No. of files in IOS?
We are working on a large Xamarin.Forms project, the customer wanted Android release first, so we complete the entire Android project and delivered it, now when we have started working on IOS project, we are facing challenges as we keep adding more forms to the IOS project. Some of the errors are

Error # 1.
Native linking error: don't know how to convert instruction ec7acce4 referencing _mono_create_corlib_exception_0.island to thumb in
'# _object_System_Type_object_System_Globalization_CultureInfo'
from /#.iOS/1db41bf625bf2eb66083739a668e7273/obj/iPhone/Debug/mtouch-cache/#.dll.armv7.o for architecture armv7 iOS

Error # 2.
Got a SIGSEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.

Since we were not making any headway, we started creating a new Solution in Xamarin.forms and started adding one Form in each Android and IOS, it worked fine until a specific number of files count, after that we started getting the same errors again in IOS.
the project works fine with about 867 files. (PCL - 638 files, ios - 107 files, Android - 122 files)

As soon as I add a new set of forms to PCL project, I get the above error #1, or Error # 2 in IOS project. The Android project works fine.
There is no sequence of the error, any of the above error just comes up, after I reduce the file count, the error is gone

Is there a limitation to the number of Forms in IOS? or Is there any limitation on the binary size. As per my understanding, IOS allows up to 100 MB in binaries. My current IOS binary is about 55 MB

I am stuck and not able to find any solution till now. Have already tried upgrading/downgrading Xamarin.forms versions, but no help, currently on Xamarin.forms 2.3.4.224
Xamrin.ios 10.3.1.8
Xamarin.Android 7.0.2.42
Xamarin 4.2.2.11
visual studio 2015 Professional

Also tried compiling and opening the project on MAC, visual studio 2017 Professional, getting same error
Also tried compiling on Xamarin studio on MAC, still getting same error.

答:
It seems the native code Xamarin generates for one of your assemblies ends up hitting size limitations in the native (Mach-O) file format.

Solution:

One of the solution from similar cases is adding --mono:framework to the "Additional mtouch arguments" at iOS Platform->Properties->iOS Build.

Then the mono runtime will be included as a framework in the app, instead of linked statically into the main executable.

References:

https://bugzilla.xamarin.com/show_bug.cgi?id=51226

https://bugzilla.xamarin.com/show_bug.cgi?id=29615


问:
Creating a Slideshow in JQuery
I'm new to JQuery and l want to create a slideshow of images. I downloaded the latest version of jquery.
Here is my html code

```<code>   <!DOCTYPE html>
   <html>
   <head>

   <script src="jquery-3.2.1.min.js"></script>
   <script src="jq.js"></script>
   <link rel="stylesheet" type="text/css" href="stl.css">

   </head>
   <body>

   <div id = "slideshow">

    <img src="images/chale-wote.jpg">
    <img src="images/accranight2.jpg">
    <img src="images/accra1.jpg">
    <img src="images/holidayinn.jpg">
    <img src="images/elmina.jpg">

    </div>

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

Here is my JQUERY code,l saved it as jq.js

```<code>      $("#slideshow > div").hide();

      setInterval(function() {
      $('#slideshow > div:first')
      .fadeOut(1000)
      .next()
      .fadeIn(1000)
      .end()
      .appendTo('#slideshow');
       },  5000);
</code>```

When l run it doesn't work. Any help is appreciated. Thanks

答:
In your HTML code you have img inside #slideshow. But in your jq you try to hide and show div inside #slideshow. Which do not exist.

Change your code to below

$("#slideshow img").hide();

setInterval(function() {
  $('#slideshow > img:first')
    .fadeOut(1000)
    .next()
    .fadeIn(1000)
    .end()
    .appendTo('#slideshow');
}, 3000);```
<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 id="slideshow">

  <img src="http://via.placeholder.com/350x150">
  <img src="http://via.placeholder.com/450x250">
  <img src="http://via.placeholder.com/250x250">
  <img src="http://via.placeholder.com/450x150">
  <img src="http://via.placeholder.com/350x100">
</div></code>```

Title: Creating a Slideshow in JQuery

Body:
I'm new to JQuery and l want to create a slideshow of images. I downloaded the latest version of jquery.
Here is my html code

   <!DOCTYPE html>

   <link rel="stylesheet" type="text/css" href="stl.css">

Here is my JQUERY code,l saved it as jq.js

      $("#slideshow > div").hide();

      setInterval(function() {
      $('#slideshow > div:first')
      .fadeOut(1000)
      .next()
      .fadeIn(1000)
      .end()
      .appendTo('#slideshow');
       },  5000);

When l run it doesn't work. Any help is appreciated. Thanks

Body:
In your HTML code you have img inside #slideshow. But in your jq you try to hide and show div inside #slideshow. Which do not exist.

Change your code to below

$("#slideshow img").hide();

setInterval(function() {
  $('#slideshow > img:first')
    .fadeOut(1000)
    .next()
    .fadeIn(1000)
    .end()
    .appendTo('#slideshow');
}, 3000);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slideshow">

  <img src="http://via.placeholder.com/350x150">
  <img src="http://via.placeholder.com/450x250">
  <img src="http://via.placeholder.com/250x250">
  <img src="http://via.placeholder.com/450x150">
  <img src="http://via.placeholder.com/350x100">
</div>


问:
Where is OnLevelWasLoaded on Unity 5?
In this new unity version, I think SceneManager is used. But I cant find how to do on level was loaded with SceneManager.

The old way :

```<code>void OnLevelWasLoaded(){
// do something
}
</code>```

When I try the old way I get this:

OnLevelWasLoaded was found on MusicManager
  This message has been deprecated and will be removed in a later version of Unity.
  Add a delegate to SceneManager.sceneLoaded instead to get notifications after scene loading has completed

I dont know how to use

```<code>SceneManager.sceneLoaded();
</code>```

Dont know what to pass...

答:
This is well explained in this post:

The old way:

```<code> void OnLevelWasLoaded (int level)
 {
 //Do Something
 }
</code>```

The new way:

```<code>     using UnityEngine.SceneManagement;
             void OnEnable()
             {
              //Tell our 'OnLevelFinishedLoading' function to start listening for a scene change as soon as this script is enabled.
                 SceneManager.sceneLoaded += OnLevelFinishedLoading;
             }

             void OnDisable()
             {
             //Tell our 'OnLevelFinishedLoading' function to stop listening for a scene change as soon as this script is disabled.
//Remember to always have an unsubscription for every delegate you
  subscribe to!
                 SceneManager.sceneLoaded -= OnLevelFinishedLoading;
             }

             void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode)
             {
                 Debug.Log("Level Loaded");
                 Debug.Log(scene.name);
                 Debug.Log(mode);
             }
</code>```

Note that 'OnLevelFinishedLoading' is a name that I've made up. You
  can name your method whatever you like.

What you're seeing in the OnEnable and OnDisable functions are
  delegate subscriptions. This simply means that we are setting a
  function of our choice (in this case, OnLevelFinishedLoading) to
  listen to the SceneManager for a level change.

Also note, that since this delegate has two parameters (Scene and
  SceneMode), that you must include those two parameters as well - even
  if you don't plan on using that information in your function.

Title: Where is OnLevelWasLoaded on Unity 5?

Body:
In this new unity version, I think SceneManager is used. But I cant find how to do on level was loaded with SceneManager.

The old way :

void OnLevelWasLoaded(){
// do something
}

When I try the old way I get this:

OnLevelWasLoaded was found on MusicManager
  This message has been deprecated and will be removed in a later version of Unity.
  Add a delegate to SceneManager.sceneLoaded instead to get notifications after scene loading has completed

I dont know how to use

SceneManager.sceneLoaded();

Dont know what to pass...

Body:
This is well explained in this post:

The old way:

 void OnLevelWasLoaded (int level)
 {
 //Do Something
 }

The new way:

     using UnityEngine.SceneManagement;
             void OnEnable()
             {
              //Tell our 'OnLevelFinishedLoading' function to start listening for a scene change as soon as this script is enabled.
                 SceneManager.sceneLoaded += OnLevelFinishedLoading;
             }

             void OnDisable()
             {
             //Tell our 'OnLevelFinishedLoading' function to stop listening for a scene change as soon as this script is disabled.
//Remember to always have an unsubscription for every delegate you
  subscribe to!
                 SceneManager.sceneLoaded -= OnLevelFinishedLoading;
             }

             void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode)
             {
                 Debug.Log("Level Loaded");
                 Debug.Log(scene.name);
                 Debug.Log(mode);
             }

Note that 'OnLevelFinishedLoading' is a name that I've made up. You
  can name your method whatever you like.

What you're seeing in the OnEnable and OnDisable functions are
  delegate subscriptions. This simply means that we are setting a
  function of our choice (in this case, OnLevelFinishedLoading) to
  listen to the SceneManager for a level change.

Also note, that since this delegate has two parameters (Scene and
  SceneMode), that you must include those two parameters as well - even
  if you don't plan on using that information in your function.


问:
removing black dots from image using OpenCV and Python
I am trying to compare two images and need to pre-process/clean one of them which is a scanned copy before comparing with a digital copy.
Scanned copy /
Digital copy

I ran this code on the scanned image and got an output which has numerous black dots. Not sure how to clean these up so that I can compare with the digital copy

```<code>img = cv2.multiply(img, 1.2)
kernel = np.ones((1, 1), np.uint8)
img = cv2.erode(img, kernel, iterations=1)
kernel1 = np.zeros( (9,9), np.float32)
kernel1[4,4] = 2.0
boxFilter = np.ones( (9,9), np.float32) / 81.0
kernel1 = kernel1 - boxFilter
img = cv2.filter2D(img, -1, kernel1)
</code>```

below is the output I got

答: Try apply filter in frequency domain, your image after FFT will have regular bright dots, because your image noise. If you will remove these dots and make inverse FFT transform you will remove dots from your image. Check this examples please: example1 , example2 and example3.</p>

Body:
I am trying to compare two images and need to pre-process/clean one of them which is a scanned copy before comparing with a digital copy.
Scanned copy /
Digital copy

I ran this code on the scanned image and got an output which has numerous black dots. Not sure how to clean these up so that I can compare with the digital copy

img = cv2.multiply(img, 1.2)
kernel = np.ones((1, 1), np.uint8)
img = cv2.erode(img, kernel, iterations=1)
kernel1 = np.zeros( (9,9), np.float32)
kernel1[4,4] = 2.0
boxFilter = np.ones( (9,9), np.float32) / 81.0
kernel1 = kernel1 - boxFilter
img = cv2.filter2D(img, -1, kernel1)

below is the output I got


问:
Removing max and min elements of array from mean calculation
I am hoping to delete the highest number and the lowest number from the array 3*4. Let's say, the data looks like this:

```<code>a=np.array([[1,4,5,10],[2,6,5,0],[3,9,9,0]])
</code>```

so I expected to see the result like this:
    deleted_data=[4,5],[2,5],[3]

Could you advise me how to delete the max and min from each array?

to do so, I did like this (UPDATE):

```<code>#to find out the max / min values:
b = np.max(a,1) #max
c = np.min(a,1) #min

#creating dataset after deleting max & min
d=(a!=b[:,None]) & (a!=c[:,None])
f=[i[j] for i,j in zip(a, d)]

output: [array([8, 7, 7, 9, 9, 8]), array([8, 7, 8, 6, 8, 8]), array([9, 8, 9, 9, 8]), array([6, 7, 7, 6, 6, 7]), array([7, 7, 7, 7, 6])]
</code>```

Now I am not sure how to calculate the mean of the list objects?
I would like to calculate the mean of each array, so I have tried this:

```<code>mean1=f.mean(axis=0)
</code>```

but it did not work.

答:
You could get to the final destination of average of elements that are not the max or min per row in two steps with masking -

```<code>In [140]: a  # input array
Out[140]:
array([[ 1,  4,  5, 10],
       [ 2,  6,  5,  0],
       [ 3,  9,  9,  0]])

In [141]: m = (a!=a.min(1,keepdims=1)) & (a!=a.max(1,keepdims=1))

In [142]: (a*m).sum(1)/m.sum(1).astype(float)
Out[142]: array([ 4.5,  3.5,  3. ])
</code>```

This avoids the mess of creating the intermediate ragged arrays, which arent the most convenient data formats to operate with NumPy funcs.

Alternatively, for performance boost, use np.einsum to get the equivalent of (a*m).sum(1) with np.einsum('ij,ij->i',a,m).

Runtime test on bigger array -

```<code>In [181]: np.random.seed(0)

In [182]: a = np.random.randint(0,10,(5000,5000))

# @Daniel F' soln from https://stackoverflow.com/a/47325431/
In [183]: %%timeit
     ...: mask = np.logical_or(a == a.max(1, keepdims = 1), a == a.min(1, keepdims = 1))
     ...: a_masked = ma.masked_array(a, mask = mask)
     ...: out = a_masked.mean(1).data
1 loop, best of 3: 251 ms per loop

# Posted in here
In [184]: %%timeit
     ...: m = (a!=a.min(1,keepdims=1)) & (a!=a.max(1,keepdims=1))
     ...: out = (a*m).sum(1)/m.sum(1).astype(float)
10 loops, best of 3: 165 ms per loop

# Posted in here with additional einsum
In [185]: %%timeit
     ...: m = (a!=a.min(1,keepdims=1)) & (a!=a.max(1,keepdims=1))
     ...: out = np.einsum('ij,ij->i',a,m)/m.sum(1).astype(float)
10 loops, best of 3: 124 ms per loop
</code>```

Body:
I am hoping to delete the highest number and the lowest number from the array 3*4. Let's say, the data looks like this:

a=np.array([[1,4,5,10],[2,6,5,0],[3,9,9,0]])

so I expected to see the result like this:
    deleted_data=[4,5],[2,5],[3]

Could you advise me how to delete the max and min from each array?

to do so, I did like this (UPDATE):

#to find out the max / min values:
b = np.max(a,1) #max
c = np.min(a,1) #min

#creating dataset after deleting max & min
d=(a!=b[:,None]) & (a!=c[:,None])
f=[i[j] for i,j in zip(a, d)]

output: [array([8, 7, 7, 9, 9, 8]), array([8, 7, 8, 6, 8, 8]), array([9, 8, 9, 9, 8]), array([6, 7, 7, 6, 6, 7]), array([7, 7, 7, 7, 6])]

Now I am not sure how to calculate the mean of the list objects?
I would like to calculate the mean of each array, so I have tried this:

mean1=f.mean(axis=0)

but it did not work.

Body:
You could get to the final destination of average of elements that are not the max or min per row in two steps with masking -

In [140]: a  # input array
Out[140]:
array([[ 1,  4,  5, 10],
       [ 2,  6,  5,  0],
       [ 3,  9,  9,  0]])

In [141]: m = (a!=a.min(1,keepdims=1)) & (a!=a.max(1,keepdims=1))

In [142]: (a*m).sum(1)/m.sum(1).astype(float)
Out[142]: array([ 4.5,  3.5,  3. ])

This avoids the mess of creating the intermediate ragged arrays, which arent the most convenient data formats to operate with NumPy funcs.

Alternatively, for performance boost, use np.einsum to get the equivalent of (a*m).sum(1) with np.einsum('ij,ij->i',a,m).

Runtime test on bigger array -

In [181]: np.random.seed(0)

In [182]: a = np.random.randint(0,10,(5000,5000))

# @Daniel F' soln from https://stackoverflow.com/a/47325431/
In [183]: %%timeit
     ...: mask = np.logical_or(a == a.max(1, keepdims = 1), a == a.min(1, keepdims = 1))
     ...: a_masked = ma.masked_array(a, mask = mask)
     ...: out = a_masked.mean(1).data
1 loop, best of 3: 251 ms per loop

# Posted in here
In [184]: %%timeit
     ...: m = (a!=a.min(1,keepdims=1)) & (a!=a.max(1,keepdims=1))
     ...: out = (a*m).sum(1)/m.sum(1).astype(float)
10 loops, best of 3: 165 ms per loop

# Posted in here with additional einsum
In [185]: %%timeit
     ...: m = (a!=a.min(1,keepdims=1)) & (a!=a.max(1,keepdims=1))
     ...: out = np.einsum('ij,ij->i',a,m)/m.sum(1).astype(float)
10 loops, best of 3: 124 ms per loop


问:
How does type coercion for numpy arrays work?
Numpy imported as np here:

```<code>np.array([True, 1, 2]) + np.array([3, 4, False])
</code>```

Which results in:

```<code>array([4, 5, 2])
</code>```

In this example boolean changed to int. I assumed it's because of the operation.

```<code>np.array([True,1,2])
</code>```

Which results in:

```<code>array(1,1,2)
</code>```

Using a string seems it took the priority and changed int to string.

```<code>np.array(["True", 1, 2])
</code>```

results in

```<code>array(['True', '1', '2'], dtype='<U4')

in [4]: np.array([0, 1, 2, 3, 'a', True])
Out[4]:
array(['0', '1', '2', '3', 'a', 'True'], dtype='<U21')`
</code>```

It now seems string takes highest priority, and not the number of objects of certain type. Why does it return dtype='<U4'/'U1'?

How exactly does this work?

Can I use this property to make change non-zero integers to be True and  and zero as False or I have to use compare operator?

答:
The answer is partially contained in your question. Boolean type has implicit conversion to other numeric types since it is just 0 or 1, allowing e.g. arithmetic operations with masks. Numbers are also easily convertible to characters, giving you strings. But the other way around, assigning a str value to int does not work straight out of the box. That's why when you add a string to your array, it gets immediately generalized to the str type. When using dtype it returns U#, where # is dictated by the length of your string array, as far as I know, see the official docs here.
Conversion from numeric arrays to bool works exactly as you specified, if an element is non-zero it returns True, otherwise False. Example:

```<code>a=np.array([0.0,1.5,0,1e8,-3])

for b in a:
    if b: print ("hi there")
    else: print ("go away!")
</code>```

Effectively a values are treated as [False,True,False,True,True]

ContentLicense: CC BY-SA 4.0

Body:
Numpy imported as np here:

np.array([True, 1, 2]) + np.array([3, 4, False])

Which results in:

array([4, 5, 2])

In this example boolean changed to int. I assumed it's because of the operation.

np.array([True,1,2])

Which results in:

array(1,1,2)

Using a string seems it took the priority and changed int to string.

np.array(["True", 1, 2])

results in

array(['True', '1', '2'], dtype='<U4')

in [4]: np.array([0, 1, 2, 3, 'a', True])
Out[4]:
array(['0', '1', '2', '3', 'a', 'True'], dtype='<U21')`

It now seems string takes highest priority, and not the number of objects of certain type. Why does it return dtype='<U4'/'U1'?

How exactly does this work?

Can I use this property to make change non-zero integers to be True and  and zero as False or I have to use compare operator?

Body:
The answer is partially contained in your question. Boolean type has implicit conversion to other numeric types since it is just 0 or 1, allowing e.g. arithmetic operations with masks. Numbers are also easily convertible to characters, giving you strings. But the other way around, assigning a str value to int does not work straight out of the box. That's why when you add a string to your array, it gets immediately generalized to the str type. When using dtype it returns U#, where # is dictated by the length of your string array, as far as I know, see the official docs here.
Conversion from numeric arrays to bool works exactly as you specified, if an element is non-zero it returns True, otherwise False. Example:

a=np.array([0.0,1.5,0,1e8,-3])

for b in a:
    if b: print ("hi there")
    else: print ("go away!")

Effectively a values are treated as [False,True,False,True,True]


问:
Determine where a gmail add-on is running
I'm developing an add-on for gmail and I'd like it to show different texts depending on whether it's running on the browser or on the android app, but I don't know if it's possible.

I've tried using HtmlService.getUserAgent() and the deprecated UiApp.getUserAgent(), but both of them return null; and I haven't found any other possibilities on the documentation.

Can anyone help on this? Thanks!

答: Solved. The function provided as onTriggerFunction of the appsscript.json file has an event parameter with a clientPlatform property that can be either 'web' or 'android'.


问:
Query work in localhost, but not in live
I need to make iframe url, for example:

```<code>https://url.com/category/{category_name)/t=desktop || /t=mobile.
</code>```

I'm using MAMP to run my local dev env and i got it working like it should be, when query string is equal to desktop it shows 3 posts and when mobile then only one post. Now the issue is following, when sysadmin is updating pre-live env he can see from logs this error:

```<code>[Wed Nov 15 20:09:42.122140 2017] [:error] [pid 7776] [client 10.1.2.66:41696] PHP Parse error: syntax error, unexpected end of file, expecting elseif (T_ELSEIF) or else (T_ELSE) or endif (T_ENDIF) in /var/lib/wordpress/wp-content/themes/wpTheme2/single_iframe.php on line 234
</code>```

single-iframe.php full code: https://pastebin.com/MBC6thDW

When i'm trying to go test url i'm either getting Error 500 or header with query function just printed  out.

I'm using PhpStorm IDE and it doesn't show any errors in my code, what i'm missing here?

答:
It is because of shorttags.
In your localhost environment using "< ?" is enabled, in your development server it is not enabled. That is the only reason.

http://php.net/manual/en/language.basic-syntax.phptags.php

So, just replace "< ?" with "< ?php", and it will work ok.

Body:
I need to make iframe url, for example:

https://url.com/category/{category_name)/t=desktop || /t=mobile.

I'm using MAMP to run my local dev env and i got it working like it should be, when query string is equal to desktop it shows 3 posts and when mobile then only one post. Now the issue is following, when sysadmin is updating pre-live env he can see from logs this error:

[Wed Nov 15 20:09:42.122140 2017] [:error] [pid 7776] [client 10.1.2.66:41696] PHP Parse error: syntax error, unexpected end of file, expecting elseif (T_ELSEIF) or else (T_ELSE) or endif (T_ENDIF) in /var/lib/wordpress/wp-content/themes/wpTheme2/single_iframe.php on line 234

single-iframe.php full code: https://pastebin.com/MBC6thDW

When i'm trying to go test url i'm either getting Error 500 or header with query function just printed  out.

I'm using PhpStorm IDE and it doesn't show any errors in my code, what i'm missing here?


问:
qtip doesnt display tip point in ie6 and ie7
```<code>$("#testing").qtip({
   content: 'Presets, presets and more presets. Let\'s spice it up a little with our own style!',
   style: {
      width: 200,
      padding: 5,
      background: '#A2D959',
      color: 'black',
      textAlign: 'center',
      border: {
         width: 7,
         radius: 5,
         color: '#A2D959'
      },
      tip: 'topLeft',
      name: 'dark' // Inherit the rest of the attributes from the preset dark style
   }
});
</code>```

HTML:

```<code><font id="testing">Test</font>
</code>```

Above codes works fine in all browser except ie6 and ie7

IE6 & IE7: Tool tip point is not displayed [i had mentioned as tip:'topLeft' but tip not appears in ie6 and ie7]

Thanks in advance...

答:
Does not work for me very good too on IE6 & IE7, http://www.jsfiddle.net/G4gU6/.

Actually for me it is just the css which seems to be misunderstood by the IE6 & IE7. You could try to fix it by applying your own css or rewrite the qTip2 css.

For more professional help on that refere to qTip2 Forum. Craig will help you ;)

a bit of search on google ;)

Body:
$("#testing").qtip({
   content: 'Presets, presets and more presets. Let\'s spice it up a little with our own style!',
   style: {
      width: 200,
      padding: 5,
      background: '#A2D959',
      color: 'black',
      textAlign: 'center',
      border: {
         width: 7,
         radius: 5,
         color: '#A2D959'
      },
      tip: 'topLeft',
      name: 'dark' // Inherit the rest of the attributes from the preset dark style
   }
});

HTML:

Test

Above codes works fine in all browser except ie6 and ie7

IE6 & IE7: Tool tip point is not displayed [i had mentioned as tip:'topLeft' but tip not appears in ie6 and ie7]

Thanks in advance...


问:
How can I make an image function as a button, and make it perform an action when clicked ( start a keyframe event, run a script)?
I've just started coding at school, and our teacher is horrible. I have to teach myself how to code, and for that reason, I've come here seeking help :). I've created this website using some simple html and css, and what I would like now is for the image I'm using in my navigation bar to act as a button, and when pressed, do something cool, like make an animation, or start a keyframe event where a few keyframes that I've set will trigger (like blinking text) or maybe even run a cool javascript. This is mostly for show, but at the same time, I'm here to learn. If my code is poorly written, feel free to correct it. Thank you.

HTML

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <link rel="icon" href="bilde.png">
    <meta charset="UTF-8">
    <title>Bully</title>
</head>
<body>
<link rel="stylesheet" type="text/css" href="css/stil2.css">
</center>
<center><ul class="navigation">
   <li><a href="bully2.html">Home</a></li>
  <li><a href="contact.html">Contact</a></li>
 <li><a href="" target="_blank">
         [This is that I want to use as a button ->] <img src="bilde.png" alt="Emblem" style="width:120px;height:120px;border:0";>
        </a>
  <li><a href="orbok2.html">Gallery</a></li>
  <li><a href="Lore.html">Lore</a></li>
</ul>

<ul class="flex-container">
    <li class="flex-item" style="font-size:42px;"><h1>~Breaking News~</h1>
  <li class="flex-item"><h1><ins>26. October, 2017.</ins></h1><br><a style="font-size:32px;">The release of the videogame "Bully 2" has just been confirmed, according to a variety of different reliable sources. Spokesperson Bad Andy from Bullworth Chess Club confirmed the release date of Bully 2 to be on January 1st of 2019. "Bully's long-awaited sequel will be a tremendous success in today's videogame-industry," said Andy in an interview with Russel Barro, owner of The Bullworth Herald.<br></a><h2>~Jimmy Hopkins~</h2></li>
  <center><ul class="flex-container">
  <center><li class="flex-item"><h1><ins>18. October, 2017.</ins></h1><br><a style="font-size:32px;">Fire alarm was set off at 11:24 by unknown student or person. Faculty and staff encourage all students to send in clues and tips about the incident to: Bullworthacademy@edu.com</a><br><h2>~Staff~</h2></li>
  <center><ul class="flex-container">
  <center><li class="flex-item"><h1><ins>Bully 2 "confirmed" by R* insider?</ins></h1><br><a style="font-size:32px;">Trusted gtaforum.com-admin "Yan2295" made a post on April 21st saying this: <br> <br> </a>
  <img src="yan.png" style="border:2.5px solid black;width:65%;height:250px;">
  </p><br><h2>~Russel Hustle~</h2></li>
</div>
</ul>

</body>
</html>

CSS
@import "compass/css3";

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
  }
body{
  background-image:url("brun.jpeg");
  background-repeat:no-repeat;
  background-size:1270px;
  background-attachment:fixed;
}

.flex-container {
  padding:0;
  margin:0;
  width:1000px;
  list-style: none;
  flex-direction:column;

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;

  -webkit-flex-flow: row-wrap;
  justify-content: center;
}

.flex-item {
  background-color: rgba(0, 0, 0, 0.25);
  margin-top: 0px;
  margin-bottom:0px;
  margin-left:0;
  border-top:0px solid ;
  border-left:3px solid rgba(0, 0, 0, 1);
  border-bottom:0px solid ;
  border-right:3px solid rgba(0, 0, 0, 1);
  border-radius:0px;
  padding-bottom:100px;
  padding-top:100px;

  line-height:40px;
  color:rgba(252, 174, 26, 255);
  font-weight: bold;
  font-size: 26px;
  font-family:NarcissusOpenSG;
  text-align:center;
  flex-grow: 0;
  justify-content:space-around;
  animation-name:text;
  animation-iteration-count:infinite;
  animation-duration:2s;
  animation-direction:alternate;
}
@keyframes jtext{

from {
  color:rgba(252, 174, 26, 255);
}
to{
    color:rgba(0, 0, 0, 0.5);
}
}
.navigation {
  list-style: none;
  border-top:3px solid black;
  border-bottom:0px solid black;
  width:994px;
  border-right:3px solid black;
  border-left:3px solid black;
  margin-top:5px;
  margin-bottom:0px;
  text-align:center;
  align-items:center;
  padding:0;
  border-top-left-radius:50px;
  border-top-right-radius:50px;
  background-color: rgba(0, 0, 0, 0.25);

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;

  -webkit-flex-flow: row wrap;
  justify-content:space-around;
  font-family:NarcissusOpenSG;
  font-size:28px;
}

.navigation a {
  text-decoration: none;
  display: block;
  padding:0;
  padding: 1em;
  opacity:0.5;
  transition-duration:0.5s;
  color:rgba(252, 174, 26, 255);
}

.navigation a:hover {
  color;
  background:;
  opacity:1;
  animation-duration:1.5s;
  animation-iteration-count:infinite;
  animation-name:blink;
  animation-direction:alternate;
}
keyframes blink {

from {
opacity:0.75;
  }

to {
opacity:0;
}
}
@media all and (max-width: 800px) {
  .navigation {
    justify-content: space-around;
  }
}

@media all and (max-width: 600px) {
  .navigation {
    -webkit-flex-flow: column wrap;
    flex-flow: column wrap;
  }

  .navigation a {
    text-align: center;
    padding:10px;
    border-top: 1px solid rgba(255,255,255,0.3);
    border-bottom: 1px solid rgba(0,0,0,0.1);
  }

  .navigation li:last-of-type a {
    border-bottom: 0;
}
</code>```

答:
You can do something like this with Jquery.

```<code><img src="yan.png" alt="image" id="image">
</code>```

And in your script put this code

```<code><script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript>
    $(document).ready(function(){
        $('#image').click(function(){
        alert('image clicked');
      });
    });
</script>
</code>```

In seated of an alert you can do something cool.

Body:
I've just started coding at school, and our teacher is horrible. I have to teach myself how to code, and for that reason, I've come here seeking help :). I've created this website using some simple html and css, and what I would like now is for the image I'm using in my navigation bar to act as a button, and when pressed, do something cool, like make an animation, or start a keyframe event where a few keyframes that I've set will trigger (like blinking text) or maybe even run a cool javascript. This is mostly for show, but at the same time, I'm here to learn. If my code is poorly written, feel free to correct it. Thank you.

HTML

<!DOCTYPE html>

    <link rel="icon" href="bilde.png">
    <meta charset="UTF-8">
    <title>Bully</title>

<link rel="stylesheet" type="text/css" href="css/stil2.css">

Home

Contact

         [This is that I want to use as a button ->]

Gallery

Lore

~Breaking News~

26. October, 2017.

The release of the videogame "Bully 2" has just been confirmed, according to a variety of different reliable sources. Spokesperson Bad Andy from Bullworth Chess Club confirmed the release date of Bully 2 to be on January 1st of 2019. "Bully's long-awaited sequel will be a tremendous success in today's videogame-industry," said Andy in an interview with Russel Barro, owner of The Bullworth Herald.

~Jimmy Hopkins~

18. October, 2017.

Fire alarm was set off at 11:24 by unknown student or person. Faculty and staff encourage all students to send in clues and tips about the incident to: Bullworthacademy@edu.com

~Staff~

Bully 2 "confirmed" by R* insider?

Trusted gtaforum.com-admin "Yan2295" made a post on April 21st saying this:

~Russel Hustle~

CSS
@import "compass/css3";

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
  }
body{
  background-image:url("brun.jpeg");
  background-repeat:no-repeat;
  background-size:1270px;
  background-attachment:fixed;
}

.flex-container {
  padding:0;
  margin:0;
  width:1000px;
  list-style: none;
  flex-direction:column;

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;

  -webkit-flex-flow: row-wrap;
  justify-content: center;
}

.flex-item {
  background-color: rgba(0, 0, 0, 0.25);
  margin-top: 0px;
  margin-bottom:0px;
  margin-left:0;
  border-top:0px solid ;
  border-left:3px solid rgba(0, 0, 0, 1);
  border-bottom:0px solid ;
  border-right:3px solid rgba(0, 0, 0, 1);
  border-radius:0px;
  padding-bottom:100px;
  padding-top:100px;

  line-height:40px;
  color:rgba(252, 174, 26, 255);
  font-weight: bold;
  font-size: 26px;
  font-family:NarcissusOpenSG;
  text-align:center;
  flex-grow: 0;
  justify-content:space-around;
  animation-name:text;
  animation-iteration-count:infinite;
  animation-duration:2s;
  animation-direction:alternate;
}
@keyframes jtext{

from {
  color:rgba(252, 174, 26, 255);
}
to{
    color:rgba(0, 0, 0, 0.5);
}
}
.navigation {
  list-style: none;
  border-top:3px solid black;
  border-bottom:0px solid black;
  width:994px;
  border-right:3px solid black;
  border-left:3px solid black;
  margin-top:5px;
  margin-bottom:0px;
  text-align:center;
  align-items:center;
  padding:0;
  border-top-left-radius:50px;
  border-top-right-radius:50px;
  background-color: rgba(0, 0, 0, 0.25);

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;

  -webkit-flex-flow: row wrap;
  justify-content:space-around;
  font-family:NarcissusOpenSG;
  font-size:28px;
}

.navigation a {
  text-decoration: none;
  display: block;
  padding:0;
  padding: 1em;
  opacity:0.5;
  transition-duration:0.5s;
  color:rgba(252, 174, 26, 255);
}

.navigation a:hover {
  color;
  background:;
  opacity:1;
  animation-duration:1.5s;
  animation-iteration-count:infinite;
  animation-name:blink;
  animation-direction:alternate;
}
keyframes blink {

from {
opacity:0.75;
  }

to {
opacity:0;
}
}
@media all and (max-width: 800px) {
  .navigation {
    justify-content: space-around;
  }
}

@media all and (max-width: 600px) {
  .navigation {
    -webkit-flex-flow: column wrap;
    flex-flow: column wrap;
  }

  .navigation a {
    text-align: center;
    padding:10px;
    border-top: 1px solid rgba(255,255,255,0.3);
    border-bottom: 1px solid rgba(0,0,0,0.1);
  }

  .navigation li:last-of-type a {
    border-bottom: 0;
}

Body:
You can do something like this with Jquery.

<img src="yan.png" alt="image" id="image">

And in your script put this code

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript>
    $(document).ready(function(){
        $('#image').click(function(){
        alert('image clicked');
      });
    });
</script>

In seated of an alert you can do something cool.


问:
is there any lib is available for splitting xml file based on tags in spark?
I try to split the XML file in Spark Scala. I find the JAXB lib for splitting the XML data in Java but I couldn't find any lib for Spark Scala. Is there any lib is available?

Thank you in advance!

答: Have you tried the spark-xml lib ?</p>

Body: Have you tried the spark-xml lib ?


问:
Is it possible to deploy the Azure Functions in Local IIS?
I have created a HttpTrigger using Visual Studio 2017. I can able to debug and able to call the azure function from web browser using below mentioned URL.

localhost:7071/api/Demofunction?name=amit

I have published the Project in a Local Folder in my system. Is it possible to deploy the generated dlls in the Local IIS and call the API from browser? If Yes, then how to do this?

答:
If your primary concern is how to use Azure Functions on premises instead of using azure you can use the Azure Functions Runtime to deploy and run azure functions on premises:

The Azure Functions Runtime provides a new way for you to take advantage of the simplicity and flexibility of the Azure Functions programming model on-premises. Built on the same open source roots as Azure Functions, Azure Functions Runtime is deployed on-premises to provide a nearly identical development experience as the cloud service.