问:
Pause HTML Video on exiting a tab
I have a section with tabs. Two tabs have a video.

Only problem is, which I can't figure out, when I click to play video it plays (that is good) but when I go to the next tab the initial video will still be playing - what I want is the video to pause when I exit each tab.

I've tried playing about with functions but just can't get it working.

Thanks!

$('ul.tabs li').click(function() {
    var tab_id = $(this).data('tab');

    $('ul.tabs li').removeClass('current');
    $('.tab-content').removeClass('current');

    $(this).addClass('current');
    $(this).parent().parent().parent().children("#"+tab_id).addClass('current');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>section {
 background: #fff;
}

ul.tabs {
 margin: 0;
 padding: 0;
 list-style: none;
  background: #ccc;
}

.tab-link {
 background: none;
 color: #fff;
 display: inline-block;
 padding: 10px;
 cursor: pointer;
 font-size: 16px;
}

.tabs .tab-link.current {
 background: #ccc;
}

.tab-content {
 display: none;
 background: #ccc;
}

.tab-content.current {
 display: block;
}

video {
 width: 100%;
 height: 400px;
}</code>```

        One

        Two

    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>

    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>

```

答:
You can simply loop through each video and pause it inside of your function.

Credit: How can I pause ALL videos (html5) at once?

$('ul.tabs li').click(function() {
 $('video').each(function() {
  $(this).get(0).pause();
 });
 var tab = $(this).data('tab');

 $('ul.tabs li').removeClass('current');
 $('.tab-content').removeClass('current');

 $(this).addClass('current');
 $(this).parent().parent().parent().children("#"+tab).addClass('current');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>section {
 background: #fff;
}

ul.tabs {
 margin: 0;
 padding: 0;
 list-style: none;
  background: #ccc;
}

.tab-link {
 background: none;
 color: #fff;
 display: inline-block;
 padding: 10px;
 cursor: pointer;
 font-size: 16px;
}

.tabs .tab-link.current {
 background: #ccc;
}

.tab-content {
 display: none;
 background: #ccc;
}

.tab-content.current {
 display: block;
}

video {
 width: 100%;
 height: 400px;
}</code>```

     One

     Two

   <video controls>
     <source type="video/mp4"
        src="http://techslides.com/demos/sample-videos/small.mp4">
   </video>

   <video controls>
     <source type="video/mp4"
        src="http://techslides.com/demos/sample-videos/small.mp4">
   </video>

```

Title: Pause HTML Video on exiting a tab

Body:
I have a section with tabs. Two tabs have a video.

Only problem is, which I can't figure out, when I click to play video it plays (that is good) but when I go to the next tab the initial video will still be playing - what I want is the video to pause when I exit each tab.

I've tried playing about with functions but just can't get it working.

Thanks!

$('ul.tabs li').click(function() {
    var tab_id = $(this).data('tab');

    $('ul.tabs li').removeClass('current');
    $('.tab-content').removeClass('current');

    $(this).addClass('current');
    $(this).parent().parent().parent().children("#"+tab_id).addClass('current');
});

section {
 background: #fff;
}

ul.tabs {
 margin: 0;
 padding: 0;
 list-style: none;
  background: #ccc;
}

.tab-link {
 background: none;
 color: #fff;
 display: inline-block;
 padding: 10px;
 cursor: pointer;
 font-size: 16px;
}

.tabs .tab-link.current {
 background: #ccc;
}

.tab-content {
 display: none;
 background: #ccc;
}

.tab-content.current {
 display: block;
}

video {
 width: 100%;
 height: 400px;
}

        One

        Two

    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>

    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>

Body:
You can simply loop through each video and pause it inside of your function.

Credit: How can I pause ALL videos (html5) at once?

$('ul.tabs li').click(function() {
 $('video').each(function() {
  $(this).get(0).pause();
 });
 var tab = $(this).data('tab');

 $('ul.tabs li').removeClass('current');
 $('.tab-content').removeClass('current');

 $(this).addClass('current');
 $(this).parent().parent().parent().children("#"+tab).addClass('current');
});

section {
 background: #fff;
}

ul.tabs {
 margin: 0;
 padding: 0;
 list-style: none;
  background: #ccc;
}

.tab-link {
 background: none;
 color: #fff;
 display: inline-block;
 padding: 10px;
 cursor: pointer;
 font-size: 16px;
}

.tabs .tab-link.current {
 background: #ccc;
}

.tab-content {
 display: none;
 background: #ccc;
}

.tab-content.current {
 display: block;
}

video {
 width: 100%;
 height: 400px;
}

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

<section>

  <nav>
   <ul class="tabs">
    <li class="tab-link current" data-tab="first">
     <a href="#tab-1">One</a>
    </li>
    <li class="tab-link" data-tab="sec">
     <a href="#tab-2">Two</a>
    </li>
   </ul>
  </nav>

  <div id="first" class="tab-content current">
   <video controls>
     <source type="video/mp4"
        src="http://techslides.com/demos/sample-videos/small.mp4">
   </video>
  </div>
  <div id="sec" class="tab-content">
   <video controls>
     <source type="video/mp4"
        src="http://techslides.com/demos/sample-videos/small.mp4">
   </video>
  </div>

</section>


来源: stackexchange

问:
How to get associated changesets from build in TFS 2017?
With c#, I was previously able to get associated changesets from TFS 2012 during a XAML build process using InformationNodeConverters.GetAssociatedChangesets(IBuildDetail).  I got the IBuildDetail from CodeActivityContext.GetExtension<IBuildDetail>().

Now that I'm using the TFS 2017 build processes, I am trying to do something similar with the code below, but it is not returning changesets.

```<code>var teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://ourtfsserver:8080/tfs/DefaultCollection"));
var versionControlServer = teamProjectCollection.GetService<VersionControlServer>();
var buildServer = teamProjectCollection.GetService<IBuildServer>();
var build = buildServer.GetBuild(new Uri(string.Format("vstfs:///Build/Build/{0}", "3807")));
var changeSets = InformationNodeConverters.GetAssociatedChangesets(build);
</code>```

All of the above seems to work, and a build is returned successfully, but changeSets.Count() is 0, when in fact there should be some changesets returned.

Is there a suggested change to the code above, or an alternate way to do this?  Or does this just no longer work in TFS 2017?

答:
Microsoft is updating TFS to use a REST API.  I think this REST API call will get you want you want.

Here's a link to the .NET client libraries for making the REST calls.

Also, if you're not already aware, Microsoft is deprecating XAML builds.  See this blog post for more information.

ContentLicense: CC BY-SA 3.0

Body:
With c#, I was previously able to get associated changesets from TFS 2012 during a XAML build process using InformationNodeConverters.GetAssociatedChangesets(IBuildDetail).  I got the IBuildDetail from CodeActivityContext.GetExtension<IBuildDetail>().

Now that I'm using the TFS 2017 build processes, I am trying to do something similar with the code below, but it is not returning changesets.

var teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://ourtfsserver:8080/tfs/DefaultCollection"));
var versionControlServer = teamProjectCollection.GetService<VersionControlServer>();
var buildServer = teamProjectCollection.GetService<IBuildServer>();
var build = buildServer.GetBuild(new Uri(string.Format("vstfs:///Build/Build/{0}", "3807")));
var changeSets = InformationNodeConverters.GetAssociatedChangesets(build);

All of the above seems to work, and a build is returned successfully, but changeSets.Count() is 0, when in fact there should be some changesets returned.

Is there a suggested change to the code above, or an alternate way to do this?  Or does this just no longer work in TFS 2017?


问:
indexpath of cells in grouped tableview
i have a table view, split into alphabetical sections, populated from array that has been filtered

how can i track the "true" indexpath of cells in a grouped tableview.
instead of the count starting at 0 for each section.

i need to get this so i can access the right bit of data from an array

at the moment it works like this(just in case im not clear)

(section 0)
row 0
row 1
row 2
(section 1)
row 0
row 1
etc...........

i need to get it so i can get

section 0)
row 0
row 1
row 2
(section 1)
row 3
row 4

thanks in advance

答:
Try this:

```<code>- (NSUInteger)indexFromIndexPath:(NSIndexPath*)indexPath
{
    NSUInteger index=0;
    for( int i=0; i<indexPath.section; i++ )
        index += [self tableView:self.tableView numberOfRowsInSection:i];

    index += indexPath.row;

    return index;
}
</code>```

It assumes that this method is placed in a UITableViewController class.
You can use it like this:

```<code>NSUInterger realIndex = [self indexFromIndexPath:indexPath];
id myObject = [dataArray objectAtIndex:realIndex];
</code>```

ContentLicense: CC BY-SA 2.5

Title: indexpath of cells in grouped tableview

Body:
Try this:

- (NSUInteger)indexFromIndexPath:(NSIndexPath*)indexPath
{
    NSUInteger index=0;
    for( int i=0; i<indexPath.section; i++ )
        index += [self tableView:self.tableView numberOfRowsInSection:i];

    index += indexPath.row;

    return index;
}

It assumes that this method is placed in a UITableViewController class.
You can use it like this:

NSUInterger realIndex = [self indexFromIndexPath:indexPath];
id myObject = [dataArray objectAtIndex:realIndex];


问:
Stack menu with content (content to the right on large screens)
Taking into consideration the position of the content div (up middle), how can I achieve stacking the divs like this?

Is there a way to do it with pure css or do I have to use jquery and move the div content out when on larger screens?

答:
Should be able to add a float:right to the content and float left to the menu when the screen width hits a certain size and it would make them stack side by side.

@media (min-width: 992px) {
  .menu{
    float:left;
  }
  .content{
    float:right;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<body>
  <div class="container-fluid">
    <div class="col-xs-12 col-md-4 menu">
      Menu 1
    </div>
    <div class="col-xs-12 col-md-6 content">
      Content
      Content
    </div>
    <div class="col-xs-12 col-md-4 menu">
      Menu 2
    </div>
  </div>
</body></code>```

Body:
Should be able to add a float:right to the content and float left to the menu when the screen width hits a certain size and it would make them stack side by side.

@media (min-width: 992px) {
  .menu{
    float:left;
  }
  .content{
    float:right;
  }
}

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<body>
  <div class="container-fluid">
    <div class="col-xs-12 col-md-4 menu">
      Menu 1
    </div>
    <div class="col-xs-12 col-md-6 content">
      Content
      Content
    </div>
    <div class="col-xs-12 col-md-4 menu">
      Menu 2
    </div>
  </div>
</body>


问:
Selenium: Open Firefox with default profile using java code
I'm using Selenium in java code to open a web application in Firefox.  But I faced a problem with Firefox profile because when I run the code,  Firefox window openned using new profile,  so the web application couldn't be opened since the proxy settings are different (I should add the IP address into Firefox no proxy IPs).  I tried get the default profile from my code,  but nothing changed.  I also tried to create new profile but I don't know how to add the IP to it.
I changed the code so I can open the Firefox manually and then Selenium opens the application in nee tab,  so the IP will be there. But this also failed and the code still opens new window.
I'll be very thankful if anyone can help. </p>

答:
Since you have to use GeckoDriver to use latest firefox so you can setup proxy in firefox for geckodriver using this.</p>

```<code>String PROXY = "localhost";
int PORT = 8080;

JSONObject json = new JsonObject();
json.addProperty("proxyType", "MANUAL");
json.addProperty("httpProxy", PROXY);
json.addProperty("httpProxyPort", PORT);
json.addProperty("sslProxy", PROXY);
json.addProperty("sslProxyPort", PORT);

DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("proxy", json);

GeckoDriverService service =new GeckoDriverService.Builder(firefoxBinary)
  .usingDriverExecutable(new File("path to geckodriver"))
  .usingAnyFreePort()
  .usingAnyFreePort()
  .build();
service.start();

// GeckoDriver currently needs the Proxy set in RequiredCapabilities
driver = new FirefoxDriver(service, cap, cap);
</code>```

Body:
Since you have to use GeckoDriver to use latest firefox so you can setup proxy in firefox for geckodriver using this.

String PROXY = "localhost";
int PORT = 8080;

JSONObject json = new JsonObject();
json.addProperty("proxyType", "MANUAL");
json.addProperty("httpProxy", PROXY);
json.addProperty("httpProxyPort", PORT);
json.addProperty("sslProxy", PROXY);
json.addProperty("sslProxyPort", PORT);

DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("proxy", json);

GeckoDriverService service =new GeckoDriverService.Builder(firefoxBinary)
  .usingDriverExecutable(new File("path to geckodriver"))
  .usingAnyFreePort()
  .usingAnyFreePort()
  .build();
service.start();

// GeckoDriver currently needs the Proxy set in RequiredCapabilities
driver = new FirefoxDriver(service, cap, cap);


问:
Python: importing from 1+ levels down
Say that I import with the unnecessarily long full path:

```<code>from pandas.core.series import Series
</code>```

The more common import is simply:

```<code>from pandas import Series
</code>```

to which I can view the full path with:

```<code>Series
Out[6]: pandas.core.series.Series
</code>```

Here is the source of my confusion.  Nowhere in the top-level __init__ module is there any import of from core import * (or core.series, for that matter).  The __init__ module for .core is empty also.

What enables me to be able to use simply from pandas import Series rather than the full path or, more generally, to import a module, function, variable, or class that is "several levels down"?

答:
You have inside the __init__.py file:

```<code>from pandas.core.api import *
</code>```

in which Series is imported.

Title: Python: importing from 1+ levels down

Body:
Say that I import with the unnecessarily long full path:

from pandas.core.series import Series

The more common import is simply:

from pandas import Series

to which I can view the full path with:

Series
Out[6]: pandas.core.series.Series

Here is the source of my confusion.  Nowhere in the top-level __init__ module is there any import of from core import * (or core.series, for that matter).  The __init__ module for .core is empty also.

What enables me to be able to use simply from pandas import Series rather than the full path or, more generally, to import a module, function, variable, or class that is "several levels down"?

Body:
You have inside the __init__.py file:

from pandas.core.api import *

in which Series is imported.


问:
How to early break reduce() method?
How can I break the iteration of reduce() method?

for:

```<code>for (var i = Things.length - 1; i >= 0; i--) {
  if(Things[i] <= 0){
    break;
  }
};
</code>```

reduce()

```<code>Things.reduce(function(memo, current){
  if(current <= 0){
    //break ???
    //return; <-- this will return undefined to memo, which is not what I want
  }
}, 0)
</code>```

答:
Array.every can provide a very natural mechanism for breaking out of high order iteration.

const product = function(array) {
    let accumulator = 1;
    array.every( factor => {
        accumulator *= factor;
        return !!factor;
    });
    return accumulator;
}
console.log(product([2,2,2,0,2,2]));
// 0```

ContentLicense: CC BY-SA 4.0

Title: How to early break reduce() method?

Body:
How can I break the iteration of reduce() method?

for:

for (var i = Things.length - 1; i >= 0; i--) {
  if(Things[i] <= 0){
    break;
  }
};

reduce()

Things.reduce(function(memo, current){
  if(current <= 0){
    //break ???
    //return; <-- this will return undefined to memo, which is not what I want
  }
}, 0)


问:
Xcode 7 and Swift 2.0 Refractoring possible?
I'm planning to upgrade my code to swift 2.0 and to use Xcode 7 in the near future. At the moment my app is still dependen on some frameworks that do not work with Swift2.0 yet.

Hast refractoring become possible with Xcode 7 or will it become possible?

At the moment (Xcode 6.4) it only works for Obj-C. If it is not planned for Xcode 7 I might as well do it in the current version by myself.

答:
From XCode 9, Swift refactoring is possible. Announced in WWDC 2017.

Refactoring. Refactoring built right into the editing experience and works across Swift, Objective-C, Interface Builder, and many other file types.

For more refer this


问:
Does <s:button> support reRender with <a4j:support>
SSIA

Can I use <s:button> with ?

I can't seem to make it work.

```<code><h:panelGroup id="pwgen">
    <s:decorate template="/layout/definition.xhtml" rendered="#{s:hasRole('sysadmin')}">
        <ui:define name="label">#{messages['manualOnetimePassword']}</ui:define>
        <s:button  value="#{messages['generate']}" propagation="join" action="#{userAdmin.generateManualPasswordForUser()}">
            <a:support event="onsubmit" reRender="pwgen" ajaxSingle="true" />
        </s:button>
        <h:inputText size="30" required="false" value="#{userAdmin.existingUser.manualPassword.password}"/>
    </s:decorate>
</h:panelGroup>
</code>```

I have tried  and  and also event="oncomplete" but it always reloads the entire page.

答:
I found the answer.

It doesn't seem that <s:button> supports .

All I did basically is changed the button to be  and removing the

Body:
SSIA

Can I use <s:button> with ?

I can't seem to make it work.

<h:panelGroup id="pwgen">
    <s:decorate template="/layout/definition.xhtml" rendered="#{s:hasRole('sysadmin')}">
        <ui:define name="label">#{messages['manualOnetimePassword']}</ui:define>
        <s:button  value="#{messages['generate']}" propagation="join" action="#{userAdmin.generateManualPasswordForUser()}">

        </s:button>
        <h:inputText size="30" required="false" value="#{userAdmin.existingUser.manualPassword.password}"/>
    </s:decorate>
</h:panelGroup>

I have tried  and  and also event="oncomplete" but it always reloads the entire page.

Body:
I found the answer.

It doesn't seem that <s:button> supports <a:support>.

All I did basically is changed the button to be <a:commandButton reRender="foo"> and removing the <a:support>


问:
z-index not working between image and text box
JSFiddle

I have an image with a text box below. I scaled the image, and it goes over the text box, i wan't the text box to be on top of the image, but it is not working with z-index.

HTML:

```<code><a href="#">
  <img src="http://images.meredith.com/content/dam/bhg/Images/2009/07/101422234.jpg.rendition.200sq.jpg" />
  <div class="text">
    This is some text.
  </div>
</a>
</code>```

CSS:

```<code>a {
  height:400px;
  width:200px;
  display:block;
  text-decoration:none;
  color:black;
  overflow:hidden;
}

img {
  transform: scale(1.1);
}

a:hover .text {
  color:white;
  background-color:black;
}

.text {
  text-align:center;
  height:200px;
  margin-top:-4px;
  background-color:white;
  transition:all 1s ease;
}
</code>```

答:
try   z-index with position:absolute;

.text {
  text-align:center;
  height:200px;
  margin-top:-4px;
  background-color:white;
  transition:all 1s ease;
  position:absolute;
  bottom:0px;
  z-index:99;
}

a {
  height:400px;
  width:200px;
  display:block;
  text-decoration:none;
  color:black;
  overflow:hidden;
  position:relative;
}

img {
 // transform: scale(1.1);
}

a:hover .text {
  color:white;
  background-color:black;
}

.text {
  text-align:center;
  height:200px;
  margin-top:-4px;
  background-color:white;
  transition:all 1s ease;
  position:absolute;
  bottom:0px;
  z-index:99;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  <img src="http://images.meredith.com/content/dam/bhg/Images/2009/07/101422234.jpg.rendition.200sq.jpg" />
  <div class="text">
    This is some text.
  </div>
</code>```

Body:
JSFiddle

I have an image with a text box below. I scaled the image, and it goes over the text box, i wan't the text box to be on top of the image, but it is not working with z-index.

HTML:

    This is some text.

CSS:

a {
  height:400px;
  width:200px;
  display:block;
  text-decoration:none;
  color:black;
  overflow:hidden;
}

img {
  transform: scale(1.1);
}

a:hover .text {
  color:white;
  background-color:black;
}

.text {
  text-align:center;
  height:200px;
  margin-top:-4px;
  background-color:white;
  transition:all 1s ease;
}

Body:
try   z-index with position:absolute;

.text {
  text-align:center;
  height:200px;
  margin-top:-4px;
  background-color:white;
  transition:all 1s ease;
  position:absolute;
  bottom:0px;
  z-index:99;
}

a {
  height:400px;
  width:200px;
  display:block;
  text-decoration:none;
  color:black;
  overflow:hidden;
  position:relative;
}

img {
 // transform: scale(1.1);
}

a:hover .text {
  color:white;
  background-color:black;
}

.text {
  text-align:center;
  height:200px;
  margin-top:-4px;
  background-color:white;
  transition:all 1s ease;
  position:absolute;
  bottom:0px;
  z-index:99;
}

<a href="#">
  <img src="http://images.meredith.com/content/dam/bhg/Images/2009/07/101422234.jpg.rendition.200sq.jpg" />
  <div class="text">
    This is some text.
  </div>
</a>


问:
cohort analysis in R
I have a dataset test of user ids and the quarter in which user ids made a transaction:

```<code>> test
   id quarter
1   7      Q1
2   7      Q1
3   5      Q1
4   8      Q1
5   3      Q1
6   6      Q1
7  10      Q1
8   3      Q2
9  10      Q2
10  8      Q2
11  2      Q2
12  7      Q2
13  6      Q2
14  6      Q3
15  9      Q3
16  6      Q3
17  4      Q3
18  9      Q3
19  2      Q3
20  5      Q4
21  8      Q4
22 10      Q4
23  7      Q4
24  1      Q4
25  8      Q4
</code>```

My objective is to find the number of unique users that were active in Quarter 1 and, of those users, get the number of users that made transactions in subsequent quarters.

The output from the above sample should be:

```<code>> output
  quarter unique_cohort_ids
1      Q1                 6
2      Q2                 5
3      Q3                 1
4      Q4                 4
</code>```

The following code works, but it is verbose and repetitive, and is not ideal for a larger dataset with dozens of quarters.  Any suggestions on how to improve it would be appreciated:

```<code>subsets <-split(test, test$quarter, drop=TRUE)

for (i in 1:length(subsets)) {
  assign(paste0("Q", i), as.data.frame(subsets[[i]]))
}

Q1_ids <- sum(uniqueQ1$id)
Q2_ids <- sum(unique(Q1$id) %in% unique(Q2$id))
Q3_ids <- sum(unique(Q1$id) %in% unique(Q3$id))
Q4_ids <- sum(unique(Q1$id) %in% unique(Q4$id))
</code>```

Cohort analysis also includes counting the number of new users
per quarter.  As opposed to manually counting the unique user ids that appear per quarter that had not appeared in any previous quarters, I am seeking a programmatic solution.  In this case, the output would be the following list:

```<code>> mylist
[[1]]
[1]  7  5  8  3  6 10

[[2]]
[1] 2

[[3]]
[1] 9 4

[[4]]
[1] 1
</code>```

Any suggestions would be appreciated

Here is the sample data:

```<code>> dput(test)
structure(list(id = c(7, 7, 5, 8, 3, 6, 10, 3, 10, 8, 2, 7, 6,
6, 9, 6, 4, 9, 2, 5, 8, 10, 7, 1, 8), quarter = c("Q1", "Q1",
"Q1", "Q1", "Q1", "Q1", "Q1", "Q2", "Q2", "Q2", "Q2", "Q2", "Q2",
"Q3", "Q3", "Q3", "Q3", "Q3", "Q3", "Q4", "Q4", "Q4", "Q4", "Q4",
"Q4")), .Names = c("id", "quarter"), row.names = c(NA, -25L), class = "data.frame")
</code>```

答:
For the unique cohort counts per quarter:

```<code>q1_ids <- test[test$quarter == 'Q1', 'id']
test_from_q1 <- test[test$id %in% q1_ids, ]
unique_from_q1 <- unique(test_from_q1)
quarter_counts <- table(unique_from_q1$quarter)
output <- as.data.frame(quarter_counts)
names(output) <- c('quarter', 'unique_cohort_ids')
</code>```

For the second part, would a data.frame be acceptable?

```<code>unique_ids <- unique(test$id)
first_appearance <- data.frame(
  id = unique_ids,
  quarter = test$quarter[match(unique_ids, test$id)]
)
</code>```

If not, then a tapply can list-ify it:

```<code>tapply(
    first_appearance$id,
    first_appearance$quarter,
    'identity',
    simplify = FALSE
)
</code>```

Title: cohort analysis in R

Body:
I have a dataset test of user ids and the quarter in which user ids made a transaction:

> test
   id quarter
1   7      Q1
2   7      Q1
3   5      Q1
4   8      Q1
5   3      Q1
6   6      Q1
7  10      Q1
8   3      Q2
9  10      Q2
10  8      Q2
11  2      Q2
12  7      Q2
13  6      Q2
14  6      Q3
15  9      Q3
16  6      Q3
17  4      Q3
18  9      Q3
19  2      Q3
20  5      Q4
21  8      Q4
22 10      Q4
23  7      Q4
24  1      Q4
25  8      Q4

My objective is to find the number of unique users that were active in Quarter 1 and, of those users, get the number of users that made transactions in subsequent quarters.

The output from the above sample should be:

> output
  quarter unique_cohort_ids
1      Q1                 6
2      Q2                 5
3      Q3                 1
4      Q4                 4

The following code works, but it is verbose and repetitive, and is not ideal for a larger dataset with dozens of quarters.  Any suggestions on how to improve it would be appreciated:

subsets <-split(test, test$quarter, drop=TRUE)

for (i in 1:length(subsets)) {
  assign(paste0("Q", i), as.data.frame(subsets[[i]]))
}

Q1_ids <- sum(uniqueQ1$id)
Q2_ids <- sum(unique(Q1$id) %in% unique(Q2$id))
Q3_ids <- sum(unique(Q1$id) %in% unique(Q3$id))
Q4_ids <- sum(unique(Q1$id) %in% unique(Q4$id))

Cohort analysis also includes counting the number of new users
per quarter.  As opposed to manually counting the unique user ids that appear per quarter that had not appeared in any previous quarters, I am seeking a programmatic solution.  In this case, the output would be the following list:

> mylist
[[1]]
[1]  7  5  8  3  6 10

[[2]]
[1] 2

[[3]]
[1] 9 4

[[4]]
[1] 1

Any suggestions would be appreciated

Here is the sample data:

> dput(test)
structure(list(id = c(7, 7, 5, 8, 3, 6, 10, 3, 10, 8, 2, 7, 6,
6, 9, 6, 4, 9, 2, 5, 8, 10, 7, 1, 8), quarter = c("Q1", "Q1",
"Q1", "Q1", "Q1", "Q1", "Q1", "Q2", "Q2", "Q2", "Q2", "Q2", "Q2",
"Q3", "Q3", "Q3", "Q3", "Q3", "Q3", "Q4", "Q4", "Q4", "Q4", "Q4",
"Q4")), .Names = c("id", "quarter"), row.names = c(NA, -25L), class = "data.frame")

Body:
For the unique cohort counts per quarter:

q1_ids <- test[test$quarter == 'Q1', 'id']
test_from_q1 <- test[test$id %in% q1_ids, ]
unique_from_q1 <- unique(test_from_q1)
quarter_counts <- table(unique_from_q1$quarter)
output <- as.data.frame(quarter_counts)
names(output) <- c('quarter', 'unique_cohort_ids')

For the second part, would a data.frame be acceptable?

unique_ids <- unique(test$id)
first_appearance <- data.frame(
  id = unique_ids,
  quarter = test$quarter[match(unique_ids, test$id)]
)

If not, then a tapply can list-ify it:

tapply(
    first_appearance$id,
    first_appearance$quarter,
    'identity',
    simplify = FALSE
)


问:
How to use a Servlet to call an EJB from same application
I am trying to call a method in an EJB from a servlet that is hosted in the same application.

However the exception I am getting is that my application cannot find the JNDI I am passing in the initialContext.lookup() method, and I have tried many. I think maybe the JBDI is not being declared properly in the XML. Does anyone know how to add the JNDI as a global variable in the weblogic-xml?

Here is the xml files for the ejb-jar and weblogic-ejb-jar

http://imgur.com/a/TcU7S

And here is my servlet:

```<code>AdminServiceLocalHome admin_Home = getAdminHome(); //does jndi lookup to get adminhome

AdminServiceLocal adminLocal  = admin_Home.create(); //creates() ejb

String output =  adminLocal.sendPendingResolutions(); //calls ejb
</code>```

答:
Figured it out. Had to add this line to the xml jar:

```<code><wls:jndi-name>services.Admin</wls:jndi-name>
</code>```

and use the above JNDI

Body:
I am trying to call a method in an EJB from a servlet that is hosted in the same application.

However the exception I am getting is that my application cannot find the JNDI I am passing in the initialContext.lookup() method, and I have tried many. I think maybe the JBDI is not being declared properly in the XML. Does anyone know how to add the JNDI as a global variable in the weblogic-xml?

Here is the xml files for the ejb-jar and weblogic-ejb-jar

http://imgur.com/a/TcU7S

And here is my servlet:

AdminServiceLocalHome admin_Home = getAdminHome(); //does jndi lookup to get adminhome

AdminServiceLocal adminLocal  = admin_Home.create(); //creates() ejb

String output =  adminLocal.sendPendingResolutions(); //calls ejb

Body:
Figured it out. Had to add this line to the xml jar:

<wls:jndi-name>services.Admin</wls:jndi-name>

and use the above JNDI


问:
Why to use Polymorphism?
I have the following code in which I have a parent class and its child. I am trying to determine how the code benefits from using polymorphism.

```<code>class FlyingMachines {
    public void fly() {
        System.out.println("No implementation");
    }
}

class Jet extends FlyingMachines {
    public void fly() {
        System.out.println("Start, Taxi, Fly");
    }

    public void bombardment() {
        System.out.println("Throw Missile");
    }
}

public class PolymorphicTest {
    public static void main(String[] args) {
        FlyingMachines flm = new Jet();
        flm.fly();

        Jet j = new Jet();
        j.bombardment();
        j.fly();
    }
}
</code>```

What is the advantage of polymorphism when both flm.fly() and j.fly() give me the same answer?

答:
Polymorphism (both runtime and compile time) is necessary in Java for quite a few reasons.

Method overriding is a run time polymorphism and overloading is compile time polymorphism.

Few of them are(some of them are already discussed):

Collections: Suppose you have multiple type of flying machines and you want to have them all in a single collection. You can just define a list of type FlyingMachines and add them all.

```<code>List<FlyingMachine> fmList = new ArrayList<>();
fmList.add(new new JetPlaneExtendingFlyingMachine());
fmList.add(new PassengerPlanePlaneExtendingFlyingMachine());
</code>```

The above can be done only by polymorphism. Otherwise you would have to maintain two separate lists.

Caste one type to another : Declare the objects like :

```<code>FlyingMachine fm1 = new JetPlaneExtendingFlyingMachine();
FlyingMachine fm2 = new PassengerPlanePlaneExtendingFlyingMachine();
fm1 = fm2; //can be done
</code>```

Overloading: Not related with the code you gave, But overloading is also another type of polymorphism called compile time polymorphism.

Can have a single method which accepts type FlyingMachine handle all types i.e. subclasses of FlyingMachine. Can only be achieved with Polymorphism.

Title: Why to use Polymorphism?

Body:
I have the following code in which I have a parent class and its child. I am trying to determine how the code benefits from using polymorphism.

class FlyingMachines {
    public void fly() {
        System.out.println("No implementation");
    }
}

class Jet extends FlyingMachines {
    public void fly() {
        System.out.println("Start, Taxi, Fly");
    }

    public void bombardment() {
        System.out.println("Throw Missile");
    }
}

public class PolymorphicTest {
    public static void main(String[] args) {
        FlyingMachines flm = new Jet();
        flm.fly();

        Jet j = new Jet();
        j.bombardment();
        j.fly();
    }
}

What is the advantage of polymorphism when both flm.fly() and j.fly() give me the same answer?

Body:
Polymorphism (both runtime and compile time) is necessary in Java for quite a few reasons.

Method overriding is a run time polymorphism and overloading is compile time polymorphism.

Few of them are(some of them are already discussed):

Collections: Suppose you have multiple type of flying machines and you want to have them all in a single collection. You can just define a list of type FlyingMachines and add them all.

List<FlyingMachine> fmList = new ArrayList<>();
fmList.add(new new JetPlaneExtendingFlyingMachine());
fmList.add(new PassengerPlanePlaneExtendingFlyingMachine());

The above can be done only by polymorphism. Otherwise you would have to maintain two separate lists.

Caste one type to another : Declare the objects like :

FlyingMachine fm1 = new JetPlaneExtendingFlyingMachine();
FlyingMachine fm2 = new PassengerPlanePlaneExtendingFlyingMachine();
fm1 = fm2; //can be done

Overloading: Not related with the code you gave, But overloading is also another type of polymorphism called compile time polymorphism.

Can have a single method which accepts type FlyingMachine handle all types i.e. subclasses of FlyingMachine. Can only be achieved with Polymorphism.


问:
Image Colors Appear Wrong on Chrome/Windows
While testing a design for a site, I took a screenshot with "TinyGrab" and sent it to a friend.

The friend saw something entirely different from myself... On Windows and only with Chrome, the blue in this photo appears purple. On OS X (even with Chrome) or with any other browser, the blues appear just fine.

Can anyone explain what is happening?

This is the image: http://c0848462.cdn.cloudfiles.rackspacecloud.com/fc3572c4aff9588ff9add4e2aad47755.png

答:
Sounds/looks like the colour profile for your monitor or a monitor is being embedded in the file. You could try using something like ImageOptim (MacOSX) as part of its lossless compression removes extraneous data like profiles from images.

Hope that helps.


问:
Can we add error and event handlers before jwplayer player can generate those errors?
The JWPlayer JS API seems unclear about what happens during .setup(). The docs recommend waiting until .setup() is completed and the player is ready. Presumably they mean the ready() event is triggered. What is the proper way to register handlers for setupError, ready and other error events before calling .setup() ?
Does anyone know what JWPlayer does with the file(s) before .setup() completes?</p>

答:
My suggestion would be to chain all of your event handlers to the same setup() call:

```<code>var playerInstance = jwplayer('myVideo');
playerInstance.setup({
    file: 'bunny.mp4',
}).on('ready',function(){
    console.log('ready');
}).on('setupError',function(){
    console.log('setupError')
});
</code>```

What are you trying to do to the file before setup() completes?

As far as what JW Player does with the file, we do not request the file URL until the player starts playback unless you are using one of the preload options as documented at https://developer.jwplayer.com/jw-player/docs/developer-guide/customization/configuration-reference/

Body:
My suggestion would be to chain all of your event handlers to the same setup() call:

var playerInstance = jwplayer('myVideo');
playerInstance.setup({
    file: 'bunny.mp4',
}).on('ready',function(){
    console.log('ready');
}).on('setupError',function(){
    console.log('setupError')
});

What are you trying to do to the file before setup() completes?

As far as what JW Player does with the file, we do not request the file URL until the player starts playback unless you are using one of the preload options as documented at https://developer.jwplayer.com/jw-player/docs/developer-guide/customization/configuration-reference/


问:
Manually encrypt user password in Symfony php
I have a need to manually encrypt the password in the same way Symfony does it.

```<code>$user->setPlainPassword($password);
$userManager->updateUser($user);
</code>```

This is application code that saves the user password. But it is obviously encrypted (not plain as method says).

How can I manually get the same result for given password?

EDIT1:

The problem is that I want to authenticate user manually in users controller code. I have readable username and password that comes as parameters. I want to return 401 if they to not exist in database.

答:
Symfony comes with a useful command to encode a password the same way it does:</p>

```<code>bin/console security:encode-password 'your_plain_password' 'AppBundle\Entity\YourUserClass'
</code>```

Body:
I have a need to manually encrypt the password in the same way Symfony does it.

$user->setPlainPassword($password);
$userManager->updateUser($user);

This is application code that saves the user password. But it is obviously encrypted (not plain as method says).

How can I manually get the same result for given password?

EDIT1:

The problem is that I want to authenticate user manually in users controller code. I have readable username and password that comes as parameters. I want to return 401 if they to not exist in database.

Body:
Symfony comes with a useful command to encode a password the same way it does:

bin/console security:encode-password 'your_plain_password' 'AppBundle\Entity\YourUserClass'


问:
How to apply multiple masks to an array and count occurrences per row
Let's say I have a 2D array with positive integers:

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

and a threshold (positive integer). I want to count, for each row, how many ocurrences are < threshold, how many >= threshold and < threshold+2, and how many >= threshold+2. The results are to be stored on a size 3 x n array, where n = a.shape[0] and each of the 3 columns corresponds to the threshold partition.

For the example above and threshold = 3, it would be:

```<code>b = numpy.array([[3, 0, 0],
                 [2, 0, 1],
                 [1, 1, 1],
                 [0, 3, 0],
                 [0, 2, 1],
                 [0, 1, 2],
                ])
</code>```

My solution was to use a for loop combined with masks, so that I could apply the masks individually for each row. But using for loops on arrays feels wrong. Is there a more optimized way to accomplish that?

My solution so far:

```<code>b = []
for row in a:
    b.append((numpy.sum(row < threshold),
              numpy.sum((row >= threshold) * (row < threshold + 2)),
              numpy.sum(row >= threshold + 2)))
b = numpy.array(b)
</code>```

答:
Approach #1

Making use of elementwise comparison against the thresholds and summing each row -

```<code>t = 3 # threshold
mask0 = (a<t)
mask2 = a>=t+2
mask1 = (a>=t) & ~mask2
out = np.c_[mask0.sum(1), mask1.sum(1), mask2.sum(1)]
</code>```

Approach #2

If you think about it closely, we are creating three bins there. So, we could use get the bin ID for each element and finally, get the count of each row based on the IDs. We would use np.searchsorted to get those bin IDs and then elementwise equate and sum along each row.

Thus, we would have a solution, like so -

```<code>t = 3 # threshold
bins = [t, t+2]   # Create intervals
N = len(bins)+1   # Number of cols in output
idx = np.searchsorted(bins,a,'right') # Get bin IDs
out = np.column_stack([(idx==i).sum(1) for i in range(N)])
</code>```

We can vectorize the last step with broadcasting -

```<code>out = (idx == np.arange(N)[:,None,None]).sum(2).T
</code>```

And one more vectorized alternative, which would also be memory efficient with np.bincount -

```<code>M = a.shape[0]
r = N*np.arange(M)[:,None]
out = np.bincount((idx + r).ravel(),minlength=M*N).reshape(M,N)
</code>```

Body:
Let's say I have a 2D array with positive integers:

a = numpy.array([[1, 1, 2],
                 [1, 2, 5],
                 [1, 3, 6],
                 [3, 3, 3],
                 [3, 4, 6],
                 [4, 5, 6],
                ])

and a threshold (positive integer). I want to count, for each row, how many ocurrences are < threshold, how many >= threshold and < threshold+2, and how many >= threshold+2. The results are to be stored on a size 3 x n array, where n = a.shape[0] and each of the 3 columns corresponds to the threshold partition.

For the example above and threshold = 3, it would be:

b = numpy.array([[3, 0, 0],
                 [2, 0, 1],
                 [1, 1, 1],
                 [0, 3, 0],
                 [0, 2, 1],
                 [0, 1, 2],
                ])

My solution was to use a for loop combined with masks, so that I could apply the masks individually for each row. But using for loops on arrays feels wrong. Is there a more optimized way to accomplish that?

My solution so far:

b = []
for row in a:
    b.append((numpy.sum(row < threshold),
              numpy.sum((row >= threshold) * (row < threshold + 2)),
              numpy.sum(row >= threshold + 2)))
b = numpy.array(b)

Body:
Approach #1

Making use of elementwise comparison against the thresholds and summing each row -

t = 3 # threshold
mask0 = (a<t)
mask2 = a>=t+2
mask1 = (a>=t) & ~mask2
out = np.c_[mask0.sum(1), mask1.sum(1), mask2.sum(1)]

Approach #2

If you think about it closely, we are creating three bins there. So, we could use get the bin ID for each element and finally, get the count of each row based on the IDs. We would use np.searchsorted to get those bin IDs and then elementwise equate and sum along each row.

Thus, we would have a solution, like so -

t = 3 # threshold
bins = [t, t+2]   # Create intervals
N = len(bins)+1   # Number of cols in output
idx = np.searchsorted(bins,a,'right') # Get bin IDs
out = np.column_stack([(idx==i).sum(1) for i in range(N)])

We can vectorize the last step with broadcasting -

out = (idx == np.arange(N)[:,None,None]).sum(2).T

And one more vectorized alternative, which would also be memory efficient with np.bincount -

M = a.shape[0]
r = N*np.arange(M)[:,None]
out = np.bincount((idx + r).ravel(),minlength=M*N).reshape(M,N)


问:
Weird thing in python classes ?
I was trying to implement a shortest path algorithm in python. I ran into some trouble when I attempted to connect my points on the path.

I have a class called NODE
I made an array of these nodes and then created new nodes in them like this:

```<code>nodes = []
for r in range ( 0, 3 ):
    for c in range ( 0, 3 ):
        nodes.append( NODE( c*WIDTH/20 + 30, r*HEIGHT/20 + 30, 10 ) )
</code>```

This created nodes, which is fine, I can draw them just fine.

At first I attempted connecting them by adding a list of node objects into the the NODE class. I ran into some issues, I thought the problem is with the recursive classes, so to test I did this.
 Where connections is a blank array within the NODE class.

```<code>nodes[0].connections.append( 0 )
print nodes[0].connections

nodes[1].connections.append( 1 )
print nodes[1].connections
print nodes[0].connections
</code>```

This is where I found the problem, Maybe I'm just being stupid, or It's a language thing ? Dunno, but I thought I'd ask.

The output is this:

[ 0 ]

[ 0, 1 ]

[ 0, 1 ]

As you can see, I only added 1 object to the connections list in the index 1. However when I print the contents, I see two.... And this confuses me.

答:
Possibilty 1: your code looks like this:

```<code>class NODE:
    connections = []
    def __init__(self, value):
        self.value = value

nodes = [NODE(23), NODE(42)]

nodes[0].connections.append( 0 )
print nodes[0].connections
nodes[1].connections.append( 1 )
print nodes[1].connections
print nodes[0].connections
</code>```

Solution: class instance attributes should be defined inside __init__. If you define connections at the class level, then every single instance of NODE will share the same one connections list.

```<code>class NODE:
    def __init__(self, value):
        self.value = value
        self.connections = []
</code>```

Possibility 2: your code looks like this:

```<code>class NODE:
    def __init__(self, value, connections = []):
        self.value = value
        self.connections = connections

nodes = [NODE(23), NODE(42)]

nodes[0].connections.append( 0 )
print nodes[0].connections
nodes[1].connections.append( 1 )
print nodes[1].connections
print nodes[0].connections
</code>```

Solution: the default value in an argument list is created only once, so all instances of NODE using that default value will share the same one list. use a non-mutable sentinel value to indicate that no argument was passed. None is usually suitable for this task.

```<code>class NODE:
    def __init__(self, value, connections = None):
        self.value = value
        if connections is not None:
            self.connections = connections
        else:
            self.connections = []
</code>```

Title: Weird thing in python classes ?

Body:
I was trying to implement a shortest path algorithm in python. I ran into some trouble when I attempted to connect my points on the path.

I have a class called NODE
I made an array of these nodes and then created new nodes in them like this:

nodes = []
for r in range ( 0, 3 ):
    for c in range ( 0, 3 ):
        nodes.append( NODE( c*WIDTH/20 + 30, r*HEIGHT/20 + 30, 10 ) )

This created nodes, which is fine, I can draw them just fine.

At first I attempted connecting them by adding a list of node objects into the the NODE class. I ran into some issues, I thought the problem is with the recursive classes, so to test I did this.
 Where connections is a blank array within the NODE class.

nodes[0].connections.append( 0 )
print nodes[0].connections

nodes[1].connections.append( 1 )
print nodes[1].connections
print nodes[0].connections

This is where I found the problem, Maybe I'm just being stupid, or It's a language thing ? Dunno, but I thought I'd ask.

The output is this:

[ 0 ]

[ 0, 1 ]

[ 0, 1 ]

As you can see, I only added 1 object to the connections list in the index 1. However when I print the contents, I see two.... And this confuses me.

Body:
Possibilty 1: your code looks like this:

class NODE:
    connections = []
    def __init__(self, value):
        self.value = value

nodes = [NODE(23), NODE(42)]

nodes[0].connections.append( 0 )
print nodes[0].connections
nodes[1].connections.append( 1 )
print nodes[1].connections
print nodes[0].connections

Solution: class instance attributes should be defined inside __init__. If you define connections at the class level, then every single instance of NODE will share the same one connections list.

class NODE:
    def __init__(self, value):
        self.value = value
        self.connections = []

Possibility 2: your code looks like this:

class NODE:
    def __init__(self, value, connections = []):
        self.value = value
        self.connections = connections

nodes = [NODE(23), NODE(42)]

nodes[0].connections.append( 0 )
print nodes[0].connections
nodes[1].connections.append( 1 )
print nodes[1].connections
print nodes[0].connections

Solution: the default value in an argument list is created only once, so all instances of NODE using that default value will share the same one list. use a non-mutable sentinel value to indicate that no argument was passed. None is usually suitable for this task.

class NODE:
    def __init__(self, value, connections = None):
        self.value = value
        if connections is not None:
            self.connections = connections
        else:
            self.connections = []


问:
Can I force unit testing of properties using the Visual Studio unit testing framework?
I am working on a C# 3.5 project using visual studio 2008, where i have several objects that need to be serialized (they implement IXmlSerializable). In writing unit tests for my serialization code, i would like a way of making sure that when i add a new property to my serializable objects, i will be notified if the serializing and deserializing of the new property is not being tested in any of my unit tests. (Via some failed unit test)

Is this possible? I would think that if there is a special attribute that i can mark my properties with, that would let the Visual Studio unit testing framework know that it needs to be tested.

Or is my approach to this completely off base? I could switch to a different unit testing framework if required.

答:
I think I would try to write a better set of serialization tests that would use reflection to populate all the properties of an object with unique values, serialize it, deserialize, and compare the initial object with the deserialized one. Of course it might be tricky if you have non-trivial validation checks in your classes. On the other hand you might use known good values for known properties and random stuff for unknown properties - this will fail for nontrivial new properties - which is what you want.
This way you test that serialization works after adding new properties (what is really your objective).

If the option above is not possible than you might try generating a coverage report (usually these are in xml format) and then write a simple tool to make sure that your classes are fully tested. I think it will be really difficult to get this to work and I am not sure it is worth the effort. As far as I know there is no better way to check if a property was called.


问:
How do you keep current paginate_button active (bootstrap) after refresh?
I want to click button and keep active currrent button after refresh/reload

My URLs not change when I click other paginate_button , But page is change.

--This button--

https://i.stack.imgur.com/86dJj.jpg

--This code--

```<code><ul class="pagination">
<li class="paginate_button previous disabled" aria-controls="dataTables-example" tabindex="0" id="dataTables-example_previous">
    <a href="#">Previous</a>
</li>
<li class="paginate_button active" aria-controls="dataTables-example" tabindex="0">
    <a href="#">1</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0">
    <a href="#">2</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0">
    <a href="#">3</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0">
    <a href="#">4</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0">
    <a href="#">5</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0">
    <a href="#">6</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0">
    <a href="#">7</a>
</li>
<li class="paginate_button next" aria-controls="dataTables-example" tabindex="0" id="dataTables-example_next">
    <a href="#">Next</a>
</li>
</code>```

答: you can use window.location.pathname or window.location.hash, depending on how you are working your URLs, to test for the current page. Use that info to select the proper li and set it to active.

Body:
I want to click button and keep active currrent button after refresh/reload

My URLs not change when I click other paginate_button , But page is change.

--This button--

https://i.stack.imgur.com/86dJj.jpg

--This code--

    Previous

    1

    2

    3

    4

    5

    6

    7

    Next


问:
function syntax // Generalizing the function
I am trying to subset duplicate observations that have a difference in a singular column. In this example I'm trying to subset observations with the same id number but difference tag numbers. I'm planning on making my own function and then using the lapply function to go through my data set.

As of now my code looks like:

```<code>test.function <- (i) {
  if(test.data[i, "id"] == test.data[i-1, "id"] &
     test.data[i, "tag.num"] != test.data[i-1, "tag.num"]){
   id.tag <- subset(i)
   }
}

lapply (test.data, test.function)
</code>```

I have a few questions regarding the above statement. Most importantly, I keep receiving:

```<code>Error: unexpected '{' in "test.data <- (i) {"
</code>```

I'm really not sure why this keeps happening and any guidance would be appreciated.

Current data set looks like (999 is just a missing value indicator):

```<code>id     tag.num
1000   999
1000   A49038483
1100   999
1100   A49294883
1200   999
1200   999
</code>```

Once again, I am just trying to subset the same id with a different tag number. In this example I am trying to subset 4 observations of id 1000 and 1100.

Also, I am wondering about the syntax inside of my if statement and if it is necessary to have to specify my data set name. I'm hoping to apply this function on several different columns within my original data set. If there is a more general way in which I could set this up and then be able to run the lapply function through for all applicable columns, that would be great knowledge. Any and all help is appreciated.

答:
As far as the error, you're missing a function and a ):

```<code>test.function <- function(i) {
  if(test.data[i, "id"] == test.data[i-1, "id"] &
     test.data[i, "tag.num"] != test.data[i-1, "tag.num"]){
       id.tag <- subset(i)
     }
}
</code>```

runs without any errors.

Body:
I am trying to subset duplicate observations that have a difference in a singular column. In this example I'm trying to subset observations with the same id number but difference tag numbers. I'm planning on making my own function and then using the lapply function to go through my data set.

As of now my code looks like:

test.function <- (i) {
  if(test.data[i, "id"] == test.data[i-1, "id"] &
     test.data[i, "tag.num"] != test.data[i-1, "tag.num"]){
   id.tag <- subset(i)
   }
}

lapply (test.data, test.function)

I have a few questions regarding the above statement. Most importantly, I keep receiving:

Error: unexpected '{' in "test.data <- (i) {"

I'm really not sure why this keeps happening and any guidance would be appreciated.

Current data set looks like (999 is just a missing value indicator):

id     tag.num
1000   999
1000   A49038483
1100   999
1100   A49294883
1200   999
1200   999

Once again, I am just trying to subset the same id with a different tag number. In this example I am trying to subset 4 observations of id 1000 and 1100.

Also, I am wondering about the syntax inside of my if statement and if it is necessary to have to specify my data set name. I'm hoping to apply this function on several different columns within my original data set. If there is a more general way in which I could set this up and then be able to run the lapply function through for all applicable columns, that would be great knowledge. Any and all help is appreciated.

Body:
As far as the error, you're missing a function and a ):

test.function <- function(i) {
  if(test.data[i, "id"] == test.data[i-1, "id"] &
     test.data[i, "tag.num"] != test.data[i-1, "tag.num"]){
       id.tag <- subset(i)
     }
}

runs without any errors.


问:
Hiding code when php field doesn't have value
I need to hide the code if a PHP field value is empty.

Here's the code:

```<code><?php if( get_field('volunteer_causes') ): ?>
                <div class="program-single-volunteer-causes">
                    <h4>Volunteer Causes</h4>
                    <?php
                    $terms = get_field('volunteer_causes');

                    if( $terms ): ?>

                        <ul>

                        <?php foreach( $terms as $term ): ?>

                            <li>
                                <span><?php echo $term ?></span>
                            </li>

                        <?php endforeach; ?>

                        </ul>

                    <?php endif; ?>
                </div><!--program-single-volunteer-causes-->
</code>```

As it is, if there's no value in the 'volunteer_causes' field then the HTML will remain.

I've tried using echo for each line containing the HTML.

Example: <?php echo '
Volunteer Causes
'; ?>

However, this changed nothing.

This method works to remove all code when there's no value present in the field:

 <?php if( !empty(the_field('volunteer_causes')) ): ?>

... however, my HTML is missing when the values do show up.

答:
You can shorten this by assigning in the if and you may have forgotten to close the first if:

```<code><?php if( $terms = get_field('volunteer_causes') ): ?>
    <div class="program-single-volunteer-causes">
        <h4>Volunteer Causes</h4>
            <ul>
            <?php foreach( $terms as $term ): ?>
                <li>
                    <span><?php echo $term ?></span>
                </li>
            <?php endforeach; ?>
            </ul>
    </div>
<?php endif; ?>
</code>```

Body:
I need to hide the code if a PHP field value is empty.

Here's the code:

<?php if( get_field('volunteer_causes') ): ?>

Volunteer Causes

                    <?php
                    $terms = get_field('volunteer_causes');

                    if( $terms ): ?>

                        <?php foreach( $terms as $term ): ?>

                                <?php echo $term ?>

                        <?php endforeach; ?>

                    <?php endif; ?>

As it is, if there's no value in the 'volunteer_causes' field then the HTML will remain.

I've tried using echo for each line containing the HTML.

Example: <?php echo '
Volunteer Causes
'; ?>

However, this changed nothing.

This method works to remove all code when there's no value present in the field:

 <?php if( !empty(the_field('volunteer_causes')) ): ?>

... however, my HTML is missing when the values do show up.

Body:
You can shorten this by assigning in the if and you may have forgotten to close the first if:

<?php if( $terms = get_field('volunteer_causes') ): ?>
    <div class="program-single-volunteer-causes">
        <h4>Volunteer Causes</h4>
            <ul>
            <?php foreach( $terms as $term ): ?>
                <li>
                    <span><?php echo $term ?></span>
                </li>
            <?php endforeach; ?>
            </ul>
    </div>
<?php endif; ?>


问:
How to draw a triangle using matplotlib.pyplot based on 3 dots (x,y) in 2D?
I would like to draw a triangle using python3 module matplotlib.

```<code>import numpy as np
import matplotlib.pyplot as plt

X_train = np.array([[1,1], [2,2.5], [3, 1], [8, 7.5], [7, 9], [9, 9]])
Y_train = ['red', 'red', 'red', 'blue', 'blue', 'blue']

plt.figure()
plt.scatter(X_train[:, 0], X_train[:, 1], s = 170, color = Y_train[:])
plt.show()
</code>```

It displays 6 dots but they are grouped separately in 2 places. (color helps to see it clearly)

There are 2 sets of 3 dots. I want each set(3 dots)  be united in the triangle.

How is it possible to implement this? How to build a triangle based on 3 dots using matplotlib?

Any suggestions are appreciated ;)

答:
A triangle is a polygon. You may use plt.Polygon to draw a polygon.

```<code>import numpy as np
import matplotlib.pyplot as plt

X = np.array([[1,1], [2,2.5], [3, 1], [8, 7.5], [7, 9], [9, 9]])
Y = ['red', 'red', 'red', 'blue', 'blue', 'blue']

plt.figure()
plt.scatter(X[:, 0], X[:, 1], s = 170, color = Y[:])

t1 = plt.Polygon(X[:3,:], color=Y[0])
plt.gca().add_patch(t1)

t2 = plt.Polygon(X[3:6,:], color=Y[3])
plt.gca().add_patch(t2)

plt.show()
</code>```

Body:
I would like to draw a triangle using python3 module matplotlib.

import numpy as np
import matplotlib.pyplot as plt

X_train = np.array([[1,1], [2,2.5], [3, 1], [8, 7.5], [7, 9], [9, 9]])
Y_train = ['red', 'red', 'red', 'blue', 'blue', 'blue']

plt.figure()
plt.scatter(X_train[:, 0], X_train[:, 1], s = 170, color = Y_train[:])
plt.show()

It displays 6 dots but they are grouped separately in 2 places. (color helps to see it clearly)

There are 2 sets of 3 dots. I want each set(3 dots)  be united in the triangle.

How is it possible to implement this? How to build a triangle based on 3 dots using matplotlib?

Any suggestions are appreciated ;)

Body:
A triangle is a polygon. You may use plt.Polygon to draw a polygon.

import numpy as np
import matplotlib.pyplot as plt

X = np.array([[1,1], [2,2.5], [3, 1], [8, 7.5], [7, 9], [9, 9]])
Y = ['red', 'red', 'red', 'blue', 'blue', 'blue']

plt.figure()
plt.scatter(X[:, 0], X[:, 1], s = 170, color = Y[:])

t1 = plt.Polygon(X[:3,:], color=Y[0])
plt.gca().add_patch(t1)

t2 = plt.Polygon(X[3:6,:], color=Y[3])
plt.gca().add_patch(t2)

plt.show()


答:
You're using transform on the img and transform starts a new stacking context. Add position: relative to .text to start a new stacking context on that element so it will appear on top of the img

a {
  height: 400px;
  width: 200px;
  display: block;
  text-decoration: none;
  color: black;
  overflow: hidden;
}

img {
  transform: scale(1.1);
}

a:hover .text {
  color: white;
  background-color: black;
}

.text {
  text-align: center;
  height: 200px;
  margin-top: -4px;
  background-color: white;
  transition: all 1s ease;
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  <img src="http://images.meredith.com/content/dam/bhg/Images/2009/07/101422234.jpg.rendition.200sq.jpg" />
  <div class="text">
    This is some text.
  </div>
</code>```

Title: z-index not working between image and text box

Body:
JSFiddle

I have an image with a text box below. I scaled the image, and it goes over the text box, i wan't the text box to be on top of the image, but it is not working with z-index.

HTML:

    This is some text.

CSS:

a {
  height:400px;
  width:200px;
  display:block;
  text-decoration:none;
  color:black;
  overflow:hidden;
}

img {
  transform: scale(1.1);
}

a:hover .text {
  color:white;
  background-color:black;
}

.text {
  text-align:center;
  height:200px;
  margin-top:-4px;
  background-color:white;
  transition:all 1s ease;
}

Body:
You're using transform on the img and transform starts a new stacking context. Add position: relative to .text to start a new stacking context on that element so it will appear on top of the img

a {
  height: 400px;
  width: 200px;
  display: block;
  text-decoration: none;
  color: black;
  overflow: hidden;
}

img {
  transform: scale(1.1);
}

a:hover .text {
  color: white;
  background-color: black;
}

.text {
  text-align: center;
  height: 200px;
  margin-top: -4px;
  background-color: white;
  transition: all 1s ease;
  position: relative;
}

<a href="#">
  <img src="http://images.meredith.com/content/dam/bhg/Images/2009/07/101422234.jpg.rendition.200sq.jpg" />
  <div class="text">
    This is some text.
  </div>
</a>


问:
total number of rows of a query
I have a very large query that is supposed to return only the top 10 results:

select top 10 ProductId from .....

The problem is that I also want the total number of results that match the criteria without that 'top 10', but in the same time it's considered unaceptable to return all rows (we are talking of roughly 100 thousand results.

Is there a way to get the total number of rows affected by the previous query, either in it or afterwords without running it again?

PS: please no temp tables of 100 000 rows :))

答:
Assuming that you're using an ORDER BY clause already (to properly define which the "TOP 10" results are), then you could add a call of ROW_NUMBER also, with the opposite sort order, and pick the highest value returned.

E.g., the following:

```<code>select top 10 *,ROW_NUMBER() OVER (order by id desc) from sysobjects order by ID
</code>```

Has a final column with values 2001, 2000, 1999, etc, descending. And the following:

```<code>select COUNT(*) from sysobjects
</code>```

Confirms that there are 2001 rows in sysobjects.

Title: total number of rows of a query

Body:
Assuming that you're using an ORDER BY clause already (to properly define which the "TOP 10" results are), then you could add a call of ROW_NUMBER also, with the opposite sort order, and pick the highest value returned.

E.g., the following:

select top 10 *,ROW_NUMBER() OVER (order by id desc) from sysobjects order by ID

Has a final column with values 2001, 2000, 1999, etc, descending. And the following:

select COUNT(*) from sysobjects

Confirms that there are 2001 rows in sysobjects.


问:
CocoaPods not working in macOS High Sierra
After upgrading to macOS High Sierra CocoaPods is not working. While it is tempting to move away from CocoaPods, it's unfortunately not in scope right now. The error message is below.

```<code>zsh: /Users/****/.gems/bin/pod: bad interpreter: /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin: no such file or directory
</code>```

I realize that the error stems from Ruby being upgraded but what is the easies fix? Trying to make CocoaPods use the new ruby version yields other errors.

Edit: For now i installed Ruby 2.0 with rvm install 2.0.0 and rvm use 2.0.0 and then reinstalled CocoaPods sudo gem install cocoapods. Seems to be working now.

答:
According to https://github.com/CocoaPods/CocoaPods/issues/6778 reinstalling CocoaPods should solve this issue:</p>

```<code>sudo gem install cocoapods
</code>```

Body:
After upgrading to macOS High Sierra CocoaPods is not working. While it is tempting to move away from CocoaPods, it's unfortunately not in scope right now. The error message is below.

zsh: /Users/****/.gems/bin/pod: bad interpreter: /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin: no such file or directory

I realize that the error stems from Ruby being upgraded but what is the easies fix? Trying to make CocoaPods use the new ruby version yields other errors.

Edit: For now i installed Ruby 2.0 with rvm install 2.0.0 and rvm use 2.0.0 and then reinstalled CocoaPods sudo gem install cocoapods. Seems to be working now.

Body:
According to https://github.com/CocoaPods/CocoaPods/issues/6778 reinstalling CocoaPods should solve this issue:

sudo gem install cocoapods


问:
Repeated incrementation of a floating point number
I'm looking at some legacy code that defines some grid points along the axis f.

```<code>int main(){
    double f[9];
    int i = 0;
    for (double a = 0; a <= 1; a += 0.125){
        f[i++] = a;
    }
}
</code>```

I'm worried about the repeated addition of 1 / 8 to a, and the loop not running correctly. This is because I don't think you can add floating point values like this and rely on it being exactly 1 when i is 8.

Or is this code OK and I should stop worrying? (The code is at least 20 years old apparently and has never caused trouble - although in the original version, double a was declared outside the loop, I'm reading up on why that is.).

答:
C standard leaves floating number implemented behavior, a lot of compiler use IEEE 754 standard. Your code is not Ok because:

Your code must be compile with IEEE 754 standard or similar standard with the same behavior.

It's hard to read. When you read the code the exact behavior is not obvious.

This is not the right way to iterate over array in C.

Imagine, someone doesn't know that requirement, and don't compile with IEEE 754 standard. The behavior could be something completely different. For example, your code could produce a out of bounds, and this is undefined behavior, your program could crash.

That said, an example of code that have the same behavior of your code when compiled with IEEE 754 standard:

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

int main(void) {
  double f[9];
  size_t const size_f = sizeof f / sizeof *f;

  double a = 0;
  for (size_t i = 0; i < size_f; i++) {
    f[i] = a;
    a += 0.125;
  }
}
</code>```

Body:
I'm looking at some legacy code that defines some grid points along the axis f.

int main(){
    double f[9];
    int i = 0;
    for (double a = 0; a <= 1; a += 0.125){
        f[i++] = a;
    }
}

I'm worried about the repeated addition of 1 / 8 to a, and the loop not running correctly. This is because I don't think you can add floating point values like this and rely on it being exactly 1 when i is 8.

Or is this code OK and I should stop worrying? (The code is at least 20 years old apparently and has never caused trouble - although in the original version, double a was declared outside the loop, I'm reading up on why that is.).

Body:
C standard leaves floating number implemented behavior, a lot of compiler use IEEE 754 standard. Your code is not Ok because:

Your code must be compile with IEEE 754 standard or similar standard with the same behavior.

It's hard to read. When you read the code the exact behavior is not obvious.

This is not the right way to iterate over array in C.

Imagine, someone doesn't know that requirement, and don't compile with IEEE 754 standard. The behavior could be something completely different. For example, your code could produce a out of bounds, and this is undefined behavior, your program could crash.

That said, an example of code that have the same behavior of your code when compiled with IEEE 754 standard:

#include <stddef.h>

int main(void) {
  double f[9];
  size_t const size_f = sizeof f / sizeof *f;

  double a = 0;
  for (size_t i = 0; i < size_f; i++) {
    f[i] = a;
    a += 0.125;
  }
}


答:
Try This </p>

```<code><div class="program-single-volunteer-causes">
  <?php

   $terms = get_field('volunteer_causes');

   if (!empty($terms)) {
    echo
     '<h4>Volunteer Causes</h4>
     <ul>';
     foreach ($terms as $term) {
      echo
       '<li><span>' . $term . '</span></li>';
     }
     echo
     '</ul>';
   } else {
     echo '<p>No Record Found</p>';
   }
 ?>
</div>
</code>```

Title: Hiding code when php field doesn't have value

Body:
Try This

<div class="program-single-volunteer-causes">
  <?php

   $terms = get_field('volunteer_causes');

   if (!empty($terms)) {
    echo
     '<h4>Volunteer Causes</h4>
     <ul>';
     foreach ($terms as $term) {
      echo
       '<li><span>' . $term . '</span></li>';
     }
     echo
     '</ul>';
   } else {
     echo '<p>No Record Found</p>';
   }
 ?>
</div>


问:
Android - Fragment is behind Buttons from Activity
So I have an activity with 2 empty ListView's and 3 Buttons. The "Hinzufügen" Button (seen in Screenshot) should load a Fragment into a Framelayout (used as Container) to lay over all components (ListView's and Buttons) from the activity. But I don't know why it lays behind all of them (can't click the Button of the Fragment because it's behind an empty ListView).

Screenshot without Fragment started:
https://abload.de/img/dqwdwqemuhi.jpeg

Screenshot with Fragment started:
https://abload.de/img/fewqfewp7u0b.jpeg

If I get the container with

```<code>View view = findViewById(R.id.container);
</code>```

and then use

```<code>view.bringtToFront();
</code>```

the Buttons from the activity are still shown but the ListView's are in the background (can click the button from the fragment now).

How do I get the buttons from the activity in the background so that the fragment lays over the whole activity and its components?

Activity XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="superhelden.com.superheldenuebersichtsapp.Activities.DeckOverview">

<FrameLayout
    android:id="@+id/addCardsContainer"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:layout_marginTop="20dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent">

</FrameLayout>

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline3"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.65"
    tools:layout_editor_absoluteY="332dp"
    tools:layout_editor_absoluteX="0dp" />

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline4"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.4"
    tools:layout_editor_absoluteY="0dp"
    tools:layout_editor_absoluteX="154dp" />

<Button
    android:id="@+id/addCards"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:text="@string/addCards"
    app:layout_constraintRight_toLeftOf="@+id/guideline4"
    app:layout_constraintTop_toTopOf="@+id/guideline3"
    android:layout_marginTop="8dp"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent" />

<Button
    android:id="@+id/removeCards"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="8dp"
    android:text="@string/removeCards"
    app:layout_constraintBottom_toTopOf="@+id/guideline5"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@+id/guideline4"
    app:layout_constraintTop_toBottomOf="@+id/addCards"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<Button
    android:id="@+id/endGame"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="8dp"
    android:text="@string/endGame"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@+id/guideline4"
    app:layout_constraintTop_toTopOf="@+id/guideline5"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline5"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.88"
    tools:layout_editor_absoluteY="450dp"
    tools:layout_editor_absoluteX="0dp" />

<ListView
    android:id="@+id/amountOfTypesList"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintLeft_toLeftOf="@+id/guideline4"
    app:layout_constraintTop_toTopOf="@+id/guideline3"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<ListView
    android:id="@+id/deckList"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:divider="#000"
    android:dividerHeight="0.5dp"
    android:scrollbars="horizontal"
    app:layout_constraintBottom_toTopOf="@+id/guideline3"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0" />

</android.support.constraint.ConstraintLayout>
</code>```

Activity Java:

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

FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
Button addCardsButton;
Button removeCardsButton;
Button endGameButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_deck_overview);
    addCardsButton = (Button) findViewById(R.id.addCards);
    addCardsButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            fragmentManager = getFragmentManager();
            fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.addCardsContainer, new addCards());
            fragmentTransaction.addToBackStack("addCards");
            fragmentTransaction.commit();
        }
    });
    removeCardsButton = (Button) findViewById(R.id.removeCards);
    removeCardsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //TODO: Karten aus Tabelle in der DB entfernen
        }
    });
    endGameButton = (Button) findViewById(R.id.endGame);
    endGameButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(), EndScreen.class);
            startActivity(intent);
            finish();
        }
    });
}

}
</code>```

Fragment XML:

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent"
tools:context="superhelden.com.superheldenuebersichtsapp.Fragments.addCards">

<ListView
    android:id="@+id/allCardsList"
    android:layout_width="0dp"
    android:layout_height="0dp"

    app:layout_constraintBottom_toTopOf="@+id/guideline7"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@+id/guideline6"
    app:layout_constraintTop_toTopOf="@+id/guideline10"

    style="@style/Margin_And_Divider_Style"/>

<ListView
    android:id="@+id/selectedCardsList"
    android:layout_width="0dp"
    android:layout_height="0dp"

    app:layout_constraintBottom_toTopOf="@+id/guideline7"
    app:layout_constraintLeft_toLeftOf="@+id/guideline6"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="@+id/guideline10"

    style="@style/Margin_And_Divider_Style"/>

<Button
    android:id="@+id/doneButtonAddCards"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="8dp"
    android:text="@string/done"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"

    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="@+id/guideline7"
    app:layout_constraintVertical_bias="0.571" />

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline6"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.5"
    tools:layout_editor_absoluteY="0dp"
    tools:layout_editor_absoluteX="180dp" />

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline7"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.86"
    tools:layout_editor_absoluteY="439dp"
    tools:layout_editor_absoluteX="0dp" />

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline10"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.1"
    tools:layout_editor_absoluteY="51dp"
    tools:layout_editor_absoluteX="0dp" />

<SearchView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="8dp"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:id="@+id/searchView"

    app:layout_constraintBottom_toTopOf="@+id/guideline10"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

Fragment Java:

```<code>List<Card> allCardsList;
ListView allCardsListView;

View addCards;

public addCards() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    allCardsList = DbClass.getInstance(getActivity()).getAllCards();
    allCardsListView = (ListView) getActivity().findViewById(R.id.allCardsList);

    Toast.makeText(getActivity(), allCardsList.get(0).getName(), Toast.LENGTH_SHORT).show();
    addCards = inflater.inflate(R.layout.fragment_add_cards, container, false);

    return addCards;
}
</code>```

答:
move addCardsContainer to the bottom of your Activity XML (last child of ConstraintLayout). Drawing is always in order of positioning in inflated layout file. bringToFront is not for this case

```<code>    ...
    <FrameLayout
        android:id="@+id/addCardsContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
</code>```

because of margin you may still see a fragment of your buttons in layer below. you can replace layout_margin with padding and set some background for cover

```<code>        android:padding="20dp"
        android:background="#000000"
</code>```

Body:
So I have an activity with 2 empty ListView's and 3 Buttons. The "Hinzufügen" Button (seen in Screenshot) should load a Fragment into a Framelayout (used as Container) to lay over all components (ListView's and Buttons) from the activity. But I don't know why it lays behind all of them (can't click the Button of the Fragment because it's behind an empty ListView).

Screenshot without Fragment started:
https://abload.de/img/dqwdwqemuhi.jpeg

Screenshot with Fragment started:
https://abload.de/img/fewqfewp7u0b.jpeg

If I get the container with

View view = findViewById(R.id.container);

and then use

view.bringtToFront();

the Buttons from the activity are still shown but the ListView's are in the background (can click the button from the fragment now).

How do I get the buttons from the activity in the background so that the fragment lays over the whole activity and its components?

Activity XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="superhelden.com.superheldenuebersichtsapp.Activities.DeckOverview">

<FrameLayout
    android:id="@+id/addCardsContainer"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:layout_marginTop="20dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent">

</FrameLayout>

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline3"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.65"
    tools:layout_editor_absoluteY="332dp"
    tools:layout_editor_absoluteX="0dp" />

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline4"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.4"
    tools:layout_editor_absoluteY="0dp"
    tools:layout_editor_absoluteX="154dp" />

<Button
    android:id="@+id/addCards"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:text="@string/addCards"
    app:layout_constraintRight_toLeftOf="@+id/guideline4"
    app:layout_constraintTop_toTopOf="@+id/guideline3"
    android:layout_marginTop="8dp"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent" />

<Button
    android:id="@+id/removeCards"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="8dp"
    android:text="@string/removeCards"
    app:layout_constraintBottom_toTopOf="@+id/guideline5"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@+id/guideline4"
    app:layout_constraintTop_toBottomOf="@+id/addCards"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<Button
    android:id="@+id/endGame"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="8dp"
    android:text="@string/endGame"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@+id/guideline4"
    app:layout_constraintTop_toTopOf="@+id/guideline5"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline5"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.88"
    tools:layout_editor_absoluteY="450dp"
    tools:layout_editor_absoluteX="0dp" />

<ListView
    android:id="@+id/amountOfTypesList"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintLeft_toLeftOf="@+id/guideline4"
    app:layout_constraintTop_toTopOf="@+id/guideline3"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<ListView
    android:id="@+id/deckList"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:divider="#000"
    android:dividerHeight="0.5dp"
    android:scrollbars="horizontal"
    app:layout_constraintBottom_toTopOf="@+id/guideline3"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0" />

</android.support.constraint.ConstraintLayout>

Activity Java:

public class DeckOverview extends AppCompatActivity {

FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
Button addCardsButton;
Button removeCardsButton;
Button endGameButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_deck_overview);
    addCardsButton = (Button) findViewById(R.id.addCards);
    addCardsButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            fragmentManager = getFragmentManager();
            fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.addCardsContainer, new addCards());
            fragmentTransaction.addToBackStack("addCards");
            fragmentTransaction.commit();
        }
    });
    removeCardsButton = (Button) findViewById(R.id.removeCards);
    removeCardsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //TODO: Karten aus Tabelle in der DB entfernen
        }
    });
    endGameButton = (Button) findViewById(R.id.endGame);
    endGameButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(), EndScreen.class);
            startActivity(intent);
            finish();
        }
    });
}

}

Fragment XML:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent"
tools:context="superhelden.com.superheldenuebersichtsapp.Fragments.addCards">

<ListView
    android:id="@+id/allCardsList"
    android:layout_width="0dp"
    android:layout_height="0dp"

    app:layout_constraintBottom_toTopOf="@+id/guideline7"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@+id/guideline6"
    app:layout_constraintTop_toTopOf="@+id/guideline10"

    style="@style/Margin_And_Divider_Style"/>

<ListView
    android:id="@+id/selectedCardsList"
    android:layout_width="0dp"
    android:layout_height="0dp"

    app:layout_constraintBottom_toTopOf="@+id/guideline7"
    app:layout_constraintLeft_toLeftOf="@+id/guideline6"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="@+id/guideline10"

    style="@style/Margin_And_Divider_Style"/>

<Button
    android:id="@+id/doneButtonAddCards"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="8dp"
    android:text="@string/done"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"

    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="@+id/guideline7"
    app:layout_constraintVertical_bias="0.571" />

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline6"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.5"
    tools:layout_editor_absoluteY="0dp"
    tools:layout_editor_absoluteX="180dp" />

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline7"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.86"
    tools:layout_editor_absoluteY="439dp"
    tools:layout_editor_absoluteX="0dp" />

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline10"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.1"
    tools:layout_editor_absoluteY="51dp"
    tools:layout_editor_absoluteX="0dp" />

<SearchView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="8dp"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:id="@+id/searchView"

    app:layout_constraintBottom_toTopOf="@+id/guideline10"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent" />

</android.support.constraint.ConstraintLayout>

Fragment Java:

List<Card> allCardsList;
ListView allCardsListView;

View addCards;

public addCards() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    allCardsList = DbClass.getInstance(getActivity()).getAllCards();
    allCardsListView = (ListView) getActivity().findViewById(R.id.allCardsList);

    Toast.makeText(getActivity(), allCardsList.get(0).getName(), Toast.LENGTH_SHORT).show();
    addCards = inflater.inflate(R.layout.fragment_add_cards, container, false);

    return addCards;
}

Body:
move addCardsContainer to the bottom of your Activity XML (last child of ConstraintLayout). Drawing is always in order of positioning in inflated layout file. bringToFront is not for this case

    ...
    <FrameLayout
        android:id="@+id/addCardsContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>

because of margin you may still see a fragment of your buttons in layer below. you can replace layout_margin with padding and set some background for cover

        android:padding="20dp"
        android:background="#000000"


问:
Filter / prioritize phone numbers on the iPhone
Is it anyway possible to tag certain phone numbers on your iPhone as high priority numbers, and then filter them out to perform some actions on them?.. e.g. allowing calls from these numbers to come through even when the ringer is off.

Does Apple even provide the dev access to phone api's to allow this sort of work?

答: jailbroken+ private APIs= impossible is nothing</p>


问:
PHP - Inconsistency with "Undefined offset" error
Why does PHP throw a "Notice: Undefined offset" error here:

```<code><?php
$MyVar = array();
echo $MyVar[0]; //Notice: Undefined offset: 0
?>
</code>```

But not here:

```<code><?php
$MyVar = false;
echo $MyVar[0]; //No error
?>
</code>```

答:
It's ultimately because in your 2nd example $MyVar[0] is null which isn't an error. You could probably reference $MyVar[0][1][2][3] and get the same result.

The first example isn't null it's a missing index in an array so it warns you.

Body:
Why does PHP throw a "Notice: Undefined offset" error here:

<?php
$MyVar = array();
echo $MyVar[0]; //Notice: Undefined offset: 0
?>

But not here:

<?php
$MyVar = false;
echo $MyVar[0]; //No error
?>


问:
How can I set a textview's style programmatically?
How can I add a style to a textview in java? I am trying to add one under my values/styles.xml, not to add each attribute individually.</p>

```<code>LinearLayout messagesLayout = (LinearLayout) findViewById(R.id.messages_layout);
TextView sentOne = new TextView(this);
sentOne.setText(sentMessage);

messagesLayout.addView(sentOne);
</code>```

答:
There is an answer for this already: https://stackoverflow.com/a/7919203/5544859

```<code>textview.setTypeface(Typeface.DEFAULT_BOLD);
</code>```

to preserve the previously set typeface attributes you can use:

```<code>textview.setTypeface(textview.getTypeface(), Typeface.DEFAULT_BOLD);
</code>```

Credit to: @Raz

Body:
How can I add a style to a textview in java? I am trying to add one under my values/styles.xml, not to add each attribute individually.

LinearLayout messagesLayout = (LinearLayout) findViewById(R.id.messages_layout);
TextView sentOne = new TextView(this);
sentOne.setText(sentMessage);

messagesLayout.addView(sentOne);

Body:
There is an answer for this already: https://stackoverflow.com/a/7919203/5544859

textview.setTypeface(Typeface.DEFAULT_BOLD);

to preserve the previously set typeface attributes you can use:

textview.setTypeface(textview.getTypeface(), Typeface.DEFAULT_BOLD);

Credit to: @Raz