问:
Bootstrap container gets margin-top 0
Why does my .container main_container div hang on the header? (Its not because the 2 php error message, i tried)

If i give the div about 100px margin-top, it will be okay, but that isn't a good method.

After the header, I added a clearfix div, but it did nothing.

Fiddle

```<code>    <nav class="navbar navbar-default navbar-fixed-top mainHeader">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="<?php echo $host; ?>"><?php echo $siteName; ?></a>
    </div>
    <div id="navbar" class="navbar-collapse collapse">
      <ul class="nav navbar-nav navbar-right">
        <?php
        $top_menuDown = mysqli_query($kapcs, "SELECT * FROM top_menu WHERE top_menu_id IN (1,3,4,5,6,7) ORDER BY top_menu_sorrend ASC");
        if(mysqli_num_rows($top_menuDown) > 0 )
        {
            while($top_nav = mysqli_fetch_assoc($top_menuDown))
            {
                echo '<li><a class="top_menu_to_link" href="'.$host.'/'.$top_nav['top_menu_seo'].'" title="'.$top_nav['top_menu_nev'].'">'.$top_nav['top_menu_nev'].'</a></li>';
            }
        }
        ?>
      </ul>
    </div>
  </div>
</nav>
<div class="clearfix"></div>
</code>```

答:
This is because you use navbar-fixed-top class in your navbar. That's a Bootstrap class which makes your navbar position: fixed in CSS. Therefore you have to add margin-top or padding-top to your main_container. Clearfix has nothing to do with your issue in this case. When you use position: fixed browser get this element out of the normal document flow.

position: absolute/fixed:

The element is removed from the flow of the document and other elements will behave as if it’s not even there whilst all the other positional properties will work on it.

Title: Bootstrap container gets margin-top 0

Body:
Why does my .container main_container div hang on the header? (Its not because the 2 php error message, i tried)

If i give the div about 100px margin-top, it will be okay, but that isn't a good method.

After the header, I added a clearfix div, but it did nothing.

Fiddle

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        Toggle navigation

      </button>
      <a class="navbar-brand" href="<?php echo $host; ?>"><?php echo $siteName; ?>

        <?php
        $top_menuDown = mysqli_query($kapcs, "SELECT * FROM top_menu WHERE top_menu_id IN (1,3,4,5,6,7) ORDER BY top_menu_sorrend ASC");
        if(mysqli_num_rows($top_menuDown) > 0 )
        {
            while($top_nav = mysqli_fetch_assoc($top_menuDown))
            {
                echo '
'.$top_nav['top_menu_nev'].'
';
            }
        }
        ?>


来源: stackexchange

问:
How to decode a Base64 string into a Bitmap image in Android
Before you label this question as a repeat, look at my case, please. I have perused most of the references on this question, but they didn't work for me.

Here is what I have in my SAX Model:

```<code>    public class Parameter {
...

    //This is retrieved from a RESTful URL as xml and nicely mapped into this field
public String image_icon_data = "iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAYAAADimHc4AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAC3ZJREFUeNrsXQmUFcUVrVlYFQYYkSCQILKdaOJKFDc29QiKC2pwQzkSJ0gSUXED0eRkUONBDu67AnoEUTREOcRoFCWsRgUJkWVAHRRQQNmHgZmhfff0a6emprr/7/+7q/vP//ecOzP95/+u6npVr6ree/V+nmVZIofokBdzAeQTOxGLiR2JXYitiU2JjYkdiIXELcRdxCr+vZm4lriD+DVxb04AyaEF8WhiL+LpxK7EbsRDWBh+UUncSFxH/Ij4MXNTTgC1QO/uQzyP2JvYI8XGThYYLUuI84jvED/PVgGcShxKvIj484jqUEF8lziLOIdVVoMWQDPiYOJI4hmsv+OCNcRXiC8QNzQ0AUClXEkcTTwp5guTrSyEx4jfNAQB9CfeQTwnw1aI5cQHiVOJezJRAFgi3snqplBkLhYSxxM/yCQBXEb8G6/bGwL2Ex8lTiDujLMADuVKjm6gG1fsIUqIy+IogO48eZ3WwK0H27mDvRQnAZxJfJaFkA2oId5NfIB4MGoBYDP1HKufbANG/CieIyIRwHDiU8QmInsxg+eFPaYFgMZ/hthI5PAq8VphG/+MCOC3xGnCNgvnYAPt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xH3uYNVRzX/3sI+WRyGRkggAndxCLEybg8ZZwEkUl15bJGFCtorarOv4LxzVaY8yI8CDADuN4DtXCKkuQAAAABJRU5ErkJggg==";

public Bitmap getImageIcon() {
    if(image_icon_data!=null) {
        byte[] image_data = Base64.decode(image_icon_data, Base64.NO_WRAP);
        return BitmapFactory.decodeByteArray(image_data, 0, image_data.length);
    }
    return null;
    }
...
}
</code>```

Then in my MainActivity.java I have:

```<code>ImageView imageView_parameter_icon = (ImageView)findViewById(R.id.imageView_parameter_icon);
    imageView_parameter_icon.setImageBitmap(parameter.getImageIcon());
</code>```

And I get NOTHING!!

答:
SOLVED!
 I figured that I needed to set BitmapFactory.Options in order to specify the mime-type and the output image resolution being expected.
Here is how:

```<code>public Bitmap getImageIcon() {
    if(image_icon_data!=null) {
        byte[] image_data = Base64.decode(image_icon_data, Base64.NO_WRAP);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.outHeight = 32; //32 pixles
        options.outWidth = 32; //32 pixles
        options.outMimeType = image_icon_type; //this could be image/jpeg, image/png, etc

        return BitmapFactory.decodeByteArray(image_data, 0, image_data.length, options);
    }
    return null;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Before you label this question as a repeat, look at my case, please. I have perused most of the references on this question, but they didn't work for me.

Here is what I have in my SAX Model:

    public class Parameter {
...

    //This is retrieved from a RESTful URL as xml and nicely mapped into this field
public String image_icon_data = "iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAYAAADimHc4AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAC3ZJREFUeNrsXQmUFcUVrVlYFQYYkSCQILKdaOJKFDc29QiKC2pwQzkSJ0gSUXED0eRkUONBDu67AnoEUTREOcRoFCWsRgUJkWVAHRRQQNmHgZmhfff0a6emprr/7/+7q/vP//ecOzP95/+u6npVr6ree/V+nmVZIofokBdzAeQTOxGLiR2JXYitiU2JjYkdiIXELcRdxCr+vZm4lriD+DVxb04AyaEF8WhiL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95DIRnTHesrNEijgKAOxoYIWECL7OSrmzQy5zpUtgV+wE4PBaDj8MA+Ot+tkew5qDKniZe3gY7RR2bmR41R61gs2GtYxYZNVNNvhZSI3/nlU/V3ZGCcDhSRzwFUQvHaLce0wIDY/Eftf5senEXQDyJD0rDYPeaxxELEdTbwuw4TGSRikjzHj2dBNAlqqr2W2Y7JGgCnaNykdKnxfuJ/H9hL3AzD6F43YqTDZEVAJw0JodJhex6aCdx3snEW+VrgewwyM/hXL3sCDhqHlD8Z6JbBKADDQ+gqb68e+jJR8u7C04v7uVr5HjB8FVJyd57/1srfyMPwcnDY7HRp6rIk4CUAE7fmc2tK3h3uoA/l18zwCCcxH3uYNVRzX/3sI+WRyGRkggAndxCLEybg8ZZwEkUl15bJGFCtorarOv4LxzVaY8yI8CDADuN4DtXCKkuQAAAABJRU5ErkJggg==";

public Bitmap getImageIcon() {
    if(image_icon_data!=null) {
        byte[] image_data = Base64.decode(image_icon_data, Base64.NO_WRAP);
        return BitmapFactory.decodeByteArray(image_data, 0, image_data.length);
    }
    return null;
    }
...
}

Then in my MainActivity.java I have:

ImageView imageView_parameter_icon = (ImageView)findViewById(R.id.imageView_parameter_icon);
    imageView_parameter_icon.setImageBitmap(parameter.getImageIcon());

And I get NOTHING!!

Body:
SOLVED!
 I figured that I needed to set BitmapFactory.Options in order to specify the mime-type and the output image resolution being expected.
Here is how:

public Bitmap getImageIcon() {
    if(image_icon_data!=null) {
        byte[] image_data = Base64.decode(image_icon_data, Base64.NO_WRAP);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.outHeight = 32; //32 pixles
        options.outWidth = 32; //32 pixles
        options.outMimeType = image_icon_type; //this could be image/jpeg, image/png, etc

        return BitmapFactory.decodeByteArray(image_data, 0, image_data.length, options);
    }
    return null;
}


问:
how do i remove one pin from a map view that has multiple pins
I add multiple pins to a map view based on a database. How do I remove certain pins based on title.

This is how I added the pins
var pinsArray: [MKPointAnnotation] = []

```<code>   for i in (0..<dbarray_id.count)
        {

            let annotation2 = MKPointAnnotation()
            annotation2.coordinate = CLLocationCoordinate2D(latitude: tmp_latitude, longitude: tmp_longitude)
            annotation2.title = dbarray_email[i]
            annotation2.subtitle = dbarray_geogroup[i]
            pinsArray.append(annotation2)
            map.addAnnotation(annotation2)
        }
</code>```

Later i want to certain pins. I tried

```<code>    for annotation_point in map.annotations
    {
        if annotation_point.title  ==  "POA"
        {
            map.removeAnnotation(annotation_point)
        }
    }
</code>```

But get error:  binary operator == cannot be applied to operands of type String?? and Sting

When I add a pin annotation I copy it to the array pinsArray.

So basically how do I remove a certain pin base on a criteria.

Thanks

答:
Try this:</p>

```<code>if let title = annotation_point.title, title  == "POA" {
    // Rest of the code goes here...
}
</code>```

Body:
I add multiple pins to a map view based on a database. How do I remove certain pins based on title.

This is how I added the pins
var pinsArray: [MKPointAnnotation] = []

   for i in (0..<dbarray_id.count)
        {

            let annotation2 = MKPointAnnotation()
            annotation2.coordinate = CLLocationCoordinate2D(latitude: tmp_latitude, longitude: tmp_longitude)
            annotation2.title = dbarray_email[i]
            annotation2.subtitle = dbarray_geogroup[i]
            pinsArray.append(annotation2)
            map.addAnnotation(annotation2)
        }

Later i want to certain pins. I tried

    for annotation_point in map.annotations
    {
        if annotation_point.title  ==  "POA"
        {
            map.removeAnnotation(annotation_point)
        }
    }

But get error:  binary operator == cannot be applied to operands of type String?? and Sting

When I add a pin annotation I copy it to the array pinsArray.

So basically how do I remove a certain pin base on a criteria.

Thanks

Body:
Try this:

if let title = annotation_point.title, title  == "POA" {
    // Rest of the code goes here...
}


Title: lodash's min returning wrong value from an array of negative values

Body:
I have this array of negative values:

["-117.911732", "-112.0756724", "-71.0595678", "-78.8783689", "-114.0833", "-78.6390779", "-87.6244212", "-104.9847034", "-83.0007065", "-96.7968994", "-83.0567375", "-113.5000", "-80.1936589", "-118.2427266", "-93.1015026", "-73.5833", "-86.78086153", "-74.1723667", "-73.9865812", "-73.9865812", "-75.7000", "-75.163789", "-79.9900861", "-121.8831349", "-90.1978889", "-82.458444", "-79.4167", "-123.1333", "-77.0366456", "-97.1667"]

Lodash's _.min function returns -104.9847034 instead of -123.1333 which is obviously wrong? What do I miss?

Here is the running example: http://codepen.io/neptune01/pen/XMOeVM

Body:
You have array of string so you need to first convert strings to numbers using _.map.

var arr = ["-117.911732", "-112.0756724", "-71.0595678", "-78.8783689", "-114.0833", "-78.6390779", "-87.6244212", "-104.9847034", "-83.0007065", "-96.7968994", "-83.0567375", "-113.5000", "-80.1936589", "-118.2427266", "-93.1015026", "-73.5833", "-86.78086153", "-74.1723667", "-73.9865812", "-73.9865812", "-75.7000", "-75.163789", "-79.9900861", "-121.8831349", "-90.1978889", "-82.458444", "-79.4167", "-123.1333", "-77.0366456", "-97.1667"];
console.log(_.min(_.map(arr, Number)))

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>


问:
Graph Theory: Queries with bounded edge weight in undirected graph
Given a weighted undirected graph of n <= 200000 nodes and m <= 200000 edges. Edge weights (integers) can be upto 1e9. There are q <= 200000 queries. Each query gives two nodes u v and a integer bound p (<= 1e9). If there's a path between u and v such that each edge weight in the path is <= p then answer is yes else no.

Notice that the path doesn't have to shortest. Just the maximum weight on the path is <= p. Naive approaches of course don't work. How to answer the queries fast (in O(n lg n) or something like that)?

答:
The problem that you describe is known as: Widest Path Problem and you can find it here: https://en.wikipedia.org/wiki/Widest_path_problem .

It could be easily proved that a path between u,v with the minimum maximum cost for each u,v is equal to the minimum spanning tree.So you need to find the minimum spanning tree in order to be sure that you have minimized the maximum cost in each path between two vertices u,v.

The difficult part is to decide for each query if the path from u to v has maximum cost less or equal than p.

The best approach would be using cartesian trees (described in the wikipedia linked) which will allow you to answer each query in constant time and I think building the cartesian tree would be O(nlogn) so overall O(nlogn + q).But this approach is difficult to implement.

I think what you're looking for is to use lowest common ancestor algorithm to answer in logn every query ,after you find the minimum spanning tree.So find minimum spanning tree (O(E log E)) and use lowest common ancestor with some preprocessing  to be able to answer each query in O(log n) so overall O( qlogn + ElogE). A very good approach to the Lowest Common Ancestor and the preprocessing could be found here: https://www.topcoder.com/community/data-science/data-science-tutorials/range-minimum-query-and-lowest-common-ancestor/
The article above describes very well all the solutions and gives enough help code useful to your problem.


问:
Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug'
I'm facing a problem when building project having multiDexEnabled is true in build.gradle

here is the error

**Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.

java.io.IOException: Can't read [APP_PATH/app/build/intermediates/transforms/CLASSES/FULL_PROJECT/jarMerging/debug/classes.jar] (Can't process class [i.class] (Unknown verification type [19] in stack map frame))**

here is the my gradle file

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion '23.0.1'
useLibrary  'org.apache.http.legacy'

defaultConfig {
    multiDexEnabled true
    applicationId "com.example.application"
    minSdkVersion 11
    targetSdkVersion 23
    versionCode 13
    versionName "2.4"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

}

dependencies {
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.squareup:android-times-square:1.6.4@aar'
compile files('libs/IDTUniPaySDK.jar')
compile files('libs/emv-bertlv-0.1.3-shaded.jar')
compile files('libs/audio.jar')
compile files('libs/bluebambooV4.4.jar')
compile 'ch.acra:acra:4.6.2'
compile 'com.google.code.ksoap2-android:ksoap2-android:3.4.0'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
}
</code>```

when i removed these two dependencies(1-compile files('libs/audio.jar')
2-compile files('libs/bluebambooV4.4.jar')) and also removed the reference code that used these 2 dependencies , my project works fine.

答:
This is what i did to fix this issue:

Go to File > project structure and
 - in section Modules, check for each module, if the Build tool version in Properties is equivalent to the Target Sdk version in Flavors.

Screenshot of the solution
log of my error:

Error:Execution failed for task
  ':app:transformClassesWithDexForRelease'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException:
    java.util.concurrent.ExecutionException:
    com.android.ide.common.process.ProcessException: Error while executing
    java process with main class com.android.dx.command.Main with
    arguments {--dex --num-threads=4 --multi-dex --main-dex-list
    ..\app\build\intermediates\multi-dex\release\maindexlist.txt --output
    ..\app\build\intermediates\transforms\dex\release\folders\1000\1f\main
    ..\app\build\intermediates\transforms\jarMerging\release\jars\1\1f\combined.jar}

Body:
I'm facing a problem when building project having multiDexEnabled is true in build.gradle

here is the error

**Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.

java.io.IOException: Can't read [APP_PATH/app/build/intermediates/transforms/CLASSES/FULL_PROJECT/jarMerging/debug/classes.jar] (Can't process class [i.class] (Unknown verification type [19] in stack map frame))**

here is the my gradle file

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion '23.0.1'
useLibrary  'org.apache.http.legacy'

defaultConfig {
    multiDexEnabled true
    applicationId "com.example.application"
    minSdkVersion 11
    targetSdkVersion 23
    versionCode 13
    versionName "2.4"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

}

dependencies {
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.squareup:android-times-square:1.6.4@aar'
compile files('libs/IDTUniPaySDK.jar')
compile files('libs/emv-bertlv-0.1.3-shaded.jar')
compile files('libs/audio.jar')
compile files('libs/bluebambooV4.4.jar')
compile 'ch.acra:acra:4.6.2'
compile 'com.google.code.ksoap2-android:ksoap2-android:3.4.0'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
}

when i removed these two dependencies(1-compile files('libs/audio.jar')
2-compile files('libs/bluebambooV4.4.jar')) and also removed the reference code that used these 2 dependencies , my project works fine.


问:
Jquery $("img").click(function() selector not working
For some reason when I click on an image with this JQuery code the alert screen doesn't show up.

HTML:

```<code><div id="example1">
 <div>
  <div>
   <div class="user">
    <img class="Image" src="images/image.jpg">
   </div>
  </div>
 </div>
</div>
</code>```

Javascript:

```<code>$(document).ready(function(){
 $("img").click(function(){
  alert("it works!");
 });
});
</code>```

I cant figure out why this isn't working I included the jquery library and the

答:
```<code> $(document).ready(function(){
    $(".Image").click(function(){
    alert("it works!");
   });
  });
</code>```

IF you want your code to work with out change just put .Image not img the class name not attribue name

Body:
For some reason when I click on an image with this JQuery code the alert screen doesn't show up.

HTML:

Javascript:

$(document).ready(function(){
 $("img").click(function(){
  alert("it works!");
 });
});

I cant figure out why this isn't working I included the jquery library and the

Body:
 $(document).ready(function(){
    $(".Image").click(function(){
    alert("it works!");
   });
  });

IF you want your code to work with out change just put .Image not img the class name not attribue name


问:
How do I map an associative array to html element attributes?
I'm building a basic form building class to speed my workflow up a bit and I'd like to be able to take an array of attributes like so:

```<code>$attributes = array(
   "type"         => "text",
   "id"           => "contact-name",
   "name"         => "contact-name",
   "required"     => true
);
</code>```

and map that to the attributes of a html element:

```<code><input type="text" id="contact-name" name="contact-name" required />
</code>```

EDIT:

What is the cleanest way of achieving the above? I'm sure I could cobble something together with a loop and some concatenation but I get the feeling printf or similar could do it in a more elegant manner.

答:
As http_build_query is meant for stringify associative array's, I hoped to stumble upon such a solution here. Didn't find one, so here's my 'one-liner':

```<code>$output = '<input ' . str_replace( '=', '="', http_build_query( $attributes, '', '" ') ) . '" />';
</code>```

Unfortunately:

it converts boolean-values to 1/0 (instead of ommiting them if false, which can be achieved by using array_filter, but results in double function-calls);

doesn't handle array's in a desired way;

Needs urldecode after http_build_query to get back the encoded spaces (for example, when having multiple html-classes in an attribute).

So, only suitable in certain situations!

Body:
I'm building a basic form building class to speed my workflow up a bit and I'd like to be able to take an array of attributes like so:

$attributes = array(
   "type"         => "text",
   "id"           => "contact-name",
   "name"         => "contact-name",
   "required"     => true
);

and map that to the attributes of a html element:

<input type="text" id="contact-name" name="contact-name" required />

EDIT:

What is the cleanest way of achieving the above? I'm sure I could cobble something together with a loop and some concatenation but I get the feeling printf or similar could do it in a more elegant manner.

Body:
As http_build_query is meant for stringify associative array's, I hoped to stumble upon such a solution here. Didn't find one, so here's my 'one-liner':

$output = '<input ' . str_replace( '=', '="', http_build_query( $attributes, '', '" ') ) . '" />';

Unfortunately:

it converts boolean-values to 1/0 (instead of ommiting them if false, which can be achieved by using array_filter, but results in double function-calls);

doesn't handle array's in a desired way;

Needs urldecode after http_build_query to get back the encoded spaces (for example, when having multiple html-classes in an attribute).

So, only suitable in certain situations!

ContentLicense: CC BY-SA 4.0


问:
Find a recursive algorithm complexity
I am not sure if I am calculating the complexity of a recursive algorithm correctly.

Could you please check it and tell if I am correct.

```<code>  public static long gcdMultiple(long[] input) {
        long result = input[0];
        for (int i = 1; i < input.length; i++) result = gcd(result, input[i]);
        return result;
    }

    public static final long gcd(long q, long p) {
        if (q == 0) return p;
        if (p == 0) return q;

        // p and q even
        if ((p & 1) == 0 && (q & 1) == 0) return gcd(p >> 1, q >> 1) << 1;

            // p is even, q is odd
        else if ((p & 1) == 0) return gcd(p >> 1, q);

            // p is odd, q is even
        else if ((q & 1) == 0) return gcd(p, q >> 1);

            // p and q odd, p >= q
        else if (p >= q) return gcd((p - q) >> 1, q);

            // p and q odd, p < q
        else return gcd(p, (q - p) >> 1);
    }
</code>```

First function gcdMultiple has the complexity equal to O(n), because it iterates n times where n is equal to number of items in the array passed to the function.
Second function is much complex, I really cannot figure out how to find its complexity, but I assume it is about O(nlog(n))
So the common complexity is nLog(n) * n = n^2log(n) = n^2
Am I right ?

Please explain how to calculate complexity correctly in my case.

答:
The inner function is binary GCD, and its complexity is O(log(p) + log(q)).
You can follow the link for details, but basically, at least one of the arguments is halved in O(1) steps, so no more than log(p) + log(q) steps are required to bring both p and q down to 1.

The outer loop runs n times, so basically, we have the upper bound O(n * log(c)) where c is the maximum possible element in the input array.

For an input consisting of n copies of the number 2k, the number of elementary operations is indeed n * k.
Note that k is proportional to log(c).
So the bound is exact.

Second function is much complex, I really cannot figure out how to find its complexity, but I assume it is about O(nlog(n))

As for your note above, and I assume n is the length of input: there is no n in the inner function in the first place.
Both arguments are just longs and don't depend on the number of inputs.

And as a side note, if we used Euclid's GCD in place of Stein's GCD as the inner function, I believe the overall complexity would go from O(n * log(c)) down to just O(n + log(c)).

Title: Find a recursive algorithm complexity

Body:
I am not sure if I am calculating the complexity of a recursive algorithm correctly.

Could you please check it and tell if I am correct.

  public static long gcdMultiple(long[] input) {
        long result = input[0];
        for (int i = 1; i < input.length; i++) result = gcd(result, input[i]);
        return result;
    }

    public static final long gcd(long q, long p) {
        if (q == 0) return p;
        if (p == 0) return q;

        // p and q even
        if ((p & 1) == 0 && (q & 1) == 0) return gcd(p >> 1, q >> 1) << 1;

            // p is even, q is odd
        else if ((p & 1) == 0) return gcd(p >> 1, q);

            // p is odd, q is even
        else if ((q & 1) == 0) return gcd(p, q >> 1);

            // p and q odd, p >= q
        else if (p >= q) return gcd((p - q) >> 1, q);

            // p and q odd, p < q
        else return gcd(p, (q - p) >> 1);
    }

First function gcdMultiple has the complexity equal to O(n), because it iterates n times where n is equal to number of items in the array passed to the function.
Second function is much complex, I really cannot figure out how to find its complexity, but I assume it is about O(nlog(n))
So the common complexity is nLog(n) * n = n^2log(n) = n^2
Am I right ?

Please explain how to calculate complexity correctly in my case.


问:
Bash script for iterating through defined set of file names and performing commands
I have a set of folders named for example 10, 12, 13, 14, 18, 24 etc. They don't change numbers in any standard increment. I then need to move repetitively into the folders and then into the next one to perform SVN commands which are the same except for some variable extension, e.g.:

```<code>/home/boy$ cp /home/files/*Session10.* . ; svn add *Session10.*; svn commit; cd ..; cd 12;
</code>```

Then the next command is analogous:

```<code>/home/boy$ cp /home/files/*Session12.* . ; svn add *Session12.*; svn commit; cd ..; cd 14;
</code>```

So there should be an array or list defined, and then a for loop through that list, and then a variable whose name is expanded to be fed into the cp and svn command.
Any thoughts? I hope that it can be done in the command prompt rather than in a bash script file.

答:
If the list is predefined and you're not iterating over every directory that exists (in other words, if a directory named 99 exists but it's not in your list you want to exclude it), you can iterate over the list:

```<code>list="10 12 13 14 18 24"; for dir in $list; do cd "$dir"; do_something "foo $dir bar"; done
</code>```

or an array:

```<code>array=(10 12 13 14 18 24); for idx in ${!array[@]}; do cd "${array[idx]}"; do_something "foo ${array[idx]} bar"; done
</code>```

You can do previous or next array elements like this: ${array[idx-1]} or ${array[idx+1]} if you do appropriate checks to make sure you're not trying to retrieve an element with a negative index (an index beyond the last element will return a null).

or:

```<code>array=(10 12 13 14 18 24); for dir in ${array[@]}; do cd "$dir"; do_something "foo $dir bar"; done
</code>```

which is essentially the same as the list example above.

ContentLicense: CC BY-SA 2.5

Body:
I have a set of folders named for example 10, 12, 13, 14, 18, 24 etc. They don't change numbers in any standard increment. I then need to move repetitively into the folders and then into the next one to perform SVN commands which are the same except for some variable extension, e.g.:

/home/boy$ cp /home/files/*Session10.* . ; svn add *Session10.*; svn commit; cd ..; cd 12;

Then the next command is analogous:

/home/boy$ cp /home/files/*Session12.* . ; svn add *Session12.*; svn commit; cd ..; cd 14;

So there should be an array or list defined, and then a for loop through that list, and then a variable whose name is expanded to be fed into the cp and svn command.
Any thoughts? I hope that it can be done in the command prompt rather than in a bash script file.

Body:
If the list is predefined and you're not iterating over every directory that exists (in other words, if a directory named 99 exists but it's not in your list you want to exclude it), you can iterate over the list:

list="10 12 13 14 18 24"; for dir in $list; do cd "$dir"; do_something "foo $dir bar"; done

or an array:

array=(10 12 13 14 18 24); for idx in ${!array[@]}; do cd "${array[idx]}"; do_something "foo ${array[idx]} bar"; done

You can do previous or next array elements like this: ${array[idx-1]} or ${array[idx+1]} if you do appropriate checks to make sure you're not trying to retrieve an element with a negative index (an index beyond the last element will return a null).

or:

array=(10 12 13 14 18 24); for dir in ${array[@]}; do cd "$dir"; do_something "foo $dir bar"; done

which is essentially the same as the list example above.


问:
Randomly generate more proportion of zeroes python
I want to simulate a variable which can have values between 0 and 1. But I also want that this random variable to have 80% zeroes. Currently I ma doing the following:

```<code>data['response']=np.random.uniform(0,1,15000)#simulate response
data['response']=data['response'].apply(lambda x:0 if x<0.85 else x)
</code>```

But this results in only the extreme values(0 and .8+) in the variable. I want to have 80 percent zeroes and rest 20% rows to have values between zero and one. This has to be done randomly.

答:
Here's another one using numpy.random.shuffle

```<code># Proportion between zeros and non-zeros
proportion = .8
n_non_zeros = 200

# Generate fake non-zero data.
# Inversion to ensure the range contains all the values between 0 and 1, except 0
non_zeros = 1 - np.random.uniform(size=[n_non_zeros])

# Append [proportion / (1 - proportion)] zeros
# to 'non_zeros' array for each non-zero
non_zeros += [0] * int(n_non_zeros * proportion / (1 - proportion))

# Shuffle data
np.random.shuffle(data)

# 'data' now contains 200 non-zeros and 800 zeros
# They are %20 and %80 of 1000
</code>```

Body:
I want to simulate a variable which can have values between 0 and 1. But I also want that this random variable to have 80% zeroes. Currently I ma doing the following:

data['response']=np.random.uniform(0,1,15000)#simulate response
data['response']=data['response'].apply(lambda x:0 if x<0.85 else x)

But this results in only the extreme values(0 and .8+) in the variable. I want to have 80 percent zeroes and rest 20% rows to have values between zero and one. This has to be done randomly.

Body:
Here's another one using numpy.random.shuffle

# Proportion between zeros and non-zeros
proportion = .8
n_non_zeros = 200

# Generate fake non-zero data.
# Inversion to ensure the range contains all the values between 0 and 1, except 0
non_zeros = 1 - np.random.uniform(size=[n_non_zeros])

# Append [proportion / (1 - proportion)] zeros
# to 'non_zeros' array for each non-zero
non_zeros += [0] * int(n_non_zeros * proportion / (1 - proportion))

# Shuffle data
np.random.shuffle(data)

# 'data' now contains 200 non-zeros and 800 zeros
# They are %20 and %80 of 1000


问:
Spark submit not working on EMR - Failing Oozie Launcher, Attempt to add apacheds-i18n-2.0.0-M15.jar multiple times to the distributed cache
I just provisioned EMR cluster with spark, oozie, hue insatlled. I am running the spark action in oozie in yarn-cluster mode. I am getting the following error:

Any help would be greatly appreciated

```<code>Failing Oozie Launcher, Main class [org.apache.oozie.action.hadoop.SparkMain], main() threw exception, Attempt to add (hdfs:namenodeec2:8020/user/oozie/share/lib/lib_20170330151923/oozie/apacheds-i18n-2.0.0-M15.jar) multiple times to the distributed cache.

java.lang.IllegalArgumentException: Attempt to add (hdfs://namenodeec2/user/oozie/share/lib/lib_20170330151923/oozie/apacheds-i18n-2.0.0-M15.jar) multiple times to the distributed cache.
at org.apache.spark.deploy.yarn.Client$$anonfun$prepareLocalResources$11$$anonfun$apply$8.apply(Client.scala:608)
at org.apache.spark.deploy.yarn.Client$$anonfun$prepareLocalResources$11$$anonfun$apply$8.apply(Client.scala:599)
at scala.collection.mutable.ArraySeq.foreach(ArraySeq.scala:74)
at org.apache.spark.deploy.yarn.Client$$anonfun$prepareLocalResources$11.apply(Client.scala:599)
at org.apache.spark.deploy.yarn.Client$$anonfun$prepareLocalResources$11.apply(Client.scala:598)
at scala.collection.immutable.List.foreach(List.scala:381)
at org.apache.spark.deploy.yarn.Client.prepareLocalResources(Client.scala:598)
at org.apache.spark.deploy.yarn.Client.createContainerLaunchContext(Client.scala:868)
at org.apache.spark.deploy.yarn.Client.submitApplication(Client.scala:170)
at org.apache.spark.deploy.yarn.Client.run(Client.scala:1154)
at org.apache.spark.deploy.yarn.Client$.main(Client.scala:1213)
at org.apache.spark.deploy.yarn.Client.main(Client.scala)
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.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:738)
at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
at org.apache.oozie.action.hadoop.SparkMain.runSpark(SparkMain.java:338)
at org.apache.oozie.action.hadoop.SparkMain.run(SparkMain.java:257)
at org.apache.oozie.action.hadoop.LauncherMain.run(LauncherMain.java:60)
at org.apache.oozie.action.hadoop.SparkMain.main(SparkMain.java:78)
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.oozie.action.hadoop.LauncherMapper.map(LauncherMapper.java:232)
at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:54)
at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:455)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:344)
at org.apache.hadoop.mapred.LocalContainerLauncher$EventHandler.runSubtask(LocalContainerLauncher.java:380)
at org.apache.hadoop.mapred.LocalContainerLauncher$EventHandler.runTask(LocalContainerLauncher.java:301)
at org.apache.hadoop.mapred.LocalContainerLauncher$EventHandler.access$200(LocalContainerLauncher.java:187)
at org.apache.hadoop.mapred.LocalContainerLauncher$EventHandler$1.run(LocalContainerLauncher.java:230)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>```

答: I have run into this issue a couple of times before and seems like AWS folks still haven't fixed this. This problem according to AWS support guys arises with EMR version 5.3. However if you downgrade your EMR to version 5.1 this issue will be resolved.</p>

Body:
I just provisioned EMR cluster with spark, oozie, hue insatlled. I am running the spark action in oozie in yarn-cluster mode. I am getting the following error:

Any help would be greatly appreciated

Failing Oozie Launcher, Main class [org.apache.oozie.action.hadoop.SparkMain], main() threw exception, Attempt to add (hdfs:namenodeec2:8020/user/oozie/share/lib/lib_20170330151923/oozie/apacheds-i18n-2.0.0-M15.jar) multiple times to the distributed cache.

java.lang.IllegalArgumentException: Attempt to add (hdfs://namenodeec2/user/oozie/share/lib/lib_20170330151923/oozie/apacheds-i18n-2.0.0-M15.jar) multiple times to the distributed cache.
at org.apache.spark.deploy.yarn.Client$$anonfun$prepareLocalResources$11$$anonfun$apply$8.apply(Client.scala:608)
at org.apache.spark.deploy.yarn.Client$$anonfun$prepareLocalResources$11$$anonfun$apply$8.apply(Client.scala:599)
at scala.collection.mutable.ArraySeq.foreach(ArraySeq.scala:74)
at org.apache.spark.deploy.yarn.Client$$anonfun$prepareLocalResources$11.apply(Client.scala:599)
at org.apache.spark.deploy.yarn.Client$$anonfun$prepareLocalResources$11.apply(Client.scala:598)
at scala.collection.immutable.List.foreach(List.scala:381)
at org.apache.spark.deploy.yarn.Client.prepareLocalResources(Client.scala:598)
at org.apache.spark.deploy.yarn.Client.createContainerLaunchContext(Client.scala:868)
at org.apache.spark.deploy.yarn.Client.submitApplication(Client.scala:170)
at org.apache.spark.deploy.yarn.Client.run(Client.scala:1154)
at org.apache.spark.deploy.yarn.Client$.main(Client.scala:1213)
at org.apache.spark.deploy.yarn.Client.main(Client.scala)
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.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:738)
at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
at org.apache.oozie.action.hadoop.SparkMain.runSpark(SparkMain.java:338)
at org.apache.oozie.action.hadoop.SparkMain.run(SparkMain.java:257)
at org.apache.oozie.action.hadoop.LauncherMain.run(LauncherMain.java:60)
at org.apache.oozie.action.hadoop.SparkMain.main(SparkMain.java:78)
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.oozie.action.hadoop.LauncherMapper.map(LauncherMapper.java:232)
at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:54)
at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:455)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:344)
at org.apache.hadoop.mapred.LocalContainerLauncher$EventHandler.runSubtask(LocalContainerLauncher.java:380)
at org.apache.hadoop.mapred.LocalContainerLauncher$EventHandler.runTask(LocalContainerLauncher.java:301)
at org.apache.hadoop.mapred.LocalContainerLauncher$EventHandler.access$200(LocalContainerLauncher.java:187)
at org.apache.hadoop.mapred.LocalContainerLauncher$EventHandler$1.run(LocalContainerLauncher.java:230)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)


问:
How to use CASE in my Scenario in SQL Server?
I have to calculate total quantity with certain cases.

#customerSales table:

```<code>ItemLookupCode  TotalQuantity
-----------------------------
111A000         20
111B001         320
111D000         5
111D001         5
111D002         1
111D003         1
</code>```

#temp_ItemRelations table

```<code>ID  ItemLookupCode  ChildItemLookupCode1   Child1Piece    ChildItemLookupCode2  Child2Piece   ChildItemLookupCode    Child3Piece
---------------------------------------------------------------------------------------------------------------
352 111A000         111A001                5                       111A002         3                   NULL             NULL
365 111B000         111B001                4                       NULL          NULL                  NULL             NULL
377 111C000         111C001                10                      111C002         5                  111C003            1
412 111D000         111D001                12                      111D002         8                  111D003            4
601 111E000         111E001                16                      111E002         6                  111E003            1
</code>```

You can see 111D000 of ItemLookupCode in #temp_ItemRelations, all children are sold including parent.

So output should be like below

```<code> ItemLookupCode     TotalQuantity    //parent    + child1 + child2 + child3
 111D000                77           //  5       + (5*12) + (1*8)  + (1*4)
 111A000                20           //  20      + no child
 111B000               1280          // noparent + (4*320)+ nochild2 & 3
</code>```

I tried the following query. But I don't how to sum those values. I know the following query is wrong. But I tried.

```<code>SELECT
    ir.ItemLookupCode,
    (CASE
        WHEN cs.ItemLookupCode = ir.ItemLookupCode
           THEN cs.TotalQuantity
        WHEN cs.itemlookupcode = ir1.childitemlookupcode1
           THEN (cs.TotalQuantity * ir.Child1Piece)
        WHEN cs.itemlookupcode = ir2.childitemlookupcode2
           THEN (cs.TotalQuantity * ir.Child2Piece)
        WHEN cs.itemlookupcode = ir3.childitemlookupcode
           THEN (cs.TotalQuantity * ir.Child3Piece)
        ELSE 0
     END) AS TotalQuantity
FROM
    #temp_ItemRelations ir
LEFT JOIN
    #customerSales cs ON cs.itemlookupcode = ir.itemlookupcode
LEFT JOIN
    #temp_ItemRelations ir1 ON cs.itemlookupcode = ir1.childitemlookupcode1
LEFT JOIN
    #temp_ItemRelations ir2 ON cs.itemlookupcode = ir2.childitemlookupcode2
LEFT JOIN
    #temp_ItemRelations ir3 ON cs.itemlookupcode = ir3.childitemlookupcode
</code>```

答:
You have a bad data structure.  Your item relations should have one row per child relationship, not multiple columns with numbers to distinguish them.

I wouldn't use case for this calculation at all, just coalesce().  More importantly, you seem to have the joins to the wrong tables:

```<code>select ir.ItemLookupCode,
       (coalesce(cs.TotalQuantity, 0) +
        coalesce(cs1.TotalQuantity * ir.Child1Piece, 0) +
        coalesce(cs2.TotalQuantity * ir.Child2Piece, 0) +
        coalesce(cs3.TotalQuantity * ir.Child3Piece, 0)
       ) as TotalQuantity
from #temp_ItemRelations ir left join
      #customerSales cs
      on cs.itemlookupcode = ir.itemlookupcode left join
      #customerSales cs1
      on cs1.itemlookupcode = ir.childitemlookupcode1 left join
      #customerSales cs2
      on cs2.itemlookupcode = ir.childitemlookupcode2 left join
      #customerSales cs3
      on cs3.itemlookupcode = ir.childitemlookupcode3;
</code>```

Body:
I have to calculate total quantity with certain cases.

#customerSales table:

ItemLookupCode  TotalQuantity
-----------------------------
111A000         20
111B001         320
111D000         5
111D001         5
111D002         1
111D003         1

#temp_ItemRelations table

ID  ItemLookupCode  ChildItemLookupCode1   Child1Piece    ChildItemLookupCode2  Child2Piece   ChildItemLookupCode    Child3Piece
---------------------------------------------------------------------------------------------------------------
352 111A000         111A001                5                       111A002         3                   NULL             NULL
365 111B000         111B001                4                       NULL          NULL                  NULL             NULL
377 111C000         111C001                10                      111C002         5                  111C003            1
412 111D000         111D001                12                      111D002         8                  111D003            4
601 111E000         111E001                16                      111E002         6                  111E003            1

You can see 111D000 of ItemLookupCode in #temp_ItemRelations, all children are sold including parent.

So output should be like below

 ItemLookupCode     TotalQuantity    //parent    + child1 + child2 + child3
 111D000                77           //  5       + (5*12) + (1*8)  + (1*4)
 111A000                20           //  20      + no child
 111B000               1280          // noparent + (4*320)+ nochild2 & 3

I tried the following query. But I don't how to sum those values. I know the following query is wrong. But I tried.

SELECT
    ir.ItemLookupCode,
    (CASE
        WHEN cs.ItemLookupCode = ir.ItemLookupCode
           THEN cs.TotalQuantity
        WHEN cs.itemlookupcode = ir1.childitemlookupcode1
           THEN (cs.TotalQuantity * ir.Child1Piece)
        WHEN cs.itemlookupcode = ir2.childitemlookupcode2
           THEN (cs.TotalQuantity * ir.Child2Piece)
        WHEN cs.itemlookupcode = ir3.childitemlookupcode
           THEN (cs.TotalQuantity * ir.Child3Piece)
        ELSE 0
     END) AS TotalQuantity
FROM
    #temp_ItemRelations ir
LEFT JOIN
    #customerSales cs ON cs.itemlookupcode = ir.itemlookupcode
LEFT JOIN
    #temp_ItemRelations ir1 ON cs.itemlookupcode = ir1.childitemlookupcode1
LEFT JOIN
    #temp_ItemRelations ir2 ON cs.itemlookupcode = ir2.childitemlookupcode2
LEFT JOIN
    #temp_ItemRelations ir3 ON cs.itemlookupcode = ir3.childitemlookupcode

Body:
You have a bad data structure.  Your item relations should have one row per child relationship, not multiple columns with numbers to distinguish them.

I wouldn't use case for this calculation at all, just coalesce().  More importantly, you seem to have the joins to the wrong tables:

select ir.ItemLookupCode,
       (coalesce(cs.TotalQuantity, 0) +
        coalesce(cs1.TotalQuantity * ir.Child1Piece, 0) +
        coalesce(cs2.TotalQuantity * ir.Child2Piece, 0) +
        coalesce(cs3.TotalQuantity * ir.Child3Piece, 0)
       ) as TotalQuantity
from #temp_ItemRelations ir left join
      #customerSales cs
      on cs.itemlookupcode = ir.itemlookupcode left join
      #customerSales cs1
      on cs1.itemlookupcode = ir.childitemlookupcode1 left join
      #customerSales cs2
      on cs2.itemlookupcode = ir.childitemlookupcode2 left join
      #customerSales cs3
      on cs3.itemlookupcode = ir.childitemlookupcode3;


问:
WooCommerce Star Symbols Showing up as Box Icons
I've read through the previous threads regarding wooCommerce star issues and haven't been able to help myself fix this problem. I apologize for any redundancies. I'm a teacher and new to css.  Here is my issue:

I'm using the Mystile theme for my website k12movieguides.com and I've combed through the wooCommerce section of my style.css file. I got the stars working properly on the individual product page and review areas, but I can't figure out how to get the stars to show up under the product thumbnails on the shop and home pages, where there are multiple products next to each. Instead of stars, I see a generic box icon.

Here is a screenshot of the box icons, I've tried to use chrome's inspect feature to figure out what is going wrong with class="rating" but I can't figure it out.

Here is the entire code in my style.css under the WooCommerce section. Please let me know if any other information is required to help fix this problem. Your time and genius is much appreciated.

/*-------------------------------------------------------------------------------------------*/
/* 7. WOOCOMMERCE */
/*-------------------------------------------------------------------------------------------*/
p.demo_store {
  background: #4d65a4;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  text-align: center;
  color: #fff;
  padding: 1em;
}
.homepage-banner {
  display: none;
}

/* ==========================================================================
 Snippet Name: WooCommerce Review Star Ratings
 Description:  This css snippet blends all woocommerce star rating for a consistant look sitewide. Consolidates code and makes uses of WooCommerce.eot font. If you disabled the woocommerce.css and built your own styles then this will work great. If you are overriding woocommerce.css by adding styles to another styesheet that loads afterwards, this will still work fine, but you may need to target specific elements or create a master reset targeting all elements listed below in order to remove some of woocommerce default margins and padding.
 Author:       GL Walker
 Author URI:   http://wsfive.com
   ========================================================================== */

.woocommerce .star-rating, .woocommerce p.stars [class^="star-"], .woocommerce p.stars [class*=" star-"] {
 font-family: WooCommerce;
 speak: none;
 font-weight: 400;
 font-variant: normal;
 text-transform: none;
 line-height: 1;
 -webkit-font-smoothing: antialiased;
 font-size: 1em;
}
.woocommerce .star-rating {
 overflow: hidden;
 position: relative;
 height: 1em;
 width: 5em;
}
.woocommerce .star-rating:before {
 content: "\e021\e021\e021\e021\e021";
 float: left;
 top: 0;
 left: 0;
 position: absolute;
 color: #999;
}
.woocommerce .star-rating span {
 overflow: hidden;
 float: left;
 top: 0;
 left: 0;
 position: absolute;
 padding-top: 1.5em
}
.woocommerce .star-rating span:before {
 content: "\e020\e020\e020\e020\e020";
 top: 0;
 position: absolute;
 left: 0;
 color: #F90;
}
/* rating block specific to single product summary area */
.woocommerce .woocommerce-product-rating {
 display: block;
 width: 100%;
}
.woocommerce .woocommerce-product-rating .star-rating {
 margin: 0 auto;
 float: left;
 font-size: 1em;
}
.woocommerce .woocommerce-product-rating .woocommerce-review-link {
 font-size: 85%;
 width: 100%;
 margin: 0.5em 0;
 float: left;
}
/* rating block specific to review submit form */
.woocommerce p.stars {
 position: relative;
 padding: 0.75em;
}
.woocommerce p.stars a {
 display: inline-block;
 margin-right: 1em;
 text-indent: -9999px;
 position: relative;
 border-bottom: 0!important;
 outline: 0;
 color: #999;
}
.woocommerce p.stars a:hover, .woocommerce p.stars a.active {
 color: #F90;
}
.woocommerce p.stars a:last-child {
 border-right: 0
}
.woocommerce p.stars [class^="star-"], .woocommerce p.stars [class*=" star-"] {
 border-right: 1px solid #ccc
}
.woocommerce p.stars [class^="star-"]:after, .woocommerce p.stars [class*=" star-"]:after {
 text-indent: 0;
 position: absolute;
 top: 0;
 left: 0
}
.woocommerce p.stars a.star-1 {
 width: 2em
}
.woocommerce p.stars a.star-1:after {
 content: "\e021"
}
.woocommerce p.stars a.star-1.active:after, .woocommerce p.stars a.star-1:hover:after {
 content: "\e020"
}
.woocommerce p.stars a.star-2 {
 width: 3em
}
.woocommerce p.stars a.star-2:after {
 content: "\e021\e021"
}
.woocommerce p.stars a.star-2.active:after, .woocommerce p.stars a.star-2:hover:after {
 content: "\e020\e020"
}
.woocommerce p.stars a.star-3 {
 width: 4em
}
.woocommerce p.stars a.star-3:after {
 content: "\e021\e021\e021"
}
.woocommerce p.stars a.star-3.active:after, .woocommerce p.stars a.star-3:hover:after {
 content: "\e020\e020\e020"
}
.woocommerce p.stars a.star-4 {
 width: 5em
}
.woocommerce p.stars a.star-4:after {
 content: "\e021\e021\e021\e021"
}
.woocommerce p.stars a.star-4.active:after, .woocommerce p.stars a.star-4:hover:after {
 content: "\e020\e020\e020\e020"
}
.woocommerce p.stars a.star-5 {
 width: 6em;
}
.woocommerce p.stars a.star-5:after {
 content: "\e021\e021\e021\e021\e021"
}
.woocommerce p.stars a.star-5.active:after, .woocommerce p.stars a.star-5:hover:after {
 content: "\e020\e020\e020\e020\e020"
}
/* rating block specific to product listing */
.woocommerce ul.products li.product .star-rating {
 display: block;
 text-align: center;
 margin: 0 auto;
}
/* rating block specific to sidebar widgets */
.woocommerce ul.cart_list li .star-rating, .woocommerce ul.product_list_widget li .star-rating {
 display: block;
 text-align: center;
 margin: 0 auto;
}
/* end of review stars */

div.quantity {
  white-space: nowrap;
  /* Disable input[type=number] buttons until the world is ready */
}
div.quantity input::-webkit-outer-spin-button,
div.quantity input::-webkit-inner-spin-button {
  display: none;
}
div.quantity .plus,
div.quantity .minus {
  font-family: 'WooCommerce';
  background: none;
  border: none;
  font-size: 1.387em;
  padding: 0;
  color: #ff4800;
  -webkit-transition: all ease-in-out 0.2s;
  -moz-transition: all ease-in-out 0.2s;
  -ms-transition: all ease-in-out 0.2s;
  -o-transition: all ease-in-out 0.2s;
  transition: all ease-in-out 0.2s;
}
div.quantity .plus:hover,
div.quantity .minus:hover {
  color: #dd2600;
}
div.quantity .qty {
  margin: 0 .618em;
  width: 2.618em;
  text-align: center;
  padding-left: 0;
  padding-right: 0;
}
table div.quantity {
  font-size: .857em;
}
.single-product div.quantity {
  float: left;
  margin-right: 1.618em;
  border-right: 4px double #e8e4e3;
  padding-right: 1.618em;
}
.single-product table div.quantity {
  padding-right: 0;
  border: 0;
}
.single-product #reviews .star-rating {
  float: right;
}
.single-product .single_variation .price {
  display: block;
  margin-bottom: .618em;
}
dl.variation dt,
dl.variation dd {
  float: left;
}
dl.variation dt {
  clear: left;
  margin-right: .53em;
}
dl.variation dd ul {
  list-style: none;
}
.backorder_notification {
  clear: both;
}
.validate-required.woocommerce-validated input {
  border-color: #84ac50;
  background: #e5eeda;
}
.validate-required.woocommerce-invalid input {
  border-color: #b85f56;
  background: #f4e7e6;
}```

答:
I'm having an incredibly similar issue, except I was able to output S's but cannot format them into stars. See the questions I've posted as they might help you. Below is some code I uses. Please excuse the tone of some of my comments. I've been working on this for an entire week lol</p>

```<code>/*--------------------------------------*/
/* MAKES LEAVE A REVIEW WORK PERFECTLY! */
/* Copied from plugins-woocommerce-assets-css-woocommerce.ss */
/*--------------------------------------*/
.woocommerce p.stars a:before,.woocommerce p.stars a:hover~a:before{content:"\e021"}.woocommerce #review_form #respond p{margin:0 0 10px}.woocommerce #review_form #respond .form-submit input{left:auto}.woocommerce #review_form #respond textarea{box-sizing:border-box;width:100%}.woocommerce p.stars a{position:relative;height:1em;width:1em;text-indent:-999em;display:inline-block;text-decoration:none}.woocommerce p.stars a:before{display:block;position:absolute;top:0;left:0;width:1em;height:1em;line-height:1;font-family:WooCommerce;text-indent:0}.woocommerce table.shop_attributes td,.woocommerce table.shop_attributes th{line-height:1.5;border-bottom:1px dotted rgba(0,0,0,.1);border-top:0;margin:0}.woocommerce p.stars.selected a.active:before,.woocommerce p.stars:hover a:before{content:"\e020"}.woocommerce p.stars.selected a.active~a:before{content:"\e021"}.woocommerce p.stars.selected a:not(.active):before{content:"\e020"}

/*--------------------------------------*/
/* STAR RATINGS!! EEEEYYYY!! */
/*--------------------------------------*/
/* COULD POSSIBLY BE FORCING S's on SHOP PAGE! When removed, all ratings change to numerical "4 out of 5". But when above taken from woocommerce.css then Add a review section works fine */

/* Adds some space between top avg review and product price */
.woocommerce div.product .woocommerce-product-rating {
    margin-bottom: 1.618em;
}

/* Deleting made no changes to Product OR Shop page stars */
/*.woocommerce .woocommerce-product-rating:after, .woocommerce .woocommerce-product-rating:before {
    content: " ";
    display: table;
}*/

/* Deleting made no changes to Product OR Shop page stars */
/*.woocommerce .woocommerce-product-rating .star-rating {
    margin: .5em 4px 0 0;
    float: left;
}*/

/* Fills in posted review's star's on product page and removes "# out of # based on customer reviews" from top of product page next to avg stars & removes "# out of # from shop page and aligns S's */
.woocommerce .star-rating {
    float: right;
    overflow: hidden;
    position: relative;
    height: 1em;
    line-height: 1;
    font-size: 1em;
    width: 5.4em;
}

/* Adds empty stars behind user submitted star ratings & grey s's to shop page */
.woocommerce .star-rating:before {
    content: "\73\73\73\73\73";
    color: #d3ced2;
    float: left;
    top: 0;
    left: 0;
    position: absolute;
    font-family: star;
}

/* Changes product page black stars to blue and removes previous "# out of #" text & removes "# out of # from Shop page*/
.woocommerce .star-rating span {
    overflow: hidden;
    float: left;
    top: 0;
    left: 0;
    position: absolute;
    padding-top: 1.5em;
    font-family = "star";
    color: #52a0cd;
}

/* Fills in product page review stars and avg star ratings appropriately based on posted reviews & Add's uppercase blue S's to Shop page */
.woocommerce .star-rating span:before {
    content: "\53\53\53\53\53";
    top: 0;
    position: absolute;
    left: 0;
    font-family: star;
    visibility: visible;
    font-family: star;
}
</code>```

Body:
I'm having an incredibly similar issue, except I was able to output S's but cannot format them into stars. See the questions I've posted as they might help you. Below is some code I uses. Please excuse the tone of some of my comments. I've been working on this for an entire week lol

/*--------------------------------------*/
/* MAKES LEAVE A REVIEW WORK PERFECTLY! */
/* Copied from plugins-woocommerce-assets-css-woocommerce.ss */
/*--------------------------------------*/
.woocommerce p.stars a:before,.woocommerce p.stars a:hover~a:before{content:"\e021"}.woocommerce #review_form #respond p{margin:0 0 10px}.woocommerce #review_form #respond .form-submit input{left:auto}.woocommerce #review_form #respond textarea{box-sizing:border-box;width:100%}.woocommerce p.stars a{position:relative;height:1em;width:1em;text-indent:-999em;display:inline-block;text-decoration:none}.woocommerce p.stars a:before{display:block;position:absolute;top:0;left:0;width:1em;height:1em;line-height:1;font-family:WooCommerce;text-indent:0}.woocommerce table.shop_attributes td,.woocommerce table.shop_attributes th{line-height:1.5;border-bottom:1px dotted rgba(0,0,0,.1);border-top:0;margin:0}.woocommerce p.stars.selected a.active:before,.woocommerce p.stars:hover a:before{content:"\e020"}.woocommerce p.stars.selected a.active~a:before{content:"\e021"}.woocommerce p.stars.selected a:not(.active):before{content:"\e020"}

/*--------------------------------------*/
/* STAR RATINGS!! EEEEYYYY!! */
/*--------------------------------------*/
/* COULD POSSIBLY BE FORCING S's on SHOP PAGE! When removed, all ratings change to numerical "4 out of 5". But when above taken from woocommerce.css then Add a review section works fine */

/* Adds some space between top avg review and product price */
.woocommerce div.product .woocommerce-product-rating {
    margin-bottom: 1.618em;
}

/* Deleting made no changes to Product OR Shop page stars */
/*.woocommerce .woocommerce-product-rating:after, .woocommerce .woocommerce-product-rating:before {
    content: " ";
    display: table;
}*/

/* Deleting made no changes to Product OR Shop page stars */
/*.woocommerce .woocommerce-product-rating .star-rating {
    margin: .5em 4px 0 0;
    float: left;
}*/

/* Fills in posted review's star's on product page and removes "# out of # based on customer reviews" from top of product page next to avg stars & removes "# out of # from shop page and aligns S's */
.woocommerce .star-rating {
    float: right;
    overflow: hidden;
    position: relative;
    height: 1em;
    line-height: 1;
    font-size: 1em;
    width: 5.4em;
}

/* Adds empty stars behind user submitted star ratings & grey s's to shop page */
.woocommerce .star-rating:before {
    content: "\73\73\73\73\73";
    color: #d3ced2;
    float: left;
    top: 0;
    left: 0;
    position: absolute;
    font-family: star;
}

/* Changes product page black stars to blue and removes previous "# out of #" text & removes "# out of # from Shop page*/
.woocommerce .star-rating span {
    overflow: hidden;
    float: left;
    top: 0;
    left: 0;
    position: absolute;
    padding-top: 1.5em;
    font-family = "star";
    color: #52a0cd;
}

/* Fills in product page review stars and avg star ratings appropriately based on posted reviews & Add's uppercase blue S's to Shop page */
.woocommerce .star-rating span:before {
    content: "\53\53\53\53\53";
    top: 0;
    position: absolute;
    left: 0;
    font-family: star;
    visibility: visible;
    font-family: star;
}


问:
searching huge text file
I have a text file consisting of ~40 million of lines in the form of a key/value, I want to retrieve the values given the key within seconds (2-3) max, I don't have enough memory to store all of them in JVM memory as a hashmap, can I use system storage + some indexing to achieve that ?
i've been reading about lucene, but not sure if it's what am looking for.</p>

答:
If you want to search a "text string" in the key or in the value you could use Apache Lucene. Lucene is a full-featured text search engine library but you can use it also simply for search the exact match of the key value. I use Lucene with more than 60 millions of documents and I have less than 1 second for every search.

Otherwise if you want only a key/value store you can use a NOSql Key/Value database like Redis, but I haven't tried yet.

Title: searching huge text file


问:
Full screen iOS share Extension
I know how to create an iOS share extension, but what I can't figure out is if there is a way to make it fullscreen such as an Action extension?

Pinterest seem to do this but I'm not sure how.

The docs for an Action extension say to use:

```<code>          <key>NSExtensionActionWantsFullScreenPresentation</key>
    <true/>
</code>```

In the plist file for the extension but this doesn't seem to have an effect in the Share extension?

Is there anyway to accomplish this?

答:
You can get ideas from there iOS Full Screen Share Extension and you can find the updated syntax for the code snippets below which is compatible with Swift 3 and Swift 4

EntryViewController

```<code>import UIKit

@objc(EntryViewController)

class EntryViewController : UINavigationController {

    override init(rootViewController: UIViewController) {
        super.init(rootViewController: ShareViewController())
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.view.transform = CGAffineTransform(translationX: 0, y: self.view.frame.size.height)
        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            self.view.transform = .identity
        })
    }

}
</code>```

ShareViewController

```<code>import UIKit
import Social

class ShareViewController: SLComposeServiceViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        self.navigationItem.title = "Share"

        self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: Selector(("cancelButtonTapped:")))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: Selector(("saveButtonTapped:")))
    }

    func saveButtonTapped(sender: UIBarButtonItem) {
        self.hideExtensionWithCompletionHandler(completion: { (Bool) -> Void in
        self.extensionContext!.completeRequest(returningItems: nil, completionHandler: nil)
        })
    }

    func cancelButtonTapped(sender: UIBarButtonItem) {
        self.hideExtensionWithCompletionHandler(completion: { (Bool) -> Void in
        self.extensionContext!.cancelRequest(withError: NSError())
        })
    }

    func hideExtensionWithCompletionHandler(completion: @escaping (Bool) -> Void) {
        UIView.animate(withDuration: 0.3, animations: {
        self.navigationController!.view.transform = CGAffineTransform(translationX: 0, y: self.navigationController!.view.frame.size.height)
        }, completion: completion)
    }

}
</code>```

Title: Full screen iOS share Extension

Body:
I know how to create an iOS share extension, but what I can't figure out is if there is a way to make it fullscreen such as an Action extension?

Pinterest seem to do this but I'm not sure how.

The docs for an Action extension say to use:

          <key>NSExtensionActionWantsFullScreenPresentation</key>
    <true/>

In the plist file for the extension but this doesn't seem to have an effect in the Share extension?

Is there anyway to accomplish this?

Body:
You can get ideas from there iOS Full Screen Share Extension and you can find the updated syntax for the code snippets below which is compatible with Swift 3 and Swift 4

EntryViewController

import UIKit

@objc(EntryViewController)

class EntryViewController : UINavigationController {

    override init(rootViewController: UIViewController) {
        super.init(rootViewController: ShareViewController())
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.view.transform = CGAffineTransform(translationX: 0, y: self.view.frame.size.height)
        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            self.view.transform = .identity
        })
    }

}

ShareViewController

import UIKit
import Social

class ShareViewController: SLComposeServiceViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        self.navigationItem.title = "Share"

        self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: Selector(("cancelButtonTapped:")))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: Selector(("saveButtonTapped:")))
    }

    func saveButtonTapped(sender: UIBarButtonItem) {
        self.hideExtensionWithCompletionHandler(completion: { (Bool) -> Void in
        self.extensionContext!.completeRequest(returningItems: nil, completionHandler: nil)
        })
    }

    func cancelButtonTapped(sender: UIBarButtonItem) {
        self.hideExtensionWithCompletionHandler(completion: { (Bool) -> Void in
        self.extensionContext!.cancelRequest(withError: NSError())
        })
    }

    func hideExtensionWithCompletionHandler(completion: @escaping (Bool) -> Void) {
        UIView.animate(withDuration: 0.3, animations: {
        self.navigationController!.view.transform = CGAffineTransform(translationX: 0, y: self.navigationController!.view.frame.size.height)
        }, completion: completion)
    }

}


答:
Building up on your code, you can just scale x when it is larger than 0.8:

lambda x: 0 if x < 0.8 else 5 * (x - 0.8)

Title: Randomly generate more proportion of zeroes python


问:
Thread safety of fixed sized stl map
I have a stl map with integer as key and a vector of class object as its value.

```<code>class foo {
    // provides wrapper around std::queue for thread safety
    private :
       std::queue<>
}

std::map<unsigned int, std::vector<foo *> > mymap;
</code>```

foo class is just a thread safe wrapper around std::queue implementation.
Now coming to the actual question - this map is used in a multi threaded scenario where each thread depending upon an arguments passed during creation accesses the corresponding vector.

So lets say i created 4 threads and passed 0,1,2,3 as argument so :

```<code>thread 0 - mymap[0];
thread 1 - mymap[1];
thread 2 - mymap[2];
thread 3 - mymap[3];
</code>```

Size of the map is fixed during creation and is not changed.

Do i need to make my map thread safe ?

as the size of map is fixed so that there will be no re-ordering of the map .

each thread changes only its corresponding vector as per its id.

答:
No, you do not need to add extra synchronization to make this use of std::map thread-safe.  You are only modifying the map nodes during initialization, and after that you are only reading the map.  Concurrent reading of the map is no problem, because its structure does not change.

The fact that you are modifying the values in the map does not matter, because they don't contribute to the ordering and structure of the map.

Title: Thread safety of fixed sized stl map

Body:
I have a stl map with integer as key and a vector of class object as its value.

class foo {
    // provides wrapper around std::queue for thread safety
    private :
       std::queue<>
}

std::map<unsigned int, std::vector<foo *> > mymap;

foo class is just a thread safe wrapper around std::queue implementation.
Now coming to the actual question - this map is used in a multi threaded scenario where each thread depending upon an arguments passed during creation accesses the corresponding vector.

So lets say i created 4 threads and passed 0,1,2,3 as argument so :

thread 0 - mymap[0];
thread 1 - mymap[1];
thread 2 - mymap[2];
thread 3 - mymap[3];

Size of the map is fixed during creation and is not changed.

Do i need to make my map thread safe ?

as the size of map is fixed so that there will be no re-ordering of the map .

each thread changes only its corresponding vector as per its id.


问:
Chaining then() and accessing data in JavaScript
Hi all I'm learning javascript for some few months now and trying to write my first, not trivial app and came across this problem. this is sample of my code:

```<code>$(document).ready(function() {
  let contributorsArr = [];
  let url = 'https://api.github.com/repos/angular/angular';
  let usersArr = [];
  fetch(url).then(response => response.json()).then(data => {
    let auth = '';
    contributorsArr = data.map(item => {
      let contributions = item.contributions;
      let id = item.id;
      return {id, contributions};
    });

    const userUrls = data.map(item => item.url + auth);
    const users = userUrls.map(userUrl => fetch(userUrl));
    return Promise.all(users);

  }).then(responses => {
    return Promise.all(responses.map(user => user.json()));
  }).then(users => {
    contributorsArr.forEach(function(obj1) {
      users.forEach(function(obj) {
        if (obj1.id === obj.id) {
          Object.assign(obj, obj1);
        }
      });
      return users;
    });

    usersArr.push(users);

    $.each(users, function (index,user) {
      let that = this;

      $('#users').on('click','#userPanel',function (user) {
        console.log(that.id);
      });

      $('#users').append(`
        <div id="userPanel" class="panel panel-default">
        <div class="panel-heading">
        <h3 class="panel-title">${user.name ? user.name :    user.login}</h3>
        </div>
        <div class="panel-body">
        <div class="row">
        <div class="col-md-3 ">
        <img class="thumbnail avatar" src="${user.avatar_url}" alt="avatar">
        <a target="_blank" class="btn btn-primary btn-block" href="${user.html_url}">View Profile on GitHub</a>
        </div>

        <div class="col-md-9">
        <span class="label label-default">Public Repos: ${user.public_repos} </span>
        <span class="label label-primary">Public Gists: ${user.public_gists}</span>
        <span class="label label-success">Contributions: ${user.contributions}</span>
        <span class="label label-info">Followers: ${user.followers}</span>
        </div>
        </div>
        </div>
        </div>
        `);

    });
  });
});
</code>```

My questions are  how do I bind event handlers for each userPanel , and is there a way to sort them  by amount of contributions or gists?

答:
As per the W3C standard,ID should not be duplicate.

So,use class="userPanel" instead of id="userPanel"

```<code>$('#users').on('click','.userPanel',function (user) {
                console.log(this); //using this u can traversee= up-down
            });//move it to outside of each.
</code>```

Actual DOM appending

```<code>$.each(users,function (index,user) {
            let that = this;

            $('#users').append(`
                    <div class="userPanel" class="panel panel-default">
                      <div class="panel-heading">
                        <h3 class="panel-title">${user.name ? user.name :    user.login}</h3>
                      </div>
                      <div class="panel-body">
                        <div class="row">
                            <div class="col-md-3 ">
                                <img class="thumbnail avatar" src="${user.avatar_url}" alt="avatar">
                                <a target="_blank" class="btn btn-primary btn-block" href="${user.html_url}">View Profile on GitHub</a>
                            </div>

                            <div class="col-md-9">
                            <span class="label label-default">Public Repos: ${user.public_repos} </span>
                            <span class="label label-primary">Public Gists: ${user.public_gists}</span>
                            <span class="label label-success">Contributions: ${user.contributions}</span>
                            <span class="label label-info">Followers: ${user.followers}</span>
                            </div>
                        </div>
                      </div>
                    </div>
                            `);

        });
</code>```

Body:
Hi all I'm learning javascript for some few months now and trying to write my first, not trivial app and came across this problem. this is sample of my code:

$(document).ready(function() {
  let contributorsArr = [];
  let url = 'https://api.github.com/repos/angular/angular';
  let usersArr = [];
  fetch(url).then(response => response.json()).then(data => {
    let auth = '';
    contributorsArr = data.map(item => {
      let contributions = item.contributions;
      let id = item.id;
      return {id, contributions};
    });

    const userUrls = data.map(item => item.url + auth);
    const users = userUrls.map(userUrl => fetch(userUrl));
    return Promise.all(users);

  }).then(responses => {
    return Promise.all(responses.map(user => user.json()));
  }).then(users => {
    contributorsArr.forEach(function(obj1) {
      users.forEach(function(obj) {
        if (obj1.id === obj.id) {
          Object.assign(obj, obj1);
        }
      });
      return users;
    });

    usersArr.push(users);

    $.each(users, function (index,user) {
      let that = this;

      $('#users').on('click','#userPanel',function (user) {
        console.log(that.id);
      });

      $('#users').append(`

${user.name ? user.name :    user.login}

        View Profile on GitHub

        Public Repos: ${user.public_repos}
        Public Gists: ${user.public_gists}
        Contributions: ${user.contributions}
        Followers: ${user.followers}

        `);

    });
  });
});

My questions are  how do I bind event handlers for each userPanel , and is there a way to sort them  by amount of contributions or gists?

Body:
As per the W3C standard,ID should not be duplicate.

So,use class="userPanel" instead of id="userPanel"

$('#users').on('click','.userPanel',function (user) {
                console.log(this); //using this u can traversee= up-down
            });//move it to outside of each.

Actual DOM appending

$.each(users,function (index,user) {
            let that = this;

            $('#users').append(`
                    <div class="userPanel" class="panel panel-default">
                      <div class="panel-heading">
                        <h3 class="panel-title">${user.name ? user.name :    user.login}</h3>
                      </div>
                      <div class="panel-body">
                        <div class="row">
                            <div class="col-md-3 ">
                                <img class="thumbnail avatar" src="${user.avatar_url}" alt="avatar">
                                <a target="_blank" class="btn btn-primary btn-block" href="${user.html_url}">View Profile on GitHub</a>
                            </div>

                            <div class="col-md-9">
                            <span class="label label-default">Public Repos: ${user.public_repos} </span>
                            <span class="label label-primary">Public Gists: ${user.public_gists}</span>
                            <span class="label label-success">Contributions: ${user.contributions}</span>
                            <span class="label label-info">Followers: ${user.followers}</span>
                            </div>
                        </div>
                      </div>
                    </div>
                            `);

        });


问:
urlib.request.urlopen not accepting query string with spaces
I am taking a udacity course on python where we are supposed to check for profane words in a document. I am using the website http://www.wdylike.appspot.com/?q= (text_to_be_checked_for_profanity). The text to be checked can be passed as a query string in the above URL and the website would return a true or false after checking for profane words. Below is my code.

```<code>import urllib.request

# Read the content from a document
def read_content():

    quotes = open("movie_quotes.txt")
    content = quotes.read()
    quotes.close()
    check_profanity(content)

def check_profanity(text_to_read):
    connection = urllib.request.urlopen("http://www.wdylike.appspot.com/?q="+text_to_read)
    result = connection.read()
    print(result)
    connection.close

read_content()
</code>```

It gives me the following error

```<code>Traceback (most recent call last):
   File "/Users/Vrushita/Desktop/Rishit/profanity_check.py", line 21, in <module>
     read_content()
   File "/Users/Vrushita/Desktop/Rishit/profanity_check.py", line 11, in read_content
     check_profanity(content)
   File "/Users/Vrushita/Desktop/Rishit/profanity_check.py", line 16, in check_profanity
     connection = urllib.request.urlopen("http://www.wdylike.appspot.com/?q="+text_to_read)
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 163, in urlopen
     return opener.open(url, data, timeout)
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 472, in open
     response = meth(req, response)
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 582, in http_response
     'http', request, response, code, msg, hdrs)
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 510, in error
     return self._call_chain(*args)
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 444, in _call_chain
     result = func(*args)
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 590, in http_error_default
     raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request
</code>```

The document that I am trying to read the content from contains a string  "Hello world" However, if I change the string to "Hello+world", the same code works and returns the desired result. Can someone explain why this is happening and what is a workaround for this?

答:
The below response is for python 3.*
400 Bad request occurs when there is space within your input text.
To avoid this use parse.
so import it.

```<code>from urllib import request, parse
</code>```

If you are sending any text along with the url then parse the text.

```<code>url = "http://www.wdylike.appspot.com/?q="
url = url + parse.quote(input_to_check)
</code>```

Check the explanation here - https://discussions.udacity.com/t/problem-in-profanity-with-python-3-solved/227328

The Udacity profanity checker program -

```<code>from urllib import request, parse

def read_file():
    fhand = open(r"E:\Python_Programming\Udacity\movie_quotes.txt")
    file_content = fhand.read()
    #print (file_content)
    fhand.close()
    profanity_check(file_content)

def profanity_check(input_to_check):
    url = "http://www.wdylike.appspot.com/?q="
    url = url + parse.quote(input_to_check)
    req = request.urlopen(url)
    answer = req.read()
    #print(answer)
    req.close()

    if b"true" in answer:
        print ("Profanity Alret!!!")
    else:
        print ("Nothing to worry")

read_file()
</code>```

Body:
I am taking a udacity course on python where we are supposed to check for profane words in a document. I am using the website http://www.wdylike.appspot.com/?q= (text_to_be_checked_for_profanity). The text to be checked can be passed as a query string in the above URL and the website would return a true or false after checking for profane words. Below is my code.

import urllib.request

# Read the content from a document
def read_content():

    quotes = open("movie_quotes.txt")
    content = quotes.read()
    quotes.close()
    check_profanity(content)

def check_profanity(text_to_read):
    connection = urllib.request.urlopen("http://www.wdylike.appspot.com/?q="+text_to_read)
    result = connection.read()
    print(result)
    connection.close

read_content()

It gives me the following error

Traceback (most recent call last):
   File "/Users/Vrushita/Desktop/Rishit/profanity_check.py", line 21, in <module>
     read_content()
   File "/Users/Vrushita/Desktop/Rishit/profanity_check.py", line 11, in read_content
     check_profanity(content)
   File "/Users/Vrushita/Desktop/Rishit/profanity_check.py", line 16, in check_profanity
     connection = urllib.request.urlopen("http://www.wdylike.appspot.com/?q="+text_to_read)
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 163, in urlopen
     return opener.open(url, data, timeout)
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 472, in open
     response = meth(req, response)
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 582, in http_response
     'http', request, response, code, msg, hdrs)
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 510, in error
     return self._call_chain(*args)
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 444, in _call_chain
     result = func(*args)
   File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 590, in http_error_default
     raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request

The document that I am trying to read the content from contains a string  "Hello world" However, if I change the string to "Hello+world", the same code works and returns the desired result. Can someone explain why this is happening and what is a workaround for this?

Body:
The below response is for python 3.*
400 Bad request occurs when there is space within your input text.
To avoid this use parse.
so import it.

from urllib import request, parse

If you are sending any text along with the url then parse the text.

url = "http://www.wdylike.appspot.com/?q="
url = url + parse.quote(input_to_check)

Check the explanation here - https://discussions.udacity.com/t/problem-in-profanity-with-python-3-solved/227328

The Udacity profanity checker program -

from urllib import request, parse

def read_file():
    fhand = open(r"E:\Python_Programming\Udacity\movie_quotes.txt")
    file_content = fhand.read()
    #print (file_content)
    fhand.close()
    profanity_check(file_content)

def profanity_check(input_to_check):
    url = "http://www.wdylike.appspot.com/?q="
    url = url + parse.quote(input_to_check)
    req = request.urlopen(url)
    answer = req.read()
    #print(answer)
    req.close()

    if b"true" in answer:
        print ("Profanity Alret!!!")
    else:
        print ("Nothing to worry")

read_file()


问:
What is the best way to tell users of my library functions that passed variables are not of the correct type
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen.

Most methods only work if the variables that are passed are of the correct datatype. Now my question is: What is the best way to alert users that the variable is not of the correct type? Should one throw an error like this?

```<code>function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
 if(typeof(thisShouldBeAString) === 'string') {
  throw('foo(var), var should be of type string');
 }
 #yadayada
}
</code>```

I know that javascript does internal type conversion, but this can create very weird results (ie '234' + 5 = '2345' but '234' * 1 = 234) and this could make my methods do very weird things.

EDIT

To make things extra clear: I do not wish to do type conversion, the variables passed should be of the correct type. What is the best way to tell the user of my library that the passed variables are not of the correct type?

答:
Some small remarks on type checking - it's actually not that complicated:

Use typeof to check for primitives and instanceof to check for specific object types.

Example: Check for strings with

```<code>typeof x === 'string'
</code>```

or

```<code>typeof x === 'string' || x instanceof String
</code>```

if you want to include string objects.

To check for arrays, just use

```<code>x instanceof Array
</code>```

This should work reasonably well (there are a few known exceptions - eg Firefox 3.0.5 has a bug where window instanceof Object === false although window.__proto__ instanceof Object === true).

edit: There are some further problems with detection of function objects:

In principle, you could both use typeof func === 'function' and func  instanceof Function.

The catch is that in an unnamed browser from a big corporation these checks return the wrong results for some predefined functions (their type is given as 'object'). I know of no workaround for this - the checks only work reliably for user-defined functions...

edit2: There are also problems with objects passed from other windows/frames, as they will inherit from different global objects - ie instanceof will fail. Workarounds for built-in objects exists: For example, you can check for arrays via Object.prototype.toString.call(x) === '[object Array]'.

OwnerDisplayName: Pim Jager

Body:
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen.

Most methods only work if the variables that are passed are of the correct datatype. Now my question is: What is the best way to alert users that the variable is not of the correct type? Should one throw an error like this?

function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
 if(typeof(thisShouldBeAString) === 'string') {
  throw('foo(var), var should be of type string');
 }
 #yadayada
}

I know that javascript does internal type conversion, but this can create very weird results (ie '234' + 5 = '2345' but '234' * 1 = 234) and this could make my methods do very weird things.

EDIT

To make things extra clear: I do not wish to do type conversion, the variables passed should be of the correct type. What is the best way to tell the user of my library that the passed variables are not of the correct type?

LastEditorDisplayName: Mitch Wheat

Body:
Some small remarks on type checking - it's actually not that complicated:

Use typeof to check for primitives and instanceof to check for specific object types.

Example: Check for strings with

typeof x === 'string'

or

typeof x === 'string' || x instanceof String

if you want to include string objects.

To check for arrays, just use

x instanceof Array

This should work reasonably well (there are a few known exceptions - eg Firefox 3.0.5 has a bug where window instanceof Object === false although window.__proto__ instanceof Object === true).

edit: There are some further problems with detection of function objects:

In principle, you could both use typeof func === 'function' and func  instanceof Function.

The catch is that in an unnamed browser from a big corporation these checks return the wrong results for some predefined functions (their type is given as 'object'). I know of no workaround for this - the checks only work reliably for user-defined functions...

edit2: There are also problems with objects passed from other windows/frames, as they will inherit from different global objects - ie instanceof will fail. Workarounds for built-in objects exists: For example, you can check for arrays via Object.prototype.toString.call(x) === '[object Array]'.

OwnerDisplayName: Christoph

LastEditorDisplayName: Christoph