问:
How to change place of elements from same line
I have a block from 3 elements - minimum value, stock of a product, maximum value.

All i need to do is to find a way to align the stock of the product in the middle between both values.

My guess is that the problem should be somewhere on these lines:

```<code><style>
    .inline-parent{text-align:center;}
    .inline-block{display:inline-block;margin-right:10px;}
</style>
<div class="max inline-parent">
    <div class="inline-block"><?php echo $tickets_sold;?></div>
    <div class="inline-block"><?php echo $max_tickets;?></div>
</div>
</code>```

My browser renders the file like this:(screenshot)

Inspect of the element shows this: (screenshot)

Using Flex wrong
even worst

CSS -

```<code>.wcl-progress-meter meter::-webkit-meter-suboptimum-value {
  box-shadow: 0 5px 5px -5px #999 inset;
  background: #cb132b;
  display:inline-block;

}

.wcl-progress-meter .zero {
  display: inline-block;
  position: absolute;
  top: -100%;
}

.wcl-progress-meter .min {
  display: inline-block;
  position: absolute;
  top: -100%;
}

.wcl-progress-meter .max {
  display: inline-block;
  position: absolute;
  top: -100%;
  right: 0;

}
</code>```

PHP- file where i tried to edit the code

```<code>$max_tickets                = $product->get_max_tickets();
$tickets_sold    = wc_get_stock_html( $product );

<div class="wcl-progress-meter <?php if($product->is_max_tickets_met()) echo 'full' ?>">
               <progress  max="<?php echo $max_tickets ?>" value="<?php echo $lottery_participants_count ?>"  low="<?php echo $min_tickets ?>"></progress></br>
                <span class="zero">0</span>
<style>
    .inline-parent{text-align:center;}
    .inline-block{display:inline-block;margin-right:10px;}
</style>
<div class="max inline-parent">
    <div class="inline-block"><?php echo $tickets_sold;?></div>
    <div class="inline-block"><?php echo $max_tickets;?></div>
</div>
</code>```

答:
CSS flexbox will help you achieve this easily.

Check this fiddle

Read about CSS flex

```<code>.value-container{
  width: 600px;
  display: flex;
  justify-content: space-between;
}
</code>```

UPDATE:

Make sure you take out the span from wcl-progress-meter div and put it inside max div

You can also get rid  of inline-block class. Refer below Code.

```<code> <span class="zero">0</span>
</code>```

PHP:

```<code><div class="max">
    <span class="zero">0</span>
    <div><?php echo $tickets_sold;?></div>
    <div><?php echo $max_tickets;?></div>
</div>
</code>```

CSS:

```<code>.max{
  display: flex;
  justify-content: space-between;
}
</code>```

UPDATE : 2 (Below CSS should work if you remove the absolute position)

```<code>.wcl-progress-meter meter::-webkit-meter-suboptimum-value {
   box-shadow: 0 5px 5px -5px #999 inset;
   background: #cb132b;
   display:inline-block;
 }

.wcl-progress-meter .zero {
 /* try removing the CSS */
}

.wcl-progress-meter .min {
/* try removing the CSS */
}

.wcl-progress-meter .max {
   display: flex;
   justify-content: space-between;
}
</code>```

Body:
I have a block from 3 elements - minimum value, stock of a product, maximum value.

All i need to do is to find a way to align the stock of the product in the middle between both values.

My guess is that the problem should be somewhere on these lines:

<?php echo $tickets_sold;?>

<?php echo $max_tickets;?>

My browser renders the file like this:(screenshot)

Inspect of the element shows this: (screenshot)

Using Flex wrong
even worst

CSS -

.wcl-progress-meter meter::-webkit-meter-suboptimum-value {
  box-shadow: 0 5px 5px -5px #999 inset;
  background: #cb132b;
  display:inline-block;

}

.wcl-progress-meter .zero {
  display: inline-block;
  position: absolute;
  top: -100%;
}

.wcl-progress-meter .min {
  display: inline-block;
  position: absolute;
  top: -100%;
}

.wcl-progress-meter .max {
  display: inline-block;
  position: absolute;
  top: -100%;
  right: 0;

}

PHP- file where i tried to edit the code

$max_tickets                = $product->get_max_tickets();
$tickets_sold    = wc_get_stock_html( $product );

<div class="wcl-progress-meter <?php if($product->is_max_tickets_met()) echo 'full' ?>">
               <progress  max="<?php echo $max_tickets ?>" value="<?php echo $lottery_participants_count ?>"  low="<?php echo $min_tickets ?>"></progress>

                0

<?php echo $tickets_sold;?>

<?php echo $max_tickets;?>

Body:
CSS flexbox will help you achieve this easily.

Check this fiddle

Read about CSS flex

.value-container{
  width: 600px;
  display: flex;
  justify-content: space-between;
}

UPDATE:

Make sure you take out the span from wcl-progress-meter div and put it inside max div

You can also get rid  of inline-block class. Refer below Code.

 <span class="zero">0</span>

PHP:

<div class="max">
    <span class="zero">0</span>
    <div><?php echo $tickets_sold;?></div>
    <div><?php echo $max_tickets;?></div>
</div>

CSS:

.max{
  display: flex;
  justify-content: space-between;
}

UPDATE : 2 (Below CSS should work if you remove the absolute position)

.wcl-progress-meter meter::-webkit-meter-suboptimum-value {
   box-shadow: 0 5px 5px -5px #999 inset;
   background: #cb132b;
   display:inline-block;
 }

.wcl-progress-meter .zero {
 /* try removing the CSS */
}

.wcl-progress-meter .min {
/* try removing the CSS */
}

.wcl-progress-meter .max {
   display: flex;
   justify-content: space-between;
}


来源: stackexchange

问:
jQuery - prevent option deselect in select multiple
Is it possible to prevent an option from being deselected in a select multiple control? Also it must not deselect any other selected options. I have tried:

```<code>$('#selections option').click(function(){
    $(this).prop('selected', true);
});
</code>```

Doesn't seem to work. Anyone know how I can achieve this?

答:
Try this:</p>

```<code>$("#selections").click(function () {
    $("#option_always_selected").prop('selected', true);
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to prevent an option from being deselected in a select multiple control? Also it must not deselect any other selected options. I have tried:

$('#selections option').click(function(){
    $(this).prop('selected', true);
});

Doesn't seem to work. Anyone know how I can achieve this?

Body:
Try this:

$("#selections").click(function () {
    $("#option_always_selected").prop('selected', true);
});

ContentLicense: CC BY-SA 4.0


问:
Can I have a horizontal multiple colour gradient on text using CSS3 / HTML 5?
I'm trying to replace a sIFR based flash effect currently used on a website with CSS 3 styling. I have the text gradient effect working well using CSS 3 but the original sIFR implementation had multiple colours rather than just a simple gradient of one colour to the next.

Can someone provide me an example of styling a text element such as an H2 using multiple colours along the horizontal axis?

Thanks,
Brian.

答:
As far as I know this is only possible in webkit

```<code>h1 {
  font-size: 72px;
  background-image: -webkit-gradient(
    linear,
    left top,
    right top,
    color-stop(0.03, rgb(250,3,3)),
    color-stop(0.52, rgb(240,255,127)),
    color-stop(0.76, rgb(42,24,173)));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
</code>```

http://jsfiddle.net/gEGHq/1

Body:
As far as I know this is only possible in webkit

h1 {
  font-size: 72px;
  background-image: -webkit-gradient(
    linear,
    left top,
    right top,
    color-stop(0.03, rgb(250,3,3)),
    color-stop(0.52, rgb(240,255,127)),
    color-stop(0.76, rgb(42,24,173)));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

http://jsfiddle.net/gEGHq/1


问:
How to change the value of a service variable from the component?
In my code, the user input should get passed to the deviceName string in my component (which it does), which in turn should get passed to the deviceIP string in my service.

I'm guessing the order in which I used the get / set methods is incorrect. Can anyone help me figure out what I've done wrong?

Here's my component:

```<code>@Component({
selector: 'app-section-computer-management',
templateUrl: './section-computer-management.component.html',
styleUrls: ['./section-computer-management.component.css'],
})

export class SectionComputerManagementComponent implements OnInit {
ping: number = 0;
public deviceName = 'cstorch-3420';

constructor(private _pingService: PingService) {
this._pingService.pingStream.subscribe(ping => {
  this.ping = ping; });
}

changeDIP(val){
  this._pingService.setDIP(this.deviceName);
}

showDIV() {
  alert(`GV ${this._pingService.getDIP}`);
}

ngOnInit() {}
}
</code>```

Here's my service:

```<code>@Injectable()
export class PingService {
pingStream: Subject<number> = new Subject<number>();
ping: number = 0;

deviceIp = "";
url = `http://${this.deviceIp}`;

setDIP(val: string) {
this.deviceIp = val;
}
getDIP(val: string) {
return this.deviceIp;
}

constructor(private _http: Http) {
interval(1000)
  .subscribe((data) => {
    let timeStart: number = performance.now();

    this._http.get(this.url)
      .subscribe((data) => {
        let timeEnd: number = performance.now();

        let ping: number = timeEnd - timeStart;
        this.ping = ping;
        this.pingStream.next(ping);
      });
  });
}
}
</code>```

Here's the template I'm using

```<code> <div class="section-container">
    <div class="cards">
        <div class="card-deck">
            <div class="card text mb-3 shadow card-theme">
                <div class="card-header card-header-theme text-center">
                    <h5>Please Enter A Device Name or IP Address</h5>
                </div>
                <div class="card-body">
                    <div ng-app="">
                        <p align="center"><input class ='form-control input-lg'
    style= "width:300px" [(ngModel)]="deviceName" type="text"> {{deviceName}}
    </p>

                    </div>
                </div>
            </div>
            <div class="card text-center mb-3 shadow card-theme">
                <div class="card-header card-header-theme">
                    <h5>Machine Ping</h5>
                </div>
                <div class="card-body">
                        {{ping | number:'1.0-0'}}ms
                </div>
            </div>
        </div>
            <div class="row-fluid cards">
                <div class="card shadow card-theme">
                    <div class="card-body">

                    </div>
                    <div class="col-sm-2">
                            <div class="card shadow card-theme">
                              <div class="card-body">
                                <h5 class="card-title">Special title treatment</h5>
                                <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
                                <a href="#" class="btn btn-primary">Go
somewhere</a>
                              </div>
                </div>
            </div>
        </div>
    </div>
</code>```

and finally the module.ts file

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { SidebarComponent } from './sidebar/sidebar.component';
import { SectionDashboardComponent } from './Sections/section-dashboard/section-dashboard.component';
import { SectionComputerManagementComponent } from './Sections/section-computer-management/section-computer-management.component';
import { SectionHelpdeskLinksComponent } from './Sections/section-helpdesk-links/section-helpdesk-links.component';
import { BarChartComponent } from './charts/bar-chart/bar-chart.component';
import { LineChartComponent } from './charts/line-chart/line-chart.component';
import { PieChartComponent } from './charts/pie-chart/pie-chart.component';
import { ChartsModule } from 'ng2-charts';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { freshServiceService } from './Services/freshservice.service';
import { PingService } from './Services/pingservice.service';
import { HttpModule } from '@angular/http';
import {FormsModule} from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    SidebarComponent,
    SectionDashboardComponent,
    SectionComputerManagementComponent,
    SectionHelpdeskLinksComponent,
    BarChartComponent,
    LineChartComponent,
    PieChartComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ChartsModule,
    HttpClientModule,
    HttpModule,
    FormsModule,

  ],
  providers: [freshServiceService, PingService, HttpClient],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答:
The setDIP method is defined in your component but it is never called. You are not calling this method when you write something into input field. You need to catch a change event on input field and execute the setDIP method.

Change your code like this:

```<code><p align="center"><input class ='form-control input-lg'
    style= "width:300px" [(ngModel)]="deviceName" (change)="setDIP($event.target.value)" type="text"> {{deviceName}}
</p>
</code>```

Body:
In my code, the user input should get passed to the deviceName string in my component (which it does), which in turn should get passed to the deviceIP string in my service.

I'm guessing the order in which I used the get / set methods is incorrect. Can anyone help me figure out what I've done wrong?

Here's my component:

@Component({
selector: 'app-section-computer-management',
templateUrl: './section-computer-management.component.html',
styleUrls: ['./section-computer-management.component.css'],
})

export class SectionComputerManagementComponent implements OnInit {
ping: number = 0;
public deviceName = 'cstorch-3420';

constructor(private _pingService: PingService) {
this._pingService.pingStream.subscribe(ping => {
  this.ping = ping; });
}

changeDIP(val){
  this._pingService.setDIP(this.deviceName);
}

showDIV() {
  alert(`GV ${this._pingService.getDIP}`);
}

ngOnInit() {}
}

Here's my service:

@Injectable()
export class PingService {
pingStream: Subject<number> = new Subject<number>();
ping: number = 0;

deviceIp = "";
url = `http://${this.deviceIp}`;

setDIP(val: string) {
this.deviceIp = val;
}
getDIP(val: string) {
return this.deviceIp;
}

constructor(private _http: Http) {
interval(1000)
  .subscribe((data) => {
    let timeStart: number = performance.now();

    this._http.get(this.url)
      .subscribe((data) => {
        let timeEnd: number = performance.now();

        let ping: number = timeEnd - timeStart;
        this.ping = ping;
        this.pingStream.next(ping);
      });
  });
}
}

Here's the template I'm using

Please Enter A Device Name or IP Address

<input class ='form-control input-lg'
    style= "width:300px" [(ngModel)]="deviceName" type="text"> {{deviceName}}

Machine Ping

                        {{ping | number:'1.0-0'}}ms

Special title treatment

With supporting text below as a natural lead-in to additional content.

                                Go
somewhere

and finally the module.ts file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { SidebarComponent } from './sidebar/sidebar.component';
import { SectionDashboardComponent } from './Sections/section-dashboard/section-dashboard.component';
import { SectionComputerManagementComponent } from './Sections/section-computer-management/section-computer-management.component';
import { SectionHelpdeskLinksComponent } from './Sections/section-helpdesk-links/section-helpdesk-links.component';
import { BarChartComponent } from './charts/bar-chart/bar-chart.component';
import { LineChartComponent } from './charts/line-chart/line-chart.component';
import { PieChartComponent } from './charts/pie-chart/pie-chart.component';
import { ChartsModule } from 'ng2-charts';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { freshServiceService } from './Services/freshservice.service';
import { PingService } from './Services/pingservice.service';
import { HttpModule } from '@angular/http';
import {FormsModule} from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    SidebarComponent,
    SectionDashboardComponent,
    SectionComputerManagementComponent,
    SectionHelpdeskLinksComponent,
    BarChartComponent,
    LineChartComponent,
    PieChartComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ChartsModule,
    HttpClientModule,
    HttpModule,
    FormsModule,

  ],
  providers: [freshServiceService, PingService, HttpClient],
  bootstrap: [AppComponent]
})
export class AppModule { }

Body:
The setDIP method is defined in your component but it is never called. You are not calling this method when you write something into input field. You need to catch a change event on input field and execute the setDIP method.

Change your code like this:

<p align="center"><input class ='form-control input-lg'
    style= "width:300px" [(ngModel)]="deviceName" (change)="setDIP($event.target.value)" type="text"> {{deviceName}}
</p>


问:
Why is it sometimes valid to write an include statement in a codeblock?
I amcoming from a python background, where the following is valid:

```<code>def f():
    import someLibrary
    someLibrary.libraryFunction()
</code>```

So when I needed to debug C code, I wrote, in the middle of my function:

```<code>void f(int param)
{
     int status;
     /* other code */
     #include <stdio.h>
     printf("status: %d", status);
     /* more code */
}
</code>```

And it compiled and worked as I expected. Later it was pointed out to me that this shouldn't compile, since the C pre-processor literally replaces the #include~ statement with the contents ofstdio.h`.
So why was this valid code?

答:
Yeah, C and Python are pretty different in this respect.

It is correct that the preprocessor replaces the #include directive with the contents of the included file prior to compilation.

Whether it leads to a compilation error or not depends entirely on the contents of the included file.  Standard headers like stdio.h don't contain any executable statements - they only contain things like typdefs, function declarations, other macros, etc.  They also usually have some kind of #include guards in place that prevent them from being loaded more than once per translation unit (that is, if you #include a file that includes stdio.h, and then #include <stdio.h> directly in the same source file, the contents of stdio.h will only be loaded once).

Theoretically, there's no problem with including stdio.h at random points in the code, but it can lead to problems.  In this case all of stdio.h's contents will only be visible to the body of f - not a problem if only f needs to use anything in stdio.h, but otherwise it will lead to headaches.

Standard headers are best included at the beginning of the source file.

Body:
I amcoming from a python background, where the following is valid:

def f():
    import someLibrary
    someLibrary.libraryFunction()

So when I needed to debug C code, I wrote, in the middle of my function:

void f(int param)
{
     int status;
     /* other code */
     #include <stdio.h>
     printf("status: %d", status);
     /* more code */
}

And it compiled and worked as I expected. Later it was pointed out to me that this shouldn't compile, since the C pre-processor literally replaces the #include~ statement with the contents ofstdio.h`.
So why was this valid code?


问:
How to fetch data after n interval of time
I have data stored of every 1 seconds in sql server, i need to fetch data of every 1 or 2 minute interval not of seconds,how can I get data every 2 minutes based using SQL?

答:
I would approach this as:

```<code>select t.*
from (select t.*,
             row_number() over (partition convert(date, datecol), datepart(hour, datecol), datepart(minute, datecol) / 2
                                order by datecol
                               ) as seqnum
      from t
     ) t
where seqnum = 1;
</code>```

The partition by is breaking the data into groups of two-minutes each (the / 2 does that).  The logic then returns the first record in each group.

Body:
I would approach this as:

select t.*
from (select t.*,
             row_number() over (partition convert(date, datecol), datepart(hour, datecol), datepart(minute, datecol) / 2
                                order by datecol
                               ) as seqnum
      from t
     ) t
where seqnum = 1;

The partition by is breaking the data into groups of two-minutes each (the / 2 does that).  The logic then returns the first record in each group.


问:
Azure Notification Hub + FCM Ionic 3
I'm trying to get the push notifications working.
Starting with the client app I added the FCM plugin to the ionic project, imported in app.module.ts and listed it in providers.

Then in app.component.ts

```<code>import { FCM } from '@ionic-native/fcm';
constructor(..., public fcm: FCM) {

platform.ready().then(() => {
  ...
  this.fcm.getToken().then(token=>{
    console.log(token);
  });
  this.fcm.onNotification().subscribe(data => {
    if(data.wasTapped){
      console.log("Received in background");
    } else {
      console.log("Received in foreground");
    };
  });
  this.fcm.onTokenRefresh().subscribe(token => {
    //backend.registerToken(token);
    console.log('token changed ', token);
  });
  this.fcm.subscribeToTopic('general');
});
}
</code>```

And I wanted to test how does it work from the FCM website. It works when I send it directly to device through its token. It works also when I send it to devices subsribing the topic 'general'. But it doesn't work when I send it just to the users of the app even though it shows me that there are 2 users right now.
example here

Then I also added the FCM server key to Azure Notification Hub and wanted to send a test message from Azure portal, but it wasn't delivered.

If I don't subscribe to any topic in the app.component.ts it also doesn't receive any notification designated to all users of the app.

答:
Apologies for the delayed response here. Just following-up on this from Ajinka's response above.
@Szymon, You have stated in your original post "But it doesn't work when I send it just to the users of the app even though it shows me that there are 2 users right now", since it does not work directly with FCM, so typically it’s not going to work with Azure Notification Hubs since Azure Notification Hubs is just sending it through FCM. So, you must identify and isolate the issue with FCM fist.</p>

Title: Azure Notification Hub + FCM Ionic 3

Body:
I'm trying to get the push notifications working.
Starting with the client app I added the FCM plugin to the ionic project, imported in app.module.ts and listed it in providers.

Then in app.component.ts

import { FCM } from '@ionic-native/fcm';
constructor(..., public fcm: FCM) {

platform.ready().then(() => {
  ...
  this.fcm.getToken().then(token=>{
    console.log(token);
  });
  this.fcm.onNotification().subscribe(data => {
    if(data.wasTapped){
      console.log("Received in background");
    } else {
      console.log("Received in foreground");
    };
  });
  this.fcm.onTokenRefresh().subscribe(token => {
    //backend.registerToken(token);
    console.log('token changed ', token);
  });
  this.fcm.subscribeToTopic('general');
});
}

And I wanted to test how does it work from the FCM website. It works when I send it directly to device through its token. It works also when I send it to devices subsribing the topic 'general'. But it doesn't work when I send it just to the users of the app even though it shows me that there are 2 users right now.
example here

Then I also added the FCM server key to Azure Notification Hub and wanted to send a test message from Azure portal, but it wasn't delivered.

If I don't subscribe to any topic in the app.component.ts it also doesn't receive any notification designated to all users of the app.


问:
Laravel unit tests not running on windows
I was trying to do unit testing with laravel framework.

I followed all the steps described in laravel documentation but it doesn't work when I do "phpunit" command.

Tried the same command on a linux machine, it ran perfectly....

```<code>Desktop\space-bubble\phpunit.xml

Time: 0 seconds, Memory: 6.00Mb
</code>```

No tests executed!

答:
Use the phpunit provided in the project's vendor folder.

Using an unix shell

~/Desktop/space-bubble
$ ./vendor/bin/phpunit
```

<p>Using windows cmd</p>

<pre class="lang-sh prettyprint-override"><code>C:\Users\[your-username]> cd Desktop\space-bubble

C:\Users\[your-username]\Desktop\space-bubble> vendor\bin\phpunit
</code>```

Body:
I was trying to do unit testing with laravel framework.

I followed all the steps described in laravel documentation but it doesn't work when I do "phpunit" command.

Tried the same command on a linux machine, it ran perfectly....

Desktop\space-bubble\phpunit.xml

Time: 0 seconds, Memory: 6.00Mb

No tests executed!

Body:
Use the phpunit provided in the project's vendor folder.

Using an unix shell

~/Desktop/space-bubble
$ ./vendor/bin/phpunit

Using windows cmd

C:\Users\[your-username]> cd Desktop\space-bubble

C:\Users\[your-username]\Desktop\space-bubble> vendor\bin\phpunit


问:
How to make array of textboxes accept only specific alphabets?
i am using visual studio c#.net winform and i have 2d array of 81 textboxes. . . i can't figured out how it is possible to make these textboxes accept only specific alphabet. . . can any one please show me the code. . .
THanx in advance</p>

答:
```<code>private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
    List<char> chrs = new List<char>{'1', '2', '3'};
    if (!chrs.Contains(e.KeyChar))
    {
        e.Handled = true;
    }
}
</code>```


问:
How to fix this code? Passing String from method to MainActivity
I can't pass the jsonParse method variables. I tried to save them in the "ArrayList " but the Array remains empty. With another method, ex. "test", it works.
Why?

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

    gridView = findViewById(R.id.griglia);
    mQueue = Volley.newRequestQueue(this);
    txt = findViewById(R.id.titolo);
    movieList= new ArrayList<Movie>();
</code>```

//
I call the metod jsonParse for to fill my ArrayList

```<code>    jsonParse();
    if(movieList.isEmpty()){
        txt.setText("vuoto");
    }
    else{
        txt.setText("pieno");
    }

}
</code>```

// I have a problem with this code. He works, but don't fill the ArrayList

```<code>public void jsonParse(){
    String url ="https://api.myjson.com/bins/tn67c";
    JsonObjectRequest request= new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        JSONArray jsonArray= response.getJSONArray("movie");

                        for(int i=0; i<jsonArray.length(); i++){
                            JSONObject emplyee = jsonArray.getJSONObject(i);

                            String titolo = emplyee.getString("titolo");
                            String url = emplyee.getString("url");
                            String icona= emplyee.getString("icona");

                            Movie movie= new Movie();
                            movie.setTitolo(titolo);
                            movie.setVideoFilePath(url);
                            movieList.add(i, movie);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    mQueue.add(request);

}
</code>```

//
I trust with a example method "prova" and now work it. Why?

```<code>public void prova(){
    int i=0;

    for(i=0; i<2; i++){
        String test= "ciao " + i;
        Movie movie= new Movie();
        movie.setTitolo(test);
        movieList.add(movie);
    }

}
</code>```

答:
It seems that your jsonParse uses callback onResponse(JSONObject response), so it is executed on background thread.

Try to debug it, set breakpoint in your onResponse method and there you set your list to TextView.

I think it will stop firstly there you set text to TextView and then in onResponse method

Body:
I can't pass the jsonParse method variables. I tried to save them in the "ArrayList " but the Array remains empty. With another method, ex. "test", it works.
Why?

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

    gridView = findViewById(R.id.griglia);
    mQueue = Volley.newRequestQueue(this);
    txt = findViewById(R.id.titolo);
    movieList= new ArrayList<Movie>();

//
I call the metod jsonParse for to fill my ArrayList

    jsonParse();
    if(movieList.isEmpty()){
        txt.setText("vuoto");
    }
    else{
        txt.setText("pieno");
    }

}

// I have a problem with this code. He works, but don't fill the ArrayList

public void jsonParse(){
    String url ="https://api.myjson.com/bins/tn67c";
    JsonObjectRequest request= new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        JSONArray jsonArray= response.getJSONArray("movie");

                        for(int i=0; i<jsonArray.length(); i++){
                            JSONObject emplyee = jsonArray.getJSONObject(i);

                            String titolo = emplyee.getString("titolo");
                            String url = emplyee.getString("url");
                            String icona= emplyee.getString("icona");

                            Movie movie= new Movie();
                            movie.setTitolo(titolo);
                            movie.setVideoFilePath(url);
                            movieList.add(i, movie);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    mQueue.add(request);

}

//
I trust with a example method "prova" and now work it. Why?

public void prova(){
    int i=0;

    for(i=0; i<2; i++){
        String test= "ciao " + i;
        Movie movie= new Movie();
        movie.setTitolo(test);
        movieList.add(movie);
    }

}


问:
How to assign multiple variables depending on a condition
I want to assign multiple variables depending on a condition, but it keeps getting the error 'SyntaxError: Identifier 'end' has already been declared'

Both functions returns a timestamp.

My previous code was just:

```<code>let [start, end] = getPeriod(period)
</code>```

But now I need to assign depending on a condition

```<code>let [start, end] = [null,null];

  if(period != 'custom') {
    [start, end] = getPeriod(period)
  } else {
    [start, end] = getCustomPeriod(startDate, endDate);
  }
</code>```

But it doesn't work. Any suggests?

答:
The error means the variable end is already declared elsewhere in your code, search for it or rename the variable in your new piece of code.

Also, you could use a ternary to make this a one-liner:

```<code>const [ start, end ] = (period !== 'custom') ? getPeriod(period) : getCustomPeriod(startDate, endDate);
</code>```

Body:
I want to assign multiple variables depending on a condition, but it keeps getting the error 'SyntaxError: Identifier 'end' has already been declared'

Both functions returns a timestamp.

My previous code was just:

let [start, end] = getPeriod(period)

But now I need to assign depending on a condition

let [start, end] = [null,null];

  if(period != 'custom') {
    [start, end] = getPeriod(period)
  } else {
    [start, end] = getCustomPeriod(startDate, endDate);
  }

But it doesn't work. Any suggests?

Body:
The error means the variable end is already declared elsewhere in your code, search for it or rename the variable in your new piece of code.

Also, you could use a ternary to make this a one-liner:

const [ start, end ] = (period !== 'custom') ? getPeriod(period) : getCustomPeriod(startDate, endDate);


Title: Spark Dataframe - How to manipulate rows with nested structure on them?

Body:
I have a spark DataFrame like this:

+---------+---------+---------------------------------------------------+
|which_one|  matchID|                                        information|
+---------+---------+---------------------------------------------------+
|    First|      123|[[1.2, 4.5, 837], [1.4, 4.8, 123], [4.1, 4.7, 143]]|
|    First|      234|[[4.8, 8.9, 234], [1.1, 4.2, 321], [3.9, 5.7, 521]]|
|   Second|      345|[[7.7, 8.1, 457], [4.5, 4.9, 345], [1.9, 2.8, 776]]|
+---------+---------+---------------------------------------------------+

for each matchID, I need to find the corresponding list of information. Then, use "which_one" to extract the info I need.

For example, for matchID = 123, it corresponds to [1.4, 4.8, 123]. Then, which_one = "First" means I need the first val 1.4.

for matchID = 234, it corresponds to [4.8, 8.9, 234]. Then, which_one = "First" means I need the first val 4.8.

for matchID = 345, it corresponds to [4.5, 4.9, 345]. Then, which_one = "Second" means I need the second val 4.9.

The result table I want is to add a new column to the end:

+---------+---------+---------------------------------------------------+---+
|which_one|  matchID|                                        information|res|
+---------+---------+---------------------------------------------------+---+
|    First|      123|[[1.2, 4.5, 837], [1.4, 4.8, 123], [4.1, 4.7, 143]]|1.4|
|    First|      234|[[4.8, 8.9, 234], [1.1, 4.2, 321], [3.9, 5.7, 521]]|4.8|
|   Second|      345|[[7.7, 8.1, 457], [4.5, 4.9, 345], [1.9, 2.8, 776]]|4.9|
+---------+---------+---------------------------------------------------+---+

I tried to use foreach and rdd to loop through each row. However, it seems helpless because I cannot find a way to search for the matchID in information column. I searched online for hours without finding useful recourse yet. Any suggestions or hints are appreciated.

Body:
Function "explode" can be used for transform  column "information" to array type, and then filter new column by "matchID":

val df = Seq(
  ("First", 123, Array(Array(1.2, 4.5, 837), Array(1.4, 4.8, 123), Array(4.1, 4.7, 143))),
  ("First", 234, Array(Array(4.8, 8.9, 234), Array(1.1, 4.2, 321), Array(3.9, 5.7, 521))),
  ("Second", 345, Array(Array(7.7, 8.1, 457), Array(4.5, 4.9, 345), Array(1.9, 2.8, 776))))
  .toDF("which_one", "matchID", "information")

val indexColumn = when($"which_one" === "First", 1).otherwise(
  when($"which_one" === "Second", 2).otherwise(3))

val exploded = df
  .withColumn("exploded", explode($"information"))
  .withColumn("indexColumn", indexColumn)

exploded.show(false)

exploded
  .where(expr("array_contains(exploded, matchID )"))
  .withColumn("res", expr("element_at(exploded,indexColumn)"))
  .drop("exploded", "indexColumn")

Output:

+---------+-------+---------------------------------------------------------+-----------------+-----------+
|which_one|matchID|information                                              |exploded         |indexColumn|
+---------+-------+---------------------------------------------------------+-----------------+-----------+
|First    |123    |[[1.2, 4.5, 837.0], [1.4, 4.8, 123.0], [4.1, 4.7, 143.0]]|[1.2, 4.5, 837.0]|1          |
|First    |123    |[[1.2, 4.5, 837.0], [1.4, 4.8, 123.0], [4.1, 4.7, 143.0]]|[1.4, 4.8, 123.0]|1          |
|First    |123    |[[1.2, 4.5, 837.0], [1.4, 4.8, 123.0], [4.1, 4.7, 143.0]]|[4.1, 4.7, 143.0]|1          |
|First    |234    |[[4.8, 8.9, 234.0], [1.1, 4.2, 321.0], [3.9, 5.7, 521.0]]|[4.8, 8.9, 234.0]|1          |
|First    |234    |[[4.8, 8.9, 234.0], [1.1, 4.2, 321.0], [3.9, 5.7, 521.0]]|[1.1, 4.2, 321.0]|1          |
|First    |234    |[[4.8, 8.9, 234.0], [1.1, 4.2, 321.0], [3.9, 5.7, 521.0]]|[3.9, 5.7, 521.0]|1          |
|Second   |345    |[[7.7, 8.1, 457.0], [4.5, 4.9, 345.0], [1.9, 2.8, 776.0]]|[7.7, 8.1, 457.0]|2          |
|Second   |345    |[[7.7, 8.1, 457.0], [4.5, 4.9, 345.0], [1.9, 2.8, 776.0]]|[4.5, 4.9, 345.0]|2          |
|Second   |345    |[[7.7, 8.1, 457.0], [4.5, 4.9, 345.0], [1.9, 2.8, 776.0]]|[1.9, 2.8, 776.0]|2          |
+---------+-------+---------------------------------------------------------+-----------------+-----------+

+---------+-------+---------------------------------------------------------+---+
|which_one|matchID|information                                              |res|
+---------+-------+---------------------------------------------------------+---+
|First    |123    |[[1.2, 4.5, 837.0], [1.4, 4.8, 123.0], [4.1, 4.7, 143.0]]|1.4|
|First    |234    |[[4.8, 8.9, 234.0], [1.1, 4.2, 321.0], [3.9, 5.7, 521.0]]|4.8|
|Second   |345    |[[7.7, 8.1, 457.0], [4.5, 4.9, 345.0], [1.9, 2.8, 776.0]]|4.9|
+---------+-------+---------------------------------------------------------+---+


问:
Duplicate entry being creating in array of objects when pushing the same data in two different arrays
I am having a weird problem all because of  allIpRecords: any; in which I want to maintain a copy of the ipRecords: any; because in the original code the ipRecords may change and I want to retain the previous copy in allIpRecords
The problem is whenever the insert function runs and if I have this.allIpRecords = res.data; inside the insert function then in both the arrays ipRecords and this.allIpRecords duplicate entries of the inserted row gets created and in the table the same row is shown two times. If I remove the this.allIpRecords then nothing of this sort happens only single entry of the inserted items is there in the array.
Even though in the database it is only inserted once but in the local array its shown two times.

```<code>   <td>
              <span></span>
          </td>
          <td>
              <input type="text" [(ngModel)]="newData.ip" />
          </td>
          <td>
              <input type="text"  [(ngModel)]="newData.forDomain" />
          </td>
          <td>
              <input type="text" [(ngModel)]="newData.status" />
          </td>
          <td>
              <input type="text" [(ngModel)]="newData.senderEmail" />
          </td>
          <td>
              <button class="common-btn" type="button" (click)="insert()">Insert</button>
          </td>

           </tr>
      <tr *ngFor="let record of ipRecords" class="colour02">
      <td>{{record.id}}</td>
      <td *ngIf="record.id === editRowId"><input type="text" [(ngModel)]="record.ip" ></td>
      <td *ngIf="record.id !== editRowId">{{record.ip}}</td>
      <td *ngIf="record.id === editRowId"><input type="text" [(ngModel)]="record.forDomain" ></td>
      <td *ngIf="record.id !== editRowId">{{record.forDomain}}</td>
      <td *ngIf="record.id === editRowId"><input type="text" [(ngModel)]="record.status" ></td>
      <td *ngIf="record.id !== editRowId">{{record.status}}</td>
      <td *ngIf="record.id === editRowId"><input type="text" [(ngModel)]="record.senderEmail" ></td>
      <td *ngIf="record.id !== editRowId">{{record.senderEmail}}</td>
      <td>
      <br>
</code>```

Ts

```<code>       private newData: any = {};
       ipRecords: any;
       allIpRecords: any;

        ngOnInit() {
        this.auth.getAllIpRecords().subscribe((res: any)=>{
       this.ipRecords = res.data;
       this.allIpRecords = res.data;
       }
        }

        insert() {
if(Object.keys(this.newData).length === 0) {
  this.toastr.error("Empty record");
  return;
}
this.auth.addIpRecord(this.newData).subscribe((res: any)=>{
  if(res.status === "Success") {
    this.newData = {};
    this.ipRecords.push(res.data);
    this.allIpRecords.push(res.data);
    }
  }
</code>```

答:
On both variables, you are passing the same object reference -

```<code>this.ipRecords = res.data;
this.allIpRecords = res.data;
</code>```

So, modification on any one variable will change all of them because they are the same reference.

To solve this, clone res.data and then assign it to the variables. There is an easy trick to do this by using JSON.stringify() and JSON.parse()

```<code>this.ipRecords = JSON.parse(JSON.stringify(res.data));
this.allIpRecords = JSON.parse(JSON.stringify(res.data));
</code>```

You can find more detailed information about object cloning HERE

Body:
I am having a weird problem all because of  allIpRecords: any; in which I want to maintain a copy of the ipRecords: any; because in the original code the ipRecords may change and I want to retain the previous copy in allIpRecords
The problem is whenever the insert function runs and if I have this.allIpRecords = res.data; inside the insert function then in both the arrays ipRecords and this.allIpRecords duplicate entries of the inserted row gets created and in the table the same row is shown two times. If I remove the this.allIpRecords then nothing of this sort happens only single entry of the inserted items is there in the array.
Even though in the database it is only inserted once but in the local array its shown two times.

              <input type="text" [(ngModel)]="newData.ip" />

              <input type="text"  [(ngModel)]="newData.forDomain" />

              <input type="text" [(ngModel)]="newData.status" />

              <input type="text" [(ngModel)]="newData.senderEmail" />

              <button class="common-btn" type="button" (click)="insert()">Insert</button>

      {{record.id}}
      <input type="text" [(ngModel)]="record.ip" >
      {{record.ip}}
      <input type="text" [(ngModel)]="record.forDomain" >
      {{record.forDomain}}
      <input type="text" [(ngModel)]="record.status" >
      {{record.status}}
      <input type="text" [(ngModel)]="record.senderEmail" >
      {{record.senderEmail}}

Ts

       private newData: any = {};
       ipRecords: any;
       allIpRecords: any;

        ngOnInit() {
        this.auth.getAllIpRecords().subscribe((res: any)=>{
       this.ipRecords = res.data;
       this.allIpRecords = res.data;
       }
        }

        insert() {
if(Object.keys(this.newData).length === 0) {
  this.toastr.error("Empty record");
  return;
}
this.auth.addIpRecord(this.newData).subscribe((res: any)=>{
  if(res.status === "Success") {
    this.newData = {};
    this.ipRecords.push(res.data);
    this.allIpRecords.push(res.data);
    }
  }

Body:
On both variables, you are passing the same object reference -

this.ipRecords = res.data;
this.allIpRecords = res.data;

So, modification on any one variable will change all of them because they are the same reference.

To solve this, clone res.data and then assign it to the variables. There is an easy trick to do this by using JSON.stringify() and JSON.parse()

this.ipRecords = JSON.parse(JSON.stringify(res.data));
this.allIpRecords = JSON.parse(JSON.stringify(res.data));

You can find more detailed information about object cloning HERE


问:
Javascript dot function with event handlers

Question

How do I create a custom javascript dot function that does the same thing as the following code in jQuery:

```<code>$(document).on("click touchstart", ".someClass", function() {
   // code goes here
});
</code>```

I'd like to declare it like this:

```<code>$(".someClass").onClick(function () {
   // code goes here
});
</code>```

It needs to:

work with dynamically created elements (hence jQuery .on() instead of .click())

work with computer clicks as well as touch taps

ideally, but not mandatorily, it would be written in pure javascript (no jQuery in the prototype itself, but can still be accessed through jQuery)

What I've Tried

```<code>Object.prototype.onClick = function() {
   $(document).on('click touchstart', this, arguments);
};
</code>```

But I receive the following error in chrome console:

Uncaught TypeError: ((n.event.special[g.origType] || {}).handle || g.handler).apply is not a function

I think I'm declaring it incorrectly, and perhaps that this is also not the correct way to access events in javascript.

答:
So you want a .onClick jQuery method

jQuery.fn.extend({
  onClick: function(sel, cb) {
    return this.on('touchstart click', sel, function(evt) {
      evt.preventDefault();
      if (cb && typeof cb === 'function') cb.apply(this, arguments);
    })
  }
});

$(document).onClick('.someClass', function(ev) {
  console.log(ev.type)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="someClass">CLICK ME</p></code>```

Or this simpler variant:

```<code>$.fn.onClick = function(sel, cb) {
  return this.on('touchstart click', sel, cb);
};

$(document).onClick('.someClass', function(ev) {
  ev.preventDefault();
  console.log(ev.type)
});
</code>```

Body:
Question

How do I create a custom javascript dot function that does the same thing as the following code in jQuery:

$(document).on("click touchstart", ".someClass", function() {
   // code goes here
});

I'd like to declare it like this:

$(".someClass").onClick(function () {
   // code goes here
});

It needs to:

work with dynamically created elements (hence jQuery .on() instead of .click())

work with computer clicks as well as touch taps

ideally, but not mandatorily, it would be written in pure javascript (no jQuery in the prototype itself, but can still be accessed through jQuery)

What I've Tried

Object.prototype.onClick = function() {
   $(document).on('click touchstart', this, arguments);
};

But I receive the following error in chrome console:

Uncaught TypeError: ((n.event.special[g.origType] || {}).handle || g.handler).apply is not a function

I think I'm declaring it incorrectly, and perhaps that this is also not the correct way to access events in javascript.

Body:
So you want a .onClick jQuery method

jQuery.fn.extend({
  onClick: function(sel, cb) {
    return this.on('touchstart click', sel, function(evt) {
      evt.preventDefault();
      if (cb && typeof cb === 'function') cb.apply(this, arguments);
    })
  }
});

$(document).onClick('.someClass', function(ev) {
  console.log(ev.type)
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="someClass">CLICK ME</p>

Or this simpler variant:

$.fn.onClick = function(sel, cb) {
  return this.on('touchstart click', sel, cb);
};

$(document).onClick('.someClass', function(ev) {
  ev.preventDefault();
  console.log(ev.type)
});


问:
Mercurial hg status displaying ignored files
Can anyone tell me why mercurial is displaying ignored files for the 'hg status' command?

Here's the confirmation that mercurial is indeed ignoring the files:

```<code>$ hg addremove
$ hg commit
nothing changed
</code>```

Now, have a look at the status output. I ran this immediately after the lines above. (Prinout is partial, with identifiable text removed)

```<code>$ hg status
? Core/target/Core-0.0.1-SNAPSHOT-tests.jar
? Core/target/Core-0.0.1-SNAPSHOT.jar
? Core/target/classes/META-INF/MANIFEST.MF
? Core/target/classes/xxx/yyy/zzz/X.class
? Core/target/classes/xxx/yyy/zzz/XBackup.class
? Core/target/classes/xxx/yyy/zzz/XBackupInput.class
? Core/target/classes/xxx/yyy/zzz/XBackupOutput.class
? Core/target/classes/xxx/yyy/zzz/XImpl$GetResultsAndStatistics.class
? Core/target/classes/xxx/yyy/zzz/XImpl$MonitoringMode.class
? Core/target/classes/xxx/yyy/zzz/XImpl$UpdateMode.class
? Core/target/classes/xxx/yyy/zzz/XImpl.class
? Core/target/classes/xxx/yyy/zzz/XIsFullException.class
? Core/target/classes/xxx/yyy/zzz/XSource.class
? Core/target/classes/xxx/yyy/zzz/XUsageException.class
? Core/target/classes/xxx/yyy/zzz/CheckResults.class
? Core/target/classes/xxx/yyy/zzz/Noise.class
? Core/target/classes/xxx/yyy/zzz/core/DateTimeGenerator$TemporalMeasure.class
? Core/target/classes/xxx/yyy/zzz/core/DateTimeGenerator.class
? Core/target/classes/xxx/yyy/zzz/core/LoggingConfigurator.class
? Core/target/classes/xxx/yyy/zzz/core/ManagedIterator.class
? Core/target/classes/xxx/yyy/zzz/core/NetworkUtils.class
? Core/target/classes/xxx/yyy/zzz/core/StackTraceUtils.class
? Core/target/classes/xxx/yyy/zzz/core/Summarisable.class
? Core/target/classes/xxx/yyy/zzz/core/TimingUtils.class
? Core/target/classes/xxx/yyy/zzz/core/XMLStaticStringUtils.class
? Core/target/classes/xxx/yyy/zzz/core/Zipper.class
...
</code>```

There's something like a thousand lines of these ignored files showing in the status printout; that's some serious guff.

How can I get rid of this?

Thanks

UPDATE:

Here's my .hgignore file.

```<code>syntax:glob
.metadata*

syntax:regexp
^target.*$
^[^/]*/target.*$
^[^/]*/[^/]*/target.*$
^bin.*$
^[^/]*/bin.*$
^[^/]*/[^/]*/bin.*$
</code>```

UPDATE:

Modified regexps a wee bit * -> .*

答:
Your .hgignore file says "^target" is ignored, but the files are in Core/target. So the ignore line should rather be "target" (without the ^) or "^Core/target".

Or am I missing sth here?

(Note: ^ implies that regex matching starts from the beginning of the path, i.e. only paths starting with target would be matched!)

ContentLicense: CC BY-SA 2.5

Body:
Can anyone tell me why mercurial is displaying ignored files for the 'hg status' command?

Here's the confirmation that mercurial is indeed ignoring the files:

$ hg addremove
$ hg commit
nothing changed

Now, have a look at the status output. I ran this immediately after the lines above. (Prinout is partial, with identifiable text removed)

$ hg status
? Core/target/Core-0.0.1-SNAPSHOT-tests.jar
? Core/target/Core-0.0.1-SNAPSHOT.jar
? Core/target/classes/META-INF/MANIFEST.MF
? Core/target/classes/xxx/yyy/zzz/X.class
? Core/target/classes/xxx/yyy/zzz/XBackup.class
? Core/target/classes/xxx/yyy/zzz/XBackupInput.class
? Core/target/classes/xxx/yyy/zzz/XBackupOutput.class
? Core/target/classes/xxx/yyy/zzz/XImpl$GetResultsAndStatistics.class
? Core/target/classes/xxx/yyy/zzz/XImpl$MonitoringMode.class
? Core/target/classes/xxx/yyy/zzz/XImpl$UpdateMode.class
? Core/target/classes/xxx/yyy/zzz/XImpl.class
? Core/target/classes/xxx/yyy/zzz/XIsFullException.class
? Core/target/classes/xxx/yyy/zzz/XSource.class
? Core/target/classes/xxx/yyy/zzz/XUsageException.class
? Core/target/classes/xxx/yyy/zzz/CheckResults.class
? Core/target/classes/xxx/yyy/zzz/Noise.class
? Core/target/classes/xxx/yyy/zzz/core/DateTimeGenerator$TemporalMeasure.class
? Core/target/classes/xxx/yyy/zzz/core/DateTimeGenerator.class
? Core/target/classes/xxx/yyy/zzz/core/LoggingConfigurator.class
? Core/target/classes/xxx/yyy/zzz/core/ManagedIterator.class
? Core/target/classes/xxx/yyy/zzz/core/NetworkUtils.class
? Core/target/classes/xxx/yyy/zzz/core/StackTraceUtils.class
? Core/target/classes/xxx/yyy/zzz/core/Summarisable.class
? Core/target/classes/xxx/yyy/zzz/core/TimingUtils.class
? Core/target/classes/xxx/yyy/zzz/core/XMLStaticStringUtils.class
? Core/target/classes/xxx/yyy/zzz/core/Zipper.class
...

There's something like a thousand lines of these ignored files showing in the status printout; that's some serious guff.

How can I get rid of this?

Thanks

UPDATE:

Here's my .hgignore file.

syntax:glob
.metadata*

syntax:regexp
^target.*$
^[^/]*/target.*$
^[^/]*/[^/]*/target.*$
^bin.*$
^[^/]*/bin.*$
^[^/]*/[^/]*/bin.*$

UPDATE:

Modified regexps a wee bit * -> .*


问:
How do I use a variable that is built from other variables?
I am trying to build a dynamic URL with some of the information stored in a list. I have loaded the list with some values and then iterate through the list concatenating the value from the list with a prefix. I then want to reference that concatenated value which matches a preloaded variable.

In the below code url_var just returns the name of the variable but not the value of the variable.

```<code>base_url_asia = "https://www.location1.com/"
base_url_americas = "https://www.location2.com/"

regions = [asia, americas]

for i in range(len(regions)):
    url_var = 'base_url_' + regions[i]
    print(url_var)
</code>```

I expect the output to be the full URL however all I get is base_url_asia or base_url_americas and not the actual url.

答:
You are defining variables that you are not using. 'base_url_' is a string and not a variable. If you want to store different locations using the same variable but with different names, you should use a dictionary.

base_url=dict()
base_url['asia'] = 'www.location1.com'
base_url['americas'] = 'www.location2.com'

continent = ['asia','americas']

for cont in continent:
    print(base_url[cont])
```

Note that cont is not an integer, but is the name of the continents.

I hope you find it useful. Good luck!

Body:
I am trying to build a dynamic URL with some of the information stored in a list. I have loaded the list with some values and then iterate through the list concatenating the value from the list with a prefix. I then want to reference that concatenated value which matches a preloaded variable.

In the below code url_var just returns the name of the variable but not the value of the variable.

base_url_asia = "https://www.location1.com/"
base_url_americas = "https://www.location2.com/"

regions = [asia, americas]

for i in range(len(regions)):
    url_var = 'base_url_' + regions[i]
    print(url_var)

I expect the output to be the full URL however all I get is base_url_asia or base_url_americas and not the actual url.

Body:
You are defining variables that you are not using. 'base_url_' is a string and not a variable. If you want to store different locations using the same variable but with different names, you should use a dictionary.

base_url=dict()
base_url['asia'] = 'www.location1.com'
base_url['americas'] = 'www.location2.com'

continent = ['asia','americas']

for cont in continent:
    print(base_url[cont])

Note that cont is not an integer, but is the name of the continents.

I hope you find it useful. Good luck!


问:
Generic extension method parameter restrictions
I am creating an extension method to IQueryable for automapper to pass in a standard parameter. Though this code below works, it seems a bit redundant to have to specify the TSource type when invoking this method (as in below invocation code)....i.e. having to specify <Item, in the method call when it already knows the type of entityQuery is Item.

I'm not an expert in generics, but wondering if there is a way to remove this redundancy during invocation but still qualify the TSource as needing to conform to interface IAuditStampsViewModel?

Invocation

```<code>public IQueryable<ItemViewModel> ConvertClassToViewModel(IQueryable<Item> entityQuery)
{
    return entityQuery.ProjectToPassUserTimeOffset<Item, ItemViewModel>();
}
</code>```

Extension Method definition

```<code>public static class AutoMapperExtensions
{
    public static IQueryable<TDestination> ProjectToPassUserTimeOffset<TSource, TDestination>(this IQueryable<TSource> entityQuery)
        where TSource : class, IAuditStampsViewModel, new()
    {
        return entityQuery.ProjectTo<TDestination>(
            new { intMinutesOffset = TimeUtilities.UserTimeZoneUTCOffsetMinutes() }
        );
    }
}
</code>```

答:
Can you just constrain on IAuditStampsViewModel? Then you could write:

```<code>public static class Extensions
{
    public static IQueryable<TDestination> ProjectToPassUserTimeOffset<TDestination>(this IQueryable<IAuditStampsViewModel> entityQuery)
    {
        return entityQuery.ProjectTo<TDestination>(new {intMinutesOffset=TimeUtilities.UserTimeZoneUTCOffsetMinutes()});
    }
}
</code>```

The caller would be:

```<code>public IQueryable<ItemViewModel> ConvertClassToViewModel(IQueryable<Item> entityQuery)
{
    return entityQuery.ProjectToPassUserTimeOffset<ItemViewModel>();
}
</code>```

Body:
I am creating an extension method to IQueryable for automapper to pass in a standard parameter. Though this code below works, it seems a bit redundant to have to specify the TSource type when invoking this method (as in below invocation code)....i.e. having to specify <Item, in the method call when it already knows the type of entityQuery is Item.

I'm not an expert in generics, but wondering if there is a way to remove this redundancy during invocation but still qualify the TSource as needing to conform to interface IAuditStampsViewModel?

Invocation

public IQueryable<ItemViewModel> ConvertClassToViewModel(IQueryable<Item> entityQuery)
{
    return entityQuery.ProjectToPassUserTimeOffset<Item, ItemViewModel>();
}

Extension Method definition

public static class AutoMapperExtensions
{
    public static IQueryable<TDestination> ProjectToPassUserTimeOffset<TSource, TDestination>(this IQueryable<TSource> entityQuery)
        where TSource : class, IAuditStampsViewModel, new()
    {
        return entityQuery.ProjectTo<TDestination>(
            new { intMinutesOffset = TimeUtilities.UserTimeZoneUTCOffsetMinutes() }
        );
    }
}

Body:
Can you just constrain on IAuditStampsViewModel? Then you could write:

public static class Extensions
{
    public static IQueryable<TDestination> ProjectToPassUserTimeOffset<TDestination>(this IQueryable<IAuditStampsViewModel> entityQuery)
    {
        return entityQuery.ProjectTo<TDestination>(new {intMinutesOffset=TimeUtilities.UserTimeZoneUTCOffsetMinutes()});
    }
}

The caller would be:

public IQueryable<ItemViewModel> ConvertClassToViewModel(IQueryable<Item> entityQuery)
{
    return entityQuery.ProjectToPassUserTimeOffset<ItemViewModel>();
}


问:
Spring - How to add a session attribute only once per session
In my Spring Boot application I add the user name as a custom session attribute. I did this so in the Tomcat manager I can see who is currently using the app:

I implemented javax.servlet.Filter to add the user name. But is this the recommended way to do that? After all, the attribute gets added on every single request. Does Spring provide a callback which is executed only once per session?

答:
Spring MVC has tools for dealing with sessions and the @SessionAttributes section of this tutorial actually discusses registering a bean with Session scope so that it is called for each new session.

more info here


问:
Why do I get a "Premature End of File" error when performing my XSLT transform?
Getting Line #-1; Column #-1; Premature end of file Error while xslt transform

XSL :

```<code><xsl:template match="/">
    <html>
        <head>
            <title>Real's HowTo</title>
        </head>
        <body>
            <table border="1">
                <tr>
                    <th>Titleamit</th>
                    <th>Link</th>
                </tr>
                <xsl:for-each select="mx:feed/mx:entry">
                    <tr>
                        <td>
                            <xsl:value-of select="mx:title" />
                        </td>
                        <td>
                            <xsl:value-of select="mx:published" />
                        </td>
                    </tr>
                </xsl:for-each>
            </table>
        </body>
    </html>
</xsl:template>
</code>```

XML:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:clearspace="http://www.jivesoftware.com/xmlns/clearspace/rss"
xmlns:dc="http://purl.org/dc/elements/1.1/">
    <title>
        Sprint Community: Space Polls - Android
    </title>
    <link rel="alternate" href="http://community.sprint.com/baw/poll.jspa?containerType=14&container=2130" />
    <subtitle>
        List of polls
    </subtitle>
    <id>
        http://community.sprint.com/baw/poll.jspa?containerType=14&container=2130
    </id>
    <generator uri="http://jivesoftware.com/products/clearspace/" version="4.5.4.1">
        Jive SBS
    </generator>
    <updated>
        2010-02-08T17:30:00Z
    </updated>
    <dc:date>
        2010-02-08T17:30:00Z
    </dc:date>
    <dc:language>
        en
    </dc:language>
    <entry>
        <title>
            What's Valuable
        </title>
        <link rel="alternate" href="http://community.sprint.com/baw/poll.jspa?poll=1062" />
        <author>
            <name>
                wengla02
            </name>
            <uri>
                /people/wengla02
            </uri>
            <email>
                noreply-buzz@sprint.com
            </email>
        </author>
        <updated>
            2010-02-08T17:30:00Z
        </updated>
        <published>
            2010-02-08T17:30:00Z
        </published>
        <summary type="html" />
        <dc:date>
            2010-02-08T17:30:00Z
        </dc:date>
        <clearspace:dateToText>
            1 year, 2 months ago
        </clearspace:dateToText>
        <clearspace:objectType>
            0
        </clearspace:objectType>
    </entry>
</feed>
</code>```

Java code:

```<code>// load xslt fromxsltFilePath
url = getClass().getClassLoader().getResource("com/sprint/mysprint/phoneMedia/myPhoneAndMedia/xsl/announcementFeed.xsl");

BufferedInputStream bis3= new BufferedInputStream(url.openStream());

if (isLoggingDebug()) {
    BufferedInputStream bis1= new BufferedInputStream(url.openStream());
    byte[] buffer1 = new byte[1024];
    int bytesRead1 = 0;

    while ((bytesRead1 = bis1.read(buffer1)) != -1) {
        String chunk1 = new String(buffer1, 0, bytesRead1);
        logDebug(" " + chunk1);
    }
}

TransformerFactory transformerFactory = TransformerFactory.newInstance();

// create xslt Template
Templates template = transformerFactory.newTemplates(
  new StreamSource(new DataInputStream(url.openStream())));

// Create Transformer
Transformer transformer = template.newTransformer();
transformer.transform(
  new StreamSource(bis), new StreamResult(xhtmlContent));
</code>```

答:
The & ampersand signs are not escaped in your xml. You should change them to & in order to be able to parse the xml data, otherwise it won't work.
After parsing and transforming, wrapping, whatever, you can update the results by changing these characters back.

Body:
Getting Line #-1; Column #-1; Premature end of file Error while xslt transform

XSL :

<xsl:template match="/">

            <title>Real's HowTo</title>

                    Titleamit
                    Link

                <xsl:for-each select="mx:feed/mx:entry">

                            <xsl:value-of select="mx:title" />

                            <xsl:value-of select="mx:published" />

                </xsl:for-each>

</xsl:template>

XML:

<?xml version="1.0" encoding="UTF-8" ?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:clearspace="http://www.jivesoftware.com/xmlns/clearspace/rss"
xmlns:dc="http://purl.org/dc/elements/1.1/">
    <title>
        Sprint Community: Space Polls - Android
    </title>
    <link rel="alternate" href="http://community.sprint.com/baw/poll.jspa?containerType=14&container=2130" />
    <subtitle>
        List of polls
    </subtitle>
    <id>
        http://community.sprint.com/baw/poll.jspa?containerType=14&container=2130
    </id>
    <generator uri="http://jivesoftware.com/products/clearspace/" version="4.5.4.1">
        Jive SBS
    </generator>
    <updated>
        2010-02-08T17:30:00Z
    </updated>
    <dc:date>
        2010-02-08T17:30:00Z
    </dc:date>
    <dc:language>
        en
    </dc:language>
    <entry>
        <title>
            What's Valuable
        </title>
        <link rel="alternate" href="http://community.sprint.com/baw/poll.jspa?poll=1062" />
        <author>
            <name>
                wengla02
            </name>
            <uri>
                /people/wengla02
            </uri>
            <email>
                noreply-buzz@sprint.com
            </email>
        </author>
        <updated>
            2010-02-08T17:30:00Z
        </updated>
        <published>
            2010-02-08T17:30:00Z
        </published>

        <dc:date>
            2010-02-08T17:30:00Z
        </dc:date>
        <clearspace:dateToText>
            1 year, 2 months ago
        </clearspace:dateToText>
        <clearspace:objectType>
            0
        </clearspace:objectType>
    </entry>
</feed>

Java code:

// load xslt fromxsltFilePath
url = getClass().getClassLoader().getResource("com/sprint/mysprint/phoneMedia/myPhoneAndMedia/xsl/announcementFeed.xsl");

BufferedInputStream bis3= new BufferedInputStream(url.openStream());

if (isLoggingDebug()) {
    BufferedInputStream bis1= new BufferedInputStream(url.openStream());
    byte[] buffer1 = new byte[1024];
    int bytesRead1 = 0;

    while ((bytesRead1 = bis1.read(buffer1)) != -1) {
        String chunk1 = new String(buffer1, 0, bytesRead1);
        logDebug(" " + chunk1);
    }
}

TransformerFactory transformerFactory = TransformerFactory.newInstance();

// create xslt Template
Templates template = transformerFactory.newTemplates(
  new StreamSource(new DataInputStream(url.openStream())));

// Create Transformer
Transformer transformer = template.newTransformer();
transformer.transform(
  new StreamSource(bis), new StreamResult(xhtmlContent));

Body:
The & ampersand signs are not escaped in your xml. You should change them to &amp; in order to be able to parse the xml data, otherwise it won't work.
After parsing and transforming, wrapping, whatever, you can update the results by changing these characters back.


问:
get real client ip address in dotnet core when using nginx
I'm using dotnet core. I'm grabbing the IP address using the line Request.HttpContext.Connection.RemoteIpAddress.ToString(). When I visit my site using my ip address I see the client ip address showing correctly. However I want to use https and I use nginx. So in my location I wrote

```<code>    proxy_set_header  X-Real-IP $remote_addr;
    proxy_set_header  X-Forwarded-Proto https;
    proxy_set_header  X-Forwarded-For $remote_addr;
    proxy_set_header  X-Forwarded-Host $remote_addr;
</code>```

When I visit my site through the domain my ipaddress shows as ::1 and 127.0.0.1 (they switch every time I refresh). My nginx config is below I'm not exactly sure how to tell .net core the real ip address

```<code>server {
    server_name         www.example.com;
    listen              443 ssl;
    ssl_certificate     /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
    root                /var/www/example.com/;
    add_header          Strict-Transport-Security "max-age=31536000";
    index index.html index.htm;
    log_not_found off;
    access_log off;
    #try_files $uri.html $uri $uri/ =404;
    expires max;
    default_type text/plain;
    include /etc/nginx/mime.types;

    index off;
    location ~/other/ {
        index off;
        autoindex on;
    }

    location /abc {
        proxy_pass http://localhost:5050;
        proxy_http_version 1.1;
        proxy_set_header  X-Real-IP $remote_addr;
        proxy_set_header  X-Forwarded-Proto https;
        proxy_set_header  X-Forwarded-For $remote_addr;
        proxy_set_header  X-Forwarded-Host $remote_addr;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}
</code>```

答:
I am using .Net Core 2.2, and found the following to work.  It's slightly different than the other answer (which I couldn't get to work).

Add Microsoft.AspNetCore.HttpOverrides as dependency

Add the following to the ConfigureServices method:

```<code>services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders =
        ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
</code>```

Add the following to the Configure method:

```<code>app.UseForwardedHeaders();
</code>```

Source: Configure ASP.NET Core to work with proxy servers and load balancers

Body:
I'm using dotnet core. I'm grabbing the IP address using the line Request.HttpContext.Connection.RemoteIpAddress.ToString(). When I visit my site using my ip address I see the client ip address showing correctly. However I want to use https and I use nginx. So in my location I wrote

    proxy_set_header  X-Real-IP $remote_addr;
    proxy_set_header  X-Forwarded-Proto https;
    proxy_set_header  X-Forwarded-For $remote_addr;
    proxy_set_header  X-Forwarded-Host $remote_addr;

When I visit my site through the domain my ipaddress shows as ::1 and 127.0.0.1 (they switch every time I refresh). My nginx config is below I'm not exactly sure how to tell .net core the real ip address

server {
    server_name         www.example.com;
    listen              443 ssl;
    ssl_certificate     /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
    root                /var/www/example.com/;
    add_header          Strict-Transport-Security "max-age=31536000";
    index index.html index.htm;
    log_not_found off;
    access_log off;
    #try_files $uri.html $uri $uri/ =404;
    expires max;
    default_type text/plain;
    include /etc/nginx/mime.types;

    index off;
    location ~/other/ {
        index off;
        autoindex on;
    }

    location /abc {
        proxy_pass http://localhost:5050;
        proxy_http_version 1.1;
        proxy_set_header  X-Real-IP $remote_addr;
        proxy_set_header  X-Forwarded-Proto https;
        proxy_set_header  X-Forwarded-For $remote_addr;
        proxy_set_header  X-Forwarded-Host $remote_addr;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Body:
I am using .Net Core 2.2, and found the following to work.  It's slightly different than the other answer (which I couldn't get to work).

Add Microsoft.AspNetCore.HttpOverrides as dependency

Add the following to the ConfigureServices method:

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders =
        ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});

Add the following to the Configure method:

app.UseForwardedHeaders();

Source: Configure ASP.NET Core to work with proxy servers and load balancers


问:
How to pass ReactJS props properly?
I am trying to pass some values using props in ReactJS but, values are not passing not showing.

This is my html for the project:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React JS</title>
</head>
<body>
    <div id="app"></div>
    <script src="main.jsx"></script>
</body>
</html>
</code>```

and this is my main.jsx which renders a class named AppContainer component

```<code>'use strict';
import React from 'react';
import {render} from 'react-dom';
import AppContainer from './AppContainer';

render(<AppContainer />, document.getElementById('app'));
</code>```

This is my AppContainer.jsx which renders Users.jsx component

```<code>'use strict';
import React, {Component} from 'react';
import Users from './Users';

export default class AppContainer extends Component{
    constructor(props){
        super(props);
        this.state = {
            users: [{id: Date.now(), name: 'John'}]
        }
    }

    render(){
        return <div>
            <h1>Hello World</h1>
            <Users users={this.state.users}/>
        </div>;
    }
}
</code>```

And this is my Users.jsx class which renders User.jsx component

```<code>'user strict';
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import User from './User';

export default class Users extends Component{
    static get propTypes(){
        return {
            //validate users must be an array
            users: PropTypes.array
        }
    }

    constructor(props){
        super(props);
        this.state ={
            man: this.props
        }
    }

    render(){
        //get users from props
        const {users} = this.state.man;

        return (
            <div>
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            users.map((user) => {
                                return <User key={user.id} user={user}  />
                            })
                        }
                    </tbody>
                </table>
            </div>
        );
    }
}
</code>```

And this is my User.jsx where I guess values are not passing properly to the props

```<code>'use strict';
import React, {Component} from 'react';

export default class User extends Component{
    constructor(props){
        super(props);
        this.state = {
            user: this.props
        }
    }

    render(){
        return(
                <tr>
                    <td>{this.state.user.id}</td>
                    <td>{this.state.user.name}</td>
                </tr>
        );
    }
}
</code>```

This is a screenshot of how my output looks like. (In outputs, the id and the name is not shown, only the  are shown as below:

Can anyone please tell me where I have done wrong? Thank you!

答:
I changed 2 things :</p>

```<code>'user strict';
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import User from './User';

export default class Users extends Component{
    static get propTypes(){
    return {
        //validate users must be an array
        users: PropTypes.array
    }
}

constructor(props){
    super(props);
//remove here
}

render(){
    //get users from props
//change here
    const {users} = this.props;

    return (
        <div>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                    </tr>
                </thead>
                <tbody>
                    {
                        users.map((user) => {
                            return <User key={user.id} user={user}  />
                        })
                    }
                </tbody>
            </table>
        </div>
    );
}
}
</code>```

Title: How to pass ReactJS props properly?

Body:
I am trying to pass some values using props in ReactJS but, values are not passing not showing.

This is my html for the project:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>React JS</title>

and this is my main.jsx which renders a class named AppContainer component

'use strict';
import React from 'react';
import {render} from 'react-dom';
import AppContainer from './AppContainer';

render(<AppContainer />, document.getElementById('app'));

This is my AppContainer.jsx which renders Users.jsx component

'use strict';
import React, {Component} from 'react';
import Users from './Users';

export default class AppContainer extends Component{
    constructor(props){
        super(props);
        this.state = {
            users: [{id: Date.now(), name: 'John'}]
        }
    }

    render(){
        return

Hello World

            <Users users={this.state.users}/>

;
    }
}

And this is my Users.jsx class which renders User.jsx component

'user strict';
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import User from './User';

export default class Users extends Component{
    static get propTypes(){
        return {
            //validate users must be an array
            users: PropTypes.array
        }
    }

    constructor(props){
        super(props);
        this.state ={
            man: this.props
        }
    }

    render(){
        //get users from props
        const {users} = this.state.man;

        return (

                            ID
                            Name

                        {
                            users.map((user) => {
                                return <User key={user.id} user={user}  />
                            })
                        }

        );
    }
}

And this is my User.jsx where I guess values are not passing properly to the props

'use strict';
import React, {Component} from 'react';

export default class User extends Component{
    constructor(props){
        super(props);
        this.state = {
            user: this.props
        }
    }

    render(){
        return(

                    {this.state.user.id}
                    {this.state.user.name}

        );
    }
}

This is a screenshot of how my output looks like. (In outputs, the id and the name is not shown, only the  are shown as below:

Can anyone please tell me where I have done wrong? Thank you!

Body:
I changed 2 things :

'user strict';
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import User from './User';

export default class Users extends Component{
    static get propTypes(){
    return {
        //validate users must be an array
        users: PropTypes.array
    }
}

constructor(props){
    super(props);
//remove here
}

render(){
    //get users from props
//change here
    const {users} = this.props;

    return (
        <div>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                    </tr>
                </thead>
                <tbody>
                    {
                        users.map((user) => {
                            return <User key={user.id} user={user}  />
                        })
                    }
                </tbody>
            </table>
        </div>
    );
}
}


问:
Getting elements in certain range of list
I have a Python list, for example list = [1,2,3,4,5,6,7,8,9]. In addition, I have another list list2 = ['a','b','c','d','e','f','g','h','j']. Now I would like to do the following:

```<code>idx = (list > 3) & (list < 7)
list2 = list2[idx]
</code>```

This should yield ['d','e','f']. Of course, this is not possible with lists. How can this be done with lists?

答:
Option with list comprehension accessing elements by index:

```<code>res = [ list2[idx] for idx, e in enumerate(list1) if 7 > e > 3 ]
print(res) #=> ['d', 'e', 'f']
</code>```

To get the elements from both the lists:

```<code>[ [list2[idx], e] for idx, e in enumerate(list1) if 7 > e > 3 ]
#=> [['d', 4], ['e', 5], ['f', 6]]
</code>```

Then transpose:

```<code>res1, res2 = [ list(i) for i in zip(*[ [list2[idx], e] for idx, e in enumerate(list1) if 7 > e > 3 ]) ]
print (res1, res2 ) #=> ['d', 'e', 'f'] [4, 5, 6]
</code>```

Body:
I have a Python list, for example list = [1,2,3,4,5,6,7,8,9]. In addition, I have another list list2 = ['a','b','c','d','e','f','g','h','j']. Now I would like to do the following:

idx = (list > 3) & (list < 7)
list2 = list2[idx]

This should yield ['d','e','f']. Of course, this is not possible with lists. How can this be done with lists?

Body:
Option with list comprehension accessing elements by index:

res = [ list2[idx] for idx, e in enumerate(list1) if 7 > e > 3 ]
print(res) #=> ['d', 'e', 'f']

To get the elements from both the lists:

[ [list2[idx], e] for idx, e in enumerate(list1) if 7 > e > 3 ]
#=> [['d', 4], ['e', 5], ['f', 6]]

Then transpose:

res1, res2 = [ list(i) for i in zip(*[ [list2[idx], e] for idx, e in enumerate(list1) if 7 > e > 3 ]) ]
print (res1, res2 ) #=> ['d', 'e', 'f'] [4, 5, 6]


问:
Adding a new field with default value in a collection in Spring Data MongoDB
I am adding a new boolean field in a collection by adding an attribute to a Java Class entity that is being used in the MongoRepository interface. However, the existing documents' new field is being initialised as null in the database. I want the new field's default value in existing documents to be set to false. How can this be done in Spring Data MongoDB?</p>

答:
Let say your version 1 Java entity was

```<code>@Document
Public Class Person {
@Id
Private String id;
private String firstName;
private String lastName;
.........
.........
</code>```

And later you have introduced

```<code>@Document
Public Class Person {
@Id
Private String id;
private String firstName;
private String lastName;
private Boolean isAlive; //New Boolean attribute
.........
.........
</code>```

In java the default value of an instance object is null and so a document in mongoDB with no value for isAlive will be defaulted to null. If you need the default value to be false you could do this

```<code>private Boolean isAlive = Boolean.FALSE;
</code>```

Body:
Let say your version 1 Java entity was

@Document
Public Class Person {
@Id
Private String id;
private String firstName;
private String lastName;
.........
.........

And later you have introduced

@Document
Public Class Person {
@Id
Private String id;
private String firstName;
private String lastName;
private Boolean isAlive; //New Boolean attribute
.........
.........

In java the default value of an instance object is null and so a document in mongoDB with no value for isAlive will be defaulted to null. If you need the default value to be false you could do this

private Boolean isAlive = Boolean.FALSE;


问:
re-using a linq variable
I am successfully using some linq to populate some variables but in order to make it more efficient I would like to avoid the current repetition when setting the variables nextMDTID, nextPatientID, nextCareID and nextMDTDate.
Can I create a variable to hold the data generated using the linq query and then re-use it to avoid the repetition?</p>

```<code>    Dim thisPTOrder = (From p In ThisMDTData Where p.MDTID = Request.QueryString("MDTID") Select p.PTOrder).FirstOrDefault
    Dim nextPTOrder = thisPTOrder + 1
    Dim d = ThisMDTData.Where(Function(p) p.PTOrder = nextPTOrder And p.PTOrder <= p.PTOrder)
    Dim nextMDTID = (From p In ThisMDTData Where p.PTOrder = nextPTOrder And p.PTOrder <= p.MaxPTOrder Select p.MDTID).FirstOrDefault
    Dim nextPatientID = (From p In ThisMDTData Where p.PTOrder = nextPTOrder And p.PTOrder <= p.MaxPTOrder Select p.PatientID).FirstOrDefault
    Dim nextCareID = (From p In ThisMDTData Where p.PTOrder = nextPTOrder And p.PTOrder <= p.MaxPTOrder Select p.CareID).FirstOrDefault
    Dim nextMDTDate = (From p In ThisMDTData Where p.PTOrder = nextPTOrder And p.PTOrder <= p.MaxPTOrder Select p.MDTDate).FirstOrDefault
</code>```

答:
Using a proper definition for d, you can simplify the results extraction:

```<code>Dim d = ThisMDTData.Where(Function(p) p.PTOrder = nextPTOrder And p.PTOrder <= p.MaxPTOrder).Select(Function(p) New With { p.MDTID, p.PatientID, p.CareID, p.MDTDate }).FirstOrDefault
Dim nextMDTID = d?.MDTID
Dim nextPatientID = d?.PatientID
Dim nextCareID = d?.CareID
Dim nextMDTDate = d?.MDTDate
</code>```

Putting the Select/FirstOrDefault on the definition of d ensures that any database is only queried once for the minimally needed data. You could leave the Select off if the row size is small, or the row only has those four properties. You can use the obvious fluent query translation for d if desired.

NOTE: If you don't want some of the variables to be Nullable, use If:

```<code>Dim nextPatientID = If(d?.PatientID, CType(Nothing, Integer))
</code>```

Title: re-using a linq variable

Body:
I am successfully using some linq to populate some variables but in order to make it more efficient I would like to avoid the current repetition when setting the variables nextMDTID, nextPatientID, nextCareID and nextMDTDate.
Can I create a variable to hold the data generated using the linq query and then re-use it to avoid the repetition?

    Dim thisPTOrder = (From p In ThisMDTData Where p.MDTID = Request.QueryString("MDTID") Select p.PTOrder).FirstOrDefault
    Dim nextPTOrder = thisPTOrder + 1
    Dim d = ThisMDTData.Where(Function(p) p.PTOrder = nextPTOrder And p.PTOrder <= p.PTOrder)
    Dim nextMDTID = (From p In ThisMDTData Where p.PTOrder = nextPTOrder And p.PTOrder <= p.MaxPTOrder Select p.MDTID).FirstOrDefault
    Dim nextPatientID = (From p In ThisMDTData Where p.PTOrder = nextPTOrder And p.PTOrder <= p.MaxPTOrder Select p.PatientID).FirstOrDefault
    Dim nextCareID = (From p In ThisMDTData Where p.PTOrder = nextPTOrder And p.PTOrder <= p.MaxPTOrder Select p.CareID).FirstOrDefault
    Dim nextMDTDate = (From p In ThisMDTData Where p.PTOrder = nextPTOrder And p.PTOrder <= p.MaxPTOrder Select p.MDTDate).FirstOrDefault

Body:
Using a proper definition for d, you can simplify the results extraction:

Dim d = ThisMDTData.Where(Function(p) p.PTOrder = nextPTOrder And p.PTOrder <= p.MaxPTOrder).Select(Function(p) New With { p.MDTID, p.PatientID, p.CareID, p.MDTDate }).FirstOrDefault
Dim nextMDTID = d?.MDTID
Dim nextPatientID = d?.PatientID
Dim nextCareID = d?.CareID
Dim nextMDTDate = d?.MDTDate

Putting the Select/FirstOrDefault on the definition of d ensures that any database is only queried once for the minimally needed data. You could leave the Select off if the row size is small, or the row only has those four properties. You can use the obvious fluent query translation for d if desired.

NOTE: If you don't want some of the variables to be Nullable, use If:

Dim nextPatientID = If(d?.PatientID, CType(Nothing, Integer))


问:
C++ Matrix Class - Suggestions
I am trying to build a templated Matrix class in C++. Below is its implementation.
I implemented two operators +,+= as of now just to give an idea on how it will look and I thought it would be best to ask for feedback before I proceed any further.

The whole implementation is public and also there are no explicit bound/error checks, this is because its not meant to be a full fledged matrix library and hence avoided unnecessary code.

It would be very helpful if someone could comment on it and may be suggest a few improvements or suggestions.

Thank you.

```<code>template<class T>
class Matrix
{
    public:
    int r,c;
    vector< vector< T > >mat;

    Matrix() {}

    // Constructor to set the size of the matrix
    Matrix(int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            mat[i].resize(c);
    }
    // Constructor to build a matrix from a C 2d array
    // Pointer to the first element is passed (&arr[0][0])
    Matrix(T *arr,int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i].push_back(arr[i*c+j]);
    }
    template<typename U>
    Matrix<T>& operator +=(const Matrix<U>&M)
    {
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i][j]+=static_cast<T>(M.mat[i][j]);
        return *this;
    }
    template<typename U>
    Matrix<T> operator +(const Matrix<U>&M)
    {
        Matrix<T>tmp=*this;
        return tmp+=M;
    }
};

template<typename T>
istream& operator >>(istream &in,Matrix<T>&M)
{
    in>>M.r>>M.c;
    Matrix<T>tmp(M.r,M.c);
    for(int i=0;i<M.r;i++)
        for(int j=0;j<M.c;j++)
            in>>tmp.mat[i][j];
    M=tmp;
    return in;
}
template<typename T>
ostream& operator <<(ostream &out,Matrix<T>M)
{
    for(int i=0;i<M.r;i++)
    {
        for(int j=0;j<M.c;j++)
            cout<<M.mat[i][j]<<" ";
        cout<<endl;
    }
    return out;
}
</code>```

EDIT:
Thank you all for the suggestions.

I just have one small question, say I do want to implement error checking (ex: checking for bounds,valid arguments etc..) however I do want the provide user with an option to disable error checking completely, is there any good way to implement this ?
What I need is something like example:`ios_base::sync_with_stdio(0);.
Thanks again.

答: You're wasting your time keeping _r and _c because the vectors keep their own sizes.

Title: C++ Matrix Class - Suggestions

Body:
I am trying to build a templated Matrix class in C++. Below is its implementation.
I implemented two operators +,+= as of now just to give an idea on how it will look and I thought it would be best to ask for feedback before I proceed any further.

The whole implementation is public and also there are no explicit bound/error checks, this is because its not meant to be a full fledged matrix library and hence avoided unnecessary code.

It would be very helpful if someone could comment on it and may be suggest a few improvements or suggestions.

Thank you.

template<class T>
class Matrix
{
    public:
    int r,c;
    vector< vector< T > >mat;

    Matrix() {}

    // Constructor to set the size of the matrix
    Matrix(int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            mat[i].resize(c);
    }
    // Constructor to build a matrix from a C 2d array
    // Pointer to the first element is passed (&arr[0][0])
    Matrix(T *arr,int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i].push_back(arr[i*c+j]);
    }
    template<typename U>
    Matrix<T>& operator +=(const Matrix&M)
    {
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i][j]+=static_cast<T>(M.mat[i][j]);
        return *this;
    }
    template<typename U>
    Matrix<T> operator +(const Matrix&M)
    {
        Matrix<T>tmp=*this;
        return tmp+=M;
    }
};

template<typename T>
istream& operator >>(istream &in,Matrix<T>&M)
{
    in>>M.r>>M.c;
    Matrix<T>tmp(M.r,M.c);
    for(int i=0;i<M.r;i++)
        for(int j=0;j<M.c;j++)
            in>>tmp.mat[i][j];
    M=tmp;
    return in;
}
template<typename T>
ostream& operator <<(ostream &out,Matrix<T>M)
{
    for(int i=0;i<M.r;i++)
    {
        for(int j=0;j<M.c;j++)
            cout<<M.mat[i][j]<<" ";
        cout<<endl;
    }
    return out;
}

EDIT:
Thank you all for the suggestions.

I just have one small question, say I do want to implement error checking (ex: checking for bounds,valid arguments etc..) however I do want the provide user with an option to disable error checking completely, is there any good way to implement this ?
What I need is something like example:`ios_base::sync_with_stdio(0);.
Thanks again.


问:
What is the space complexity of this code
What is the space complexity of the code:</p>

```<code>function double(n) {         //Here n is an array
   newArr = [];
   for (i = 0; i < n.length; i++) {
     newArr.push(2 * n[i]);
   }
  return newArr;
}
</code>```

答:
The space complexity is indeed O(N) because space depends not on how many variables your program has defined but rather on how runtime factors affect memory size.

An exploration of space

Think of the space complexity of an application as a factor of the eventual space requirements of the application.

This factor is determined by your application's memory requirements over various runs of the same application. If the amount of memory an application needs is independent of any variables within the application, then the factor is simply 1 i.e. space complexity of O(1). It is a constant because it does not change. This means that a program that allocates memory depending on user input (such as in your case) will have a seemingly higher space complexity (factor) than a program that only ever allocates 1GB of memory when it starts.

It may sound confusing because you might wonder why your simple program has space complexity of O(N), but a random C application which allocates 1GB of memory at the start is only O(1). Well it all boils down to the factor - if space requirements is dependent on a runtime variable within the program, then the space complexity is a factor of that variable otherwise space is constant.

Body:
What is the space complexity of the code:

function double(n) {         //Here n is an array
   newArr = [];
   for (i = 0; i < n.length; i++) {
     newArr.push(2 * n[i]);
   }
  return newArr;
}


问:
Pattern Matching In SQL where characters appears anywhere but in sequence
I'm attempting to write a query to fix invalid email formats. The invalid email format I am getting is of the form first@name_company@com.

The characters always appear as '@' '_' '@' in that sequence.

If this is the format then I am replacing @ with . and _ with @ to get a correct format as:

```<code>first.name@company.com
</code>```

I am considering a case condition like this:

```<code>When @email like '[a-z,0-9,_,-,@]_[a-z,0-9,_,-@]'  THEN replace(replace(replace(@email,'@','.'),'_','@'))
</code>```

This only seems to work if I put "_" as a wildcard like this '[a-z,0-9,_,-,@]%_%[a-z,0-9,_,-@]'

答:
I found two ways to do this using your specific example.</p>

```<code>create table #myTemp
(someText varchar(50))

insert into #myTemp
values
('first@name_company@com')

select
    -- check based on length after replacing the characters with nothing
    case when len(someText) - len(replace(replace(someText,'@',''),'_','')) = 3
    then replace(replace(someText,'@','.'),'_','@')
    end as LengthCheck,
    -- check the position of @ to the left and right of _
    case when charindex('@',(Right(someText, CHARINDEX('_', reverse(someText))-1))) > 0
        and charindex('@',(LEFT(someText, CHARINDEX('_', someText)))) > 0
    then replace(replace(someText,'@','.'),'_','@')
    end as CharCheck
from #myTemp
</code>```

Body:
I'm attempting to write a query to fix invalid email formats. The invalid email format I am getting is of the form first@name_company@com.

The characters always appear as '@' '_' '@' in that sequence.

If this is the format then I am replacing @ with . and _ with @ to get a correct format as:

first.name@company.com

I am considering a case condition like this:

When @email like '[a-z,0-9,_,-,@]_[a-z,0-9,_,-@]'  THEN replace(replace(replace(@email,'@','.'),'_','@'))

This only seems to work if I put "_" as a wildcard like this '[a-z,0-9,_,-,@]%_%[a-z,0-9,_,-@]'

Body:
I found two ways to do this using your specific example.

create table #myTemp
(someText varchar(50))

insert into #myTemp
values
('first@name_company@com')

select
    -- check based on length after replacing the characters with nothing
    case when len(someText) - len(replace(replace(someText,'@',''),'_','')) = 3
    then replace(replace(someText,'@','.'),'_','@')
    end as LengthCheck,
    -- check the position of @ to the left and right of _
    case when charindex('@',(Right(someText, CHARINDEX('_', reverse(someText))-1))) > 0
        and charindex('@',(LEFT(someText, CHARINDEX('_', someText)))) > 0
    then replace(replace(someText,'@','.'),'_','@')
    end as CharCheck
from #myTemp