问:
How to use the Wicked wizard gem with AJAX?
I am using the wicked to create a multistep wizard. I want to use AJAX so that i can step through the form without having to reload the page. I can't find anything online about how to do this. Has anyone done this before? </p>

答:
I'm probably a bit late but I'm just working on a project using these same features so if there's anyone else wondering the same thing hopefully this might help.

In general, it's best to set up Wicked just like you would for a normal HTML wizard:

app/controller/set_up_positions_controller.rb

```<code>class SetUpPositionController < ApplicationController

    include Wicked::Wizard

    steps :appointment_settings, :lab_settings

    def show
        case step
        when :appointment_settings
        when :lab_settings
        end
        render_wizard
    end

    def update
        case step
        when :appointment_settings
            #LOGIC
        when :lab_settings
            #LOGIC
        end
        render_wizard @position
    end

end
</code>```

From here the trick is to create both a step_name.js.erb and a _step_name.html.erb file for each step. Ie.

app/views/set_up_positions/appointment_settings.js.erb

```<code>$('#clinics-content').html('<%= j render "clinic_management/set_up_position/appointment_settings" %>');
</code>```

app/views/set_up_positions/_appointment_settings.html.erb

```<code><%= simple_form_for [:clinic_management, @clinic, @position], url: wizard_path, method: :put, remote: true do |f| %>
  <%= f.input :bill_authorization, collection: bill_authorization_options %>
  #etc etc
<% end%>
</code>```

You'll probably want to add in some error messaging with the JS file (right now it calls the same JS and renders errors under the field names which may or may not be what you'd want in this case).

Depending on your use case it may also be easier to use one of the JS frameworks for this type of thing(like steps.js). I didn't because I understand ruby a bit better than JS, but for others it's an option as well.

Body:
I'm probably a bit late but I'm just working on a project using these same features so if there's anyone else wondering the same thing hopefully this might help.

In general, it's best to set up Wicked just like you would for a normal HTML wizard:

app/controller/set_up_positions_controller.rb

class SetUpPositionController < ApplicationController

    include Wicked::Wizard

    steps :appointment_settings, :lab_settings

    def show
        case step
        when :appointment_settings
        when :lab_settings
        end
        render_wizard
    end

    def update
        case step
        when :appointment_settings
            #LOGIC
        when :lab_settings
            #LOGIC
        end
        render_wizard @position
    end

end

From here the trick is to create both a step_name.js.erb and a _step_name.html.erb file for each step. Ie.

app/views/set_up_positions/appointment_settings.js.erb

$('#clinics-content').html('<%= j render "clinic_management/set_up_position/appointment_settings" %>');

app/views/set_up_positions/_appointment_settings.html.erb

<%= simple_form_for [:clinic_management, @clinic, @position], url: wizard_path, method: :put, remote: true do |f| %>
  <%= f.input :bill_authorization, collection: bill_authorization_options %>
  #etc etc
<% end%>

You'll probably want to add in some error messaging with the JS file (right now it calls the same JS and renders errors under the field names which may or may not be what you'd want in this case).

Depending on your use case it may also be easier to use one of the JS frameworks for this type of thing(like steps.js). I didn't because I understand ruby a bit better than JS, but for others it's an option as well.


来源: stackexchange

问:
Virtual Keyboard hides fields/textareas/contenteditable (hidden below keyboard)
I know there are already some StackOverflow threads about the problem that the virtual keyboard of mobile phones hide or overlapping input fields, text areas and so on. But all these threads were useless, I searched a lot but many talked about this problem based on Android development and also some based on web development.

I focus on web development. The problem is, there is NO thread where the problem was solved or any really useful answer was given/posted.

So I started this one with the hope that it will be solved now. So now what is the problem directly?

If you click on an area where something can be entered, on a mobile device, you would usually expect that the website scroll up and the virtual keyboard is opening after the editable area, but what happen is not like this. The virtual keyboard is opening just as an overlay - It starts overlapping the editable area.

In my case, I open a jQuery UI dialogue where my are fields located, but I think that that shouldn't matter.

So I let my thoughts crossing and came to the solution to add some additional space. Something like this: JSFiddle.

So I am able to scroll down. But this is annoying in that it is useless or with other words not needed for people which do not use a device which opens a virtual keyboard. So I thought about a function like this:

```<code>function isMobileDevice() {
    var isiPhone = navigator.userAgent.toLowerCase().indexOf("iphone");
    var isiPad = navigator.userAgent.toLowerCase().indexOf("ipad");
    var isiPod = navigator.userAgent.toLowerCase().indexOf("ipod");
    var isAndroid = navigator.userAgent.toLowerCase().indexOf("android");
    if (isiPhone > -1 || isiPad > -1 || isiPod > -1 || isAndroid > -1) {
        return true
    } else {
        return false;
    }
}
</code>```

Well, for this part would be my question did I forget a device, which also opens a virtual keyboard and the primary question would be is there anything else except my workaround? I didn't find something to recognise the virtual keyboard explicitly.

Edit 24.04.2015:

Guys I just tested it with a Samsung Galaxy Note and the newest mobile browser versions of Firefox, Chrome as well as Opera. (Updated all three, today!)

Okay here is my result:

as you can see all browsers, except Firefox, fail and THIS is the perfect visual example of my problem. The virtual keyboard is overlapping the editable area!
Usually, I prefer Chrome over any other browser, but for this case, I have to say - good work Firefox!

答:
...from the looks of the photos that have been posted, you must be using an overflown scrollable element with height:100% to hold the content. Am I right?

If so, this is why the virtual keyboard overlaps your content: virtual keyboards tend to push body content in order to focus on an input and not overflown elements. In this case, body content does not move, so the virtual keyboard just overlaps your content. I don't know if developers over at Mozilla spent more time on this specific issue, but looks like they did.

Edit: I answered the question without reading the comments first, and looks like I had already commented, but looks like my comment was disregarded - I wonder why, since probably I am spot on. :/

ContentLicense: CC BY-SA 3.0

Body:
I know there are already some StackOverflow threads about the problem that the virtual keyboard of mobile phones hide or overlapping input fields, text areas and so on. But all these threads were useless, I searched a lot but many talked about this problem based on Android development and also some based on web development.

I focus on web development. The problem is, there is NO thread where the problem was solved or any really useful answer was given/posted.

So I started this one with the hope that it will be solved now. So now what is the problem directly?

If you click on an area where something can be entered, on a mobile device, you would usually expect that the website scroll up and the virtual keyboard is opening after the editable area, but what happen is not like this. The virtual keyboard is opening just as an overlay - It starts overlapping the editable area.

In my case, I open a jQuery UI dialogue where my are fields located, but I think that that shouldn't matter.

So I let my thoughts crossing and came to the solution to add some additional space. Something like this: JSFiddle.

So I am able to scroll down. But this is annoying in that it is useless or with other words not needed for people which do not use a device which opens a virtual keyboard. So I thought about a function like this:

function isMobileDevice() {
    var isiPhone = navigator.userAgent.toLowerCase().indexOf("iphone");
    var isiPad = navigator.userAgent.toLowerCase().indexOf("ipad");
    var isiPod = navigator.userAgent.toLowerCase().indexOf("ipod");
    var isAndroid = navigator.userAgent.toLowerCase().indexOf("android");
    if (isiPhone > -1 || isiPad > -1 || isiPod > -1 || isAndroid > -1) {
        return true
    } else {
        return false;
    }
}

Well, for this part would be my question did I forget a device, which also opens a virtual keyboard and the primary question would be is there anything else except my workaround? I didn't find something to recognise the virtual keyboard explicitly.

Edit 24.04.2015:

Guys I just tested it with a Samsung Galaxy Note and the newest mobile browser versions of Firefox, Chrome as well as Opera. (Updated all three, today!)

Okay here is my result:

as you can see all browsers, except Firefox, fail and THIS is the perfect visual example of my problem. The virtual keyboard is overlapping the editable area!
Usually, I prefer Chrome over any other browser, but for this case, I have to say - good work Firefox!


问:
What's the difference between using a variable or %s in Python string formatting?
What is the difference between defining a variable and using it in a string and putting %s in a string and passing in the value after?

```<code>site = "Stackoverflow"
site + " is great!"

"%s is great!" % "Stackoverflow"
</code>```

Printing either of these gives the same result so when is it better to use one over the other?

答:
For two strings, there is little difference.

For multiple strings, s1 + s2 + s3 is less efficient, as it has to create a temporary str object for the first concatenation, where as both "%s %s %s" % (s1, s2, s3) and "{} {} {}".format(s1, s2, s3) creates the final str object immediately.

```<code>One:

'string' + 'string'

Two:

'%s %s' % ('one', 'two')
'{} {}'.format('one', 'two')
</code>```

There is a great article on this here: https://pyformat.info/

Also the docs are a great resource: https://docs.python.org/2/library/string.html#format-string-syntax

Version one is less efficient with larger amounts of concatenation.

Body:
What is the difference between defining a variable and using it in a string and putting %s in a string and passing in the value after?

site = "Stackoverflow"
site + " is great!"

"%s is great!" % "Stackoverflow"

Printing either of these gives the same result so when is it better to use one over the other?

Body:
For two strings, there is little difference.

For multiple strings, s1 + s2 + s3 is less efficient, as it has to create a temporary str object for the first concatenation, where as both "%s %s %s" % (s1, s2, s3) and "{} {} {}".format(s1, s2, s3) creates the final str object immediately.

One:

'string' + 'string'

Two:

'%s %s' % ('one', 'two')
'{} {}'.format('one', 'two')

There is a great article on this here: https://pyformat.info/

Also the docs are a great resource: https://docs.python.org/2/library/string.html#format-string-syntax

Version one is less efficient with larger amounts of concatenation.


问:
Second MySQL database PHP from WordPress page
I am building a new WP site and want to create a couple of pages that access data from a separate mysql database. I want to insert the PHP into the pages using a plugin like Insert PHP.

I've installed the plugin but, I cannot seem to get the database to connect from within the WP page.

First off, I am not even sure where to put the second mysql file on the same server. It has a different login and PW than the WP site.

Should I put it in the \var\www\html folder? I don't want to replace the DB I am using, just send some queries out to another one on the same server to get some data.

I've added PHP with the insert PHP plugin and I get an access denied message:

Connection failed: Access denied for user 'root'@'localhost'

Here is the code I use:

```<code>$servername = "localhost";
$username = "xxxx";
$password = "xxxx";
$dbname = "xxxx";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
</code>```

Please help and TY.

答: PHP is executing the script so looks like your MySQL user or password is wrong. Considering you are using 'root' which is a security concern, I would suggest you create a new user for that database.</p>

Body:
I am building a new WP site and want to create a couple of pages that access data from a separate mysql database. I want to insert the PHP into the pages using a plugin like Insert PHP.

I've installed the plugin but, I cannot seem to get the database to connect from within the WP page.

First off, I am not even sure where to put the second mysql file on the same server. It has a different login and PW than the WP site.

Should I put it in the \var\www\html folder? I don't want to replace the DB I am using, just send some queries out to another one on the same server to get some data.

I've added PHP with the insert PHP plugin and I get an access denied message:

Connection failed: Access denied for user 'root'@'localhost'

Here is the code I use:

$servername = "localhost";
$username = "xxxx";
$password = "xxxx";
$dbname = "xxxx";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

Please help and TY.


问:
Comparing file contents in F#
I wrote a quick and dirty function to compare file contents (BTW, I have already tested that they are of equal size):

```<code>let eqFiles f1 f2 =
  let bytes1 = Seq.ofArray (File.ReadAllBytes f1)
  let bytes2 = Seq.ofArray (File.ReadAllBytes f2)
  let res = Seq.compareWith (fun x y -> (int x) - (int y)) bytes1 bytes2
  res = 0
</code>```

I'm not happy with reading the whole contents into an array. I'd rather have a lazy sequence of bytes, but I can't find the right API in F#.

答:
this will compare the files byte for byte and shortcut if there's a differences along the way. It will also handle different files sizes</p>

```<code>let rec compareFiles (fs1: FileStream) (fs2: FileStream) =
      match fs1.ReadByte(),fs2.ReadByte() with
      | -1,-1 -> true //all bytes have been enumerated and were all equal
      | _,-1 -> false //the files are of different length
      | -1,_ -> false //the files are of different length
      | x,y when x <> y -> false
             //only continue to the next bytes when the present two are equal
      | _ -> compareFiles fs1 fs2
</code>```

ContentLicense: CC BY-SA 2.5

Title: Comparing file contents in F#

Body:
I wrote a quick and dirty function to compare file contents (BTW, I have already tested that they are of equal size):

let eqFiles f1 f2 =
  let bytes1 = Seq.ofArray (File.ReadAllBytes f1)
  let bytes2 = Seq.ofArray (File.ReadAllBytes f2)
  let res = Seq.compareWith (fun x y -> (int x) - (int y)) bytes1 bytes2
  res = 0

I'm not happy with reading the whole contents into an array. I'd rather have a lazy sequence of bytes, but I can't find the right API in F#.

Body:
this will compare the files byte for byte and shortcut if there's a differences along the way. It will also handle different files sizes

let rec compareFiles (fs1: FileStream) (fs2: FileStream) =
      match fs1.ReadByte(),fs2.ReadByte() with
      | -1,-1 -> true //all bytes have been enumerated and were all equal
      | _,-1 -> false //the files are of different length
      | -1,_ -> false //the files are of different length
      | x,y when x <> y -> false
             //only continue to the next bytes when the present two are equal
      | _ -> compareFiles fs1 fs2


问:
Node.js, date-time based reminder
I am building a SaaS application, where users logs in and creates reminders for a particular date and time in future, and when the time is met, my application is responsible for reminding the respective user about the reminder he/she has set in the past

Example:
Say user "Foo" logs in and creates a reminder on 2:30pm 27th April 2018 (a date time in future).

My application should send an email on that exact date-time to "Foo" as any other reminder app.

Like this there can be thousands of reminders ACTIVE for hundreds of users.

Technology

Node.js

What I tried

I have tried packages like node-schedule and other cron-job solutions but I believe/found - Cron-jobs are not designed for solving problems like one of mine.

Please help me with a solution. Thanks

答: If it's reminder by email, you should try SendGrid or Mailgun. They both offer a limited amount of emails for free. You can also try using Twilio for sms reminders. All can be set up pretty easily, you'd just have to invoke the api calls at set remind times.</p>

Title: Node.js, date-time based reminder


问:
How many times a digit show up
Please help me. I don't get why the out put is in "occurs" is "30", instead of '3'.. It's as if I'm multiplying the answer with '10', but I'm not.. Maybe the answer to my problem is right in to my code but Can someone explain why and how? please..  Thank you very much in advance..

Please take a look at my code.

```<code>#include <stdio.h>

int main(){

    int arr[10] = {7, 7, 3, 2, 9, 8, 5, 1, 7, 9};
    int occur[10] = {NULL};
    int max = 0;
    int most;

    for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            occur[arr[j]]++;
            if(occur[arr[j]] > max)
            {
                max = occur[arr[j]];
                most = arr[j];
            }
        }
    }

    printf("Most frequent: %d\ occurs: %d\n", most, max);

    return 0;
}
</code>```

I am getting the correct answer in "Most Frequent". But the "occurs" is 30, instead of just 3 because 7 occurs 3 times.

答:
It becomes 30 because there is an outer loop which executes 10 times.
I'm guessing that you want to get the most frequent number in the array and how many times it occurred that's why you have an outer loop. This will not work if you have a number in your array that is greater than 9 which will result in index out of bounds problem in occur array. You should change your implementation to this:

```<code>#include <stdio.h>

int main(){

    int arr[10] = {7, 7, 3, 2, 9, 8, 5, 1, 7, 9};
    int max = 0;
    int most;

    for(int i = 0; i < 10; i++)
    {
        int tmp = arr[i], count = 0;
        // if the current number is the current max number then skip
        if(tmp == max)
           continue;
        for(int j = 0; j < 10; j++)
        {
            // increment count if number in index j is equal to tmp number
            count += arr[j] == tmp ? 1 : 0;
        }
        // [this condition will depend on the requirement.]
        // replace max and most if the count of tmp number is greater than your
        // current max
        if(count > max){
            max = count;
            most = tmp;
        }
    }
    printf("Most frequent: %d\ occurs: %d\n", most, max);

    return 0;
}
</code>```

This is not tested so if there are any problems, please feel free to edit.

Title: How many times a digit show up

Body:
Please help me. I don't get why the out put is in "occurs" is "30", instead of '3'.. It's as if I'm multiplying the answer with '10', but I'm not.. Maybe the answer to my problem is right in to my code but Can someone explain why and how? please..  Thank you very much in advance..

Please take a look at my code.

#include <stdio.h>

int main(){

    int arr[10] = {7, 7, 3, 2, 9, 8, 5, 1, 7, 9};
    int occur[10] = {NULL};
    int max = 0;
    int most;

    for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            occur[arr[j]]++;
            if(occur[arr[j]] > max)
            {
                max = occur[arr[j]];
                most = arr[j];
            }
        }
    }

    printf("Most frequent: %d\ occurs: %d\n", most, max);

    return 0;
}

I am getting the correct answer in "Most Frequent". But the "occurs" is 30, instead of just 3 because 7 occurs 3 times.

Body:
It becomes 30 because there is an outer loop which executes 10 times.
I'm guessing that you want to get the most frequent number in the array and how many times it occurred that's why you have an outer loop. This will not work if you have a number in your array that is greater than 9 which will result in index out of bounds problem in occur array. You should change your implementation to this:

#include <stdio.h>

int main(){

    int arr[10] = {7, 7, 3, 2, 9, 8, 5, 1, 7, 9};
    int max = 0;
    int most;

    for(int i = 0; i < 10; i++)
    {
        int tmp = arr[i], count = 0;
        // if the current number is the current max number then skip
        if(tmp == max)
           continue;
        for(int j = 0; j < 10; j++)
        {
            // increment count if number in index j is equal to tmp number
            count += arr[j] == tmp ? 1 : 0;
        }
        // [this condition will depend on the requirement.]
        // replace max and most if the count of tmp number is greater than your
        // current max
        if(count > max){
            max = count;
            most = tmp;
        }
    }
    printf("Most frequent: %d\ occurs: %d\n", most, max);

    return 0;
}

This is not tested so if there are any problems, please feel free to edit.


问:
Alignment Issues
I am new to HTML/CSS and Stack-overflow. I am working on a project for my class and I'm having problems aligning the logos, breads, condiments etc. properly. I've tried different things in CSS, but nothing seemed to work. Any help would be much appreciated. Also I apologize in advance if I am posting incorrectly, this is my first attempt at stack-overflow and I am just trying to learn!

```<code>My attempt:
</code>```

https://codepen.io/megmckinsey92/pen/awqVRq/?editors=1100

答:
For each of your divs that are too wide try adding this property:

```<code>.everythingThatIsTooWide {
  width: 25%;
  margin: auto;
 }
</code>```

Also for each of your divs that that contain multiple div elements in a line such as .extra and .upgrades do this:

```<code><div class="wrapper">
/* My divs */
</div>

.wrapper {
  width: 25%;
  margin: auto;
}
</code>```

Title: Alignment Issues

Body:
I am new to HTML/CSS and Stack-overflow. I am working on a project for my class and I'm having problems aligning the logos, breads, condiments etc. properly. I've tried different things in CSS, but nothing seemed to work. Any help would be much appreciated. Also I apologize in advance if I am posting incorrectly, this is my first attempt at stack-overflow and I am just trying to learn!

My attempt:

https://codepen.io/megmckinsey92/pen/awqVRq/?editors=1100

Body:
For each of your divs that are too wide try adding this property:

.everythingThatIsTooWide {
  width: 25%;
  margin: auto;
 }

Also for each of your divs that that contain multiple div elements in a line such as .extra and .upgrades do this:

<div class="wrapper">
/* My divs */
</div>

.wrapper {
  width: 25%;
  margin: auto;
}


问:
What is the best practice for responsive website widths?
I have recently started learning how to use CSS media queries to develop websites that are responsive / mobile friendly however, I am not familiar with the best practices associated with determining which width ranges to develop designs for.

For example, I normally use three sets of CSS rules. One for a small width (mobile) , one for a medium width (tablet or small laptop screen) and one for a large width (desktop).

This is what it looks like in code:

```<code>@media screen and (min-width: 1495px)  {
//CSS RULES HERE
}

@media screen and (max-width: 1494px) and (min-width: 1245px) {
//CSS RULES HERE
}

@media screen and (max-width: 1244px) and (min-width: 751px) {
//CSS RULES HERE
}
</code>```

My sizing conventions (min width & max width) are completely arbitrary and I determine whether it works from trial and error. Often This doesn't work very well and I can't get the design to look good on all difference screen resolutions.

First of all.... Is there a best practice for the most ideal width ranges to use?

Secondly, is there a framework or template that will make all of this easier?

(That is not Bootstrap).

FYI: I use Foundation 6 to as a grid system but I haven't really found information much on responsive sites in Foundation 6.

答: You can use js to calculate the value of the font size in the HTML, then use a framework such as CSS to do the calculations dynamically</p>

Body:
I have recently started learning how to use CSS media queries to develop websites that are responsive / mobile friendly however, I am not familiar with the best practices associated with determining which width ranges to develop designs for.

For example, I normally use three sets of CSS rules. One for a small width (mobile) , one for a medium width (tablet or small laptop screen) and one for a large width (desktop).

This is what it looks like in code:

@media screen and (min-width: 1495px)  {
//CSS RULES HERE
}

@media screen and (max-width: 1494px) and (min-width: 1245px) {
//CSS RULES HERE
}

@media screen and (max-width: 1244px) and (min-width: 751px) {
//CSS RULES HERE
}

My sizing conventions (min width & max width) are completely arbitrary and I determine whether it works from trial and error. Often This doesn't work very well and I can't get the design to look good on all difference screen resolutions.

First of all.... Is there a best practice for the most ideal width ranges to use?

Secondly, is there a framework or template that will make all of this easier?

(That is not Bootstrap).

FYI: I use Foundation 6 to as a grid system but I haven't really found information much on responsive sites in Foundation 6.


问:
Typescript/Javascript: Setting a unique list with an additional property
I have the following empty array declared:

```<code>  myYears: { year: number, checked: boolean }[] = [];
</code>```

My goal is to fill this array of objects with a year and a boolean on whether or not that year is checked.  I like having the property names here as well. When initially populating myYears, I fill it like below to obtain my list of unique years from myBigDataList object array.  This is successful in giving me an array of unique year numbers, and I've gotten this far.  Now what's the best way to turn this into an array of {year: number, checked: boolean} objects instead of just numbers, and where everything is initialized to true?

```<code>  this.myYears= Array.from(new Set(this.myBigDataList.map(item => {item.activityYear})));
</code>```

答:
You can do it in your map function.

let myYears = [
  1971,
  1972,
  1973
];

myYears = myYears.map(year => {
  return {
    year: year,
    checked: true
  };
});

console.log(myYears);```

Body:
I have the following empty array declared:

  myYears: { year: number, checked: boolean }[] = [];

My goal is to fill this array of objects with a year and a boolean on whether or not that year is checked.  I like having the property names here as well. When initially populating myYears, I fill it like below to obtain my list of unique years from myBigDataList object array.  This is successful in giving me an array of unique year numbers, and I've gotten this far.  Now what's the best way to turn this into an array of {year: number, checked: boolean} objects instead of just numbers, and where everything is initialized to true?

  this.myYears= Array.from(new Set(this.myBigDataList.map(item => {item.activityYear})));


问:
NgUpgrade: Unable to use templateUrl when upgrading Angular1 components
I want to upgrade a ng1 component to be used inside an ng2 component.

If I use just a template string the ng1 component, to be upgraded, it works.  However, if I switch to using a templateUrl instead, the app crashes and give me this error:

```<code>angular.js:13920 Error: loading directive templates asynchronously is not supported
at RemoteUrlComponent.UpgradeComponent.compileTemplate (upgrade-static.umd.js:720)
at RemoteUrlComponent.UpgradeComponent (upgrade-static.umd.js:521)
at new RemoteUrlComponent (remote-url.component.ts:11)
at new Wrapper_RemoteUrlComponent (wrapper.ngfactory.js:7)
at View_AppComponent1.createInternal (component.ngfactory.js:73)
at View_AppComponent1.AppView.create (core.umd.js:12262)
at TemplateRef_.createEmbeddedView (core.umd.js:9320)
at ViewContainerRef_.createEmbeddedView (core.umd.js:9552)
at eval (common.umd.js:1670)
at DefaultIterableDiffer.forEachOperation (core.umd.js:4653)
</code>```

Here is a plunk demonstrating my issue:

https://plnkr.co/edit/2fXvfc?p=info

I've followed the Angular 1 -> 2 upgrade guide and it seems that this code should work.  I'm not quite sure why its not working.

答:
A pretty low-tech solution to this issue is to load your templates up in your index.html, and assign them IDs that match the templateUrls the directives are looking for, ie:

```<code><script type="text/ng-template" id="some/file/path.html">
  <div>
    <p>Here's my template!</p>
  </div>
</script>
</code>```

Angular then automatically puts the template into the $templateCache, which  is where UpgradeComponent's compileTemplate is looking for the template to begin with, so without changing the templateUrl in your directive, things will work because the id matches the templateUrl.

If you check the source code of UpgradeComponent (see below), you can see commented out code that deals with fetching the url, so it must be in the works, but for the time being this could be a viable solution and even a scriptable one.

```<code>private compileTemplate(directive: angular.IDirective): angular.ILinkFn {
    if (this.directive.template !== undefined) {
      return this.compileHtml(getOrCall(this.directive.template));
    } else if (this.directive.templateUrl) {
      const url = getOrCall(this.directive.templateUrl);
      const html = this.$templateCache.get(url) as string;
      if (html !== undefined) {
        return this.compileHtml(html);
      } else {
        throw new Error('loading directive templates asynchronously is not supported');
        // return new Promise((resolve, reject) => {
        //   this.$httpBackend('GET', url, null, (status: number, response: string) => {
        //     if (status == 200) {
        //       resolve(this.compileHtml(this.$templateCache.put(url, response)));
        //     } else {
        //       reject(`GET component template from '${url}' returned '${status}: ${response}'`);
        //     }
        //   });
        // });
      }
    } else {
      throw new Error(`Directive '${this.name}' is not a component, it is missing template.`);
    }
  }
</code>```

Body:
I want to upgrade a ng1 component to be used inside an ng2 component.

If I use just a template string the ng1 component, to be upgraded, it works.  However, if I switch to using a templateUrl instead, the app crashes and give me this error:

angular.js:13920 Error: loading directive templates asynchronously is not supported
at RemoteUrlComponent.UpgradeComponent.compileTemplate (upgrade-static.umd.js:720)
at RemoteUrlComponent.UpgradeComponent (upgrade-static.umd.js:521)
at new RemoteUrlComponent (remote-url.component.ts:11)
at new Wrapper_RemoteUrlComponent (wrapper.ngfactory.js:7)
at View_AppComponent1.createInternal (component.ngfactory.js:73)
at View_AppComponent1.AppView.create (core.umd.js:12262)
at TemplateRef_.createEmbeddedView (core.umd.js:9320)
at ViewContainerRef_.createEmbeddedView (core.umd.js:9552)
at eval (common.umd.js:1670)
at DefaultIterableDiffer.forEachOperation (core.umd.js:4653)

Here is a plunk demonstrating my issue:

https://plnkr.co/edit/2fXvfc?p=info

I've followed the Angular 1 -> 2 upgrade guide and it seems that this code should work.  I'm not quite sure why its not working.

Body:
A pretty low-tech solution to this issue is to load your templates up in your index.html, and assign them IDs that match the templateUrls the directives are looking for, ie:

<script type="text/ng-template" id="some/file/path.html">
  <div>
    <p>Here's my template!</p>
  </div>
</script>

Angular then automatically puts the template into the $templateCache, which  is where UpgradeComponent's compileTemplate is looking for the template to begin with, so without changing the templateUrl in your directive, things will work because the id matches the templateUrl.

If you check the source code of UpgradeComponent (see below), you can see commented out code that deals with fetching the url, so it must be in the works, but for the time being this could be a viable solution and even a scriptable one.

private compileTemplate(directive: angular.IDirective): angular.ILinkFn {
    if (this.directive.template !== undefined) {
      return this.compileHtml(getOrCall(this.directive.template));
    } else if (this.directive.templateUrl) {
      const url = getOrCall(this.directive.templateUrl);
      const html = this.$templateCache.get(url) as string;
      if (html !== undefined) {
        return this.compileHtml(html);
      } else {
        throw new Error('loading directive templates asynchronously is not supported');
        // return new Promise((resolve, reject) => {
        //   this.$httpBackend('GET', url, null, (status: number, response: string) => {
        //     if (status == 200) {
        //       resolve(this.compileHtml(this.$templateCache.put(url, response)));
        //     } else {
        //       reject(`GET component template from '${url}' returned '${status}: ${response}'`);
        //     }
        //   });
        // });
      }
    } else {
      throw new Error(`Directive '${this.name}' is not a component, it is missing template.`);
    }
  }


问:
Implementing a generic node
I keep receiving an error when I'm trying to implement a node with generic data types. the node must be able to take an int input as well as a fraction input. what am i doing wrong? The compiler says that "method Node(A) is undefined for class BinarySearchtree</p>

```<code>    //creates a generic binary search tree class
public class BinarySearchTree<A> {

    //the root of the node, which is the middle value
    Node root;

    //this constructor will add a node
    public void addNode(A userNumber){

        Node<A> newNode = Node<A>(A userNumber);

    }//end addNode

    public class Node<T>{
        //this generic variable will become the user input either int or fraction
        private T number;

        //nodes that will become the left of right child of a parent node
        Node<T> leftChild;
        Node<T> rightChild;

        //a node constructor that will take a generic input
        Node(T number){
            this.number = number;
        }//end node constructor
    }//end the Node class

}//end binary search tree
</code>```

答:
Instead of

```<code>    Node<A> newNode = Node<A>(A userNumber);
</code>```

use

```<code>    Node<A> newNode = new Node<A>(A userNumber);
</code>```

You don't have any method Node which the compiler gladly tells you about.

Title: Implementing a generic node

Body:
I keep receiving an error when I'm trying to implement a node with generic data types. the node must be able to take an int input as well as a fraction input. what am i doing wrong? The compiler says that "method Node(A) is undefined for class BinarySearchtree

    //creates a generic binary search tree class
public class BinarySearchTree {

    //the root of the node, which is the middle value
    Node root;

    //this constructor will add a node
    public void addNode(A userNumber){

        Node newNode = Node(A userNumber);

    }//end addNode

    public class Node<T>{
        //this generic variable will become the user input either int or fraction
        private T number;

        //nodes that will become the left of right child of a parent node
        Node<T> leftChild;
        Node<T> rightChild;

        //a node constructor that will take a generic input
        Node(T number){
            this.number = number;
        }//end node constructor
    }//end the Node class

}//end binary search tree

Body:
Instead of

    Node<A> newNode = Node<A>(A userNumber);

use

    Node<A> newNode = new Node<A>(A userNumber);

You don't have any method Node which the compiler gladly tells you about.


问:
Calculate an Average from user input of five to ten numbers using Methods
My assignment requires me to prompt a user for 5 to 10 numbers and then calculate the average of those numbers. I also have to use methods to do so. My question is, how do I get the program to calculate the average if exactly if I'm not sure if they will enter 5 or 10 numbers? Below is what I have so far, I'm also having a little trouble understanding how to get the methods to execute in the main method but I think I have the actual method ideas right.

It was suggested that I format as reflected below, but my problem here is that it does not print anything after the user inputs its numbers, can anyone see what I'm missing? I'm thinking maybe I did something wrong in the main method?

```<code>public class AverageWithMethods {

    public static void main(String[] args) {
        String userNumbers = getUserNums();
        double average = userNumAvg(userNumbers);
        printAverage(0, userNumbers);

    }

    public static String getUserNums() {
        Scanner in = new Scanner(System.in);
        String userNumInput = "";
        System.out.print("Please enter five to ten numbers separated by spaces: ");
        userNumInput = in.nextLine();
        return userNumInput;
    }

    public static double userNumAvg(String userNumInput) {
        Scanner in = new Scanner(System.in);
        Scanner line = new Scanner(in.nextLine());

        double count = 0;
        double average = 0.0;
        double sum =0;

        while (in.hasNextDouble()) {
            count++;
            sum = line.nextDouble();

        }
        if (count != 0) {
            average = sum / count;
            count = Double.parseDouble(userNumInput);
        }

        return average;
    }

    public static void printAverage(double average, String userNumInput) {
        System.out.printf("The average of the numbers " + userNumInput + " is %.2f", average);

    }
}
</code>```

答:
When you want to understand how many numbers input the user, you can:

```<code>String[] userNumInput = in.nextLine().split(" ");
int quantity = userNumInput.length;
</code>```

User input quantity numbers.

Here is one of the possible ways to do from your original code:

```<code>import java.util.Scanner;

public class GetAverage {

    public GetAverage() {
        String getStr = getUserNums();
        double result = userAvg(getStr);
        printAverage(result, getStr);

    }

    public String getUserNums() {
        Scanner in = new Scanner(System.in);
        System.out.println("Please enter five to ten numbers separated by spaces: ");
        return in.nextLine();
    }

    public static double userAvg(String str) {
        String[] arr = str.split(" ");
        double sum = 0.0;
        double average = 0.0;
        for (int i = 0; i < arr.length; i++) {
            sum += Integer.parseInt(arr[i]);
        }
        if (arr.length > 0) {
            average = sum / arr.length;
        }

        return average; // how do I get the program to count what to divide by since user can input 5- 10?
    }

    public static void printAverage(double average, String userNumInput) {
        System.out.printf("The average of the numbers " + userNumInput + "is %.2f", average);

    }

    public static void main(String[] args) {
        new GetAverage();

    }
}
</code>```

OUTPUT:

```<code>Please enter five to ten numbers separated by spaces:
5 7 8 9 6 3 2 4
The average of the numbers 5 7 8 9 6 3 2 4is 5.50
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My assignment requires me to prompt a user for 5 to 10 numbers and then calculate the average of those numbers. I also have to use methods to do so. My question is, how do I get the program to calculate the average if exactly if I'm not sure if they will enter 5 or 10 numbers? Below is what I have so far, I'm also having a little trouble understanding how to get the methods to execute in the main method but I think I have the actual method ideas right.

It was suggested that I format as reflected below, but my problem here is that it does not print anything after the user inputs its numbers, can anyone see what I'm missing? I'm thinking maybe I did something wrong in the main method?

public class AverageWithMethods {

    public static void main(String[] args) {
        String userNumbers = getUserNums();
        double average = userNumAvg(userNumbers);
        printAverage(0, userNumbers);

    }

    public static String getUserNums() {
        Scanner in = new Scanner(System.in);
        String userNumInput = "";
        System.out.print("Please enter five to ten numbers separated by spaces: ");
        userNumInput = in.nextLine();
        return userNumInput;
    }

    public static double userNumAvg(String userNumInput) {
        Scanner in = new Scanner(System.in);
        Scanner line = new Scanner(in.nextLine());

        double count = 0;
        double average = 0.0;
        double sum =0;

        while (in.hasNextDouble()) {
            count++;
            sum = line.nextDouble();

        }
        if (count != 0) {
            average = sum / count;
            count = Double.parseDouble(userNumInput);
        }

        return average;
    }

    public static void printAverage(double average, String userNumInput) {
        System.out.printf("The average of the numbers " + userNumInput + " is %.2f", average);

    }
}

Body:
When you want to understand how many numbers input the user, you can:

String[] userNumInput = in.nextLine().split(" ");
int quantity = userNumInput.length;

User input quantity numbers.

Here is one of the possible ways to do from your original code:

import java.util.Scanner;

public class GetAverage {

    public GetAverage() {
        String getStr = getUserNums();
        double result = userAvg(getStr);
        printAverage(result, getStr);

    }

    public String getUserNums() {
        Scanner in = new Scanner(System.in);
        System.out.println("Please enter five to ten numbers separated by spaces: ");
        return in.nextLine();
    }

    public static double userAvg(String str) {
        String[] arr = str.split(" ");
        double sum = 0.0;
        double average = 0.0;
        for (int i = 0; i < arr.length; i++) {
            sum += Integer.parseInt(arr[i]);
        }
        if (arr.length > 0) {
            average = sum / arr.length;
        }

        return average; // how do I get the program to count what to divide by since user can input 5- 10?
    }

    public static void printAverage(double average, String userNumInput) {
        System.out.printf("The average of the numbers " + userNumInput + "is %.2f", average);

    }

    public static void main(String[] args) {
        new GetAverage();

    }
}

OUTPUT:

Please enter five to ten numbers separated by spaces:
5 7 8 9 6 3 2 4
The average of the numbers 5 7 8 9 6 3 2 4is 5.50


问:
jQuery slideDown/slideUp laggy animation on Android devices
I have problem with jQuery slide animation. I'm trying to make menu which is hiding when user scrolls the page. Here is live example (works only on mobile):

$(document).ready(function() {
    if ($(window).width() < 992) {
        $(window).scroll(function() {
            if ($(this).scrollTop() > 0) {
                $('.section-menu-link').not('.section-menu-link.active').slideUp(300);
            } else {
                $('.section-menu-link').not('.section-menu-link.active').slideDown(300);
            }
        });
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.section-menu{
    margin-top: 100px;
}
.section-menu-link{
    display: block;
    height: 30px;
    text-align: center;
}
.section-menu-link.active{
    color: red;
}</code>```

  Link
  Link
  Link
  Link
  Link

Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test

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

<p>It works nice on iOS but on every Android phone I've tested it, animation doesn't work smoothly.</p>

<p>I tried to do it with CSS transition:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
    if ($(window).width() < 992) {
        $(window).scroll(function() {
            if ($(this).scrollTop() > 0) {
                $('.section-menu').addClass('hide');
            } else {
                $('.section-menu').removeClass('hide');
            }
        });
    }
});</code>```

.section-menu{
    margin-top: 100px;
}
.section-menu.hide .section-menu-link{
    max-height: 0;
}
.section-menu.hide .section-menu-link.active{
    max-height: 30px;
}
.section-menu-link{
    display: block;
    height: 30px;
    max-height: 30px;
    overflow: hidden;
    text-align: center;
    transition: max-height .3s ease;
}
.section-menu-link.active{
    color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section-menu">
Link
Link
Link
Link
Link
</div>
<div class="content">
Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test
</div></code>```

But it works as bad as in first example.

Is there any way to make it smoother?

答:
Please keep in mind that jQuery is not specialized on supporting mobile frontend development, so not everything that works in your browser behaves the same way in mobile. Events like click() and scroll() in jQuery will usually get trapped into the mobile browser waiting some milliseconds (this is on purpose to ease mobile browsing) or waiting for some additional event to happen before they trigger.

To get rid of the lag, use touch events instead of click (or desktop) events; for example, replace:

```<code>$(window).scroll(function() {
</code>```

With something similar to:

```<code>element.addEventListener("touchmove", touchMove, false);
</code>```

As you might have noticed, the code above is not JQuery but plain javascript (you can read more about this on https://developer.mozilla.org/en-US/docs/Web/Events/touchmove).

Unfortunately, jQuery doesn't handle touch events by default, so you will either have to use the JavaScript event listener or use an additional library to handle touch events (jQuery Mobile for example, although there are much better choices like https://github.com/benmajor/jQuery-Touch-Events).

Body:
I have problem with jQuery slide animation. I'm trying to make menu which is hiding when user scrolls the page. Here is live example (works only on mobile):

$(document).ready(function() {
    if ($(window).width() < 992) {
        $(window).scroll(function() {
            if ($(this).scrollTop() > 0) {
                $('.section-menu-link').not('.section-menu-link.active').slideUp(300);
            } else {
                $('.section-menu-link').not('.section-menu-link.active').slideDown(300);
            }
        });
    }
});

.section-menu{
    margin-top: 100px;
}
.section-menu-link{
    display: block;
    height: 30px;
    text-align: center;
}
.section-menu-link.active{
    color: red;
}

  Link
  Link
  Link
  Link
  Link

Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test

It works nice on iOS but on every Android phone I've tested it, animation doesn't work smoothly.

I tried to do it with CSS transition:

$(document).ready(function() {
    if ($(window).width() < 992) {
        $(window).scroll(function() {
            if ($(this).scrollTop() > 0) {
                $('.section-menu').addClass('hide');
            } else {
                $('.section-menu').removeClass('hide');
            }
        });
    }
});

.section-menu{
    margin-top: 100px;
}
.section-menu.hide .section-menu-link{
    max-height: 0;
}
.section-menu.hide .section-menu-link.active{
    max-height: 30px;
}
.section-menu-link{
    display: block;
    height: 30px;
    max-height: 30px;
    overflow: hidden;
    text-align: center;
    transition: max-height .3s ease;
}
.section-menu-link.active{
    color: red;
}

Link
Link
Link
Link
Link

Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test

But it works as bad as in first example.

Is there any way to make it smoother?

Body:
Please keep in mind that jQuery is not specialized on supporting mobile frontend development, so not everything that works in your browser behaves the same way in mobile. Events like click() and scroll() in jQuery will usually get trapped into the mobile browser waiting some milliseconds (this is on purpose to ease mobile browsing) or waiting for some additional event to happen before they trigger.

To get rid of the lag, use touch events instead of click (or desktop) events; for example, replace:

$(window).scroll(function() {

With something similar to:

element.addEventListener("touchmove", touchMove, false);

As you might have noticed, the code above is not JQuery but plain javascript (you can read more about this on https://developer.mozilla.org/en-US/docs/Web/Events/touchmove).

Unfortunately, jQuery doesn't handle touch events by default, so you will either have to use the JavaScript event listener or use an additional library to handle touch events (jQuery Mobile for example, although there are much better choices like https://github.com/benmajor/jQuery-Touch-Events).


问:
How can I extract only the email body with Python using IMAP?
I am relatively new to programming and to python, but I think I have done ok so far. This is the code I have, and it works fine, except it gets the entire message in MIME format. I only want the text body of unread emails, but I can't quite figure it out how to strip out all of the formatting and header info. If I send a basic email using a smtp python script that I made it works fine, and only prints the body, but if I send the email using outlook it prints a bunch of extra garbage. Any help is very much appreciated.

```<code>client = imaplib.IMAP4_SSL(PopServer)

client.login(USER, PASSWORD)
client.select('INBOX')
status, email_ids = client.search(None, '(UNSEEN SUBJECT "%s")' % PrintSubject)
print email_ids
client.store(email_ids[0].replace(' ',','),'+FLAGS','\Seen')
for email in get_emails(email_ids):
</code>```

get_emails()

```<code>    def get_emails(email_ids):
        data = []
        for e_id in email_ids[0].split():
            _, response = client.fetch(e_id, '(UID BODY[TEXT])')
            data.append(response[0][1])
        return data
</code>```

答:
Sounds like you're looking for the email package:

The email package provides a standard parser that understands most email document structures, including MIME documents. You can pass the parser a string or a file object, and the parser will return to you the root Message instance of the object structure. For simple, non-MIME messages the payload of this root object will likely be a string containing the text of the message. For MIME messages, the root object will return True from its is_multipart() method, and the subparts can be accessed via the get_payload() and walk() methods.

Body:
I am relatively new to programming and to python, but I think I have done ok so far. This is the code I have, and it works fine, except it gets the entire message in MIME format. I only want the text body of unread emails, but I can't quite figure it out how to strip out all of the formatting and header info. If I send a basic email using a smtp python script that I made it works fine, and only prints the body, but if I send the email using outlook it prints a bunch of extra garbage. Any help is very much appreciated.

client = imaplib.IMAP4_SSL(PopServer)

client.login(USER, PASSWORD)
client.select('INBOX')
status, email_ids = client.search(None, '(UNSEEN SUBJECT "%s")' % PrintSubject)
print email_ids
client.store(email_ids[0].replace(' ',','),'+FLAGS','\Seen')
for email in get_emails(email_ids):

get_emails()

    def get_emails(email_ids):
        data = []
        for e_id in email_ids[0].split():
            _, response = client.fetch(e_id, '(UID BODY[TEXT])')
            data.append(response[0][1])
        return data


问:
Bootstrap problems when resizing my browser
I've found some problems in a template I've done with Bootstrap, and I'm almost crazy on finding what's happening with this strange behaviour. Can you help me make this site present exactly as is seen in a mobile phone when I resize my browser? I think I lack something...

The website is http://www.joanraga.com/blog, when you open it in a mobile browser it fits nicely, all responsive and good. When you open it in a computer browser, it does as well, but when you resize the browser it looks like somebody fooled my CSS. If you use the adaptative view on Firefox, it shows nicely as well.

I'll post here some pics about how it's supossed to be seen:

Tablet mode, nice

Phone mode, nice

Resized browser, all f&%$*d up

答: checking your page it seems that you have defined as min width 992 px, that's why you are seeing that behaviour: @media (min-device-width: 992px) use min-width instead.


问:
Beginner at programming. C++ colon on line 9 included in this example code from textbook. I understand up to line 8 but what does the colon do?
Colon on line 9 is throwing me off. I'm not sure what its purpose is.</p>

```<code>    #include <iostream>
    using namespace std;

    const int TOTALYEARS = 100;

    int main()
    {
        int ageFrequency[TOTALYEARS]; // reserves memory for 100 ints
        :
        return 0;
    }
</code>```

答: Not sure if this was insinuating cheating or copying from review notes. The example was, in fact, from the guided reading that is assigned before the knowledge is applied to various exercises that follow.

Body:
Colon on line 9 is throwing me off. I'm not sure what its purpose is.

    #include <iostream>
    using namespace std;

    const int TOTALYEARS = 100;

    int main()
    {
        int ageFrequency[TOTALYEARS]; // reserves memory for 100 ints
        :
        return 0;
    }


问:
Dynamic Object .NET
I am facing an interesting problem right now.
I know it is not that pretty but I have to cope with it anyway.

I am calling a webservice that returns (array of string) something like that (by index)

0 - Table Name ("Employees")

1 - List of all fields returned ("Id, Name, Birthdate")

2 - First field value ("1")

3 - Second field value ("Bobby")

4 - Third field value ("1970-01-01")

What I would like to accomplish is to create a object name after the index 0, having all the strings in the index 1 being all the properties and feed them with their proper value.

What would be the best way to accomplish this? I have started reading about the ExpandoObject but before going too far I would like to hear your take on this.

Regards

EDIT: I will have quite a few different tables to fetch the data from, that is what is causing me the problem.

答:
If you recive always different kinds of objects with non-predictable set of fields that using ExpandoObject is a good idea (Take a look on Clay library in this case). In other case you just need to create some types that reflects the structure of your object and then materialize them.

Obviously you can use just a simple dictionary, but Using Dynamic object can give you more power, you decide. Real usage case will allow me to give you a better help.

Title: Dynamic Object .NET


问:
How to save a student from the model?
I have two models, one is called Employer and the other is called Student. Employers can view student profiles. How can I let employers save student profiles they like?

What I mean by that is, when the employer views a student profile and they like it, they must be able to click "save" and a link to that user profile will be saved and displayed on the employers profile. So when the employer goes to his own profile page, there will be a section called "Saved students" and links to the profiles of the students will be there.

I was thinking I add an array called "saved_profiles" to the employer model and then add a "save" button to the student profile. When an employer clicks it, the web address they are looking at right now, gets added to the saved_profiles array. By web address, I mean like "www.mywebsite.com/students/jake-madison". I'm not completely sure how to implement this though, any help on how to make this happen will be greatly appreciated.

答:
An array on the "employers" table is what we would call a "denormalized" strategy. A "normalized" strategy would involve storing that save as a record in a join table. The denormalized solution is quick and easy - at first. It can cause headaches later on. So let's talk about the normalized solution using Rail's magical has many through association.

rails

```<code>class Employer
  has_many :employer_students
  has_many :students, through: :employer_students

class Student

class EmployerStudent
  belongs_to :student
  belongs_to :employer
</code>```

database

```<code>table: students
columns: id, name

table: employers
columns: id, name

table: employer_students
columns: employer_id, student_id
</code>```

When an employer "saves" a student's profile, we create a record in the employer_students table, linking that employer to that student. Then, when we want to see the students that an employer has saved, we do a join.

```<code>employer.students
</code>```

Title: How to save a student from the model?

Body:
An array on the "employers" table is what we would call a "denormalized" strategy. A "normalized" strategy would involve storing that save as a record in a join table. The denormalized solution is quick and easy - at first. It can cause headaches later on. So let's talk about the normalized solution using Rail's magical has many through association.

rails

class Employer
  has_many :employer_students
  has_many :students, through: :employer_students

class Student

class EmployerStudent
  belongs_to :student
  belongs_to :employer

database

table: students
columns: id, name

table: employers
columns: id, name

table: employer_students
columns: employer_id, student_id

When an employer "saves" a student's profile, we create a record in the employer_students table, linking that employer to that student. Then, when we want to see the students that an employer has saved, we do a join.

employer.students


问:
How to Combine Array String As Keys And Number As Value In Php
I have a problem to do the combining between 2 arrays.

In the first array as a string (example array data):

```<code>Array
(
    [0] => courses
    [1] => courses
    [2] => courses
    [3] => courses
    [4] => courses
)
</code>```

Second array as a value (Example Array values):

```<code>Array
(
    [0] => 64
    [1] => 63
    [2] => 62
    [3] => 2
    [4] => 9
)
</code>```

After I tried to combine between 2 arrays like this:

$combine = (array_combine($data, $courses))

I can only get a combination result like this:

```<code>Array
(
    [courses] => 9
)
</code>```

How can i get the result of combination between the two arrays above, like this?

```<code>Array
(
    [courses] => 64
    [courses] => 63
    [courses] => 62
    [courses] => 2
    [courses] => 9
)
</code>```

Thanks In Advance.

答:
You are not able to generate your intended output as you can't have multiple of the same key in an array. This is why you are ending up with one entry of 'courses'.

For example this would be do-able:

```<code>Array
(
    [courses] => array(
        [0] => 63
        [1] => 63
        [2] => 62
        [3] => 2
        [4] => 9
    )
)
</code>```

You need to change your approach.

Body:
I have a problem to do the combining between 2 arrays.

In the first array as a string (example array data):

Array
(
    [0] => courses
    [1] => courses
    [2] => courses
    [3] => courses
    [4] => courses
)

Second array as a value (Example Array values):

Array
(
    [0] => 64
    [1] => 63
    [2] => 62
    [3] => 2
    [4] => 9
)

After I tried to combine between 2 arrays like this:

$combine = (array_combine($data, $courses))

I can only get a combination result like this:

Array
(
    [courses] => 9
)

How can i get the result of combination between the two arrays above, like this?

Array
(
    [courses] => 64
    [courses] => 63
    [courses] => 62
    [courses] => 2
    [courses] => 9
)

Thanks In Advance.

Body:
You are not able to generate your intended output as you can't have multiple of the same key in an array. This is why you are ending up with one entry of 'courses'.

For example this would be do-able:

Array
(
    [courses] => array(
        [0] => 63
        [1] => 63
        [2] => 62
        [3] => 2
        [4] => 9
    )
)

You need to change your approach.


问:
pg_config executable not found
I am having trouble installing psycopg2. I get the following error when I try to pip install psycopg2:

```<code>Error: pg_config executable not found.

Please add the directory containing pg_config to the PATH

or specify the full executable path with the option:

    python setup.py build_ext --pg-config /path/to/pg_config build ...

or with the pg_config option in 'setup.cfg'.

----------------------------------------
Command python setup.py egg_info failed with error code 1 in /tmp/pip-build/psycopg2
</code>```

But the problem is pg_config is actually in my PATH; it runs without any problem:

```<code>$ which pg_config
/usr/pgsql-9.1/bin/pg_config
</code>```

I tried adding the pg_config path to the setup.cfg file and building it using the source files I downloaded from their website (http://initd.org/psycopg/) and I get the following error message!

```<code>Error: Unable to find 'pg_config' file in '/usr/pgsql-9.1/bin/'
</code>```

But it is actually THERE!!!

I am baffled by these errors. Can anyone help please?

By the way, I sudo all the commands. Also I am on RHEL 5.5.

答:
On alpine, the library containing pg_config is postgresql-dev. To install, run:

```<code>apk add postgresql-dev
</code>```

Title: pg_config executable not found

Body:
I am having trouble installing psycopg2. I get the following error when I try to pip install psycopg2:

Error: pg_config executable not found.

Please add the directory containing pg_config to the PATH

or specify the full executable path with the option:

    python setup.py build_ext --pg-config /path/to/pg_config build ...

or with the pg_config option in 'setup.cfg'.

----------------------------------------
Command python setup.py egg_info failed with error code 1 in /tmp/pip-build/psycopg2

But the problem is pg_config is actually in my PATH; it runs without any problem:

$ which pg_config
/usr/pgsql-9.1/bin/pg_config

I tried adding the pg_config path to the setup.cfg file and building it using the source files I downloaded from their website (http://initd.org/psycopg/) and I get the following error message!

Error: Unable to find 'pg_config' file in '/usr/pgsql-9.1/bin/'

But it is actually THERE!!!

I am baffled by these errors. Can anyone help please?

By the way, I sudo all the commands. Also I am on RHEL 5.5.

Body:
On alpine, the library containing pg_config is postgresql-dev. To install, run:

apk add postgresql-dev


问:
Saving layer weights at each epoch during training into a numpy type/array? Converting TensorFlow Variable to numpy array?
I am working with keras for the first time and am attempting to write a custom keras.callbacks.Callback which saves the weights of each model layer during fit. I am having trouble converting the type of keras.models.layers.weights to a numpy array (or anything from which I can extract the primitive type value).

From what I can tell keras.models.layers.weights (for my model) is a list of tensorflow.python.ops.variables.Variable that hold either a (1, 1) matrix or (1,) matrix. I just cannot seem to get this variable type as a float (the dtype of the matrices).

Here is a SSCCE of my issue.

```<code>import keras
import numpy as np

xONE = np.mat([[0], [1]])
yNOT = np.mat([[1], [0]])

# Simple Keras callback which saves not only loss and acc
# but also the layer weights at each epoch end
class History_LAW(keras.callbacks.Callback):
    def on_train_begin(self, logs={}):
        self.epoch = []
        self.weights = []
        self.history = {}
        self.weights.append(self.model.weights)

    def on_epoch_end(self, epoch, logs={}):
        logs = logs or {}
        self.epoch.append(epoch)
        self.weights.append(self.model.weights)
        for k, v in logs.items():
            self.history.setdefault(k, []).append(v)

# Used to programmatically generaly a simple model
# given the data that it is meant to fit to
def generateModel(xShape, yShape):
    model = keras.models.Sequential()
    model.add(
        keras.layers.Dense(
            yShape[1], input_shape = (xShape[1],)))
    model.add(keras.layers.Activation('hard_sigmoid'))
    model.summary()
    return model

# Generate a model based on the simply NOT relationship
model = generateModel(xONE.shape, yNOT.shape)
model.compile(
    optimizer = 'adam',
    loss = 'binary_crossentropy',
    metrics = ['accuracy'])

# Create the custom callback and pass it to fit
model_Hist = History_LAW()
model.fit(xONE, yNOT,
    epochs = 4, batch_size = 2, verbose = 1, callbacks = [model_Hist])

# Display the raw weight structure and its type
print('========== Raw w output')
for weight in model_Hist.weights:
    print([w for w in weight])

print('========== Type of w')
for weight in model_Hist.weights:
    print([type(w) for w in weight])
</code>```

I did find this SO answer which proposes to use eval() (I think a TensorFlow function) to "evalute" the tensors (not exactly sure what that means yet but I think thats the proper terminology) into their underlying type -- Which I assume is a numpy matrix or array. Though follow this seems to lead down another rabbit hole of errors (passing session = tf.InteractiveSession) to eval, resulting in "the tensor's graph is different from the session's graph.").

I have found various callbacks which can record layer weights during fitting though from what I can tell none of them return them in the desired format.

How can I convert these weights to some numpy object? Is there an easier way other than what I propose in the SSCCE to accomplish what I want?

For reference the output of the SSCCE above is:

```<code>========== Raw w output
[<tf.Variable 'dense_1/kernel:0' shape=(1, 1) dtype=float32_ref>, <tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32_ref>]
[<tf.Variable 'dense_1/kernel:0' shape=(1, 1) dtype=float32_ref>, <tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32_ref>]
[<tf.Variable 'dense_1/kernel:0' shape=(1, 1) dtype=float32_ref>, <tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32_ref>]
[<tf.Variable 'dense_1/kernel:0' shape=(1, 1) dtype=float32_ref>, <tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32_ref>]
[<tf.Variable 'dense_1/kernel:0' shape=(1, 1) dtype=float32_ref>, <tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32_ref>]
========== Type of w
[<class 'tensorflow.python.ops.variables.Variable'>, <class 'tensorflow.python.ops.variables.Variable'>]
[<class 'tensorflow.python.ops.variables.Variable'>, <class 'tensorflow.python.ops.variables.Variable'>]
[<class 'tensorflow.python.ops.variables.Variable'>, <class 'tensorflow.python.ops.variables.Variable'>]
[<class 'tensorflow.python.ops.variables.Variable'>, <class 'tensorflow.python.ops.variables.Variable'>]
[<class 'tensorflow.python.ops.variables.Variable'>, <class 'tensorflow.python.ops.variables.Variable'>]
</code>```

答:
I have found that I need to use the method keras.model.layer.get_weights() to get the weights as numpy arrays.

For instance my callback would change to something like

```<code>def on_epoch_end(self, epoch, logs={}):
    logs = logs or {}
    self.epoch.append(epoch)
    for k, v in logs.items():
        self.history.setdefault(k, []).append(v)

    modelWeights = []
    for layer in model.layers:
        layerWeights = []
        for weight in layer.get_weights():
            layerWeights.append(weight)
        modelWeights.append(layerWeights)
    self.weights.append(modelWeights)
</code>```

Body:
I am working with keras for the first time and am attempting to write a custom keras.callbacks.Callback which saves the weights of each model layer during fit. I am having trouble converting the type of keras.models.layers.weights to a numpy array (or anything from which I can extract the primitive type value).

From what I can tell keras.models.layers.weights (for my model) is a list of tensorflow.python.ops.variables.Variable that hold either a (1, 1) matrix or (1,) matrix. I just cannot seem to get this variable type as a float (the dtype of the matrices).

Here is a SSCCE of my issue.

import keras
import numpy as np

xONE = np.mat([[0], [1]])
yNOT = np.mat([[1], [0]])

# Simple Keras callback which saves not only loss and acc
# but also the layer weights at each epoch end
class History_LAW(keras.callbacks.Callback):
    def on_train_begin(self, logs={}):
        self.epoch = []
        self.weights = []
        self.history = {}
        self.weights.append(self.model.weights)

    def on_epoch_end(self, epoch, logs={}):
        logs = logs or {}
        self.epoch.append(epoch)
        self.weights.append(self.model.weights)
        for k, v in logs.items():
            self.history.setdefault(k, []).append(v)

# Used to programmatically generaly a simple model
# given the data that it is meant to fit to
def generateModel(xShape, yShape):
    model = keras.models.Sequential()
    model.add(
        keras.layers.Dense(
            yShape[1], input_shape = (xShape[1],)))
    model.add(keras.layers.Activation('hard_sigmoid'))
    model.summary()
    return model

# Generate a model based on the simply NOT relationship
model = generateModel(xONE.shape, yNOT.shape)
model.compile(
    optimizer = 'adam',
    loss = 'binary_crossentropy',
    metrics = ['accuracy'])

# Create the custom callback and pass it to fit
model_Hist = History_LAW()
model.fit(xONE, yNOT,
    epochs = 4, batch_size = 2, verbose = 1, callbacks = [model_Hist])

# Display the raw weight structure and its type
print('========== Raw w output')
for weight in model_Hist.weights:
    print([w for w in weight])

print('========== Type of w')
for weight in model_Hist.weights:
    print([type(w) for w in weight])

I did find this SO answer which proposes to use eval() (I think a TensorFlow function) to "evalute" the tensors (not exactly sure what that means yet but I think thats the proper terminology) into their underlying type -- Which I assume is a numpy matrix or array. Though follow this seems to lead down another rabbit hole of errors (passing session = tf.InteractiveSession) to eval, resulting in "the tensor's graph is different from the session's graph.").

I have found various callbacks which can record layer weights during fitting though from what I can tell none of them return them in the desired format.

How can I convert these weights to some numpy object? Is there an easier way other than what I propose in the SSCCE to accomplish what I want?

For reference the output of the SSCCE above is:

========== Raw w output
[<tf.Variable 'dense_1/kernel:0' shape=(1, 1) dtype=float32_ref>, <tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32_ref>]
[<tf.Variable 'dense_1/kernel:0' shape=(1, 1) dtype=float32_ref>, <tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32_ref>]
[<tf.Variable 'dense_1/kernel:0' shape=(1, 1) dtype=float32_ref>, <tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32_ref>]
[<tf.Variable 'dense_1/kernel:0' shape=(1, 1) dtype=float32_ref>, <tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32_ref>]
[<tf.Variable 'dense_1/kernel:0' shape=(1, 1) dtype=float32_ref>, <tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32_ref>]
========== Type of w
[<class 'tensorflow.python.ops.variables.Variable'>, <class 'tensorflow.python.ops.variables.Variable'>]
[<class 'tensorflow.python.ops.variables.Variable'>, <class 'tensorflow.python.ops.variables.Variable'>]
[<class 'tensorflow.python.ops.variables.Variable'>, <class 'tensorflow.python.ops.variables.Variable'>]
[<class 'tensorflow.python.ops.variables.Variable'>, <class 'tensorflow.python.ops.variables.Variable'>]
[<class 'tensorflow.python.ops.variables.Variable'>, <class 'tensorflow.python.ops.variables.Variable'>]

Body:
I have found that I need to use the method keras.model.layer.get_weights() to get the weights as numpy arrays.

For instance my callback would change to something like

def on_epoch_end(self, epoch, logs={}):
    logs = logs or {}
    self.epoch.append(epoch)
    for k, v in logs.items():
        self.history.setdefault(k, []).append(v)

    modelWeights = []
    for layer in model.layers:
        layerWeights = []
        for weight in layer.get_weights():
            layerWeights.append(weight)
        modelWeights.append(layerWeights)
    self.weights.append(modelWeights)


问:
The account you entered is not recognized. Contact your Team Foundation Server administrator to add your account
I am using TFS 2013 and I am trying to customize a workitem template using the ProcessEditor form (I also tried to do the same using the editing and importing xml file),I am trying to add a "ReadlOnly" rule to a field only for some new TFS global group, so I added the new Group and after that I could see and select the newly added Group from the "For" dropdown but when I am trying to save the changes I always got the error "The account you entered is not recognized. Contact your Team Foundation Server administrator to add your account" I googled the error and found a suggestion here http://www.databaseforum.info/30/943697.aspx that it may be a caching issue so I waited days for this and restarted the client and the TFS server machines but without any luck  although I can use old created groups without any issues however if I renamed one of these old groups then tried to use it I still got the same error message no matter I add the new groups as a member of any other group.</p>

答:
First, make sure your TFS admin  not have done any security changes (adding account or groups or permissions) for your account.

If not, you could try below  two possibilities to narrow down the issue:

Check if you had added a field that contained backslashes as values
   and TFS may interpreted it as user account. For example if your field
   contained a list of suggested values that looked like this: Category
   1\Subcategory 1

When you add a value such as

```<code><TRANSITION from="Resolved" to="Complete" for="[project]AllTesters" not="[project]NewTesters">
</TRANSITION>
</code>```

you should not extend the project to [your project name]AllTesters, should just use [project]AllTesters

For more detail info and ways, please refer below similar issues:

TF26204: The account you entered is not recognized

Experiment on Limit AssignedTo field of WIT to Team Members

Warnings TF26171 and TF26204 during WIT import

Body:
First, make sure your TFS admin  not have done any security changes (adding account or groups or permissions) for your account.

If not, you could try below  two possibilities to narrow down the issue:

Check if you had added a field that contained backslashes as values
   and TFS may interpreted it as user account. For example if your field
   contained a list of suggested values that looked like this: Category
   1\Subcategory 1

When you add a value such as

<TRANSITION from="Resolved" to="Complete" for="[project]AllTesters" not="[project]NewTesters">
</TRANSITION>

you should not extend the project to [your project name]AllTesters, should just use [project]AllTesters

For more detail info and ways, please refer below similar issues:

TF26204: The account you entered is not recognized

Experiment on Limit AssignedTo field of WIT to Team Members

Warnings TF26171 and TF26204 during WIT import


问:
Render a Markdown file stored in S3 uploaded with shrine - Rails
I'm using shrine to upload files from my rails application to S3. All is working fine, but I dont know how to display that file using redcarpet gem.

For example I can do this:

```<code><div>
    <%= markdown("##title
    * ") %>
</div>
</code>```

And works fine.

But if I do this:

```<code><%= markdown(@rfile.rfile.url) %>
</code>```

Is showing me a download link from S3.

How I can get the file content and not the file link?

答:
Call to @rfile.rfile returns a Shrine::UploadedFile object, which has many more convenient methods other than just #url. On such method is #read, which retrieves content of the file:

```<code><%= markdown(@rfile.rfile.read) %>
</code>```

However, in this case the file would be opened and read, but not closed. So it's better to call #open with a block, and call #read on the yielded IO object, which can be neatly written as

```<code><%= markdown(@rfile.rfile.open(&:read)) %>
</code>```

Body:
I'm using shrine to upload files from my rails application to S3. All is working fine, but I dont know how to display that file using redcarpet gem.

For example I can do this:

    <%= markdown("##title
    * ") %>

And works fine.

But if I do this:

<%= markdown(@rfile.rfile.url) %>

Is showing me a download link from S3.

How I can get the file content and not the file link?

Body:
Call to @rfile.rfile returns a Shrine::UploadedFile object, which has many more convenient methods other than just #url. On such method is #read, which retrieves content of the file:

<%= markdown(@rfile.rfile.read) %>

However, in this case the file would be opened and read, but not closed. So it's better to call #open with a block, and call #read on the yielded IO object, which can be neatly written as

<%= markdown(@rfile.rfile.open(&:read)) %>


问:
Python Import failing
I have a simple structure of my Flask application and couldn't make imports.

```<code>FlaskFolder
__init__.py (includes db parameters for flask SqlAlchemy)
dbase.py (Trying to import DB variable from __init__.py and its failing.
</code>```

In my __init__.py I am trying to import like "from FlaskFolder import dbase" within the same folder and I couldn't do it.

In my dbase.py I am trying to import like "from FlaskFolder import db" (db is a class in __init__.py) but couldn't do it.

```<code>Error: No module named FlaskFolder
</code>```

Please advise how to resolve this issue.

答:
I think this is circular import.

First, when from FlaskFolder import dbase in __init__.py，program will
execute dbase.py file. The file will execute from FlaskFolder import db.
This will go to __init__.py, execute the from FlaskFolder import dbase.
And balalala....

This has 2 solutions.

in __init__.py, let from FlaskFolder import dbase after flask SqlAlchemy db define.

define flask SqlAlchemy db in dbbase.py. and import it in __init__.py

Title: Python Import failing

Body:
I have a simple structure of my Flask application and couldn't make imports.

FlaskFolder
__init__.py (includes db parameters for flask SqlAlchemy)
dbase.py (Trying to import DB variable from __init__.py and its failing.

In my __init__.py I am trying to import like "from FlaskFolder import dbase" within the same folder and I couldn't do it.

In my dbase.py I am trying to import like "from FlaskFolder import db" (db is a class in __init__.py) but couldn't do it.

Error: No module named FlaskFolder

Please advise how to resolve this issue.


问:
Issues on Installing a Github Package on Python
I am quite new in Github and I would like to install a module

I run this on my cmd:

```<code>C:\Users\memonkey>pip install git+git://github.com/bitsoex/bitso-py
Collecting git+git://github.com/bitsoex/bitso-py
Cloning git://github.com/bitsoex/bitso-py to
c:\users\memonkey\appdata\local\temp\pip-a9n7xpt6-build
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\memonkey\AppData\Local\Temp\pip-a9n7xpt6-build\setup.py", line 5, in <module>
    long_description = open('README.md').read()
  File "C:\ProgramData\Anaconda3\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 23274: character maps to <undefined>

    ----------------------------------------
 Command "python setup.py egg_info" failed with error code 1 in
 C:\Users\memonkey\AppData\Local\Temp\pip-a9n7xpt6-build\
</code>```

I have no idea what is going on, anybody could help me on this

答:
The problem is that on windows, the encoding defaults to cp1252, failing to decode curly quotes in the text: “Major_Minor”..... in the Notations Section

So, replacing the curly quotes in the license file with normal ones should resolve this issue. So pls contact the developer of that repo for the fix Or fork that repo on your github, fix the content in Notations section from

```<code>...as “Major_Minor”. For example: “btc_mxn”
</code>```

to

```<code>...as "Major_Minor". For example: "btc_mxn"
</code>```

And pip install from your repo

Body:
I am quite new in Github and I would like to install a module

I run this on my cmd:

C:\Users\memonkey>pip install git+git://github.com/bitsoex/bitso-py
Collecting git+git://github.com/bitsoex/bitso-py
Cloning git://github.com/bitsoex/bitso-py to
c:\users\memonkey\appdata\local\temp\pip-a9n7xpt6-build
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\memonkey\AppData\Local\Temp\pip-a9n7xpt6-build\setup.py", line 5, in <module>
    long_description = open('README.md').read()
  File "C:\ProgramData\Anaconda3\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 23274: character maps to <undefined>

    ----------------------------------------
 Command "python setup.py egg_info" failed with error code 1 in
 C:\Users\memonkey\AppData\Local\Temp\pip-a9n7xpt6-build\

I have no idea what is going on, anybody could help me on this

Body:
The problem is that on windows, the encoding defaults to cp1252, failing to decode curly quotes in the text: “Major_Minor”..... in the Notations Section

So, replacing the curly quotes in the license file with normal ones should resolve this issue. So pls contact the developer of that repo for the fix Or fork that repo on your github, fix the content in Notations section from

...as “Major_Minor”. For example: “btc_mxn”

to

...as "Major_Minor". For example: "btc_mxn"

And pip install from your repo