问:
How to refresh a page or refresh ngOnInit() in ionic 2
i'm wondering if there is a way to refresh the ngOnInit() function or refresh the component. i don't wanna use the pull to refresh method. i want to do it on button click or tap. Thank you

home.ts file

```<code>  checkNetwork() {
  console.log("check internet");
this.platform.ready().then(() => {
  if(this.network.type == "none"){
    this.shouldHide = false;
    this.dividerHide = true;
  }
    let alert = this.alertCtrl.create({
        title: "Connection Status",
        subTitle: <string> this.network.type,
        buttons: ["OK"]
    });
  alert.present();
});
}
</code>```

home.html file

```<code><ion-card [hidden]="shouldHide">
<ion-card-header>
  <img src="img/sad.png" />
</ion-card-header>
<ion-card-content>
  <ion-card-title style="text-align:center">
    No INTERNET!
  </ion-card-title>
  <button ion-button full (click)="refreshPage($event)">Retry</button>
</ion-card-content>
</code>```

when the connection will be available i want the page to refresh

答:
Thank you all, this is how i managed it

home.ts file

```<code>ngOnInit(){
 this.LoadData();}

checkNetwork() {
  console.log("check internet");
this.platform.ready().then(() => {
  if(this.network.type == "none"){
    this.shouldHide = false;
    this.dividerHide = true;
  }else{
    this.shouldHide = true;
    this.dividerHide = false;
    this.presentLoading()
  }
});
}

refreshPage()
  {this.LoadData();
}

public LoadData(){...}
</code>```

Home.html file

```<code><ion-card [hidden]="shouldHide">
<ion-card-header>
  <img src="img/sad.png" />
</ion-card-header>
<ion-card-content>
  <ion-card-title style="text-align:center">
    Pas de connexion internet!
  </ion-card-title>
  <button ion-button full (click)="refreshPage()">Reessayer</button>
</ion-card-content>
</code>```

Body:
i'm wondering if there is a way to refresh the ngOnInit() function or refresh the component. i don't wanna use the pull to refresh method. i want to do it on button click or tap. Thank you

home.ts file

  checkNetwork() {
  console.log("check internet");
this.platform.ready().then(() => {
  if(this.network.type == "none"){
    this.shouldHide = false;
    this.dividerHide = true;
  }
    let alert = this.alertCtrl.create({
        title: "Connection Status",
        subTitle: <string> this.network.type,
        buttons: ["OK"]
    });
  alert.present();
});
}

home.html file

<ion-card [hidden]="shouldHide">
<ion-card-header>

</ion-card-header>
<ion-card-content>
  <ion-card-title style="text-align:center">
    No INTERNET!
  </ion-card-title>
  <button ion-button full (click)="refreshPage($event)">Retry</button>
</ion-card-content>

when the connection will be available i want the page to refresh

Body:
Thank you all, this is how i managed it

home.ts file

ngOnInit(){
 this.LoadData();}

checkNetwork() {
  console.log("check internet");
this.platform.ready().then(() => {
  if(this.network.type == "none"){
    this.shouldHide = false;
    this.dividerHide = true;
  }else{
    this.shouldHide = true;
    this.dividerHide = false;
    this.presentLoading()
  }
});
}

refreshPage()
  {this.LoadData();
}

public LoadData(){...}

Home.html file

<ion-card [hidden]="shouldHide">
<ion-card-header>
  <img src="img/sad.png" />
</ion-card-header>
<ion-card-content>
  <ion-card-title style="text-align:center">
    Pas de connexion internet!
  </ion-card-title>
  <button ion-button full (click)="refreshPage()">Reessayer</button>
</ion-card-content>


来源: stackexchange

问:
CSV formatting in rows and columns
I'm using the following code for converting my json file into csv:

```<code>import csv
import sys

txt_file = r"myfile.txt"
csv_file = r"out.csv"

in_txt = csv.reader(open(txt_file, "r"), delimiter = ',')
out_csv = csv.writer(open(csv_file, 'w'))

out_csv.writerows(in_txt)
</code>```

My output turns out to be formatted in a single row, and I want field with the tag "name" stores all the name in a single column not in extended rows.

How else can i make this work?

答: Just a thought have you tried a semicolon ; as the delimiter. I know you have csv indicated, but I recall seeing somewhere a semicolon will work.</p>

ContentLicense: CC BY-SA 3.0

Title: CSV formatting in rows and columns

Body:
I'm using the following code for converting my json file into csv:

import csv
import sys

txt_file = r"myfile.txt"
csv_file = r"out.csv"

in_txt = csv.reader(open(txt_file, "r"), delimiter = ',')
out_csv = csv.writer(open(csv_file, 'w'))

out_csv.writerows(in_txt)

My output turns out to be formatted in a single row, and I want field with the tag "name" stores all the name in a single column not in extended rows.

How else can i make this work?


问:
What is the equivalent of <template *ngFor in Angular 2?
I want to do something like this:

```<code><div *ngFor="let parent of parents">
    <div *ngFor="let child of parent.children">
    </div>
</div>
</code>```

but I don't want that extra outer div. From what i've been able to find searching, in Angular 1 I could achieve this by doing this:

```<code><template *ngFor="let parent of parents">
    <div *ngFor="let child of parent.children">
    </div>
</template>
</code>```

This doesn't seem to work in Angular 2 though. What's the correct way to do this?

答:
<ng-container> behaves like a <template> tag (it is not added to the DOM) but allows to use the more convenient *foo structural directive syntax:

```<code><ng-container *ngFor="let parent of parents">
    <div *ngFor="let child of parent.children">
    </div>
</ng-container>
</code>```

For more details about NgFor see https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html

Body:
I want to do something like this:

but I don't want that extra outer div. From what i've been able to find searching, in Angular 1 I could achieve this by doing this:

<template *ngFor="let parent of parents">

</template>

This doesn't seem to work in Angular 2 though. What's the correct way to do this?

Body:
<ng-container> behaves like a <template> tag (it is not added to the DOM) but allows to use the more convenient *foo structural directive syntax:

<ng-container *ngFor="let parent of parents">
    <div *ngFor="let child of parent.children">
    </div>
</ng-container>

For more details about NgFor see https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html


问:
Managing UIWindow height when on call
I am working in IOS application where all the work is done programmatically and we haven't used autolayout in complete application.

But I am facing one issue here from long time that when I got call or if my hotspot is on in that case my device status bar height changes.

So In this case how I can manage the application frame so that my UIView's will be managed.

Thank you in advance.

答:
A good way is to set the views and subviews autoresizing correctly through code(in your case).

OR
Add this method to your AppDelegate.m :

```<code>-(void)application:(UIApplication *)application didChangeStatusBarFrame (CGRect)oldStatusBarFrame
{
   // update layout
}
</code>```

You can update the layout here with code.

Try this for autoresizing views:

```<code>view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
</code>```

Title: Managing UIWindow height when on call

Body:
A good way is to set the views and subviews autoresizing correctly through code(in your case).

OR
Add this method to your AppDelegate.m :

-(void)application:(UIApplication *)application didChangeStatusBarFrame (CGRect)oldStatusBarFrame
{
   // update layout
}

You can update the layout here with code.

Try this for autoresizing views:

view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;


问:
How do I parse HTML in Rails?
I have a string with html tags in it saved.

```<code>=> "<p>hey man this is crazy g funk</p>\n<p>here i come with another crazy message from..</p>\n<p>dj eassssy d!@#!.</p>"
</code>```

How do you parse this so that it displays the way the HTML tags are implying?

I tried:

```<code>= Post.text
=h Post.text
= RedCloth.new(Post.text).to_html
= Hpricot(Post.text)
</code>```

答:
You want to do this:

```<code><%= raw Post.text %>
</code>```

or in haml

```<code>= raw Post.text
</code>```

The reason is because rails escapes your html and will convert
 into
.

ContentLicense: CC BY-SA 2.5

Title: How do I parse HTML in Rails?

Body:
I have a string with html tags in it saved.

=> "
hey man this is crazy g funk
\n
here i come with another crazy message from..
\n
dj eassssy d!@#!.
"

How do you parse this so that it displays the way the HTML tags are implying?

I tried:

= Post.text
=h Post.text
= RedCloth.new(Post.text).to_html
= Hpricot(Post.text)

Body:
You want to do this:

<%= raw Post.text %>

or in haml

= raw Post.text

The reason is because rails escapes your html and will convert <p> into &lt;p&gt;.


问:
select all checkboxes in angular 2?
I have to select all checkboxes if user select 'All Neighbourhoods' checkbox in angular.  I tried with below code. But not working. How to fix this in angular 2?

explore-list.Component.html

```<code>    <div class="checkbox_cont">
        <div class="checkbox ">
            <!--<input id="modal_checkbox1" type="checkbox" name="categories" unchecked="">-->
            <input type="checkbox" name="allneighbourhoods"  [value]="allneighbourhoods" (change)="neighbourhoodname [$event.target.getAttribute('value')]=$event.target.checked" id="allneighbourhoods" ng-click="toggleSelect($event)" />
            <label for="allneighbourhoods">All Neighbourhoods</label>
        </div>
    </div>
    <div class="modal_line"></div>
    <div class="checkbox " *ngFor="let neighbourhood of neighbourhoods;let i=index;">
        <input type="checkbox" name="neighbourhoodname[{{i}}]"  [value]="neighbourhood" (change)="neighbourhoodname [$event.target.getAttribute('value')]=$event.target.checked" id="{{neighbourhood}}"  [checked]='true' />
        <label for="{{neighbourhood}}">{{neighbourhood}}</label>
    </div>
</code>```

explore-list.Component.ts

```<code>    export class ExploreListComponent implements OnInit {
        neighbourhoodname={};

        toggleSelect = function(event){
            this.forEach(this.checkboxes, function(item){
                console.log(item);
                item.selected = event.target.checked;
            });
        }
    }
</code>```

neighbourhoods json

答:
You can add ngModel to the check boxes,

[(ngModel)]="neighbourhood.selected"

```<code><form #f="ngForm" novalidate>
   <div class="checkbox_cont">
       <div class="checkbox ">
           <input type="checkbox" id="allneighbourhoods" name="allneighbourhoods"  value="allneighbourhoods" (click)="toggleSelect($event)" />
           <label for="allneighbourhoods">All Neighbourhoods</label>
       </div>
   </div>
   <div class="modal_line"></div>
     <div class="checkbox " *ngFor="let neighbourhood of neighbourhoods;let i=index;">
      <input type="checkbox" name="neighbourhoodname[{{i}}]"  [checked]="neighbourhood.selected" value="neighbourhood.selected" id="{{neighbourhood.name}}" (change)="neighbourhood.selected = !(neighbourhood.selected)"/>
      <label for="{{neighbourhood.name}}">{{neighbourhood.name}}</label>
   </div>
   <input type="button" (click)="ApplyFilters(f.valid)"  class="btn btn-primary filters_btn" value="Apply Filters">
</form>
</code>```

Now, your function will be same,

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

 neighbourhoods = [{"name":"Taito"},{"name":"Shinjuku"},{"name":"Shibuya"}];

 toggleSelect = function(event){

        this.allneighbourhoods = event.target.checked;
        this.neighbourhoods.forEach(function(item){
         console.log(item);
         item.selected = event.target.checked;
      });

  }

  ApplyFilters(isValid: boolean) {
    var datas  = this.neighbourhoods.filter(function (data) { return data.selected == true });
  console.log(datas);
    if (!isValid) return;

 }
}
</code>```

I have added a selected property, so that the selected value of main checkbox will be the model value of all checkboxes.

Here is a Working DEMO

Title: select all checkboxes in angular 2?

Body:
I have to select all checkboxes if user select 'All Neighbourhoods' checkbox in angular.  I tried with below code. But not working. How to fix this in angular 2?

explore-list.Component.html

            <input type="checkbox" name="allneighbourhoods"  [value]="allneighbourhoods" (change)="neighbourhoodname [$event.target.getAttribute('value')]=$event.target.checked" id="allneighbourhoods" ng-click="toggleSelect($event)" />
            All Neighbourhoods

        <input type="checkbox" name="neighbourhoodname[{{i}}]"  [value]="neighbourhood" (change)="neighbourhoodname [$event.target.getAttribute('value')]=$event.target.checked" id="{{neighbourhood}}"  [checked]='true' />
        {{neighbourhood}}

explore-list.Component.ts

    export class ExploreListComponent implements OnInit {
        neighbourhoodname={};

        toggleSelect = function(event){
            this.forEach(this.checkboxes, function(item){
                console.log(item);
                item.selected = event.target.checked;
            });
        }
    }

neighbourhoods json

Body:
You can add ngModel to the check boxes,

[(ngModel)]="neighbourhood.selected"

<form #f="ngForm" novalidate>
   <div class="checkbox_cont">
       <div class="checkbox ">
           <input type="checkbox" id="allneighbourhoods" name="allneighbourhoods"  value="allneighbourhoods" (click)="toggleSelect($event)" />
           <label for="allneighbourhoods">All Neighbourhoods</label>
       </div>
   </div>
   <div class="modal_line"></div>
     <div class="checkbox " *ngFor="let neighbourhood of neighbourhoods;let i=index;">
      <input type="checkbox" name="neighbourhoodname[{{i}}]"  [checked]="neighbourhood.selected" value="neighbourhood.selected" id="{{neighbourhood.name}}" (change)="neighbourhood.selected = !(neighbourhood.selected)"/>
      <label for="{{neighbourhood.name}}">{{neighbourhood.name}}</label>
   </div>
   <input type="button" (click)="ApplyFilters(f.valid)"  class="btn btn-primary filters_btn" value="Apply Filters">
</form>

Now, your function will be same,

export class ExploreListComponent implements OnInit {

 neighbourhoods = [{"name":"Taito"},{"name":"Shinjuku"},{"name":"Shibuya"}];

 toggleSelect = function(event){

        this.allneighbourhoods = event.target.checked;
        this.neighbourhoods.forEach(function(item){
         console.log(item);
         item.selected = event.target.checked;
      });

  }

  ApplyFilters(isValid: boolean) {
    var datas  = this.neighbourhoods.filter(function (data) { return data.selected == true });
  console.log(datas);
    if (!isValid) return;

 }
}

I have added a selected property, so that the selected value of main checkbox will be the model value of all checkboxes.

Here is a Working DEMO


问:
Convert "informal" month-day index to a datetime index
I have a series whose index is in month-day format. It is not officially a datetime index. In addition, the series contains one datum for each day of the year:

```<code>       Data_Value
01-01         156
01-02         139
01-03         133
01-04         106
01-05         128
01-06         189
</code>```

My goal is to make a line plot with the "Data_Value" in the y-axis and the twelve months in the x-axis. But I want to plot the 365 data, not aggregate them into 12 months. Something like this:

Anyway, my first movement has been to plot the 365 data ignoring the fact of putting the months names in the x-axis:

```<code>s = np.array(s)
plt.figure()
plt.plot(s, '-o')
</code>```

But in the last command I got the error "ValueError: could not convert string to float: '12-31'".

Does anybody how to convert "informal" month-day index to a datetime index omitting the year? Or any other solution to reach my final goal of plotting the series? Thx.

Body:
I have a series whose index is in month-day format. It is not officially a datetime index. In addition, the series contains one datum for each day of the year:

       Data_Value
01-01         156
01-02         139
01-03         133
01-04         106
01-05         128
01-06         189

My goal is to make a line plot with the "Data_Value" in the y-axis and the twelve months in the x-axis. But I want to plot the 365 data, not aggregate them into 12 months. Something like this:

Anyway, my first movement has been to plot the 365 data ignoring the fact of putting the months names in the x-axis:

s = np.array(s)
plt.figure()
plt.plot(s, '-o')

But in the last command I got the error "ValueError: could not convert string to float: '12-31'".

Does anybody how to convert "informal" month-day index to a datetime index omitting the year? Or any other solution to reach my final goal of plotting the series? Thx.

Body:
You can use:

np.random.seed(100)
rng = pd.date_range('2017-01-01', periods=365).strftime('%m-%d')
df = pd.DataFrame({ 'Data_value': np.random.randint(1000, size=365)}, index=rng)
#print (df)

d = {'01':'Jan', '02':'Feb', '03':'Mar','04': 'Apr', '05':'May','06': 'Jun',
     '07':'Jul', '08':'Aug','09': 'Sep','10': 'Oct', '11':'Nov','12': 'Dec'}

#add _for match only first value of string to dict
d = {'_' + k:v for k, v in d.items()}

#add _ to index
df.index = '_' + df.index
#split values by - to MultiIndex
df.index = df.index.str.split('-', expand=True)

#reshape and replace NaN to 0
df = df['Data_value'].unstack(fill_value=0)
#rename index values by dict
df = df.rename(index=d)

print (df)
      01   02   03   04   05   06   07   08   09   10 ...    22   23   24  \
Jan  520  792  835  871  855   79  944  906  350  948 ...   316  570  912
Feb  900  415  897  141  757  723  612    4  603  955 ...     2  889  617
Mar  181  283  824  238  369  926  944  303  679  877 ...   618   30   17
Apr  693  846    0   13  185  460  362  131  582  643 ...   811   36  773
May  852   95  626  749  631   76  801  314  102  938 ...   419  407  765
Jun  677  870  122  628  186  295  619  734  819  286 ...    16  524  854
Jul  138  776  473  712  414  908  658  349  887  604 ...   389  435  346
Aug  385   14  883  289  148  168  536  477  442  796 ...   730  250  477
Sep   82  998  401  906  653  593  885  793  194  655 ...   944  754  506
Oct  144  819  182  183   83  502  356  554  957  760 ...    70  309  994
Nov  674  131  870  139  305  797  804  861  451  922 ...   723  119   71
Dec  781  304  466  544  294  296  497  693   93  398 ...   915  716  322

      25   26   27   28   29   30   31
Jan  507  649   93   86  386  667  876
Feb  478  403  994   63    0    0    0
Mar   53   68  946  488  347  475  979
Apr  839   38  214   94  738  170    0
May  521  944  496  789  409  438  262
Jun  466  621   67  220  223  788    0
Jul   34  451  862  974  694   77  212
Aug  736   74  437  798   67  668  933
Sep  693  657  705  298  861  172    0
Oct  736  943  944  905  689  821  879
Nov  829   93  498  804  123  554    0
Dec  141   87   65  324  182  640  343

[12 rows x 31 columns]

Last DataFrame.plot:

df.plot()


问:
Webpack 2 non-inline sourcemaps not showing up in chrome
I am trying to upgrade to Webpack 2.

I have added devtool: "source-map" to my webpack.config.js file.  When I build I get a bundle.js.map file created just like I would expect.

But when I open the page up in Chrome I don't get any source map information:

As you can see, the webpack:// folder that is usually there for source map info is missing.

But chrome says "Source Map detected".  (Clicking on that does not help.)  Clearly it kind of knows that I have source maps...  (Pressing ctrl+p just shows the bundled download files, not my source files.)  Am I wrong in thinking that Chrome should just automatically go request my source map file and use it?

However when I used devtool: "inline-source-source-map then it works.  But this adds the source maps to my javascript bundle file.  Making it 13 megs!  (Way too big to leave like that.)

How can I get Chrome to correctly load my bundle.js.map file?

I am running Webpack 2.3.2.

答:
Generally, there seem to be problems with source maps and webpack 2. For my project, I needed a rule for source maps, the SourceMapDevToolPlugin, and the devtool option "eval-source-map":

module:
        {

```<code>   rules:
        [
            ...
            {
                use: ['source-map-loader'],
                test: /\.js$/,
                enforce: 'pre',
                exclude: [
                    // these packages have problems with their sourcemaps
                    '/node_modules/ajv'
                ]
            }
        ]

    },

...

plugins: [
...
    new webpack.SourceMapDevToolPlugin({ compress: false,
                                         sourceMap: true,
                                         mangle: false,
                                         beautify: true,
                                         module: true,
                                         filename: '[file].map',
                                         columns: false      })
         ],

devtool: 'eval-source-map',
</code>```

Body:
Generally, there seem to be problems with source maps and webpack 2. For my project, I needed a rule for source maps, the SourceMapDevToolPlugin, and the devtool option "eval-source-map":

module:
        {

   rules:
        [
            ...
            {
                use: ['source-map-loader'],
                test: /\.js$/,
                enforce: 'pre',
                exclude: [
                    // these packages have problems with their sourcemaps
                    '/node_modules/ajv'
                ]
            }
        ]

    },

...

plugins: [
...
    new webpack.SourceMapDevToolPlugin({ compress: false,
                                         sourceMap: true,
                                         mangle: false,
                                         beautify: true,
                                         module: true,
                                         filename: '[file].map',
                                         columns: false      })
         ],

devtool: 'eval-source-map',


问:
Adding custom radio buttons in android

I am trying to get radiobutton effect for regular buttons in android

I have a simple android radio button below

Code for this is ::

activity_main.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >

        <RadioButton
            android:id="@+id/radio0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="RadioButton1" />

        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioButton2" />

        <RadioButton
            android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioButton3" />
    </RadioGroup>

</RelativeLayout>
</code>```

How to customize it as below::

Thanks !

[EDIT] using code from one of the answers

But the button name is overshadowed by the select option how to remove it ?

{EDIT} more changes

Finall changes should atleast i should know which button i have selected out of three radio buttons  .... is it possible to get as below ?

答:
Simple way try this

Create a new layout in drawable folder and name it custom_radiobutton (You can rename also)

```<code> <?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android" >
 <item android:state_checked="false"
android:drawable="@drawable/your_radio_off_image_name" />
 <item android:state_checked="true"
android:drawable="@drawable/your_radio_on_image_name" />
</selector>
</code>```

Use this in your layout activity

```<code><RadioButton
 android:id="@+id/radiobutton"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:button="@drawable/custom_radiobutton"/>
</code>```

Title: Adding custom radio buttons in android

Body:
I am trying to get radiobutton effect for regular buttons in android

I have a simple android radio button below

Code for this is ::

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >

        <RadioButton
            android:id="@+id/radio0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="RadioButton1" />

        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioButton2" />

        <RadioButton
            android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioButton3" />
    </RadioGroup>

</RelativeLayout>

How to customize it as below::

Thanks !

[EDIT] using code from one of the answers

But the button name is overshadowed by the select option how to remove it ?

{EDIT} more changes

Finall changes should atleast i should know which button i have selected out of three radio buttons  .... is it possible to get as below ?

Body:
Simple way try this

Create a new layout in drawable folder and name it custom_radiobutton (You can rename also)

 <?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android" >
 <item android:state_checked="false"
android:drawable="@drawable/your_radio_off_image_name" />
 <item android:state_checked="true"
android:drawable="@drawable/your_radio_on_image_name" />
</selector>

Use this in your layout activity

<RadioButton
 android:id="@+id/radiobutton"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:button="@drawable/custom_radiobutton"/>


问:
how to write case and group by in hive query
This is my hive table:

```<code>course   dept    subject   status

btech     cse     java     pass
btech     cse     hadoop   fail
btech     cse     cg       detained
btech     cse     cc       pass
btech      it     daa      pass
btech      it     wt       pass
btech      it     cnn      pass
mba        hr     hrlaw    pass
mba        hr     hrguid   absent
mtech      cs     java     pass
mtech      cs     cd       pass
mtech      cs     cp       detained
</code>```

I want to query this table to retrieve data in the following way:

```<code>course   dept    status

btech     cse     fail
btech      it     pass
mba        hr     absent
mtech      cs     fail
</code>```

First, it will check for "fail" or "detained" in the status of each dept and course grouped together. If it finds "fail" or "detained", it will output "fail" as the status. Else, if an "absent" is found in the same group, it will output "absent" as the status. Else, it will output "pass".

I got an error message when I ran the following query:

```<code>select course,dept,
case
when status in ( 'fail','detained') then 'fail'
when status in ( 'absent') then 'absent'
when status in ( 'pass') then 'pass'
else null
end as Final_Status
from college
group by course,dept;
</code>```

答:
Try this.</p>

```<code>select course,dept,
collect_set(
case
when status in ( 'fail','detained') then 'FAILED'
when status in ( 'absent') then 'absent'
when status in ( 'pass') then 'PASSED'
else null
end ) as Final_Status
from college
group by course,dept;
</code>```

Body:
This is my hive table:

course   dept    subject   status

btech     cse     java     pass
btech     cse     hadoop   fail
btech     cse     cg       detained
btech     cse     cc       pass
btech      it     daa      pass
btech      it     wt       pass
btech      it     cnn      pass
mba        hr     hrlaw    pass
mba        hr     hrguid   absent
mtech      cs     java     pass
mtech      cs     cd       pass
mtech      cs     cp       detained

I want to query this table to retrieve data in the following way:

course   dept    status

btech     cse     fail
btech      it     pass
mba        hr     absent
mtech      cs     fail

First, it will check for "fail" or "detained" in the status of each dept and course grouped together. If it finds "fail" or "detained", it will output "fail" as the status. Else, if an "absent" is found in the same group, it will output "absent" as the status. Else, it will output "pass".

I got an error message when I ran the following query:

select course,dept,
case
when status in ( 'fail','detained') then 'fail'
when status in ( 'absent') then 'absent'
when status in ( 'pass') then 'pass'
else null
end as Final_Status
from college
group by course,dept;

Body:
Try this.

select course,dept,
collect_set(
case
when status in ( 'fail','detained') then 'FAILED'
when status in ( 'absent') then 'absent'
when status in ( 'pass') then 'PASSED'
else null
end ) as Final_Status
from college
group by course,dept;


问:
PHP preg_replace in javascript
I had working preg_replace in PHP, but I had to move it to JavaScript code and it doesn't work there. I've searched here in topics, but haven't found working solution for me...
My PHP looked like:

```<code>preg_replace('/^\d+_/', '', $docTypes);
</code>```

And now, my JS looks like, important thing, var documentTypes is object:

```<code>   var documentTypesObj = {};
   var counter = 0;
   {foreach $documentTypes as $key =>$value}
   documentTypesObj[counter + '_' + {$key}] = {$value};
   counter++;
   {/foreach}

    var documentTypes = documentTypesObj;

    documentTypes = documentTypes.map(d => { return d.replace(/^\d+_/g, "")});

    console.log(documentTypes);
</code>```

Inside var documentTypes are values with prefix, which I have to remove. Values are for example:

```<code>0_xxxx
1_xxxx
2_xxxx
</code>```

Thank you for advices!

答:
If it's an array: </p>

```<code>var docs = ["0_xxx", "1_yyy", "2_zzzz"];
docs = docs.map(d => { return d.replace(/^\d+_/g, "")});
</code>```

Title: PHP preg_replace in javascript

Body:
I had working preg_replace in PHP, but I had to move it to JavaScript code and it doesn't work there. I've searched here in topics, but haven't found working solution for me...
My PHP looked like:

preg_replace('/^\d+_/', '', $docTypes);

And now, my JS looks like, important thing, var documentTypes is object:

   var documentTypesObj = {};
   var counter = 0;
   {foreach $documentTypes as $key =>$value}
   documentTypesObj[counter + '_' + {$key}] = {$value};
   counter++;
   {/foreach}

    var documentTypes = documentTypesObj;

    documentTypes = documentTypes.map(d => { return d.replace(/^\d+_/g, "")});

    console.log(documentTypes);

Inside var documentTypes are values with prefix, which I have to remove. Values are for example:

0_xxxx
1_xxxx
2_xxxx

Thank you for advices!

Body:
If it's an array:

var docs = ["0_xxx", "1_yyy", "2_zzzz"];
docs = docs.map(d => { return d.replace(/^\d+_/g, "")});


问:
How to Intent into specific Tab Fragment?
T have two Activities: MainActivity and LoginActivity. I have one Fragment too, the name is TabFragment (with a TabLayout), its parent is MainActivity. How can I intent into the specific TabFragment from my Login Activity.

This is my Main Activity:

```<code> protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        id = getIntent().getStringExtra("id");

        if (savedInstanceState == null) {
     getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new FragmentUtama()).commit();
            getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new TabFragment()).commit();
        }
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        sharedPreferences = getSharedPreferences("login.conf", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        String username = sharedPreferences.getString("username", "");
        String password = sharedPreferences.getString("password", "");
        Log.d(TAG, "Username:"+username+"\npassword:"+password);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }
</code>```

And This my Tab Fragment:

```<code>  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.viewpager, null);

        tabLayout = (TabLayout)view.findViewById(R.id.tabs);
        viewPager = (ViewPager)view.findViewById(R.id.viewpager);
        viewPager.setAdapter(new Adapterbaru(getChildFragmentManager()));
         tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });
        Long tsLong = System.currentTimeMillis()/1000;
        String ts = tsLong.toString();

        return view;
    }

    public interface OnFragmentInteractionListener {

        void onFragmentInteraction(Uri uri);
    }
    public class Adapterbaru extends FragmentPagerAdapter{
        public Adapterbaru(FragmentManager fm){
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0 : {
                    return new Fragmentone();
                }
                case 1 : {
                    return new FragmentTwo();

                }
                case 2 : {
                    return new Fragmenttree();

                }
            }
            return null;
        }

        @Override
        public int getCount() {
           return jumlah_tab;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch(position){
                case 0 : {
                    return "First";

                }
                case 1 : {
                    return "Second";

                }
                case 2 : {
                    return "Third";
                }
            }
            return null;
        }
</code>```

答:
You can check it as

```<code>if(isFromLogin){
  viewpager.setCurrentItem(specificFragmentPosition);
}
</code>```

Happy Coding!

Body:
T have two Activities: MainActivity and LoginActivity. I have one Fragment too, the name is TabFragment (with a TabLayout), its parent is MainActivity. How can I intent into the specific TabFragment from my Login Activity.

This is my Main Activity:

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        id = getIntent().getStringExtra("id");

        if (savedInstanceState == null) {
     getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new FragmentUtama()).commit();
            getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new TabFragment()).commit();
        }
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        sharedPreferences = getSharedPreferences("login.conf", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        String username = sharedPreferences.getString("username", "");
        String password = sharedPreferences.getString("password", "");
        Log.d(TAG, "Username:"+username+"\npassword:"+password);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }

And This my Tab Fragment:

  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.viewpager, null);

        tabLayout = (TabLayout)view.findViewById(R.id.tabs);
        viewPager = (ViewPager)view.findViewById(R.id.viewpager);
        viewPager.setAdapter(new Adapterbaru(getChildFragmentManager()));
         tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });
        Long tsLong = System.currentTimeMillis()/1000;
        String ts = tsLong.toString();

        return view;
    }

    public interface OnFragmentInteractionListener {

        void onFragmentInteraction(Uri uri);
    }
    public class Adapterbaru extends FragmentPagerAdapter{
        public Adapterbaru(FragmentManager fm){
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0 : {
                    return new Fragmentone();
                }
                case 1 : {
                    return new FragmentTwo();

                }
                case 2 : {
                    return new Fragmenttree();

                }
            }
            return null;
        }

        @Override
        public int getCount() {
           return jumlah_tab;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch(position){
                case 0 : {
                    return "First";

                }
                case 1 : {
                    return "Second";

                }
                case 2 : {
                    return "Third";
                }
            }
            return null;
        }

Body:
You can check it as

if(isFromLogin){
  viewpager.setCurrentItem(specificFragmentPosition);
}

Happy Coding!


问:
django pass field-name as variable in get_or_create
I am trying to see if I can pass field name as a variable in get_or_create (since I have a function where the key in the kwargs can vary)

Like so:

```<code>def convert_value(cell_value, field_to_lookup):
        rem_obj, created = Rem.objects.get_or_create(field_to_lookup=cell_value)
        print ('created? ',created)
        return rem_obj
</code>```

The above wont work since it would look for 'field_to_lookup' as the key.

This post suggests using getattr but not sure if that'll be applicable in this case since I will again need to assign the output to a variable

答:
This post helped. Now passing the field-value pair as dict which allows passing variables for field names. Here's the code:

```<code>def convert_value(cell_value, field_to_lookup):
        rem_obj, created = Rem.objects.get_or_create(**{field_to_lookup:cell_value})
        print ('created? ',created)
        return rem_obj
</code>```

Alternatively, I could directly just pass the dict to the function.

Body:
I am trying to see if I can pass field name as a variable in get_or_create (since I have a function where the key in the kwargs can vary)

Like so:

def convert_value(cell_value, field_to_lookup):
        rem_obj, created = Rem.objects.get_or_create(field_to_lookup=cell_value)
        print ('created? ',created)
        return rem_obj

The above wont work since it would look for 'field_to_lookup' as the key.

This post suggests using getattr but not sure if that'll be applicable in this case since I will again need to assign the output to a variable

Body:
This post helped. Now passing the field-value pair as dict which allows passing variables for field names. Here's the code:

def convert_value(cell_value, field_to_lookup):
        rem_obj, created = Rem.objects.get_or_create(**{field_to_lookup:cell_value})
        print ('created? ',created)
        return rem_obj

Alternatively, I could directly just pass the dict to the function.


问:
Get current location, latitude and longitude in ReactNative using react-native-maps
I am developing a map location. When I click in some particular place I get the latitude and longitude, but not the current location, latitude and longitude.

I don't know how to find out.

How can I get them and how can I put the marker at that position?

Here is my code:

```<code>class Maps extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      region: {
        latitude:       LATITUDE,
        longitude:      LONGITUDE,
        latitudeDelta:  LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      },
      marker: {
        latlng:{
          latitude:       null,
          longitude:      null,
          latitudeDelta:  LATITUDE_DELTA,
          longitudeDelta: LONGITUDE_DELTA
        }
      }
    }
  }

  componentDidMount() {
    navigator.geolocation.getCurrentPosition (
      (position) => { alert("value:" + position) },
      (error)    => { console.log(error) },
      {
        enableHighAccuracy: true,
        timeout:            20000,
        maximumAge:         10000
      }
    )
  }

  onMapPress(e) {
    alert("coordinates:" + JSON.stringify(e.nativeEvent.coordinate))
      this.setState({
        marker: [{ coordinate: e.nativeEvent.coordinate }]
      })
    }

  render() {
    return (
      <View style={styles.container}>
        <View style={{flexGrow:1}}>
          <MapView
            ref="map"
            provider={this.props.provider}
            style={styles.map}
            onPress={this.onMapPress.bind(this)}
            provider = {PROVIDER_DEFAULT}
            mapType="standard"
            zoomEnabled={true}
            pitchEnabled={true}
            showsUserLocation={true}
            followsUserLocation={true}
            showsCompass={true}
            showsBuildings={true}
            showsTraffic={true}
            showsIndoors={true}>
          </MapView>
        </View>
      </View>
    )
  }
}
</code>```

答:
I suggest you to read this official documentation about geolocalisation: https://facebook.github.io/react-native/docs/geolocation.html

Then, with the current location, you can put that information into your state:

```<code>navigator.geolocation.getCurrentPosition((position) => {
    this.setState({position: {longitude: position.longitude, latitude: position.latitude}});
}, (error) => {
    alert(JSON.stringify(error))
}, {
    enableHighAccuracy: true,
    timeout: 20000,
    maximumAge: 1000
});
</code>```

You will be able next, in your render method, to compose your final view with a marker:

```<code>render() {
  return (
    <MapView ...>
      <MapView.Marker
        coordinate={this.state.position}
        title="title"
        description="description"
      />
    </MapView>
  )
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am developing a map location. When I click in some particular place I get the latitude and longitude, but not the current location, latitude and longitude.

I don't know how to find out.

How can I get them and how can I put the marker at that position?

Here is my code:

class Maps extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      region: {
        latitude:       LATITUDE,
        longitude:      LONGITUDE,
        latitudeDelta:  LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      },
      marker: {
        latlng:{
          latitude:       null,
          longitude:      null,
          latitudeDelta:  LATITUDE_DELTA,
          longitudeDelta: LONGITUDE_DELTA
        }
      }
    }
  }

  componentDidMount() {
    navigator.geolocation.getCurrentPosition (
      (position) => { alert("value:" + position) },
      (error)    => { console.log(error) },
      {
        enableHighAccuracy: true,
        timeout:            20000,
        maximumAge:         10000
      }
    )
  }

  onMapPress(e) {
    alert("coordinates:" + JSON.stringify(e.nativeEvent.coordinate))
      this.setState({
        marker: [{ coordinate: e.nativeEvent.coordinate }]
      })
    }

  render() {
    return (
      <View style={styles.container}>
        <View style={{flexGrow:1}}>
          <MapView
            ref="map"
            provider={this.props.provider}
            style={styles.map}
            onPress={this.onMapPress.bind(this)}
            provider = {PROVIDER_DEFAULT}
            mapType="standard"
            zoomEnabled={true}
            pitchEnabled={true}
            showsUserLocation={true}
            followsUserLocation={true}
            showsCompass={true}
            showsBuildings={true}
            showsTraffic={true}
            showsIndoors={true}>
          </MapView>
        </View>
      </View>
    )
  }
}

Body:
I suggest you to read this official documentation about geolocalisation: https://facebook.github.io/react-native/docs/geolocation.html

Then, with the current location, you can put that information into your state:

navigator.geolocation.getCurrentPosition((position) => {
    this.setState({position: {longitude: position.longitude, latitude: position.latitude}});
}, (error) => {
    alert(JSON.stringify(error))
}, {
    enableHighAccuracy: true,
    timeout: 20000,
    maximumAge: 1000
});

You will be able next, in your render method, to compose your final view with a marker:

render() {
  return (
    <MapView ...>
      <MapView.Marker
        coordinate={this.state.position}
        title="title"
        description="description"
      />
    </MapView>
  )
}


问:
Elastic search/lucene index on multiple words?
When I search say car engine(this is first time any user has searched for this keyword) in  Elastic search/lucene , does search engine search the index for individual words in index table first and then find intersection. For example :- Say engine found the 10
documents for car and then it will search for engine say it got 5 documents. Now in 5 documents(minimal no of documents), it will search for car.  It has found 2 documents.

Now search engine will rank it based on above results . Is this how multiple words are searched in index table at high level ?

For future searches against same keyword, does search engine make new entry for key car engine in index table ?

答:
Yes, it does search for individual terms and takes the intersection or union of the results, according to your query. It uses something called an "inverted index" which it generates, as and when the documents to be searched are "indexed" into elasticsearch.
Indexing operations are different from searching. So, No, it wouldn't index user searches unless you tell it to (in your application).
The basic functioning of elasticsearch can be split into two parts:

Indexing. You create an index of documents by indexing all the documents that you want to search in. These documents could be anything from your MySQL store, or from Logstash etc, or could be made up of users' search queries that your application indexes into a relevant elastic index.

Searching. You search for the indexed documents using some keywords that could be user generated or application generated or a mixture, using ElasticSearch queries (DSL). If a result is found (according to your query) then elasticsearch returns the relevant records.

I'd encourage you to read this doc for a better understanding of how elastic searches docs:
https://www.elastic.co/blog/found-elasticsearch-from-the-bottom-up


问:
Convert DataTable columns to typed IEnumerable[]
How to convert DataTable columns to IEnumerable[] which is required to create a data frame in R.NET

I have the following code:

```<code>DataTable dt = CreateDateTable();
REngine e = REngine.GetInstance();
IEnumerable[] columns = new IEnumerable[dt.Columns.Count];
string[] columnNames = dt.Columns.Cast<DataColumn>()
                       .Select(x => x.ColumnName)
                       .ToArray();

for(int i=0; i<dt.Columns.Count; i++)
    //This is the place where I am stuck. How to convert column to base type array instead of object array
    columns[i] = dt.Rows.Cast<DataRow>().Select(row => row[i]).ToArray();

DataFrame df = e.CreateDataFrame(columns: columns,
 columnNames: columnNames,
 stringsAsFactors: false);
</code>```

I get the following exception:

```<code>Test 'XXX.ReadResultsTest' failed: System.NotSupportedException : Cannot convert type System.Object[] to an R vector
       w RDotNet.REngineExtension.ToVector(REngine engine, IEnumerable values)
       w System.Array.ConvertAll[TInput,TOutput](TInput[] array, Converter`2 converter)
       w RDotNet.REngineExtension.CreateDataFrame(REngine engine, IEnumerable[] columns, String[] columnNames, String[] rowNames, Boolean checkRows, Boolean checkNames, Boolean stringsAsFactors)
</code>```

DataTable has columns of different types and I don't know what are the types so I cannot do like in this example with double:

```<code>for (int i = 0; i < dt.Columns.Count; i++)
        columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<double>(i)).ToArray();
</code>```

UPDATE

So far I have an ugly solution, can it be done better?

```<code>for (int i = 0; i < dt.Columns.Count; i++)
{
    switch (Type.GetTypeCode(dt.Columns[i].DataType))
    {
        case TypeCode.String:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<string>(i)).ToArray();
            break;

        case TypeCode.Double:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<double>(i)).ToArray();
            break;

        case TypeCode.Int32:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<int>(i)).ToArray();
            break;

        case TypeCode.Int64:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<long>(i)).ToArray();
            break;

        default:
            //columns[i] = dt.Rows.Cast<DataRow>().Select(row => row[i]).ToArray();
            throw new InvalidOperationException(String.Format("Type {0} is not supported", dt.Columns[i].DataType.Name));
    }
}
</code>```

答:
```<code>public IEnumerable<int> ListToIenumerable(IEnumerable enumerable)
{
    List<int> list = new List<int>();

    foreach (object obj in enumerable)
    {
        list.Add(Convert.ToInt32(obj.ToString()));
    }

    IEnumerable<int> returnValue = list.ToArray();

    return returnValue;
}
</code>```

Body:
How to convert DataTable columns to IEnumerable[] which is required to create a data frame in R.NET

I have the following code:

DataTable dt = CreateDateTable();
REngine e = REngine.GetInstance();
IEnumerable[] columns = new IEnumerable[dt.Columns.Count];
string[] columnNames = dt.Columns.Cast<DataColumn>()
                       .Select(x => x.ColumnName)
                       .ToArray();

for(int i=0; i<dt.Columns.Count; i++)
    //This is the place where I am stuck. How to convert column to base type array instead of object array
    columns[i] = dt.Rows.Cast<DataRow>().Select(row => row[i]).ToArray();

DataFrame df = e.CreateDataFrame(columns: columns,
 columnNames: columnNames,
 stringsAsFactors: false);

I get the following exception:

Test 'XXX.ReadResultsTest' failed: System.NotSupportedException : Cannot convert type System.Object[] to an R vector
       w RDotNet.REngineExtension.ToVector(REngine engine, IEnumerable values)
       w System.Array.ConvertAll[TInput,TOutput](TInput[] array, Converter`2 converter)
       w RDotNet.REngineExtension.CreateDataFrame(REngine engine, IEnumerable[] columns, String[] columnNames, String[] rowNames, Boolean checkRows, Boolean checkNames, Boolean stringsAsFactors)

DataTable has columns of different types and I don't know what are the types so I cannot do like in this example with double:

for (int i = 0; i < dt.Columns.Count; i++)
        columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<double>(i)).ToArray();

UPDATE

So far I have an ugly solution, can it be done better?

for (int i = 0; i < dt.Columns.Count; i++)
{
    switch (Type.GetTypeCode(dt.Columns[i].DataType))
    {
        case TypeCode.String:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<string>(i)).ToArray();
            break;

        case TypeCode.Double:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<double>(i)).ToArray();
            break;

        case TypeCode.Int32:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<int>(i)).ToArray();
            break;

        case TypeCode.Int64:
            columns[i] = dt.Rows.Cast<DataRow>().Select(row => row.Field<long>(i)).ToArray();
            break;

        default:
            //columns[i] = dt.Rows.Cast<DataRow>().Select(row => row[i]).ToArray();
            throw new InvalidOperationException(String.Format("Type {0} is not supported", dt.Columns[i].DataType.Name));
    }
}


问:
Add default value to select list in Laravel form::select
Simple question, I hope.

I need to add a default value to my select list 'Please Select', and set it to disabled.

```<code><select name="myselect" id="myselect">
  <option value="" disabled>Please Select</option>
  <option value="1">Item 1</option>
  <option value="2">Item 2</option>
</select>
</code>```

My current laravel form::select is

```<code>{{
Form::select(
    'myselect',
    $categories,
    $myselectedcategories,
    array(
        'class' => 'form-control',
        'id' => 'myselect'
    )
}}
</code>```

How can I amend this to include the default option value?

答:
Add 'placeholder' => 'Please Select' into the Form::select.

```<code>{!!
  Form::select(
    'myselect',
    $categories,
    null,
    ['class' => 'form-control', 'placeholder' => 'Please Select'])
!!}
</code>```

Body:
Simple question, I hope.

I need to add a default value to my select list 'Please Select', and set it to disabled.

<select name="myselect" id="myselect">
  <option value="" disabled>Please Select</option>
  <option value="1">Item 1</option>
  <option value="2">Item 2</option>
</select>

My current laravel form::select is

{{
Form::select(
    'myselect',
    $categories,
    $myselectedcategories,
    array(
        'class' => 'form-control',
        'id' => 'myselect'
    )
}}

How can I amend this to include the default option value?

Body:
Add 'placeholder' => 'Please Select' into the Form::select.

{!!
  Form::select(
    'myselect',
    $categories,
    null,
    ['class' => 'form-control', 'placeholder' => 'Please Select'])
!!}


问:
Capturing method in if statement in a list comprehension
I have a following use case:

```<code>[(x, f(x)) for x in list_x if f(x) == cond(x)]
</code>```

Above list comprehension, I think makes a f(x) call twice? How do I avoid that and capture value of f(x) so that f(x) is called only once.

I guess, easy fix is to convert above list comprehension into a for loop, but am curious if it can be done efficiently using a list comprehension.

答:
If you do not want to call f twice, you can apply f to the list first

[a for a in map(lambda x: (x, f(x)), list_x) if a[1] == cond(x)]

Body:
I have a following use case:

[(x, f(x)) for x in list_x if f(x) == cond(x)]

Above list comprehension, I think makes a f(x) call twice? How do I avoid that and capture value of f(x) so that f(x) is called only once.

I guess, easy fix is to convert above list comprehension into a for loop, but am curious if it can be done efficiently using a list comprehension.


问:
How to configure Jacoco and Sonar in Maven build tool?
I need to setup the code coverage in SonarQube using Jacoco. For this, I need to use the Maven build tool for building purpose.

I would need the code settings for this configuration. Please help me in this regard. SonarQube is running on Remote server.

Please help me how to setup the above configuration for one of my projects. I need to check the code coverage % in SonarQube (HTML) for my project X.

Thanks,
Gopi

答:
Open Google

Type jacoco sonarqube

Open first result and read documentation (or look at the sample project)


问:
How to change src in Floating Action Button from Service.class?
I have method, which fulfills actions by pressing on buttons in notification.

```<code>private void handleIncomingActions(Intent playbackAction) {
        if (playbackAction == null || playbackAction.getAction() == null) {
            return;
        }

        String actionString = playbackAction.getAction();

        if (actionString.equalsIgnoreCase(ACTION_PLAY)) {
            if (mediaPlayer != null) {
                playMedia();
            }
        }
        if (actionString.equalsIgnoreCase(ACTION_PAUSE)) {
            if (mediaPlayer != null) {
                pauseMedia();

                //HERE NEED TO CHANGE SRC
            }
        }
        if (actionString.equalsIgnoreCase(ACTION_CLOSE)) {
            if (mediaPlayer != null) {
                stopService(new Intent(this, MediaService.class));
                getApplicationContext().unbindService(PlayerActivity.serviceConnection);
                PlayerActivity.serviceBound = false;

                //HERE NEED TO CHANGE SRC

            }
        }
    }
</code>```

In two cases I need to change FAB's icon in my PlayerActivity class from Service.class.
How can I access the FAB without using "static" and without singleton?

答:
In service:

```<code>public static final String SERVICE_REQUEST = "com.example.app.service.SERVICE_REQUEST";
// ...
Intent data = new Intent(SERVICE_REQUEST);
LocalBroadcastManager.getInstance(ServiceClass.this).sendBroadcast(data);
</code>```

In Activity:

```<code>// in onCreate for example
reseiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // update your fab here
            }
}
// ...
@Override
public void onStop() {
       LocalBroadcastManager.getInstance(this).unregisterReceiver(reseiver);
       super.onStop();
}

@Override
public void onStart() {
        super.onStart();
        LocalBroadcastManager.getInstance(this).registerReceiver(reseiver, new IntentFilter(ServiceClass.SERVICE_REQUEST));
}
</code>```

Body:
I have method, which fulfills actions by pressing on buttons in notification.

private void handleIncomingActions(Intent playbackAction) {
        if (playbackAction == null || playbackAction.getAction() == null) {
            return;
        }

        String actionString = playbackAction.getAction();

        if (actionString.equalsIgnoreCase(ACTION_PLAY)) {
            if (mediaPlayer != null) {
                playMedia();
            }
        }
        if (actionString.equalsIgnoreCase(ACTION_PAUSE)) {
            if (mediaPlayer != null) {
                pauseMedia();

                //HERE NEED TO CHANGE SRC
            }
        }
        if (actionString.equalsIgnoreCase(ACTION_CLOSE)) {
            if (mediaPlayer != null) {
                stopService(new Intent(this, MediaService.class));
                getApplicationContext().unbindService(PlayerActivity.serviceConnection);
                PlayerActivity.serviceBound = false;

                //HERE NEED TO CHANGE SRC

            }
        }
    }

In two cases I need to change FAB's icon in my PlayerActivity class from Service.class.
How can I access the FAB without using "static" and without singleton?

Body:
In service:

public static final String SERVICE_REQUEST = "com.example.app.service.SERVICE_REQUEST";
// ...
Intent data = new Intent(SERVICE_REQUEST);
LocalBroadcastManager.getInstance(ServiceClass.this).sendBroadcast(data);

In Activity:

// in onCreate for example
reseiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // update your fab here
            }
}
// ...
@Override
public void onStop() {
       LocalBroadcastManager.getInstance(this).unregisterReceiver(reseiver);
       super.onStop();
}

@Override
public void onStart() {
        super.onStart();
        LocalBroadcastManager.getInstance(this).registerReceiver(reseiver, new IntentFilter(ServiceClass.SERVICE_REQUEST));
}


问:
vsnprintf returns the size over given buffer size
Very long string with myPrint() function is going to crash.

I thought that vsnprintf() cannot return the written size over buffer length from linux man page.

My expected string is truncated string in buffer size but that's totally wrong from below test code.

What is wrong below??

```<code>void myPrint(const char* fmt, ...)
{
    char buffer[512] = {0,};

    va_list arg;
    va_start(arg, fmt);

    int r = vsnprintf(buffer, 511, fmt, arg); // buffer size is given
    if (r > 0)              // works correctly
        buffer[r+1] = '\0'; // crash because r is 200,000
    va_end(arg);
}

int main(int, char**)
{
    const char * data = "abcdefg...." // assuming that a length is 200,000 byte string
    myPrint("%s\n", data);
}
</code>```

答:
No, the vsnprintf very specifically returns the number of characters required for the full string. C11 7.21.6.12p3:

The vsnprintf function returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred. Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than n.

Additionally, the input size should be the full buffer size, e.g. here 512. Then vsnprintf would write up to 511 characters and add the terminating '\0' after the last character written. (C11 snprintf description):

Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.

Additionally, note that (7.21.6.5p2):

[...] Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than n.

That is, if your buffer is an array of 512 char and you passed in 512, the string was properly written and not truncated iff the return n value of *snprintf is 0 <= n <= 511

Beware that the Microsoft Visual C++ had a very broken function by the name _vsnprintf that:

[...] return the number of characters written if the number of characters to write is less than or equal to count; if the number of characters to write is greater than count, these functions return -1 indicating that output has been truncated.

Finally, if you're writing only Linux / Glibc specific code, you could also consider using vasprintf that would dynamically allocate a buffer large enough to hold the entire string.

Body:
Very long string with myPrint() function is going to crash.

I thought that vsnprintf() cannot return the written size over buffer length from linux man page.

My expected string is truncated string in buffer size but that's totally wrong from below test code.

What is wrong below??

void myPrint(const char* fmt, ...)
{
    char buffer[512] = {0,};

    va_list arg;
    va_start(arg, fmt);

    int r = vsnprintf(buffer, 511, fmt, arg); // buffer size is given
    if (r > 0)              // works correctly
        buffer[r+1] = '\0'; // crash because r is 200,000
    va_end(arg);
}

int main(int, char**)
{
    const char * data = "abcdefg...." // assuming that a length is 200,000 byte string
    myPrint("%s\n", data);
}


问:
Why the call to thrust::inclusive_scan is much slower than subsequent calls?
When I call thrust::inclusive_scan several times, why is the first time much slower than subsequent calls?

Here is the code

```<code>float ttime;
for(int i=0;i<5;i++){
     cudaEvent_t start,stop;
     cudaEventCreate(&start);
     cudaEventCreate(&stop);
     cudaEventRecord(start,0);

     thrust::device_ptr<int > din(device_input);
     thrust::device_ptr<int > dout(device_output);
     thrust::inclusive_scan(din,din+N,dout);

     cudaEventRecord(stop,0);
     cudaEventSynchronize(stop);
     cudaEventElapsedTime(&ttime,start,stop);
     printf("cost %fms\n",ttime);
}
</code>```

I run it on GTX1080,and result are

```<code>cost 39.180702ms
cost 0.200704ms
cost 0.201728ms
cost 0.202752ms
cost 0.197632ms
</code>```

Can anybody help explain this?

答:
Adding a few words to Talonmies' valid answer:

In this question of mine, there's some cocktail-napkin calculations of how much time the CUDA initialization takes.

I also suggest that, to separate the loading+init time for libthrust from the runtime API initialization overhead, you perform the following three phases:

Execute some dummy kernel which doesn't write any output - twice (T_1, T2_)

Make a libthrust call with (almost) no data (but which does launch a kernel) - twice (T_3, T_4)

Now time your real calls

Roughly, (T_1 - T_2) is the CUDA load & init time and (T_3 - T_4) is the thrust load & init time.

Looking at the profiling timeline is helpful; CUDA will "shove" most of its initialization into one of your API calls - but not necessarily the first one.

Body:
When I call thrust::inclusive_scan several times, why is the first time much slower than subsequent calls?

Here is the code

float ttime;
for(int i=0;i<5;i++){
     cudaEvent_t start,stop;
     cudaEventCreate(&start);
     cudaEventCreate(&stop);
     cudaEventRecord(start,0);

     thrust::device_ptr<int > din(device_input);
     thrust::device_ptr<int > dout(device_output);
     thrust::inclusive_scan(din,din+N,dout);

     cudaEventRecord(stop,0);
     cudaEventSynchronize(stop);
     cudaEventElapsedTime(&ttime,start,stop);
     printf("cost %fms\n",ttime);
}

I run it on GTX1080,and result are

cost 39.180702ms
cost 0.200704ms
cost 0.201728ms
cost 0.202752ms
cost 0.197632ms

Can anybody help explain this?


问:
Unity : Can't read the string from the JSON file
i'm trying to read stringfrom json file and pass it to my UI Text in Unity, The issue i'm facing is that the string is always null and i'm not sure why, Right now i find the JSON file path and read it, but when i try to access the string it's null. i'm not sure how to read the json. I really don't understand how this all works. i'm new to JSON format and i'm trying to practice it. This is my first approach. i'm using Unity Engine, and i'm reading the json file using Streaming Assets

Read Data from Json Script:

```<code>using UnityEngine;
using System.IO;

public class ReadFromJson : MonoBehaviour {

private string _filePath = "myText.json";

Data dh;

string str;
 void Start()
{

    LoadGameData();
}

public Data getCurrentRoundData()
{
    return dh;
}

private void LoadGameData()
{
    string filePath = Path.Combine(Application.streamingAssetsPath, _filePath);

    if (File.Exists(filePath))
    {

        string dataAsJSON = File.ReadAllText(filePath);
        DataHolder loadedData = JsonUtility.FromJson<DataHolder>(dataAsJSON);

        dh = loadedData.data;
        str = loadedData.data.TextToPass;
        Debug.Log("My Text is" + dh.TextToPass);

        Debug.Log("Path Exist");

    }

    else
    {
        Debug.LogError("CANNOT LOAD GAME DATA!!");
    }

}

}
</code>```

Manager that applies the json data to my UI Text

```<code>    DataController = FindObjectOfType<ReadFromJson>();

    _data = DataController.getCurrentRoundData();

    myText.text = _data.TextToPass;
</code>```

DataHolder.cs

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]

public class DataHolder {

public Data data;
</code>```

}

Json Text

```<code>{"DataHolder":

    {
        "TextToPass":"I'm A Horse"
    }
</code>```

}

Data.cs

```<code>[System.Serializable]
public class Data {

public string TextToPass ;
}
</code>```

What i get is TextToPass is null

答:
The model has Data, the JSON has DataHolder. The JSON library doesn't assume that "oh, there's one property, they must have meant that" - it goes by name, and the names don't match.

Either change your types, or change the JSON. They need to match. As an illustration, a type of the form:

```<code>public class Foo {
    public int Bar {get;set;}
}
</code>```

matches JSON of the form:

```<code>{ "Bar": 123 }
</code>```

Body:
i'm trying to read stringfrom json file and pass it to my UI Text in Unity, The issue i'm facing is that the string is always null and i'm not sure why, Right now i find the JSON file path and read it, but when i try to access the string it's null. i'm not sure how to read the json. I really don't understand how this all works. i'm new to JSON format and i'm trying to practice it. This is my first approach. i'm using Unity Engine, and i'm reading the json file using Streaming Assets

Read Data from Json Script:

using UnityEngine;
using System.IO;

public class ReadFromJson : MonoBehaviour {

private string _filePath = "myText.json";

Data dh;

string str;
 void Start()
{

    LoadGameData();
}

public Data getCurrentRoundData()
{
    return dh;
}

private void LoadGameData()
{
    string filePath = Path.Combine(Application.streamingAssetsPath, _filePath);

    if (File.Exists(filePath))
    {

        string dataAsJSON = File.ReadAllText(filePath);
        DataHolder loadedData = JsonUtility.FromJson<DataHolder>(dataAsJSON);

        dh = loadedData.data;
        str = loadedData.data.TextToPass;
        Debug.Log("My Text is" + dh.TextToPass);

        Debug.Log("Path Exist");

    }

    else
    {
        Debug.LogError("CANNOT LOAD GAME DATA!!");
    }

}

}

Manager that applies the json data to my UI Text

    DataController = FindObjectOfType<ReadFromJson>();

    _data = DataController.getCurrentRoundData();

    myText.text = _data.TextToPass;

DataHolder.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]

public class DataHolder {

public Data data;

}

Json Text

{"DataHolder":

    {
        "TextToPass":"I'm A Horse"
    }

}

Data.cs

[System.Serializable]
public class Data {

public string TextToPass ;
}

What i get is TextToPass is null

Body:
The model has Data, the JSON has DataHolder. The JSON library doesn't assume that "oh, there's one property, they must have meant that" - it goes by name, and the names don't match.

Either change your types, or change the JSON. They need to match. As an illustration, a type of the form:

public class Foo {
    public int Bar {get;set;}
}

matches JSON of the form:

{ "Bar": 123 }


问:
C# Do I need TRY/CATCH in order to throw?
If all I want to do is throw the exception up a level when it occurs?

```<code>private void TryCatch()
{
   try
   {
       foo();
   }
   catch (Exception ex)
   {
       throw;
   }
}

private void NoTryCatch()
{
   foo();
}
</code>```

Aren't these two methods the same?

If an exception occurs in TryCatch it will be thrown up a level and if an exception occurs in NoTryCatch, the exception will also be thrown up a level.

This question came about after using ReSharper and noticing that it suggested to remove the try/catch block as it was redundant.

答: ReSharper is correct.  Unless you actually intend to catch and do something about an exception there is no point including a try..catch block.</p>

OwnerDisplayName: Petrolios

LastEditorDisplayName: Jon Skeet

Body:
If all I want to do is throw the exception up a level when it occurs?

private void TryCatch()
{
   try
   {
       foo();
   }
   catch (Exception ex)
   {
       throw;
   }
}

private void NoTryCatch()
{
   foo();
}

Aren't these two methods the same?

If an exception occurs in TryCatch it will be thrown up a level and if an exception occurs in NoTryCatch, the exception will also be thrown up a level.

This question came about after using ReSharper and noticing that it suggested to remove the try/catch block as it was redundant.

OwnerDisplayName: AnthonyWJones


问:
A quickie: python, terminal "print command not found"
Been using terminal to run python scripts written in textwrangler for about 18 months. Decided to look at possibility of moving to an IDE so downloaded a couple of trial versions. Just downloaded BBEedit and suddenly having problems executing script, either from BBedit or Textwrangler. The following code:

```<code>print "Please work"

for i in range(50):
    print i
</code>```

yields the following error message:

```<code>/Users/paulpatterson/Documents/Python/Scripts/t.py: line 1: print: command not found
/Users/paulpatterson/Documents/Python/Scripts/t.py: line 3: syntax error near unexpected token `('
/Users/paulpatterson/Documents/Python/Scripts/t.py: line 3: `for i in range(50):'
</code>```

Some files still work okay, but I'm struggling to figure out why others now aren't -
not even sure if BBedit download has caused the problem.
Can anyone help?

答:
Also, be aware that this form of print (print-as-command) is changing to print-as-a-function when you convert to Python 3.  So:

```<code>print "please work"
</code>```

will have to be changed to:

```<code>print ("please work")
</code>```

Body:
Been using terminal to run python scripts written in textwrangler for about 18 months. Decided to look at possibility of moving to an IDE so downloaded a couple of trial versions. Just downloaded BBEedit and suddenly having problems executing script, either from BBedit or Textwrangler. The following code:

print "Please work"

for i in range(50):
    print i

yields the following error message:

/Users/paulpatterson/Documents/Python/Scripts/t.py: line 1: print: command not found
/Users/paulpatterson/Documents/Python/Scripts/t.py: line 3: syntax error near unexpected token `('
/Users/paulpatterson/Documents/Python/Scripts/t.py: line 3: `for i in range(50):'

Some files still work okay, but I'm struggling to figure out why others now aren't -
not even sure if BBedit download has caused the problem.
Can anyone help?

Body:
Also, be aware that this form of print (print-as-command) is changing to print-as-a-function when you convert to Python 3.  So:

print "please work"

will have to be changed to:

print ("please work")


问:
c# Problems with Localization, CultureInfo Norway and Denmark, translations don't work
I am trying to implement language translations of my existing web application.
The application is written in C#, Javascript and Angular JS.

I have successfully added (resx files) and tested the following languages:

-German
-Spanish
-Finnish
-French
-Italian
-Dutch
-Swedish

In the same way, I have also added the resources for Danish and Norwegian, but these fail.

I did the exact same thing, at the exact same time to implement all of them; I checked all properties and everything else matches.

Is there anything special about these two cultures that might be hindering this?

I called them Translations.no.resx for norwegian and Translations.dk.resx for Danish, and I added the routes accordingly, like this:

```<code>    private static readonly List<LanguageModel> AllLanguages = new List<LanguageModel>
    {
        new LanguageModel { Name = "English", TwoLetterIsoLanguageName = "en" },
        new LanguageModel { Name = "Svenska", TwoLetterIsoLanguageName = "sv" },
        // ITCR-1182 adding translations. DK and NO are not working.
        new LanguageModel { Name = "Dansk", TwoLetterIsoLanguageName = "dk" },
        new LanguageModel { Name = "Español", TwoLetterIsoLanguageName = "es" },
        new LanguageModel { Name = "Deutsch", TwoLetterIsoLanguageName = "de" },
        new LanguageModel { Name = "Nederlands", TwoLetterIsoLanguageName = "nl" },
        new LanguageModel { Name = "Française", TwoLetterIsoLanguageName = "fr" },
        new LanguageModel { Name = "Norsk", TwoLetterIsoLanguageName = "no" },
        new LanguageModel { Name = "Suomi", TwoLetterIsoLanguageName = "fi" },
        new LanguageModel { Name = "Italiano", TwoLetterIsoLanguageName = "it" }
    };
</code>```

This list is used currently for the language selector, but it will be generated from the database... as soon as I can get them to work!

All language resources are called accordingly:

```<code>Translations.{TwoLetterIsoLanguageName}.resx
</code>```

Except the english one which is default, Translations.resx

The routes are formed like this

```<code>    routes.MapRoute(
        name: "Default",
        url: "{culture}/{site}/{controller}/{action}/{id}",
        defaults: new { culture = LocalizationAttribute.DefaultCulture, site = LayoutController.DefaultSite, controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
</code>```

And as I said, it works for every language except Norwegian and Danish. Or rather, the routes show up as they should, with the "no" or "dk" references, but the translations are not mapping, the default english comes up instead.

Is there something else I can provide, that may help?

答:
The answer was provided by @PalleDue and @LocEngineer, I was using the wrong two-letter ISO code:

DA for Danish
NN or NB for Norwegian, but better to use NB because it's used by ~85% of the population.

Thank you guys!!!

Body:
I am trying to implement language translations of my existing web application.
The application is written in C#, Javascript and Angular JS.

I have successfully added (resx files) and tested the following languages:

-German
-Spanish
-Finnish
-French
-Italian
-Dutch
-Swedish

In the same way, I have also added the resources for Danish and Norwegian, but these fail.

I did the exact same thing, at the exact same time to implement all of them; I checked all properties and everything else matches.

Is there anything special about these two cultures that might be hindering this?

I called them Translations.no.resx for norwegian and Translations.dk.resx for Danish, and I added the routes accordingly, like this:

    private static readonly List<LanguageModel> AllLanguages = new List<LanguageModel>
    {
        new LanguageModel { Name = "English", TwoLetterIsoLanguageName = "en" },
        new LanguageModel { Name = "Svenska", TwoLetterIsoLanguageName = "sv" },
        // ITCR-1182 adding translations. DK and NO are not working.
        new LanguageModel { Name = "Dansk", TwoLetterIsoLanguageName = "dk" },
        new LanguageModel { Name = "Español", TwoLetterIsoLanguageName = "es" },
        new LanguageModel { Name = "Deutsch", TwoLetterIsoLanguageName = "de" },
        new LanguageModel { Name = "Nederlands", TwoLetterIsoLanguageName = "nl" },
        new LanguageModel { Name = "Française", TwoLetterIsoLanguageName = "fr" },
        new LanguageModel { Name = "Norsk", TwoLetterIsoLanguageName = "no" },
        new LanguageModel { Name = "Suomi", TwoLetterIsoLanguageName = "fi" },
        new LanguageModel { Name = "Italiano", TwoLetterIsoLanguageName = "it" }
    };

This list is used currently for the language selector, but it will be generated from the database... as soon as I can get them to work!

All language resources are called accordingly:

Translations.{TwoLetterIsoLanguageName}.resx

Except the english one which is default, Translations.resx

The routes are formed like this

    routes.MapRoute(
        name: "Default",
        url: "{culture}/{site}/{controller}/{action}/{id}",
        defaults: new { culture = LocalizationAttribute.DefaultCulture, site = LayoutController.DefaultSite, controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

And as I said, it works for every language except Norwegian and Danish. Or rather, the routes show up as they should, with the "no" or "dk" references, but the translations are not mapping, the default english comes up instead.

Is there something else I can provide, that may help?


问:
Check if JSON object exist (Postman)
I am trying to write a test in Postman to check if JSON keys are present in the response I received from the server.

The response:

```<code>{
  "Result": 0,
  "ResponseStatus": {
    "ErrorCode": null,
    "Message": null,
    "StackTrace": null,
    "Errors": null
  },
  "ResponseHeader": {
    "Succeeded": true,
    "Errors": null
  },
  "SessionId": "XXX-XXX-XXX"
}
</code>```

I want to check "Results, Errorcode, Message,Succeeded" etc..

Thanks!

答:
You could check the response scheme using:</p>

```<code>var jsonData = JSON.parse(responseBody);
tests['response json contain Results'] = _.has(jsonData, 'Results');
</code>```

Title: Check if JSON object exist (Postman)

Body:
I am trying to write a test in Postman to check if JSON keys are present in the response I received from the server.

The response:

{
  "Result": 0,
  "ResponseStatus": {
    "ErrorCode": null,
    "Message": null,
    "StackTrace": null,
    "Errors": null
  },
  "ResponseHeader": {
    "Succeeded": true,
    "Errors": null
  },
  "SessionId": "XXX-XXX-XXX"
}

I want to check "Results, Errorcode, Message,Succeeded" etc..

Thanks!

Body:
You could check the response scheme using:

var jsonData = JSON.parse(responseBody);
tests['response json contain Results'] = _.has(jsonData, 'Results');


问:
How to show and hide menu based on start and scroll
I have two menus on a page, I am trying to show the one when the page is loaded and the other when there is a scroll.
This is my page Link

I would like to show the white part when position is at the top
and the blue part when there is a scroll past the top position

This is what am trying presently

```<code> <script type="text/javascript" src="//code.jquery.com/jquery-git.js"></script>
<script type='text/javascript'>//<![CDATA[
$(function(){
// Hide Header on on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('header').outerHeight();

$(window).scroll(function(event){
    didScroll = true;
});

setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
    }
}, 250);

function hasScrolled() {
    var st = $(this).scrollTop();

    // Make sure they scroll more than delta
    if(Math.abs(lastScrollTop - st) <= delta)
        return;

    // If they scrolled down and are past the navbar, add class .nav-up.
    // This is necessary so you never see what is "behind" the navbar.
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
        $('header').removeClass('nav-bar-below op-page-header cf').addClass('banner include-nav');
    } else {
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $('header').removeClass('banner include-nav').addClass('nav-bar-below op-page-header cf');
        }
    }

    lastScrollTop = st;
}
});//]]>

</script>
</code>```

can some one please help its not working for me

答:
sample code for fix the menu at top position.</p>

```<code>$(document).scroll(function() {

var y = $(document).scrollTop()
var header = $('.include-nav');
var blue-menu = $('.cf');
var screenHeight = header.height();
if (y >= screenHeight) {
    blue-menu.css({
        position : "fixed",
        "top" : "0",
        "left" : "0"
    });
    header.css("position", "relative");
} else {
    blue-menu.css("position", "relative");
}
});
</code>```

Body:
I have two menus on a page, I am trying to show the one when the page is loaded and the other when there is a scroll.
This is my page Link

I would like to show the white part when position is at the top
and the blue part when there is a scroll past the top position

This is what am trying presently

can some one please help its not working for me

Body:
sample code for fix the menu at top position.

$(document).scroll(function() {

var y = $(document).scrollTop()
var header = $('.include-nav');
var blue-menu = $('.cf');
var screenHeight = header.height();
if (y >= screenHeight) {
    blue-menu.css({
        position : "fixed",
        "top" : "0",
        "left" : "0"
    });
    header.css("position", "relative");
} else {
    blue-menu.css("position", "relative");
}
});


问:
Comma constant in internal library
I want to use constant char/string comma (,) in my code.

Where I can find static final variable in standard library? If there is not such a place, can you point me popular external library for that?

EDIT: I don't want to create my own constant, I want to use it from JDK (or external library if it not exists)

答:
What would be the benefit of depending on an external library for just a constant? If your not using code from that library I would advise to define the constant in your own project.

If you use the comma-constant all over the place in your code try to find a common interface/class and define the constant in that interface/class.

If there is no common interface/class create an enum with a logical name. Do not create a class or interface just for wrapping a constant.

If you need the comma-constant in a single class declare it in that class. (either protected or private).

See also What is the best way to implement constants in Java?

But if you really want to use a third-party library, you might want to look at:
https://github.com/google/caja/blob/master/src/com/google/caja/lexer/Punctuation.java

Title: Comma constant in internal library


答:
There are multiple things to fix here:

You can give complete buffer size to vsnprintf:

```<code>int r = vsnprintf(buffer, sizeof buffer, fmt, arg);
</code>```

You don't need to nul terminate buffer after call. vsnprintf truncates too long string correctly.

vsnprintf returns the length that would have been, if truncation hadn't happened. If you need to detect truncation, you can do it as follows:

```<code>if(r >= sizeof buffer) {
     // Buffer was too small
}
</code>```

Title: vsnprintf returns the size over given buffer size

Body:
There are multiple things to fix here:

You can give complete buffer size to vsnprintf:

int r = vsnprintf(buffer, sizeof buffer, fmt, arg);

You don't need to nul terminate buffer after call. vsnprintf truncates too long string correctly.

vsnprintf returns the length that would have been, if truncation hadn't happened. If you need to detect truncation, you can do it as follows:

if(r >= sizeof buffer) {
     // Buffer was too small
}


问:
Reading xml ref attribute in .NET
I can do this in Xpath, but unfortunately for this particular project I am unable to use xpath.

I have the following node selected:

```<code><client href="http://somewebsitehere.com" rel="needthisdata"></client>

clientnode.Attributes["href"].Value
</code>```

correctly returns "http://somewebsitehere.com", but

```<code>clientnode.Attributes["rel"].Value
</code>```

does not work?

What am I doing wrong here?

Full Usage:

```<code>foreach (XmlNode clientnode in clientnodelist)
{
    MessageBox.Show(clientnode.Attributes["rel"].Value);
}
</code>```

The above gives a NullReferenceException, whereas replacing "rel" with "href" works fine.

I'm sure i've selected the correct node as well as innertext matches, as well as attribute.count returning 2.

答: I would add a break at the loop and take a look at what is in my Attributes collection. Also, for kicks, try changing "rel" to something else to see if it fixes the issue.</p>

Title: Reading xml ref attribute in .NET

Body:
I can do this in Xpath, but unfortunately for this particular project I am unable to use xpath.

I have the following node selected:

<client href="http://somewebsitehere.com" rel="needthisdata"></client>

clientnode.Attributes["href"].Value

correctly returns "http://somewebsitehere.com", but

clientnode.Attributes["rel"].Value

does not work?

What am I doing wrong here?

Full Usage:

foreach (XmlNode clientnode in clientnodelist)
{
    MessageBox.Show(clientnode.Attributes["rel"].Value);
}

The above gives a NullReferenceException, whereas replacing "rel" with "href" works fine.

I'm sure i've selected the correct node as well as innertext matches, as well as attribute.count returning 2.


问:
How to list available storage drivers in docker?
Info shows:

```<code>Storage Driver: vfs
</code>```

Kubernetes doesn't like it, kubeadm init prints:

```<code>unsupported graph driver: vfs
</code>```

How to list available drivers?

答:
You can't get a list of available drivers by the command line (with a "service docker status" you can only see the one being used), you can learn about it on the documentation and proceed to configurate one of your choice, they don't work "out of the box" but it's just a question of OS configuration.

P.D.: if  want a quick workaround use a previous version like docker 12.3.

Body:
Info shows:

Storage Driver: vfs

Kubernetes doesn't like it, kubeadm init prints:

unsupported graph driver: vfs

How to list available drivers?


问:
Forward to a servlet from another servlet or from a filter
Usually I forward to a jsp or to a mapped URL from a servlet, and internet is full of such examples. But I need to forward a request to an internal servlet. For example by using its full class name, without mapping that servlet to an URL. How to forward a request to an internal servlet from another servlet, or from a filter?</p>

答:
As Shadab commented, I think you should use @WebServlet annotation (and RequestDispatcher), for example:

```<code>@WebServlet(urlPatterns = { "/sample" })
public class SampleServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    RequestDispatcher dispatch = req.getRequestDispatcher( "/forwardpath");
    dispatch.forward(req, res);
}
</code>```

SampleServlet -> ForwardedServlet

```<code>@WebServlet(urlPatterns = { "/forwardpath" })
public class ForwardedServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ...
}
</code>```

Body:
As Shadab commented, I think you should use @WebServlet annotation (and RequestDispatcher), for example:

@WebServlet(urlPatterns = { "/sample" })
public class SampleServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    RequestDispatcher dispatch = req.getRequestDispatcher( "/forwardpath");
    dispatch.forward(req, res);
}

SampleServlet -> ForwardedServlet

@WebServlet(urlPatterns = { "/forwardpath" })
public class ForwardedServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ...
}


问:
How to make multiple validation on field in angular 2?
I am building a model driven form in angular 2 and i want a specific field to have a range validation between 1-1000 and can also have values of 2000 and 2001,

I tried to put it in compose:

this.configForm.controls["field"].setValidators(Validators.compose([Validators.required,CustomValidators.equal(2000),CustomValidators.equal(2001), CustomValidators.range([1,1000])]));```

But it didn't work..

How to do it?

Thanks.

答:
According to FormControl API,
there is no setValidators() function.

You may have to add new control:

```<code>this.configForm.controls["field"] = new FormControl('',Validators.compose([
      Validators.required,CustomValidators.equal(2000),
      CustomValidators.equal(2001),
      CustomValidators.range([1,1000])]
      ));
</code>```

Body:
I am building a model driven form in angular 2 and i want a specific field to have a range validation between 1-1000 and can also have values of 2000 and 2001,

I tried to put it in compose:

this.configForm.controls["field"].setValidators(Validators.compose([Validators.required,CustomValidators.equal(2000),CustomValidators.equal(2001), CustomValidators.range([1,1000])]));

But it didn't work..

How to do it?

Thanks.

Body:
According to FormControl API,
there is no setValidators() function.

You may have to add new control:

this.configForm.controls["field"] = new FormControl('',Validators.compose([
      Validators.required,CustomValidators.equal(2000),
      CustomValidators.equal(2001),
      CustomValidators.range([1,1000])]
      ));


问:
Cron job schedule
I want to schedule cron job for my app to do a particular task. How can i schedule in this requirement?

Requirement:
cron-data.js should be run every Mondays to Fridays hourly from 9:30am - 3:30pm.

Title: Cron job schedule

Body:
This is just an example. You can try this and customize as per your requirement.

# Use the hash sign to prefix a comment
# +---------------- minute (0 - 59)
# |  +------------- hour (0 - 23)
# |  |  +---------- day of month (1 - 31)
# |  |  |  +------- month (1 - 12)
# |  |  |  |  +---- day of week (0 - 7) (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *  command to be executed
#--------------------------------------------------------------------------

# Run my cron job every Monday to Friday hourly from 9:30am
30 9 * * 1,2,3,4,5 cron-data.js


问:
Capturing method in if statement in a list comprehension
I have a following use case:

```<code>[(x, f(x)) for x in list_x if f(x) == cond(x)]
</code>```

Above list comprehension, I think makes a f(x) call twice? How do I avoid that and capture value of f(x) so that f(x) is called only once.

I guess, easy fix is to convert above list comprehension into a for loop, but am curious if it can be done efficiently using a list comprehension.

答:
You can use a nested generator expression to call the function only once:

```<code>[(x, fx) for (x, fx) in ((x, f(x)) for x in list_x) if fx == cond(x)]
</code>```

The generator expression is iterated in lockstep to produce the (x, fx) tuples for the list comprehension.

If you find this easier on the reader, you can split out the generator expression into a separate name first:

```<code>mapped_x = ((x, f(x)) for x in list_x)
filtered_x = [(x, fx) for (x, fx) in mapped_x if fx == cond(x)]
</code>```

To re-iterate this point: the generator expression is executed lazily; the for loop in the expression is advanced step by step for each step in the for ... in mapped_x loop.

Demo:

```<code>>>> list_x = range(5)
>>> f = lambda x: print('f({!r})'.format(x)) or (x ** 2 - 1)
>>> cond = lambda x: print('cond({!r})'.format(x)) or x % 2 == 0
>>> mapped_x = ((x, f(x)) for x in list_x)
>>> [(x, fx) for (x, fx) in mapped_x if fx == cond(x)]
f(0)
cond(0)
f(1)
cond(1)
f(2)
cond(2)
f(3)
cond(3)
f(4)
cond(4)
[(1, 0)]
</code>```

Note how f(x) is called just once, and the condition is checked immediately.

How efficient this is depends on how costly the f(x) call is; a generator expression is executed as a separate function frame, and the interpreter will switch between the two frames (the loop for the list comprehension is also a frame object).

If f(x) is a Python function, you'll already have won, as you now halved the number of function frame objects that are created (each f(x) call creates a frame object too, and creating these is relatively costly). For C functions, you should create some trial runs with the timeit module to see what is faster for your expected list size.

Body:
I have a following use case:

[(x, f(x)) for x in list_x if f(x) == cond(x)]

Above list comprehension, I think makes a f(x) call twice? How do I avoid that and capture value of f(x) so that f(x) is called only once.

I guess, easy fix is to convert above list comprehension into a for loop, but am curious if it can be done efficiently using a list comprehension.

Body:
You can use a nested generator expression to call the function only once:

[(x, fx) for (x, fx) in ((x, f(x)) for x in list_x) if fx == cond(x)]

The generator expression is iterated in lockstep to produce the (x, fx) tuples for the list comprehension.

If you find this easier on the reader, you can split out the generator expression into a separate name first:

mapped_x = ((x, f(x)) for x in list_x)
filtered_x = [(x, fx) for (x, fx) in mapped_x if fx == cond(x)]

To re-iterate this point: the generator expression is executed lazily; the for loop in the expression is advanced step by step for each step in the for ... in mapped_x loop.

Demo:

>>> list_x = range(5)
>>> f = lambda x: print('f({!r})'.format(x)) or (x ** 2 - 1)
>>> cond = lambda x: print('cond({!r})'.format(x)) or x % 2 == 0
>>> mapped_x = ((x, f(x)) for x in list_x)
>>> [(x, fx) for (x, fx) in mapped_x if fx == cond(x)]
f(0)
cond(0)
f(1)
cond(1)
f(2)
cond(2)
f(3)
cond(3)
f(4)
cond(4)
[(1, 0)]

Note how f(x) is called just once, and the condition is checked immediately.

How efficient this is depends on how costly the f(x) call is; a generator expression is executed as a separate function frame, and the interpreter will switch between the two frames (the loop for the list comprehension is also a frame object).

If f(x) is a Python function, you'll already have won, as you now halved the number of function frame objects that are created (each f(x) call creates a frame object too, and creating these is relatively costly). For C functions, you should create some trial runs with the timeit module to see what is faster for your expected list size.