问:
Applying clip-path to parent causes shaky animations to child elements
Currently, I'm running into a weird bug with clip-path property in css. I'm applying the polygon clip path to create an angled section on this landing page I'm developing for my job. The issue is, whenever I apply clip-path, any child elements inside of this parent container that have transitions become shaky. I've toggled the property on/off and for some reason, whenever I removed the clip-path property, the animations are smooth again?

Click to view my jsfiddle

Below is the html and css:

HTML

```<code><header class="gs_hero">
 <div class="container-fluid">
    <div class="row">
        <section class="gs_hero_contents">
            <div class="gs_hero_callout">
                <h1>Getting Started</h1>
                <p>7 Steps To Setting Up Your Artwork</p>
                <button class="gs_lm_btn" id="gs_lm_btn">Learn More</button>
            </div>
        </section>
    </div>
 </div>
</header>
</code>```

CSS

```<code>.gs_hero {
  background: url(../img/custom_journey_header.jpg) no-repeat;
  background-position: 0 60%;
  background-size: cover;
  position: relative;
  padding-bottom: 100px;
  -webkit-clip-path: polygon(0 0, 1600px 0, 1600px 70%, 0 100%);
  clip-path: polygon(0 0, 1600px 0, 1600px 70%, 0 100%);
  transition: -webkit-clip-path 0.35s, clip-path 0.35s;
}
.gs_hero:before {
  content: "";
  display: block;
  background-color: rgba(130, 29, 33, 0.75);
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.gs_hero_contents {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}
.gs_hero_contents h1 {
  font-size: 25px;
  font-weight: 800;
  margin: 0;
  text-transform: uppercase;
}
.gs_hero_contents p {
  font-size: 19px;
  margin: 8px auto;
}
.gs_hero_callout {
  color: rgba(255, 255, 255, 1);
  text-align: center;
  margin: 60px auto 0;
}
.gs_lm_btn {
  background-color: rgba(236, 54, 66, 1);
  border: none;
  border-radius: 38px;
  color: rgba(255, 255, 255, 1);
  font-size: 17px;
  font-weight: 900;
  text-transform: uppercase;
  outline: none;
  margin: 15px auto 0;
  padding: 12px;
  width: 160px;
  -webkit-appearance: none;
  -moz-appearance: none;
  -o-appearance: none;
  -webkit-transition: box-shadow 425ms ease, opacity 425ms ease,
  transform 425ms ease;
  -moz-transition: box-shadow 425ms ease, opacity 425ms ease, transform
  425ms ease;
  -o-transition: box-shadow 425ms ease, opacity 425ms ease, transform
  425ms ease;
 }
 .gs_lm_btn:hover {
    box-shadow: 0 33px 35px -10px rgba(0,0,0,0.15);
    opacity: 0.8;
    transform: translateY(2px);
 }
</code>```

答:
As it appears to not work properly with clip-path, and since clip-path has bad browser support, one workaround could be to use transform: skew to create the sloped/slanted bottom

/*********************************************************************
- overrides
*********************************************************************/
body {
    font-family: 'Source Sans Pro','Helvetica Neue',Helvetica,Arial,sans-serif;
}
h1,h2,h3,h4,h5,h6 {
    font-family: 'Source Sans Pro','Helvetica Neue',Helvetica,Arial,sans-serif;
}
h2 {
    margin: 0;
}
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}
.content {
    padding: 0;
    /*min-height: 4000px;*/
}
.content-wrapper {
    background-color: rgba(255,255,255,1);
}
/*********************************************************************
- gs hero parent
*********************************************************************/
.gs_hero {
    background: url(../img/custom_journey_header.jpg) no-repeat;
    background-position: 0 60%;
    background-size: cover;
    position: relative;
    padding-bottom: 100px;
    overflow: hidden;
}
.gs_hero:before {
    content: "";
    display: block;
    background-color: rgba(130, 29, 33, 0.75);
    position: absolute;
    transform: skewY(-3deg);
    top: -50%;
    left: 0;
    width: 100%;
    height: 130%;
}
/*********************************************************************
- gs hero contents
*********************************************************************/
.gs_hero_contents {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    /*margin: 10vh auto;*/
}
.gs_hero_contents h1 {
    font-size: 25px;
    font-weight: 800;
    margin: 0;
    text-transform: uppercase;
}
.gs_hero_contents p {
    font-size: 19px;
    margin: 8px auto;
}
.gs_hero_callout {
    color: rgba(255, 255, 255, 1);
    text-align: center;
    margin: 60px auto 0;
}
.gs_lm_btn {
    background-color: rgba(236, 54, 66, 1);
    border: none;
    border-radius: 38px;
    color: rgba(255, 255, 255, 1);
    font-size: 17px;
    font-weight: 900;
    text-transform: uppercase;
    outline: none;
    margin: 15px auto 0;
    padding: 12px;
    width: 160px;
    -webkit-appearance: none;
    -moz-appearance: none;
    -o-appearance: none;
    -webkit-transition: box-shadow 425ms ease, opacity 425ms ease, transform 425ms ease;
    -moz-transition: box-shadow 425ms ease, opacity 425ms ease, transform 425ms ease;
    -o-transition: box-shadow 425ms ease, opacity 425ms ease, transform 425ms ease;
}
.gs_lm_btn:hover {
    box-shadow: 0 33px 35px -10px rgba(0,0,0,0.15);
    opacity: 0.8;
    transform: translateY(2px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="gs_hero">
 <div class="container-fluid">
  <div class="row">
   <section class="gs_hero_contents">
    <div class="gs_hero_callout">
     <h1>Getting started</h1>
     <p>7 Steps To Setting Up Your Artwork</p>
     <button class="gs_lm_btn" id="gs_lm_btn">Learn More</button>
    </div>
   </section>
  </div>
 </div>
</header></code>```

Body:
Currently, I'm running into a weird bug with clip-path property in css. I'm applying the polygon clip path to create an angled section on this landing page I'm developing for my job. The issue is, whenever I apply clip-path, any child elements inside of this parent container that have transitions become shaky. I've toggled the property on/off and for some reason, whenever I removed the clip-path property, the animations are smooth again?

Click to view my jsfiddle

Below is the html and css:

HTML

Getting Started

7 Steps To Setting Up Your Artwork

                <button class="gs_lm_btn" id="gs_lm_btn">Learn More</button>

CSS

.gs_hero {
  background: url(../img/custom_journey_header.jpg) no-repeat;
  background-position: 0 60%;
  background-size: cover;
  position: relative;
  padding-bottom: 100px;
  -webkit-clip-path: polygon(0 0, 1600px 0, 1600px 70%, 0 100%);
  clip-path: polygon(0 0, 1600px 0, 1600px 70%, 0 100%);
  transition: -webkit-clip-path 0.35s, clip-path 0.35s;
}
.gs_hero:before {
  content: "";
  display: block;
  background-color: rgba(130, 29, 33, 0.75);
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.gs_hero_contents {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}
.gs_hero_contents h1 {
  font-size: 25px;
  font-weight: 800;
  margin: 0;
  text-transform: uppercase;
}
.gs_hero_contents p {
  font-size: 19px;
  margin: 8px auto;
}
.gs_hero_callout {
  color: rgba(255, 255, 255, 1);
  text-align: center;
  margin: 60px auto 0;
}
.gs_lm_btn {
  background-color: rgba(236, 54, 66, 1);
  border: none;
  border-radius: 38px;
  color: rgba(255, 255, 255, 1);
  font-size: 17px;
  font-weight: 900;
  text-transform: uppercase;
  outline: none;
  margin: 15px auto 0;
  padding: 12px;
  width: 160px;
  -webkit-appearance: none;
  -moz-appearance: none;
  -o-appearance: none;
  -webkit-transition: box-shadow 425ms ease, opacity 425ms ease,
  transform 425ms ease;
  -moz-transition: box-shadow 425ms ease, opacity 425ms ease, transform
  425ms ease;
  -o-transition: box-shadow 425ms ease, opacity 425ms ease, transform
  425ms ease;
 }
 .gs_lm_btn:hover {
    box-shadow: 0 33px 35px -10px rgba(0,0,0,0.15);
    opacity: 0.8;
    transform: translateY(2px);
 }

Body:
As it appears to not work properly with clip-path, and since clip-path has bad browser support, one workaround could be to use transform: skew to create the sloped/slanted bottom

/*********************************************************************
- overrides
*********************************************************************/
body {
    font-family: 'Source Sans Pro','Helvetica Neue',Helvetica,Arial,sans-serif;
}
h1,h2,h3,h4,h5,h6 {
    font-family: 'Source Sans Pro','Helvetica Neue',Helvetica,Arial,sans-serif;
}
h2 {
    margin: 0;
}
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}
.content {
    padding: 0;
    /*min-height: 4000px;*/
}
.content-wrapper {
    background-color: rgba(255,255,255,1);
}
/*********************************************************************
- gs hero parent
*********************************************************************/
.gs_hero {
    background: url(../img/custom_journey_header.jpg) no-repeat;
    background-position: 0 60%;
    background-size: cover;
    position: relative;
    padding-bottom: 100px;
    overflow: hidden;
}
.gs_hero:before {
    content: "";
    display: block;
    background-color: rgba(130, 29, 33, 0.75);
    position: absolute;
    transform: skewY(-3deg);
    top: -50%;
    left: 0;
    width: 100%;
    height: 130%;
}
/*********************************************************************
- gs hero contents
*********************************************************************/
.gs_hero_contents {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    /*margin: 10vh auto;*/
}
.gs_hero_contents h1 {
    font-size: 25px;
    font-weight: 800;
    margin: 0;
    text-transform: uppercase;
}
.gs_hero_contents p {
    font-size: 19px;
    margin: 8px auto;
}
.gs_hero_callout {
    color: rgba(255, 255, 255, 1);
    text-align: center;
    margin: 60px auto 0;
}
.gs_lm_btn {
    background-color: rgba(236, 54, 66, 1);
    border: none;
    border-radius: 38px;
    color: rgba(255, 255, 255, 1);
    font-size: 17px;
    font-weight: 900;
    text-transform: uppercase;
    outline: none;
    margin: 15px auto 0;
    padding: 12px;
    width: 160px;
    -webkit-appearance: none;
    -moz-appearance: none;
    -o-appearance: none;
    -webkit-transition: box-shadow 425ms ease, opacity 425ms ease, transform 425ms ease;
    -moz-transition: box-shadow 425ms ease, opacity 425ms ease, transform 425ms ease;
    -o-transition: box-shadow 425ms ease, opacity 425ms ease, transform 425ms ease;
}
.gs_lm_btn:hover {
    box-shadow: 0 33px 35px -10px rgba(0,0,0,0.15);
    opacity: 0.8;
    transform: translateY(2px);
}

<header class="gs_hero">
 <div class="container-fluid">
  <div class="row">
   <section class="gs_hero_contents">
    <div class="gs_hero_callout">
     <h1>Getting started</h1>
     <p>7 Steps To Setting Up Your Artwork</p>
     <button class="gs_lm_btn" id="gs_lm_btn">Learn More</button>
    </div>
   </section>
  </div>
 </div>
</header>


来源: stackexchange

问:
How do I use a PriorityQueue?
How do I get a PriorityQueue to sort on what I want it to sort on?

Also, is there a difference between the offer and add methods?

答:
no different, as declare in javadoc:</p>

```<code>public boolean add(E e) {
    return offer(e);
}
</code>```

OwnerDisplayName: Svish

ContentLicense: CC BY-SA 3.0

Title: How do I use a PriorityQueue?

Body:
no different, as declare in javadoc:

public boolean add(E e) {
    return offer(e);
}

ContentLicense: CC BY-SA 2.5


问:
Android Studio and Git commit error
I made a first git commit from inside an Android Studio project.
It asked me to check for a CR option, i have done that, and it was successful but some files were left again in the Local Changes tab.
Then I tried a second commit and it failed with the same error for all the left files:

0 files committed, 46 files failed to commit

Error:warning: CRLF will be replaced by LF in gradlew.bat.
  The file will have its original line endings in your working directory.

(Android Studio 1.5.1 on Ubuntu 14.04)

How can I solve the issue?

答:
According to JetBrains's blog:

You can change the line ending style for the current file in the status bar:

or

You can also perform a bulk change. Just select a target file or a directory in the project view and choose new separator via Main Menu → File → Line Separator.

Title: Android Studio and Git commit error


问:
Extracting a javascript file from webpack build
I am using webpack for a project where I need to have a javascript config file as part of the built files, but I cannot figure out how to do that.

So I need to have these files in the output:

index.html
app.js
config.js

I figure I need to either:

1) Copy the config.js file from the source folder to the build folder with CopyWebpackPlugin, or

2) Include the file in the compiled bundle and then extract it with ExtractTextWebpackPlugin.

I have tried dozens of different ways of configuring this, but when trying with the copy method, I get the file both inside the app.js bundle AND as a separate file. When I try with the extract method, I cannot seem to figure out how to extract javascript from the main bundle. The docs all seem to explain how to extract css.

How would I go about something like this?

答:
You should be able to accomplish this by using multiple entry points.
https://webpack.js.org/concepts/entry-points/

```<code>entry: {
    main: './path/to/file/app.js',
    config: './path/to/file/config.js'
}

output: {
    filename: 'output/path/[name].js'
}
</code>```

A more complex option, which is typically used for vendor files, would be to use code-splitting.
https://webpack.js.org/guides/code-splitting/

Body:
You should be able to accomplish this by using multiple entry points.
https://webpack.js.org/concepts/entry-points/

entry: {
    main: './path/to/file/app.js',
    config: './path/to/file/config.js'
}

output: {
    filename: 'output/path/[name].js'
}

A more complex option, which is typically used for vendor files, would be to use code-splitting.
https://webpack.js.org/guides/code-splitting/


问:
Look for new versions of dependencies
Is there any way to make maven look for new versions of dependencies?

for example, i have

            commons-lang
            commons-lang
            2.3

version 2.4 could be out, I dont know. i'd rather not check is manually(by writting 2.4 in this case), because i have many dependencies. I think i saw some trick to make maven use latest version.

答:
Yah you can't make it look for newer versions of dependencies. What you can do is look at the repo, try a search at http://www.mvnrepository.com/

Really you shouldn't want Maven doing this. It could cause a lot of nasty issues. Sometimes backwards compatibility can break even in point releases.

OwnerDisplayName: mark

Title: Look for new versions of dependencies

OwnerDisplayName: Rob Ottaway


问:
How can I restore the "default" button style
I have a save button, and when the user mouses over it, I change some styles - for example:

```<code>$('.saveButton').mouseover(function() {
   $(this).css("background-color", "red");
   $(this).parents('fieldset').css("border", "2px solid red");
});
</code>```

When the mouse leaves the button, I would like to restore the original:

```<code>$('.saveButton').mouseout(function() {
   $(this).css("background-color", "#EEE");
   $(this).parents('fieldset').css("border", "1px solid gray");
});
</code>```

However, leaving aside the matter of whether or not the default button background color is #EEE, when this code executes the button loses its rounded look, and has square corners.

Is it possible to do this?

答:
This would be far better suited for CSS :hover pseudo-clas.  And much faster than javascript too.

```<code>.fieldset-class:hover { border: 2px solid red;}
.saveButton:hover { background-color:red;}
</code>```

Any time you only need to change CSS on mouseover/mouseout events, use this method.

Here is a live example from Soh Tanaka of CSS :hover in action.  Those popup tooltips on the bar?  Pure CSS.

UPDATE

There is a flaw in my CSS in relation to your problem model.  This will cause the hover on the fieldset to fire even if you are not hovering on the button.  I would use the second line, .saveButton:hover in CSS, and use JavaScript for the fieldset hover, using a class as the other answers have pointed out.

(Actaully I would change my problem model to accept a pure CSS solution, but I digress...)

Body:
I have a save button, and when the user mouses over it, I change some styles - for example:

$('.saveButton').mouseover(function() {
   $(this).css("background-color", "red");
   $(this).parents('fieldset').css("border", "2px solid red");
});

When the mouse leaves the button, I would like to restore the original:

$('.saveButton').mouseout(function() {
   $(this).css("background-color", "#EEE");
   $(this).parents('fieldset').css("border", "1px solid gray");
});

However, leaving aside the matter of whether or not the default button background color is #EEE, when this code executes the button loses its rounded look, and has square corners.

Is it possible to do this?

Body:
This would be far better suited for CSS :hover pseudo-clas.  And much faster than javascript too.

.fieldset-class:hover { border: 2px solid red;}
.saveButton:hover { background-color:red;}

Any time you only need to change CSS on mouseover/mouseout events, use this method.

Here is a live example from Soh Tanaka of CSS :hover in action.  Those popup tooltips on the bar?  Pure CSS.

UPDATE

There is a flaw in my CSS in relation to your problem model.  This will cause the hover on the fieldset to fire even if you are not hovering on the button.  I would use the second line, .saveButton:hover in CSS, and use JavaScript for the fieldset hover, using a class as the other answers have pointed out.

(Actaully I would change my problem model to accept a pure CSS solution, but I digress...)


问:
equals() doesn't work as expected with Selenium
I am trying to compare current URL with a string URL, but the following code returns false.

```<code>driver.get("https://www.facebook.com");
System.out.println(driver.getCurrentUrl().equals("https://www.facebook.com"));
</code>```

答:
Instead of using equals() try to use startsWith():

driver.getCurrentUrl().startsWith("https://www.facebook.com")

or contains():

driver.getCurrentUrl().contains("https://www.facebook.com")

This approach will be much better.

For using equals() you need to have exactly the same path which you expect.

However with contains() or startsWith() you can check expected behaviour and make an assertion.

I created some demo code:

```<code>public class FacebookDemoTest {

    private WebDriver driver;

    @BeforeMethod
    public void setUp() {
        driver = DriverManager.getInstance();
        driver.get("https://www.facebook.com");
    }

    @Test
    public void testContainsAndStartsWith() throws Exception {
        System.out.println("CURRENT URL:" + driver.getCurrentUrl());

        Assert.assertTrue(driver.getCurrentUrl().contains("https://www.facebook.com"));
        Assert.assertTrue(driver.getCurrentUrl().startsWith("https://www.facebook.com"));
    }

    @Test
    public void testEquals() throws Exception {
        System.out.println("CURRENT URL:" + driver.getCurrentUrl());

        Assert.assertTrue(driver.getCurrentUrl().equals("https://www.facebook.com"));
        Assert.assertTrue(driver.getCurrentUrl().contentEquals("https://www.facebook.com"));
    }

    @AfterMethod
    public void tearDown() throws Exception {
        DriverManager.closeQuietly();
    }
}
</code>```

Here is results:

and current URL from console log:

CURRENT URL:https://www.facebook.com/

Body:
I am trying to compare current URL with a string URL, but the following code returns false.

driver.get("https://www.facebook.com");
System.out.println(driver.getCurrentUrl().equals("https://www.facebook.com"));

Body:
Instead of using equals() try to use startsWith():

driver.getCurrentUrl().startsWith("https://www.facebook.com")

or contains():

driver.getCurrentUrl().contains("https://www.facebook.com")

This approach will be much better.

For using equals() you need to have exactly the same path which you expect.

However with contains() or startsWith() you can check expected behaviour and make an assertion.

I created some demo code:

public class FacebookDemoTest {

    private WebDriver driver;

    @BeforeMethod
    public void setUp() {
        driver = DriverManager.getInstance();
        driver.get("https://www.facebook.com");
    }

    @Test
    public void testContainsAndStartsWith() throws Exception {
        System.out.println("CURRENT URL:" + driver.getCurrentUrl());

        Assert.assertTrue(driver.getCurrentUrl().contains("https://www.facebook.com"));
        Assert.assertTrue(driver.getCurrentUrl().startsWith("https://www.facebook.com"));
    }

    @Test
    public void testEquals() throws Exception {
        System.out.println("CURRENT URL:" + driver.getCurrentUrl());

        Assert.assertTrue(driver.getCurrentUrl().equals("https://www.facebook.com"));
        Assert.assertTrue(driver.getCurrentUrl().contentEquals("https://www.facebook.com"));
    }

    @AfterMethod
    public void tearDown() throws Exception {
        DriverManager.closeQuietly();
    }
}

Here is results:

and current URL from console log:

CURRENT URL:https://www.facebook.com/


问:
asp.net mvc core knockout.js multiple nested containers not binding properly
This is the code of the testing application i am creating.

```<code><style>
#scroll-wrapper {
    margin: 5px;
    max-height: 250px;
    overflow: auto;
    vertical-align: top;
}

#thumbnails {
    vertical-align: top;
    padding-bottom: 10px;
    max-height: 500px;
    min-width: 100px;
    overflow-y: hidden;
    overflow-x: scroll;
    white-space: nowrap;
}

.thumbnail-container {
    display: inline-block;
    position: relative;
    line-height: 5px;
    margin: 3px;
    margin-bottom: 15px !important;
}
#abc {
    overflow-y: scroll;
    overflow-x: hidden;
    height: 200px;
}
</code>```

```<code><form method="post">
    <div data-bind="foreach: lists" id="thumbnails">
            <div class="thumbnail-container">
                <span data-bind="text:listname"></span><br /><br /><br /><br /><br />
                <div id="abc">
                    <ul class="list-group" data-bind="foreach: cardlists">
                        <li class="list-group-item">
                            <span data-bind="text: cardname"></span>
                            <a href="#" data-bind="click: $root.removecard">Del</a>
                        </li>
                    </ul>
                    <a href="#" data-bind="click:  $parent.showhideaddcard">Add Card</a><br />
                    <div data-bind="visible: $parent.showRenderTimes">
                        <input type="text" data-bind="value: $parent.cardtext" /><br /><br /><br />
                        <input type="button" value="Add" data-bind="click: $parent.addcard" />
                        <input type="button" value="Cancel" data-bind="click: $parent.cancelcard" />
                    </div>
                </div>
            </div>
       </div>
    <p>
        <span id="addVar" data-bind="click: addList">Add List</span>
    </p>
    <p class="alignRight">
        <input type="submit" value="Check">
    </p>
</form>

<script type="text/javascript">

        var initialData = [
        {
            listname: "list1",containername :"container1", cardlists: [
            { cardname: "car1111111" },
            { cardname: "caddsdf" }]
        },
        {
            listname: "list2",containername :"container2", cardlists: [
                       { cardname: "card 1" },
                       { cardname: "card 2" }]
        },
        {
            listname: "list3", containername: "container3", cardlists: [
                       { cardname: "card 1" },
                       { cardname: "card 2" }]
            },
        {
            listname: "list4", containername: "container4", cardlists: [
                       { cardname: "card 1" },
                       { cardname: "card 2" }]
            },
        {
            listname: "list5", containername: "container5", cardlists: [
                       { cardname: "card 1" },
                       { cardname: "card 2" }]
            },
        {
            listname: "list6", containername: "container6", cardlists: [
                       { cardname: "card 1" },
                       { cardname: "card 2" }]
            },
        {
            listname: "list7", containername: "container7", cardlists: [
                    { cardname: "card 3" },
                    { cardname: "card 4" },
                    { cardname: "card 5" },
                    { cardname: "card 6" },
                    { cardname: "card 7" },
                    { cardname: "card 8" },
                    { cardname: "card 9" },
                    { cardname: "card 10" },
                    { cardname: "card 11" }]
            },
        {
            listname: "list6", containername: "container8", cardlists: [
                { cardname: "card 1" },
                { cardname: "card 2" }]
            },
        {
            listname: "list6", containername: "container9", cardlists: [
                 { cardname: "card 1" },
                 { cardname: "card 2" }]
            },
        {
            listname: "list6", containername: "container10", cardlists: [
                 { cardname: "card 1" },
                 { cardname: "card 2" }]
            },
        {
            listname: "list6", containername: "container11", cardlists: [
                { cardname: "card 1" },
                { cardname: "card 2" }]
            }
        ];

    var ListModal = function(lists) {
        var self = this;
        self.showRenderTimes = ko.observable(false);
        self.cardtext = ko.observable("ff");
        self.lists = ko.observableArray(ko.utils.arrayMap(lists, function (list) {
            return { listname: list.listname, containername:list.containername, cardlists: ko.observableArray(list.cardlists) };
        }));

        self.addList = function() {
            self.lists.push({
                listname: "abc",
                containername:"container5",
                cardlists: ko.observableArray([
                    {
                        cardname: "Bungle"
                    },
                    {
                        cardname: "George"
                    },
                    {
                        cardname: "Zippy"
                    }
                ])
            });
        };

        self.addcard = function (lists) {
            lists.cardlists.push({
                cardname: self.cardtext
            });
            self.showRenderTimes(false);
        };
        self.cancelcard = function () {
            self.showRenderTimes(false);
        };

        self.showhideaddcard = function (lists) {
           self.showRenderTimes(true);
        };

        self.removecard = function (cardlist) {
            $.each(self.lists(), function () { this.cardlists.remove(cardlist) })
        };

        self.save = function ()
        {
        };
    };
    ko.applyBindings(new ListModal(initialData));
</script>
</code>```

The code generate this view

Now what should happened that when i click for example third add card in the picture only that textbox should appear but it is opening all the add card textboxes in the application.

apparently the binding is not correct. can someone correct my binding so when i press the no 3 containers add card only no 3 textbox appears. I have the idea that maybe div abc is the problem but i am not able to correct it.

答:
The bindings are working correctly. The problem is that you have only a single parent observable that stores the visible state for all your add-card sections. Naturally if each section is bound to the same showRenderTimes observable then they'll all be hidden/visible at the same time. You need to create an observable for each list that stores its visibility status.

You could move showRenderTimes from the parent ListModal to the individual lists:

```<code>self.lists = ko.observableArray(ko.utils.arrayMap(lists, function (list) {
    return { listname: list.listname, containername:list.containername, cardlists: ko.observableArray(list.cardlists), showRenderTimes: ko.observable(false) };
}));
</code>```

Then you'll need to update the bindings that use it to remove the $parent context:

```<code><!--<div data-bind="visible: $parent.showRenderTimes">-->
<div data-bind="visible: showRenderTimes">
</code>```

And your showHideAddCard and cancelCard functions modify the variable on the list that was clicked and so become:

```<code>  self.cancelcard = function (list) {
    list.showRenderTimes(false);
  };

  self.showhideaddcard = function (list) {
    list.showRenderTimes(true);
  };
</code>```

Example jsFiddle

Body:
The bindings are working correctly. The problem is that you have only a single parent observable that stores the visible state for all your add-card sections. Naturally if each section is bound to the same showRenderTimes observable then they'll all be hidden/visible at the same time. You need to create an observable for each list that stores its visibility status.

You could move showRenderTimes from the parent ListModal to the individual lists:

self.lists = ko.observableArray(ko.utils.arrayMap(lists, function (list) {
    return { listname: list.listname, containername:list.containername, cardlists: ko.observableArray(list.cardlists), showRenderTimes: ko.observable(false) };
}));

Then you'll need to update the bindings that use it to remove the $parent context:

<!--<div data-bind="visible: $parent.showRenderTimes">-->
<div data-bind="visible: showRenderTimes">

And your showHideAddCard and cancelCard functions modify the variable on the list that was clicked and so become:

  self.cancelcard = function (list) {
    list.showRenderTimes(false);
  };

  self.showhideaddcard = function (list) {
    list.showRenderTimes(true);
  };

Example jsFiddle


问:
Embed Google maps with Microsoft Power BI
I am a power BI user. I want to embed Google Maps in Power BI so as to have a flexibility like:

Lat and Long

I want them to get plotted on the Google map and when I click a location on google map, it should give me the option to put up the destination by fixing the clicked location as current location so that I can find out the distance between both the locations.

Please respond!

答:
Power BI is a Microsoft product and does not integrate with Google maps. </p>

<p>Power BI can plot data on a Bing map with lat/long. However, it doesn't sound like you want to plot data, but rather you want an interactive distance calculator. For that, I would not recommend Power BI at all. </p>

Body:
Power BI is a Microsoft product and does not integrate with Google maps.

Power BI can plot data on a Bing map with lat/long. However, it doesn't sound like you want to plot data, but rather you want an interactive distance calculator. For that, I would not recommend Power BI at all.


问:
case when in sqlserver
i try to use case in for my condition to show out which is late,but after i use case when my result show out too many result.

```<code>select
        grp.checktime,
        --min(CONVERT(smalldatetime,l.checktime)) as clockin,
        --max(CONVERT(smalldatetime,l.checktime)) as clockout,
        ClockIn = case when min(cast(l.checktime as time)) <= cast(sc.StartTime as time)
                        then convert(varchar(100), cast(l.checktime as time), 100)
                        else 'Late ClockIn ' + convert(varchar(100), cast(l.checktime as time), 100)
                        end,
        Clockout = case when max(cast(l.checktime as time)) >= cast(sc.EndTime as time)
                        then convert(varchar(100), cast(l.checktime as time), 100)
                        else 'Early ClockOut ' + convert(varchar(100), cast(l.checktime as time), 100)
                        end,
        l.userid,
        u.showname,
        u.BADGENUMBER
    from checkinout l
    inner join userinfo u on l.userid = u.userid
    inner join UserUsedsclasses uuc on u.userid = uuc.userid
    inner join SchClass sc on uuc.SchId = sc.schClassid
    inner join (
                    select distinct CONVERT(Date,checktime) as checktime
                    from checkinout
                    group by CONVERT(Date,checktime)
                ) as grp on grp.checktime = CONVERT(Date, l.checktime)
    where uuc.SchId = 1 and u.badgenumber = 107
    and u.badgenumber not in (79, 103, 78)
    and l.checktime >= dateadd(month, datediff(month, 0, GETDATE() )  , 0)
    and l.checktime <  dateadd(month, datediff(month, 0, GETDATE ())+1, 0)
    group by grp.checktime,l.userid,u.showname,u.BADGENUMBER,sc.StartTime,l.checktime,sc.EndTime
</code>```

my result show me

答:
Change your group by to group by the date of l.checktime.

```<code>select
        grp.checktime,
        --min(convert(smalldatetime,l.checktime)) as clockin,
        --max(convert(smalldatetime,l.checktime)) as clockout,
        ClockIn = case when min(cast(l.checktime as time)) <= cast(sc.StartTime as time)
                        then convert(varchar(100), cast(l.checktime as time), 100)
                        else 'Late ClockIn ' + convert(varchar(100), cast(l.checktime as time), 100)
                        end,
        Clockout = case when max(cast(l.checktime as time)) >= cast(sc.EndTime as time)
                        then convert(varchar(100), cast(l.checktime as time), 100)
                        else 'Early ClockOut ' + convert(varchar(100), cast(l.checktime as time), 100)
                        end,
        l.userid,
        u.showname,
        u.BADGENUMBER
    from checkinout l
    inner join userinfo u on l.userid = u.userid
    inner join UserUsedsclasses uuc on u.userid = uuc.userid
    inner join SchClass sc on uuc.SchId = sc.schClassid
    inner join (
                    select distinct convert(Date,checktime) as checktime
                    from checkinout
                    group by convert(Date,checktime)
                ) as grp on grp.checktime = convert(Date, l.checktime)
    where uuc.SchId = 1 and u.badgenumber = 107
      and u.badgenumber not in (79, 103, 78)
      and l.checktime >= dateadd(month, datediff(month, 0, getdate() )  , 0)
      and l.checktime <  dateadd(month, datediff(month, 0, getdate ())+1, 0)
    group by
        grp.checktime
      , l.userid
      , u.showname
      , u.BADGENUMBER
      , sc.StartTime
      , convert(date, l.checktime)
      , sc.EndTime
</code>```

Title: case when in sqlserver

Body:
i try to use case in for my condition to show out which is late,but after i use case when my result show out too many result.

select
        grp.checktime,
        --min(CONVERT(smalldatetime,l.checktime)) as clockin,
        --max(CONVERT(smalldatetime,l.checktime)) as clockout,
        ClockIn = case when min(cast(l.checktime as time)) <= cast(sc.StartTime as time)
                        then convert(varchar(100), cast(l.checktime as time), 100)
                        else 'Late ClockIn ' + convert(varchar(100), cast(l.checktime as time), 100)
                        end,
        Clockout = case when max(cast(l.checktime as time)) >= cast(sc.EndTime as time)
                        then convert(varchar(100), cast(l.checktime as time), 100)
                        else 'Early ClockOut ' + convert(varchar(100), cast(l.checktime as time), 100)
                        end,
        l.userid,
        u.showname,
        u.BADGENUMBER
    from checkinout l
    inner join userinfo u on l.userid = u.userid
    inner join UserUsedsclasses uuc on u.userid = uuc.userid
    inner join SchClass sc on uuc.SchId = sc.schClassid
    inner join (
                    select distinct CONVERT(Date,checktime) as checktime
                    from checkinout
                    group by CONVERT(Date,checktime)
                ) as grp on grp.checktime = CONVERT(Date, l.checktime)
    where uuc.SchId = 1 and u.badgenumber = 107
    and u.badgenumber not in (79, 103, 78)
    and l.checktime >= dateadd(month, datediff(month, 0, GETDATE() )  , 0)
    and l.checktime <  dateadd(month, datediff(month, 0, GETDATE ())+1, 0)
    group by grp.checktime,l.userid,u.showname,u.BADGENUMBER,sc.StartTime,l.checktime,sc.EndTime

my result show me

Body:
Change your group by to group by the date of l.checktime.

select
        grp.checktime,
        --min(convert(smalldatetime,l.checktime)) as clockin,
        --max(convert(smalldatetime,l.checktime)) as clockout,
        ClockIn = case when min(cast(l.checktime as time)) <= cast(sc.StartTime as time)
                        then convert(varchar(100), cast(l.checktime as time), 100)
                        else 'Late ClockIn ' + convert(varchar(100), cast(l.checktime as time), 100)
                        end,
        Clockout = case when max(cast(l.checktime as time)) >= cast(sc.EndTime as time)
                        then convert(varchar(100), cast(l.checktime as time), 100)
                        else 'Early ClockOut ' + convert(varchar(100), cast(l.checktime as time), 100)
                        end,
        l.userid,
        u.showname,
        u.BADGENUMBER
    from checkinout l
    inner join userinfo u on l.userid = u.userid
    inner join UserUsedsclasses uuc on u.userid = uuc.userid
    inner join SchClass sc on uuc.SchId = sc.schClassid
    inner join (
                    select distinct convert(Date,checktime) as checktime
                    from checkinout
                    group by convert(Date,checktime)
                ) as grp on grp.checktime = convert(Date, l.checktime)
    where uuc.SchId = 1 and u.badgenumber = 107
      and u.badgenumber not in (79, 103, 78)
      and l.checktime >= dateadd(month, datediff(month, 0, getdate() )  , 0)
      and l.checktime <  dateadd(month, datediff(month, 0, getdate ())+1, 0)
    group by
        grp.checktime
      , l.userid
      , u.showname
      , u.BADGENUMBER
      , sc.StartTime
      , convert(date, l.checktime)
      , sc.EndTime


问:
Flow of execution in Map Reduce
I knew that the reducer cannot start until the Mapper is run fully. I want to know if the reduce in the Reducer can run while the Shuffle or Sort is still running /not fully completed. </p>

答:
A reducer can start even if "mapper task have partially completed". The param controlling it is mapreduce.slowstart

Follow this.
http://bytepadding.com/big-data/map-reduce/understanding-map-reduce-the-missing-guide/

Title: Flow of execution in Map Reduce


问:
How can I config two different git repo with different credentials in one system?
Local Repository-1

I have been working on application for my organization whose git repository cloned at C drive folder.
 I have set global configurations, and I have been able to perform commit, push, pull operations. This is private repository of my organization with unique user name, password and url. Everything working fine this repository.

Problem

Local Repository-2
  Now, I want to create local repository of my own github project (different from first one) on the same system, but on different location. This repository have different configurations than other repository on the same system. So my concern is, how can I maintain repository specific configurations(user name, password, urls) on the same client system.

答:
You have the below 2 options, Based on your preferred way (ssh or password) based access to git account:-

SSH based access:- create 2 ssh key-pairs one for your company git account and one for your own git account. you need to add public ssh keys on both the git accounts by following this article.

Password based access :- In this case you don't need to do anything, you just need to give the username and password on git push etc.

Important:- Now you need to add the git configs (git username, email etc) for your system, git has option to set these at global and local leval. I would recommend setting the user.email and user.name setting globally according to your organization, to avoid commits to your company repo which has your private git username and email.

For example below git command will show the global setting of git :-

```<code>git config --global --list
user.name=<firstname.lastname>
user.email=<company mail address>
</code>```

And to set the git username and password in your private git repo, use below command, inside your repository

```<code>git config --local user.name "amit"
git config --local user.email "amit@mail.com"
</code>```

You can confirm, that your own private repo does not have, your company username and password by running git config --edit command or git config --local --list.

Body:
You have the below 2 options, Based on your preferred way (ssh or password) based access to git account:-

SSH based access:- create 2 ssh key-pairs one for your company git account and one for your own git account. you need to add public ssh keys on both the git accounts by following this article.

Password based access :- In this case you don't need to do anything, you just need to give the username and password on git push etc.

Important:- Now you need to add the git configs (git username, email etc) for your system, git has option to set these at global and local leval. I would recommend setting the user.email and user.name setting globally according to your organization, to avoid commits to your company repo which has your private git username and email.

For example below git command will show the global setting of git :-

git config --global --list
user.name=<firstname.lastname>
user.email=<company mail address>

And to set the git username and password in your private git repo, use below command, inside your repository

git config --local user.name "amit"
git config --local user.email "amit@mail.com"

You can confirm, that your own private repo does not have, your company username and password by running git config --edit command or git config --local --list.

ContentLicense: CC BY-SA 4.0


问:
ggplot geom_point Ignoring unknown aesthetics: text issue?
I am generating an SVG facet chart. I want a tooltip to appear on hover over the points. I am using a text aesthetic in ggplot/geom_point to craft the tooltip text.

A warning is produced... Warning: Ignoring unknown aesthetics: text. In spite of the warning, it does in fact produce a tooltip as I have defined it below in the sprintf of geom_point. However, once the number of facets in the chart exceed 21, the tooltip only appears for a subset of the points. It just seems unreliable. However, removing the text aesthetic always results in a default tooltip for all points across any number of facets. When including the text aesthetic the tooltip generated is a combination of default text and the bespoke text that I have defined and looks like this...screenshot of tooltip... not ideal but at least it contains the information I want to show, in particular the Rate/'000 as an actual value rather than as a log value.

Should I avoid this functionality or is there a better, more reliable, way to achieve this effect?

```<code>    p <- ggplot(data=df.data_chart_category
               ,aes(x=TourDate, y=rate_per_thousand_lifts, group=key, colour=factor(key))
               ,environment = environment()
        ) +
        geom_point(aes(size = size, text = sprintf("Rate/'000: %s<br>Misses: %s<br>Hits: %s<br>Total Lifts: %s", rate_per_thousand_lifts, misses, hits, total_tour_count)), alpha=0.4) +
        scale_size(name = "Bin count", breaks = c(10, 50, 100, 500, 800, 1000), range = c(1,12)) +
        scale_color_manual("", values = c("Lifter1" = "red", "Lifter2" = "green", "Lifter3" = "lightblue", "Lifter4" = "purple", "NoLifter" = "cyan", "GPS" = "darkgrey")) +
        guides(colour = guide_legend(override.aes = list(size=10))) +
        facet_wrap(as.formula(paste("~", facet_wrap_column_name)), ncol=number_of_facet_columns) +
        labs(x = x_axis_label, y = snr_y_axis_label, title = snr_chart_title, subtitle = snr_chart_subtitle, caption = snr_chart_caption, color="Lifter") +
        theme_few() +
        theme(axis.text.x = element_text(angle=90, vjust=-0.01)) +
        theme(axis.title = element_text(size = axis_font_size)) +
        theme(plot.title = element_text(color = '#666666',
                                  face = 'bold',
                                  size = title_font_size,
                                  hjust = 0)) +
        scale_y_log10()

    pp <- ggplotly(p)
    htmlwidgets::saveWidget(widget=pp, file="index.html", selfcontained=FALSE)
</code>```

答:
I got my example working somewhat as I expected. I wasn't really understanding how to set up bespoke tooltips. I've posted a working example here. Data for the example can still be found at TooltipNotWorkingData.txt

The main issue related to my tooltip parameter placement.

```<code>    p <- ggplot(data=df.data_chart_category
               ,aes(x=calendar_day, y=rate_per_thousand, group=key, colour=factor(key), text = tooltip, onclick = clickjs)
               ,environment = environment()
        )
</code>```

It should be part of ggplot/aes and not geom_point/aes. Referencing tooltip in the ggplotly call pp <- ggplotly(p, tooltip = "tooltip") is necessary to override the default tooltip.

I'm still having problems with tooltip display on certain size charts and I've opened a new question for that on SO here.

Body:
I am generating an SVG facet chart. I want a tooltip to appear on hover over the points. I am using a text aesthetic in ggplot/geom_point to craft the tooltip text.

A warning is produced... Warning: Ignoring unknown aesthetics: text. In spite of the warning, it does in fact produce a tooltip as I have defined it below in the sprintf of geom_point. However, once the number of facets in the chart exceed 21, the tooltip only appears for a subset of the points. It just seems unreliable. However, removing the text aesthetic always results in a default tooltip for all points across any number of facets. When including the text aesthetic the tooltip generated is a combination of default text and the bespoke text that I have defined and looks like this...screenshot of tooltip... not ideal but at least it contains the information I want to show, in particular the Rate/'000 as an actual value rather than as a log value.

Should I avoid this functionality or is there a better, more reliable, way to achieve this effect?

    p <- ggplot(data=df.data_chart_category
               ,aes(x=TourDate, y=rate_per_thousand_lifts, group=key, colour=factor(key))
               ,environment = environment()
        ) +
        geom_point(aes(size = size, text = sprintf("Rate/'000: %s
Misses: %s
Hits: %s
Total Lifts: %s", rate_per_thousand_lifts, misses, hits, total_tour_count)), alpha=0.4) +
        scale_size(name = "Bin count", breaks = c(10, 50, 100, 500, 800, 1000), range = c(1,12)) +
        scale_color_manual("", values = c("Lifter1" = "red", "Lifter2" = "green", "Lifter3" = "lightblue", "Lifter4" = "purple", "NoLifter" = "cyan", "GPS" = "darkgrey")) +
        guides(colour = guide_legend(override.aes = list(size=10))) +
        facet_wrap(as.formula(paste("~", facet_wrap_column_name)), ncol=number_of_facet_columns) +
        labs(x = x_axis_label, y = snr_y_axis_label, title = snr_chart_title, subtitle = snr_chart_subtitle, caption = snr_chart_caption, color="Lifter") +
        theme_few() +
        theme(axis.text.x = element_text(angle=90, vjust=-0.01)) +
        theme(axis.title = element_text(size = axis_font_size)) +
        theme(plot.title = element_text(color = '#666666',
                                  face = 'bold',
                                  size = title_font_size,
                                  hjust = 0)) +
        scale_y_log10()

    pp <- ggplotly(p)
    htmlwidgets::saveWidget(widget=pp, file="index.html", selfcontained=FALSE)

Body:
I got my example working somewhat as I expected. I wasn't really understanding how to set up bespoke tooltips. I've posted a working example here. Data for the example can still be found at TooltipNotWorkingData.txt

The main issue related to my tooltip parameter placement.

    p <- ggplot(data=df.data_chart_category
               ,aes(x=calendar_day, y=rate_per_thousand, group=key, colour=factor(key), text = tooltip, onclick = clickjs)
               ,environment = environment()
        )

It should be part of ggplot/aes and not geom_point/aes. Referencing tooltip in the ggplotly call pp <- ggplotly(p, tooltip = "tooltip") is necessary to override the default tooltip.

I'm still having problems with tooltip display on certain size charts and I've opened a new question for that on SO here.


问:
Understanding sentry-provider.ini file syntax
sentry-provider.ini

```<code>[groups]
# Assigns each Hadoop group to its set of roles
engineer = engineer_role
ops = ops_role
dev_ops = engineer_role, ops_role
hbase_admin = hbase_admin_role

[roles]
# The following grants all access to source_code.
# "collection = source_code" can also be used as syntactic
# sugar for "collection = source_code->action=*"
engineer_role = collection = source_code->action=*

# The following imply more restricted access.
ops_role = collection = hive_logs->action=Query
dev_ops_role = collection = hbase_logs->action=Query

#give hbase_admin_role the ability to create/delete/modify the hbase_logs collection
#as well as to update the config for the hbase_logs collection, called hbase_logs_config.
hbase_admin_role = collection=admin->action=*, collection=hbase_logs->action=*, config=hbase_logs_config->action=*
</code>```

I do not understand what is the syntax used here and what is its meaning?
From where do these groups and role values come from?
Why there are two = symbols in one line?

Thanks!

答:
Sentry depends on an underlying authentication framework to reliably identify the requesting user, i.e. Kerberos or LDAP. This tells you what groups a user belongs to.

The Sentry configuration then defines roles. This is a level of indirection that lets you share/re-use sets of privileges across multiple groups.

Group(s) can be assigned to a role, thus giving the users in those groups the privileges associated with the role.

Privileges are defined on (typically) Hive tables or Solr collections. This can be done at several levels (server, database and/or table in the case of Hive, or collection in the case of Solr).

So the following line:

```<code>engineer_role = collection = source_code->action=*
</code>```

should be interpreted to mean: The engineer role has one privilege, which is: for the "source_code" collection, allow all actions.

When put together with group information:

```<code> [groups]
 engineer = engineer_role
 [roles]
 engineer_role = collection = source_code->action=*
</code>```

This means that any user in the "engineer" group (as determined by your authentication framework) belongs to the "engineer_role" role, and thus can perform any action on the "source_code" collection in Solr.

There are more detailed examples in the Cloudera documentation (CDH 5.8):

Policy File https://www.cloudera.com/documentation/enterprise/5-8-x/topics/cdh_sg_sentry.html

Solr https://www.cloudera.com/documentation/enterprise/5-8-x/topics/search_sentry.html

Body:
sentry-provider.ini

[groups]
# Assigns each Hadoop group to its set of roles
engineer = engineer_role
ops = ops_role
dev_ops = engineer_role, ops_role
hbase_admin = hbase_admin_role

[roles]
# The following grants all access to source_code.
# "collection = source_code" can also be used as syntactic
# sugar for "collection = source_code->action=*"
engineer_role = collection = source_code->action=*

# The following imply more restricted access.
ops_role = collection = hive_logs->action=Query
dev_ops_role = collection = hbase_logs->action=Query

#give hbase_admin_role the ability to create/delete/modify the hbase_logs collection
#as well as to update the config for the hbase_logs collection, called hbase_logs_config.
hbase_admin_role = collection=admin->action=*, collection=hbase_logs->action=*, config=hbase_logs_config->action=*

I do not understand what is the syntax used here and what is its meaning?
From where do these groups and role values come from?
Why there are two = symbols in one line?

Thanks!

Body:
Sentry depends on an underlying authentication framework to reliably identify the requesting user, i.e. Kerberos or LDAP. This tells you what groups a user belongs to.

The Sentry configuration then defines roles. This is a level of indirection that lets you share/re-use sets of privileges across multiple groups.

Group(s) can be assigned to a role, thus giving the users in those groups the privileges associated with the role.

Privileges are defined on (typically) Hive tables or Solr collections. This can be done at several levels (server, database and/or table in the case of Hive, or collection in the case of Solr).

So the following line:

engineer_role = collection = source_code->action=*

should be interpreted to mean: The engineer role has one privilege, which is: for the "source_code" collection, allow all actions.

When put together with group information:

 [groups]
 engineer = engineer_role
 [roles]
 engineer_role = collection = source_code->action=*

This means that any user in the "engineer" group (as determined by your authentication framework) belongs to the "engineer_role" role, and thus can perform any action on the "source_code" collection in Solr.

There are more detailed examples in the Cloudera documentation (CDH 5.8):

Policy File https://www.cloudera.com/documentation/enterprise/5-8-x/topics/cdh_sg_sentry.html

Solr https://www.cloudera.com/documentation/enterprise/5-8-x/topics/search_sentry.html


问:
Python elasticsearch return only entries that have a certain field
I'm trying to query an Elasticsearch, and only get results that have a certain field.

How do I query for documents that have field fields.EventData.PGID and ignore ones that don't?

```<code>datadict = es.search(index=idx1,
                     q='run_id:"Run001" AND "fields.EventData.PGID exists"',
                     sort='fields.System.TimeCreated.SystemTime',
                     size=1000)
</code>```

The way events are logged in the ES is inconsistent and such I need to find only ones where a PGID was logged. I tried doing a try block in the Python code trying to access the field from the returned values and ignoring it if I get a KeyError, but due to the limit on how many items you can receive as a query result, in some cases I have all my results lacking a PGID so I just end up wasting a query and am unable to access actual results, so I would like this filtering to happen at the query level.

答:
You can try with this filtered query

```<code>{
  "size": 1000,
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": {
            "exists": {
              "field": "fields.EventData.PGID"
            },
            "term": {
              "run_id": "Run001"
            }
          }
        }
      }
    }
  }
}
</code>```

I think you can also add the sorting to the query

Body:
I'm trying to query an Elasticsearch, and only get results that have a certain field.

How do I query for documents that have field fields.EventData.PGID and ignore ones that don't?

datadict = es.search(index=idx1,
                     q='run_id:"Run001" AND "fields.EventData.PGID exists"',
                     sort='fields.System.TimeCreated.SystemTime',
                     size=1000)

The way events are logged in the ES is inconsistent and such I need to find only ones where a PGID was logged. I tried doing a try block in the Python code trying to access the field from the returned values and ignoring it if I get a KeyError, but due to the limit on how many items you can receive as a query result, in some cases I have all my results lacking a PGID so I just end up wasting a query and am unable to access actual results, so I would like this filtering to happen at the query level.

Body:
You can try with this filtered query

{
  "size": 1000,
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": {
            "exists": {
              "field": "fields.EventData.PGID"
            },
            "term": {
              "run_id": "Run001"
            }
          }
        }
      }
    }
  }
}

I think you can also add the sorting to the query


问:
Browse fragment customisation
I want to customize a BrowseFragment.

Normally, a BrowseFragment is composed of multiple rows (header + items).

My question : Is it possible to have, for a same row (highlighted in blue), differents item types ? (see image below).

Thanks.

答:
Use the PresenterSelector

Here is an example provided by Google: CardPresenterSelector.java. The example is part of Leanback-Showcase, if you download and run it you'll notice they don't actually do what you are specifically looking for - but I believe its setup to do so if you just made some edits in the CardPresenterSelector (linked above). (There's also a nice youtube video to go along with it)

Title: Browse fragment customisation


问:
Where are fonts defined/installed for Openjdk Java on linux
Installed Oracle 8 jdk on Ubuntu, within jre/lib it has various fontProperties files plus a fonts dir containing fonts. But when installed OpenJdk 8 there is no such fonts folder on font files within jre/lib.

So where does it get its fonts from, does it come with any fonts on depen on the system having some fonts installed somewhere else.

Update
Based on advise from gerynix

fc-list

returns no fonts

```<code>GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()
</code>```

gives

```<code>java.lang.NullPointerException
        at sun.awt.FontConfiguration.getVersion(FontConfiguration.java:1264)
        at sun.awt.FontConfiguration.readFontConfigFile(FontConfiguration.java:219)
        at sun.awt.FontConfiguration.init(FontConfiguration.java:107)
        at sun.awt.X11FontManager.createFontConfiguration(X11FontManager.java:774)
        at sun.font.SunFontManager$2.run(SunFontManager.java:431)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.font.SunFontManager.<init>(SunFontManager.java:376)
        at sun.awt.FcFontManager.<init>(FcFontManager.java:35)
        at sun.awt.X11FontManager.<init>(X11FontManager.java:57)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at java.lang.Class.newInstance(Class.java:442)
        at sun.font.FontManagerFactory$1.run(FontManagerFactory.java:83)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.font.FontManagerFactory.getInstance(FontManagerFactory.java:74)
        at sun.java2d.SunGraphicsEnvironment.getFontManagerForSGE(SunGraphicsEnvironment.java:190)
        at sun.java2d.SunGraphicsEnvironment.getAvailableFontFamilyNames(SunGraphicsEnvironment.java:224)
        at sun.java2d.SunGraphicsEnvironment.getAvailableFontFamilyNames(SunGraphicsEnvironment.java:252)
        at sun.java2d.HeadlessGraphicsEnvironment.getAvailableFontFamilyNames(HeadlessGraphicsEnvironment.java:94)
        at Fonts.main(Fonts.java:10)
</code>```

答:
It gets it from the environment on top of which you are running your application.

Look into:

```<code>GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()
</code>```

https://docs.oracle.com/javase/7/docs/api/java/awt/GraphicsEnvironment.html

Body:
Installed Oracle 8 jdk on Ubuntu, within jre/lib it has various fontProperties files plus a fonts dir containing fonts. But when installed OpenJdk 8 there is no such fonts folder on font files within jre/lib.

So where does it get its fonts from, does it come with any fonts on depen on the system having some fonts installed somewhere else.

Update
Based on advise from gerynix

fc-list

returns no fonts

GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()

gives

java.lang.NullPointerException
        at sun.awt.FontConfiguration.getVersion(FontConfiguration.java:1264)
        at sun.awt.FontConfiguration.readFontConfigFile(FontConfiguration.java:219)
        at sun.awt.FontConfiguration.init(FontConfiguration.java:107)
        at sun.awt.X11FontManager.createFontConfiguration(X11FontManager.java:774)
        at sun.font.SunFontManager$2.run(SunFontManager.java:431)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.font.SunFontManager.<init>(SunFontManager.java:376)
        at sun.awt.FcFontManager.<init>(FcFontManager.java:35)
        at sun.awt.X11FontManager.<init>(X11FontManager.java:57)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at java.lang.Class.newInstance(Class.java:442)
        at sun.font.FontManagerFactory$1.run(FontManagerFactory.java:83)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.font.FontManagerFactory.getInstance(FontManagerFactory.java:74)
        at sun.java2d.SunGraphicsEnvironment.getFontManagerForSGE(SunGraphicsEnvironment.java:190)
        at sun.java2d.SunGraphicsEnvironment.getAvailableFontFamilyNames(SunGraphicsEnvironment.java:224)
        at sun.java2d.SunGraphicsEnvironment.getAvailableFontFamilyNames(SunGraphicsEnvironment.java:252)
        at sun.java2d.HeadlessGraphicsEnvironment.getAvailableFontFamilyNames(HeadlessGraphicsEnvironment.java:94)
        at Fonts.main(Fonts.java:10)

Body:
It gets it from the environment on top of which you are running your application.

Look into:

GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()

https://docs.oracle.com/javase/7/docs/api/java/awt/GraphicsEnvironment.html


问:
Python 3.4 Panda sort market-data by Date
I am trying to set up Python (3.4) code to sort a time-series by date.

In python shell, I key in the following

```<code>>>>data = quandl.get("YAHOO/INDEX_GSPC", start_date="2017-01-01", end_date="2017-01-20")
>>>print(data)
</code>```

So, I can load in the data. But when I try to use sort by the command

```<code>>>>data = data.sort_values(by='Date')
</code>```

I get the following list of errors messages. I can't seem to understand/get the syntax for date sort from http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_values.html

Experts out there......., many thanks for advice.

```<code>Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\pandas\indexes\base.py", line 2134, in get_loc
    return self._engine.get_loc(key)
  File "pandas\index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)
  File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:4279)
  File "pandas\src\hashtable_class_helper.pxi", line 732, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742)
  File "pandas\src\hashtable_class_helper.pxi", line 740, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696)
KeyError: 'Date'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    data = data.sort_values(by='Date')
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 3230, in sort_values
    k = self.xs(by, axis=other_axis).values
  File "C:\Python34\lib\site-packages\pandas\core\generic.py", line 1770, in xs
    return self[key]
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 2059, in __getitem__
    return self._getitem_column(key)
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 2066, in _getitem_column
    return self._get_item_cache(key)
  File "C:\Python34\lib\site-packages\pandas\core\generic.py", line 1386, in _get_item_cache
    values = self._data.get(item)
  File "C:\Python34\lib\site-packages\pandas\core\internals.py", line 3543, in get
    loc = self.items.get_loc(item)
  File "C:\Python34\lib\site-packages\pandas\indexes\base.py", line 2136, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas\index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)
  File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:4279)
  File "pandas\src\hashtable_class_helper.pxi", line 732, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742)
  File "pandas\src\hashtable_class_helper.pxi", line 740, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696)
KeyError: 'Date'
</code>```

答:
quandl.get loads a DataFrame with the date as index.

So if you sort by index, you're good to go:

```<code>data = data.sort_index()
</code>```

Body:
I am trying to set up Python (3.4) code to sort a time-series by date.

In python shell, I key in the following

>>>data = quandl.get("YAHOO/INDEX_GSPC", start_date="2017-01-01", end_date="2017-01-20")
>>>print(data)

So, I can load in the data. But when I try to use sort by the command

>>>data = data.sort_values(by='Date')

I get the following list of errors messages. I can't seem to understand/get the syntax for date sort from http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_values.html

Experts out there......., many thanks for advice.

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\pandas\indexes\base.py", line 2134, in get_loc
    return self._engine.get_loc(key)
  File "pandas\index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)
  File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:4279)
  File "pandas\src\hashtable_class_helper.pxi", line 732, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742)
  File "pandas\src\hashtable_class_helper.pxi", line 740, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696)
KeyError: 'Date'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    data = data.sort_values(by='Date')
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 3230, in sort_values
    k = self.xs(by, axis=other_axis).values
  File "C:\Python34\lib\site-packages\pandas\core\generic.py", line 1770, in xs
    return self[key]
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 2059, in __getitem__
    return self._getitem_column(key)
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 2066, in _getitem_column
    return self._get_item_cache(key)
  File "C:\Python34\lib\site-packages\pandas\core\generic.py", line 1386, in _get_item_cache
    values = self._data.get(item)
  File "C:\Python34\lib\site-packages\pandas\core\internals.py", line 3543, in get
    loc = self.items.get_loc(item)
  File "C:\Python34\lib\site-packages\pandas\indexes\base.py", line 2136, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas\index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)
  File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:4279)
  File "pandas\src\hashtable_class_helper.pxi", line 732, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742)
  File "pandas\src\hashtable_class_helper.pxi", line 740, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696)
KeyError: 'Date'

Body:
quandl.get loads a DataFrame with the date as index.

So if you sort by index, you're good to go:

data = data.sort_index()


问:
C# DateTimePicker DataBinding Parse event not working
I have a datetimepicker that I am binding with nullable Date/Time column in dataset. I applied Format event successfully for null and not null object value. But, when I uncheck dtp control it does not get set to null in the dataset.
This is my code:

```<code>dtpBirthdate.DataBindings.Add(new Binding("Value", bsStaff, "birthDate", true));
dtpBirthdate.DataBindings["Value"].Format += new ConvertEventHandler(dtpFormat);
dtpBirthdate.DataBindings["Value"].Parse += new ConvertEventHandler(dtpParse);
</code>```

Format and Parse events:

```<code>private void dtpFormat(object sender, ConvertEventArgs e)
{
      Binding b = sender as Binding;
      if(b != null)
      {
           DateTimePicker dtp = (b.Control as DateTimePicker);
           if(dtp != null)
           {
                if (e.Value == null || e.Value == DBNull.Value)
                {
                    dtp.Checked = false;
                    dtp.CustomFormat = " ";
                    e.Value = false;
                }
                else
                {
                    dtp.Checked = true;
                    dtp.CustomFormat = "dd-MMM-yyyy";
                    dtp.Value = (DateTime) e.Value;
                }
            }
        }
    }

    private void dtpParse(object sender, ConvertEventArgs e)
    {
        Binding b = sender as Binding;

        if (b != null)
        {
            DateTimePicker dtp = (b.Control as DateTimePicker);
            if (dtp != null)
            {
                if (dtp.Checked == false)
                {
                    e.Value = DBNull.Value;
                }
                else
                {
                    e.Value = dtp.Value;
                }
            }
        }
   }
</code>```

After debugging, I found that it goes to infinite loop between parse and format events. What is wrong with my code?

Edit: There is also a datagridview binded to bsStaff bindingsource.

答:
I noticed that you are using a Databinding event capture for both controls but on your first dtpFormat event handler you don't check for databinding values first.

Imho this line of code:

if (e.Value == null || e.Value == DBNull.Value)

needs to be changed to

if (e.Value == DBNull.Value || e.Value == null)

Body:
I have a datetimepicker that I am binding with nullable Date/Time column in dataset. I applied Format event successfully for null and not null object value. But, when I uncheck dtp control it does not get set to null in the dataset.
This is my code:

dtpBirthdate.DataBindings.Add(new Binding("Value", bsStaff, "birthDate", true));
dtpBirthdate.DataBindings["Value"].Format += new ConvertEventHandler(dtpFormat);
dtpBirthdate.DataBindings["Value"].Parse += new ConvertEventHandler(dtpParse);

Format and Parse events:

private void dtpFormat(object sender, ConvertEventArgs e)
{
      Binding b = sender as Binding;
      if(b != null)
      {
           DateTimePicker dtp = (b.Control as DateTimePicker);
           if(dtp != null)
           {
                if (e.Value == null || e.Value == DBNull.Value)
                {
                    dtp.Checked = false;
                    dtp.CustomFormat = " ";
                    e.Value = false;
                }
                else
                {
                    dtp.Checked = true;
                    dtp.CustomFormat = "dd-MMM-yyyy";
                    dtp.Value = (DateTime) e.Value;
                }
            }
        }
    }

    private void dtpParse(object sender, ConvertEventArgs e)
    {
        Binding b = sender as Binding;

        if (b != null)
        {
            DateTimePicker dtp = (b.Control as DateTimePicker);
            if (dtp != null)
            {
                if (dtp.Checked == false)
                {
                    e.Value = DBNull.Value;
                }
                else
                {
                    e.Value = dtp.Value;
                }
            }
        }
   }

After debugging, I found that it goes to infinite loop between parse and format events. What is wrong with my code?

Edit: There is also a datagridview binded to bsStaff bindingsource.


问:
Laravel 5 next and previous paging
Hello I have a list of max 5 articles in my homepage but I have many more articles and I would like to show these articles in other pages. So when I see more old posts, I would like to do a pagination like user home page / 1 when I get it as a result of posting it as url. But I do not follow the correct paths when I make directions.
I need to change the following lines of code to help you change the point, good day, good day
app/Http/Controller/HomeController:

```<code>public function deneme($page){
        $url = url()->full();
        $myUrl = explode('/', $url);
        $uz= sizeof($myUrl);
        $myUrl = $myUrl[$uz-1];
        if ($myUrl == 'work.com'){
            $yazilar = YaziModel::join('users as u','u.id','=', 'yazilar.kullaniciid')->select('yazilar.*','u.name','u.created_at')->orderBy('yazilar.id', 'DESC')->get();

            $posts = array_slice($yazilar->getIterator()->getArrayCopy(),0,5);
            return view('backend.pages.anasayfa')->with('yazilar', $posts);
        }else{
            $baslangic = $page*5;
            $yazilar = YaziModel::join('users as u','u.id','=', 'yazilar.kullaniciid')->select('yazilar.*','u.name','u.created_at')->orderBy('yazilar.id', 'DESC')->get();

            $posts = array_slice($yazilar->getIterator()->getArrayCopy(),$baslangic,5);
            return view('backend.pages.anasayfa')->with('yazilar' ,$posts);
        }

    }

routes/web.php:

Route::get('/{page}', 'HomeController@deneme');
</code>```

View :

```<code><ul class="pager">
                    <li class="next">
                        <a href="{{url()->full()}}">Older Post →</a>
                    </li>
                </ul>
</code>```

答:
Use Pagination

Controller

```<code>$users = DB::table('users')->paginate(15);
</code>```

View

```<code>{{ $users->links() }}
</code>```

for More Details https://laravel.com/docs/5.2/pagination

Title: Laravel 5 next and previous paging

Body:
Hello I have a list of max 5 articles in my homepage but I have many more articles and I would like to show these articles in other pages. So when I see more old posts, I would like to do a pagination like user home page / 1 when I get it as a result of posting it as url. But I do not follow the correct paths when I make directions.
I need to change the following lines of code to help you change the point, good day, good day
app/Http/Controller/HomeController:

public function deneme($page){
        $url = url()->full();
        $myUrl = explode('/', $url);
        $uz= sizeof($myUrl);
        $myUrl = $myUrl[$uz-1];
        if ($myUrl == 'work.com'){
            $yazilar = YaziModel::join('users as u','u.id','=', 'yazilar.kullaniciid')->select('yazilar.*','u.name','u.created_at')->orderBy('yazilar.id', 'DESC')->get();

            $posts = array_slice($yazilar->getIterator()->getArrayCopy(),0,5);
            return view('backend.pages.anasayfa')->with('yazilar', $posts);
        }else{
            $baslangic = $page*5;
            $yazilar = YaziModel::join('users as u','u.id','=', 'yazilar.kullaniciid')->select('yazilar.*','u.name','u.created_at')->orderBy('yazilar.id', 'DESC')->get();

            $posts = array_slice($yazilar->getIterator()->getArrayCopy(),$baslangic,5);
            return view('backend.pages.anasayfa')->with('yazilar' ,$posts);
        }

    }

routes/web.php:

Route::get('/{page}', 'HomeController@deneme');

View :

                        full()}}">Older Post →

Body:
Use Pagination

Controller

$users = DB::table('users')->paginate(15);

View

{{ $users->links() }}

for More Details https://laravel.com/docs/5.2/pagination


问:
AjaxFileUpload adding OnClientUploadCompleteAll breaks layout
I have the following:

```<code><ajaxToolkit:AjaxFileUpload ID="afuPhotosUpload" runat="server"
    AllowedFileTypes="jpg,jpeg,png,gif"
    OnUploadComplete="afuPhotosUpload_UploadComplete" />
</code>```

This works completely fine but as soon as I add OnClientUploadCompleteAll like this:

```<code><ajaxToolkit:AjaxFileUpload ID="afuPhotosUpload" runat="server"
    AllowedFileTypes="jpg,jpeg,png,gif"
    OnUploadComplete="afuPhotosUpload_UploadComplete"
    OnClientUploadCompleteAll='__doPostBack("HiddenButton", "");' />
</code>```

The layout of the the control freaks out and becomes almost unusable.  Can anyone see what I'm doing wrong?

答:
You need to pass it a javascript function name only.

```<code>OnClientUploadCompleteAll="UploadCompleteFunctionName"
</code>```

For whatever reason, they decided to treat it in same way as declaring the server-side function to execute.

Body:
I have the following:

<ajaxToolkit:AjaxFileUpload ID="afuPhotosUpload" runat="server"
    AllowedFileTypes="jpg,jpeg,png,gif"
    OnUploadComplete="afuPhotosUpload_UploadComplete" />

This works completely fine but as soon as I add OnClientUploadCompleteAll like this:

<ajaxToolkit:AjaxFileUpload ID="afuPhotosUpload" runat="server"
    AllowedFileTypes="jpg,jpeg,png,gif"
    OnUploadComplete="afuPhotosUpload_UploadComplete"
    OnClientUploadCompleteAll='__doPostBack("HiddenButton", "");' />

The layout of the the control freaks out and becomes almost unusable.  Can anyone see what I'm doing wrong?

Body:
You need to pass it a javascript function name only.

OnClientUploadCompleteAll="UploadCompleteFunctionName"

For whatever reason, they decided to treat it in same way as declaring the server-side function to execute.


问:
Dealing with a 3rd party library who's function call causes heap corruptions when P/Invoking
I have created a library wrapper which invokes FlexNet Publisher. It is written in C. I am trying to P/Invoke it:

```<code>[DllImport("lmgr11.dll")]
public static extern void free_job();
</code>```

Its implementation is fairly simple:

```<code>void WINAPI free_job()
{
    if (jobPtr != NULL)
        lc_free_job(jobPtr);
    jobPtr = NULL;
}
</code>```

The documentation says that lc_free_job should free a job as well as all resources. Calling lc_free_job works just fine from native code (I made an ATL object expose a wrapper to it through a COM object and I can consume this method all day long from a Visual C++ console application, so I know it must work).

However, from C#, when I try to P/Invoke this method, I get the following error which crashes my application:

Unhandled exception at 0x00007FFA39358283 (ntdll.dll) in
  CerberusTestHarness.exe: 0xC0000374: A heap has been corrupted
  (parameters: 0x00007FFA393AF6B0).

Why is this? Can I catch it or circumvent it in any way? I can't seem to catch the exception if I wrap the call in a try-catch because its not throwing a .NET exception. Note that I don't have the source code for lc_free_job so I can't inspect it or view its source code, unfortunately. Its written in C.

答:
The issue was due to my C# P/Invoke code from a previous invocation. Hopefully this helps anyone else who comes across the same issue.

I had defined this P/Invoke to get an error string back from a function which returns char *:

```<code>[DllImport("lmgr11.dll")]
public static extern string errstring();
</code>```

I was calling it every time something failed in my 3rd party library as above. This is not the correct way to P/Invoke a method which returns char *. Otherwise, when freeing the error from the native side, it will cause a heap corruption due to the way this string was marshaled.

It needed to be defined like this:

```<code>[DllImport("lmgr11.dll")]
public static extern IntPtr errstring();
</code>```

And called as follows:

```<code>var errorMessage = Marshal.PtrToStringAnsi(errstring());
</code>```

Body:
I have created a library wrapper which invokes FlexNet Publisher. It is written in C. I am trying to P/Invoke it:

[DllImport("lmgr11.dll")]
public static extern void free_job();

Its implementation is fairly simple:

void WINAPI free_job()
{
    if (jobPtr != NULL)
        lc_free_job(jobPtr);
    jobPtr = NULL;
}

The documentation says that lc_free_job should free a job as well as all resources. Calling lc_free_job works just fine from native code (I made an ATL object expose a wrapper to it through a COM object and I can consume this method all day long from a Visual C++ console application, so I know it must work).

However, from C#, when I try to P/Invoke this method, I get the following error which crashes my application:

Unhandled exception at 0x00007FFA39358283 (ntdll.dll) in
  CerberusTestHarness.exe: 0xC0000374: A heap has been corrupted
  (parameters: 0x00007FFA393AF6B0).

Why is this? Can I catch it or circumvent it in any way? I can't seem to catch the exception if I wrap the call in a try-catch because its not throwing a .NET exception. Note that I don't have the source code for lc_free_job so I can't inspect it or view its source code, unfortunately. Its written in C.

Body:
The issue was due to my C# P/Invoke code from a previous invocation. Hopefully this helps anyone else who comes across the same issue.

I had defined this P/Invoke to get an error string back from a function which returns char *:

[DllImport("lmgr11.dll")]
public static extern string errstring();

I was calling it every time something failed in my 3rd party library as above. This is not the correct way to P/Invoke a method which returns char *. Otherwise, when freeing the error from the native side, it will cause a heap corruption due to the way this string was marshaled.

It needed to be defined like this:

[DllImport("lmgr11.dll")]
public static extern IntPtr errstring();

And called as follows:

var errorMessage = Marshal.PtrToStringAnsi(errstring());


问:
Moving Java (Spring, Hibernate, MySql) project from Windows to Debian
I am writing project on Windows (IntelliJIdea), and all OK. It compiles, and runs. But when I try to run on Debian(GNU/Linux 5.0), I have

 SEVERE: Access denied for user 'root'@'localhost' (using password: YES)

     [java] 30.11.2010 15:39:04 org.hibernate.cfg.SettingsFactory buildSettings

     [java] WARNING: Could not obtain connection to query metadata

     [java] java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

     [java]     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1075)

     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)

     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)

     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:919)

I use such Spring config:

```<code><bean id="mySqlDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://127.0.0.1:3306/mydb"/>
    <property name="username" value="mydb"/>
    <property name="password" value="Fallout_3"/>
</bean>

<bean id="mySqlSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="mySqlDataSource"/>

    <property name="mappingResources">
        <list>
            <value>entities/ClientPrices.hbm.xml</value>
            <value>entities/User.hbm.xml</value>
            <value>entities/Provider.hbm.xml</value>
            <value>entities/MessageQueue.hbm.xml</value>
            <value> hibernate/SimpleEntity.hbm.xml</value>
        </list>
    </property>

    <property name="hibernateProperties">
        <value>
            hibernate.dialect=org.hibernate.dialect.MySQLDialect
            hibernate.show_sql=true
            hibernate.hbm2ddl.auto=create
            hibernate.current_session_context_class=thread
        </value>
    </property>

</bean>
</code>```

答:
You need to add permission to root for localhost in your mysql server

execute :

```<code>GRANT ALL ON *.* TO 'root'@'localhost';
</code>```

on your mysql console.

Resource

Body:
I am writing project on Windows (IntelliJIdea), and all OK. It compiles, and runs. But when I try to run on Debian(GNU/Linux 5.0), I have

 SEVERE: Access denied for user 'root'@'localhost' (using password: YES)

     [java] 30.11.2010 15:39:04 org.hibernate.cfg.SettingsFactory buildSettings

     [java] WARNING: Could not obtain connection to query metadata

     [java] java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

     [java]     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1075)

     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)

     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)

     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:919)

I use such Spring config:

<bean id="mySqlDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://127.0.0.1:3306/mydb"/>
    <property name="username" value="mydb"/>
    <property name="password" value="Fallout_3"/>
</bean>

<bean id="mySqlSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="mySqlDataSource"/>

    <property name="mappingResources">
        <list>
            <value>entities/ClientPrices.hbm.xml</value>
            <value>entities/User.hbm.xml</value>
            <value>entities/Provider.hbm.xml</value>
            <value>entities/MessageQueue.hbm.xml</value>
            <value> hibernate/SimpleEntity.hbm.xml</value>
        </list>
    </property>

    <property name="hibernateProperties">
        <value>
            hibernate.dialect=org.hibernate.dialect.MySQLDialect
            hibernate.show_sql=true
            hibernate.hbm2ddl.auto=create
            hibernate.current_session_context_class=thread
        </value>
    </property>

</bean>

Body:
You need to add permission to root for localhost in your mysql server

execute :

GRANT ALL ON *.* TO 'root'@'localhost';

on your mysql console.

Resource


问:
How to create a new column in a dataframe whose values represent the ranges that values from a certain column fall into?
I have read a .csv file to create a dict that, for each given sequence, contains names as keys and a list with one DNA sequence and one fluorescence measurement as values. After these sequences are processed for a while by a variety of other functions, I will be making a new dataframe that contains the fluorescence values and other various values that are the products of the said functions.

I now want to create a new column that basically "sorts" each each row into a class that represents the range in which the fluorescence measurement falls in. For example, if a certain DNA sequence is associated with a fluorescence measurement of 240, it should fall into the class labeled "200-300", or "100-400". As I have not yet decided what sizes my ranges should be set to, just assume that I will have three classes (for the sake of simplicity): "<100", "100-200", and ">200".

I have the following code that works fine for making a new dataframe with the new values, but I don't know how to set it up in order to make add the "class" in which the respective fluorescence measurements fall in.

```<code>def data_assembler(folder_contents):
    df= DataFrame(columns= ['Column1','Column2','Column3])
    for candidate in folder_contents.keys()[:50]:
        fluorescence= folder_contents[candidate][0]
        score0= fluorescence
        if score0 < 100:
             class1= str("<100")
        elif score0>100 and score0<200:
             class2= str("100-200")
        elif score0>200:
             class3= str(">200")
        score1= calculate_complex_mfe(folder_contents[candidate][1])
        score2= calculate_complex_ensemble_defect(folder_contents[candidate][1])
        score3= calculate_GC_content(folder_contents[candidate][1])
    ###note: the following line is not correct because I'm not sure how to add the class to the particular cell
    df.loc[candidate]= [class1 or class2 or class3 or score0, score1, score2, score3]
    df= df.sort(['score3'], ascending=False)
df.to_csv(path.join(output, "DNAScoring.csv"))
</code>```

How can I ameliorate my code in order for it to ultimately have a dataframe that would look something like this:

答:
I think you need cut:

```<code>df = pd.DataFrame({'Fluorescence':[0,100,200,300]})
bins = [-np.inf, 99, 200, np.inf]
labels=['<100','100-200','>200']
df['Class'] = pd.cut(df['Fluorescence'], bins=bins, labels=labels)
print (df)
   Fluorescence    Class
0             0     <100
1           100  100-200
2           200  100-200
3           300     >200
</code>```

Body:
I have read a .csv file to create a dict that, for each given sequence, contains names as keys and a list with one DNA sequence and one fluorescence measurement as values. After these sequences are processed for a while by a variety of other functions, I will be making a new dataframe that contains the fluorescence values and other various values that are the products of the said functions.

I now want to create a new column that basically "sorts" each each row into a class that represents the range in which the fluorescence measurement falls in. For example, if a certain DNA sequence is associated with a fluorescence measurement of 240, it should fall into the class labeled "200-300", or "100-400". As I have not yet decided what sizes my ranges should be set to, just assume that I will have three classes (for the sake of simplicity): "<100", "100-200", and ">200".

I have the following code that works fine for making a new dataframe with the new values, but I don't know how to set it up in order to make add the "class" in which the respective fluorescence measurements fall in.

def data_assembler(folder_contents):
    df= DataFrame(columns= ['Column1','Column2','Column3])
    for candidate in folder_contents.keys()[:50]:
        fluorescence= folder_contents[candidate][0]
        score0= fluorescence
        if score0 < 100:
             class1= str("<100")
        elif score0>100 and score0<200:
             class2= str("100-200")
        elif score0>200:
             class3= str(">200")
        score1= calculate_complex_mfe(folder_contents[candidate][1])
        score2= calculate_complex_ensemble_defect(folder_contents[candidate][1])
        score3= calculate_GC_content(folder_contents[candidate][1])
    ###note: the following line is not correct because I'm not sure how to add the class to the particular cell
    df.loc[candidate]= [class1 or class2 or class3 or score0, score1, score2, score3]
    df= df.sort(['score3'], ascending=False)
df.to_csv(path.join(output, "DNAScoring.csv"))

How can I ameliorate my code in order for it to ultimately have a dataframe that would look something like this:

Body:
I think you need cut:

df = pd.DataFrame({'Fluorescence':[0,100,200,300]})
bins = [-np.inf, 99, 200, np.inf]
labels=['<100','100-200','>200']
df['Class'] = pd.cut(df['Fluorescence'], bins=bins, labels=labels)
print (df)
   Fluorescence    Class
0             0     <100
1           100  100-200
2           200  100-200
3           300     >200