问:
Customise FileOpenPicker in UWP
I have a sub folder in downloads folder named 'StudentDetails'. It contains subfolders with student names.And each student name contains images related to that student.
By default, I want to open that StudentDetails folder (OnSuggestedStartLocation not reach the goal). And it should list all student name on left side. When user clicks on each student name corresponding files should show on right side. Is it possible on uwp?</p>

```<code>        FileOpenPicker openPicker = new FileOpenPicker();
        openPicker.ViewMode = PickerViewMode.Thumbnail;
        openPicker.SuggestedStartLocation = PickerLocationId.Downloads;

        foreach (string extension in FileExtensions.Video)
        {
            openPicker.FileTypeFilter.Add(extension);
        }

        file = await openPicker.PickSingleFileAsync();
</code>```

答:
It's not possible as you know the Filepicker is a native windows component and the UWP utilizes it to fetch files as unlike wpf it doesn't have access to the local file system of windows. So in-case of a wpf I would have suggested you to simply create a control that does what the filepicker is doing but in UWP there is no way.

Please let me know if there is anything in the comments section

Title: Customise FileOpenPicker in UWP

Body:
I have a sub folder in downloads folder named 'StudentDetails'. It contains subfolders with student names.And each student name contains images related to that student.
By default, I want to open that StudentDetails folder (OnSuggestedStartLocation not reach the goal). And it should list all student name on left side. When user clicks on each student name corresponding files should show on right side. Is it possible on uwp?

        FileOpenPicker openPicker = new FileOpenPicker();
        openPicker.ViewMode = PickerViewMode.Thumbnail;
        openPicker.SuggestedStartLocation = PickerLocationId.Downloads;

        foreach (string extension in FileExtensions.Video)
        {
            openPicker.FileTypeFilter.Add(extension);
        }

        file = await openPicker.PickSingleFileAsync();


来源: stackexchange

问:
SQL sort by two columns - date and time zone
I'm trying to provide sorting functionality by two columns:

```<code>  START_DATE_TIME               TIMESTAMP(6)                NOT NULL,
  START_DATE_TIME_ZONE          VARCHAR2(255)               NULL,
</code>```

The regular data that I save in these columns looks like this:

```<code>START_DATE_TIME: 29.10.2017 01:00:00,000000000
START_DATE_TIME_ZONE: America/Los_Angeles
</code>```

I tried just the regular order by:

```<code>SELECT
    *
FROM
    event
ORDER BY
    start_date_time ASC,
    start_date_time_zone ASC
</code>```

But, as I was probably expected, it wasn't sorted correctly. Time zone is sorted as word, not as the offset. What I want to achieve here is to get the time zone applied to the time I have in UTC in order to get the exact point in time which I can use for my sorting. Is there a way to achive that using the structure that I have or I will have to merge my two columns and store time zones there? e.g.

```<code>  START_DATE_TIME            TIMESTAMP(6) WITH TIME ZONE NOT NULL
</code>```

Basically I'm using Spring Data + Oracle.

答:
I believe this will work:

```<code>select to_timestamp_tz(START_DATE_TIME || ' ' || START_DATE_TIME_ZONE)
from . . .
</code>```

As an example, you can run:

```<code>select to_timestamp_tz(timestamp '2017-10-29 01:00:00.000000000' || ' America/Los_Angeles')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to provide sorting functionality by two columns:

  START_DATE_TIME               TIMESTAMP(6)                NOT NULL,
  START_DATE_TIME_ZONE          VARCHAR2(255)               NULL,

The regular data that I save in these columns looks like this:

START_DATE_TIME: 29.10.2017 01:00:00,000000000
START_DATE_TIME_ZONE: America/Los_Angeles

I tried just the regular order by:

SELECT
    *
FROM
    event
ORDER BY
    start_date_time ASC,
    start_date_time_zone ASC

But, as I was probably expected, it wasn't sorted correctly. Time zone is sorted as word, not as the offset. What I want to achieve here is to get the time zone applied to the time I have in UTC in order to get the exact point in time which I can use for my sorting. Is there a way to achive that using the structure that I have or I will have to merge my two columns and store time zones there? e.g.

  START_DATE_TIME            TIMESTAMP(6) WITH TIME ZONE NOT NULL

Basically I'm using Spring Data + Oracle.

Body:
I believe this will work:

select to_timestamp_tz(START_DATE_TIME || ' ' || START_DATE_TIME_ZONE)
from . . .

As an example, you can run:

select to_timestamp_tz(timestamp '2017-10-29 01:00:00.000000000' || ' America/Los_Angeles')


问:
HashSet<Point>: How to sort all points according to x coordinates?
can you give me a hint how to sort the points according to x coordinates in  O(nLogn)?

```<code>    Set<Point> points = new HashSet<Point>();
    points.add(new Point(9, 0));
    points.add(new Point(1, 1));
    points.add(new Point(5, 6));
    points.add(new Point(3, 3));
    points.add(new Point(2, 7));
    points.add(new Point(1, 8));
    points.add(new Point(6, 1));
</code>```

I wish I could do something like Point[] points2 = points.toArray(); and afterwards sort it. But of course it isn´t working.

答:
```<code>Set<Point> sortedPoints = points
                        .stream()
                        .sorted(Comparator.comparing(Point::getX))
                        .collect(Collectors.toCollection(LinkedHashSet::new));
</code>```

I am sure this way is better of all because:
1) on the big amount of Points you can use

```<code>.paralellStream()
</code>```

to increase the performance.

and

2) the notation has declarative style and looks more clear.

Body:
can you give me a hint how to sort the points according to x coordinates in  O(nLogn)?

    Set<Point> points = new HashSet<Point>();
    points.add(new Point(9, 0));
    points.add(new Point(1, 1));
    points.add(new Point(5, 6));
    points.add(new Point(3, 3));
    points.add(new Point(2, 7));
    points.add(new Point(1, 8));
    points.add(new Point(6, 1));

I wish I could do something like Point[] points2 = points.toArray(); and afterwards sort it. But of course it isn´t working.

Body:
Set<Point> sortedPoints = points
                        .stream()
                        .sorted(Comparator.comparing(Point::getX))
                        .collect(Collectors.toCollection(LinkedHashSet::new));

I am sure this way is better of all because:
1) on the big amount of Points you can use

.paralellStream()

to increase the performance.

and

2) the notation has declarative style and looks more clear.


问:
Not sure how to resolve this particular undefined offset issue
Hello guys,

I am relatively new to Php, so go easy on me. Having said that, the output of the code is exactly what I am expecting ( a table of 6 columns and n rows ).My problem is that I have 5 notifications at the end of the table of undefined offset 1, 2 ,3 ,4 ,5 (indicating the lines  $result[1]...$result[5];

By printing the array I am also noticing at the end of it  Array ( [0] => [1] => [2] => [3] => [4] => [5] => ) maybe that is the problem, the index being set to nothing, but I hate 'maybe' so I am quite stuck at the moment.

Thanks in advance

```<code>$csvData = file_get_contents('excel_csv.csv');
$lines = explode(PHP_EOL, $csvData);

$array = array();
foreach ($lines as $line) {
    $array[] = str_getcsv($line);
}

echo "<table class='main-table'>";
    foreach($array as $result) {
           echo "<tr class='main-row'>
             <td class='main-column'><img src='poze/$result[0]'/></td>
             <td class='main-column'>$result[1]</td>
             <td class='main-column'>$result[2]</td>
             <td class='main-column'>$result[3]</td>
             <td class='main-column'>$result[4]</td>
             <td class='main-column'>$result[5]</td>
            </tr>";
    }
echo "</table>";
</code>```

答:
change 1st tow line

```<code>$csvData = file_get_contents('excel_csv.csv');
$lines = explode(PHP_EOL, $csvData);
</code>```

with

```<code>$lines = file('excel_csv.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
</code>```

to avoid empty lines

Body:
Hello guys,

I am relatively new to Php, so go easy on me. Having said that, the output of the code is exactly what I am expecting ( a table of 6 columns and n rows ).My problem is that I have 5 notifications at the end of the table of undefined offset 1, 2 ,3 ,4 ,5 (indicating the lines  $result[1]...$result[5];

By printing the array I am also noticing at the end of it  Array ( [0] => [1] => [2] => [3] => [4] => [5] => ) maybe that is the problem, the index being set to nothing, but I hate 'maybe' so I am quite stuck at the moment.

Thanks in advance

$csvData = file_get_contents('excel_csv.csv');
$lines = explode(PHP_EOL, $csvData);

$array = array();
foreach ($lines as $line) {
    $array[] = str_getcsv($line);
}

echo "
";
    foreach($array as $result) {
           echo "

             $result[1]
             $result[2]
             $result[3]
             $result[4]
             $result[5]

";
    }
echo "
";

Body:
change 1st tow line

$csvData = file_get_contents('excel_csv.csv');
$lines = explode(PHP_EOL, $csvData);

with

$lines = file('excel_csv.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

to avoid empty lines


问:
does angular have the "computed property" feature like in vue.js?
I learnt Vue.js first, and now have a project in Angular 4 so I just learnt Angular. I find everything is not that different from Vue except the "Computed Property". In Vue, I can create a computed property that listens to changes of other properties and run calculations automatically.

For example(in Vue 2):

```<code>computed: {
    name(){
        return this.firstname + ' ' + this.lastname;
    }
}
</code>```

The name property will only recalculate when one of firstname or lastname change. How to handle this in Angular 2 or 4 ?

答:
While this is already answered but I think this is not very good answer and users should not use getters as computed properties in angular. Why you may ask? getter is just sugar syntax for function and it will be compiled to plain function, this means that it will be executed on every change detection check. This is terrible for performance because property is recomputed hundred of times on any change.

Take a look at this example: https://plnkr.co/edit/TQMQFb?p=preview

```<code>@Component({
    selector: 'cities-page',
    template: `
        <label>Angular computed properties are bad</label>

        <ng-select [items]="cities"
                   bindLabel="name"
                   bindValue="id"
                   placeholder="Select city"
                   [(ngModel)]="selectedCityId">
        </ng-select>
        <p *ngIf="hasSelectedCity">
            Selected city ID: {{selectedCityId}}
        </p>
        <p><b>hasSelectedCity</b> is recomputed <b [ngStyle]="{'font-size': calls + 'px'}">{{calls}}</b> times</p>
    `
})
export class CitiesPageComponent {
    cities: NgOption[] = [
        {id: 1, name: 'Vilnius'},
        {id: 2, name: 'Kaunas'},
        {id: 3, name: 'Pabradė'}
    ];
    selectedCityId: any;

    calls = 0;

    get hasSelectedCity() {
      console.log('hasSelectedCity is called', this.calls);
      this.calls++;
      return !!this.selectedCityId;
    }
}
</code>```

If you really want to have computed properties you can use state container like mobx

```<code>class TodoList {
    @observable todos = [];
    @computed get unfinishedTodoCount() {
        return this.todos.filter(todo => !todo.finished).length;
    }
}
</code>```

mobx has @computed decorator so getter property will be cached and recalculated only when needed

Body:
I learnt Vue.js first, and now have a project in Angular 4 so I just learnt Angular. I find everything is not that different from Vue except the "Computed Property". In Vue, I can create a computed property that listens to changes of other properties and run calculations automatically.

For example(in Vue 2):

computed: {
    name(){
        return this.firstname + ' ' + this.lastname;
    }
}

The name property will only recalculate when one of firstname or lastname change. How to handle this in Angular 2 or 4 ?

Body:
While this is already answered but I think this is not very good answer and users should not use getters as computed properties in angular. Why you may ask? getter is just sugar syntax for function and it will be compiled to plain function, this means that it will be executed on every change detection check. This is terrible for performance because property is recomputed hundred of times on any change.

Take a look at this example: https://plnkr.co/edit/TQMQFb?p=preview

@Component({
    selector: 'cities-page',
    template: `
        <label>Angular computed properties are bad</label>

        <ng-select [items]="cities"
                   bindLabel="name"
                   bindValue="id"
                   placeholder="Select city"
                   [(ngModel)]="selectedCityId">
        </ng-select>
        <p *ngIf="hasSelectedCity">
            Selected city ID: {{selectedCityId}}
        </p>
        <p><b>hasSelectedCity</b> is recomputed <b [ngStyle]="{'font-size': calls + 'px'}">{{calls}}</b> times</p>
    `
})
export class CitiesPageComponent {
    cities: NgOption[] = [
        {id: 1, name: 'Vilnius'},
        {id: 2, name: 'Kaunas'},
        {id: 3, name: 'Pabradė'}
    ];
    selectedCityId: any;

    calls = 0;

    get hasSelectedCity() {
      console.log('hasSelectedCity is called', this.calls);
      this.calls++;
      return !!this.selectedCityId;
    }
}

If you really want to have computed properties you can use state container like mobx

class TodoList {
    @observable todos = [];
    @computed get unfinishedTodoCount() {
        return this.todos.filter(todo => !todo.finished).length;
    }
}

mobx has @computed decorator so getter property will be cached and recalculated only when needed


问:
Host ASP.NET core and ASP.NET (full) in same machine
I have 2 websites written in ASP.NET MVC (.NET Framework 4.5) in same machine using IIS binding port 80 with different host name.

Now I want to host ASP.NET Core into the same machine with another host name but still bind to port 80

Is that possible?

答: You can host it with a different host name the same way as your other MVC application. Make sure you make a new application pool with no managed code and install the .NET core software hosting bundle on the server.


问:
Function returning a lambda expression
I wonder if it's possible to write a function that returns a lambda function in C++11. Of course one problem is how to declare such function. Each lambda has a type, but that type is not expressible in C++. I don't think this would work:

```<code>auto retFun() -> decltype ([](int x) -> int)
{
    return [](int x) { return x; }
}
</code>```

Nor this:

```<code>int(int) retFun();
</code>```

I'm not aware of any automatic conversions from lambdas to, say, pointers to functions, or some such. Is the only solution handcrafting a function object and returning it?

答:
For this simple example, you don't need std::function.

From standard §5.1.2/6:

The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.

Because your function doesn't have a capture, it means that the lambda can be converted to a pointer to function of type int (*)(int):

```<code>typedef int (*identity_t)(int); // works with gcc
identity_t retFun() {
  return [](int x) { return x; };
}
</code>```

That's my understanding, correct me if I'm wrong.

Title: Function returning a lambda expression

Body:
I wonder if it's possible to write a function that returns a lambda function in C++11. Of course one problem is how to declare such function. Each lambda has a type, but that type is not expressible in C++. I don't think this would work:

auto retFun() -> decltype ([](int x) -> int)
{
    return [](int x) { return x; }
}

Nor this:

int(int) retFun();

I'm not aware of any automatic conversions from lambdas to, say, pointers to functions, or some such. Is the only solution handcrafting a function object and returning it?

Body:
For this simple example, you don't need std::function.

From standard §5.1.2/6:

The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.

Because your function doesn't have a capture, it means that the lambda can be converted to a pointer to function of type int (*)(int):

typedef int (*identity_t)(int); // works with gcc
identity_t retFun() {
  return [](int x) { return x; };
}

That's my understanding, correct me if I'm wrong.


问:
SSRS 2017: Want to set a parameter to a default of NULL in a shared dateaset

the problem

I have a problem with a SSRS 2017 shared dataset.

This dataset is calling a stored procedure. One of the SP's parameters is of type DateTime. Within the dataset's parameters dialog I've set the default to (Null). But this seems to be ignored...

With paginated reports everything works fine. The defined report parameters (or built-in parameters) can be used to pass valid values.

But when I try to use this dataset within a mobile report I get an error. I cannot even add the dataset! After quite some search I found, that the SP was called with a blank instead of NULL (Pofiler tells me: ,@ClientTime=N''), hence the type conversion to DateTime failed.

I do not want to change this parameter to a string type, because this report will run in various environments. The correct date getting into the stored proc if taken as string is really awful: Nov 14 2017  3:35PM (culture and language dependant!) I do not want to rely on any conversion from string!

the question

How can I force a SSRS shared dataset to use a real NULL for a parameter?

答:
Well, I found a solution... Not really a solution to the problem, but it seems to help me out:

```<code>DECLARE @blank VARCHAR(1)='';
SELECT CAST(@blank AS DATETIME) AS toDateTime
      ,CAST(@blank AS DATETIME2) AS toDateTime2
      ,CAST(@blank AS TIME) AS toTime
      ,CAST(@blank AS DATE) AS toDate
      ,CAST(@blank AS BIT) AS toBit
      ,CAST(@blank AS INT) AS toInt
      ,CAST(@blank AS FLOAT) AS toFloat
</code>```

the result

```<code>toDateTime          toDateTime2         toTime      toDate      toBit toInt toFloat
1900-01-01 00:00:00 1900-01-01 00:00:00 00:00:00    1900-01-01  0     0     0
</code>```

The reason for the error on adding the dataset to a mobile report did not come from the DATETIME-conversion of a blank string but from a deeper place within my T-SQL-code, where I caculated a time difference and did not expect a value of 1900-01-01. The error message is very large, half of the screen is covered with text, but there's no real hint about the reason...

But this throws an error, hence I'll avoid data types not converting from a blank natively:

```<code>SELECT CAST(@blank AS decimal(10,4)) AS toDecimal
</code>```

Msg 8114, Level 16, State 5, Line 10

Error converting data type varchar to numeric.

That means: I have to take the value 1900-01-01 as NULL. Still it is rather silly, that SSRS allows parameters with a default of NULL but to send a blank in the background.

If there are other solutions which lead to a real NULL I'd still be happy to read them!

UPDATE: Fun fact

The profiler tells me, that a paginated report passes a parameter set to (Null) as a blank (as shown in the question). But with a mobile Report the (Null) is passed over as ,@DateTimeFrom=N'Nothing'. The default value must be set to an empty value, which is taken as blank...

Body:
Well, I found a solution... Not really a solution to the problem, but it seems to help me out:

DECLARE @blank VARCHAR(1)='';
SELECT CAST(@blank AS DATETIME) AS toDateTime
      ,CAST(@blank AS DATETIME2) AS toDateTime2
      ,CAST(@blank AS TIME) AS toTime
      ,CAST(@blank AS DATE) AS toDate
      ,CAST(@blank AS BIT) AS toBit
      ,CAST(@blank AS INT) AS toInt
      ,CAST(@blank AS FLOAT) AS toFloat

the result

toDateTime          toDateTime2         toTime      toDate      toBit toInt toFloat
1900-01-01 00:00:00 1900-01-01 00:00:00 00:00:00    1900-01-01  0     0     0

The reason for the error on adding the dataset to a mobile report did not come from the DATETIME-conversion of a blank string but from a deeper place within my T-SQL-code, where I caculated a time difference and did not expect a value of 1900-01-01. The error message is very large, half of the screen is covered with text, but there's no real hint about the reason...

But this throws an error, hence I'll avoid data types not converting from a blank natively:

SELECT CAST(@blank AS decimal(10,4)) AS toDecimal

Msg 8114, Level 16, State 5, Line 10

Error converting data type varchar to numeric.

That means: I have to take the value 1900-01-01 as NULL. Still it is rather silly, that SSRS allows parameters with a default of NULL but to send a blank in the background.

If there are other solutions which lead to a real NULL I'd still be happy to read them!

UPDATE: Fun fact

The profiler tells me, that a paginated report passes a parameter set to (Null) as a blank (as shown in the question). But with a mobile Report the (Null) is passed over as ,@DateTimeFrom=N'Nothing'. The default value must be set to an empty value, which is taken as blank...


问:
What can be used instead of tooltip in iphone app?
What can be used instead of tooltip in iphone app?

Best alternative of tooltip in touch screen systems?

答:
You don't. Instead apply a stronger preference for text buttons over buttons with an icon. Sometimes a footer message describes the current status in more detail.

(this is just me, interpreting Apple app design as good practice)

ContentLicense: CC BY-SA 2.5


问:
Angular 4 RouterModule
I have some issue when i try to add RouterModule on my application.
After i added router system on my app.module.ts file. i got this error again and again:

compiler.es5.js:1689 Uncaught Error: RouterModule cannot be used as an entry component.

Also here is my app.module.ts code:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { FormsModule  }   from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { RouterModule, Routes} from '@angular/router';

import { AppComponent } from './app.component';
import { ContactComponent } from './components/contact.component';

const appRoutes : Routes = [
    { path: 'test1', component : ContactComponent}
]

@NgModule({
  declarations: [
    AppComponent,
    ContactComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule.forRoot(appRoutes)
  ],

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

答:
Its a blunder though, You need to use like this.

```<code>  bootstrap: [AppComponent] // <== Remove RouterModule from here
</code>```

You must not add any Modules, Services, Directives, Pipes in  bootstrap (The bootstrap array).

bootstrap — The root AppComponent that Angular creates and inserts into the index.html host web page.

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent // Components, Services, Pipes
  ],
  imports: [
    BrowserModule // Modules
  ],
  providers: [], // Services
  bootstrap: [AppComponent] // The root Component E.g. AppComponent
})
export class AppModule { }
</code>```

Title: Angular 4 RouterModule

Body:
I have some issue when i try to add RouterModule on my application.
After i added router system on my app.module.ts file. i got this error again and again:

compiler.es5.js:1689 Uncaught Error: RouterModule cannot be used as an entry component.

Also here is my app.module.ts code:

import { BrowserModule } from '@angular/platform-browser';
import { FormsModule  }   from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { RouterModule, Routes} from '@angular/router';

import { AppComponent } from './app.component';
import { ContactComponent } from './components/contact.component';

const appRoutes : Routes = [
    { path: 'test1', component : ContactComponent}
]

@NgModule({
  declarations: [
    AppComponent,
    ContactComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule.forRoot(appRoutes)
  ],

  providers: [],
  bootstrap: [AppComponent, RouterModule]
 })
export class AppModule { }

Body:
Its a blunder though, You need to use like this.

  bootstrap: [AppComponent] // <== Remove RouterModule from here

You must not add any Modules, Services, Directives, Pipes in  bootstrap (The bootstrap array).

bootstrap — The root AppComponent that Angular creates and inserts into the index.html host web page.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent // Components, Services, Pipes
  ],
  imports: [
    BrowserModule // Modules
  ],
  providers: [], // Services
  bootstrap: [AppComponent] // The root Component E.g. AppComponent
})
export class AppModule { }


问:
Xamarin MvvmCross Unhandled Exceptions
Does anyone know how to set a catch all for all exceptions raised from a Xamarin Android app which uses MvvmCross. I have tried the solution in this article but I am still getting the unhandled exception in Visual Studio and the exception handler code is never executed.

I am just using a demo app to explore the features of MvvmCross V5.4, so I don't want to hook into hockey or anything.

答: OK, So I was trying to add exception handling in my MainActivity. What I should have been doing was creating an Application class as per this example. </p>

Title: Xamarin MvvmCross Unhandled Exceptions


问:
Why does adding an array to number return a string?
```<code>var array = [1,2,4];

array+1  //gives '1,2,41'.
</code>```

<p>Can anyone explain this behaviour? </p>

答:
What did you expect? [2,3,5]?

You haven't wrote a mutator for array, you added 1 to array (which is an object). Why do you expect for object to be able to add 1 to it?

JS figured out you need a primitive from that object and listed that object into a string. Now it knows how to "add" 2 strings (precisely its concatenate) so it did.

If you expected an entire array to get +1 on all elements. You  want:

```<code>for (var i=array .length; i--;) {
    array [i]++;
}
</code>```

Or

```<code>array = array.map(function(e) {return '#' + e});
</code>```

Or in ES6 and beyond arrow function with map

```<code>array = array.map(i => i + 1);
</code>```

Body:
var array = [1,2,4];

array+1  //gives '1,2,41'.

Can anyone explain this behaviour?

Body:
What did you expect? [2,3,5]?

You haven't wrote a mutator for array, you added 1 to array (which is an object). Why do you expect for object to be able to add 1 to it?

JS figured out you need a primitive from that object and listed that object into a string. Now it knows how to "add" 2 strings (precisely its concatenate) so it did.

If you expected an entire array to get +1 on all elements. You  want:

for (var i=array .length; i--;) {
    array [i]++;
}

Or

array = array.map(function(e) {return '#' + e});

Or in ES6 and beyond arrow function with map

array = array.map(i => i + 1);


问:
Getting Git to work with a proxy server - fails with "Request timed out"
How do I get Git to use a proxy server?

I need to check out code from a Git server, but it shows "Request timed out" every time. How do I get around this?

Alternatively, how can I set a proxy server?

答:
In addition of these answers, I found helpful to consider these two points:

One may need to enforce an authentication scheme:

```<code>[http]
    # https://github.com/git/git/blob/master/Documentation/config.txt
    proxyAuthMethod = anyauth|basic|digest|negotiate|ntlm
</code>```

Also, typically with an NTLM authentication schema, one may need to provide the AD domain explicitly.

In Git Bash:

```<code>echo %userdomain%
</code>```

And update the http.proxy accordingly:

```<code>git config --global http.proxy http://DOMAIN\\proxyuser:proxypwd@proxy.server.com:8080
</code>```

Anyway, investigation may be helped by adding CURL logs:

```<code>export GIT_CURL_VERBOSE=1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In addition of these answers, I found helpful to consider these two points:

One may need to enforce an authentication scheme:

[http]
    # https://github.com/git/git/blob/master/Documentation/config.txt
    proxyAuthMethod = anyauth|basic|digest|negotiate|ntlm

Also, typically with an NTLM authentication schema, one may need to provide the AD domain explicitly.

In Git Bash:

echo %userdomain%

And update the http.proxy accordingly:

git config --global http.proxy http://DOMAIN\\proxyuser:proxypwd@proxy.server.com:8080

Anyway, investigation may be helped by adding CURL logs:

export GIT_CURL_VERBOSE=1


问:
Filter non-digits from string
Using only swift code I cant figure out how to take "(555) 555-5555" and return only the numeric values and get "5555555555".  I need to remove all the parentheses, white spaces, and the dash.  The only examples I can find are in objective-C and they seem to all use the .trim() method.  It appears as though swift doesn't have this method but it does have the .stringByTrimmingCharacters method, but that only seems to trim the white spaces before and after the data. </p>

答:
Here is @Tapani Swift 3.2 solution</p>

```<code>let phno = contact.phoneNumbers[0].phoneNumber
let strarr = phno.components(separatedBy: NSCharacterSet.decimalDigits.inverted)
let newString = NSArray(array: strarr).componentsJoined(by: "")
print(newString)
</code>```

Title: Filter non-digits from string

Body:
Here is @Tapani Swift 3.2 solution

let phno = contact.phoneNumbers[0].phoneNumber
let strarr = phno.components(separatedBy: NSCharacterSet.decimalDigits.inverted)
let newString = NSArray(array: strarr).componentsJoined(by: "")
print(newString)


问:
How to get the value of the href attribute?
With the help of XPath, how to get the value of the href attribute in the following case (only grabbing the url that is the right one)?:

```<code><a href="http://foo.com">a wrong one</a>
<a href="http://example.com">the right one</a>
<a href="http://boo.com">a wrong one</a>
</code>```

That is, to get the value of the href attribute if the link has a particular text.

Body:
With the help of XPath, how to get the value of the href attribute in the following case (only grabbing the url that is the right one)?:

a wrong one
the right one
a wrong one

That is, to get the value of the href attribute if the link has a particular text.


问:
Update a nested state array based on selected value
I am trying to update which menu item was clicked and therefore change the class accordingly. I have tried different way suggested to do it but couldn't make it work.

Heres my code:

```<code>constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
        this.state = {
            menuState: [
                {
                    menuName: 'homeMenuStatus',
                    homeMenuStatus: 'inactive',
                    ulSidenavClass: "nav child_menu no-display"
                },
                {
                    menuName: 'accountMenuStatus',
                    accountMenuStatus: 'active',
                    ulSidenavClass: "nav child_menu block-display"
                },
                {
                    menuName: 'contactMenuStatus',
                    peopleMenuStatus: 'inactive',
                    ulSidenavClass: "nav child_menu no-display"
                },

            ]
        }
    }

handleClick(menuClicked) {
        this.state.menuState.map((name, index) => {
            let thisMenu = name.menuName;

            if(name.menuName == menuClicked) {
                if(this.state.menuClicked === 'active') {
                    this.setState({
                        ...this.state,
                        menuClicked: 'inactive',
                        ulSidenavClass: 'block-display height-adjust'
                    });
                } else {
                    this.setState({
                        ...this.state,
                        menuClicked: 'active',
                        ulSidenavClass: 'block-display'
                    });
                }
            } else {
                this.setState({
                    ...this.state,
                    thisMenu: 'inactive',
                    ulSidenavClass: 'block-display height-adjust'
                });
            }
        });
    }
</code>```

HTML:

```<code>    <div>
        <ul>
            <li className={this.state.menuState[0].homeMenuStatus}>
                <a onClick={() => this.handleClick('homeMenuStatus')}>Home </a>
                <ul className={this.state.menuState[0].ulSidenavClass}>
                    <li>
                        <a href="#">Dashboard</a>
                    </li>
                    <li>
                        <a href="#">Activities</a>
                    </li>
                </ul>
            </li>
        </ul>
    </div>
</code>```

My state object is not getting changed. Must be doing something wrong in setState(). Can anyone please guide me.

答:
You are incorrectly updating the state, use prevState syntax and return the mapped updated values like</p>

```<code>handleClick(menuClicked) {
    this.setState((prevState) => ({menuState: prevState.menuState.map((name, index) => {
           if(name.menuName === menuClicked) {
              if(name.menuClicked === 'active') {
                  return {
                      ...name,
                      menuClicked: 'inactive,
                      ulSidenavClass: 'block-display height-adjust'
                  }
              } else {
                  return {
                      ...name,
                      menuClicked: 'active,
                      ulSidenavClass: 'block-display'
                  }
              }

           } else {
                 return {
                      ...name,
                      menuClicked: 'inactive,
                      ulSidenavClass: 'block-display height-adjust'
                  }
            }
    })}))

}
</code>```

Body:
I am trying to update which menu item was clicked and therefore change the class accordingly. I have tried different way suggested to do it but couldn't make it work.

Heres my code:

constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
        this.state = {
            menuState: [
                {
                    menuName: 'homeMenuStatus',
                    homeMenuStatus: 'inactive',
                    ulSidenavClass: "nav child_menu no-display"
                },
                {
                    menuName: 'accountMenuStatus',
                    accountMenuStatus: 'active',
                    ulSidenavClass: "nav child_menu block-display"
                },
                {
                    menuName: 'contactMenuStatus',
                    peopleMenuStatus: 'inactive',
                    ulSidenavClass: "nav child_menu no-display"
                },

            ]
        }
    }

handleClick(menuClicked) {
        this.state.menuState.map((name, index) => {
            let thisMenu = name.menuName;

            if(name.menuName == menuClicked) {
                if(this.state.menuClicked === 'active') {
                    this.setState({
                        ...this.state,
                        menuClicked: 'inactive',
                        ulSidenavClass: 'block-display height-adjust'
                    });
                } else {
                    this.setState({
                        ...this.state,
                        menuClicked: 'active',
                        ulSidenavClass: 'block-display'
                    });
                }
            } else {
                this.setState({
                    ...this.state,
                    thisMenu: 'inactive',
                    ulSidenavClass: 'block-display height-adjust'
                });
            }
        });
    }

HTML:

                 this.handleClick('homeMenuStatus')}>Home

                        Dashboard

                        Activities

My state object is not getting changed. Must be doing something wrong in setState(). Can anyone please guide me.

Body:
You are incorrectly updating the state, use prevState syntax and return the mapped updated values like

handleClick(menuClicked) {
    this.setState((prevState) => ({menuState: prevState.menuState.map((name, index) => {
           if(name.menuName === menuClicked) {
              if(name.menuClicked === 'active') {
                  return {
                      ...name,
                      menuClicked: 'inactive,
                      ulSidenavClass: 'block-display height-adjust'
                  }
              } else {
                  return {
                      ...name,
                      menuClicked: 'active,
                      ulSidenavClass: 'block-display'
                  }
              }

           } else {
                 return {
                      ...name,
                      menuClicked: 'inactive,
                      ulSidenavClass: 'block-display height-adjust'
                  }
            }
    })}))

}


问:
i18n - How to use it in application.hbs?
In which route/component should I inject the "i18n" service for it to be used in application.hbs?
I'm trying to use it in other HBS files, and if I inject "i18n" into the route/component - I'm able to use it.

But it's just not working in application.hbs

答:
You can do it by using an instance initializer and inject i18n service to your all routes and components by using this code:

/instance-initializers/component-route-i18n-injector.js

```<code>import Ember from 'ember';

export function initialize(appInstance) {

  let i18n = appInstance.lookup('service:i18n');
  Ember.Component.reopen({
    i18n: i18n
  });
  Ember.Controller.reopen({
    i18n: i18n
  });
}

export default {
  name: 'component-route-i18n-injector',
  initialize
};
</code>```

You can take a look at this twiddle.

Body:
You can do it by using an instance initializer and inject i18n service to your all routes and components by using this code:

/instance-initializers/component-route-i18n-injector.js

import Ember from 'ember';

export function initialize(appInstance) {

  let i18n = appInstance.lookup('service:i18n');
  Ember.Component.reopen({
    i18n: i18n
  });
  Ember.Controller.reopen({
    i18n: i18n
  });
}

export default {
  name: 'component-route-i18n-injector',
  initialize
};

You can take a look at this twiddle.


问:
swagger error: Conflicting schemaIds: Duplicate schemaIds detected for types A and B
Using Web API and using swashbuckle to generate swagger documentation,
I defined two different classes with the same name in two different namespaces. when I open swagger page in my browser it says

Conflicting schemaIds: Duplicate schemaIds detected for types A and B. See the config setting - "UseFullTypeNameInSchemaIds" for a potential workaround

full message:

500 : {"Message":"An error has occurred.","ExceptionMessage":"Conflicting schemaIds: Duplicate schemaIds detected for types A and B. See the config setting - \"UseFullTypeNameInSchemaIds\" for a potential workaround","ExceptionType":"System.InvalidOperationException","StackTrace":" at Swashbuckle.Swagger.SchemaRegistry.CreateRefSchema(Type type)\r\n at Swashbuckle.Swagger.SchemaRegistry.CreateInlineSchema(Type type)\r\n at Swashbuckle.Swagger.SchemaRegistry.b__1f(JsonProperty prop)\r\n at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable1 source, Func2 keySelector, Func2 elementSelector, IEqualityComparer1 comparer)\r\n at Swashbuckle.Swagger.SchemaRegistry.CreateObjectSchema(JsonObjectContract jsonContract)\r\n at Swashbuckle.Swagger.SchemaRegistry.CreateDefinitionSchema(Type type)\r\n at Swashbuckle.Swagger.SchemaRegistry.GetOrRegister(Type type)\r\n at Swashbuckle.Swagger.SwaggerGenerator.CreateOperation(ApiDescription apiDesc, SchemaRegistry schemaRegistry)\r\n at Swashbuckle.Swagger.SwaggerGenerator.CreatePathItem(IEnumerable1 apiDescriptions, SchemaRegistry schemaRegistry)\r\n at Swashbuckle.Swagger.SwaggerGenerator.<>c__DisplayClass7.<GetSwagger>b__4(IGrouping2 group)\r\n at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable1 source, Func2 keySelector, Func2 elementSelector, IEqualityComparer1 comparer)\r\n at Swashbuckle.Swagger.SwaggerGenerator.GetSwagger(String rootUrl, String apiVersion)\r\n at Swashbuckle.Application.SwaggerDocsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.HttpServer.d__0.MoveNext()"} http://localhost:24215/swagger/docs/v1

I don't want to change my classes' names. How can I fix it?

答:
Every class in the swagger JSON must have a unique schemaId.

Swashbuckler tries to just use the class name as a simple schemaId, however if you have two classes in different namespaces with the same name (as you do) this will not work.

As the error suggests, you can use the config setting "UseFullTypeNameInSchemaIds*" for a potential workaround (Update: not available in recent versions)

In newer versions you can achieve the same behavior via options.CustomSchemaIds(x => x.FullName).

Here is an example:

```<code>   services.ConfigureSwaggerGen(options =>
   {
       //your custom configuration goes here

...

  // UseFullTypeNameInSchemaIds replacement for .NET Core
       options.CustomSchemaIds(x => x.FullName);
   });
</code>```

for more information http://wegotcode.com/microsoft/swagger-fix-for-dotnetcore/

Body:
Every class in the swagger JSON must have a unique schemaId.

Swashbuckler tries to just use the class name as a simple schemaId, however if you have two classes in different namespaces with the same name (as you do) this will not work.

As the error suggests, you can use the config setting "UseFullTypeNameInSchemaIds*" for a potential workaround (Update: not available in recent versions)

In newer versions you can achieve the same behavior via options.CustomSchemaIds(x => x.FullName).

Here is an example:

   services.ConfigureSwaggerGen(options =>
   {
       //your custom configuration goes here

...

  // UseFullTypeNameInSchemaIds replacement for .NET Core
       options.CustomSchemaIds(x => x.FullName);
   });

for more information http://wegotcode.com/microsoft/swagger-fix-for-dotnetcore/


问:
Best web-programming language for math-problems generator
Firstly I am new in web programming but have knowledge in Java,C++, and HTML
I have a project for my college, in which I'll be making some sort of math-problems generator using web-programming language. It is something like www.wamap.org or basically it generates math problems based on the data stored in the database, generates the solutions, and compare them with students' solution.
What would be the best language to use? I mean the one that is more convenient if I have experience in desktop programming. I am thinking of PHP right now, but a friend said Ruby on Rails would also make a great choice. I read a little bit about rails and I think it is more suitable for view-oriented web application which in this case is not my project. Any suggestions are really appreciated.

Regards,

Denny Harijanto

答: If you know java you can use Java servlets. It's very easy to implement (well, it's java).</p>


问:
Save dynamic data to two tables using relationship in Laravel
I have two tables Students and Hobbies. I've all details in one form but I want to save details to separate tables on submit. How can I achieve this?

My Student model

```<code><?php

namespace App;

class Students extends Model {
protected $fillable = ['name', 'address'];

public function hobbies() {
    return $this->hasMany(Hobby::class);
}
}
</code>```

Hobby model:

```<code><?php

namespace App;

use App\Product;

class Hobby extends Model
{

protected $fillable = [
    'entertainment', 'sports'
    ];

public function hobby()
{
    return $this->belongsTo(Student::class);
}
}
</code>```

Controller:

```<code>public function save(Request $request, Student $student)
{
    $students= new Student;
                $students->name= request('name');
                $students->address= request('address');
                $students->save();
    if($students->save())
    {
        $hobbies= [];
        $images = $request->file('hob_img');
        $hob_desc = $request->hob_desc;

        foreach ($request->hob_name as $key => $hobby) {
            $hob_img = '';
            {
                $hob_img = uniqid() . '.' . $files[$key]->getClientOriginalExtension();
                $files[$key]->move(public_path('/assets/images/'), $hob_img);
            }
            $hobbies[] = [
                'hob_name' => $hobby,
                'hob_desc' => $hob_desc[$key],
                'hob_img' => $hob_img
            ];

        }
        $hobbies[] = new Hobby;
                    $hobbies->hob_name = request('hob_name')[$key];
                    $hobbies->hob_desc= request('hob_desc')[$key];
                    $hobbies->hob_img = request($hob_img)[$key];
        $hobbies->save();

    }
}
</code>```

But I cannot save it. It says SQLSTATE[HY000]: General error: 1364 Field 'student_id' doesn't have a default value

答:
Try the insert to save many records at onece :

```<code>public function save(Request $request, Student $student)
{
    $student= new Student;
    $student->name= request('name');
    $student->address= request('address');
    if($student->save())
    {
        $hobbies= [];
        $images = $request->file('hob_img');
        $hob_desc = $request->hob_desc;

        foreach ($request->hob_name as $key => $hobby) {
            $hob_img = '';

            $hob_img = uniqid() . '.' . $files[$key]->getClientOriginalExtension();
            // $files i think it should be $images
            $files[$key]->move(public_path('/assets/images/'), $hob_img);

            $hobbies[] = [
                'hob_name' => $hobby,
                'hob_desc' => $hob_desc[$key],
                'hob_img' => $hob_img,
                'student_id'=> $student->id
            ];

        }
        Hobby::insert($hobbies); // useing Eloquent

        // Or you can use Query Builder
        // DB::table('hobbies')->insert($hobbies);
    }
}
</code>```

Body:
I have two tables Students and Hobbies. I've all details in one form but I want to save details to separate tables on submit. How can I achieve this?

My Student model

<?php

namespace App;

class Students extends Model {
protected $fillable = ['name', 'address'];

public function hobbies() {
    return $this->hasMany(Hobby::class);
}
}

Hobby model:

<?php

namespace App;

use App\Product;

class Hobby extends Model
{

protected $fillable = [
    'entertainment', 'sports'
    ];

public function hobby()
{
    return $this->belongsTo(Student::class);
}
}

Controller:

public function save(Request $request, Student $student)
{
    $students= new Student;
                $students->name= request('name');
                $students->address= request('address');
                $students->save();
    if($students->save())
    {
        $hobbies= [];
        $images = $request->file('hob_img');
        $hob_desc = $request->hob_desc;

        foreach ($request->hob_name as $key => $hobby) {
            $hob_img = '';
            {
                $hob_img = uniqid() . '.' . $files[$key]->getClientOriginalExtension();
                $files[$key]->move(public_path('/assets/images/'), $hob_img);
            }
            $hobbies[] = [
                'hob_name' => $hobby,
                'hob_desc' => $hob_desc[$key],
                'hob_img' => $hob_img
            ];

        }
        $hobbies[] = new Hobby;
                    $hobbies->hob_name = request('hob_name')[$key];
                    $hobbies->hob_desc= request('hob_desc')[$key];
                    $hobbies->hob_img = request($hob_img)[$key];
        $hobbies->save();

    }
}

But I cannot save it. It says SQLSTATE[HY000]: General error: 1364 Field 'student_id' doesn't have a default value

Body:
Try the insert to save many records at onece :

public function save(Request $request, Student $student)
{
    $student= new Student;
    $student->name= request('name');
    $student->address= request('address');
    if($student->save())
    {
        $hobbies= [];
        $images = $request->file('hob_img');
        $hob_desc = $request->hob_desc;

        foreach ($request->hob_name as $key => $hobby) {
            $hob_img = '';

            $hob_img = uniqid() . '.' . $files[$key]->getClientOriginalExtension();
            // $files i think it should be $images
            $files[$key]->move(public_path('/assets/images/'), $hob_img);

            $hobbies[] = [
                'hob_name' => $hobby,
                'hob_desc' => $hob_desc[$key],
                'hob_img' => $hob_img,
                'student_id'=> $student->id
            ];

        }
        Hobby::insert($hobbies); // useing Eloquent

        // Or you can use Query Builder
        // DB::table('hobbies')->insert($hobbies);
    }
}


问:
How to add unexported functions to R Package
I am working on a R Package with several functions that I use in one exported function.

My question, probably a silly one, is where am I supposed to put all these unexported functions? Or how can I make this possible?

I don't want to let user access this functions from R/ directory.

Here is my fictitious function that uses the unexported function add:

```<code>my_func <- function(x, y){
   result <- exp(add(x, y))
   return(result)
   }
</code>```

And here is my fictitious function add that I do not want to export:

```<code>add <- function(x, y) {
 result <- x + y
 return(result)
}
</code>```

Thank you

EDIT

If I put all functions in /R they will be "visible" for user. For example, generate.cv.folds from xgboost package is unexported but you still can access it with xgboost:::generate.cv.foldsand I want to do the same.

答:
R does not provide infrastructure for hiding source code[1]. Doing that is against the R developers' values and wishes.

So, what you want to do is not possible with R.

[1] http://r.789695.n4.nabble.com/how-to-hide-code-of-any-function-td4474822.html

Body:
I am working on a R Package with several functions that I use in one exported function.

My question, probably a silly one, is where am I supposed to put all these unexported functions? Or how can I make this possible?

I don't want to let user access this functions from R/ directory.

Here is my fictitious function that uses the unexported function add:

my_func <- function(x, y){
   result <- exp(add(x, y))
   return(result)
   }

And here is my fictitious function add that I do not want to export:

add <- function(x, y) {
 result <- x + y
 return(result)
}

Thank you

EDIT

If I put all functions in /R they will be "visible" for user. For example, generate.cv.folds from xgboost package is unexported but you still can access it with xgboost:::generate.cv.foldsand I want to do the same.


问:
Google Guava isNullOrEmpty for collections
I see that Guava has isNullOrEmpty utility method for Strings

```<code>Strings.isNullOrEmpty(str)
</code>```

Do we have anything similar for Lists? Something like

```<code>Lists.isNullOrEmpty(list)
</code>```

which should be equivalent to

```<code>list == null || list.isEmpty()
</code>```

Also, do we have anything similar for Arrays? Something like

```<code>Arrays.isNullOrEmpty(arr)
</code>```

which should be equivalent to

```<code>arr == null || arr.length == 0
</code>```

答:
Look at Appache Collections
CollectionUtils.isEmpty()
returns true if collection is null or empty</p>

Body:
I see that Guava has isNullOrEmpty utility method for Strings

Strings.isNullOrEmpty(str)

Do we have anything similar for Lists? Something like

Lists.isNullOrEmpty(list)

which should be equivalent to

list == null || list.isEmpty()

Also, do we have anything similar for Arrays? Something like

Arrays.isNullOrEmpty(arr)

which should be equivalent to

arr == null || arr.length == 0


问:
moving an xml file based on multiple search strings
still learning powershell. I have a script that moves an xml file based on a search string but it needs to match more than 1 search string and I'm struggling with a way to do this.

Here's the code as I have it, which currently works for a single string:

```<code>$SrcDir = "c:\source"
$DestDir = "c:\destination"
$SearchString1 = "String1"
$SearchString2 = "String2"

Get-ChildItem $SrcDir -filter *.xml |
  Select-String $SearchString1 -List |
  Select-Object Path |
  Move-Item -Dest $DestDir
</code>```

So it's clear what I'm trying to achieve: If the xml file contains $SearchString1 AND $SearchString2 then move from source to destination. I can't seem to make it match both. It's probably very simple, or maybe I need to do it a different way, but I would appreciate some help.

答:
Looking at Select-String's help:

```<code>PS> Get-Help Select-String -Parameter Pattern
</code>```

-Pattern

Specifies the text to find. Type a string or regular expression. If you type a string, use the SimpleMatch parameter.

To learn about regular expressions, see about_Regular_Expressions.

It says, that -Pattern wants a reqular expression, not a [string]. As suggested by the help page, we learn more about Regular Expressions using Get-Help About_Regular_Expressions.

This results in replacing your statement Select-String $SearchString1 -List with:

```<code>Select-String "($SearchString1.*$SearchString2|$SearchString2.*$SearchString1)" -List | #[...]
</code>```

Will do the trick.

Body:
still learning powershell. I have a script that moves an xml file based on a search string but it needs to match more than 1 search string and I'm struggling with a way to do this.

Here's the code as I have it, which currently works for a single string:

$SrcDir = "c:\source"
$DestDir = "c:\destination"
$SearchString1 = "String1"
$SearchString2 = "String2"

Get-ChildItem $SrcDir -filter *.xml |
  Select-String $SearchString1 -List |
  Select-Object Path |
  Move-Item -Dest $DestDir

So it's clear what I'm trying to achieve: If the xml file contains $SearchString1 AND $SearchString2 then move from source to destination. I can't seem to make it match both. It's probably very simple, or maybe I need to do it a different way, but I would appreciate some help.

Body:
Looking at Select-String's help:

PS> Get-Help Select-String -Parameter Pattern

-Pattern

Specifies the text to find. Type a string or regular expression. If you type a string, use the SimpleMatch parameter.

To learn about regular expressions, see about_Regular_Expressions.

It says, that -Pattern wants a reqular expression, not a [string]. As suggested by the help page, we learn more about Regular Expressions using Get-Help About_Regular_Expressions.

This results in replacing your statement Select-String $SearchString1 -List with:

Select-String "($SearchString1.*$SearchString2|$SearchString2.*$SearchString1)" -List | #[...]

Will do the trick.


问:
how I can hide displaying result of exec command
```<code>WHILE @nxt < @rc
    BEGIN
       set @sql = (select Rec from DmsRec where row=@nxt)
       use TestDB1
       exec (@sql)
       select @rc_child = @@ROWCOUNT
       use MyTempDB
       if @rc_child = 0
       begin
            insert into DMSResults
            select DOCID from DmsRec where row=@nxt
       end
       set @nxt = @nxt + 1
    END
</code>```

My Question is how I can hide displaying result of exec command.
(using Sql Server 2008r2) Above query is small part of complete procedure.

Accessing multiple conditions,value and multiple databases I generate a select statement and stored in Rec Field into table DmsRec

After generating require Select.... statement I stored it into table DmsRec.
e.g. SELECT ACCD FROM M_TABLE WHERE 1=1  and ACCD='0034422'.

This select statement which is stored as a value in table DmsRec
want to execute in different database.

So I used use command and change the database name, access the recordset.
If the executed sql (return 0 row) then run the insert command which is executed in different database.
With this I came to know wether Inserted docid into DMSResults is those tranaction whose master is not avalialbel.

It works perfectly but can not hide displaying records of exec command.

I run exec(@sql) is only to check whether it is returning any row or not.
and stored rowcount value into variable.

But do not want to display records in grid (at the same time result {effected rows} should stored in variable).

Without changing options in SSMS manually i.e.
Tools/Options, Query Results/SQL Server/Results to XX, check "Discard results after query executes"

答:
EDIT - based on comments below

You can use sp_executesql and pass parameters to it, even OUTPUT parameters.

Here's an example - you will need to amend the SQL query you're storing slightly

```<code>DECLARE @SQL NVARCHAR(MAX), @Rows INT, @nxt INT = 1
CREATE TABLE DmsRec (row INT, rec NVARCHAR(10))
INSERT INTO DmsRec(row, rec)
    VALUES(1, 1)

SET @SQL = 'IF EXISTS ( SELECT rec FROM dbo.DmsRec WHERE row = @nxt) SET @Rows = 1  ELSE SET @Rows = 0' --+'; SELECT @Rows = @@ROWCOUNT'
EXEC sys.sp_executesql @sql, N'@nxt INT, @Rows INT OUTPUT', @nxt, @Rows OUTPUT;
SELECT @Rows
</code>```

```<code>SET @nxt = 0 -- record doesn't exist
SET @SQL = 'IF EXISTS ( SELECT rec FROM dbo.DmsRec WHERE row = @nxt) SET @Rows = 1 ELSE SET @Rows = 0'

EXEC sys.sp_executesql @sql, N'@nxt INT, @Rows INT OUTPUT', @nxt, @Rows OUTPUT;
SELECT @Rows
</code>```

You can then use @Rows variable to determine whether you need to insert a new record or not.

```<code>If @Rows = 1
BEGIN
   --INSERT record
END
</code>```

Body:
WHILE @nxt < @rc
    BEGIN
       set @sql = (select Rec from DmsRec where row=@nxt)
       use TestDB1
       exec (@sql)
       select @rc_child = @@ROWCOUNT
       use MyTempDB
       if @rc_child = 0
       begin
            insert into DMSResults
            select DOCID from DmsRec where row=@nxt
       end
       set @nxt = @nxt + 1
    END

My Question is how I can hide displaying result of exec command.
(using Sql Server 2008r2) Above query is small part of complete procedure.

Accessing multiple conditions,value and multiple databases I generate a select statement and stored in Rec Field into table DmsRec

After generating require Select.... statement I stored it into table DmsRec.
e.g. SELECT ACCD FROM M_TABLE WHERE 1=1  and ACCD='0034422'.

This select statement which is stored as a value in table DmsRec
want to execute in different database.

So I used use command and change the database name, access the recordset.
If the executed sql (return 0 row) then run the insert command which is executed in different database.
With this I came to know wether Inserted docid into DMSResults is those tranaction whose master is not avalialbel.

It works perfectly but can not hide displaying records of exec command.

I run exec(@sql) is only to check whether it is returning any row or not.
and stored rowcount value into variable.

But do not want to display records in grid (at the same time result {effected rows} should stored in variable).

Without changing options in SSMS manually i.e.
Tools/Options, Query Results/SQL Server/Results to XX, check "Discard results after query executes"

Body:
EDIT - based on comments below

You can use sp_executesql and pass parameters to it, even OUTPUT parameters.

Here's an example - you will need to amend the SQL query you're storing slightly

DECLARE @SQL NVARCHAR(MAX), @Rows INT, @nxt INT = 1
CREATE TABLE DmsRec (row INT, rec NVARCHAR(10))
INSERT INTO DmsRec(row, rec)
    VALUES(1, 1)

SET @SQL = 'IF EXISTS ( SELECT rec FROM dbo.DmsRec WHERE row = @nxt) SET @Rows = 1  ELSE SET @Rows = 0' --+'; SELECT @Rows = @@ROWCOUNT'
EXEC sys.sp_executesql @sql, N'@nxt INT, @Rows INT OUTPUT', @nxt, @Rows OUTPUT;
SELECT @Rows

SET @nxt = 0 -- record doesn't exist
SET @SQL = 'IF EXISTS ( SELECT rec FROM dbo.DmsRec WHERE row = @nxt) SET @Rows = 1 ELSE SET @Rows = 0'

EXEC sys.sp_executesql @sql, N'@nxt INT, @Rows INT OUTPUT', @nxt, @Rows OUTPUT;
SELECT @Rows

You can then use @Rows variable to determine whether you need to insert a new record or not.

If @Rows = 1
BEGIN
   --INSERT record
END


问:
How do I populate one listbox from another listbox using JavaScript?
Can anyone tell me how to populate one listbox from another listbox item using JavaScript or ASP.NET 2.0?

Duplicate

How would I move one list box items to another listbox items in JavaScript?

For ex--My 1st listbox is Region then accourding to region selection the second listbox country will be display and accourding to country seletion state listbox will display all will come from database depends on Region Id or Country id n all

答:
You may be interested in the 'Cascading Dropdown' control from the ASP.net AJAX Control Toolkit.  http://www.asp.net/AJAX/AjaxControlToolkit/Samples/CascadingDropDown/CascadingDropDown.aspx

You could also probably do this without the toolkit, using the standard UpdatePanel from ASP.net AJAX and specifing the "onChange" event of the first dropdown as a "trigger" for that UpdatePanel to be updated.  Be sure you set AutoPostback="true" on the dropdown so it is fired properly is you go this route also.

OwnerDisplayName: priti

OwnerDisplayName: Kyle B.


问:
verifying a list using moq
Given the calling code

```<code>List<Person> loginStaff = new List<Person>();

loginStaff.add(new Person{FirstName = "John", LastName = "Doe"});

this._iViewLoginPanel.Staff = loginStaff;
</code>```

What is the syntax for verifying that there exists a staff by the name of john doe and that there is at least one staff being set? Currently, all the examples that I've seen are pretty basic, using only It.IsAny or Staff = some basic type but none actually verify data within complex types like lists.

My assert looks like

```<code>this._mockViewLoginPanel.VerifySet(x=> x.Staff = It.IsAny<List<Person>>());
</code>```

which only checks the type given to the setter but not the size or items within the list itself. I've tried to do something like this:

```<code>        this._mockViewLoginPanel.VerifySet(
           x =>
           {
               List<string> expectedStaffs = new List<string>{"John Doe", "Joe Blow", "A A", "Blah"};
               foreach (Person staff in x.Staff)
               {
                   if (!expectedStaffs.Contains(staff.FirstName + " " + staff.LastName))
                       return false;
               }
               return true;
           });
</code>```

But that tells me that the lambda statement body cannot be converted to an expression tree.
Then i got the idea of putting the statement body into a function and running that, but during runtime I get:

System.ArgumentException: Expression is not a property setter invocation.

Update:
In light of the first two answers to use assert, I tried that method but found that even after setting Staff to a non null list, it still shows up in debug as null. So this is how the full test looks

```<code>[TestMethod]
public void When_The_Presenter_Is_Created_Then_All_CP_Staff_Is_Added_To_Dropdown()
{
    this._mockViewLoginPanel = new Mock<IViewLoginPanel>();

    PresenterLoginPanel target = new PresenterLoginPanel(this._mockViewLoginPanel.Object);

    this._mockViewLoginPanel
        .VerifySet(x => x.Staff = It.IsAny<List<Person>>());

    Assert.AreEqual(5, this._mockViewLoginPanel.Object.Staff.Count);
}
</code>```

And somewhere within the constructor of PresenterLoginPanel

```<code>public PresenterLoginPanel
{
    private IViewLoginPanel _iViewLoginPanel;

    public PresenterLoginPanel(IViewLoginPanel panel)
    {
        this._iViewLoginPanel = panel;
        SomeFunction();
    }

    SomeFunction() {
        List<Person> loginStaff = new List<Person>();

        loginStaff.add(new Person{FirstName = "John", LastName = "Doe"});

        this._iViewLoginPanel.Staff = loginStaff;
    }
}
</code>```

When i debug to the next line, this._iViewLoginPanel.Staff is null which is what's causing the null exception in the assert.

答:
This checks that the staff count should be more than 0, that there should be at least one item that is not null and there is at least one item that has first name equal to Joe. if you want to compare the objects, you'll have to add a comparer.</p>

```<code>Assert.AreNotEqual(this._mockViewLoginPanel.Object.Staff.Count, 0);
Assert.AreNotEqual(this._mockViewLoginPanel.Object.Staff.All(x => x == null), true);
Assert.AreEqual(this._mockViewLoginPanel.Object.Staff.Any(x => x.FirstName == "Joe"), true);
</code>```

Title: verifying a list using moq

Body:
Given the calling code

List<Person> loginStaff = new List<Person>();

loginStaff.add(new Person{FirstName = "John", LastName = "Doe"});

this._iViewLoginPanel.Staff = loginStaff;

What is the syntax for verifying that there exists a staff by the name of john doe and that there is at least one staff being set? Currently, all the examples that I've seen are pretty basic, using only It.IsAny or Staff = some basic type but none actually verify data within complex types like lists.

My assert looks like

this._mockViewLoginPanel.VerifySet(x=> x.Staff = It.IsAny<List<Person>>());

which only checks the type given to the setter but not the size or items within the list itself. I've tried to do something like this:

        this._mockViewLoginPanel.VerifySet(
           x =>
           {
               List<string> expectedStaffs = new List<string>{"John Doe", "Joe Blow", "A A", "Blah"};
               foreach (Person staff in x.Staff)
               {
                   if (!expectedStaffs.Contains(staff.FirstName + " " + staff.LastName))
                       return false;
               }
               return true;
           });

But that tells me that the lambda statement body cannot be converted to an expression tree.
Then i got the idea of putting the statement body into a function and running that, but during runtime I get:

System.ArgumentException: Expression is not a property setter invocation.

Update:
In light of the first two answers to use assert, I tried that method but found that even after setting Staff to a non null list, it still shows up in debug as null. So this is how the full test looks

[TestMethod]
public void When_The_Presenter_Is_Created_Then_All_CP_Staff_Is_Added_To_Dropdown()
{
    this._mockViewLoginPanel = new Mock<IViewLoginPanel>();

    PresenterLoginPanel target = new PresenterLoginPanel(this._mockViewLoginPanel.Object);

    this._mockViewLoginPanel
        .VerifySet(x => x.Staff = It.IsAny<List<Person>>());

    Assert.AreEqual(5, this._mockViewLoginPanel.Object.Staff.Count);
}

And somewhere within the constructor of PresenterLoginPanel

public PresenterLoginPanel
{
    private IViewLoginPanel _iViewLoginPanel;

    public PresenterLoginPanel(IViewLoginPanel panel)
    {
        this._iViewLoginPanel = panel;
        SomeFunction();
    }

    SomeFunction() {
        List<Person> loginStaff = new List<Person>();

        loginStaff.add(new Person{FirstName = "John", LastName = "Doe"});

        this._iViewLoginPanel.Staff = loginStaff;
    }
}

When i debug to the next line, this._iViewLoginPanel.Staff is null which is what's causing the null exception in the assert.

Body:
This checks that the staff count should be more than 0, that there should be at least one item that is not null and there is at least one item that has first name equal to Joe. if you want to compare the objects, you'll have to add a comparer.

Assert.AreNotEqual(this._mockViewLoginPanel.Object.Staff.Count, 0);
Assert.AreNotEqual(this._mockViewLoginPanel.Object.Staff.All(x => x == null), true);
Assert.AreEqual(this._mockViewLoginPanel.Object.Staff.Any(x => x.FirstName == "Joe"), true);


问:
links with parent directory
I'm using materializecss as a framework but I have many problems.

I have an issue with links and my CSS. I make several include's files to make it easy for me. But when I test my links on the browser in the console's chrome: my CSS is not found and refer to a directory that it doesn't exist!

```<code><link type="text/css" href="../css/admin.css" rel="stylesheet" />
</code>```

This CSS is in the file header.inc.php which is in the file admin/

```<code><?php
include( './inc/header.inc.php' );
?>
<title>Ma page d'administration</title>
</head>

<body>
  <div class="row">
    <?php
    include( './inc/nav.inc.php' );
    ?>
  </div>
</code>```

My links at ./inc/nav.inc.php are not working at all!

```<code><nav>
<div class="nav-wrapper">
  <a href="#!" class="brand-logo hide-on-small-only"><i class="material-icons">lock</i>Section d'administration</a>
  <ul class="right">
    <li><a href="../index.php"><i class="material-icons">home</i></a></li>
    <li><a href="../portfolio.php"><i class="material-icons">add_a_photo</i></a></li>
    <li><a href="../rubriques.php"><i class="material-icons">playlist_add</i></a></li>
  </ul>
</div>
</nav>
</code>```

The browser doesn't find these files portfolio.php and rubriques.php

Browser make the link like it was at root directory.

http://localhost/portfolio.php : wrong link

http://localhost/admin/portfolio.php : right link

here the error message:

admin.css Failed to load resource: the server responded with a status of 404 (Not Found)

Roboto-Regular.woff2 Failed to load resource: the server responded with a status of 404 (Not Found)

Roboto-Regular.woff Failed to load resource: the server responded with a status of 404 (Not Found)

admin.css Failed to load resource: the server responded with a status of 404 (Not Found)

May be you can help me because it really makes me crazy. I really don't understand why links are going to root directory.

Thanks for your help! I appreciate.

答:
A problem you often see when including php files is linking. The moment one php file gets included in another, it will use the directory from the page you included it into (in your case header.inc.php)

So if you had a directory like this:

```<code>index.php
/inc
  --header.inc.php
  --nav.inc.php
/admin
  --portfolio.php
</code>```

You will have to change any include in nav.inc.php to href="admin/portfolio.php">. The same would go for other files.

Title: links with parent directory

Body:
I'm using materializecss as a framework but I have many problems.

I have an issue with links and my CSS. I make several include's files to make it easy for me. But when I test my links on the browser in the console's chrome: my CSS is not found and refer to a directory that it doesn't exist!

<link type="text/css" href="../css/admin.css" rel="stylesheet" />

This CSS is in the file header.inc.php which is in the file admin/

<?php
include( './inc/header.inc.php' );
?>
<title>Ma page d'administration</title>

    <?php
    include( './inc/nav.inc.php' );
    ?>

My links at ./inc/nav.inc.php are not working at all!

  lockSection d'administration

home

add_a_photo

playlist_add

The browser doesn't find these files portfolio.php and rubriques.php

Browser make the link like it was at root directory.

http://localhost/portfolio.php : wrong link

http://localhost/admin/portfolio.php : right link

here the error message:

admin.css Failed to load resource: the server responded with a status of 404 (Not Found)

Roboto-Regular.woff2 Failed to load resource: the server responded with a status of 404 (Not Found)

Roboto-Regular.woff Failed to load resource: the server responded with a status of 404 (Not Found)

admin.css Failed to load resource: the server responded with a status of 404 (Not Found)

May be you can help me because it really makes me crazy. I really don't understand why links are going to root directory.

Thanks for your help! I appreciate.

Body:
A problem you often see when including php files is linking. The moment one php file gets included in another, it will use the directory from the page you included it into (in your case header.inc.php)

So if you had a directory like this:

index.php
/inc
  --header.inc.php
  --nav.inc.php
/admin
  --portfolio.php

You will have to change any include in nav.inc.php to <a href="admin/portfolio.php">. The same would go for other files.


问:
Windows screenshot with scaling
I am trying to take screenshots of every screen on my windows 10 machine.
My system has 2 monitors which are of multiple DPIs.

My primary monitor has "scale and layout" set to 200%.

My secondary
has "scale and layout" set to 100%.

I am trying to use C# to take a screenshot of every single monitor.
However my scaled monitor is reporting the wrong coordinates:
Everything is halved.
As a result, the primary monitor's screenshot is only 1/4th  of the screen area (width/2,height/2).

Here is my code:

```<code>    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;

namespace CsSourceClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Screen[] screens;
            screens = Screen.AllScreens;

            int i = 0;

            foreach (var screen in System.Windows.Forms.Screen.AllScreens)
            {
                var savePath = "monitor" + i+".jpg";
                var x = screen.Bounds.Location.X;
                var y = screen.Bounds.Location.Y;
                var w = screen.Bounds.Width;
                var h = screen.Bounds.Height;
                Console.Out.WriteLine("Monitor: " + i + " extents:" + x + "," + y + " " + w + "," + h);
                using (Bitmap bmp = new Bitmap(w, h))
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.CopyFromScreen(x, y, 0, 0, bmp.Size);
                    }

                    bmp.Save(savePath, ImageFormat.Jpeg);
                    Console.Out.WriteLine("saved: " + savePath);
                }
                i++;
            }

        }
    }
}
</code>```

PS: I get different values based on what I set "dpiaware" in the manifest file: https://social.msdn.microsoft.com/Forums/en-US/054c1d49-9f24-4617-aa83-9bc4f1bb4a5d/use-appmanifest-file-to-make-winforms-application-dpi-aware?forum=vbgeneral

If I don't set dpiaware, then the primary monitor's bounds get halved (cropping out 3/4ths of the screen).
If I set dpiaware to true, then the secondary monitor's bounds get doubled (leaving big black areas in the screenshot).

答:
As mentioned in the comments, the solution is to set the app.manifest dpiAware tag to "true/pm". The effect is different than just setting it to true.

```<code><application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
      <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
    </windowsSettings>
  </application>
</code>```

Title: Windows screenshot with scaling

Body:
I am trying to take screenshots of every screen on my windows 10 machine.
My system has 2 monitors which are of multiple DPIs.

My primary monitor has "scale and layout" set to 200%.

My secondary
has "scale and layout" set to 100%.

I am trying to use C# to take a screenshot of every single monitor.
However my scaled monitor is reporting the wrong coordinates:
Everything is halved.
As a result, the primary monitor's screenshot is only 1/4th  of the screen area (width/2,height/2).

Here is my code:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;

namespace CsSourceClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Screen[] screens;
            screens = Screen.AllScreens;

            int i = 0;

            foreach (var screen in System.Windows.Forms.Screen.AllScreens)
            {
                var savePath = "monitor" + i+".jpg";
                var x = screen.Bounds.Location.X;
                var y = screen.Bounds.Location.Y;
                var w = screen.Bounds.Width;
                var h = screen.Bounds.Height;
                Console.Out.WriteLine("Monitor: " + i + " extents:" + x + "," + y + " " + w + "," + h);
                using (Bitmap bmp = new Bitmap(w, h))
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.CopyFromScreen(x, y, 0, 0, bmp.Size);
                    }

                    bmp.Save(savePath, ImageFormat.Jpeg);
                    Console.Out.WriteLine("saved: " + savePath);
                }
                i++;
            }

        }
    }
}

PS: I get different values based on what I set "dpiaware" in the manifest file: https://social.msdn.microsoft.com/Forums/en-US/054c1d49-9f24-4617-aa83-9bc4f1bb4a5d/use-appmanifest-file-to-make-winforms-application-dpi-aware?forum=vbgeneral

If I don't set dpiaware, then the primary monitor's bounds get halved (cropping out 3/4ths of the screen).
If I set dpiaware to true, then the secondary monitor's bounds get doubled (leaving big black areas in the screenshot).

Body:
As mentioned in the comments, the solution is to set the app.manifest dpiAware tag to "true/pm". The effect is different than just setting it to true.

<application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
      <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
    </windowsSettings>
  </application>


问:
Why does adding an array to number return a string?
```<code>var array = [1,2,4];

array+1  //gives '1,2,41'.
</code>```

<p>Can anyone explain this behaviour? </p>

答:
When the operands of an operator are different types, they will be converted to a common type.

Both an array and a Number can be converted to string, this is called coercion.

If you would like to add 1 to an array, you can do this:

```<code>var array = [1,2,4];
array.push(1);
</code>```

Body:
var array = [1,2,4];

array+1  //gives '1,2,41'.

Can anyone explain this behaviour?

Body:
When the operands of an operator are different types, they will be converted to a common type.

Both an array and a Number can be converted to string, this is called coercion.

If you would like to add 1 to an array, you can do this:

var array = [1,2,4];
array.push(1);


问:
Using Public Activity to Show who has been followed
Im using public activity to provide notifications for activities of people followed. I want to show if a user follows another in the format of

```<code>John Doe followed Sam Smith
</code>```

But all I can achieve so far is

```<code>John Doe followed 1
</code>```

here is my code. Relationships controller

```<code>class RelationshipsController < ApplicationController
 before_action :authenticate_user!

 def create
  @user = User.find(params[:followed_id])
  current_user.follow(@user)
  respond_to do |format|
    format.html { redirect_to @user }
    format.js
  end
 end

 def destroy
  @user = Relationship.find(params[:id]).followed
  current_user.unfollow(@user)
  respond_to do |format|
   format.html { redirect_to @user }
   format.js
  end
 end
end
</code>```

Relationship model

```<code>class Relationship < ApplicationRecord
 include PublicActivity::Model
  tracked owner: ->(controller, model) { controller && controller.current_user }

  belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"

  validates :follower_id, presence: true
  validates :followed_id, presence: true
end
</code>```

Relationship create file inside public_activity folder

```<code><% if activity.trackable %>
  Followed <%= activity.trackable.followed_id %>
<% else %>
  Unfollowed a User
 <% end %>
</code>```

答:
Instead of just rendering a followed_id you might want to render the followed.name instead. Change:

```<code>Followed <%= activity.trackable.followed_id %>
</code>```

to something like this (replace name with a method that makes sense in your application):

```<code>Followed <%= activity.trackable.followed.name %>
</code>```

Body:
Im using public activity to provide notifications for activities of people followed. I want to show if a user follows another in the format of

John Doe followed Sam Smith

But all I can achieve so far is

John Doe followed 1

here is my code. Relationships controller

class RelationshipsController < ApplicationController
 before_action :authenticate_user!

 def create
  @user = User.find(params[:followed_id])
  current_user.follow(@user)
  respond_to do |format|
    format.html { redirect_to @user }
    format.js
  end
 end

 def destroy
  @user = Relationship.find(params[:id]).followed
  current_user.unfollow(@user)
  respond_to do |format|
   format.html { redirect_to @user }
   format.js
  end
 end
end

Relationship model

class Relationship < ApplicationRecord
 include PublicActivity::Model
  tracked owner: ->(controller, model) { controller && controller.current_user }

  belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"

  validates :follower_id, presence: true
  validates :followed_id, presence: true
end

Relationship create file inside public_activity folder

<% if activity.trackable %>
  Followed <%= activity.trackable.followed_id %>
<% else %>
  Unfollowed a User
 <% end %>

Body:
Instead of just rendering a followed_id you might want to render the followed.name instead. Change:

Followed <%= activity.trackable.followed_id %>

to something like this (replace name with a method that makes sense in your application):

Followed <%= activity.trackable.followed.name %>


问:
What's the purpose of (IN.uv.xyxy).xy)?
I'v got a surface shader some other people wrote.And it works fine.However I see codes like this:

```<code>struct Input
{
    float2 uv;
    //...
}

void surf(Input IN,//...)
{
    float4 tex = tex2D(_Tex, (IN.uv.xyxy).xy);
}
</code>```

...

I tried to replace (IN.uv.xyxy).xy with IN.uv. The output effect seems nothing different.

So I was wondering what does the (.xyxy).xy do?

Does the code have to be like this?Thanks for any help!

答:
In GLSL, this is known as swizzle operation.

You can use it to filter, reorder, and repeat float components.

You can use any combination of up to 4 of the letters to create a vector4 (of the same basic type) of that length.

So
IN.uv.xyxyis a vector4, created using only x and y components on uv in repetition.

Then

(IN.uv.xyxy).xy is vector2 same type as IN.uv but so with called enhancement. I guess in your code these two would not be much different as its just like creating a Vector4 from Vector2 and then using its first 2 values to create Vector2.

Like in following example:

```<code>Vector2 v2 = new Vector2(2f,4f);
Vector4 v4 = new Vector4(v2.x, v2.y, v2.x, v2.y);
Vector2 v2_new = new Vector2(v4.x, v4.y); // same as v2
</code>```

Any combination of up to 4 letters is acceptable, so long as the source vector actually has those components.

Hope this helps.

Title: What's the purpose of (IN.uv.xyxy).xy)?

Body:
I'v got a surface shader some other people wrote.And it works fine.However I see codes like this:

struct Input
{
    float2 uv;
    //...
}

void surf(Input IN,//...)
{
    float4 tex = tex2D(_Tex, (IN.uv.xyxy).xy);
}

...

I tried to replace (IN.uv.xyxy).xy with IN.uv. The output effect seems nothing different.

So I was wondering what does the (.xyxy).xy do?

Does the code have to be like this?Thanks for any help!

Body:
In GLSL, this is known as swizzle operation.

You can use it to filter, reorder, and repeat float components.

You can use any combination of up to 4 of the letters to create a vector4 (of the same basic type) of that length.

So
IN.uv.xyxyis a vector4, created using only x and y components on uv in repetition.

Then

(IN.uv.xyxy).xy is vector2 same type as IN.uv but so with called enhancement. I guess in your code these two would not be much different as its just like creating a Vector4 from Vector2 and then using its first 2 values to create Vector2.

Like in following example:

Vector2 v2 = new Vector2(2f,4f);
Vector4 v4 = new Vector4(v2.x, v2.y, v2.x, v2.y);
Vector2 v2_new = new Vector2(v4.x, v4.y); // same as v2

Any combination of up to 4 letters is acceptable, so long as the source vector actually has those components.

Hope this helps.


问:
Getting window list in Xvfb server
I'm trying to get the window list in a Xvfb server in a debian squeeze machine.
What I'm doing is:

```<code>$ Xvfb :2&
$ DISPLAY=:2; wmctrl -l
</code>```

But I'm getting this error:

```<code>Cannot get client list properties. (_NET_CLIENT_LIST or _WIN_CLIENT_LIST)
</code>```

Is this normal or am I missing something?

Thanks!!

答:
I had similar problem. Im my case xfce-panel was not configured.
Finally I executed:

```<code>sudo chmod -x /usr/bin/xfce4-panel
</code>```

This solved the problem (I did not need this panel).
This is a dirty hack. The proper approach is configuring the panel.

Title: Getting window list in Xvfb server

Body:
I'm trying to get the window list in a Xvfb server in a debian squeeze machine.
What I'm doing is:

$ Xvfb :2&
$ DISPLAY=:2; wmctrl -l

But I'm getting this error:

Cannot get client list properties. (_NET_CLIENT_LIST or _WIN_CLIENT_LIST)

Is this normal or am I missing something?

Thanks!!

Body:
I had similar problem. Im my case xfce-panel was not configured.
Finally I executed:

sudo chmod -x /usr/bin/xfce4-panel

This solved the problem (I did not need this panel).
This is a dirty hack. The proper approach is configuring the panel.


问:
Download and extract .tar.gz file with PHP cURL and return to client as string doesn't work
I try to download a .tar.gz file via PHP cURL, extract it and return the file's content as string to the client.

When I try via terminal it works:

```<code>curl "https://domain.com/filename.tar.gz?what=ever&fu=bar" | tar -xz
</code>```

Trying via PHP cURL doesn't work (where responseUrl comes from the client app):

```<code>$_curl = curl_init();
curl_setopt_array($_curl, array(
    CURLOPT_URL => $_POST['responseUrl'],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => 'gzip'
));
$_responseFile = curl_exec($_curl);
curl_close($_curl);

echo file_get_contents($_responseFile);
</code>```

The return I get to the client Angular2 app is:

```<code>Response {
    _body: "",
    headers: Headers,
    ok: true,
    status: 200,
    statusText: "Ok",
    type: 2,
    url: "http://test.local/api/getResponse.php",
    __proto__: Object
}
</code>```

What's wrong with my script? Any help appreciated!

答:
I can help - How To Download & Extract Zip Archives in PHP

Hope it will work for the  .tar.gz file.

PHP has the Zip Archive Extension. You can see the php manual for installing ZipArchive Extension. The usage of ZipArchive extension is very easy.

Download

For downloading, we will use cURL. First we create a blank zip file, download the zip file from server and put it’s contents to the blank zip file we created.

```<code>$url = "http://example.com/pathtozipfile.zip";
$zipFile = "folder/zipfile.zip"; // Local Zip File Path
$zipResource = fopen($zipFile, "w");
// Get The Zip File From Server
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FILE, $zipResource);
$page = curl_exec($ch);
if(!$page) {
echo "Error :- ".curl_error($ch);
}
curl_close($ch);
</code>```

cURL will get the Zip archive file from url mentioned in the variable $url. The $zipFile variable contain the local path of the file were we’re going to save the Zip archive file.

Extract (Unzip)

For extracting as we mentioned before, we will use the PHP Zip Archive Extension.
We’ll make the class variable, open the Zip archive file and extract it :

```<code>/* Open the Zip file */
$zip = new ZipArchive;
$extractPath = "path_to_extract";
if($zip->open($zipFile) != "true"){
echo "Error :- Unable to open the Zip File";
}
/* Extract Zip File */
$zip->extractTo($extractPath);
$zip->close();
</code>```

The extract path should be mentioned in the $extractPath variable. If any of the files exists, it will be overwritten or merged.

Body:
I try to download a .tar.gz file via PHP cURL, extract it and return the file's content as string to the client.

When I try via terminal it works:

curl "https://domain.com/filename.tar.gz?what=ever&fu=bar" | tar -xz

Trying via PHP cURL doesn't work (where responseUrl comes from the client app):

$_curl = curl_init();
curl_setopt_array($_curl, array(
    CURLOPT_URL => $_POST['responseUrl'],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => 'gzip'
));
$_responseFile = curl_exec($_curl);
curl_close($_curl);

echo file_get_contents($_responseFile);

The return I get to the client Angular2 app is:

Response {
    _body: "",
    headers: Headers,
    ok: true,
    status: 200,
    statusText: "Ok",
    type: 2,
    url: "http://test.local/api/getResponse.php",
    __proto__: Object
}

What's wrong with my script? Any help appreciated!

Body:
I can help - How To Download & Extract Zip Archives in PHP

Hope it will work for the  .tar.gz file.

PHP has the Zip Archive Extension. You can see the php manual for installing ZipArchive Extension. The usage of ZipArchive extension is very easy.

Download

For downloading, we will use cURL. First we create a blank zip file, download the zip file from server and put it’s contents to the blank zip file we created.

$url = "http://example.com/pathtozipfile.zip";
$zipFile = "folder/zipfile.zip"; // Local Zip File Path
$zipResource = fopen($zipFile, "w");
// Get The Zip File From Server
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FILE, $zipResource);
$page = curl_exec($ch);
if(!$page) {
echo "Error :- ".curl_error($ch);
}
curl_close($ch);

cURL will get the Zip archive file from url mentioned in the variable $url. The $zipFile variable contain the local path of the file were we’re going to save the Zip archive file.

Extract (Unzip)

For extracting as we mentioned before, we will use the PHP Zip Archive Extension.
We’ll make the class variable, open the Zip archive file and extract it :

/* Open the Zip file */
$zip = new ZipArchive;
$extractPath = "path_to_extract";
if($zip->open($zipFile) != "true"){
echo "Error :- Unable to open the Zip File";
}
/* Extract Zip File */
$zip->extractTo($extractPath);
$zip->close();

The extract path should be mentioned in the $extractPath variable. If any of the files exists, it will be overwritten or merged.


问:
Redirect url to html file with appended parameter
I asked this question on serverfault.com, but I did not get full answer.

I need to redirect requested url to a html file on the file system. I already know the answer to this:

```<code>location /this/is/some/url {
    index file.html;
    alias /path/to/the/;
}
</code>```

The location of file.html on the file system is /path/to/the/file.html.

However, I also need to append an empty parameter to the end of the url /this/is/some/url. So it should look like this /this/is/some/url?_escaped_fragment_=.

I tried various examples with rewrite but it did not help because I don't use correctly.

答:
You need to make a redirect unless the parameter is present. Because it is an empty parameter, it may be simplest to use a regular expression on $request_uri.

```<code>location /this/is/some/url {
    index file.html;
    alias /path/to/the;

    if ($request_uri !~ [?].*\b_escaped_fragment_=) {
        return 302 $uri?_escaped_fragment_=&$args;
    }
}
</code>```

The example above assumes that there may be other parameters present, hence the trailing &.

Body:
I asked this question on serverfault.com, but I did not get full answer.

I need to redirect requested url to a html file on the file system. I already know the answer to this:

location /this/is/some/url {
    index file.html;
    alias /path/to/the/;
}

The location of file.html on the file system is /path/to/the/file.html.

However, I also need to append an empty parameter to the end of the url /this/is/some/url. So it should look like this /this/is/some/url?_escaped_fragment_=.

I tried various examples with rewrite but it did not help because I don't use correctly.

Body:
You need to make a redirect unless the parameter is present. Because it is an empty parameter, it may be simplest to use a regular expression on $request_uri.

location /this/is/some/url {
    index file.html;
    alias /path/to/the;

    if ($request_uri !~ [?].*\b_escaped_fragment_=) {
        return 302 $uri?_escaped_fragment_=&$args;
    }
}

The example above assumes that there may be other parameters present, hence the trailing &.


问:
Programmatically change log level in Log4j2
I'm interested in programmatically changing the log level in Log4j2. I tried looking at their configuration documentation but that didn't seem to have anything. I also tried looking in the package: org.apache.logging.log4j.core.config, but nothing in there looked helpful either.

答:
One un-usual way i found to do is to create two separate file with different logging level.

For example. log4j2.xml and log4j-debug.xml
Now change the configuration from this files.

Sample Code:

```<code>ConfigurationFactory configFactory = XmlConfigurationFactory.getInstance();
            ConfigurationFactory.setConfigurationFactory(configFactory);
            LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            InputStream inputStream = classloader.getResourceAsStream(logFileName);
            ConfigurationSource configurationSource = new ConfigurationSource(inputStream);

            ctx.start(configFactory.getConfiguration(ctx, configurationSource));
</code>```

Body:
One un-usual way i found to do is to create two separate file with different logging level.

For example. log4j2.xml and log4j-debug.xml
Now change the configuration from this files.

Sample Code:

ConfigurationFactory configFactory = XmlConfigurationFactory.getInstance();
            ConfigurationFactory.setConfigurationFactory(configFactory);
            LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            InputStream inputStream = classloader.getResourceAsStream(logFileName);
            ConfigurationSource configurationSource = new ConfigurationSource(inputStream);

            ctx.start(configFactory.getConfiguration(ctx, configurationSource));


问:
How to stop PyCharm from closing networked folders
I've been testing out PyCharm but ran into a crazy little feature and or bug and cannot figure out how to solve it.

I've created a project on a network, and created a project locally and added a network folder to the project both are resulting in the same bizarre behavior.

I can open files, navigate the project tree and everything is fine inside of PyCharm. But once I switch focus to another window and then come back to PyCharm, it will automatically close the entire project tree back to the root and close any files I have had open.

This is certainly making PyCharm completely unusable. I've been searching most of the morning to find out how to stop this but haven't even come across any other similar problems.

To test, I made a sample Python directory on the network, filled it with a few folders to simulate modules and added init.py files to them all. Then created a PyCharm project in the folder. It will exhibit this behavior and I can't figure out how to stop it from closing everything.  What's going on?

This is Windows Community PyCharm 2017.2.1 Version. A picture would just be everything open and then everything closed and the tree view, since it closes everything when it regains focus. I'm not sure how I'd best take a picture of that.

答:
There is an open bug filed in PyCharm for this issue which is yet to be fixed : https://youtrack.jetbrains.com/issue/IDEA-171352

Description of the bug mentions :

I didn't observe the problem with PyCharm 2016.3.3.

PY-171.3780.115, JRE 1.8.0_112-release-736-b13x64 JetBrains s.r.o, OS
  Windows 10(amd64) v10.0 , screens 2560x1440, 1920x1080, 1080x1920

Apparently the issue is in later releases of PyCharm