问:
Adding tag in bootstrap tags input dynamically not working
I'm trying to set tags via bootstrap tags input but it's not working and giving following error:

```<code>TypeError: b.options.itemValue(...) is undefined
</code>```

my code is as follow:

```<code>$('#searchGeoBottom').tagsinput({
    maxTags: 5,
    delay: 500,
    itemValue: 'value',
    itemText: 'text',
    typeahead: {
        displayKey: 'text',
        source: function (query) {
            if (ajax) {
                ajax.abort();
            }
            var data = {term: query};
            ajax = $.getJSON((baseUrl + "geoSearch"), data);
            return ajax;
        },
        afterSelect: function () {
            this.$element[0].value = '';
        }
    }
});
if (typeof searchGeo != 'undefined' && searchGeo != '') {
    $('#searchGeoBottom').tagsinput('add', searchGeo);
}
</code>```

I've also tried following approach which i found while searching:

```<code>var elt = $('#searchGeoBottom').tagsinput({....});
elt.tagsinput('add', searchGeo);
</code>```

But it didn't work either, gives elt is not defined or elt is not a function..

Following is the json I'm passing in add function:

```<code>[{"text":"Lahore. United States","value":4768156}]
</code>```

答:
For those who might have the same problem, try this code:</p>

```<code>var elt = $('#searchGeoBottom'); // get element
elt.tagsinput({....}); // initialize tagsinput
elt.tagsinput('add', searchGeo[0]); // adding one object at a time and not an array
</code>```

Body:
I'm trying to set tags via bootstrap tags input but it's not working and giving following error:

TypeError: b.options.itemValue(...) is undefined

my code is as follow:

$('#searchGeoBottom').tagsinput({
    maxTags: 5,
    delay: 500,
    itemValue: 'value',
    itemText: 'text',
    typeahead: {
        displayKey: 'text',
        source: function (query) {
            if (ajax) {
                ajax.abort();
            }
            var data = {term: query};
            ajax = $.getJSON((baseUrl + "geoSearch"), data);
            return ajax;
        },
        afterSelect: function () {
            this.$element[0].value = '';
        }
    }
});
if (typeof searchGeo != 'undefined' && searchGeo != '') {
    $('#searchGeoBottom').tagsinput('add', searchGeo);
}

I've also tried following approach which i found while searching:

var elt = $('#searchGeoBottom').tagsinput({....});
elt.tagsinput('add', searchGeo);

But it didn't work either, gives elt is not defined or elt is not a function..

Following is the json I'm passing in add function:

[{"text":"Lahore. United States","value":4768156}]

Body:
For those who might have the same problem, try this code:

var elt = $('#searchGeoBottom'); // get element
elt.tagsinput({....}); // initialize tagsinput
elt.tagsinput('add', searchGeo[0]); // adding one object at a time and not an array


来源: stackexchange

问:
Site is down after migrating to Cloudflare
I wanted to use CloudFlare for my website (hosted on Microsoft Azure).

I have added my domain to Cloudflare, and changed my domains nameservers to the ones I got from Cloudflare.

Furthermore, cloudflare imported my current DNS settings which are the following (my domain has been replaced with domain.com):

I thought the migration would go smoothly, however, when I go to www.domain.com I get the error:

The webpage at http://www.domain.com/ might be temporarily down or
  it may have moved permanently to a new web address.

However, when I refresh a couple of times it finally loads the site.
If I go to domain.com (no www-prefix), I get the error:

domain.com’s server DNS address could not be found.

What could be going on?

答:
You need both @ and www CNAME specified in your host records. Not just www.

the refresh is normal after you make a dns change. The browser keeps the dns lookup in cache, so if you visit the site on another browser you won't have to do a refresh. Just clear your browser cache when you want to see dns changes, but some edits could take 15min or longer to see changes.

ContentLicense: CC BY-SA 3.0


问:
fill column with previous column if NA
I have a data frame like this

```<code>df <- data.frame(v1 = 10:14, v2 = c(NA, 1, NA, 3, 6), v3 = c(1, NA, NA, 9, 4))

  v1 v2 v3
1 10 NA  1
2 11  1 NA
3 12 NA NA
4 13  3  9
5 14  6  4
</code>```

I now want to fill the NAs with the value of the previous column, so it looks like this:

```<code>  v1 v2 v3
1 10 10  1
2 11  1  1
3 12 12 12
4 13  3  9
5 14  6  4
</code>```

I know how to do this manually, like this:

```<code>df$v2 <- ifelse(is.na(df$v2), df$v1, df$v2)
</code>```

How can I automate this for a full data frame with many columns?

答:
```<code>for (i in 2:ncol(df))
  df[,i] = ifelse(is.na(df[,i]), df[,i-1],df[,i])
</code>```

This will propagate values across streaks of NA columns. If you don't want this, just reverse the order of the indexes in the for loop declaration.

Title: fill column with previous column if NA

Body:
I have a data frame like this

df <- data.frame(v1 = 10:14, v2 = c(NA, 1, NA, 3, 6), v3 = c(1, NA, NA, 9, 4))

  v1 v2 v3
1 10 NA  1
2 11  1 NA
3 12 NA NA
4 13  3  9
5 14  6  4

I now want to fill the NAs with the value of the previous column, so it looks like this:

  v1 v2 v3
1 10 10  1
2 11  1  1
3 12 12 12
4 13  3  9
5 14  6  4

I know how to do this manually, like this:

df$v2 <- ifelse(is.na(df$v2), df$v1, df$v2)

How can I automate this for a full data frame with many columns?

Body:
for (i in 2:ncol(df))
  df[,i] = ifelse(is.na(df[,i]), df[,i-1],df[,i])

This will propagate values across streaks of NA columns. If you don't want this, just reverse the order of the indexes in the for loop declaration.


问:
JQuery hide/show from textbox
I'm trying to get a password field to be shown/hidden depending on value that of a different input element.

For example if the username is "admin" it should hide the password field.

If you they type in anything else then the password field appears or remains.

function togglePassword() {
  if ($("#j_username").val() == "admin")
    $("#j_password").hide();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>User Name</label>
<input type='text' id="j_username" name='j_username' style='text-align: Left;' MaxLength='100' size='20' tabindex='1' onkeypress='javascript:return loginIdKeyPress(event);' />

<label>Password</label>
<input type='password' id="j_password" name='j_password' value='' Align='Left' size='20' tabindex='2' onkeypress='javascript:return passwordKeyPress(event);' />
<br/></code>```

Currently this code doesn't work for me, what should I change?

答:
You can use the keyup event along with the toggle() function to toggle hide/show.

Example below outputs the value of the condition on each keypress to the console. If admin string is present, password field is hidden.

$("#j_username").on("keyup", function() {
  //gets value of input element and evaluates if true/false
  var inputValue = ($(this).val() == "admin");
  //outputs value in console for each keypress
  console.log(inputValue);
  //shows password field if inputValue is false, hides if true
  $("#j_password").toggle( !inputValue );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>User Name</label>
<input type='text' id="j_username" name='j_username' style='text-align: Left;' MaxLength='100' size='20' tabindex='1'  />
<br/>
<label>Password</label>
<input type='password' id="j_password" name='j_password' value='' Align='Left' size='20' tabindex='2'/>
<br/></code>```

Title: JQuery hide/show from textbox

Body:
I'm trying to get a password field to be shown/hidden depending on value that of a different input element.

For example if the username is "admin" it should hide the password field.

If you they type in anything else then the password field appears or remains.

function togglePassword() {
  if ($("#j_username").val() == "admin")
    $("#j_password").hide();
}

User Name
<input type='text' id="j_username" name='j_username' style='text-align: Left;' MaxLength='100' size='20' tabindex='1' onkeypress='javascript:return loginIdKeyPress(event);' />

Password
<input type='password' id="j_password" name='j_password' value='' Align='Left' size='20' tabindex='2' onkeypress='javascript:return passwordKeyPress(event);' />

Currently this code doesn't work for me, what should I change?

Body:
You can use the keyup event along with the toggle() function to toggle hide/show.

Example below outputs the value of the condition on each keypress to the console. If admin string is present, password field is hidden.

$("#j_username").on("keyup", function() {
  //gets value of input element and evaluates if true/false
  var inputValue = ($(this).val() == "admin");
  //outputs value in console for each keypress
  console.log(inputValue);
  //shows password field if inputValue is false, hides if true
  $("#j_password").toggle( !inputValue );
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>User Name</label>
<input type='text' id="j_username" name='j_username' style='text-align: Left;' MaxLength='100' size='20' tabindex='1'  />
<br/>
<label>Password</label>
<input type='password' id="j_password" name='j_password' value='' Align='Left' size='20' tabindex='2'/>
<br/>


问:
How to increment a number within a variable name in jQuery
I have this javascript for loop:

```<code>for (var i=1; i <= 2; i++) {
   $(".afterglowplayer"+i).click(function () {$.afterglowplayer+i.toggle(this); return false;});
}
</code>```

I need to increment the number at the end of a jQuery variable name so that I get this:

```<code>$.afterglowplayer1.toggle(this);
$.afterglowplayer2.toggle(this);
</code>```

I have tried using

```<code>$.afterglowplayer+i.toggle(this);
</code>```

and

```<code>$.afterglowplayer+"+i+".toggle(this);
</code>```

But it is not correct way... is it possible to increment the number at the end of a jQuery variable name?

答:
You can use the let keyword

for (let i=1; i <= 2; i++) {
   $(".afterglowplayer"+i).click(function () {
      $('.afterglowplayer'+i).toggle(this);
      return false;
   });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='afterglowplayer1'>Foo</div>
<div class='afterglowplayer2'>Bar</div></code>```

Body:
I have this javascript for loop:

for (var i=1; i <= 2; i++) {
   $(".afterglowplayer"+i).click(function () {$.afterglowplayer+i.toggle(this); return false;});
}

I need to increment the number at the end of a jQuery variable name so that I get this:

$.afterglowplayer1.toggle(this);
$.afterglowplayer2.toggle(this);

I have tried using

$.afterglowplayer+i.toggle(this);

and

$.afterglowplayer+"+i+".toggle(this);

But it is not correct way... is it possible to increment the number at the end of a jQuery variable name?

Body:
You can use the let keyword

for (let i=1; i <= 2; i++) {
   $(".afterglowplayer"+i).click(function () {
      $('.afterglowplayer'+i).toggle(this);
      return false;
   });
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='afterglowplayer1'>Foo</div>
<div class='afterglowplayer2'>Bar</div>


问:
Using Protractor 'Expect'

I have some simple specs that run in sequence. The first one has an expect assertion for the webpage title - as does the second.

However, when I run the sequence, the first assertion passes but the second one fails and console.log shows that parts of the first spec's expect have become merged with the second spec's expect.

I have a feeling this is something to do with promise...please can someone confirm this (or deny it!!) and advise on a way to close the promise?

Thanks

First Spec

describe('JL Homepage', function() {
//browser.waitForAngularEnabled(false);
browser.get('https://mwac-johnlewis-dev.digitalbridge.eu/landing');

 browser.sleep(10000);

it('should have a title', function(){
expect (browser.getTitle()).toBe('John Lewis Wallpaper Visualiser:
Welcome');
});

});
```

<p><strong>Second Spec</strong></p>

<pre class="lang-js prettyprint-override"><code>describe('Demo photo', function() {
browser.waitForAngularEnabled(false);

browser.sleep(3000);
element(by.xpath('html/body/webapp-app/div/div/webapp-johnlewis-landing/div/div/ul/li[2]/a/span')).click();

it('should load a demo room', function(){

    expect (browser.getTitle()).toEqual('John Lewis Wallpaper Visualiser: Design your room');

browser.sleep(3000);
});

});
</code>```

Console

2 specs, 1 failure
Finished in 19.409 seconds

**************************************************
*                    Failures                    *
**************************************************

1) Demo photo should load a demo room
  - Expected 'John Lewis Wallpaper Visualiser: Welcome' to equal 'John
  Lewis Wallpaper Visualiser: Design your room'.

Executed 2 of 2 specs (1 FAILED) in 19 secs.
[12:08:21] I/launcher - 0 instance(s) of WebDriver still running
[12:08:21] I/launcher - chrome #01 failed 1 test(s)
[12:08:21] I/launcher - overall: 1 failed spec(s)
[12:08:21] E/launcher - Process exited with error code 1
Admins-MacBook:jl_autotests davidredmayne$
```

答:
You need to wrap all of your actions inside a valid Jasmine-block.

Find an introduction of Jasmine with examples here and the latest API description here.

As addition: browser.get() is always a bit difficult to handle, because Protractor cannot know, if the page to load contains Angular. Therefore the test execution could continue, before the page is fully loaded.

To prevent too fast execution, use ExpectedConditions and browser.wait()

Here, how I suggest the first Spec to be:

describe('JL Homepage', function() {
    //possibility for beforeAll(), beforeEach(), afterAll(), afterEach()
    it('should load the page and have a title', function(){
        var EC = protractor.ExpectedConditions;
        browser.get('https://mwac-johnlewis-dev.digitalbridge.eu/landing');
        //wait until URL has changed
        browser.wait(EC.urlIs('https://mwac-johnlewis-dev.digitalbridge.eu/landing'),5000);
        //wait until page has finished loading
        browser.waitForAngular();
        expect (browser.getTitle()).toBe('John Lewis Wallpaper Visualiser: Welcome');
    });
});
```

ContentLicense: CC BY-SA 4.0

Title: Using Protractor 'Expect'

Body:
I have some simple specs that run in sequence. The first one has an expect assertion for the webpage title - as does the second.

However, when I run the sequence, the first assertion passes but the second one fails and console.log shows that parts of the first spec's expect have become merged with the second spec's expect.

I have a feeling this is something to do with promise...please can someone confirm this (or deny it!!) and advise on a way to close the promise?

Thanks

First Spec

describe('JL Homepage', function() {
//browser.waitForAngularEnabled(false);
browser.get('https://mwac-johnlewis-dev.digitalbridge.eu/landing');

 browser.sleep(10000);

it('should have a title', function(){
expect (browser.getTitle()).toBe('John Lewis Wallpaper Visualiser:
Welcome');
});

});

Second Spec

describe('Demo photo', function() {
browser.waitForAngularEnabled(false);

browser.sleep(3000);
element(by.xpath('html/body/webapp-app/div/div/webapp-johnlewis-landing/div/div/ul/li[2]/a/span')).click();

it('should load a demo room', function(){

    expect (browser.getTitle()).toEqual('John Lewis Wallpaper Visualiser: Design your room');

browser.sleep(3000);
});

});

Console

2 specs, 1 failure
Finished in 19.409 seconds

**************************************************
*                    Failures                    *
**************************************************

1) Demo photo should load a demo room
  - Expected 'John Lewis Wallpaper Visualiser: Welcome' to equal 'John
  Lewis Wallpaper Visualiser: Design your room'.

Executed 2 of 2 specs (1 FAILED) in 19 secs.
[12:08:21] I/launcher - 0 instance(s) of WebDriver still running
[12:08:21] I/launcher - chrome #01 failed 1 test(s)
[12:08:21] I/launcher - overall: 1 failed spec(s)
[12:08:21] E/launcher - Process exited with error code 1
Admins-MacBook:jl_autotests davidredmayne$


问:
Lambda expression question
```<code>string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

/*
 This code produces the following output:

 {index=0, str=}
 {index=1, str=b}
 {index=2, str=ma}
 {index=3, str=ora}
 {index=4, str=pass}
 {index=5, str=grape}
*/
</code>```

Could somebody explain, how "index" is associated here as array index of the elements?

Say, I need a query that instead of first letter returns me the whole object (string in this case) + associated index.

答:
To return the whole string in each case just modify the query thus:

```<code>var query =
    fruits.Select((fruit, index) =>
                  new { index, str = fruit });
</code>```

index is just that, the array element index.

ContentLicense: CC BY-SA 2.5

Title: Lambda expression question

Body:
string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

/*
 This code produces the following output:

 {index=0, str=}
 {index=1, str=b}
 {index=2, str=ma}
 {index=3, str=ora}
 {index=4, str=pass}
 {index=5, str=grape}
*/

Could somebody explain, how "index" is associated here as array index of the elements?

Say, I need a query that instead of first letter returns me the whole object (string in this case) + associated index.

Body:
To return the whole string in each case just modify the query thus:

var query =
    fruits.Select((fruit, index) =>
                  new { index, str = fruit });

index is just that, the array element index.


问:
Django QuerySet not appearing in HTML file for PythonAnywhere Web App
I'm having a bit of trouble with this part of the DjangoGirls tutorial (about templates).

Currently, my website is at chocoberrie.pythonanywhere.com. It's supposed to show a few posts inside the QuerySet, but the list is empty, and I don't know why (or how to fix it).

1) The QuerySet isn't loading at all in the HTML file.

I followed the steps to import the Post model into views.py and add the QuerySet in the posts variable (the previous part of the tutorial). When I tried putting {{ posts }} in the HTML file (post_list.html), nothing appears in the QuerySet that loads on the page.

2) I don't know how to edit the database file on PythonAnywhere. This database file is supposed to be separate from the local db.sqlite3 on my computer (since db.sqlite3 is in the .gitignore file, it's not committed).

I read about this here. I understand that this is useful to keep production changes from being displayed on the live website, but how I supposed to have this data on the PythonAnywhere side? What file am I supposed to edit on PythonAnywhere?

Thanks for the help, I appreciate it!

Here are my local files:

urls.py

```<code>from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.post_list, name='post_list'),
]
</code>```

views.py

```<code>from django.shortcuts import render
from django.utils import timezone
from .models import Post

def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'blog/post_list.html', {'posts': posts})
</code>```

post_list.html

```<code><html>
  <head>
    <title>Dina's blog</title>
  </head>
  <body>
    <div>
      <h1><a href="/">Dina's Blog</a></h1>
    </div>

    {{ posts }}

  </body>
</html>
</code>```

答:
I don't know if you have already done it or not, but when actually creating the posts you will also have to save it. So for example:

Example form.py

```<code>from django import forms

class createPostForm(forms.Form):
    title = forms.CharField(required = True)
    detail = forms.CharField(required = True)
</code>```

Example views.py

```<code>import models

def createPost(request):
    if request.method == 'POST':
        form = PostForm(request.POST)

        if form.is_valid():
            title = form.cleaned_data.get('title')
            detail = form.cleaned_data.get('detail')

            newPost = models.Post(title = title, detail = detail)
            newPost.save()
            return redirect('blog/post_list.html')
</code>```

Otherwise you won't be able to access it, since your website will take the inputs in and it will look like a post was created if the fields were valid, but your posts won't actually get created and your database will be empty! Also get a database viewer so that you can see if the entries are actually there.

Body:
I'm having a bit of trouble with this part of the DjangoGirls tutorial (about templates).

Currently, my website is at chocoberrie.pythonanywhere.com. It's supposed to show a few posts inside the QuerySet, but the list is empty, and I don't know why (or how to fix it).

1) The QuerySet isn't loading at all in the HTML file.

I followed the steps to import the Post model into views.py and add the QuerySet in the posts variable (the previous part of the tutorial). When I tried putting {{ posts }} in the HTML file (post_list.html), nothing appears in the QuerySet that loads on the page.

2) I don't know how to edit the database file on PythonAnywhere. This database file is supposed to be separate from the local db.sqlite3 on my computer (since db.sqlite3 is in the .gitignore file, it's not committed).

I read about this here. I understand that this is useful to keep production changes from being displayed on the live website, but how I supposed to have this data on the PythonAnywhere side? What file am I supposed to edit on PythonAnywhere?

Thanks for the help, I appreciate it!

Here are my local files:

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.post_list, name='post_list'),
]

views.py

from django.shortcuts import render
from django.utils import timezone
from .models import Post

def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'blog/post_list.html', {'posts': posts})

post_list.html

    <title>Dina's blog</title>

Dina's Blog

    {{ posts }}

Body:
I don't know if you have already done it or not, but when actually creating the posts you will also have to save it. So for example:

Example form.py

from django import forms

class createPostForm(forms.Form):
    title = forms.CharField(required = True)
    detail = forms.CharField(required = True)

Example views.py

import models

def createPost(request):
    if request.method == 'POST':
        form = PostForm(request.POST)

        if form.is_valid():
            title = form.cleaned_data.get('title')
            detail = form.cleaned_data.get('detail')

            newPost = models.Post(title = title, detail = detail)
            newPost.save()
            return redirect('blog/post_list.html')

Otherwise you won't be able to access it, since your website will take the inputs in and it will look like a post was created if the fields were valid, but your posts won't actually get created and your database will be empty! Also get a database viewer so that you can see if the entries are actually there.


答:
Add jQuery library and do like below:-

$(document).ready(function(){
  $('#j_username').on('input',function(){
    if($(this).val() =='admin'){
      $('#j_password').hide();
    }else{
      $('#j_password').show();
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>User Name</label>
     <input type='text' id="j_username" name='j_username' style='text-align: Left;' MaxLength='100' size='20' tabindex='1'/>
       <br/>
<label>Password</label>
<input type='password' id="j_password" name='j_password' value='' Align='Left' size='20' tabindex='2'/>
<br/></code>```

Note:- You use $ syntax which is jQuery syntax actually.

Title: JQuery hide/show from textbox

Body:
Add jQuery library and do like below:-

$(document).ready(function(){
  $('#j_username').on('input',function(){
    if($(this).val() =='admin'){
      $('#j_password').hide();
    }else{
      $('#j_password').show();
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>User Name</label>
     <input type='text' id="j_username" name='j_username' style='text-align: Left;' MaxLength='100' size='20' tabindex='1'/>
       <br/>
<label>Password</label>
<input type='password' id="j_password" name='j_password' value='' Align='Left' size='20' tabindex='2'/>
<br/>

Note:- You use $ syntax which is jQuery syntax actually.


问:
Providing YouTube video link (How to Play/Use) button in iOS app or game
Is it legal to make a button for YouTube tutorial link in app?

I have just started publishing games on iOS. It takes hours to upload a game(ipa) on iTunes Connect. It is very frustrating to upload your game again and wait for hours to upload. So definitely I don't want my game to get rejected. I tried google for this question but haven't found any thing related to that.

Is it legal to use same app preview(You Tube Video) that I have made for Google Play, to use in iOS preview video.

答:
See this post for the differences between an "App Preview video" vs "App Demo video"

App Preview: matches device screen sizes; shows only what the user sees on screen; is uploaded via iTunes Connect and appears in the App Store. Apple has specific guidelines to follow.

App Demo: for promotion or tutorial purposes; Can be any content you own & you post it on Youtube or your site or wherever you want.

You could include a link to an external Demo/Tutorial video in your app Settings or About content. However it might be better to include the video directly in the app so users don't have to exit their game to view it, especially if it's a "tutorial" on how to play, or in case they're offline. Better to make that video part of the UI/UX of the game or onboarding process. (If your video is too large to include in the app, it might be too long and complicated anyway).

For "App Preview" details, see Apple's docs on "Creating Videos for App Previews".

My comment above was not accurate - you are supposed to upload a separate preview video for each supported iOS device/size so it perfectly fits the device. It's also supposed to ONLY show real content from your app - no actors, ads, or overlays except for explanatory text and graphics indicating user interaction (e.g. displaying a "touch" or gesture).

Your single Android promo video probably will not cover all your needs:

"Each app preview is device-specific and requires iPhone, iPad, iPod
  touch, or Apple TV to view and submit. For iOS devices, you can submit
  a landscape and portrait version of your video. For Apple TV, your
  video must be in landscape orientation. Your final movie submitted to
  iTunes Connect must be in M4V, MP4, or MOV file format, less than 500
  MB, and saved at the following resolutions. For detailed technical
  specifications and step-by-step instructions on how to submit app
  previews, read the iTunes Connect Developer Guide."

The iTunes Connect Guide has specific details on App Preview video properties, including resolution, target bit rate, min/max length & files size, etc.

Using Quicktime you can capture the screen of different devices directly.
You can add audio separately in iMovie/Final Cut/some other video editing program.

Looks like you could meet the requirements with 4 different video resolutions:

1920 x 1080

1334 x 750

1200 x 900

1600 x 1200

You could try to crop & resize your existing video, if it only contains footage of your running app, but that might not work that well.

If your app supports a certain device or resolution, it should have a preview for it, ideally. Since App Previews are an optional feature anyway, you should be able to leave some out & not get rejected. I couldn't find any info about that.


问:
SQL join three tables in a query

I'm trying to join 3 tables in my query. Here's the situation:

I have two tables (inscription and fees) that have their secondary key in a third table.

Inscription

Bills

Fees

I can find inscriptions and fees in bills. I'm able to associate an inscription to bills but not able to associate fees to an inscription.

When an inscription is placed, there are some fees applied to that inscription plus an inscription price itself.
BillID can have both inscription price and fees applied.

The table bills is an intermediate. I believe that if I have a BillID I am able to assign the fee to an inscription. But that is my challenge.

```<code>select
*
from bills i
left join  Inscription ip
on ip.Idinscription = i.IDinscription
left join  fees f
on f.IDfee = i.Idfee
</code>```

When I have IDfee, IDinscription is null and when I have IDinscription, IDfee is null as well. Both bill and fee have the same IDbill.

results requested

答:
select distinct * from bills i left join Inscription ip on ip.Idinscription = i.IDinscription left join fees f on f.IDfee = i.Idfee where i.idfee is not null and i.idinscription is not null gives you a syntax issue? – Joseph Cho 20 mins ago

Thank You Mr Joseph Cho. Your query answered my question. I m gonna move my sql result to SSRS. Thank You – Blessed 2 mins ago   edit

Title: SQL join three tables in a query

Body:
I'm trying to join 3 tables in my query. Here's the situation:

I have two tables (inscription and fees) that have their secondary key in a third table.

Inscription

Bills

Fees

I can find inscriptions and fees in bills. I'm able to associate an inscription to bills but not able to associate fees to an inscription.

When an inscription is placed, there are some fees applied to that inscription plus an inscription price itself.
BillID can have both inscription price and fees applied.

The table bills is an intermediate. I believe that if I have a BillID I am able to assign the fee to an inscription. But that is my challenge.

select
*
from bills i
left join  Inscription ip
on ip.Idinscription = i.IDinscription
left join  fees f
on f.IDfee = i.Idfee

When I have IDfee, IDinscription is null and when I have IDinscription, IDfee is null as well. Both bill and fee have the same IDbill.

results requested


问:
Pandas: sum values in column if multiple values match str/contains/join
I am having trouble searching one list of numbers from one dataframe in the column of another. I am dealing with a case where different numbers refer to the same item.
I am having trouble searching one list of numbers from one dataframe in the column of another. I am dealing with a case where different numbers refer to the same item.

In my sample code, "term2" has entries with both code 'AAAA' and 'CCCC'.

```<code>    df1 = pd.DataFrame(
        {
        'term' : ['term1','term2','term3','term4','term1','term3','term2'],
        'code': ['ZZZZ', 'AAAA','XXXX','QQQQ','ZZZZ','XXXX','CCCC'],
        'count':['1','3','1','1','1','1','3']
        }
        )
df1 = df1[['term'] + df1.columns[:-1].tolist()]
df2 = pd.DataFrame(
        {
        'name': ['Dan','Sara','Conroy','Steve'],
        'rate': ['3','3.5','5.2','3'],
        'location': ['FL','OH','NM','NM'],
        'code': ['XXXX','BBBB','PPPP','TTTT'],
        'allcodes': ['XXXX,YYYY,ZZZZ','AAAA,BBBB,CCCC','PPPP,QQQQ,RRRR','SSSS,TTTT,UUUU']
         }
         )

df2 = df2[['name','rate','location','code','allcodes']]
pmissnlist = df1['code'].values.tolist()
df3 = df2[df2['allcodes'].str.contains('|'.join(pmissnlist))].reset_index()

df4 = pd.DataFrame(df3['allcodes'].str.split(',').tolist(),
                            index=df3.code).stack(level=0).reset_index(level=0)
matches = df4[df4[0].isin(df1.code)]
df5 = df3[df3.code.isin(matches.code)]
df5 = df5.drop_duplicates()#drops duplicate rows

df5_temp = df5.set_index(['name','rate','location','code']).allcodes.str.split(',',expand = True)\
                                  .stack().reset_index(4,drop = True).reset_index(name = 'allcodes')
df5 = pd.merge(df1, df5_temp, left_on = 'code', right_on = 'allcodes')
df5 = df5.drop('allcodes', 1).groupby(['code_y','term','count','name','rate','location']).code_x.\
                                    apply(','.join).reset_index().sort_values(by='count', ascending=False)
print(df5)
</code>```

The output is:

```<code>      code_y   term   count  name   rate  location  code_x
0     BBBB     term2  3      Sara   3.5   OH        AAAA,CCCC
1     PPPP     term4  1      Conroy 5.2   NM        QQQQ
2     XXXX     term1  1      Dan    3     FL        ZZZZ,ZZZZ
3     XXXX     term3  1      Dan    3     FL        XXXX,XXXX
</code>```

There are two instances of term2 associated with Sara, so I want her count to be 6, not 3. The counts should be 2 for each of Dan's rows, too. If I understand the dataframe correctly, this is expected: the dataframe contains the data that satisfies the condition of the first term2. When the second instance is compared, the related data already exists in the dataframe.

How do I sum the count values where multiple codes are matched in the "allcode" field of df2?

EDIT: Adding desired outcome

```<code>      code_y   term   count  name   rate  location  code_x
0     BBBB     term2  6      Sara   3.5   OH        AAAA,CCCC
1     PPPP     term4  1      Conroy 5.2   NM        QQQQ
2     XXXX     term1  2      Dan    3     FL        ZZZZ,ZZZZ
3     XXXX     term3  2      Dan    3     FL        XXXX,XXXX
</code>```

EDIT2:
The problem is with the groupby.

Here is the output of df5 BEFORE the statement with the groupby:

```<code>    term code_x  count    name rate location code_y allcodes
0  term1   ZZZZ      1     Dan    3       FL   XXXX     ZZZZ
1  term1   ZZZZ      1     Dan    3       FL   XXXX     ZZZZ
2  term2   AAAA      3    Sara  3.5       OH   BBBB     AAAA
3  term3   XXXX      1     Dan    3       FL   XXXX     XXXX
4  term3   XXXX      1     Dan    3       FL   XXXX     XXXX
5  term4   QQQQ      1  Conroy  5.2       NM   PPPP     QQQQ
6  term2   CCCC      2    Sara  3.5       OH   BBBB     CCCC
7  term6   TTTT      1   Steve    3       NM   TTTT     TTTT
</code>```

So, essentially I want counts for the column with the same term (term2 for Sara, and term3 & term4 for Dan) before the groupby.

答:
I created a small function to get the expected output.

```<code>def f(x):
     return pd.Series(dict(count = x['count'].sum(),
                        code_x = "%s" % ', '.join(x['code_x'])))

df5=df5.groupby(['code_y','term','name','rate','location'])[['code_x','count']].apply(f).reset_index()
</code>```

output

```<code>  code_y   term    name rate location      code_x  count
0   BBBB  term2    Sara  3.5       OH  AAAA, CCCC      6
1   PPPP  term4  Conroy  5.2       NM        QQQQ      1
2   XXXX  term1     Dan    3       FL  ZZZZ, ZZZZ      2
3   XXXX  term3     Dan    3       FL  XXXX, XXXX      2
</code>```

Inspired by https://stackoverflow.com/a/17841294/6626530

Body:
I am having trouble searching one list of numbers from one dataframe in the column of another. I am dealing with a case where different numbers refer to the same item.
I am having trouble searching one list of numbers from one dataframe in the column of another. I am dealing with a case where different numbers refer to the same item.

In my sample code, "term2" has entries with both code 'AAAA' and 'CCCC'.

    df1 = pd.DataFrame(
        {
        'term' : ['term1','term2','term3','term4','term1','term3','term2'],
        'code': ['ZZZZ', 'AAAA','XXXX','QQQQ','ZZZZ','XXXX','CCCC'],
        'count':['1','3','1','1','1','1','3']
        }
        )
df1 = df1[['term'] + df1.columns[:-1].tolist()]
df2 = pd.DataFrame(
        {
        'name': ['Dan','Sara','Conroy','Steve'],
        'rate': ['3','3.5','5.2','3'],
        'location': ['FL','OH','NM','NM'],
        'code': ['XXXX','BBBB','PPPP','TTTT'],
        'allcodes': ['XXXX,YYYY,ZZZZ','AAAA,BBBB,CCCC','PPPP,QQQQ,RRRR','SSSS,TTTT,UUUU']
         }
         )

df2 = df2[['name','rate','location','code','allcodes']]
pmissnlist = df1['code'].values.tolist()
df3 = df2[df2['allcodes'].str.contains('|'.join(pmissnlist))].reset_index()

df4 = pd.DataFrame(df3['allcodes'].str.split(',').tolist(),
                            index=df3.code).stack(level=0).reset_index(level=0)
matches = df4[df4[0].isin(df1.code)]
df5 = df3[df3.code.isin(matches.code)]
df5 = df5.drop_duplicates()#drops duplicate rows

df5_temp = df5.set_index(['name','rate','location','code']).allcodes.str.split(',',expand = True)\
                                  .stack().reset_index(4,drop = True).reset_index(name = 'allcodes')
df5 = pd.merge(df1, df5_temp, left_on = 'code', right_on = 'allcodes')
df5 = df5.drop('allcodes', 1).groupby(['code_y','term','count','name','rate','location']).code_x.\
                                    apply(','.join).reset_index().sort_values(by='count', ascending=False)
print(df5)

The output is:

      code_y   term   count  name   rate  location  code_x
0     BBBB     term2  3      Sara   3.5   OH        AAAA,CCCC
1     PPPP     term4  1      Conroy 5.2   NM        QQQQ
2     XXXX     term1  1      Dan    3     FL        ZZZZ,ZZZZ
3     XXXX     term3  1      Dan    3     FL        XXXX,XXXX

There are two instances of term2 associated with Sara, so I want her count to be 6, not 3. The counts should be 2 for each of Dan's rows, too. If I understand the dataframe correctly, this is expected: the dataframe contains the data that satisfies the condition of the first term2. When the second instance is compared, the related data already exists in the dataframe.

How do I sum the count values where multiple codes are matched in the "allcode" field of df2?

EDIT: Adding desired outcome

      code_y   term   count  name   rate  location  code_x
0     BBBB     term2  6      Sara   3.5   OH        AAAA,CCCC
1     PPPP     term4  1      Conroy 5.2   NM        QQQQ
2     XXXX     term1  2      Dan    3     FL        ZZZZ,ZZZZ
3     XXXX     term3  2      Dan    3     FL        XXXX,XXXX

EDIT2:
The problem is with the groupby.

Here is the output of df5 BEFORE the statement with the groupby:

    term code_x  count    name rate location code_y allcodes
0  term1   ZZZZ      1     Dan    3       FL   XXXX     ZZZZ
1  term1   ZZZZ      1     Dan    3       FL   XXXX     ZZZZ
2  term2   AAAA      3    Sara  3.5       OH   BBBB     AAAA
3  term3   XXXX      1     Dan    3       FL   XXXX     XXXX
4  term3   XXXX      1     Dan    3       FL   XXXX     XXXX
5  term4   QQQQ      1  Conroy  5.2       NM   PPPP     QQQQ
6  term2   CCCC      2    Sara  3.5       OH   BBBB     CCCC
7  term6   TTTT      1   Steve    3       NM   TTTT     TTTT

So, essentially I want counts for the column with the same term (term2 for Sara, and term3 & term4 for Dan) before the groupby.

Body:
I created a small function to get the expected output.

def f(x):
     return pd.Series(dict(count = x['count'].sum(),
                        code_x = "%s" % ', '.join(x['code_x'])))

df5=df5.groupby(['code_y','term','name','rate','location'])[['code_x','count']].apply(f).reset_index()

output

  code_y   term    name rate location      code_x  count
0   BBBB  term2    Sara  3.5       OH  AAAA, CCCC      6
1   PPPP  term4  Conroy  5.2       NM        QQQQ      1
2   XXXX  term1     Dan    3       FL  ZZZZ, ZZZZ      2
3   XXXX  term3     Dan    3       FL  XXXX, XXXX      2

Inspired by https://stackoverflow.com/a/17841294/6626530


问:
How do you detect/avoid Memory leaks in your (Unmanaged) code?
In unmanaged C/C++ code, what are the best practices to detect memory leaks? And coding guidelines to avoid? (As if it's that simple ;)

We have used a bit of a silly way in the past: having a counter increment for every memory allocation call and decrement while freeing. At the end of the program, the counter value should be zero.

I know this is not a great way and there are a few catches. (For instance, if you are freeing memory which was allocated by a platform API call, your allocation count will not exactly match your freeing count. Of course, then we incremented the counter when calling API calls that allocated memory.)

I am expecting your experiences, suggestions and maybe some references to tools which simplify this.

答:
Detect:

Debug CRT

Avoid:

Smart pointers, boehm GC

OwnerDisplayName: Prakash

OwnerDisplayName: DrPizza


问:
How to make a loading graphic in WPF XAML?
So I have a little WPF XAML that gets the titles of my RSS feed and puts them in a ListBox.

However, it takes about 2 seconds to load.

How can I have put some kind of AJAXy spinning graphic in the ListBox until the data is there?

Here is the code:

```<code><Window x:Class="WpfApplication5.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <StackPanel.Resources>
            <XmlDataProvider x:Key="ExternalColors" Source="http://www.tanguay.info/web/rss" XPath="/"/>
        </StackPanel.Resources>
        <TextBlock Text="RSS Feeds:"/>
        <ListBox Name="lbColor" Height="200" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource ExternalColors}, XPath=//item/title}"/>

        <TextBlock Text="You selected this feed:"/>
        <TextBox
            Text="{Binding ElementName=lbColor, Path=SelectedValue}"
            Background="{Binding ElementName=lbColor, Path=SelectedValue}">
        </TextBox>
    </StackPanel>
</Window>
</code>```

答: You could could create the spinny-loady-thingy and add it to the AdornerLayer of the ListBox.</p>

OwnerDisplayName: Edward Tanguay

Body:
So I have a little WPF XAML that gets the titles of my RSS feed and puts them in a ListBox.

However, it takes about 2 seconds to load.

How can I have put some kind of AJAXy spinning graphic in the ListBox until the data is there?

Here is the code:

<Window x:Class="WpfApplication5.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <StackPanel.Resources>
            <XmlDataProvider x:Key="ExternalColors" Source="http://www.tanguay.info/web/rss" XPath="/"/>
        </StackPanel.Resources>
        <TextBlock Text="RSS Feeds:"/>
        <ListBox Name="lbColor" Height="200" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource ExternalColors}, XPath=//item/title}"/>

        <TextBlock Text="You selected this feed:"/>
        <TextBox
            Text="{Binding ElementName=lbColor, Path=SelectedValue}"
            Background="{Binding ElementName=lbColor, Path=SelectedValue}">
        </TextBox>
    </StackPanel>
</Window>

OwnerDisplayName: Micah


问:
Why is replace() not working in Node.js?
I have some data I'm handling in Node.js and I need to replace the ampersands with the escape key. I have this code:

```<code>let newValue = data;
for (label in labelData.data) {
    let key = "Label " + label;
     newValue = newValue.replace(key, labelData.data[label]);

}
let noAmpersands = newValue.replace('&', '&');
console.log(noAmpersands);
</code>```

This code replaces placeholders in an SVG, but obviously the ampersands needed to be replaced with their escape character. However. this logs out the value without the ampersands replaced. For example, this:

```<code><g transform="matrix(1 0 0 1 -865.665 -1513.81)">
 <text x="3000" y="3750" id="text4790-27" class="fil1 fnt0" text-anchor="middle">EthCAN 3 &</text>
</code>```

should be

```<code><g transform="matrix(1 0 0 1 -865.665 -1513.81)">
 <text x="3000" y="3750" id="text4790-27" class="fil1 fnt0" text-anchor="middle">EthCAN 3 &</text>
</code>```

What's going on?

答:
Your end goal here is to encode HTML entities, There are various online articles and answers on how to achieve that. just google

If you just want to replace the &:
Assuming that newVlaue is a string

your code: newValue.replace('&', '&'); will only replace the first occurrence and not all occurrences. to replace all occurrences, use: newValue.replace(/&/g, '&');

Body:
I have some data I'm handling in Node.js and I need to replace the ampersands with the escape key. I have this code:

let newValue = data;
for (label in labelData.data) {
    let key = "Label " + label;
     newValue = newValue.replace(key, labelData.data[label]);

}
let noAmpersands = newValue.replace('&', '&');
console.log(noAmpersands);

This code replaces placeholders in an SVG, but obviously the ampersands needed to be replaced with their escape character. However. this logs out the value without the ampersands replaced. For example, this:

<g transform="matrix(1 0 0 1 -865.665 -1513.81)">
 <text x="3000" y="3750" id="text4790-27" class="fil1 fnt0" text-anchor="middle">EthCAN 3 &</text>

should be

<g transform="matrix(1 0 0 1 -865.665 -1513.81)">
 <text x="3000" y="3750" id="text4790-27" class="fil1 fnt0" text-anchor="middle">EthCAN 3 &</text>

What's going on?

Body:
Your end goal here is to encode HTML entities, There are various online articles and answers on how to achieve that. just google

If you just want to replace the &:
Assuming that newVlaue is a string

your code: newValue.replace('&', '&amp;'); will only replace the first occurrence and not all occurrences. to replace all occurrences, use: newValue.replace(/&/g, '&amp;');


问:
factory pattern in autofac
I want to implement factory pattern in Autofac. This is how it was done in Ninject:

```<code>Bind<ICarFilter>().To<CarFilter >();
Bind<IBikeFilter>().To<BikeFilter>();
Bind<IFilterFacade>().ToFactory().InSingletonScope();
</code>```

This is a definitnion of IFilterFacade

```<code>public interface IFilterFacade
    {
        ICarFilter CreateCarFilter();

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

If I want an instance of CarFilter type, all I need to do is the following:

```<code>public class HomeController(IFilterFacade filterFacade)
{
    FilterFacade = filterFacade;
}

public IFilterFacade FilterFacade { get;set; }

public ActionResult Index()
{
  var bikeFilter = FilterFacade.CreateBikeFilter();
}
</code>```

Any example how to do that in AutoFac. I checked AutoFac documentation, but was not able to find the answer or example.

答:
Autofac has no such feature as dynamically implementing user-defined factory interface. It does allow binding to delegates, but it's not the same.

If you want to receive a kind of factory in constructor, then obtain individual components from that factory in relevant methods, it is definitely possible with Autofac.

Composition root

Here I register individual components as singletons (this was the behavior with Ninject, if I get it correctly), but you can use any lifetime option that fits your requirements.

```<code>ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<BikeFilter>().As<IBikeFilter>().SingleInstance();
builder.RegisterType<CarFilter>().As<ICarFilter>().SingleInstance();
</code>```

Controller

```<code>public class HomeController
{
    private readonly IComponentContext _components;

    public HomeController(IComponentContext components)
    {
        _components = components; // instead of factory interface
    }

    public ActionResult Index()
    {
        var bikeFilter = _components.Resolve<IBikeFilter>();
        // ...
    }
}
</code>```

BTW

I think that factory interface is a nice feature of Ninject. Another added value of it is allowing to explore through IntelliSense. In your example, when I type FilterFacade and the dot character, I'm presented with a list of supported filters (CreateCarFilter, CreateBikeFilter, ...). So that even if I'm not fully familiar with the project codebase, I can pick one that fits best. With Autofac, IComponentContext allows me request any component, which doesn't help me find out what relevant components exist, or which components I'm expected to request.

Title: factory pattern in autofac

Body:
I want to implement factory pattern in Autofac. This is how it was done in Ninject:

Bind<ICarFilter>().To<CarFilter >();
Bind<IBikeFilter>().To<BikeFilter>();
Bind<IFilterFacade>().ToFactory().InSingletonScope();

This is a definitnion of IFilterFacade

public interface IFilterFacade
    {
        ICarFilter CreateCarFilter();

        IBikeFIlter CreateBikeFilter();
    }

If I want an instance of CarFilter type, all I need to do is the following:

public class HomeController(IFilterFacade filterFacade)
{
    FilterFacade = filterFacade;
}

public IFilterFacade FilterFacade { get;set; }

public ActionResult Index()
{
  var bikeFilter = FilterFacade.CreateBikeFilter();
}

Any example how to do that in AutoFac. I checked AutoFac documentation, but was not able to find the answer or example.

Body:
Autofac has no such feature as dynamically implementing user-defined factory interface. It does allow binding to delegates, but it's not the same.

If you want to receive a kind of factory in constructor, then obtain individual components from that factory in relevant methods, it is definitely possible with Autofac.

Composition root

Here I register individual components as singletons (this was the behavior with Ninject, if I get it correctly), but you can use any lifetime option that fits your requirements.

ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<BikeFilter>().As<IBikeFilter>().SingleInstance();
builder.RegisterType<CarFilter>().As<ICarFilter>().SingleInstance();

Controller

public class HomeController
{
    private readonly IComponentContext _components;

    public HomeController(IComponentContext components)
    {
        _components = components; // instead of factory interface
    }

    public ActionResult Index()
    {
        var bikeFilter = _components.Resolve<IBikeFilter>();
        // ...
    }
}

BTW

I think that factory interface is a nice feature of Ninject. Another added value of it is allowing to explore through IntelliSense. In your example, when I type FilterFacade and the dot character, I'm presented with a list of supported filters (CreateCarFilter, CreateBikeFilter, ...). So that even if I'm not fully familiar with the project codebase, I can pick one that fits best. With Autofac, IComponentContext allows me request any component, which doesn't help me find out what relevant components exist, or which components I'm expected to request.


问:
CMake: how to use INTERFACE_INCLUDE_DIRECTORIES with ExternalProject?
I'm trying to add external project as a library to my project using ExternalProject_Add:

```<code>ExternalProject_Add(
        xgboost
        GIT_REPOSITORY https://github.com/dmlc/xgboost.git
        GIT_TAG v0.60
        PREFIX ${CMAKE_CURRENT_BINARY_DIR}
        INSTALL_COMMAND ""
)
</code>```

Also, I'm defining library target and adding external project as a dependency:

```<code>set(XGBOOST_PREFIX_PATH "${CMAKE_CURRENT_BINARY_DIR}/src")
set(XGBOOST_BINARY_PATH "${XGBOOST_PREFIX_PATH}/xgboost-build")
set(XGBOOST_BINARY_INCLUDE "${XGBOOST_PREFIX_PATH}/xgboost/include;${XGBOOST_PREFIX_PATH}/xgboost/dmlc-core/include;${XGBOOST_PREFIX_PATH}/xgboost/rabit/include")
add_library(libxgboost IMPORTED STATIC GLOBAL)
add_dependencies(libxgboost xgboost)

set_target_properties(libxgboost PROPERTIES
        "IMPORTED_LOCATION" "${XGBOOST_BINARY_PATH}/liblibxgboost.dylib"
        "IMPORTED_LINK_INTERFACE_LIBRARIES" "${CMAKE_THREAD_LIBS_INIT}"
        "INTERFACE_INCLUDE_DIRECTORIES" "${XGBOOST_BINARY_INCLUDE}"
        )
</code>```

in another CMakeLists.txt:

```<code>add_library(somelib STATIC SomeLib.cpp)
target_include_directories(somelib PUBLIC libxgboost)
target_link_libraries(somelib libxgboost)
</code>```

The problem is that cmake INTERFACE_INCLUDE_DIRECTORIES doesn't allow to export include dir which does not exist.

Is there any other way to make header files being included automatically for all targets which depend on libxgboost ?

UPDATE:

Error message:

```<code>CMake Error in somelib/CMakeLists.txt:
  Imported target "libxgboost" includes non-existent path

    "build/xgboost/src/xgboost/include"

  in its INTERFACE_INCLUDE_DIRECTORIES.  Possible reasons include:

  * The path was deleted, renamed, or moved to another location.

  * An install or uninstall procedure did not complete successfully.

  * The installation package was faulty and references files it does not
  provide.
</code>```

答:
I'll post the final CMakeLists.txt to include xgboost into your project, it might be useful for someone, the solution to the problem above is to create directories during cmake configure phase (NOTE: I'm using OSX to build that, so you would need to use liblibxgboost.so for GNU/Linux instead of liblibxgboost.dylib):

```<code>include(ExternalProject)

ExternalProject_Add(
        xgboost
        GIT_REPOSITORY https://github.com/dmlc/xgboost.git
        GIT_TAG v0.60
        PREFIX ${CMAKE_CURRENT_BINARY_DIR}
        INSTALL_COMMAND ""
)

set(XGBOOST_PREFIX_PATH "${CMAKE_CURRENT_BINARY_DIR}/src")
set(XGBOOST_BINARY_PATH "${XGBOOST_PREFIX_PATH}/xgboost-build")

set(XGBOOST_LIB_INCLUDE "${XGBOOST_PREFIX_PATH}/xgboost/include")
set(DMLC_LIB_INCLUDE "${XGBOOST_PREFIX_PATH}/xgboost/dmlc-core/include")
set(RABIT_LIB_INCLUDE "${XGBOOST_PREFIX_PATH}/xgboost/rabit/include")
set(XGBOOST_BINARY_INCLUDE "${XGBOOST_LIB_INCLUDE};${DMLC_LIB_INCLUDE};${RABIT_LIB_INCLUDE}")

# Hack to make it work, otherwise INTERFACE_INCLUDE_DIRECTORIES will not be propagated
file(MAKE_DIRECTORY ${XGBOOST_LIB_INCLUDE})
file(MAKE_DIRECTORY ${DMLC_LIB_INCLUDE})
file(MAKE_DIRECTORY ${RABIT_LIB_INCLUDE})

add_library(libxgboost IMPORTED STATIC GLOBAL)
add_dependencies(libxgboost xgboost)

set_target_properties(libxgboost PROPERTIES
        "IMPORTED_LOCATION" "${XGBOOST_BINARY_PATH}/liblibxgboost.dylib"
        "INTERFACE_INCLUDE_DIRECTORIES" "${XGBOOST_BINARY_INCLUDE}"
)
</code>```

Body:
I'm trying to add external project as a library to my project using ExternalProject_Add:

ExternalProject_Add(
        xgboost
        GIT_REPOSITORY https://github.com/dmlc/xgboost.git
        GIT_TAG v0.60
        PREFIX ${CMAKE_CURRENT_BINARY_DIR}
        INSTALL_COMMAND ""
)

Also, I'm defining library target and adding external project as a dependency:

set(XGBOOST_PREFIX_PATH "${CMAKE_CURRENT_BINARY_DIR}/src")
set(XGBOOST_BINARY_PATH "${XGBOOST_PREFIX_PATH}/xgboost-build")
set(XGBOOST_BINARY_INCLUDE "${XGBOOST_PREFIX_PATH}/xgboost/include;${XGBOOST_PREFIX_PATH}/xgboost/dmlc-core/include;${XGBOOST_PREFIX_PATH}/xgboost/rabit/include")
add_library(libxgboost IMPORTED STATIC GLOBAL)
add_dependencies(libxgboost xgboost)

set_target_properties(libxgboost PROPERTIES
        "IMPORTED_LOCATION" "${XGBOOST_BINARY_PATH}/liblibxgboost.dylib"
        "IMPORTED_LINK_INTERFACE_LIBRARIES" "${CMAKE_THREAD_LIBS_INIT}"
        "INTERFACE_INCLUDE_DIRECTORIES" "${XGBOOST_BINARY_INCLUDE}"
        )

in another CMakeLists.txt:

add_library(somelib STATIC SomeLib.cpp)
target_include_directories(somelib PUBLIC libxgboost)
target_link_libraries(somelib libxgboost)

The problem is that cmake INTERFACE_INCLUDE_DIRECTORIES doesn't allow to export include dir which does not exist.

Is there any other way to make header files being included automatically for all targets which depend on libxgboost ?

UPDATE:

Error message:

CMake Error in somelib/CMakeLists.txt:
  Imported target "libxgboost" includes non-existent path

    "build/xgboost/src/xgboost/include"

  in its INTERFACE_INCLUDE_DIRECTORIES.  Possible reasons include:

  * The path was deleted, renamed, or moved to another location.

  * An install or uninstall procedure did not complete successfully.

  * The installation package was faulty and references files it does not
  provide.

Body:
I'll post the final CMakeLists.txt to include xgboost into your project, it might be useful for someone, the solution to the problem above is to create directories during cmake configure phase (NOTE: I'm using OSX to build that, so you would need to use liblibxgboost.so for GNU/Linux instead of liblibxgboost.dylib):

include(ExternalProject)

ExternalProject_Add(
        xgboost
        GIT_REPOSITORY https://github.com/dmlc/xgboost.git
        GIT_TAG v0.60
        PREFIX ${CMAKE_CURRENT_BINARY_DIR}
        INSTALL_COMMAND ""
)

set(XGBOOST_PREFIX_PATH "${CMAKE_CURRENT_BINARY_DIR}/src")
set(XGBOOST_BINARY_PATH "${XGBOOST_PREFIX_PATH}/xgboost-build")

set(XGBOOST_LIB_INCLUDE "${XGBOOST_PREFIX_PATH}/xgboost/include")
set(DMLC_LIB_INCLUDE "${XGBOOST_PREFIX_PATH}/xgboost/dmlc-core/include")
set(RABIT_LIB_INCLUDE "${XGBOOST_PREFIX_PATH}/xgboost/rabit/include")
set(XGBOOST_BINARY_INCLUDE "${XGBOOST_LIB_INCLUDE};${DMLC_LIB_INCLUDE};${RABIT_LIB_INCLUDE}")

# Hack to make it work, otherwise INTERFACE_INCLUDE_DIRECTORIES will not be propagated
file(MAKE_DIRECTORY ${XGBOOST_LIB_INCLUDE})
file(MAKE_DIRECTORY ${DMLC_LIB_INCLUDE})
file(MAKE_DIRECTORY ${RABIT_LIB_INCLUDE})

add_library(libxgboost IMPORTED STATIC GLOBAL)
add_dependencies(libxgboost xgboost)

set_target_properties(libxgboost PROPERTIES
        "IMPORTED_LOCATION" "${XGBOOST_BINARY_PATH}/liblibxgboost.dylib"
        "INTERFACE_INCLUDE_DIRECTORIES" "${XGBOOST_BINARY_INCLUDE}"
)


答:
You could use apply but note that the output will be a matrix

```<code>t(apply(df, 1, function(x){
    replace(x, is.na(x), x[cumsum(!is.na(x))][is.na(x)])
}))
#     v1 v2 v3
#[1,] 10 10  1
#[2,] 11  1  1
#[3,] 12 12 12
#[4,] 13  3  9
#[5,] 14  6  4
</code>```

Title: fill column with previous column if NA

Body:
I have a data frame like this

df <- data.frame(v1 = 10:14, v2 = c(NA, 1, NA, 3, 6), v3 = c(1, NA, NA, 9, 4))

  v1 v2 v3
1 10 NA  1
2 11  1 NA
3 12 NA NA
4 13  3  9
5 14  6  4

I now want to fill the NAs with the value of the previous column, so it looks like this:

  v1 v2 v3
1 10 10  1
2 11  1  1
3 12 12 12
4 13  3  9
5 14  6  4

I know how to do this manually, like this:

df$v2 <- ifelse(is.na(df$v2), df$v1, df$v2)

How can I automate this for a full data frame with many columns?

Body:
You could use apply but note that the output will be a matrix

t(apply(df, 1, function(x){
    replace(x, is.na(x), x[cumsum(!is.na(x))][is.na(x)])
}))
#     v1 v2 v3
#[1,] 10 10  1
#[2,] 11  1  1
#[3,] 12 12 12
#[4,] 13  3  9
#[5,] 14  6  4


问:
Getting selected text when UIMenuController is shown
When the user selects some text in UITextView or UIWebView, UIMenuController is shown. Is there any way to access this selected text programmitically?

I need it because I want to add custom item to UIMenuController: 'Search' option which will be intended to search for selected text in database.

Is it possible without using 'Copy' item in order to copy the text to pasteboard and then getting it from UIPasteBoard with the next time? - I am not interested in such workaround.

答:
Did you have a look at Apple's documentation.You can use the MenuItems property provided to create your custom UIMenuController.Have a look at the image below

and follow this

link for details.

You can also have a look at the sample code provided by Apple to understand that feature.

http://developer.apple.com/library/ios/#samplecode/TableViewUpdates/Introduction/Intro.html#//apple_ref/doc/uid/DTS40010139

In this sample code they have show "Email" in the UIMenuController.

So go ahead and code...All the best...

Cheers


问:
SQL Server: Group By 30 Day Windows
I have developed this SQL script to do a Group By on 30 day windows:

```<code>SELECT MIN(id.customer_id),
       DATEADD(DAY, DATEDIFF(DAY, 0, e.transaction_datetime) / 30 * 30, 0) as [window_start_dt],
       DATEADD(DAY, DATEDIFF(DAY, -30, e.transaction_datetime) / 30 * 30, 0) as [window_end_dt],
FROM event as e
INNER JOIN customer_identity as id
      ON id.customer_id = e.customer_id
WHERE e.transaction_datetime BETWEEN '2003-01-06' AND '2017-12-31'
GROUP BY id.customer_id,
      DATEADD(DAY, DATEDIFF(DAY, 0, e.transaction_datetime) / 30 * 30, 0),
      DATEADD(DAY, DATEDIFF(DAY, -30, e.transaction_datetime) / 30 * 30, 0)
ORDER BY [window_start_dt], [window_end_dt]
</code>```

Which results in the this:

```<code>customer_id,window_start_dt,window_end_dt
1,2003-01-06,2003-02-05
</code>```

However that is not exactly the 30 day window that I want:

```<code>customer_id,window_start_dt,window_end_dt
1,2003-01-06,2003-02-05
</code>```

So my issue is with the window_end_dt being off.  Currently, I am using a -30 in a DATEDIFF which is a little odd, so I would be welcome to a better way for the window_end_dt.

EDIT:

Here is small example dataset for the first month at least:

```<code>customer_id, transaction_datetime
1, 2013-02-04
1, 2013-01-21
1, 2013-01-22
1, 2013-01-27
2, 2013-02-02
2, 2013-01-08
2, 2013-01-19
2, 2013-01-21
3, 2013-02-03
3, 2013-01-15
3, 2013-01-19
</code>```

Additionally, I would like to be able to pick an arbitrary start date for the windowing to begin if possible (not aligned to months). For example, I'd like to ideally start the windows on 2003-01-06.

Edit:

I made changes to reflect to the desired 2003-01-06 start date for 30 day windows and to avoid confusion. There are additional columns I am calculating in these windows. But I have removed them to keep it simple and focus on the date logic for the group bys.

答:
I'm confused as to the ultimate goal, but you can make your running date window with a cte and then just join to it...

```<code>declare @startDate date = '20130101' --or perhaps select min(transaction_datetime) from your table
declare @endDate date = '20130301'   --or perhaps select max(transaction_datetime) from your table

;with dates as(
    select TheDate = @startDate
    union all
    select TheDate = dateadd(day,30,TheDate)
    from dates
    where TheDate <= @endDate
)

select
    StartWindow = TheDate
    ,EndWindow = dateadd(day,29,TheDate)
from dates
option (maxrecursion 0)
</code>```

So with your data.... perhaps something like this....

```<code>declare @table table (customer_id int, transaction_datetime datetime)
insert into @table
values
(1, '2013-01-06'),
(1, '2013-01-21'),
(1, '2013-01-22'),
(1, '2013-01-27'),
(2, '2013-01-02'),
(2, '2013-01-08'),
(2, '2013-01-19'),
(2, '2013-01-21'),
(3, '2013-01-27'),
(3, '2013-01-15'),
(3, '2013-01-19'),
(3, '2013-02-19'),    --I the following 3 rows this to show where id could fall in multiple windows
(3, '2013-03-14'),
(3, '2013-01-29')

declare @startDate date = '20130101'
declare @endDate date = (select max(transaction_datetime ) from @table)

;with dates as(
    select TheDate = @startDate
    union all
    select TheDate = dateadd(day,30,TheDate)
    from dates
    where TheDate <= @endDate
)

select distinct
    customer_id
    ,StartWindow = TheDate
    ,EndWindow = dateadd(day,29,TheDate)
from @table
    inner join dates on
    transaction_datetime between TheDate and dateadd(day,29,TheDate)
option (maxrecursion 0)
</code>```

RETURNS

```<code>+-------------+-------------+------------+
| customer_id | StartWindow | EndWindow  |
+-------------+-------------+------------+
|           1 | 2013-01-01  | 2013-01-30 |
|           2 | 2013-01-01  | 2013-01-30 |
|           3 | 2013-01-01  | 2013-01-30 |
|           3 | 2013-01-31  | 2013-03-01 |
|           3 | 2013-03-02  | 2013-03-31 |
+-------------+-------------+------------+
</code>```

Title: SQL Server: Group By 30 Day Windows

Body:
I have developed this SQL script to do a Group By on 30 day windows:

SELECT MIN(id.customer_id),
       DATEADD(DAY, DATEDIFF(DAY, 0, e.transaction_datetime) / 30 * 30, 0) as [window_start_dt],
       DATEADD(DAY, DATEDIFF(DAY, -30, e.transaction_datetime) / 30 * 30, 0) as [window_end_dt],
FROM event as e
INNER JOIN customer_identity as id
      ON id.customer_id = e.customer_id
WHERE e.transaction_datetime BETWEEN '2003-01-06' AND '2017-12-31'
GROUP BY id.customer_id,
      DATEADD(DAY, DATEDIFF(DAY, 0, e.transaction_datetime) / 30 * 30, 0),
      DATEADD(DAY, DATEDIFF(DAY, -30, e.transaction_datetime) / 30 * 30, 0)
ORDER BY [window_start_dt], [window_end_dt]

Which results in the this:

customer_id,window_start_dt,window_end_dt
1,2003-01-06,2003-02-05

However that is not exactly the 30 day window that I want:

customer_id,window_start_dt,window_end_dt
1,2003-01-06,2003-02-05

So my issue is with the window_end_dt being off.  Currently, I am using a -30 in a DATEDIFF which is a little odd, so I would be welcome to a better way for the window_end_dt.

EDIT:

Here is small example dataset for the first month at least:

customer_id, transaction_datetime
1, 2013-02-04
1, 2013-01-21
1, 2013-01-22
1, 2013-01-27
2, 2013-02-02
2, 2013-01-08
2, 2013-01-19
2, 2013-01-21
3, 2013-02-03
3, 2013-01-15
3, 2013-01-19

Additionally, I would like to be able to pick an arbitrary start date for the windowing to begin if possible (not aligned to months). For example, I'd like to ideally start the windows on 2003-01-06.

Edit:

I made changes to reflect to the desired 2003-01-06 start date for 30 day windows and to avoid confusion. There are additional columns I am calculating in these windows. But I have removed them to keep it simple and focus on the date logic for the group bys.

Body:
I'm confused as to the ultimate goal, but you can make your running date window with a cte and then just join to it...

declare @startDate date = '20130101' --or perhaps select min(transaction_datetime) from your table
declare @endDate date = '20130301'   --or perhaps select max(transaction_datetime) from your table

;with dates as(
    select TheDate = @startDate
    union all
    select TheDate = dateadd(day,30,TheDate)
    from dates
    where TheDate <= @endDate
)

select
    StartWindow = TheDate
    ,EndWindow = dateadd(day,29,TheDate)
from dates
option (maxrecursion 0)

So with your data.... perhaps something like this....

declare @table table (customer_id int, transaction_datetime datetime)
insert into @table
values
(1, '2013-01-06'),
(1, '2013-01-21'),
(1, '2013-01-22'),
(1, '2013-01-27'),
(2, '2013-01-02'),
(2, '2013-01-08'),
(2, '2013-01-19'),
(2, '2013-01-21'),
(3, '2013-01-27'),
(3, '2013-01-15'),
(3, '2013-01-19'),
(3, '2013-02-19'),    --I the following 3 rows this to show where id could fall in multiple windows
(3, '2013-03-14'),
(3, '2013-01-29')

declare @startDate date = '20130101'
declare @endDate date = (select max(transaction_datetime ) from @table)

;with dates as(
    select TheDate = @startDate
    union all
    select TheDate = dateadd(day,30,TheDate)
    from dates
    where TheDate <= @endDate
)

select distinct
    customer_id
    ,StartWindow = TheDate
    ,EndWindow = dateadd(day,29,TheDate)
from @table
    inner join dates on
    transaction_datetime between TheDate and dateadd(day,29,TheDate)
option (maxrecursion 0)

RETURNS

+-------------+-------------+------------+
| customer_id | StartWindow | EndWindow  |
+-------------+-------------+------------+
|           1 | 2013-01-01  | 2013-01-30 |
|           2 | 2013-01-01  | 2013-01-30 |
|           3 | 2013-01-01  | 2013-01-30 |
|           3 | 2013-01-31  | 2013-03-01 |
|           3 | 2013-03-02  | 2013-03-31 |
+-------------+-------------+------------+


问:
How do I pop() from a list without using pop()?
I have a function called pop_item() that I am trying to make act like a pop() that works with the list class, how would I do that, here is my code:
    def empty(lst):
        return lst == []

```<code>def pop_item(lst):
    lst = lst[::-1]
    new_lst = []
    for i in lst:
        if i != lst[-1]:
            new_lst += [i]
    lst = new_lst
    return lst

def main():
    todo = [1,2,3,4]

    print(todo) #prints [1,2,3,4] as expected

    print('\n' + 75 * '_' + '\n')

    print(pop_item(todo)) #pop the item off
    print(todo) #output should then be [1,2,3]

if __name__ == '__main__':
    main()
</code>```

Note: I am not allowed to use any built in functions eg len(),index,del() etc.

答:
Here are a few variants of popping items from a list without using list functions, only slicing & list comprehension

pop the last item using slicing & slicing assignment:

```<code>def pop_item(lst):
    lst[:] = lst[:-1]
</code>```

pop a valued item (last one but can be a parameter) by rebuilding the list & slice assign

```<code>def pop_item(lst):
    lst[:] = [x for x in lst if x!=lst[-1]]
</code>```

(that can pop other items in the list if they have the same value)

by speciftying item position/index in the list:

```<code>def pop_item(lst,item_position):
    lst[:] = [x for i,x in enumerate(lst) if i!=item_position]
</code>```

Body:
I have a function called pop_item() that I am trying to make act like a pop() that works with the list class, how would I do that, here is my code:
    def empty(lst):
        return lst == []

def pop_item(lst):
    lst = lst[::-1]
    new_lst = []
    for i in lst:
        if i != lst[-1]:
            new_lst += [i]
    lst = new_lst
    return lst

def main():
    todo = [1,2,3,4]

    print(todo) #prints [1,2,3,4] as expected

    print('\n' + 75 * '_' + '\n')

    print(pop_item(todo)) #pop the item off
    print(todo) #output should then be [1,2,3]

if __name__ == '__main__':
    main()

Note: I am not allowed to use any built in functions eg len(),index,del() etc.

Body:
Here are a few variants of popping items from a list without using list functions, only slicing & list comprehension

pop the last item using slicing & slicing assignment:

def pop_item(lst):
    lst[:] = lst[:-1]

pop a valued item (last one but can be a parameter) by rebuilding the list & slice assign

def pop_item(lst):
    lst[:] = [x for x in lst if x!=lst[-1]]

(that can pop other items in the list if they have the same value)

by speciftying item position/index in the list:

def pop_item(lst,item_position):
    lst[:] = [x for i,x in enumerate(lst) if i!=item_position]


问:
fill column with previous column if NA
I have a data frame like this

```<code>df <- data.frame(v1 = 10:14, v2 = c(NA, 1, NA, 3, 6), v3 = c(1, NA, NA, 9, 4))

  v1 v2 v3
1 10 NA  1
2 11  1 NA
3 12 NA NA
4 13  3  9
5 14  6  4
</code>```

I now want to fill the NAs with the value of the previous column, so it looks like this:

```<code>  v1 v2 v3
1 10 10  1
2 11  1  1
3 12 12 12
4 13  3  9
5 14  6  4
</code>```

I know how to do this manually, like this:

```<code>df$v2 <- ifelse(is.na(df$v2), df$v1, df$v2)
</code>```

How can I automate this for a full data frame with many columns?

答:
You can do this with fill from tidyr:

```<code>library(dplyr)
library(tidyr)

data.frame(t(df)) %>%
  fill(., names(.)) %>%
  t()
</code>```

Result:

```<code>   v1 v2 v3
X1 10 10  1
X2 11  1  1
X3 12 12 12
X4 13  3  9
X5 14  6  4
</code>```

Note:

Basically, I transposed df, filled every column downward, then transposed it back to the original orientation

Title: fill column with previous column if NA

Body:
You can do this with fill from tidyr:

library(dplyr)
library(tidyr)

data.frame(t(df)) %>%
  fill(., names(.)) %>%
  t()

Result:

   v1 v2 v3
X1 10 10  1
X2 11  1  1
X3 12 12 12
X4 13  3  9
X5 14  6  4

Note:

Basically, I transposed df, filled every column downward, then transposed it back to the original orientation


问:
In-place type conversion of a NumPy array
Given a NumPy array of int32, how do I convert it to float32 in place?  So basically, I would like to do

```<code>a = a.astype(numpy.float32)
</code>```

without copying the array.  It is big.

The reason for doing this is that I have two algorithms for the computation of a.  One of them returns an array of int32, the other returns an array of float32 (and this is inherent to the two different algorithms).  All further computations assume that a is an array of float32.

Currently I do the conversion in a C function called via ctypes.  Is there a way to do this in Python?

答: a = np.subtract(a, 0., dtype=np.float32)

Body:
Given a NumPy array of int32, how do I convert it to float32 in place?  So basically, I would like to do

a = a.astype(numpy.float32)

without copying the array.  It is big.

The reason for doing this is that I have two algorithms for the computation of a.  One of them returns an array of int32, the other returns an array of float32 (and this is inherent to the two different algorithms).  All further computations assume that a is an array of float32.

Currently I do the conversion in a C function called via ctypes.  Is there a way to do this in Python?


问:
Set URL of "like" button embedded in Facebook comments plugin
How can I set the URL of the "like" button embedded in the Facebook comments plugin?

The XFBML <fb:like> tag has an href attribute, but the <fb:comments> tag lacks an equivalent attribute.

答:
updated for new version of Facebook comments plugin:

The new Facebook comments plugin no longer uses the xid attribute. Instead, the href attribute is used to both identify the comments box and associate a URL with it.

Compare new <fb:comments> to legacy <fb:comments>

original answer:

Figured it out while asking the question:

The <fb:comments> url attribute works like the <fb:like> href attribute.


问:
templatetag: QuerySet' object has no attribute 'getlist'
I'm greeted with the following error when attempting to follow a books example of templatetags with modification:

```<code>QuerySet' object has no attribute 'getlist'report_id=88&report_id=89 HTTP/1.1" 500 180158
</code>```

I'm following the instructions of adding templatetags to my app directory and included the init.py and the app_filter.py i'd like to filter on, as such:

```<code>Security

        accounts

           templatetags

                app_filters.py

                __init__.py
</code>```

My app_filter.py is defined as such:

```<code>from django import template
register = template.Library()

@register.filter
def get_list(querydict, itemToGet ):

    return querydict.getlist(itemToGet)
</code>```

My settings.py includes the following:

```<code>INSTALLED_APPS = [
    'django_python3_ldap',
    'django_extensions',
    'django_filters',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts',
]
</code>```

My view is passing the array correctly:

```<code>checked = request.GET.get('report_id')
checkedlist = request.GET.getlist('report_id')

reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True)

print (checked)
print (checkedlist)

args = {'retreivecheckbox': reportlist}

return render(request,'accounts/requestaccess.html', args)
</code>```

I see the array in my console, when doing a print checkedlist:

```<code>['75', '76', '77']
</code>```

My template is the following:

```<code>{% load app_filters %}
{% for reports in retreivecheckbox %}

        {{ retreivecheckbox|get_list:'report_id' }}
    </div>
{% endfor %}
</code>```

答:
I had to use {{ retreivecheckbox|get_list:report_id }}

and not {{ retreivecheckbox|get_list:'report_id' }}

```<code>{% load app_filters %}
{% for reports in retreivecheckbox %}

        {{ retreivecheckbox|get_list:report_name_sc }}

    </div>
{% endfor %}
</code>```

Body:
I'm greeted with the following error when attempting to follow a books example of templatetags with modification:

QuerySet' object has no attribute 'getlist'report_id=88&report_id=89 HTTP/1.1" 500 180158

I'm following the instructions of adding templatetags to my app directory and included the init.py and the app_filter.py i'd like to filter on, as such:

Security

        accounts

           templatetags

                app_filters.py

                __init__.py

My app_filter.py is defined as such:

from django import template
register = template.Library()

@register.filter
def get_list(querydict, itemToGet ):

    return querydict.getlist(itemToGet)

My settings.py includes the following:

INSTALLED_APPS = [
    'django_python3_ldap',
    'django_extensions',
    'django_filters',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts',
]

My view is passing the array correctly:

checked = request.GET.get('report_id')
checkedlist = request.GET.getlist('report_id')

reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True)

print (checked)
print (checkedlist)

args = {'retreivecheckbox': reportlist}

return render(request,'accounts/requestaccess.html', args)

I see the array in my console, when doing a print checkedlist:

['75', '76', '77']

My template is the following:

{% load app_filters %}
{% for reports in retreivecheckbox %}

        {{ retreivecheckbox|get_list:'report_id' }}

{% endfor %}

Body:
I had to use {{ retreivecheckbox|get_list:report_id }}

and not {{ retreivecheckbox|get_list:'report_id' }}

{% load app_filters %}
{% for reports in retreivecheckbox %}

        {{ retreivecheckbox|get_list:report_name_sc }}

    </div>
{% endfor %}


问:
Push secret changesets
That may look paradoxical, I know that secret changesets are meant to be private, but what if I want to backup those secret changesets?

I work with some branches in parallel and sometimes I want to push one, but not the others. To achieve that, I work in separate clones but I hate that.

So now mercurial has phases, I can make secret branches and have everything in the same repository. The problem is that between the beginning of the secret branch and its publication, I want to backup those secret changesets (I have a clone in another machine just to hold my backups in case something happens with my local repo or my machine).

Is there a way of doing that or my workflow is completly wrong?

答:
This is the best I have come up with so far. I think its essentially equivalent to what you want push/pull to be able to do.

Mark all the secret changesets you want to transfer as draft

In the source repo run hg bundle -r last_draft_rev bundlefile.hg path\to\backup\repo

In the destination repo run hg unbundle bundlefile.hg

The changesets will come into the backup as DRAFT

Mark the first draft changeset as secret, and all its descendants will be marked thusly

I couldn't get #2 to work if the changesets were still marked secret.

Title: Push secret changesets


问:
Gitlab - Get SSH Key For Non-Master Branch
I'm trying to avoid using the git command line, simply using the SSH key given in Gitlab and using that SSH key to import to Intellij Idea IDE.
I have a project with two branches: "master" and "development." under Gitlab's "Project" page, there is an SSH key, but it seems to only refer to the master branch; when checked out into the Intellij IDE, it only gets the master files. Is there a separate SSH key for the development branch? How can I access and check it out?</p>

答:
SSH key provides you SSH access to the repository - so with the key, you can clone all branches.

The thing is that by default git clone clones only the master branch,  Since IDE just uses a command line git, it clones master only as well.

To get developer branch to your repository, you could use the branches widget and checkout the remote branch as the local one. If you do not see the remote branch in the list, do VCS - Git - Fetch


问:
converting object to str and back to objects
i had a list of obj

```<code>[<DiffMatchPatch.patch_obj instance at 0x152a0b00>, <DiffMatchPatch.patch_obj instance at 0x152a0ab8>]
</code>```

i later converted them to a strs - then i got

```<code>["@@ -797,44 +797,8 @@\n :  %0A\n-       print 'WithDrwaing %25d' %25 shs%0A\n     \n", "@@ -854,158 +854,4 @@\n e %0A%0A\n-'''%0Aif __name__ == '__main__': %0A       b=Transcations(amount=9) %0A       b.deposit() %0A       b.withdraw(2000) %0A       b.interest(30) %0A       b.chk()%0A'''%0A%0A%0A\n"]
</code>```

is it possible to convert the strs back to objects?

答:
Although it is not exactly what you ask for, maybe the "serialization" can solve your problems:

http://en.wikipedia.org/wiki/Serialization

http://docs.python.org/library/marshal.html

http://docs.python.org/library/pickle.html

Also, you can think about defining your own __ str __ function and a constructor that will spawn an object from the string (created by __ str __)

Body:
i had a list of obj

[<DiffMatchPatch.patch_obj instance at 0x152a0b00>, <DiffMatchPatch.patch_obj instance at 0x152a0ab8>]

i later converted them to a strs - then i got

["@@ -797,44 +797,8 @@\n :  %0A\n-       print 'WithDrwaing %25d' %25 shs%0A\n     \n", "@@ -854,158 +854,4 @@\n e %0A%0A\n-'''%0Aif __name__ == '__main__': %0A       b=Transcations(amount=9) %0A       b.deposit() %0A       b.withdraw(2000) %0A       b.interest(30) %0A       b.chk()%0A'''%0A%0A%0A\n"]

is it possible to convert the strs back to objects?


问:
Is is possible to use federated identities in AWS Cognito for my web/mobile apps?
I know that user pools allow to authenticate users to my apps, but what about federated identities? As far as I understand, they allow only to grant access to the AWS resources, not to the app. Or am I not right?</p>

答: Yes, Federated Identities only provide you short term AWS Credentials to access AWS resources. If access to your app is based on AWS resources then you can use Federated Identities otherwise User Pools is a better fit.</p>


问:
R: for loop error
I'm trying to remove NA values in the columns of a data frame and trying to cbind the resulting vectors another data frame. Here's the code I'm using:

```<code>for (x in df_wide[4:8]) {
  a <- df_wide[[x]][!is.na(df_wide[[x]])]
  df <- cbind(df, a)
}
</code>```

But I'm getting this error:

```<code>`Error in .subset2(x, i, exact = exact) : no such index at level 1`
</code>```

I've also tried using apply function, but I got the same error.

```<code>`Error in .subset2(x, i, exact = exact) : no such index at level 1`
function (x, i, exact)
if (is.matrix(i)) as.matrix(x)[[i]] else .subset2(x, i, exact = exact)
</code>```

Can anyone please explain me why I'm getting this error and how can I fix it?

If you want to see the data frame, please refer to my previous question.

Thanks in advance.

答:
for (x in df_wide[4:8])

is putting the whole results in x. So x is equal to the whole vector of of that column. Ex: x <- df_wide[4], then x <- df_wide[5], then... etc.

a <- df_wide[[x]][!is.na(df_wide[[x]])]

is saying that you should find the vector of values (without header) of df_wide[[]] where the column number is the whole vector of df_wide[4] (or 5 or 6 or 7). But the column number (singular) cannot be all of the values in the x vector

A similar way to do this would be from this post you can search for using "omit NA values"

df_out <- df_wide[complete.cases(df_wide[,4:8]),]

which checks to see if the cases in columns 4:8 are complete, and then returns all columns in df_wide where the rows are complete cases.

Title: R: for loop error

Body:
I'm trying to remove NA values in the columns of a data frame and trying to cbind the resulting vectors another data frame. Here's the code I'm using:

for (x in df_wide[4:8]) {
  a <- df_wide[[x]][!is.na(df_wide[[x]])]
  df <- cbind(df, a)
}

But I'm getting this error:

`Error in .subset2(x, i, exact = exact) : no such index at level 1`

I've also tried using apply function, but I got the same error.

`Error in .subset2(x, i, exact = exact) : no such index at level 1`
function (x, i, exact)
if (is.matrix(i)) as.matrix(x)[[i]] else .subset2(x, i, exact = exact)

Can anyone please explain me why I'm getting this error and how can I fix it?

If you want to see the data frame, please refer to my previous question.

Thanks in advance.


问:
Reset the Value of a Select Box
I'm trying to reset the value of two select fields, structured like this,

```<code><select>
  <option></option>
  <option></option>
  <option></option>
</select>

<select>
  <option></option>
  <option></option>
  <option></option>
</select>
</code>```

jQuery,

```<code>$('select').each(function(idx, sel) {
  $(sel).find('option :eq(0)').attr('selected', true);
});
</code>```

Unfortunately, no matter how many ways I try it, it just doesn't happen. Nothing in the console. I have no idea what's going on? I know there has to be a way to do this, you can do anything with JS

EDIT:

I figured out that the issue only occurs when I try to fire the code on the click of a dom element, however, I know that the code should be working, because when I have

```<code>$('p').click(function(){
  console.log('test');
});
</code>```

It outputs 'test' to the console, but when I include the code in this function, nothing happens. Why is this?

答:
neRok touched on this answer above and I'm just expanding on it.

According to the slightly dated, but handy O'Reilly reference book, Javascript: The Definitive Guide:

The selectedIndex property of the Select object is an integer that specifies the index of the selected option within the Select object.  If no option is selected, selectedIndex is -1.

As such, the following javascript code will "reset" the Select object to no options selected:

```<code>select_box = document.getElementById("myselectbox");
select_box.selectedIndex = -1;
</code>```

Note that changing the selection in this way does not trigger the onchange() event handler.

Title: Reset the Value of a Select Box

Body:
I'm trying to reset the value of two select fields, structured like this,

<select>
  <option></option>
  <option></option>
  <option></option>
</select>

<select>
  <option></option>
  <option></option>
  <option></option>
</select>

jQuery,

$('select').each(function(idx, sel) {
  $(sel).find('option :eq(0)').attr('selected', true);
});

Unfortunately, no matter how many ways I try it, it just doesn't happen. Nothing in the console. I have no idea what's going on? I know there has to be a way to do this, you can do anything with JS

EDIT:

I figured out that the issue only occurs when I try to fire the code on the click of a dom element, however, I know that the code should be working, because when I have

$('p').click(function(){
  console.log('test');
});

It outputs 'test' to the console, but when I include the code in this function, nothing happens. Why is this?

Body:
neRok touched on this answer above and I'm just expanding on it.

According to the slightly dated, but handy O'Reilly reference book, Javascript: The Definitive Guide:

The selectedIndex property of the Select object is an integer that specifies the index of the selected option within the Select object.  If no option is selected, selectedIndex is -1.

As such, the following javascript code will "reset" the Select object to no options selected:

select_box = document.getElementById("myselectbox");
select_box.selectedIndex = -1;

Note that changing the selection in this way does not trigger the onchange() event handler.


问:
Update user input as they type it
This problem is related a basic app that utilizes email intent.

The UI of the app displays 4 inputs:

Email Address

Subject

Name

Messages

Button

The message is of a textMultiLine input type.

The message has a default text that says: "Hello CustomerName (This is a dynamic variable that would update as the user types their name in input number 3), could you please review our app..."

What I am trying to do is to update in real-time the CustomerName to the actual customer name as they type it in input number 3 (Name).

Source:

```<code>package com.example.apit.testemailintent;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    EditText receiver, sub, mesg;
    EditText customerName;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        receiver = (EditText) findViewById(R.id.email);
        sub = (EditText) findViewById(R.id.subject);
        customerName = (EditText) findViewById(R.id.name);
        mesg = (EditText) findViewById(R.id.message);
        btn = (Button) findViewById(R.id.submitButton);

        addListenerOnButton1();

    }

    public void addListenerOnButton1() {
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                String Sendto = receiver.getText().toString();
                String subject = sub.getText().toString();
                String cusName = customerName.getText().toString();
                String mesgs = "Hello " + cusName + ", could you please review our app...?";

                Intent email = new Intent(Intent.ACTION_SEND);
                email.putExtra(Intent.EXTRA_EMAIL, new String[]{Sendto});
                email.putExtra(Intent.EXTRA_SUBJECT, subject);
                email.putExtra(Intent.EXTRA_TEXT, mesgs);

                email.setType("message/rfc822");
                startActivity(Intent.createChooser(email, "Please Choose an Email Client"));

            }
        });

    }

}
</code>```

Thank you,

答:
```<code>nameEditText.addTextChangedListener(new TextWatcher() {

   @Override
   public void afterTextChanged(Editable s) {}

   @Override
   public void beforeTextChanged(CharSequence s, int start,
     int count, int after) {
   }

   @Override
   public void onTextChanged(CharSequence s, int start,int before, int count) {
      messageEditText.setText("Hello " + s + " could you please review our app")
   }
  });
</code>```

Title: Update user input as they type it

Body:
This problem is related a basic app that utilizes email intent.

The UI of the app displays 4 inputs:

Email Address

Subject

Name

Messages

Button

The message is of a textMultiLine input type.

The message has a default text that says: "Hello CustomerName (This is a dynamic variable that would update as the user types their name in input number 3), could you please review our app..."

What I am trying to do is to update in real-time the CustomerName to the actual customer name as they type it in input number 3 (Name).

Source:

package com.example.apit.testemailintent;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    EditText receiver, sub, mesg;
    EditText customerName;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        receiver = (EditText) findViewById(R.id.email);
        sub = (EditText) findViewById(R.id.subject);
        customerName = (EditText) findViewById(R.id.name);
        mesg = (EditText) findViewById(R.id.message);
        btn = (Button) findViewById(R.id.submitButton);

        addListenerOnButton1();

    }

    public void addListenerOnButton1() {
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                String Sendto = receiver.getText().toString();
                String subject = sub.getText().toString();
                String cusName = customerName.getText().toString();
                String mesgs = "Hello " + cusName + ", could you please review our app...?";

                Intent email = new Intent(Intent.ACTION_SEND);
                email.putExtra(Intent.EXTRA_EMAIL, new String[]{Sendto});
                email.putExtra(Intent.EXTRA_SUBJECT, subject);
                email.putExtra(Intent.EXTRA_TEXT, mesgs);

                email.setType("message/rfc822");
                startActivity(Intent.createChooser(email, "Please Choose an Email Client"));

            }
        });

    }

}

Thank you,