问:
How to get indexOf of multidimentional array?
I'm having some troubles getting the indexOf a multidimentional array.

```<code>var z = [["231f20", 5385], ["ffffff", 2419], ["ffafff", 2419]];
var index = z[0].indexOf('ffffff');
alert(index); #returns -1
</code>```

As you can observe, the hex value and numbers (pixel quantity) are inside the same list in z.

How can I filter and get the indexOf the correct list ?

答:
How can I filter and get the indexOf the correct list ?

You could use filter, but I wouldn't; I'd use findIndex*:

var z = [["231f20", 5385], ["ffffff", 2419], ["ffafff", 2419]];
var index = z.findIndex(function(entry) {
  return entry.indexOf("ffffff") != -1;
});
console.log(index);```
</div>
</div>
</p>

<p><code>findIndex</code> returns the index of the first entry for which your callback returned a truthy value.</p>

<p>That just tells you the outer index (1). If you wanted <strong>both</strong> indexes, I'd probably use <code>some</code>** and have the callback close over the result variables:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var z = [["231f20", 5385], ["ffffff", 2419], ["ffafff", 2419]];
var outerIndex, innerIndex;
var index = z.some(function(entry, index) {
  var n = entry.indexOf("ffffff");
  if (n != -1) {
    outerIndex = index;
    innerIndex = n;
    return true;
  }
});
console.log(outerIndex, innerIndex);</code>```

* findIndex was added in ES2015, but it's trivial to polyfill; see the linked MDN article for a polyfill.

** some is from ES5 back in 2009, so it'll be on everything but truly obsolete browsers like IE8. Also polyfillable.

Body:
I'm having some troubles getting the indexOf a multidimentional array.

var z = [["231f20", 5385], ["ffffff", 2419], ["ffafff", 2419]];
var index = z[0].indexOf('ffffff');
alert(index); #returns -1

As you can observe, the hex value and numbers (pixel quantity) are inside the same list in z.

How can I filter and get the indexOf the correct list ?

Body:
How can I filter and get the indexOf the correct list ?

You could use filter, but I wouldn't; I'd use findIndex*:

var z = [["231f20", 5385], ["ffffff", 2419], ["ffafff", 2419]];
var index = z.findIndex(function(entry) {
  return entry.indexOf("ffffff") != -1;
});
console.log(index);

findIndex returns the index of the first entry for which your callback returned a truthy value.

That just tells you the outer index (1). If you wanted both indexes, I'd probably use some** and have the callback close over the result variables:

var z = [["231f20", 5385], ["ffffff", 2419], ["ffafff", 2419]];
var outerIndex, innerIndex;
var index = z.some(function(entry, index) {
  var n = entry.indexOf("ffffff");
  if (n != -1) {
    outerIndex = index;
    innerIndex = n;
    return true;
  }
});
console.log(outerIndex, innerIndex);

* findIndex was added in ES2015, but it's trivial to polyfill; see the linked MDN article for a polyfill.

** some is from ES5 back in 2009, so it'll be on everything but truly obsolete browsers like IE8. Also polyfillable.


来源: stackexchange

问:
How to merge two different pandas data frame in python
by thought is using iterate the data frame column and check for required data in another column using condition checks.
suggest is it correct or any other way.

答: Merge, join and concatenate: look here</p>

ContentLicense: CC BY-SA 3.0

Body: Merge, join and concatenate: look here


问:
Sorting of y-axis labels in ggplot
I have a biographical dataset in two dataframes:

```<code>library(tidyverse)
# dataframe of one-time ovents
one_timers <-
  tribble(~event, ~date,
          "birth", as.Date("1984/02/10"),
          "first toy", as.Date("1984/02/11"),
          "first kiss", as.Date("1992/05/15"),
          "moved out", as.Date("2003/08/29"),
          "first car", as.Date("2002/04/11"),
          "job", as.Date("2000/02/10"))
#dataframe of repeating events, say switchingt between companies that provide internet
sequence <-
  tribble(~event, ~from, ~to,  ~quality,
          "job", as.Date("2000/02/10"), as.Date("2000/02/17"), 2,
          "job", as.Date("2001/05/15"), as.Date("2001/06/10"), 4,
          "job", as.Date("2003/08/29"), as.Date("2004/02/10"), 5,
          "job", as.Date("2004/04/11"), as.Date("2005/01/10"), 10)
</code>```

And I want create a plot of those events:

```<code># plotting events
one_timers %>%
  ggplot(aes(x = date, y = event)) +
  geom_point()
</code>```

Which results in:

This plot is okay, but I want events to be sorted chronologically, so I'm switching my event variable to factor end reorder it according to date:

```<code>one_timers <-
  one_timers %>%
  mutate(event = event %>% as.factor() %>% forcats::fct_reorder(date))
levels(one_timers$event)
# and it works
one_timers %>%
  ggplot(aes(x = date, y = event)) +
  geom_point()
</code>```

But now let's complicate it with additional layer, that uses different dataframe. This layer will be under the points (it works just OK if it's above):

```<code>one_timers %>%
  ggplot(aes(x = date, y = event)) +
  geom_segment(data = sequence,
               aes(x = from,
                   xend = to,
                   y = event,
                   yend = event,
                   colour = quality),
               size = 3) +
  geom_point()
</code>```

I've tried coercing event from second dataframe to factor with the same levels and ordering, but it's not that (picture doesn't change at all):

```<code>factors <- list(one_timers$event, sequence$event %>% as.factor())
sequence$event <- fct_unify(fs = factors)[[2]]
sequence$event

one_timers %>%
  ggplot(aes(x = date, y = event)) +
  geom_segment(data = sequence,
               aes(x = from,
                   xend = to,
                   y = event,
                   yend = event,
                   colour = quality),
               size = 3) +
  geom_point()
# still doesn't work
</code>```

Anybody knows how to fix this?

答:
Interesting, that adding the segment layer confuses the axis.

I managed to work around by introducing a numerical variable:

```<code>one_timers <- one_timers %>% mutate(eventNum = as.numeric(event))
sequence <- sequence %>% mutate(eventNum = which(levels(one_timers$event) %in% event))

one_timers %>%
  ggplot(aes(x = date, y = eventNum)) +
  geom_segment(data = sequence,
               aes(x = from,
                   xend = to,
                   y = eventNum,
                   yend = eventNum,
                   colour = quality),
               size = 3) +
  geom_point() +
  scale_y_continuous("event",
                   breaks = one_timers$eventNum,
                   labels = as.character(one_timers$event))
</code>```

Title: Sorting of y-axis labels in ggplot

Body:
I have a biographical dataset in two dataframes:

library(tidyverse)
# dataframe of one-time ovents
one_timers <-
  tribble(~event, ~date,
          "birth", as.Date("1984/02/10"),
          "first toy", as.Date("1984/02/11"),
          "first kiss", as.Date("1992/05/15"),
          "moved out", as.Date("2003/08/29"),
          "first car", as.Date("2002/04/11"),
          "job", as.Date("2000/02/10"))
#dataframe of repeating events, say switchingt between companies that provide internet
sequence <-
  tribble(~event, ~from, ~to,  ~quality,
          "job", as.Date("2000/02/10"), as.Date("2000/02/17"), 2,
          "job", as.Date("2001/05/15"), as.Date("2001/06/10"), 4,
          "job", as.Date("2003/08/29"), as.Date("2004/02/10"), 5,
          "job", as.Date("2004/04/11"), as.Date("2005/01/10"), 10)

And I want create a plot of those events:

# plotting events
one_timers %>%
  ggplot(aes(x = date, y = event)) +
  geom_point()

Which results in:

This plot is okay, but I want events to be sorted chronologically, so I'm switching my event variable to factor end reorder it according to date:

one_timers <-
  one_timers %>%
  mutate(event = event %>% as.factor() %>% forcats::fct_reorder(date))
levels(one_timers$event)
# and it works
one_timers %>%
  ggplot(aes(x = date, y = event)) +
  geom_point()

But now let's complicate it with additional layer, that uses different dataframe. This layer will be under the points (it works just OK if it's above):

one_timers %>%
  ggplot(aes(x = date, y = event)) +
  geom_segment(data = sequence,
               aes(x = from,
                   xend = to,
                   y = event,
                   yend = event,
                   colour = quality),
               size = 3) +
  geom_point()

I've tried coercing event from second dataframe to factor with the same levels and ordering, but it's not that (picture doesn't change at all):

factors <- list(one_timers$event, sequence$event %>% as.factor())
sequence$event <- fct_unify(fs = factors)[[2]]
sequence$event

one_timers %>%
  ggplot(aes(x = date, y = event)) +
  geom_segment(data = sequence,
               aes(x = from,
                   xend = to,
                   y = event,
                   yend = event,
                   colour = quality),
               size = 3) +
  geom_point()
# still doesn't work

Anybody knows how to fix this?

Body:
Interesting, that adding the segment layer confuses the axis.

I managed to work around by introducing a numerical variable:

one_timers <- one_timers %>% mutate(eventNum = as.numeric(event))
sequence <- sequence %>% mutate(eventNum = which(levels(one_timers$event) %in% event))

one_timers %>%
  ggplot(aes(x = date, y = eventNum)) +
  geom_segment(data = sequence,
               aes(x = from,
                   xend = to,
                   y = eventNum,
                   yend = eventNum,
                   colour = quality),
               size = 3) +
  geom_point() +
  scale_y_continuous("event",
                   breaks = one_timers$eventNum,
                   labels = as.character(one_timers$event))


问:
cmake choose output directory .exe
I tried to define where to put the .exe generated by cmake + visual studio.
I put this in the cmakefiles.txt

```<code>IF(CMAKE_SYSTEM_NAME STREQUAL Windows)
INSTALL(TARGETS
    mialsrtkRefineHRMaskByIntersection
    DESTINATION ${CMAKE_INSTALL_PREFIX})

ENDIF(CMAKE_SYSTEM_NAME STREQUAL Windows)
</code>```

but at the end all exe are in the folder of the vcxproj in a subfolder Debut.
is that normal ?
How can I specify the output directory ?
on linux I put destination bin and it works.

答:
What you're setting is the installation destination directory. In Visual Studio, installation is performed by building the special target INSTALL. That is equivalent to make install in Make world.

Note that you can also specify the build output directory. The ways to do that are :

Variable CMAKE_RUNTIME_OUTPUT_DIRECTORY, which provides global settings.

Target property RUNTIME_OUTPUT_DIRECTORY, which controls settings for a particular target.

Both of these have per-configuration variants, or sister variables/properties which affect other things than executables (e.g. CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG). Please see the CMake docs for details.

Title: cmake choose output directory .exe

Body:
I tried to define where to put the .exe generated by cmake + visual studio.
I put this in the cmakefiles.txt

IF(CMAKE_SYSTEM_NAME STREQUAL Windows)
INSTALL(TARGETS
    mialsrtkRefineHRMaskByIntersection
    DESTINATION ${CMAKE_INSTALL_PREFIX})

ENDIF(CMAKE_SYSTEM_NAME STREQUAL Windows)

but at the end all exe are in the folder of the vcxproj in a subfolder Debut.
is that normal ?
How can I specify the output directory ?
on linux I put destination bin and it works.


问:
String parameter having name of column of database to actual column value
I have a method that sends a string parameter(paramType) having name of column of database. and I want to get the value of the column in my Select statement.

I need to replace paramType with value of that column.

```<code>var details = DetailsRepository
                        .Find(application => application.Created > compareDate)
                        .Select(m => new {m.ApplicationId, paramType })
                        .Distinct();
</code>```

I just need to replace the paramType with name of the column is Select. Suppose I have paramtype = "Address", I want the second element to be m.Address.

答:
If the value of paramType is the name of a member, then to do this you'll have to build an expression tree at runtime. This is possible, but is awkward unless all the columns you'll be selecting will always be of the same type.This is further complicated by the fact that you want to select a tuple in the lambda. Frankly, it would be easier to write the SQL dynamically in this case...

Edit: you could try this, which demonstrates the amount of evil needed here:

```<code>static Expression<Func<Application, T>> BuildTupleSelector<T>(
    string paramType, Func<T> usedForGenericTypeInference)
{
    var m = Expression.Parameter(typeof(Application), "m");
    var body = Expression.New(typeof(T).GetConstructors().Single(),
        new Expression[] {
            Expression.PropertyOrField(m, nameof(Application.ApplicationId)),
            Expression.PropertyOrField(m, paramType)
        },
        new MemberInfo[]
        {
            typeof(T).GetProperty("ApplicationId").GetGetMethod(),
            typeof(T).GetProperty("Value").GetGetMethod()
        });
    return Expression.Lambda<Func<Application, T>>(body, m);
}
</code>```

with usage:

```<code>var details = DetailsRepository
   .Find(application => application.Created > compareDate)
   .Select(BuildTupleSelector(paramType,
       () => new { ApplicationId = 123, Value = "abc" }))
   .Distinct();
</code>```

details should now the the anonymous type with an int ApplicationId and string Value.

Body:
I have a method that sends a string parameter(paramType) having name of column of database. and I want to get the value of the column in my Select statement.

I need to replace paramType with value of that column.

var details = DetailsRepository
                        .Find(application => application.Created > compareDate)
                        .Select(m => new {m.ApplicationId, paramType })
                        .Distinct();

I just need to replace the paramType with name of the column is Select. Suppose I have paramtype = "Address", I want the second element to be m.Address.

Body:
If the value of paramType is the name of a member, then to do this you'll have to build an expression tree at runtime. This is possible, but is awkward unless all the columns you'll be selecting will always be of the same type.This is further complicated by the fact that you want to select a tuple in the lambda. Frankly, it would be easier to write the SQL dynamically in this case...

Edit: you could try this, which demonstrates the amount of evil needed here:

static Expression<Func<Application, T>> BuildTupleSelector<T>(
    string paramType, Func<T> usedForGenericTypeInference)
{
    var m = Expression.Parameter(typeof(Application), "m");
    var body = Expression.New(typeof(T).GetConstructors().Single(),
        new Expression[] {
            Expression.PropertyOrField(m, nameof(Application.ApplicationId)),
            Expression.PropertyOrField(m, paramType)
        },
        new MemberInfo[]
        {
            typeof(T).GetProperty("ApplicationId").GetGetMethod(),
            typeof(T).GetProperty("Value").GetGetMethod()
        });
    return Expression.Lambda<Func<Application, T>>(body, m);
}

with usage:

var details = DetailsRepository
   .Find(application => application.Created > compareDate)
   .Select(BuildTupleSelector(paramType,
       () => new { ApplicationId = 123, Value = "abc" }))
   .Distinct();

details should now the the anonymous type with an int ApplicationId and string Value.


问:
django raw query percent sign problem
I trying to Django raw sql query in like function, but results is empty. I try mysql client tool this query and get many records. how to solution this problem?

my query:

```<code>  SELECT s.* , s.id as pk
    FROM d_status as s,
         (select post_id
            from p_useractions
           where from_user_id in
                 (select to_user_id
                    from p_fallowers
                   where from_user_id = 1)
         ) as a
   WHERE s.from_user_id = 1 OR
         s.text like '%@Mustafa Yontar2123%' OR
         s.id = a.post_id
GROUP BY s.id
ORDER BY s.last_update
   LIMIT 25
</code>```

答: Try replacing each % with %%.  So, the relevant part in your example would look like this: '%%@Mustafa Yontar2123%%'.

ContentLicense: CC BY-SA 2.5

Title: django raw query percent sign problem

Body:
I trying to Django raw sql query in like function, but results is empty. I try mysql client tool this query and get many records. how to solution this problem?

my query:

  SELECT s.* , s.id as pk
    FROM d_status as s,
         (select post_id
            from p_useractions
           where from_user_id in
                 (select to_user_id
                    from p_fallowers
                   where from_user_id = 1)
         ) as a
   WHERE s.from_user_id = 1 OR
         s.text like '%@Mustafa Yontar2123%' OR
         s.id = a.post_id
GROUP BY s.id
ORDER BY s.last_update
   LIMIT 25


问:
Notepad++ Mirrored Right to Left Text
I am using Notepad++ Version 6.5.5.

I am using both English and Hebrew, hence alternately need to switch back and forth from
Left-To-Right English text to Right-To-Left Hebrew text.

While pressing ALT+CTRL+R:

Page layout flips to the right side as expected.

However, all text appears mirrored.

In order to see text correctly I need to refresh my display in one of these methods:

Pressing F11 twice, OR

Pressing F12 twice, OR

Minimize then Maximize window.

While pressing ALT+CTR+L:

Page layout flips back to the left side as expected.

However, all text appears mirrored again.

This problem seems to appear just in recent versions as it didn't happen in the past.
Is there any solution for that?
If not I'd like to downgrade Notepad++ to the last version (BTW which one was it?) it worked correctly. So where can I find it now?

答:
TEXT DIRECTION KEYS

Press CTRL+ALT+L --> Text Direction Left to Right

Press CTRL+ALT+R --> Text Direction Right to Left

Title: Notepad++ Mirrored Right to Left Text


问:
Fastlane version upload - We're temporarily unable to save your changes. Please try again later
I'm trying to upload a new version of my ios app using FastLane. I already have version 1.0 live and now trying to upload a newer version.

On trying to upload I get the following error.

Itunes connect - We're temporarily unable to save your changes. Please try again later

```<code>[16:58:43]: Loading './fastlane/metadata/en-US/description.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/keywords.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/release_notes.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/support_url.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/marketing_url.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/promotional_text.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/name.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/subtitle.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/privacy_url.txt'...
[16:58:43]: Loading './fastlane/metadata/copyright.txt'...
[16:58:43]: Loading './fastlane/metadata/primary_category.txt'...
[16:58:43]: Loading './fastlane/metadata/secondary_category.txt'...
[16:58:43]: Loading './fastlane/metadata/primary_first_sub_category.txt'...
[16:58:43]: Loading './fastlane/metadata/primary_second_sub_category.txt'...
[16:58:43]: Loading './fastlane/metadata/secondary_first_sub_category.txt'...
[16:58:43]: Loading './fastlane/metadata/secondary_second_sub_category.txt'...
[16:58:43]: Loading './fastlane/metadata/trade_representative_contact_information/trade_name.txt'...
[16:58:43]: Loading './fastlane/metadata/trade_representative_contact_information/address_line1.txt'...
[16:58:43]: Loading './fastlane/metadata/trade_representative_contact_information/address_line2.txt'...
[16:58:43]: Loading './fastlane/metadata/trade_representative_contact_information/city_name.txt'...
[16:58:43]: Loading './fastlane/metadata/trade_representative_contact_information/country.txt'...
[16:58:43]: Loading './fastlane/metadata/trade_representative_contact_information/postal_code.txt'...
[16:58:43]: Loading './fastlane/metadata/trade_representative_contact_information/is_displayed_on_app_store.txt'...
[16:58:43]: Loading './fastlane/metadata/review_information/first_name.txt'...
[16:58:43]: Loading './fastlane/metadata/review_information/last_name.txt'...
[16:58:43]: Loading './fastlane/metadata/review_information/phone_number.txt'...
[16:58:43]: Loading './fastlane/metadata/review_information/email_address.txt'...
[16:58:43]: Loading './fastlane/metadata/review_information/demo_user.txt'...
[16:58:43]: Loading './fastlane/metadata/review_information/demo_password.txt'...
[16:58:43]: Loading './fastlane/metadata/review_information/notes.txt'...
[16:58:45]: Activating language en-US...
[16:58:49]: Uploading metadata to iTunes Connect
iTunes Connect temporary error received: 'We're temporarily unable to save your changes. Please try again later.'. Retrying after 60 seconds (remaining: 4)...
</code>```

I haven't made any noticable changes in the app meta data or even the app itself. What am I doing wrong?

答: I encountered this error too and it took me a while to figure it out. In my case the review information .txt files (first_name.txt, last_name.txt) were empty but the information was manually edited with the iTunes Connect web interface for a previous version and copied to the new version. This seems to result in a mismatch. Adding the values to the .txt files solved this for me. I guess this could happen for any other of the metadata. So it would be safer to not touch the metadata in iTunes Connect web interface when using fastlane deliver. The error message should be improved though.</p>

Body:
I'm trying to upload a new version of my ios app using FastLane. I already have version 1.0 live and now trying to upload a newer version.

On trying to upload I get the following error.

Itunes connect - We're temporarily unable to save your changes. Please try again later

[16:58:43]: Loading './fastlane/metadata/en-US/description.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/keywords.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/release_notes.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/support_url.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/marketing_url.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/promotional_text.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/name.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/subtitle.txt'...
[16:58:43]: Loading './fastlane/metadata/en-US/privacy_url.txt'...
[16:58:43]: Loading './fastlane/metadata/copyright.txt'...
[16:58:43]: Loading './fastlane/metadata/primary_category.txt'...
[16:58:43]: Loading './fastlane/metadata/secondary_category.txt'...
[16:58:43]: Loading './fastlane/metadata/primary_first_sub_category.txt'...
[16:58:43]: Loading './fastlane/metadata/primary_second_sub_category.txt'...
[16:58:43]: Loading './fastlane/metadata/secondary_first_sub_category.txt'...
[16:58:43]: Loading './fastlane/metadata/secondary_second_sub_category.txt'...
[16:58:43]: Loading './fastlane/metadata/trade_representative_contact_information/trade_name.txt'...
[16:58:43]: Loading './fastlane/metadata/trade_representative_contact_information/address_line1.txt'...
[16:58:43]: Loading './fastlane/metadata/trade_representative_contact_information/address_line2.txt'...
[16:58:43]: Loading './fastlane/metadata/trade_representative_contact_information/city_name.txt'...
[16:58:43]: Loading './fastlane/metadata/trade_representative_contact_information/country.txt'...
[16:58:43]: Loading './fastlane/metadata/trade_representative_contact_information/postal_code.txt'...
[16:58:43]: Loading './fastlane/metadata/trade_representative_contact_information/is_displayed_on_app_store.txt'...
[16:58:43]: Loading './fastlane/metadata/review_information/first_name.txt'...
[16:58:43]: Loading './fastlane/metadata/review_information/last_name.txt'...
[16:58:43]: Loading './fastlane/metadata/review_information/phone_number.txt'...
[16:58:43]: Loading './fastlane/metadata/review_information/email_address.txt'...
[16:58:43]: Loading './fastlane/metadata/review_information/demo_user.txt'...
[16:58:43]: Loading './fastlane/metadata/review_information/demo_password.txt'...
[16:58:43]: Loading './fastlane/metadata/review_information/notes.txt'...
[16:58:45]: Activating language en-US...
[16:58:49]: Uploading metadata to iTunes Connect
iTunes Connect temporary error received: 'We're temporarily unable to save your changes. Please try again later.'. Retrying after 60 seconds (remaining: 4)...

I haven't made any noticable changes in the app meta data or even the app itself. What am I doing wrong?


问:
Array push is not working in my Angular 2 component

I have one component like this

```<code>export class DishComponent implements OnInit{

    @Input() dishID : number
    @Input() showList: boolean = false;
    selectedDishes : Array<any> = [];
    dishSubscribe : Subscription;
    totalDishprice : number;
    dish : any;

    constructor(
        private dishComponentService : DishComponentService,
        private dishService : DishService
    ) {
           this.dishSubscribe = this.dishService.dishItems$.subscribe( data =>{
           this.totalDishprice = data.map( dish => Number(dish.price)).reduce((prev, next) => prev + next, 0);
              console.log(this.totalDishprice);
           })
      }

      ngOnInit(){
          this.dishComponentService.getDishByID(this.dishID).subscribe( response => {
             console.log(response);
             this.dish = response.data[0];
        },(err) =>{
              console.log(err);
        })
     }

     checkDish(dish,isChecked){
         if(isChecked){
            this.selectedDishes.push(dish);
            //this.selectedDishes = [...this.selectedDishes, dish];
            this.dishService.addDish(this.selectedDishes);
         }else{
            let index = this.selectedDishes.findIndex(x => x.id == dish.id);
            this.selectedDishes.splice(index,1);
            this.dishService.addDish(this.selectedDishes);
         }
         console.log(this.selectedDishes);
     }
}
</code>```

and the view is like that,

```<code> <ng-container *ngIf="!showList">
     <ion-item class="order-third-dish horizontal-item checkbox-tag">
       <ion-label><span>{{dish?.name}}</span></ion-label>
       <ion-checkbox class="myinput large custom" (ionChange)="checkDish(dish,$event.checked)"  [checked]="isInArray(dish?.id)">
       </ion-checkbox>
     </ion-item>
 </ng-container>

 <ng-container *ngIf="showList">
     <h2 class="item-title">{{dish?.name}}</h2>
      <ion-note class="item-time" item-right>{{dish?.price | currency : 'INR' : true : '.2-2'}}</ion-note>
     <ion-checkbox class="dish_check" (ionChange)="checkDish(dish,$event.checked)" [checked]="isInArray(dish?.id)">
     </ion-checkbox>
 </ng-container>
</code>```

Here I what I am doing is, updating the selectedDishes array on every check in the checkbox. But the problem is push not working in the checkDish function. this.dishService.addDish(this.selectedDishes); here I am doing just adding it in a observable.

答:
You are getting object there in the dish

{id: "1", name: "Omelettes", price: "35.00", image: false, …} like this

So you have an array of the selected dish and then you are pushing an object into it
If you want to access that dish name and push it to the selected dish then you have to do it like this...

a = [1,2,3,4,{id:1,name:"aarsh"}]
if you want to access name then

a[4].name then you get "aarsh" as output.

So here you are getting dish = {id: "1", name: "Omelettes", price: "35.00", image: false, …}
then you can do like this dish.name and you will get Omelettes

Body:
I have one component like this

export class DishComponent implements OnInit{

    @Input() dishID : number
    @Input() showList: boolean = false;
    selectedDishes : Array<any> = [];
    dishSubscribe : Subscription;
    totalDishprice : number;
    dish : any;

    constructor(
        private dishComponentService : DishComponentService,
        private dishService : DishService
    ) {
           this.dishSubscribe = this.dishService.dishItems$.subscribe( data =>{
           this.totalDishprice = data.map( dish => Number(dish.price)).reduce((prev, next) => prev + next, 0);
              console.log(this.totalDishprice);
           })
      }

      ngOnInit(){
          this.dishComponentService.getDishByID(this.dishID).subscribe( response => {
             console.log(response);
             this.dish = response.data[0];
        },(err) =>{
              console.log(err);
        })
     }

     checkDish(dish,isChecked){
         if(isChecked){
            this.selectedDishes.push(dish);
            //this.selectedDishes = [...this.selectedDishes, dish];
            this.dishService.addDish(this.selectedDishes);
         }else{
            let index = this.selectedDishes.findIndex(x => x.id == dish.id);
            this.selectedDishes.splice(index,1);
            this.dishService.addDish(this.selectedDishes);
         }
         console.log(this.selectedDishes);
     }
}

and the view is like that,

 <ng-container *ngIf="!showList">
     <ion-item class="order-third-dish horizontal-item checkbox-tag">
       <ion-label>{{dish?.name}}</ion-label>
       <ion-checkbox class="myinput large custom" (ionChange)="checkDish(dish,$event.checked)"  [checked]="isInArray(dish?.id)">
       </ion-checkbox>
     </ion-item>
 </ng-container>

 <ng-container *ngIf="showList">

{{dish?.name}}

      <ion-note class="item-time" item-right>{{dish?.price | currency : 'INR' : true : '.2-2'}}</ion-note>
     <ion-checkbox class="dish_check" (ionChange)="checkDish(dish,$event.checked)" [checked]="isInArray(dish?.id)">
     </ion-checkbox>
 </ng-container>

Here I what I am doing is, updating the selectedDishes array on every check in the checkbox. But the problem is push not working in the checkDish function. this.dishService.addDish(this.selectedDishes); here I am doing just adding it in a observable.

ContentLicense: CC BY-SA 4.0


问:
Wordpress - One page navigation
I'm a complete Wordpress newbie so maybe my question is like super dumb.
I installed a Wordpress and a theme, (works well).
This theme is a static one page navigation with one main top menu.

When you click on the contact button, it scrolls all the way down with a nice parallax effect (it was in the theme). The thing is, it only works with CONTACT and HOME (the first one).
I tried everything, there's no differences in the page settings, they're all templates issued, with a navigation ID that is the same as what is in the menu.

The only difference there is is that when I click on CONTACT or HOME the URL stays the same http://website.com . BUT when I click on the other ones (those that dont work) the URL become this :  http://website.com/#slug .

I get that this is what makes the difference but I have no idea how to change that.

Edit : If I download the demo content of the theme it works great without changing anything.

Save me :p.

Thank you for your time.

答:
website.com/#slug means the page header link wants to go to an ID section on that page if the section doesnt have an id called slug it wont work.

Example.

.height {
min-height: 150px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>header <br> content <br> bottom content <br> footer

<div class="height" id="section1">header (the divs could be anything from p tags to a tags, form tags...)</div>
<div class="height" id="section2">content</div>
<div class="height" id="section3">bottom content</div>
<div class="height" id="section4">footer</div></code>```

should be something like this... So your menu has to link to the correct section id. Then it should work.

Title: Wordpress - One page navigation

Body:
website.com/#slug means the page header link wants to go to an ID section on that page if the section doesnt have an id called slug it wont work.

Example.

.height {
min-height: 150px;
}

<a href="#section1">header</a> <br> <a href="#section2">content</a> <br> <a href="#section3">bottom content</a> <br> <a href="#section4">footer</a>

<div class="height" id="section1">header (the divs could be anything from p tags to a tags, form tags...)</div>
<div class="height" id="section2">content</div>
<div class="height" id="section3">bottom content</div>
<div class="height" id="section4">footer</div>

should be something like this... So your menu has to link to the correct section id. Then it should work.


问:
Python Gtk3, How can I insert a Response (Button) to MessageDialog?
some times I need to insert new response (button) to MessageDialog but I don't know how I can do this. for example msg_dialog.insert_response(Gtk.STOCK_OK, Gtk.ResponseType.OK, 2)

Thanks

答:
The method you are looking for is Gtk.Dialog.add_button:

Adds a button with the given text and sets things up so that clicking
  the button will emit the Gtk.Dialog ::response signal with the given
  response_id. The button is appended to the end of the dialog’s action
  area. The button widget is returned, but usually you don’t need it.

If you want to add several buttons, then you can use Gtk.Dialog.add_buttons:

The add_buttons() method adds several buttons to the Gtk.Dialog using
  the button data passed as arguments to the method. This method is the
  same as calling the Gtk.Dialog.add_button() repeatedly.

The button data pairs - button text (or stock ID) and a response ID integer are passed individually. For example:

```<code>dialog.add_buttons(Gtk.STOCK_OPEN, 42, "Close", Gtk.ResponseType.CLOSE)
</code>```

will add “Open” and “Close” buttons to dialog.

Body:
The method you are looking for is Gtk.Dialog.add_button:

Adds a button with the given text and sets things up so that clicking
  the button will emit the Gtk.Dialog ::response signal with the given
  response_id. The button is appended to the end of the dialog’s action
  area. The button widget is returned, but usually you don’t need it.

If you want to add several buttons, then you can use Gtk.Dialog.add_buttons:

The add_buttons() method adds several buttons to the Gtk.Dialog using
  the button data passed as arguments to the method. This method is the
  same as calling the Gtk.Dialog.add_button() repeatedly.

The button data pairs - button text (or stock ID) and a response ID integer are passed individually. For example:

dialog.add_buttons(Gtk.STOCK_OPEN, 42, "Close", Gtk.ResponseType.CLOSE)

will add “Open” and “Close” buttons to dialog.


问:
VBA: How to compare two columns in two different worksheets
I have only managed to do it when both columns are in the same worksheet.

What I want to do:
Compare two columns in two different worksheets (worksheet A & B). Cells that only exist in worksheet A but not in worksheet B should be pasted in worksheet B. Same goes for cells that only exist in worksheet B but not in worksheet A. I would also like to have the first row empty for categories. So it should begin counting with the second row.

Can anyone help?

```<code>Sub test()

Dim d1 As Object, d2 As Object, d3 As Object, e

Set d1 = CreateObject("scripting.dictionary")
Set d2 = CreateObject("scripting.dictionary")
Set d3 = CreateObject("scripting.dictionary")

For Each e In Cells(1).Resize(Cells(Rows.Count, 1).End(3).Row).Value
    d1(e) = True
    d2(e) = True
Next e

For Each e In Cells(2).Resize(Cells(Rows.Count, 2).End(3).Row).Value
    If (d2(e)) * (d1.exists(e)) Then d1.Remove e
    If Not d2(e) Then d3(e) = True
Next e

On Error Resume Next
Range("J1").Resize(d1.Count) = Application.Transpose(d1.keys)
Range("K1").Resize(d3.Count) = Application.Transpose(d3.keys)
On Error GoTo 0

End Sub
</code>```

答:
You have to refer the cells, rows, and etc to a given worksheet. It is not a difficult task, if you do it correctly.

Take a look how to refer to the worksheets:

```<code>Sub TestMe()

    Dim shA     As Worksheet
    Dim shB     As Worksheet
    Dim e       As Range

    Set shA = Worksheets(1)
    Set shB = Worksheets("Tabelle2")

    With shA
        For Each e In .Cells(1).Resize(.Cells(.Rows.Count, 1).End(3).Row)
            Debug.Print e.Address
        Next e
    End With
End Sub
</code>```

As you see the methods are mainly 2:

By index - Set shA = Worksheets(1)

By name  - Set shB = Worksheets("Tabelle2")

There is a third method, by vba's object name, but you probably not need it now. In the example above, pay attention that you are refering three times to the parent shA in this line:

```<code>For Each e In .Cells(1).Resize(.Cells(.Rows.Count, 1).End(3).Row)
</code>```

.Cells(1)...

.(Cells(...

.Rows.Count,..

This is rather important, when working with worksheets and probably the number 1 mistake in StackOverflow, that people do when working with VBA. E.g. here - VBA Runtime error 1004 when trying to access range of sheet or VBA - Getting a runtime error '1004' when running this code

If you miss the three time-referring, the Cells and the Rows from the above range would be automatically referred to the ActiveSheet. Which is probably not always the desired case.

Body:
I have only managed to do it when both columns are in the same worksheet.

What I want to do:
Compare two columns in two different worksheets (worksheet A & B). Cells that only exist in worksheet A but not in worksheet B should be pasted in worksheet B. Same goes for cells that only exist in worksheet B but not in worksheet A. I would also like to have the first row empty for categories. So it should begin counting with the second row.

Can anyone help?

Sub test()

Dim d1 As Object, d2 As Object, d3 As Object, e

Set d1 = CreateObject("scripting.dictionary")
Set d2 = CreateObject("scripting.dictionary")
Set d3 = CreateObject("scripting.dictionary")

For Each e In Cells(1).Resize(Cells(Rows.Count, 1).End(3).Row).Value
    d1(e) = True
    d2(e) = True
Next e

For Each e In Cells(2).Resize(Cells(Rows.Count, 2).End(3).Row).Value
    If (d2(e)) * (d1.exists(e)) Then d1.Remove e
    If Not d2(e) Then d3(e) = True
Next e

On Error Resume Next
Range("J1").Resize(d1.Count) = Application.Transpose(d1.keys)
Range("K1").Resize(d3.Count) = Application.Transpose(d3.keys)
On Error GoTo 0

End Sub

Body:
You have to refer the cells, rows, and etc to a given worksheet. It is not a difficult task, if you do it correctly.

Take a look how to refer to the worksheets:

Sub TestMe()

    Dim shA     As Worksheet
    Dim shB     As Worksheet
    Dim e       As Range

    Set shA = Worksheets(1)
    Set shB = Worksheets("Tabelle2")

    With shA
        For Each e In .Cells(1).Resize(.Cells(.Rows.Count, 1).End(3).Row)
            Debug.Print e.Address
        Next e
    End With
End Sub

As you see the methods are mainly 2:

By index - Set shA = Worksheets(1)

By name  - Set shB = Worksheets("Tabelle2")

There is a third method, by vba's object name, but you probably not need it now. In the example above, pay attention that you are refering three times to the parent shA in this line:

For Each e In .Cells(1).Resize(.Cells(.Rows.Count, 1).End(3).Row)

.Cells(1)...

.(Cells(...

.Rows.Count,..

This is rather important, when working with worksheets and probably the number 1 mistake in StackOverflow, that people do when working with VBA. E.g. here - VBA Runtime error 1004 when trying to access range of sheet or VBA - Getting a runtime error '1004' when running this code

If you miss the three time-referring, the Cells and the Rows from the above range would be automatically referred to the ActiveSheet. Which is probably not always the desired case.


问:
Dictionary unpacking into function when parameters are incompatible
I'm not sure that it's possible, I would like to unpack dictionary into function but I haven't similar parameters. Is it possible to easily restrict a dictionary to a subset?

```<code>def foo(a=0, b=0, c=0):
    print("a=%s, b=%s, c=%s"%(a,b,c))

my_dict = {'a':10, 'b':20, 'd':40}
foo(**my_dict)
</code>```

Output

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-1-d40731664736> in <module>()
      3
      4 my_dict = {'a':10, 'b':20, 'd':40}
----> 5 foo(**my_dict)

TypeError: foo() got an unexpected keyword argument 'd'
</code>```

And I want to obtain

```<code>a=10, b=20, c=0
</code>```

result where 'd' is automatically rejected.

It's just an example. In my case the function is not mine, I cannot redefined her parameters, foo is unmodifiable.

I have many functions in similar case as foo() and these functions are object's methods.

Any ideas?

答:
Inspecting the function signature will help:</p>

```<code>import inspect

params = inspect.signature(foo).parameters.keys()

foo(**{k: v for k, v in my_dict.items() if k in params})
</code>```

Body:
I'm not sure that it's possible, I would like to unpack dictionary into function but I haven't similar parameters. Is it possible to easily restrict a dictionary to a subset?

def foo(a=0, b=0, c=0):
    print("a=%s, b=%s, c=%s"%(a,b,c))

my_dict = {'a':10, 'b':20, 'd':40}
foo(**my_dict)

Output

TypeError                                 Traceback (most recent call last)
<ipython-input-1-d40731664736> in <module>()
      3
      4 my_dict = {'a':10, 'b':20, 'd':40}
----> 5 foo(**my_dict)

TypeError: foo() got an unexpected keyword argument 'd'

And I want to obtain

a=10, b=20, c=0

result where 'd' is automatically rejected.

It's just an example. In my case the function is not mine, I cannot redefined her parameters, foo is unmodifiable.

I have many functions in similar case as foo() and these functions are object's methods.

Any ideas?

Body:
Inspecting the function signature will help:

import inspect

params = inspect.signature(foo).parameters.keys()

foo(**{k: v for k, v in my_dict.items() if k in params})


问:
Generate a random alphanumeric string in Cocoa
I want to call a method, pass it the length and have it generate a random alphanumeric string.

Are there any utility libraries out there that may have a bunch of these types of functions?

答:
Modification for keithyip's answer:</p>

```<code>+ (NSString *)randomAlphanumericStringWithLength:(NSInteger)length
{
    static NSString * const letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        srand(time(NULL));
    });

    NSMutableString *randomString = [NSMutableString stringWithCapacity:length];

    for (int i = 0; i < length; i++) {
        [randomString appendFormat:@"%C", [letters characterAtIndex:arc4random() % [letters length]]];
    }

    return randomString;
}
</code>```

Body:
Modification for keithyip's answer:

+ (NSString *)randomAlphanumericStringWithLength:(NSInteger)length
{
    static NSString * const letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        srand(time(NULL));
    });

    NSMutableString *randomString = [NSMutableString stringWithCapacity:length];

    for (int i = 0; i < length; i++) {
        [randomString appendFormat:@"%C", [letters characterAtIndex:arc4random() % [letters length]]];
    }

    return randomString;
}


问:
How to make QGraphicsView Flat?
How can I make QGraphicsView look flat? It looks like this:

I don't want the outline to be shown.
Thanks!

答:
You can also use the stylesheet to customize the look (including the borders) of a QFrame, see the stylesheet doc.

To make your widget look flat just add this CSS : border: 0px

Title: How to make QGraphicsView Flat?


问:
How do you enable customers use their openid on your website, just like stackoverflow?
I want customers to use their openId on my site. I googled for this but didn't find any good tutorial. I use PHP and MySQL.

There is one at Plaxo. But it says we should download something from JanRain.com.

I saw the openId module of Drupal. It doesn't want anything to be downloaded.

Can anyone tell me what to do exactly?

答: If you are hosting your site on a linux machine, there should be a php-openid package you can install that will supply you with an open id client library you can use to enable open id logins.  The package comes with good example code to get you started.  If you aren't running linux or your distribution doesn't have php-openid, I'm 99% certain that php-openid is based on (or is directly) JanRain.com's php library, so downloading it directly should get you the same thing.</p>

OwnerDisplayName: iSattar

OwnerDisplayName: Ryan Ahearn


问:
Is there a way to configure router forwarding in a wireless network?
I'm running a web server on my laptop and using a service called no-ip to couple
the domain with my IP.

The problem is that the IP recognized is the router's IP.

Usually I use wireless networks so I can't configure port forwarding from a specific router.
Is there a way to configure a router remotely?

Another question: after forwarding configuration, will I be recognized on the internet by my PC's IP?

答:
If you have access to the router's admin page (http://defaultGatewayIP) . You can port forward any ports you want manually or using a third-party software that detects the router type and do the rest of work to you. You may try Simple Port Forwarding , It's easy to use and will do all the work for you. After port forwarding, you will still be recognized on the internet by your router IP, because Your router is what is connected to the internet, it just routes the traffic to your pc. So your pc isn't actually connected to the internet, it's connected to a middle-man (router).

If you don't know your default gateway, You can open a cmd instance and type

```<code>ipconfig /all
</code>```

you will find your default gateway IP in the output, Surf it from any web browser and will see your router configuration page.

Body:
If you have access to the router's admin page (http://defaultGatewayIP) . You can port forward any ports you want manually or using a third-party software that detects the router type and do the rest of work to you. You may try Simple Port Forwarding , It's easy to use and will do all the work for you. After port forwarding, you will still be recognized on the internet by your router IP, because Your router is what is connected to the internet, it just routes the traffic to your pc. So your pc isn't actually connected to the internet, it's connected to a middle-man (router).

If you don't know your default gateway, You can open a cmd instance and type

ipconfig /all

you will find your default gateway IP in the output, Surf it from any web browser and will see your router configuration page.


问:
Bootstrap - Input not respecting Grid size/Restraints
I haven't been able to find any answers to my question elsewhere, nor previous posts here.

I am working on a website for internal purposes for work, and just playing trying to get things working at home. I am not sure if I am doing something wrong or if there is a bug, or maybe I should be using another JS UI.

What I need for a UI, is tabs, a grid system and form input. Bootstrap seems to be the best option I have found so far. I had settled on 4.0.0.beta2 since it is the most recent. Everything works except the Input elements, text, number and so on. When I put these in a grid system with bootstrap the input elements do not respect the grid sizing. All other form elements do.

Here is my current testing page without all the extra clutter. The input type flows outside of the grid to the right. I have tried form-groups, moving stuff around, different sizes, input types, pretty much anything I can think of. (Edit - changed detail-row to just row as it should have been, still did not fix the issue)

```<code><!DOCTYPE html>

    <html lang=en>
    <head>
      <!-- Standard Meta -->
  <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Site Properties -->
    <link rel="stylesheet" href="css/bootstrap.4.0.0.beta2.min.css">

<title> -- </title>
</head>

<body>
<div id="viewport" class="container">

<div class="row">
<div class="col-sm-2">Type</div>
<div class="col-sm-2">Vendor</div>
<div class="col-sm-3">Item</div>
<div class="col-sm-3">Note</div>
<div class="col-sm-1">Min Stock</div>
<div class="col-sm-1">To Order</div>
</div>

<div class="row">
  <div class="col-sm-2">Animal</div>
  <div class="col-sm-2">Bear</div>
  <div class="col-sm-3">Black</div>
  <div class="col-sm-3">Midnight</div>
  <div class="col-sm-1">0</div>
  <div class="col-sm-1">
    <input class="input-sm" id="item-87">
  </div>
  </div>
</div>

<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/bootstrap.bundle.4.0.0.beta2.min.js"></script>
</body>
</html>
</code>```

Side note:
If I encapsulate the input type in a Col / Row / Col, outside of the main with a label it will constrain itself to the column width. But it then falls out of alignment with the other row's since they are different sizes.

答:
I belive that you should apply bootstrap grid class to your input elemtnt

something like

```<code><input class="input-sm col-sm-12" id="item-87">
</code>```

so your grid should be like,

```<code><div class="detail-row">
  <div class="col-sm-2">Animal</div>
  <div class="col-sm-2">Bear</div>
  <div class="col-sm-3">Black</div>
  <div class="col-sm-3">Midnight</div>
  <div class="col-sm-1">0</div>
  <div class="col-sm-1">
    <input class="input-sm col-sm-12" id="item-87">
  </div>
</code>```

Body:
I haven't been able to find any answers to my question elsewhere, nor previous posts here.

I am working on a website for internal purposes for work, and just playing trying to get things working at home. I am not sure if I am doing something wrong or if there is a bug, or maybe I should be using another JS UI.

What I need for a UI, is tabs, a grid system and form input. Bootstrap seems to be the best option I have found so far. I had settled on 4.0.0.beta2 since it is the most recent. Everything works except the Input elements, text, number and so on. When I put these in a grid system with bootstrap the input elements do not respect the grid sizing. All other form elements do.

Here is my current testing page without all the extra clutter. The input type flows outside of the grid to the right. I have tried form-groups, moving stuff around, different sizes, input types, pretty much anything I can think of. (Edit - changed detail-row to just row as it should have been, still did not fix the issue)

<!DOCTYPE html>

  <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="css/bootstrap.4.0.0.beta2.min.css">

<title> -- </title>

Type

Vendor

Item

Note

Min Stock

To Order

Animal

Bear

Black

Midnight

0

    <input class="input-sm" id="item-87">

Side note:
If I encapsulate the input type in a Col / Row / Col, outside of the main with a label it will constrain itself to the column width. But it then falls out of alignment with the other row's since they are different sizes.

Body:
I belive that you should apply bootstrap grid class to your input elemtnt

something like

<input class="input-sm col-sm-12" id="item-87">

so your grid should be like,

<div class="detail-row">
  <div class="col-sm-2">Animal</div>
  <div class="col-sm-2">Bear</div>
  <div class="col-sm-3">Black</div>
  <div class="col-sm-3">Midnight</div>
  <div class="col-sm-1">0</div>
  <div class="col-sm-1">
    <input class="input-sm col-sm-12" id="item-87">
  </div>


问:
C++ Socket Error (new initializer expression list treated as compound expression)
i'm starting coding socket in c++ and i have a strange error :

```<code>C:\Users\Martin\CLionProjects\CryptoRecv\connexion.cpp:11:56: error: new initializer expression list treated as compound expression [-fpermissive]
 sock = new SOCKET(AF_INET, SOCK_STREAM, IPPROTO_TCP);
</code>```

The code :

```<code>connexion::connexion(std::string ip, int port) {
WSADATA WSAData;
WSAStartup(MAKEWORD(2, 2), &WSAData);
sock = new SOCKET(AF_INET, SOCK_STREAM, IPPROTO_TCP); /*<--- Error ligne*/
if(*sock == INVALID_SOCKET){
    std::cout << "INVALID SOCKET" << std::endl;
}

addr = new SOCKADDR_IN;
addr->sin_addr.s_addr = inet_addr(ip.data());
addr->sin_family = AF_INET;
addr->sin_port = htonl(port);

if(connect(*sock, (SOCKADDR *)addr, sizeof(*addr)) == SOCKET_ERROR) {
    std::cout << "Erreur connection : " << WSAGetLastError() << std::endl;
}

message = new std::string();
}
</code>```

This code work well before i put it in a class.
Sorry for bad english.
:)

答:
Just from reading the code, I think your problem should be solved by changing the line that have caused the error with this one :

```<code>sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
</code>```

socket() is a function and not a class to try to instantiate it.

Make sure that you have already declared "sock" variable as an instance in your class, because I don't see it in your function.

Body:
i'm starting coding socket in c++ and i have a strange error :

C:\Users\Martin\CLionProjects\CryptoRecv\connexion.cpp:11:56: error: new initializer expression list treated as compound expression [-fpermissive]
 sock = new SOCKET(AF_INET, SOCK_STREAM, IPPROTO_TCP);

The code :

connexion::connexion(std::string ip, int port) {
WSADATA WSAData;
WSAStartup(MAKEWORD(2, 2), &WSAData);
sock = new SOCKET(AF_INET, SOCK_STREAM, IPPROTO_TCP); /*<--- Error ligne*/
if(*sock == INVALID_SOCKET){
    std::cout << "INVALID SOCKET" << std::endl;
}

addr = new SOCKADDR_IN;
addr->sin_addr.s_addr = inet_addr(ip.data());
addr->sin_family = AF_INET;
addr->sin_port = htonl(port);

if(connect(*sock, (SOCKADDR *)addr, sizeof(*addr)) == SOCKET_ERROR) {
    std::cout << "Erreur connection : " << WSAGetLastError() << std::endl;
}

message = new std::string();
}

This code work well before i put it in a class.
Sorry for bad english.
:)

Body:
Just from reading the code, I think your problem should be solved by changing the line that have caused the error with this one :

sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

socket() is a function and not a class to try to instantiate it.

Make sure that you have already declared "sock" variable as an instance in your class, because I don't see it in your function.


问:
How to use Coroutines and Callback properly? Retrieving an array out of an IEnumerator
we have some trouble with an IEnumerator and don't know how to retrieve an array out of it. We found out that you have to do it with a callback , but we don't really know how to use it. Here is the code of the IEnumerator and the void that needs to receive a string array from it.

```<code>public void StartRoutineGetProjects(string username, string password, string url){
    StartCoroutine(GetProjects(username, password, url));

    // here we dont know how to receive the array, need some help here
}

public IEnumerator GetProjects (string username, string password, string url, Action<string[]> callback)
{
    string privateURL = "http://" + url + "/Unity/myprojects.php";

    WWWForm form = new WWWForm ();
    form.AddField ("username", username);
    form.AddField ("password", password);

    // Send WWWForm
    WWW projects_get = new WWW (privateURL, form);

    if (projects_get.error != null && projects_get.error != "") {
        Debug.Log ("Internal Error");
    } else {
        // splitting the result at "|"
        string[] tempProjects = projects_get.text.Split ("|".ToCharArray ());

        yield return tempProjects;

        callback(tempProjects) // <-- here we want to return the array

    }
}
</code>```

We would be glad for every help we can get.

答:
[SOLVED] Yes finally it works. Thank you very much. We don't want to withhold our solution, so others can benefit from it.
So here is the code.
First the databasescript:

```<code>        public void StartRoutineCheckLoginCorrect (string username, string password, string url, Action<string[]> callback)
    {
        StartCoroutine (Login (username, password, url, callback));
    }

    IEnumerator Login (string username, string password, string url,Action<string[]> callback)
    {
        string loginURL = "http://" + url + "/Unity/mylogin.php";
        WWWForm form = new WWWForm ();
        form.AddField ("username", username);
        form.AddField ("password", password);

        WWW users_get = new WWW (loginURL, form);

        yield return users_get;

        if (users_get.error != null && users_get.error != "") {
            Debug.Log ("Login failed");

        } else {
            string[] temp = users_get.text.Split ("*".ToCharArray ());

            if (temp.Length <= 2 || temp [0].ToString () == "Username or password false") {
                Debug.Log (temp [0].ToString ());
                login = false;
            } else {
                Debug.Log ("Login succeeded");
                login = true;
                callback (temp);
            }
        }
    }

    public void StartRoutineGetProjects(string id, string username, string url, Action<string[]> callback){
        StartCoroutine (GetProjects (id, username, url,callback));
    }

    public IEnumerator GetProjects (string id, string username, string url, Action<string[]> callback)
    {
        string privateURL = "http://" + url + "/Unity/myprojects.php";

        WWWForm form = new WWWForm ();
        form.AddField ("id", id);
        form.AddField ("username", username);

        WWW projects_get = new WWW (privateURL, form);

        yield return projects_get;

        if (projects_get.error != null && projects_get.error != "") {
            Debug.Log ("Internal error");
            callback (null);
        } else {
            string[] tempProjects = projects_get.text.Split ("|".ToCharArray ());

            callback (tempProjects);

        }
    }
</code>```

Second the Loginscript: Here we get Access to the variables from the databasescript.

```<code>    public void LoginStart ()
{
    StartCoroutine (Login ());
}

IEnumerator Login ()
{
    userName = inputUsername.text;
    password = inputPassword.text;

    string[] userData = null;
    bool wait2 = true;
    dbscript.StartRoutineCheckLoginCorrect (userName, password, url,(callback) =>{
        userData = callback;
        wait2 = false;
    });

    while (wait2) {
        yield return null;
    }

    id = userData [0];

    string[] stringArray = null;
    bool wait = true;
    dbscript.StartRoutineGetProjects (id, userName, url, (callback) => {
        stringArray = callback;
        wait = false;
    });
</code>```

Body:
we have some trouble with an IEnumerator and don't know how to retrieve an array out of it. We found out that you have to do it with a callback , but we don't really know how to use it. Here is the code of the IEnumerator and the void that needs to receive a string array from it.

public void StartRoutineGetProjects(string username, string password, string url){
    StartCoroutine(GetProjects(username, password, url));

    // here we dont know how to receive the array, need some help here
}

public IEnumerator GetProjects (string username, string password, string url, Action<string[]> callback)
{
    string privateURL = "http://" + url + "/Unity/myprojects.php";

    WWWForm form = new WWWForm ();
    form.AddField ("username", username);
    form.AddField ("password", password);

    // Send WWWForm
    WWW projects_get = new WWW (privateURL, form);

    if (projects_get.error != null && projects_get.error != "") {
        Debug.Log ("Internal Error");
    } else {
        // splitting the result at "|"
        string[] tempProjects = projects_get.text.Split ("|".ToCharArray ());

        yield return tempProjects;

        callback(tempProjects) // <-- here we want to return the array

    }
}

We would be glad for every help we can get.

Body:
[SOLVED] Yes finally it works. Thank you very much. We don't want to withhold our solution, so others can benefit from it.
So here is the code.
First the databasescript:

        public void StartRoutineCheckLoginCorrect (string username, string password, string url, Action<string[]> callback)
    {
        StartCoroutine (Login (username, password, url, callback));
    }

    IEnumerator Login (string username, string password, string url,Action<string[]> callback)
    {
        string loginURL = "http://" + url + "/Unity/mylogin.php";
        WWWForm form = new WWWForm ();
        form.AddField ("username", username);
        form.AddField ("password", password);

        WWW users_get = new WWW (loginURL, form);

        yield return users_get;

        if (users_get.error != null && users_get.error != "") {
            Debug.Log ("Login failed");

        } else {
            string[] temp = users_get.text.Split ("*".ToCharArray ());

            if (temp.Length <= 2 || temp [0].ToString () == "Username or password false") {
                Debug.Log (temp [0].ToString ());
                login = false;
            } else {
                Debug.Log ("Login succeeded");
                login = true;
                callback (temp);
            }
        }
    }

    public void StartRoutineGetProjects(string id, string username, string url, Action<string[]> callback){
        StartCoroutine (GetProjects (id, username, url,callback));
    }

    public IEnumerator GetProjects (string id, string username, string url, Action<string[]> callback)
    {
        string privateURL = "http://" + url + "/Unity/myprojects.php";

        WWWForm form = new WWWForm ();
        form.AddField ("id", id);
        form.AddField ("username", username);

        WWW projects_get = new WWW (privateURL, form);

        yield return projects_get;

        if (projects_get.error != null && projects_get.error != "") {
            Debug.Log ("Internal error");
            callback (null);
        } else {
            string[] tempProjects = projects_get.text.Split ("|".ToCharArray ());

            callback (tempProjects);

        }
    }

Second the Loginscript: Here we get Access to the variables from the databasescript.

    public void LoginStart ()
{
    StartCoroutine (Login ());
}

IEnumerator Login ()
{
    userName = inputUsername.text;
    password = inputPassword.text;

    string[] userData = null;
    bool wait2 = true;
    dbscript.StartRoutineCheckLoginCorrect (userName, password, url,(callback) =>{
        userData = callback;
        wait2 = false;
    });

    while (wait2) {
        yield return null;
    }

    id = userData [0];

    string[] stringArray = null;
    bool wait = true;
    dbscript.StartRoutineGetProjects (id, userName, url, (callback) => {
        stringArray = callback;
        wait = false;
    });


问:
How to skip a command if already exist in ansible
I have just started my hands on Ansible and trying some stuff on my own. I am running the below code:

```<code>---
- hosts: test-server
  remote_user: root
  tasks:
  - name: install java 8
    apt: name=openjdk-7-jdk update-cache=yes force=yes
  - name: add group
    command: addgroup hadoop
</code>```

and getting the below error:-

fatal: [10.150.0.3]: FAILED! => {"changed": true, "cmd": ["addgroup", "hadoop"], "delta": "0:00:00.033669", "end": "2017-12-08 12:50:15.342671", "msg": "non-zero return code", "rc": 1, "start": "2017-12-08 12:50:15.309002", "stderr": "addgroup: The group `hadoop' already exists.", "stderr_lines": ["addgroup: The group 'hadoop' already exists."], "stdout": "", "stdout_lines": []}

  to retry, use: --limit @/root/hdp1.retry

I can go ahead and remove the group 'hadoop' and try the code again and it will be succeeded. But I want to make some condition in the code so that if the group already exists that step will be ignored. I have researched on it and found we could use some stat_result like when: stat_result.stat.exists == False. But I am not sure how to incorporate it in the code.

答:
This is not how you should write Ansible code.

Ansible is a declarative language and you should use a native module group which provides idempotence:

```<code>- name: Ensure 'hadoop' group exists
  group:
    name: hadoop
    state: present
</code>```

This way you don't have to check anything. The same task will either create a new group (status changed) or report that the group already exists (status ok). The state after executing will be the same: group hadoop is present.

Unfortunately not every action you want to perform has been implemented as native modules, that's why command module exists. But it should be used as a last resort.

Body:
I have just started my hands on Ansible and trying some stuff on my own. I am running the below code:

---
- hosts: test-server
  remote_user: root
  tasks:
  - name: install java 8
    apt: name=openjdk-7-jdk update-cache=yes force=yes
  - name: add group
    command: addgroup hadoop

and getting the below error:-

fatal: [10.150.0.3]: FAILED! => {"changed": true, "cmd": ["addgroup", "hadoop"], "delta": "0:00:00.033669", "end": "2017-12-08 12:50:15.342671", "msg": "non-zero return code", "rc": 1, "start": "2017-12-08 12:50:15.309002", "stderr": "addgroup: The group `hadoop' already exists.", "stderr_lines": ["addgroup: The group 'hadoop' already exists."], "stdout": "", "stdout_lines": []}

  to retry, use: --limit @/root/hdp1.retry

I can go ahead and remove the group 'hadoop' and try the code again and it will be succeeded. But I want to make some condition in the code so that if the group already exists that step will be ignored. I have researched on it and found we could use some stat_result like when: stat_result.stat.exists == False. But I am not sure how to incorporate it in the code.

Body:
This is not how you should write Ansible code.

Ansible is a declarative language and you should use a native module group which provides idempotence:

- name: Ensure 'hadoop' group exists
  group:
    name: hadoop
    state: present

This way you don't have to check anything. The same task will either create a new group (status changed) or report that the group already exists (status ok). The state after executing will be the same: group hadoop is present.

Unfortunately not every action you want to perform has been implemented as native modules, that's why command module exists. But it should be used as a last resort.


问:
Form Validation in JavaScript-html
I've built a simple website that contains three pages. I created a form in home page and something goes wrong with my JavaScript - I'm having a problem in setting a field right next to the input field with a relevant message to the user telling him what they did wrong(prompt).
so I'm inputting below the homepage (the form which is in the body of the page -html) and the script itself which includes a simple function.

My purpose is to check if user fills the field name and after that they delete it, so I want to display a red color message that tells the user that this field is required.
I'd be glad if someone can help me with that.

function validateName(){
  var name=document.getElementById("fullName").value;
  if (name.length == null)
  {
    nameRequiredPromt("Name Is Required",fullNamePrompt,"white");
    return false;
  }
}

function nameRequiredPromt(message,promtLocation,color){
  document.getElementById(promtLocation).innerHTML=message;
  document.getElementById(promtLocation).style.color=color;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form" style="color:white;">
  <table>
    <tr>
      <td>
      FullName :
      </td>
      <td>
        <input type="text" placeholder="fullName" id="fullName"
        onkeyup="validateName()" type="text"/> <label id="fullNamePrompt">aaaa
        </label> <br>
      </td>
    </tr>
    <tr>
      <td>
      E-mail :
      </td>
      <td>
        <input type="email" placeholder="email" id="email"/><label
        id="emailPrompt"> </label><br>
      </td>
    </tr>
    <tr>
      <td>
      New Password :
      </td>
      <td>
        <input type="password" placeholder="password" id="newPassWord"/> <label
            id="PasswordPrompt"> </label><br>
      </td>
    </tr>
    <tr>
      <td>
      Repeat Password :
      </td>
      <td>
        <input type="password" placeholder="repeatedPassword"
        id="repeatedPassWord"/> <label id="repeatedPassWordPrompt"> </label><br>
      </td>
    </tr>
    <tr>
      <td>

      </td>
      <td>
        <input type="submit" value="submit" id="submit"/> <label
        id="submitPrompt"> </label><br>
      </td>
    </tr>
  </table>
</form></code>```

I did some checks to be sure that the script works and it did work so I think my problem is in the declaration of the label "id".

答:
switch

```<code>name.length == null
</code>```

to

```<code>!name.length
</code>```

length will be zero not null

also fullNamePrompt appears undefined

try nameRequiredPromt("Name Is Required","fullNamePrompt","white");

Fixed: name.length == null and also fullNamePrompt undefined and color: white to red

function validateName(){
  var name=document.getElementById("fullName").value;
  if (!name.length)
  {
    nameRequiredPromt("Name Is Required","fullNamePrompt","red");
    return false;
  }
}

function nameRequiredPromt(message,promtLocation,color){
  document.getElementById(promtLocation).innerHTML=message;
  document.getElementById(promtLocation).style.color=color;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form" style="color:white;">
  <table>
    <tr>
      <td>
      FullName :
      </td>
      <td>
        <input type="text" placeholder="fullName" id="fullName"
        onkeyup="validateName()" type="text"/> <label id="fullNamePrompt">aaaa
        </label> <br>
      </td>
    </tr>
    <tr>
      <td>
      E-mail :
      </td>
      <td>
        <input type="email" placeholder="email" id="email"/><label
        id="emailPrompt"> </label><br>
      </td>
    </tr>
    <tr>
      <td>
      New Password :
      </td>
      <td>
        <input type="password" placeholder="password" id="newPassWord"/> <label
            id="PasswordPrompt"> </label><br>
      </td>
    </tr>
    <tr>
      <td>
      Repeat Password :
      </td>
      <td>
        <input type="password" placeholder="repeatedPassword"
        id="repeatedPassWord"/> <label id="repeatedPassWordPrompt"> </label><br>
      </td>
    </tr>
    <tr>
      <td>

      </td>
      <td>
        <input type="submit" value="submit" id="submit" onclick="return validateName();"/> <label
        id="submitPrompt"> </label><br>
      </td>
    </tr>
  </table>
</form></code>```

Title: Form Validation in JavaScript-html

Body:
I've built a simple website that contains three pages. I created a form in home page and something goes wrong with my JavaScript - I'm having a problem in setting a field right next to the input field with a relevant message to the user telling him what they did wrong(prompt).
so I'm inputting below the homepage (the form which is in the body of the page -html) and the script itself which includes a simple function.

My purpose is to check if user fills the field name and after that they delete it, so I want to display a red color message that tells the user that this field is required.
I'd be glad if someone can help me with that.

function validateName(){
  var name=document.getElementById("fullName").value;
  if (name.length == null)
  {
    nameRequiredPromt("Name Is Required",fullNamePrompt,"white");
    return false;
  }
}

function nameRequiredPromt(message,promtLocation,color){
  document.getElementById(promtLocation).innerHTML=message;
  document.getElementById(promtLocation).style.color=color;
}

<form id="form" style="color:white;">

      FullName :

        <input type="text" placeholder="fullName" id="fullName"
        onkeyup="validateName()" type="text"/> aaaa

      E-mail :

        <input type="email" placeholder="email" id="email"/>

      New Password :

        <input type="password" placeholder="password" id="newPassWord"/>

      Repeat Password :

        <input type="password" placeholder="repeatedPassword"
        id="repeatedPassWord"/>

        <input type="submit" value="submit" id="submit"/>

</form>

I did some checks to be sure that the script works and it did work so I think my problem is in the declaration of the label "id".

Body:
switch

name.length == null

to

!name.length

length will be zero not null

also fullNamePrompt appears undefined

try nameRequiredPromt("Name Is Required","fullNamePrompt","white");

Fixed: name.length == null and also fullNamePrompt undefined and color: white to red

function validateName(){
  var name=document.getElementById("fullName").value;
  if (!name.length)
  {
    nameRequiredPromt("Name Is Required","fullNamePrompt","red");
    return false;
  }
}

function nameRequiredPromt(message,promtLocation,color){
  document.getElementById(promtLocation).innerHTML=message;
  document.getElementById(promtLocation).style.color=color;
}

<form id="form" style="color:white;">
  <table>
    <tr>
      <td>
      FullName :
      </td>
      <td>
        <input type="text" placeholder="fullName" id="fullName"
        onkeyup="validateName()" type="text"/> <label id="fullNamePrompt">aaaa
        </label> <br>
      </td>
    </tr>
    <tr>
      <td>
      E-mail :
      </td>
      <td>
        <input type="email" placeholder="email" id="email"/><label
        id="emailPrompt"> </label><br>
      </td>
    </tr>
    <tr>
      <td>
      New Password :
      </td>
      <td>
        <input type="password" placeholder="password" id="newPassWord"/> <label
            id="PasswordPrompt"> </label><br>
      </td>
    </tr>
    <tr>
      <td>
      Repeat Password :
      </td>
      <td>
        <input type="password" placeholder="repeatedPassword"
        id="repeatedPassWord"/> <label id="repeatedPassWordPrompt"> </label><br>
      </td>
    </tr>
    <tr>
      <td>

      </td>
      <td>
        <input type="submit" value="submit" id="submit" onclick="return validateName();"/> <label
        id="submitPrompt"> </label><br>
      </td>
    </tr>
  </table>
</form>


问:
Opening a new window in PHP using PrestaShop
I need help opening a new window by executing the validation code. The thing is that I need this when the next PHP file is run.</p>

```<code><?php

class hhpaymentvalidationModuleFrontController extends ModuleFrontController
{

    /**
     * Validation du paiement standard
     * Puis redirection vers la page de succès de commande
     */
    public function postProcess()
    {
         $cart = $this->context->cart;

       $this->abrir("http://davivienda.com");
//       0abrir("http://davivienda.com");

        if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) {
            Tools::redirect('index.php?controller=order&step=1');
        }

        $customer = new Customer($cart->id_customer);

        if (!Validate::isLoadedObject($customer)) {
            Tools::redirect('index.php?controller=order&step=1');
        }

        $currency = $this->context->currency;
        $total = (float)$cart->getOrderTotal(true, Cart::BOTH);

        //La command passe directement en statut payé
        $this->module->validateOrder((int)$cart->id, Configuration::get('PS_OS_PAYMENT'), $total, $this->module->displayName, null, array(), (int)$currency->id, false, $customer->secure_key);
        Tools::redirect('index.php?controller=order-confirmation&id_cart='.(int)$cart->id.'&id_module='.(int)$this->module->id.'&id_order='.$this->module->currentOrder.'&key='.$customer->secure_key);
    }

public function abrir( $param )
  {

    echo '<script type="text/javascript">';
    echo "window.open( '{$param}', 'ventana1', 'scrollbars=0, width=300, height=300' )";
    echo '</script>';
  }

}
</code>```

答:
You can't open new window/tab through a PHP script because it is server-side language. But you can pass some variable within your redirect url and use it in client side. Like

```<code>Tools::redirect('index.php?controller=order&step=1&popup=1');
</code>```

then use jQuery to open new window with your URL

```<code>$(document).ready(function() {
  let searchParams = new URLSearchParams(window.location.search);
  if (searchParams.has('popup')) {
    window.open('Your URL', 'window name', 'window settings')
  }
});
</code>```

Body:
I need help opening a new window by executing the validation code. The thing is that I need this when the next PHP file is run.

<?php

class hhpaymentvalidationModuleFrontController extends ModuleFrontController
{

    /**
     * Validation du paiement standard
     * Puis redirection vers la page de succès de commande
     */
    public function postProcess()
    {
         $cart = $this->context->cart;

       $this->abrir("http://davivienda.com");
//       0abrir("http://davivienda.com");

        if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) {
            Tools::redirect('index.php?controller=order&step=1');
        }

        $customer = new Customer($cart->id_customer);

        if (!Validate::isLoadedObject($customer)) {
            Tools::redirect('index.php?controller=order&step=1');
        }

        $currency = $this->context->currency;
        $total = (float)$cart->getOrderTotal(true, Cart::BOTH);

        //La command passe directement en statut payé
        $this->module->validateOrder((int)$cart->id, Configuration::get('PS_OS_PAYMENT'), $total, $this->module->displayName, null, array(), (int)$currency->id, false, $customer->secure_key);
        Tools::redirect('index.php?controller=order-confirmation&id_cart='.(int)$cart->id.'&id_module='.(int)$this->module->id.'&id_order='.$this->module->currentOrder.'&key='.$customer->secure_key);
    }

public function abrir( $param )
  {

    echo '';
  }

}

Body:
You can't open new window/tab through a PHP script because it is server-side language. But you can pass some variable within your redirect url and use it in client side. Like

Tools::redirect('index.php?controller=order&step=1&popup=1');

then use jQuery to open new window with your URL

$(document).ready(function() {
  let searchParams = new URLSearchParams(window.location.search);
  if (searchParams.has('popup')) {
    window.open('Your URL', 'window name', 'window settings')
  }
});


问:
Android referral tracking does not work
I am attempting to get Android Referral tracking to work. I am following the only documentation I have found here http://code.google.com/mobile/analytics/docs/android/#referrals  I have the following in my android manifest file

```<code><receiver
android:name="com.google.android.apps.analytics.AnalyticsReceiver"
android:exported="true">
    <intent-filter>
                <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
</receiver>
<receiver android:name="com.package.Receiver" android:exported="true">
        <intent-filter>
                <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
</receiver>
<uses-sdk android:minSdkVersion="4"/>
</code>```

com.package.Receiver starts with:

```<code>public void onReceive(Context paramContext, Intent paramIntent) {
        String str1 = paramIntent.getStringExtra("referrer");
        Log.i("myapp", "action: '" + paramIntent.getAction() + "'
referrer string: '" + str1 + "'");
</code>```

Also with a little bit of decompiling com.google.android.apps.analytics.AnalyticsReceiver has the following code in it:

```<code>public void onReceive(Context ctx, Intent intent)
/*     */   {
/*  24 */     String referrer = intent.getStringExtra("referrer");
/*     */
/*  26 */     if ((!
("com.android.vending.INSTALL_REFERRER".equals(intent.getAction())))
|| (referrer == null))
/*     */     {
/*  28 */       return;
/*     */     }
/*     */
/*  31 */     String formattedReferrer = formatReferrer(referrer);
/*     */
/*  33 */     if (formattedReferrer != null) {
/*  34 */       PersistentEventStore store = new
PersistentEventStore(ctx);
/*  35 */       store.setReferrer(formattedReferrer);
/*  36 */       Log.d("googleanalytics", new
StringBuilder().append("Stored
referrer:").append(formattedReferrer).toString());
/*     */     } else {
/*  38 */       Log.w("googleanalytics", "Badly formatted referrer, ignored");
/*     */     }
/*     */   }
</code>```

Note the two lines 36 and 38 that Log "googleanalytics" I have tried pushing the above app to the market, downloading it on my Nexus One (after uninstalling a previous version of the app). I have generated a link using the google page I linked to at the beginning of this post

http://www.google.com/url?sa=D&q=http://market.android.com/search%3Fq%3Dpname:com.package.app%26referrer%3Dutm_source%253Dgoogle%2526utm_medium%253Dcpc%2526utm_term%253Drunning%25252Bshoes%2526utm_content%253Dcontent1%2526utm_campaign%253Dslogan&usg=AFQjCNFctwqk1WgWl0bhiIBNVqy3U4OPRw

I attached logcat to my Nexus One while I download the app from that link, I do not see any logs from "googleanalytics" or "myapp". The rest of the google analytics library does work for my app. I.E. I see records on google analytics about pages hits etc. However all the traffic sources are "Direct Traffic". I am at a loss as to what is going on. Does anyone
have any insight into what I might be doing wrong?

答:
As is often the case I found my own answer. My problem was in my AndroidManifest.xml

I had the following in my manifest:

```<code><manifest>
    <application>
    </application>
    <receiver>
    </receiver>
    <uses-sd/>
 </manifest>
</code>```

The receiver tag was in the wrong spot. It should look like this

```<code><manifest>
    <application>
        <receiver>
        </receiver>
    </application>
    <uses-sd/>
 </manifest>
</code>```

I am now seeing the logs I expect to when I install the app. In a few hours hopefully Google Analytics will have the data as well.

Title: Android referral tracking does not work

Body:
I am attempting to get Android Referral tracking to work. I am following the only documentation I have found here http://code.google.com/mobile/analytics/docs/android/#referrals  I have the following in my android manifest file

<receiver
android:name="com.google.android.apps.analytics.AnalyticsReceiver"
android:exported="true">
    <intent-filter>
                <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
</receiver>
<receiver android:name="com.package.Receiver" android:exported="true">
        <intent-filter>
                <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
</receiver>
<uses-sdk android:minSdkVersion="4"/>

com.package.Receiver starts with:

public void onReceive(Context paramContext, Intent paramIntent) {
        String str1 = paramIntent.getStringExtra("referrer");
        Log.i("myapp", "action: '" + paramIntent.getAction() + "'
referrer string: '" + str1 + "'");

Also with a little bit of decompiling com.google.android.apps.analytics.AnalyticsReceiver has the following code in it:

public void onReceive(Context ctx, Intent intent)
/*     */   {
/*  24 */     String referrer = intent.getStringExtra("referrer");
/*     */
/*  26 */     if ((!
("com.android.vending.INSTALL_REFERRER".equals(intent.getAction())))
|| (referrer == null))
/*     */     {
/*  28 */       return;
/*     */     }
/*     */
/*  31 */     String formattedReferrer = formatReferrer(referrer);
/*     */
/*  33 */     if (formattedReferrer != null) {
/*  34 */       PersistentEventStore store = new
PersistentEventStore(ctx);
/*  35 */       store.setReferrer(formattedReferrer);
/*  36 */       Log.d("googleanalytics", new
StringBuilder().append("Stored
referrer:").append(formattedReferrer).toString());
/*     */     } else {
/*  38 */       Log.w("googleanalytics", "Badly formatted referrer, ignored");
/*     */     }
/*     */   }

Note the two lines 36 and 38 that Log "googleanalytics" I have tried pushing the above app to the market, downloading it on my Nexus One (after uninstalling a previous version of the app). I have generated a link using the google page I linked to at the beginning of this post

http://www.google.com/url?sa=D&q=http://market.android.com/search%3Fq%3Dpname:com.package.app%26referrer%3Dutm_source%253Dgoogle%2526utm_medium%253Dcpc%2526utm_term%253Drunning%25252Bshoes%2526utm_content%253Dcontent1%2526utm_campaign%253Dslogan&usg=AFQjCNFctwqk1WgWl0bhiIBNVqy3U4OPRw

I attached logcat to my Nexus One while I download the app from that link, I do not see any logs from "googleanalytics" or "myapp". The rest of the google analytics library does work for my app. I.E. I see records on google analytics about pages hits etc. However all the traffic sources are "Direct Traffic". I am at a loss as to what is going on. Does anyone
have any insight into what I might be doing wrong?

Body:
As is often the case I found my own answer. My problem was in my AndroidManifest.xml

I had the following in my manifest:

<manifest>
    <application>
    </application>
    <receiver>
    </receiver>
    <uses-sd/>
 </manifest>

The receiver tag was in the wrong spot. It should look like this

<manifest>
    <application>
        <receiver>
        </receiver>
    </application>
    <uses-sd/>
 </manifest>

I am now seeing the logs I expect to when I install the app. In a few hours hopefully Google Analytics will have the data as well.