问:
Show Hide Text using JavaScript by words not characters
I have found this code that works great, but it counts by characters. As a result the words sometimes are incomplete, and when you click on read more it creates a space in the word. I have also found a function of how to count by words, but I don't have the know how to merge the two. Below is my working code, and the function
Thanks

====== Working Code ======

// Show more text option -campaing page
    var showChar = 196;  // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Read more";
    var lesstext = "Read less";

    //Cut content based on showChar length
    if ($(".toggle-text").length) {
        $(".toggle-text").each(function() {

            var content = $(this).html();

            if(content.length > showChar) {

                var contentExcert = content.substr(0, showChar);
                var contentRest = content.substr(showChar, content.length - showChar);
                var html = contentExcert + '' + ellipsestext + '  ' + contentRest + '' + moretext + '';

                $(this).html(html);
            }
        });
    }

    //Toggle content when click on read more link
    $(".toggle-text-link").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });```
</div>
</div>
</p>

<p>====== Function Code ======</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>function limitWords(element, quantity){

   var text = $(element).text();

   var words = text.split(" ");

   quantity = Math.min( quantity, words.length );

   $(element).text( words.slice(0,quantity) + "..." );

}</code>```

答:
Here ya go:</p>

```<code>var charCount = 0;
var contentExcert = content.split(" ").map((n)=>{
    charCount += n.length + 1;
    return charCount - 1 <= showChar ? n : false;
}).filter(n=>n).join(" ");
charCount = 0;
var contentRest = content.split(" ").map((n)=>{
    charCount += n.length + 1;
    return charCount - 1 >= showChar ? n : false;
}).filter(n=>n).join(" ");
</code>```

Body:
I have found this code that works great, but it counts by characters. As a result the words sometimes are incomplete, and when you click on read more it creates a space in the word. I have also found a function of how to count by words, but I don't have the know how to merge the two. Below is my working code, and the function
Thanks

====== Working Code ======

// Show more text option -campaing page
    var showChar = 196;  // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Read more";
    var lesstext = "Read less";

    //Cut content based on showChar length
    if ($(".toggle-text").length) {
        $(".toggle-text").each(function() {

            var content = $(this).html();

            if(content.length > showChar) {

                var contentExcert = content.substr(0, showChar);
                var contentRest = content.substr(showChar, content.length - showChar);
                var html = contentExcert + '' + ellipsestext + '  ' + contentRest + '' + moretext + '';

                $(this).html(html);
            }
        });
    }

    //Toggle content when click on read more link
    $(".toggle-text-link").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });

====== Function Code ======

function limitWords(element, quantity){

   var text = $(element).text();

   var words = text.split(" ");

   quantity = Math.min( quantity, words.length );

   $(element).text( words.slice(0,quantity) + "..." );

}

Body:
Here ya go:

var charCount = 0;
var contentExcert = content.split(" ").map((n)=>{
    charCount += n.length + 1;
    return charCount - 1 <= showChar ? n : false;
}).filter(n=>n).join(" ");
charCount = 0;
var contentRest = content.split(" ").map((n)=>{
    charCount += n.length + 1;
    return charCount - 1 >= showChar ? n : false;
}).filter(n=>n).join(" ");


来源: stackexchange

问:
Android TextView with multiple lines
I want a TextView that should be broken into 4 lines. For e.g.

```<code>Vishal Vyas
  Having
   342
Reputation
</code>```

Note, the gravity should be center_horizontal

I tried following :

```<code><TextView
    android:gravity="center_horizontal"
    android:id="@+id/lblUserRep"
    android:layout_width="70dp"
    android:layout_height="wrap_content"
    android:lines="4"
    android:maxLines="4"
    android:text="VishalVyas Having 342 Reputation" >
</TextView>
</code>```

This works! but produces following output:

```<code>VishalVyas
  Having
   342
Reputation
</code>```

Problems:

It doesn't work with the space between words Vishal and Vyas.

android:layout_width="70dp" is harcoded and there can be any name with n number of characters instead of VishalVyas.

Please advice.

Added:
It would be fine if I need to write a custom TextView for achieving this but I'll require some guidance.

Thanks in advance.

答:
I did so:

The Container of TextView:

```<code>    android:layout_width="match_parent"
    android:layout_height="match_parent"
</code>```

The TextView:

```<code>    android:layout_width="match_parent"
    android:layout_height="wrap_content"
</code>```

Then,

The Text of the TextView was showed in two lines or more...

ContentLicense: CC BY-SA 3.0

Title: Android TextView with multiple lines

Body:
I want a TextView that should be broken into 4 lines. For e.g.

Vishal Vyas
  Having
   342
Reputation

Note, the gravity should be center_horizontal

I tried following :

<TextView
    android:gravity="center_horizontal"
    android:id="@+id/lblUserRep"
    android:layout_width="70dp"
    android:layout_height="wrap_content"
    android:lines="4"
    android:maxLines="4"
    android:text="VishalVyas Having 342 Reputation" >
</TextView>

This works! but produces following output:

VishalVyas
  Having
   342
Reputation

Problems:

It doesn't work with the space between words Vishal and Vyas.

android:layout_width="70dp" is harcoded and there can be any name with n number of characters instead of VishalVyas.

Please advice.

Added:
It would be fine if I need to write a custom TextView for achieving this but I'll require some guidance.

Thanks in advance.

Body:
I did so:

The Container of TextView:

    android:layout_width="match_parent"
    android:layout_height="match_parent"

The TextView:

    android:layout_width="match_parent"
    android:layout_height="wrap_content"

Then,

The Text of the TextView was showed in two lines or more...


问:
Internationalisation with asp.net, c# and VSCode
I would like to create an internationalization file in my asp.net project using VS Code. I just found how to do it using a common VS version, just creating a .resx file, and using a specific interface to insert the variables and the value.

How can I create an internationalization file using Visual Studio Code?

答:
Resx files are only going to partially function in VS Code.

Typically, a resx file produces two artifacts: an embedded resource in your assembly, and a code file containing APIs to access your resources by name.

The embedded resource is created from an MSBuild task, so it will be handled as long as you are building with MSBuild, which is pretty standard for any .NET project.

However, the code file that gets generated is created by a "Custom Tool" in Visual Studio, so you won't get that for free if you use VSCode. This generated code file can be written by hand, but it isn't much fun keeping it in sync with your .resx.

As an alternative to .resx, I've been working on creating a .resj file format. This functions entirely in MSBuild, and so should work just as well from VSCode as it does from Visual Studio. The project is open sourced here. I've packaged it up as a nuget package "Elemental.JsonResource" (currently only pre-release). If you add that package to your project you should be able to use .resj files. Currently, it only supports string resources, but I hope to add support for other resource types in the future. It doesn't add a run-time dependency to your project, it only operates at build time.


问:
Pandas for inserting a columns as index
When reading from excel to pandas, it shows like this

```<code>t0001   Albania 0.03914382317658349
0   t0001   Algeria 0.298994
1   t0001   Austria 1.01137
2   t0001   Belgium 0.306369
</code>```

What I want to achieve is inserting a columns of 'time','region','value', and it should be shows like below

```<code>    time    region  value
0   t0001   Albania 0.0391438
1   t0001   Algeria 0.298994
2   t0001   Austria 1.01137
3   t0001   Belgium 0.306369
</code>```

Is it possible to achieve in the pandas?

答:
When reading your excel file, read it as so, with a header and names parameter.

```<code>df = pd.read_excel(..., header=None, names=['time', 'region', 'value'])
</code>```

If you are curious, the fix would be to call reset_index and assign columns:

```<code>df = df.T.reset_index().T
df.columns = ['time', 'region', 'value']

df['value'] = df['value'].astype(float)

df

        time   region     value
index  t0001  Albania  0.039144
0      t0001  Algeria  0.298994
1      t0001  Austria  1.011370
2      t0001  Belgium  0.306369
</code>```

You should strive as much as possible to not reach a point that would necessitate running cleanup code like this.

Title: Pandas for inserting a columns as index

Body:
When reading from excel to pandas, it shows like this

t0001   Albania 0.03914382317658349
0   t0001   Algeria 0.298994
1   t0001   Austria 1.01137
2   t0001   Belgium 0.306369

What I want to achieve is inserting a columns of 'time','region','value', and it should be shows like below

    time    region  value
0   t0001   Albania 0.0391438
1   t0001   Algeria 0.298994
2   t0001   Austria 1.01137
3   t0001   Belgium 0.306369

Is it possible to achieve in the pandas?

Body:
When reading your excel file, read it as so, with a header and names parameter.

df = pd.read_excel(..., header=None, names=['time', 'region', 'value'])

If you are curious, the fix would be to call reset_index and assign columns:

df = df.T.reset_index().T
df.columns = ['time', 'region', 'value']

df['value'] = df['value'].astype(float)

df

        time   region     value
index  t0001  Albania  0.039144
0      t0001  Algeria  0.298994
1      t0001  Austria  1.011370
2      t0001  Belgium  0.306369

You should strive as much as possible to not reach a point that would necessitate running cleanup code like this.


问:
Include second source file in Chapel file
In C++, when I need classes in 'actions.cpp' from classes.cpp I include the header, like #include <classes.h>.  But trying use classes.chpl fails, is there a .h equivalent I should be using?

答:
Use is only for module names, not full file names.  If your file classes.chpl does not have an explicit module enclosing its entire contents, then you would type

```<code>use classes;
</code>```

in order to access its contents from another file.

If classes.chpl is in the same directory as the file with the use statement, that should be all that is necessary to access its symbols.

If classes.chpl is in a different directory, you would additionally need to specify its location at compile time via the -M or --module-dir flag.  For example, if usesClasses.chpl has a use of classes.chpl, and classes.chpl lived in a directory named helpers, you would write

```<code>chpl -M helpers/ usesClasses.chpl
</code>```

when compiling the program

Body:
Use is only for module names, not full file names.  If your file classes.chpl does not have an explicit module enclosing its entire contents, then you would type

use classes;

in order to access its contents from another file.

If classes.chpl is in the same directory as the file with the use statement, that should be all that is necessary to access its symbols.

If classes.chpl is in a different directory, you would additionally need to specify its location at compile time via the -M or --module-dir flag.  For example, if usesClasses.chpl has a use of classes.chpl, and classes.chpl lived in a directory named helpers, you would write

chpl -M helpers/ usesClasses.chpl

when compiling the program


问:
Create Envelope Error on Live Environment - One or both of Username and Password are invalid
Envelope creation was worked well on the sandbox environment. After I made the integrator key live, and used it with the live account, I am getting the error:

Error calling CreateEnvelope: {\r\n  \"errorCode\": \"USER_AUTHENTICATION_FAILED\",\r\n  \"message\": \"One or both of Username and Password are invalid.

Any idea why this is not working on production?

答: I figured it out. For anybody who has this question in future, please send an envelope manually from your docusign account and use the url of the envelope as your base path.</p>


问:
Jhipster: ZonedDateTime in domain class is not getting converted to timestamp , instead getting converted to TINYBLOB in liquibase changelog file
I am using JHipster 4.1 and need help in adding new model.
I am trying to create my model class extending AbstractAuditingEntity class, but when I do mvnw liquibase:diff for changelog file generation the new file has TINYBLOB data type for timestamp. I am not sure why it is generating so.

```<code>> <column name="created_by" type="VARCHAR(50)">
>             <constraints nullable="false"/>
>          </column>
>          <column name="created_date" type="TINYBLOB">
>             <constraints nullable="false"/>
>          </column>
>          <column name="last_modified_by" type="VARCHAR(50)"/>
>          <column name="last_modified_date" type="TINYBLOB"/>
</code>```

Can anyone please suggest why it is generating wrong datatype.

答:
Must be a limitation on Liquibase. Just take a look this issue:  https://github.com/jhipster/generator-jhipster/issues/6291

You can fix it manually in this way:

```<code><column name="last_modified_date" type="timestamp"/>
</code>```

More details here http://www.liquibase.org/documentation/column.html

Body:
I am using JHipster 4.1 and need help in adding new model.
I am trying to create my model class extending AbstractAuditingEntity class, but when I do mvnw liquibase:diff for changelog file generation the new file has TINYBLOB data type for timestamp. I am not sure why it is generating so.

> <column name="created_by" type="VARCHAR(50)">
>             <constraints nullable="false"/>
>          </column>
>          <column name="created_date" type="TINYBLOB">
>             <constraints nullable="false"/>
>          </column>
>          <column name="last_modified_by" type="VARCHAR(50)"/>
>          <column name="last_modified_date" type="TINYBLOB"/>

Can anyone please suggest why it is generating wrong datatype.

Body:
Must be a limitation on Liquibase. Just take a look this issue:  https://github.com/jhipster/generator-jhipster/issues/6291

You can fix it manually in this way:

<column name="last_modified_date" type="timestamp"/>

More details here http://www.liquibase.org/documentation/column.html


问:
CSS isn't showing up on a specific part of the page
So I'm working on a website I'm building and am in the process of consolidating stylesheets. I'm currently having a problem where one div section of the page is not connecting to the stylesheet. The rest of the page is fine but it's just this one section and I have no idea why. I copied and pasted it (html and style) from the first draft and am using the same fonts and bootstrap cdn (bootstrap fonts 4.1 and bootstrap cdn 3.3.7) but am getting different results. Would appreciate any help you could offer.

here's the html

```<code><div class="main">
                    <div class="container">
                    <header>
                        <center><h2>My Work</h2></center>
                    </header>
                    <div class="box">
                        <span class="image featured"><img src="laptopstock.jpg" alt="" /></span>
                        <h3><a href="sampleofficial.html">Arris SURFboard SBG6700-AC Wireless Gateway Manual</a></h3>
                            <p>The Arris SURFboard SBG6700-AC wireless gateway is the premier modem on the market today. It's top of the line security, simple user interface and blazing fast speeds make it the number one consumer choice for modems. With this guide you can set up your home wireless network in 30 minutes.</p>
                            <br>
                            <p><a href="sampleofficial.html" class="button-alt">Learn More</a></p>
                        </div>
                    </div>
                </div>
</code>```

here's the css

```<code>        main {
            padding: 8em 0;
        }

            main.header {
                text-align: center;
                margin: 0em 0 3em 0;
                padding-top: 1000em;
            }
    /* difference between padding and margin?
    padding is on the inside.
    margin on the outside.*/
    /* this is the gray space between the header and the image */

                main.header h2 {
                    font-size: 2.75em;
                    margin: 0;
                    letter-spacing: .005em;
                    color: #000;
                }

        body.landing main {
            margin-top: -14em;
        }
    .container {
      margin-right: auto;
      margin-left: auto;
      padding-right: 15px;
      padding-left: 15px;
      width: 100%;
    }
.box {
                margin: 1em;
                overflow-x: hidden;
                padding: 2em 2em !important;
            }

                .box.features .features-row {
                    border-top: 0;
                    padding: 0;
                }

                    .box.features .features-row section {
                        border: 0;
                        border-top: solid 1px #e5e5e5 !important;
                        float: none;
                        margin: 2em 0 0 0 !important;
                        padding: 2em 0 0 0 !important;
                        width: 100%;
                    }

                    .box.features .features-row:first-child section:first-child {
                        border-top: 0 !important;
                        margin-top: 0 !important;
                        padding-top: 0 !important;
                    }

                .box .image.featured {
                    margin-left: -2em;
                    width: calc(100% + 4em);
                }

                    .box .image.featured:first-child {
                        margin-bottom: 2em;
                        margin-top: -2em;
                    }

                    .box .image.featured:last-child {
                        margin-bottom: -2em;
                        margin-top: 2em;
                    }
</code>```

答:
Your element selector is wrong. From your html, 'main' is a class, 'header' is an element. To refer to class in css, use '.' as in .main, to refer to element, use the tag name directly. Writing main.header means and element 'main' that has class 'header' which is not what you want. Use the Css instead;

```<code>.main {
        padding: 8em 0;
    }

        .main header {
            text-align: center;
            margin: 0em 0 3em 0;
            padding-top: 1000em;
        }
/* difference between padding and margin?
padding is on the inside.
margin on the outside.*/
/* this is the gray space between the header and the image */

            .main header h2 {
                font-size: 2.75em;
                margin: 0;
                letter-spacing: .005em;
                color: #000;
            }
</code>```

That should work. Let me know how it goes.

Body:
So I'm working on a website I'm building and am in the process of consolidating stylesheets. I'm currently having a problem where one div section of the page is not connecting to the stylesheet. The rest of the page is fine but it's just this one section and I have no idea why. I copied and pasted it (html and style) from the first draft and am using the same fonts and bootstrap cdn (bootstrap fonts 4.1 and bootstrap cdn 3.3.7) but am getting different results. Would appreciate any help you could offer.

here's the html

My Work

Arris SURFboard SBG6700-AC Wireless Gateway Manual

The Arris SURFboard SBG6700-AC wireless gateway is the premier modem on the market today. It's top of the line security, simple user interface and blazing fast speeds make it the number one consumer choice for modems. With this guide you can set up your home wireless network in 30 minutes.

Learn More

here's the css

        main {
            padding: 8em 0;
        }

            main.header {
                text-align: center;
                margin: 0em 0 3em 0;
                padding-top: 1000em;
            }
    /* difference between padding and margin?
    padding is on the inside.
    margin on the outside.*/
    /* this is the gray space between the header and the image */

                main.header h2 {
                    font-size: 2.75em;
                    margin: 0;
                    letter-spacing: .005em;
                    color: #000;
                }

        body.landing main {
            margin-top: -14em;
        }
    .container {
      margin-right: auto;
      margin-left: auto;
      padding-right: 15px;
      padding-left: 15px;
      width: 100%;
    }
.box {
                margin: 1em;
                overflow-x: hidden;
                padding: 2em 2em !important;
            }

                .box.features .features-row {
                    border-top: 0;
                    padding: 0;
                }

                    .box.features .features-row section {
                        border: 0;
                        border-top: solid 1px #e5e5e5 !important;
                        float: none;
                        margin: 2em 0 0 0 !important;
                        padding: 2em 0 0 0 !important;
                        width: 100%;
                    }

                    .box.features .features-row:first-child section:first-child {
                        border-top: 0 !important;
                        margin-top: 0 !important;
                        padding-top: 0 !important;
                    }

                .box .image.featured {
                    margin-left: -2em;
                    width: calc(100% + 4em);
                }

                    .box .image.featured:first-child {
                        margin-bottom: 2em;
                        margin-top: -2em;
                    }

                    .box .image.featured:last-child {
                        margin-bottom: -2em;
                        margin-top: 2em;
                    }

Body:
Your element selector is wrong. From your html, 'main' is a class, 'header' is an element. To refer to class in css, use '.' as in .main, to refer to element, use the tag name directly. Writing main.header means and element 'main' that has class 'header' which is not what you want. Use the Css instead;

.main {
        padding: 8em 0;
    }

        .main header {
            text-align: center;
            margin: 0em 0 3em 0;
            padding-top: 1000em;
        }
/* difference between padding and margin?
padding is on the inside.
margin on the outside.*/
/* this is the gray space between the header and the image */

            .main header h2 {
                font-size: 2.75em;
                margin: 0;
                letter-spacing: .005em;
                color: #000;
            }

That should work. Let me know how it goes.


问:
Unit Testing: Beginner Questions
I'm finally starting out with unit testing, having known that I should be doing it for a while, but I have a few questions:

Should or shouldn't I retest parent
classes when testing the children if
no methods have been overwritten?

Conceptually, how do you test the
submitted part of a form? I'm using
PHP. (Edit: The reason I ask this is that I have a high level form class that generates a form, validates it, filters it, and generates any error messages by taking a JSON-like array as input and delegating to a variety of smaller classes. However, I can't test the errors, etc without submitting the form. Edit: This looks like it might be an answer.)

If you have optional parameter in a
method, should you write a test for
both when they are present and when
they are not?

Should unit testing in any way be
combined with testing code execution
time or should they remain completely
separate?

Is there any valid reason not to run
your full test suite every time?

Just so I'm getting my terminology
right, to what does the unit in unit
testing refer? The class being
tested? The method? The parameter?
Something else?

答:
(Not quite in the same order as your questions)

If the full test suite doesn't take too long, you should always run it complete. You often don't know which side-effects may result from changes exactly.

If you can combine speed tests with your favorite unit testing tool, you should do it. This gives you additional information about the quality of your changes. But only do this for time-critical parts of your code.

From Wikipedia: "A unit is the smallest testable part of an application."

OwnerDisplayName: VirtuosiMedia

ContentLicense: CC BY-SA 2.5

Title: Unit Testing: Beginner Questions

LastEditorDisplayName: VirtuosiMedia

OwnerDisplayName: schnaader

LastEditorDisplayName: schnaader


问:
jQuery Forms post with $.ajax
I have this vote system on a wordpress installation everything works fine if I have only one post if I have more, the AJAX posts only for the first form.

So every post has a HTML form:

```<code><form method="post" id="vote_<?php the_ID(); ?>" class="vote" name="vote">
    <input type="hidden" id="vote_post_id" name="vote_post_id" value="<?php the_ID(); ?>" />
    <input type="hidden" id="vote_count" name="vote_count" value="1" />
    <span class="votes_count"><?php echo get_post_meta($post->ID, 'votes', true); ?></span>
    <input type="submit" name="vote_up" class="vote_up" value="+1" />
</form>
</code>```

And here's the jQuery:

```<code>$(function() {
    $('form.vote').submit(function() {
        var url = 'http://bla-bla.com/lib/';
            post_id = $('input#vote_post_id').attr('value');
            count = $('input#vote_count').attr('value');
            form_id = $('form.vote').attr('id');
            cast_vote = 'post_id=' + post_id + '&count=' + count;
            original_count = $('span.votes_count').html();
            new_value = parseInt(original_count) + 1;

        //alert (cast_vote);return false;
        $.ajax({
            type: 'POST',
            url: url + 'cast.php',
            cache: false,
            timeout: 10000,
            data: cast_vote,
            success: function(data){
                $('form.vote').find('span.votes_count').fadeIn(1500, function() {
                    $(this).html(new_value);
                });
                $('form.vote').removeClass('vote').addClass('user_voted disabled');
            }
        });
        return false;
    });

});
</code>```

So I want this to work, only on the form that have been submited. How do I achieve that?

.each() will work?

答:
If I am understanding this correctly(if not just ignore me lol)...

You can use the .live function to hold a reference to every submit button on the page...

```<code>$('.vote-up').live('click', function(){

      //do your ajax calls here...

});
</code>```

this will essentially create a click event for each vote up button...

Title: jQuery Forms post with $.ajax

Body:
I have this vote system on a wordpress installation everything works fine if I have only one post if I have more, the AJAX posts only for the first form.

So every post has a HTML form:

<form method="post" id="vote_<?php the_ID(); ?>" class="vote" name="vote">
    <input type="hidden" id="vote_post_id" name="vote_post_id" value="<?php the_ID(); ?>" />
    <input type="hidden" id="vote_count" name="vote_count" value="1" />
    <?php echo get_post_meta($post->ID, 'votes', true); ?>
    <input type="submit" name="vote_up" class="vote_up" value="+1" />
</form>

And here's the jQuery:

$(function() {
    $('form.vote').submit(function() {
        var url = 'http://bla-bla.com/lib/';
            post_id = $('input#vote_post_id').attr('value');
            count = $('input#vote_count').attr('value');
            form_id = $('form.vote').attr('id');
            cast_vote = 'post_id=' + post_id + '&count=' + count;
            original_count = $('span.votes_count').html();
            new_value = parseInt(original_count) + 1;

        //alert (cast_vote);return false;
        $.ajax({
            type: 'POST',
            url: url + 'cast.php',
            cache: false,
            timeout: 10000,
            data: cast_vote,
            success: function(data){
                $('form.vote').find('span.votes_count').fadeIn(1500, function() {
                    $(this).html(new_value);
                });
                $('form.vote').removeClass('vote').addClass('user_voted disabled');
            }
        });
        return false;
    });

});

So I want this to work, only on the form that have been submited. How do I achieve that?

.each() will work?

Body:
If I am understanding this correctly(if not just ignore me lol)...

You can use the .live function to hold a reference to every submit button on the page...

$('.vote-up').live('click', function(){

      //do your ajax calls here...

});

this will essentially create a click event for each vote up button...


问:
AngularJS V1.2 - Error: $q is not a function
```<code>(function () {
angular.module('Testing')
    .controller('Testing', Testing);
    Testing.$inject('$q', '$location', 'authentication');
    function  Testing($q, $location, authentication) {
    var vm = this;

    function asyncGreet(name) {
    return $q(function (resolve, reject) {
        setTimeout(function(){
            if(username){
                resolve('Hello, ' + username);
            }
            else {
                reject('Greeting ' +  name + 'is not allowed');
            }
        }, 3000)
    });
}

var promise = asyncGreet("oo");
promise.then(function (greeting) {
    console.log('Success: ' + greeting);
}, function (reason) {
    console.log('Failed: ' + reason);
});

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

I am using angular version 1.2.9, and i am trying to make use of $q, and i keep getting an error that says $q is not a function, .

Can someone please point me to what i am doing wrong? Thank you.

答:
$q !== Promise in your version.  I don't know when $q was changed to be a function, but I'm pretty sure much after 1.2.9. Any reason you're using such an old version?

Try this variation:

var deferred = $q.defer();
setTimeout(function(){
  if(username){
    deferred.resolve()
  } else {
    deferred.reject()
  }
});
return deferred;
```

See docs for your version (at least, pre 1.3)

https://code.angularjs.org/1.2.32/docs/api/ng/service/$q

Body:
(function () {
angular.module('Testing')
    .controller('Testing', Testing);
    Testing.$inject('$q', '$location', 'authentication');
    function  Testing($q, $location, authentication) {
    var vm = this;

    function asyncGreet(name) {
    return $q(function (resolve, reject) {
        setTimeout(function(){
            if(username){
                resolve('Hello, ' + username);
            }
            else {
                reject('Greeting ' +  name + 'is not allowed');
            }
        }, 3000)
    });
}

var promise = asyncGreet("oo");
promise.then(function (greeting) {
    console.log('Success: ' + greeting);
}, function (reason) {
    console.log('Failed: ' + reason);
});

} ());

I am using angular version 1.2.9, and i am trying to make use of $q, and i keep getting an error that says $q is not a function, .

Can someone please point me to what i am doing wrong? Thank you.

Body:
$q !== Promise in your version.  I don't know when $q was changed to be a function, but I'm pretty sure much after 1.2.9. Any reason you're using such an old version?

Try this variation:

var deferred = $q.defer();
setTimeout(function(){
  if(username){
    deferred.resolve()
  } else {
    deferred.reject()
  }
});
return deferred;

See docs for your version (at least, pre 1.3)

https://code.angularjs.org/1.2.32/docs/api/ng/service/$q


问:
Sticky footer hiding content
I made the following sticky footer using CSS. The bottom page content is currently hidden behind the footer (see the attached screenshot). How can I adjust my CSS so that all of the body content is visible and the footer remains stuck to the bottom of the browser window? Thank you!

CSS:

```<code>.fo {
    position: absolute;
    left: 0;
    bottom: 0;
    height:65px;
    width: 100%;
    color: #eaeaea;
    margin-left: -8px;
}
</code>```

答:
I was having the same issue and the other solutions pointed me in the right direction, but because I am using Angular Material all I had to do was add layout="column" and it worked great</p>

```<code>    <div id="container" layout="column">
       <div id="header"></div>
       <div id="body"></div>
       <div id="footer"></div>
    </div>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Sticky footer hiding content

Body:
I made the following sticky footer using CSS. The bottom page content is currently hidden behind the footer (see the attached screenshot). How can I adjust my CSS so that all of the body content is visible and the footer remains stuck to the bottom of the browser window? Thank you!

CSS:

.fo {
    position: absolute;
    left: 0;
    bottom: 0;
    height:65px;
    width: 100%;
    color: #eaeaea;
    margin-left: -8px;
}

Body:
I was having the same issue and the other solutions pointed me in the right direction, but because I am using Angular Material all I had to do was add layout="column" and it worked great

    <div id="container" layout="column">
       <div id="header"></div>
       <div id="body"></div>
       <div id="footer"></div>
    </div>


问:
Azure IoT Hub - How to use Table Storage in IoT Hub?
First of all, sorry for my english skill.

I'm a high school student from South Korea who's doing project with Azure IoT Hub.

I am working on a project where a raspberry pi device is sending values to an Azure IoT Hub. I would like to save this data in Azure Table Storage as this data will be used by some other services (Azure WebApp for example).

So I tried to save raspberry pi values in Azure Table Storage.
But when I add endpoints of IoT Hub, I just can use only blob storage container

of course i still don't understand about iot hub
please don't look so bad.

In a nutshell

I want to send raspberry pi values to Azure Table Storage and not Blob Storage however only option available to me is Blob Storage when I am setting endpoints for Azure IoT Hub.

How to send values to Table Storage via Azure IoT Hub.

by any chance, my logic for Azure is completely wrong?

答: You can use either functions or Azure Stream Analytics to push hub data to Azure table storage. I found Stream Analytics worked best for me as I was better able to format the data.</p>


问:
Android - Get Location Only One Time
i need to get the current user location on an android app, so i've read some tutorials and samples on the web, but i see that in all the examples, the location is retrived from a "onLocationChange" that mean that every time the location change, the code in the "onLocationChange" is executed.

i need only to get the user location at the moment the app is started.

Thanks for your help!

答:
Put this in the main activity:

```<code>
boolean bFirst = true;
function void onCreate(blabla) {
  if(bFirst) {
    //Do your stuff to get the location
    bFirst = false;
  }
}
</code>```

Put the same in the onResume();

Title: Android - Get Location Only One Time

Body:
Put this in the main activity:

boolean bFirst = true;
function void onCreate(blabla) {
  if(bFirst) {
    //Do your stuff to get the location
    bFirst = false;
  }
}

Put the same in the onResume();


问:
How to order a list of objects using a list of object attributes
I have a list of objects with ids (object.id) and a list of ids. What is the most efficient way to use the list of ids to order the object list? I have the following solution... just wondering whether there is a faster one?

Input:

result = list of user objects with user ids (user.id)

list_of_ids = list of user ids e.g. [3, 2, 5, 8, 9]

Output:

list of user objects ordered according to list_of_ids

Code:

```<code>ordered_result = []
for user_id in list_of_ids:
    for user in result:
        if user_id == user.id:
            ordered_result.append(user)
            break
</code>```

答:
You could first put the users in a dict:

```<code>usrdict = {}
for user in result:
    usrdict[user.id] = user
</code>```

And then you'd have a few options, based on looking up the users by their id, for example:

```<code>ordered_result = [usrdict[x] for x in list_of_ids]
</code>```

Edit: I'd probably, unless you have a very large list or have perform the operation many times, not worry about efficiency that much, but rather focus on having it clear and readable.

Body:
I have a list of objects with ids (object.id) and a list of ids. What is the most efficient way to use the list of ids to order the object list? I have the following solution... just wondering whether there is a faster one?

Input:

result = list of user objects with user ids (user.id)

list_of_ids = list of user ids e.g. [3, 2, 5, 8, 9]

Output:

list of user objects ordered according to list_of_ids

Code:

ordered_result = []
for user_id in list_of_ids:
    for user in result:
        if user_id == user.id:
            ordered_result.append(user)
            break

Body:
You could first put the users in a dict:

usrdict = {}
for user in result:
    usrdict[user.id] = user

And then you'd have a few options, based on looking up the users by their id, for example:

ordered_result = [usrdict[x] for x in list_of_ids]

Edit: I'd probably, unless you have a very large list or have perform the operation many times, not worry about efficiency that much, but rather focus on having it clear and readable.


问:
C++ Error: Does not name a type, templated class
I am designing a templated class within a namespace, and I can't understand why I'm getting this error: 'Test' does not name a type. It seems to only be giving me this error for the constructor and destructor definitions. Any help would be much appreciated.

Note: I am doing this for a class assignment and must keep these files set up in the way that I have. I must have a test.h file and test.hpp included into test.h.

test.h:

```<code>#ifndef TEST_H
#define TEST_H

namespace mynamespace
{
    template <typename A, typename B>
    class Test
    {
            public:

                    // constructor
                    Test();

                    // destructor
                    ~Test();
    };
}

#include "test.hpp"

#endif
</code>```

test.hpp:

```<code>// constructor
template <typename A, typename B>
Test<A, B>::Test()
{

}

// destructor
template <typename A, typename B>
Test<A, B>::~Test()
{

}
</code>```

main.cpp:

```<code>#include "test.h"

using namespace mynamespace;

int main()
{
    return 0;
}
</code>```

makefile:

```<code>CC = g++ -std=c++11 -Wall -pedantic

main.x: main.o
        $(CC) -o main.x main.o

main.o: main.cpp test.h
        $(CC) -c main.cpp

clean:
        rm *.o *.x
</code>```

答:
The contents of test.hpp are outside the namespace since you include the file after the closing brace.

As indicated by other commenters having the implementations split into another file is not common practice for a template, but if you are required to do it that way you could fix it by adding the namespace to test.hpp.

Body:
I am designing a templated class within a namespace, and I can't understand why I'm getting this error: 'Test' does not name a type. It seems to only be giving me this error for the constructor and destructor definitions. Any help would be much appreciated.

Note: I am doing this for a class assignment and must keep these files set up in the way that I have. I must have a test.h file and test.hpp included into test.h.

test.h:

#ifndef TEST_H
#define TEST_H

namespace mynamespace
{
    template <typename A, typename B>
    class Test
    {
            public:

                    // constructor
                    Test();

                    // destructor
                    ~Test();
    };
}

#include "test.hpp"

#endif

test.hpp:

// constructor
template <typename A, typename B>
Test::Test()
{

}

// destructor
template <typename A, typename B>
Test::~Test()
{

}

main.cpp:

#include "test.h"

using namespace mynamespace;

int main()
{
    return 0;
}

makefile:

CC = g++ -std=c++11 -Wall -pedantic

main.x: main.o
        $(CC) -o main.x main.o

main.o: main.cpp test.h
        $(CC) -c main.cpp

clean:
        rm *.o *.x


问:
codeigniter email function not working fine while sending multiple emails with an attachments
here is code for sending emails for multiple with an attachment.the loop was running for 1st time only.so it was sending the mail to 1st person and all the remaining was not getting mails.here is my code.since i'm for working from 2days on it.still i didn't get where i had done a mistake.i hope this is best time to learn from you guys.here is my code.

```<code><?php
foreach ($ids as $key => $value)
     {
                  $where['applicant_id']=$value;
                  $this->db->trans_start();
                  $this->db->where($where);
          $result=$this->db->get('applicant');
          if($this->db->trans_status() === FALSE)
          {
          $this->db->trans_rollback();
          }
          else
          {
          $check++;
          $array=$result->row_array();
          $this->db->trans_complete(); $update_data[$key]=array('applicant_id'=>$array['applicant_id'],'status'=>'SHORTLISTED');
    $subject='Congratualations You Had Short Listed For Singing Competition';

             $array['title']='Admitcard';
             $data=$array;

             $this->email->set_mailtype('html');
             $this->email->from('xxx@gmail.com','xxxcompetations');
             $this->email->to($array['email']);
             $this->email->bcc('xxx51@gmail.com');
             $this->email->subject($subject);
             $this->email->message($message);
             $this->pdf->load_view('admitcard',$data);
             $name=random_string('alnum', 9);
             $this->pdf->render();
             $pdf = $this->pdf->output(); //$this->pdf->stream($name.".pdf");
             file_put_contents("pdf/$name".".pdf", $pdf);
             $this->email->attach("pdf/$name".".pdf");
             $this->email->send();
             $this->email->clear(TRUE);
             $ecount++;
          }
      }

?>
</code>```

------------------------this is the error i'm getting how to overcome this----------

Fatal error: Uncaught exception 'DOMPDF_Exception' with message 'No block-level parent found. Not good.' in /home/mycityon/public_html/navy/application/libraries/dompdf/include/inline_positioner.cls.php:38 Stack trace: #0 /home/mycityon/public_html/navy/application/libraries/dompdf/include/frame_decorator.cls.php(546): Inline_Positioner->position() #1 /home/mycityon/public_html/navy/application/libraries/dompdf/include/inline_frame_reflower.cls.php(37): Frame_Decorator->position() #2 /home/mycityon/public_html/navy/application/libraries/dompdf/include/frame_decorator.cls.php(556): Inline_Frame_Reflower->reflow(NULL) #3 /home/mycityon/public_html/navy/application/libraries/dompdf/include/page_frame_reflower.cls.php(138): Frame_Decorator->reflow() #4 /home/mycityon/public_html/navy/application/libraries/dompdf/include/frame_decorator.cls.php(556): Page_Frame_Reflower->reflow(NULL) #5 /home/mycityon/public_html/navy/application/libraries/dompdf/include/dompdf.cls.php(817): Frame_Decorator->reflow() #6 /home/mycityon/public_ in /home/mycityon/public_html/navy/application/libraries/dompdf/include/inline_positioner.cls.php on line 38

答: I believe the fix is to re-instantiate dompdf. See the following, DOMPDF, I cannot create two pdf at time  </p>

Body:
here is code for sending emails for multiple with an attachment.the loop was running for 1st time only.so it was sending the mail to 1st person and all the remaining was not getting mails.here is my code.since i'm for working from 2days on it.still i didn't get where i had done a mistake.i hope this is best time to learn from you guys.here is my code.

<?php
foreach ($ids as $key => $value)
     {
                  $where['applicant_id']=$value;
                  $this->db->trans_start();
                  $this->db->where($where);
          $result=$this->db->get('applicant');
          if($this->db->trans_status() === FALSE)
          {
          $this->db->trans_rollback();
          }
          else
          {
          $check++;
          $array=$result->row_array();
          $this->db->trans_complete(); $update_data[$key]=array('applicant_id'=>$array['applicant_id'],'status'=>'SHORTLISTED');
    $subject='Congratualations You Had Short Listed For Singing Competition';

             $array['title']='Admitcard';
             $data=$array;

             $this->email->set_mailtype('html');
             $this->email->from('xxx@gmail.com','xxxcompetations');
             $this->email->to($array['email']);
             $this->email->bcc('xxx51@gmail.com');
             $this->email->subject($subject);
             $this->email->message($message);
             $this->pdf->load_view('admitcard',$data);
             $name=random_string('alnum', 9);
             $this->pdf->render();
             $pdf = $this->pdf->output(); //$this->pdf->stream($name.".pdf");
             file_put_contents("pdf/$name".".pdf", $pdf);
             $this->email->attach("pdf/$name".".pdf");
             $this->email->send();
             $this->email->clear(TRUE);
             $ecount++;
          }
      }

?>

------------------------this is the error i'm getting how to overcome this----------

Fatal error: Uncaught exception 'DOMPDF_Exception' with message 'No block-level parent found. Not good.' in /home/mycityon/public_html/navy/application/libraries/dompdf/include/inline_positioner.cls.php:38 Stack trace: #0 /home/mycityon/public_html/navy/application/libraries/dompdf/include/frame_decorator.cls.php(546): Inline_Positioner->position() #1 /home/mycityon/public_html/navy/application/libraries/dompdf/include/inline_frame_reflower.cls.php(37): Frame_Decorator->position() #2 /home/mycityon/public_html/navy/application/libraries/dompdf/include/frame_decorator.cls.php(556): Inline_Frame_Reflower->reflow(NULL) #3 /home/mycityon/public_html/navy/application/libraries/dompdf/include/page_frame_reflower.cls.php(138): Frame_Decorator->reflow() #4 /home/mycityon/public_html/navy/application/libraries/dompdf/include/frame_decorator.cls.php(556): Page_Frame_Reflower->reflow(NULL) #5 /home/mycityon/public_html/navy/application/libraries/dompdf/include/dompdf.cls.php(817): Frame_Decorator->reflow() #6 /home/mycityon/public_ in /home/mycityon/public_html/navy/application/libraries/dompdf/include/inline_positioner.cls.php on line 38


问:
Excel Macro Copy Paste REF! Error
I am currently new to excel macros and trying to figure out why this is not working. Basically, I want Cell "D22" from "Sheet1" to be copied and then pasted to "sheet2" Cell "A2". The problem is on sheet1 I have a formula in cell D22 so when I copy and paste it into the new sheet, I get a #REF! ERROR   :(

I have looked it up and tried fixing it but still no luck. Below is my basic code. I know there is probably a simple solution but if someone could please advise me in the right direction much would be appreciated! xD

```<code>Sub Insert()
 Sheets("Sheet1").Select
 Range("D22").Select
 Selection.Copy
 Sheets("Sheet2").Select
 Range("A2").Select
 ActiveSheet.Paste
End Sub
</code>```

答:
If you just want to assign the value of one cell to another, don't use copy/paste, just use the Value property:

```<code>Sub Insert()
    Sheets("Sheet2").Range("A2").Value = Sheets("Sheet1").Range("D22").Value
End Sub
</code>```

Title: Excel Macro Copy Paste REF! Error

Body:
I am currently new to excel macros and trying to figure out why this is not working. Basically, I want Cell "D22" from "Sheet1" to be copied and then pasted to "sheet2" Cell "A2". The problem is on sheet1 I have a formula in cell D22 so when I copy and paste it into the new sheet, I get a #REF! ERROR   :(

I have looked it up and tried fixing it but still no luck. Below is my basic code. I know there is probably a simple solution but if someone could please advise me in the right direction much would be appreciated! xD

Sub Insert()
 Sheets("Sheet1").Select
 Range("D22").Select
 Selection.Copy
 Sheets("Sheet2").Select
 Range("A2").Select
 ActiveSheet.Paste
End Sub

Body:
If you just want to assign the value of one cell to another, don't use copy/paste, just use the Value property:

Sub Insert()
    Sheets("Sheet2").Range("A2").Value = Sheets("Sheet1").Range("D22").Value
End Sub


问:
Acquiring retrieval name for latest version of a document in a DocumentSet using FileNet API
I have this piece of code:

```<code>Folder fold = Factory.Folder.fetchInstance(os, folderPath, null);
DocumentSet docs = fold.get_ContainedDocuments();
Iterator it = docs.iterator();

Document retr;
try {
    while (it.hasNext()) {
        retr = (Document)it.next();
        String name = retr.get_Name();
        System.out.println(name);

        if(name.equals(fileName)) {
            System.out.println("Match Found");
            System.out.println("Document Name : " + retr.get_Name());
            return retr;
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

Currently, this code works fine for retrieving a document with a certain file name. I want to add to this so that it can also select the latest version of the file with that name. What should i do?

I've considered adding an extra if inside the existing one, but i'm afraid of impacting the performance.

答:
If you are filing a Document (or a subclass of Document), the contained document will be the current document version. In this case, the current document version is (in order of use):

the released version (if there is one), else

the current version (if there is one), otherwise,

the reservation version.

You cannot use the Folder.file method to file a specific document version into the folder, and hence you will always have the DocumentSet with the latest version in the folder

Body:
I have this piece of code:

Folder fold = Factory.Folder.fetchInstance(os, folderPath, null);
DocumentSet docs = fold.get_ContainedDocuments();
Iterator it = docs.iterator();

Document retr;
try {
    while (it.hasNext()) {
        retr = (Document)it.next();
        String name = retr.get_Name();
        System.out.println(name);

        if(name.equals(fileName)) {
            System.out.println("Match Found");
            System.out.println("Document Name : " + retr.get_Name());
            return retr;
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

Currently, this code works fine for retrieving a document with a certain file name. I want to add to this so that it can also select the latest version of the file with that name. What should i do?

I've considered adding an extra if inside the existing one, but i'm afraid of impacting the performance.


答:
Your implementation file doesn’t specify the right namespace, so they can’t find mynamespace::Test. If you change it to include the namespace, it’ll work:

```<code>template <typename A, typename B>
mynamespace::Test<A, B>::Test()
{

}

// destructor
template <typename A, typename B>
mynamespace::Test<A, B>::~Test()
{

}
</code>```

Title: C++ Error: Does not name a type, templated class

Body:
Your implementation file doesn’t specify the right namespace, so they can’t find mynamespace::Test. If you change it to include the namespace, it’ll work:

template <typename A, typename B>
mynamespace::Test<A, B>::Test()
{

}

// destructor
template <typename A, typename B>
mynamespace::Test<A, B>::~Test()
{

}


问:
Can't create Trigger on MySql table within Google Cloud
```<code>CREATE TRIGGER trigger_LocationType_Insert
BEFORE UPDATE ON LocationType
FOR EACH ROW
SET NEW.NAME = ''
</code>```

Returns this error:

[HY000][1419] You do not have the SUPER privilege and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)

I know this is because even the root user "has all privileges except SUPER and FILE."
https://cloud.google.com/sql/docs/mysql/users

And I think that if I could "Set log_bin_trust_function_creators to 1" then it would work (this user does have CREATE TRIGGER permission). However, I don't see how to do that in the Google Cloud SQL console or from a sql statement.

How do you create a TRIGGER then within this environment?

答:
This page described how to change MySQL configuration options for a Google Cloud instance: https://cloud.google.com/sql/docs/mysql/flags

Select the instance to open its Instance Overview page.

The database flags that have been set are listed under the Database flags section.

You have to use their UI to change global variables, because you can't use SET GLOBAL without SUPER privilege.

The log_bin_trust_function_creators option is listed among the supported configuration options you can change in the UI on the page I linked to above.

To read more about this error, see https://dev.mysql.com/doc/refman/5.7/en/stored-programs-logging.html

Body:
CREATE TRIGGER trigger_LocationType_Insert
BEFORE UPDATE ON LocationType
FOR EACH ROW
SET NEW.NAME = ''

Returns this error:

[HY000][1419] You do not have the SUPER privilege and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)

I know this is because even the root user "has all privileges except SUPER and FILE."
https://cloud.google.com/sql/docs/mysql/users

And I think that if I could "Set log_bin_trust_function_creators to 1" then it would work (this user does have CREATE TRIGGER permission). However, I don't see how to do that in the Google Cloud SQL console or from a sql statement.

How do you create a TRIGGER then within this environment?


答: center tag is deprecated in your html header.  Replace with text-align in css.  An example would be:  h2 { text-align: center; }</p>

Title: CSS isn't showing up on a specific part of the page

Body:
So I'm working on a website I'm building and am in the process of consolidating stylesheets. I'm currently having a problem where one div section of the page is not connecting to the stylesheet. The rest of the page is fine but it's just this one section and I have no idea why. I copied and pasted it (html and style) from the first draft and am using the same fonts and bootstrap cdn (bootstrap fonts 4.1 and bootstrap cdn 3.3.7) but am getting different results. Would appreciate any help you could offer.

here's the html

My Work

Arris SURFboard SBG6700-AC Wireless Gateway Manual

The Arris SURFboard SBG6700-AC wireless gateway is the premier modem on the market today. It's top of the line security, simple user interface and blazing fast speeds make it the number one consumer choice for modems. With this guide you can set up your home wireless network in 30 minutes.

Learn More

here's the css

        main {
            padding: 8em 0;
        }

            main.header {
                text-align: center;
                margin: 0em 0 3em 0;
                padding-top: 1000em;
            }
    /* difference between padding and margin?
    padding is on the inside.
    margin on the outside.*/
    /* this is the gray space between the header and the image */

                main.header h2 {
                    font-size: 2.75em;
                    margin: 0;
                    letter-spacing: .005em;
                    color: #000;
                }

        body.landing main {
            margin-top: -14em;
        }
    .container {
      margin-right: auto;
      margin-left: auto;
      padding-right: 15px;
      padding-left: 15px;
      width: 100%;
    }
.box {
                margin: 1em;
                overflow-x: hidden;
                padding: 2em 2em !important;
            }

                .box.features .features-row {
                    border-top: 0;
                    padding: 0;
                }

                    .box.features .features-row section {
                        border: 0;
                        border-top: solid 1px #e5e5e5 !important;
                        float: none;
                        margin: 2em 0 0 0 !important;
                        padding: 2em 0 0 0 !important;
                        width: 100%;
                    }

                    .box.features .features-row:first-child section:first-child {
                        border-top: 0 !important;
                        margin-top: 0 !important;
                        padding-top: 0 !important;
                    }

                .box .image.featured {
                    margin-left: -2em;
                    width: calc(100% + 4em);
                }

                    .box .image.featured:first-child {
                        margin-bottom: 2em;
                        margin-top: -2em;
                    }

                    .box .image.featured:last-child {
                        margin-bottom: -2em;
                        margin-top: 2em;
                    }


问:
unattended wim deployment backinfo
I have a script that deploys a WIM to a partition and makes it bootable and it uses an unattend.xml to configure the name and everything else. I include the BackInfo.exe with settings for it and when the OS boots up I have it run a logon script to initialize the OS for a bunch of stuff. I have tried in the script to run the BackInfo.exe, I have tried in the unattend.xml, I have tried adding a registry key into HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run, I have tried adding a scheduled task.

No matter what happens the background is always the default one and never set to the generated one from BackInfo. When I run the command manually it works perfectly. I for the life of me can't seem to get this working.

Any help would be very much appreciated!

答:
So turns out I had placed the code into the FirstLogonCommands section which turns out wouldn't work, I changed it over to LogonCommands.

```<code>        <LogonCommands>
            <AsynchronousCommand wcm:action="add">
                <CommandLine>%SystemDrive%\Applications\BackInfo\BackInfo.exe</CommandLine>
                <Description>BgInfo</Description>
                <Order>1</Order>
            </AsynchronousCommand>
        </LogonCommands>
</code>```

Hopefully this can help someone else in the future and prevent them from wasting time trying to figure out other ways.

Title: unattended wim deployment backinfo

Body:
So turns out I had placed the code into the FirstLogonCommands section which turns out wouldn't work, I changed it over to LogonCommands.

        <LogonCommands>
            <AsynchronousCommand wcm:action="add">
                <CommandLine>%SystemDrive%\Applications\BackInfo\BackInfo.exe</CommandLine>
                <Description>BgInfo</Description>
                <Order>1</Order>
            </AsynchronousCommand>
        </LogonCommands>

Hopefully this can help someone else in the future and prevent them from wasting time trying to figure out other ways.


问:
Redirect to homepage after log in
React newbie here.
I have an application built with react and rails. There is a link to log-in, in the homepage. The takes the user to the log-in page. On verifying if the username exists, I am trying to redirect to the homepage using the below code.

```<code>export default class Login extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
             username: '',
             isValid: false
        };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleChange = this.handleChange.bind(this);
    }

    handleSubmit(event) {
        axios.get('/isuser/'+this.state.username)
            .then(res => {
                this.setState({ isValid: true });
            })
            .catch(function (error) {
                console.log(error);
            });
        event.preventDefault();
    }

    handleChange(event) {
        this.setState({username: event.target.value});
    }

    render() {
        if (this.state.isValid) {
             return <Redirect to={{
                      pathname: '/',
                      state: {
                              username: this.state.username,
                              loggedIn: true
                      }
              }}/>
        }
        return (
                <div>
                //form
                </div>
        );
    }
}
</code>```

However, the props is empty. I am fetching it using the code below.

```<code>export default class LoginLink extends React.Component {

    constructor(props) {
        super(props);
        if(this.props.state == undefined) { // always empty
            this.state = {loggedIn: false, redirect: false};
        }
        else {
            this.state = {
                       loggedIn: this.props.location.state.loggedIn,
                       username: this.props.location.state.username
            };
        }
        this.handleOnClick = this.handleOnClick.bind(this);
    }

    handleOnClick(event) {
        this.setState({redirect: true});
        event.preventDefault();
    }

    render() {
        if (this.state.redirect) {
            return <Redirect to={{
                      pathname: '/login'
                    }}/>
        }
        else {
            if (this.state.loggedIn) {
                return (
                    <ul className="nav navbar-nav navbar-right" id="topnav">
                        <li><a href="">{this.state.username}</a></li>
                    </ul>
                );
            }
            else {
                return (
                    <ul className="nav navbar-nav navbar-right" id="topnav">
                        <li>
                           <Button bsStyle="link" onClick={this.handleOnClick}>Log in</Button>
                        </li>
                    </ul>
                );
            }
        }
    }
}
</code>```

Here are my routes:

```<code><main>
  <Switch>
    <Route exact path='/' component={Home}/>
    <Route path='/login' component={Login}/>
  </Switch>
</main>
</code>```

I don't know if there is some sort of an infinite loop(calling super).
Any help is appreciated.

答:
It's not very good practice to return different states in the constructor. as It's unclear is the state structure of the component. I'd suggest something like:

```<code>constructor(props) {
  super(props);
  this.state = {
    loggedIn: props.location.state.loggedIn || false,
    username: props.location.state.username || null,
  }
}
</code>```

then in the render() function

```<code>render() {
  // if loggedIn go to '/'
  if (this.state.loggedIn) {
    return <Redirect to={{ pathname: '/', state: { ...this.state, loggedIn: true } }} />
  }
  // otherwise
  // return something else or Redirect to login...
}
</code>```

Title: Redirect to homepage after log in

Body:
React newbie here.
I have an application built with react and rails. There is a link to log-in, in the homepage. The takes the user to the log-in page. On verifying if the username exists, I am trying to redirect to the homepage using the below code.

export default class Login extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
             username: '',
             isValid: false
        };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleChange = this.handleChange.bind(this);
    }

    handleSubmit(event) {
        axios.get('/isuser/'+this.state.username)
            .then(res => {
                this.setState({ isValid: true });
            })
            .catch(function (error) {
                console.log(error);
            });
        event.preventDefault();
    }

    handleChange(event) {
        this.setState({username: event.target.value});
    }

    render() {
        if (this.state.isValid) {
             return <Redirect to={{
                      pathname: '/',
                      state: {
                              username: this.state.username,
                              loggedIn: true
                      }
              }}/>
        }
        return (

                //form

        );
    }
}

However, the props is empty. I am fetching it using the code below.

export default class LoginLink extends React.Component {

    constructor(props) {
        super(props);
        if(this.props.state == undefined) { // always empty
            this.state = {loggedIn: false, redirect: false};
        }
        else {
            this.state = {
                       loggedIn: this.props.location.state.loggedIn,
                       username: this.props.location.state.username
            };
        }
        this.handleOnClick = this.handleOnClick.bind(this);
    }

    handleOnClick(event) {
        this.setState({redirect: true});
        event.preventDefault();
    }

    render() {
        if (this.state.redirect) {
            return <Redirect to={{
                      pathname: '/login'
                    }}/>
        }
        else {
            if (this.state.loggedIn) {
                return (

{this.state.username}

                );
            }
            else {
                return (

                           <Button bsStyle="link" onClick={this.handleOnClick}>Log in</Button>

                );
            }
        }
    }
}

Here are my routes:

  <Switch>
    <Route exact path='/' component={Home}/>
    <Route path='/login' component={Login}/>
  </Switch>

I don't know if there is some sort of an infinite loop(calling super).
Any help is appreciated.

Body:
It's not very good practice to return different states in the constructor. as It's unclear is the state structure of the component. I'd suggest something like:

constructor(props) {
  super(props);
  this.state = {
    loggedIn: props.location.state.loggedIn || false,
    username: props.location.state.username || null,
  }
}

then in the render() function

render() {
  // if loggedIn go to '/'
  if (this.state.loggedIn) {
    return <Redirect to={{ pathname: '/', state: { ...this.state, loggedIn: true } }} />
  }
  // otherwise
  // return something else or Redirect to login...
}


问:
SQL: Add only a year value in a date column
I want a table with the name of an employee and the year of his birth. ONLY THE YEAR IN DATE FORMAT:

```<code>CREATE TABLE EMPLOYEE(
  Name VARCHAR2(50) NOT NULL,
  Year_Birth DATE NOT NULL,
  PRIMARY KEY (Name)
);
</code>```

I want to do this:

```<code>INSERT INTO EMPLOYEE(Name, Year_Birth)
VALUES ('John Smith', 1985);
</code>```

But it doesn't work (cause i'm passing a number value to a date column). I also tried this:

```<code>INSERT INTO EMPLOYEE(Name, Year_Birth)
VALUES ('John Smith', to_date('1972','YYYY') )
</code>```

If i try this one i will get this:
ORA-02290: check constraint (PROJECTNAME.SYS_C0066777818) violated

Year_Birth must be a date column. Is there any way to achieve this?

答:
You can create a column which is of data type int. The insert statement will work.</p>

```<code>insert into employee(Name, Year_Birth)
values ('John Smith', 1985);
</code>```

Body:
I want a table with the name of an employee and the year of his birth. ONLY THE YEAR IN DATE FORMAT:

CREATE TABLE EMPLOYEE(
  Name VARCHAR2(50) NOT NULL,
  Year_Birth DATE NOT NULL,
  PRIMARY KEY (Name)
);

I want to do this:

INSERT INTO EMPLOYEE(Name, Year_Birth)
VALUES ('John Smith', 1985);

But it doesn't work (cause i'm passing a number value to a date column). I also tried this:

INSERT INTO EMPLOYEE(Name, Year_Birth)
VALUES ('John Smith', to_date('1972','YYYY') )

If i try this one i will get this:
ORA-02290: check constraint (PROJECTNAME.SYS_C0066777818) violated

Year_Birth must be a date column. Is there any way to achieve this?

Body:
You can create a column which is of data type int. The insert statement will work.

insert into employee(Name, Year_Birth)
values ('John Smith', 1985);


问:
Block textbox for input in userform
I am using a userform for the first time and I want a textbox to be blocked for input. I have tried a lot of different things, but still without a proper result.
Can anybody help me with this matter ?</p>

答:
if you don't want the user to be able to change or select the text in the textbox, Change the enabled Property to False.  This will grey out the textbox and make the text un-editable.

If you don't want it greyed out, try setting the focus on another control as soon as a user enters your textbox

```<code>Private Sub TextBox1_Enter()
    TextBox2.SetFocus
End Sub
</code>```

Title: Block textbox for input in userform

Body:
if you don't want the user to be able to change or select the text in the textbox, Change the enabled Property to False.  This will grey out the textbox and make the text un-editable.

If you don't want it greyed out, try setting the focus on another control as soon as a user enters your textbox

Private Sub TextBox1_Enter()
    TextBox2.SetFocus
End Sub


问:
Retrieving child value across random key -Firebase
enter image description hereI want to retrieve temperature values that updating to Firebase by using random key over time. I want to show the temperature value in app according to real time data. I try to use addValueEventListner but seems like the value didnt manage to changes in real time. `public class SecondActivityB extends AppCompatActivity {</p>

```<code>private DatabaseReference mDatebase;
private TextView mTempView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second_b);
    mDatebase = FirebaseDatabase.getInstance().getReference().child("Region 1").child("Parameter Reading").child("temperature");
    mTempView = (TextView) findViewById(R.id.tempvalue);

     mDatebase.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
        @Override
        public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
            String name = dataSnapshot.getValue(String.class);

            mTempView.setText("Temperature, C: " + name);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

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

答:
So the way you are referring to your data is the problem.

your data location is:

hydroponic-monitoring-system / Region 1 / Parameter Reading / KzB1.../temperature

The way you read your data

Region 1 / Parameter Reading / temperature

so you skipped  the child (hydroponic-monitoring-system).

The problem you face

now the child (KzB1..) or (KzB2..) these are push keys which means you are not able to refer to them, because you don't know them they are pushed.

Your possible solution is to loop through children like that:

change the:

```<code>  mDatebase = FirebaseDatabase.getInstance().getReference().child("Region 1").child("Parameter Reading").child("temperature");
</code>```

into this

```<code>  mDatebase = FirebaseDatabase.getInstance().getReference().child("hydroponic-monitoring-system").child("Region 1").child("Parameter Reading");
</code>```

and in your value event listener do this in onDatachange

```<code>       @Override
    public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {

          //loop through the keys
         for  (DataSnapshot datasnap: dataSnapshot.getChildren()){

           String name = datasnap.child("temperature").getValue(String.class);
           mTempView.setText("Temperature, C: " + name);
         }

    }
</code>```

and you should read now the temp at each level of push keys.

Body:
enter image description hereI want to retrieve temperature values that updating to Firebase by using random key over time. I want to show the temperature value in app according to real time data. I try to use addValueEventListner but seems like the value didnt manage to changes in real time. `public class SecondActivityB extends AppCompatActivity {

private DatabaseReference mDatebase;
private TextView mTempView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second_b);
    mDatebase = FirebaseDatabase.getInstance().getReference().child("Region 1").child("Parameter Reading").child("temperature");
    mTempView = (TextView) findViewById(R.id.tempvalue);

     mDatebase.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
        @Override
        public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
            String name = dataSnapshot.getValue(String.class);

            mTempView.setText("Temperature, C: " + name);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });`}

Body:
So the way you are referring to your data is the problem.

your data location is:

hydroponic-monitoring-system / Region 1 / Parameter Reading / KzB1.../temperature

The way you read your data

Region 1 / Parameter Reading / temperature

so you skipped  the child (hydroponic-monitoring-system).

The problem you face

now the child (KzB1..) or (KzB2..) these are push keys which means you are not able to refer to them, because you don't know them they are pushed.

Your possible solution is to loop through children like that:

change the:

  mDatebase = FirebaseDatabase.getInstance().getReference().child("Region 1").child("Parameter Reading").child("temperature");

into this

  mDatebase = FirebaseDatabase.getInstance().getReference().child("hydroponic-monitoring-system").child("Region 1").child("Parameter Reading");

and in your value event listener do this in onDatachange

       @Override
    public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {

          //loop through the keys
         for  (DataSnapshot datasnap: dataSnapshot.getChildren()){

           String name = datasnap.child("temperature").getValue(String.class);
           mTempView.setText("Temperature, C: " + name);
         }

    }

and you should read now the temp at each level of push keys.


问:
Starting a new activity or intent in listview for certain items based on content rather than position
I am wondering if it is possible to have clickable items in a listview that start a new activity or intent based upon the content of the items rather than position.  Each specific item needs to have a specific specific action and I want my app to be able to move items from the top or bottom in the listview or add them to a new list.  If the items are stationary, then basing the action on the item's position will work fine, but since the items will move, it will create problems.  Therefore, having the action based on the content of the items(Strings in this instnce) is the best bet, because it will work wherever the items are.

Currently, I am using if (item_position==1), if (item_position==2), if (item_position==3),etc.  Here is the full code for reference:

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

    ArrayList<String> selectedItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        selectedItems = new ArrayList<String>();
        ListView chl = (ListView) findViewById(R.id.colorselector);
        chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        String[] items = {"Blue", "Green", "Yellow", "White", "Black", "Grey"};
        Adapter adapter=new Adapter(this,items);
        chl.setAdapter(adapter);

        chl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                int item_position=i;
                if (item_position==1){

                }
</code>```

答:
Try this code

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

ArrayList<String> selectedItems;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    selectedItems = new ArrayList<String>();
    ListView chl = (ListView) findViewById(R.id.colorselector);
    chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    String[] items = {"Blue", "Green", "Yellow", "White", "Black", "Grey"};
    Adapter adapter=new Adapter(this,items);
    chl.setAdapter(adapter);

    chl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            if(view instance of TextView){
               TextView textView=(TextView)view;
               String data=textView.getText();

               if(data.equal("Blue")){

               }else if(data.equals("Green")){

               }

            }

      }};
</code>```

Body:
I am wondering if it is possible to have clickable items in a listview that start a new activity or intent based upon the content of the items rather than position.  Each specific item needs to have a specific specific action and I want my app to be able to move items from the top or bottom in the listview or add them to a new list.  If the items are stationary, then basing the action on the item's position will work fine, but since the items will move, it will create problems.  Therefore, having the action based on the content of the items(Strings in this instnce) is the best bet, because it will work wherever the items are.

Currently, I am using if (item_position==1), if (item_position==2), if (item_position==3),etc.  Here is the full code for reference:

public class MainActivity extends AppCompatActivity {

    ArrayList<String> selectedItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        selectedItems = new ArrayList<String>();
        ListView chl = (ListView) findViewById(R.id.colorselector);
        chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        String[] items = {"Blue", "Green", "Yellow", "White", "Black", "Grey"};
        Adapter adapter=new Adapter(this,items);
        chl.setAdapter(adapter);

        chl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                int item_position=i;
                if (item_position==1){

                }

Body:
Try this code

public class MainActivity extends AppCompatActivity {

ArrayList<String> selectedItems;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    selectedItems = new ArrayList<String>();
    ListView chl = (ListView) findViewById(R.id.colorselector);
    chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    String[] items = {"Blue", "Green", "Yellow", "White", "Black", "Grey"};
    Adapter adapter=new Adapter(this,items);
    chl.setAdapter(adapter);

    chl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            if(view instance of TextView){
               TextView textView=(TextView)view;
               String data=textView.getText();

               if(data.equal("Blue")){

               }else if(data.equals("Green")){

               }

            }

      }};


问:
PHP count of occurrences of characters of a string within another string
Let's say I have two strings.

```<code>$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';
</code>```

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!

答:
There is no specific method to do this, but this built in method can surely help you:

```<code>$count = substr_count($haystack , $needle);
</code>```

edit: I just reported the general substr_count method..in your particular case you need to call it for each character inside $needle (thanks @Alan Whitelaw)

Body:
Let's say I have two strings.

$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!

Body:
There is no specific method to do this, but this built in method can surely help you:

$count = substr_count($haystack , $needle);

edit: I just reported the general substr_count method..in your particular case you need to call it for each character inside $needle (thanks @Alan Whitelaw)


问:
Displaying price only when the variation is selected and discount in percentage relatively to the regular price
I've this problem. Let me show pictures so I can explain better.

Variation product selected but because all the variations have the same price the price do not show in the bottom:

Variation product selected, because they have different PROMO prices they show on top and the regular-promo price after selection:

What I need is that only after selected the variations the price is show in the bottom like the second image and calculation the discount between the promo variation price and the regular variation price. I need the same behavior in the two cases.

I've searched a lot, but none of the things have solved this behavior. Here some answer that are very close:

calculating discount percentage

variation prices customizations

答:
After some search, there this simple dedicated filter hook woocommerce_show_variation_price that will make exactly what you are expecting:

```<code>add_filter( 'woocommerce_show_variation_price', 'filter_show_variation_price', 10, 3 );
function filter_show_variation_price( $condition, $product, $variation ){
    if( $variation->get_price() === "" ) return false;
    else return true;
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and work… This will display the selected variation price even if all variations prices are the same…

Body:
After some search, there this simple dedicated filter hook woocommerce_show_variation_price that will make exactly what you are expecting:

add_filter( 'woocommerce_show_variation_price', 'filter_show_variation_price', 10, 3 );
function filter_show_variation_price( $condition, $product, $variation ){
    if( $variation->get_price() === "" ) return false;
    else return true;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and work… This will display the selected variation price even if all variations prices are the same…


问:
"Algorithm negotiation fail" error in Eclipse when trying to connect by SSH to a personal Git Server
I have Eclipse Juno, a Synology Server DS213+ with a Git Server. I'm trying to checkout a project from my Git Server to my workspace and when I use EGit in Eclipse I have this error: </p>

```<code>org.eclipse.jgit.api.errors.TransportException: ssh://[route]/volume1/Git/project.git: Algorithm negotiation fail
    at org.eclipse.jgit.api.LsRemoteCommand.execute(LsRemoteCommand.java:223)
    at org.eclipse.jgit.api.LsRemoteCommand.call(LsRemoteCommand.java:159)
    at org.eclipse.egit.core.op.ListRemoteOperation.run(ListRemoteOperation.java:99)
    at org.eclipse.egit.ui.internal.clone.SourceBranchPage$8.run(SourceBranchPage.java:324)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)
Caused by: org.eclipse.jgit.errors.TransportException: ssh://[route]/volume1/Git/project.git: Algorithm negotiation fail
    at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:159)
    at org.eclipse.jgit.transport.SshTransport.getSession(SshTransport.java:136)
    at org.eclipse.jgit.transport.TransportGitSsh$SshFetchConnection.<init>(TransportGitSsh.java:262)
    at org.eclipse.jgit.transport.TransportGitSsh.openFetch(TransportGitSsh.java:161)
    at org.eclipse.jgit.api.LsRemoteCommand.execute(LsRemoteCommand.java:202)
    ... 4 more
Caused by: com.jcraft.jsch.JSchException: Algorithm negotiation fail
    at com.jcraft.jsch.Session.receive_kexinit(Session.java:583)
    at com.jcraft.jsch.Session.connect(Session.java:320)
    at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:116)
    ... 8 more
</code>```

<p>[route] is correct and works fine in other git softwares</p>

答:
Egit in Eclipse seems to throw this error when it does not support any of the chipers supported the the ssh server. In my case, the SSH server was set to only accept a handful of strong chipers. I noticed errors similar to the following on the server's ssh logs:

fatal: Unable to negotiate with xx.xx.xx.xx port 12345: no matching cipher found. Their offer: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc

The reason for the error on the client was because the default Java install did not support any of the strong chipers. Since we were already using the webupd8 team ppa to install our Java packages, the solution was to simply install the unlimited-jce-policy package.

```<code>apt install oracle-java8-unlimited-jce-policy
</code>```

Restart Eclipse and you're all set.

Body:
I have Eclipse Juno, a Synology Server DS213+ with a Git Server. I'm trying to checkout a project from my Git Server to my workspace and when I use EGit in Eclipse I have this error:

org.eclipse.jgit.api.errors.TransportException: ssh://[route]/volume1/Git/project.git: Algorithm negotiation fail
    at org.eclipse.jgit.api.LsRemoteCommand.execute(LsRemoteCommand.java:223)
    at org.eclipse.jgit.api.LsRemoteCommand.call(LsRemoteCommand.java:159)
    at org.eclipse.egit.core.op.ListRemoteOperation.run(ListRemoteOperation.java:99)
    at org.eclipse.egit.ui.internal.clone.SourceBranchPage$8.run(SourceBranchPage.java:324)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)
Caused by: org.eclipse.jgit.errors.TransportException: ssh://[route]/volume1/Git/project.git: Algorithm negotiation fail
    at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:159)
    at org.eclipse.jgit.transport.SshTransport.getSession(SshTransport.java:136)
    at org.eclipse.jgit.transport.TransportGitSsh$SshFetchConnection.<init>(TransportGitSsh.java:262)
    at org.eclipse.jgit.transport.TransportGitSsh.openFetch(TransportGitSsh.java:161)
    at org.eclipse.jgit.api.LsRemoteCommand.execute(LsRemoteCommand.java:202)
    ... 4 more
Caused by: com.jcraft.jsch.JSchException: Algorithm negotiation fail
    at com.jcraft.jsch.Session.receive_kexinit(Session.java:583)
    at com.jcraft.jsch.Session.connect(Session.java:320)
    at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:116)
    ... 8 more

[route] is correct and works fine in other git softwares

Body:
Egit in Eclipse seems to throw this error when it does not support any of the chipers supported the the ssh server. In my case, the SSH server was set to only accept a handful of strong chipers. I noticed errors similar to the following on the server's ssh logs:

fatal: Unable to negotiate with xx.xx.xx.xx port 12345: no matching cipher found. Their offer: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc

The reason for the error on the client was because the default Java install did not support any of the strong chipers. Since we were already using the webupd8 team ppa to install our Java packages, the solution was to simply install the unlimited-jce-policy package.

apt install oracle-java8-unlimited-jce-policy

Restart Eclipse and you're all set.