问:
Sort an array of objects in Angular2
I have problems with sorting an array of object in Angular2.

The object looks like:

```<code>[
  {
    "name": "t10",
    "ts": 1476778297100,
    "value": "32.339264",
    "xid": "DP_049908"
  },
  {
    "name": "t17",
    "ts": 1476778341100,
    "value": "true",
    "xid": "DP_693259"
  },
  {
    "name": "t16",
    "ts": 1476778341100,
    "value": "true",
    "xid": "DP_891890"
  }
]
</code>```

And is being stored inside the values variable.

All I want is to make the *ngFor loop sort it by the name property.

```<code><table *ngIf="values.length">
    <tr *ngFor="let elem of values">
      <td>{{ elem.name }}</td>
      <td>{{ elem.ts }}</td>
      <td>{{ elem.value }}</td>
    </tr>
</table>
</code>```

Tried to do it with pipes, but failed miserably.
Any help appreciated.

Plunker link: https://plnkr.co/edit/e9laTBnqJKb8VzhHEBmn?p=preview

Edit

My pipe:

```<code>import {Component, Inject, OnInit, Pipe, PipeTransform} from '@angular/core';

@Component({
  selector: 'watchlist',
  templateUrl: './watchlist.component.html',
  styleUrls: ['./watchlist.component.css'],
  pipes: [ ArraySortPipe ]
})
@Pipe({
  name: "sort"
})

export class ArraySortPipe implements PipeTransform {
  transform(array: Array<string>, args: string): Array<string> {
    array.sort((a: any, b: any) => {
      if (a < b) {
        return -1;
      } else if (a > b) {
        return 1;
      } else {
        return 0;
      }
    });
    return array;
  }
}
</code>```

And just put the pipe name into html file:

```<code><tr *ngFor="let elem of values | sort">
</code>```

答:
This is adaptable to any such usecase.

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'sortBy'
})
export class SortByPipe implements PipeTransform {
  transform(arr: Array<any>, prop: any, reverse: boolean = false): any {
    if (arr === undefined) return
    const m = reverse ? -1 : 1
    return arr.sort((a: any, b: any): number => {
      const x = a[prop]
      const y = b[prop]
      return (x === y) ? 0 : (x < y) ? -1*m : 1*m
    })
  }
}
</code>```

Usage:-

UPDATE

Refer Bo's answer as filtering and sorting in pipes is not recommended.

Title: Sort an array of objects in Angular2

Body:
I have problems with sorting an array of object in Angular2.

The object looks like:

[
  {
    "name": "t10",
    "ts": 1476778297100,
    "value": "32.339264",
    "xid": "DP_049908"
  },
  {
    "name": "t17",
    "ts": 1476778341100,
    "value": "true",
    "xid": "DP_693259"
  },
  {
    "name": "t16",
    "ts": 1476778341100,
    "value": "true",
    "xid": "DP_891890"
  }
]

And is being stored inside the values variable.

All I want is to make the *ngFor loop sort it by the name property.

      {{ elem.name }}
      {{ elem.ts }}
      {{ elem.value }}

Tried to do it with pipes, but failed miserably.
Any help appreciated.

Plunker link: https://plnkr.co/edit/e9laTBnqJKb8VzhHEBmn?p=preview

Edit

My pipe:

import {Component, Inject, OnInit, Pipe, PipeTransform} from '@angular/core';

@Component({
  selector: 'watchlist',
  templateUrl: './watchlist.component.html',
  styleUrls: ['./watchlist.component.css'],
  pipes: [ ArraySortPipe ]
})
@Pipe({
  name: "sort"
})

export class ArraySortPipe implements PipeTransform {
  transform(array: Array<string>, args: string): Array<string> {
    array.sort((a: any, b: any) => {
      if (a  b) {
        return 1;
      } else {
        return 0;
      }
    });
    return array;
  }
}

And just put the pipe name into html file:

Body:
This is adaptable to any such usecase.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'sortBy'
})
export class SortByPipe implements PipeTransform {
  transform(arr: Array<any>, prop: any, reverse: boolean = false): any {
    if (arr === undefined) return
    const m = reverse ? -1 : 1
    return arr.sort((a: any, b: any): number => {
      const x = a[prop]
      const y = b[prop]
      return (x === y) ? 0 : (x < y) ? -1*m : 1*m
    })
  }
}

Usage:-

<div *ngFor="let item of list | sortBy: 'isDir': true">

UPDATE

Refer Bo's answer as filtering and sorting in pipes is not recommended.


来源: stackexchange

问:
MYSQL Stored Procedure only updates on record
MYSQL Stored Procedure only updates one record when it should update all the ids in the WHERE id IN clause. When I run the SELECT and UPDATE outside of the stored procedure it works fine. Any suggestions?

```<code>DELIMITER $$
CREATE PROCEDURE update_ids(IN source int(10),IN target int(10))
BEGIN
    DECLARE idList varchar(5000) DEFAULT NULL;
    SET idList = (SELECT GROUP_CONCAT(id SEPARATOR ', ') FROM myTable ii WHERE ii.generic_id = source);
    UPDATE myTable i SET i.generic_id = target WHERE i.id IN (idList);

END$$
DELIMITER ;
</code>```

Then I call it by -->

```<code>CALL update_generic_ids(63, 1258);
</code>```

Update : 1 row effected.

Thanks in advance,

答:
Actually, as per my comments, I think is may be the answer..

There's a world of difference between these two queries:

```<code>UPDATE a SET b = c WHERE d IN ('1,2,3,4')

UPDATE a SET b = c WHERE d IN (1,2,3,4)
</code>```

I'd recommend you amend your procedure so you're not storing your list of ids in a string variable. Actually you shouldn't need to store anything, just put the list generated by the select into the update:

```<code>    UPDATE myTable i SET i.generic_id = target
    WHERE i.id IN
       (SELECT id SEPARATOR FROM myTable ii WHERE ii.generic_id = source);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
MYSQL Stored Procedure only updates one record when it should update all the ids in the WHERE id IN clause. When I run the SELECT and UPDATE outside of the stored procedure it works fine. Any suggestions?

DELIMITER $$
CREATE PROCEDURE update_ids(IN source int(10),IN target int(10))
BEGIN
    DECLARE idList varchar(5000) DEFAULT NULL;
    SET idList = (SELECT GROUP_CONCAT(id SEPARATOR ', ') FROM myTable ii WHERE ii.generic_id = source);
    UPDATE myTable i SET i.generic_id = target WHERE i.id IN (idList);

END$$
DELIMITER ;

Then I call it by -->

CALL update_generic_ids(63, 1258);

Update : 1 row effected.

Thanks in advance,

Body:
Actually, as per my comments, I think is may be the answer..

There's a world of difference between these two queries:

UPDATE a SET b = c WHERE d IN ('1,2,3,4')

UPDATE a SET b = c WHERE d IN (1,2,3,4)

I'd recommend you amend your procedure so you're not storing your list of ids in a string variable. Actually you shouldn't need to store anything, just put the list generated by the select into the update:

    UPDATE myTable i SET i.generic_id = target
    WHERE i.id IN
       (SELECT id SEPARATOR FROM myTable ii WHERE ii.generic_id = source);


问:
Choose Browser while clicking url in UITextView
I have a URL link in my UITextView. And in my iPhone, there are both safari & chrome apps. Whenever I click on the URL link, I want to list both safari & Chrome (and all other browsers in the phone) in a pop up view so that the user can choose which browser they want to open the url. Now it is always opening safari as it is the default browser in my phone. Is there any way I can choose the browser to open the URL? I know there is this delegate

```<code>func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        // Got the url here. how can i force this url to open in chrome
        return true
    }
</code>```

but how can i force this url to open in chrome or any other browser? And how can I list all available browsers in a view?

答:
Currently I can't find any APIs for listing all browsers.

Instead You can use canOpenURL: method to manually check whether the specific app is installed or not.

```<code>- (BOOL)isSafariInstalled {
    return [[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"http://google.com"]];
}

- (BOOL)isChromeInstalled {
    return [[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"googlechrome://"]];
}

- (BOOL)isOperaInstalled {
    return [[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"opera-http://google.com"]];
}
</code>```

For more about Chrome - Check Docs

Body:
I have a URL link in my UITextView. And in my iPhone, there are both safari & chrome apps. Whenever I click on the URL link, I want to list both safari & Chrome (and all other browsers in the phone) in a pop up view so that the user can choose which browser they want to open the url. Now it is always opening safari as it is the default browser in my phone. Is there any way I can choose the browser to open the URL? I know there is this delegate

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        // Got the url here. how can i force this url to open in chrome
        return true
    }

but how can i force this url to open in chrome or any other browser? And how can I list all available browsers in a view?

Body:
Currently I can't find any APIs for listing all browsers.

Instead You can use canOpenURL: method to manually check whether the specific app is installed or not.

- (BOOL)isSafariInstalled {
    return [[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"http://google.com"]];
}

- (BOOL)isChromeInstalled {
    return [[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"googlechrome://"]];
}

- (BOOL)isOperaInstalled {
    return [[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"opera-http://google.com"]];
}

For more about Chrome - Check Docs


问:
Delete batch operation in Azure Storage
I have been trying to implement a DAO method for delete operation for Azure Storage entities. Delete using TableOperation was ok.

```<code>TableOperation deleteEntity = TableOperation.delete(entity);
</code>```

But when I tried it using Batch Operation, It was not supported.

Any suggestions to overcome this issue is highly appreciated.

答:
```<code>public void deleteLocationsForDevice(String id) {
    logger.info("Going to delete location data for Device [{}]", id);

    // Create a filter condition where the partition key is deviceId.
    String partitionFilter = TableQuery.generateFilterCondition(
            PARTITION_KEY,
            TableQuery.QueryComparisons.EQUAL,
            id);

    // Specify a partition query, using  partition key filter.
    TableQuery<AzureLocationData> partitionQuery =
            TableQuery.from(AzureLocationData.class)
                    .where(partitionFilter);

    if (partitionQuery != null) {
        for (AzureLocationData entity : cloudTable.execute(partitionQuery)) {

            TableOperation deleteEntity = TableOperation.delete(entity);
            try {
                cloudTable.execute(deleteEntity);
                logger.info("Successfully deleted location records with : " + entity.getPartitionKey());
            } catch (StorageException e) {
                e.printStackTrace();
            }

        }

    } else {
        logger.debug("No records to delete!");
    }

    //  throw new UnsupportedOperationException("AzureIotLocationDataDao Delete Operation not supported");
}
</code>```

Title: Delete batch operation in Azure Storage

Body:
I have been trying to implement a DAO method for delete operation for Azure Storage entities. Delete using TableOperation was ok.

TableOperation deleteEntity = TableOperation.delete(entity);

But when I tried it using Batch Operation, It was not supported.

Any suggestions to overcome this issue is highly appreciated.


问:
fluentd filter regex pattern gives an invalid strptime format error
I am trying to use the regex filter to parse my log
My regex expression and sample string are as follows
Regex:

```<code>/^(?<logtime>[^\|]*)\S +(?<cpu-usr>\S+) +(?<cpu-sys>\S+) +(?<cpu-idl>\S+) +(?<cpu-wai>\S+) +(?<cpu-hiq>\S+) +(?<cpu-siq>[^|]+)\S +(?<mem-used>\S+) +(?<mem-buff>\S+) +(?<mem-cach>\S+) +(?<mem-free>\S+)/
</code>```

Sample string:

```<code>07-07 17:18:12|  0   0 100   0   0   0| 197M 48.9M  182M  546M
</code>```

So I have written the following filter into my fluent.conf file

```<code>#filter dstat log into fields.
#----system---- ----total-cpu-usage---- ------memory-usage-----
#  date/time   |usr sys idl wai hiq siq| used  buff  cach  free
<filter input.dstat>
  @type parser
  format /^(?<logtime>[^\|]*)\S +(?<cpu-usr>\S+) +(?<cpu-sys>\S+) +(?<cpu-idl>\S+) +(?<cpu-wai>\S+) +(?<cpu-hiq>\S+) +(?<cpu-siq>[^|]+)\S +(?<mem-used>\S+) +(?<mem-buff>\S+) +(?<mem-cach>\S+) +(?<mem-free>\S+)/
  time_format %d-%m %H:%M:%S
  time_key logtime
  keep_time_key true
  key_name log
</filter>
</code>```

However, I get the following error for this filter.

fluentd_1        | 2017-07-07 05:42:36 +0000 [warn]: invalid time format: value = 07-0, error_class = ArgumentError, error = invalid strptime format - `%d-%m %H:%M:%S'

I have already checked the regex and time format using http://fluentular.herokuapp.com/ and it seems to be ok according to that. How do I proceed with this? My current assumption is that the error is due to %Y or year being missing from the time format. However my log does not contain the year information.

答:
The problem was that I used '-' in the names instead of '_'
After replacing them, it works fine.</p>

Body:
I am trying to use the regex filter to parse my log
My regex expression and sample string are as follows
Regex:

/^(?<logtime>[^\|]*)\S +(?<cpu-usr>\S+) +(?<cpu-sys>\S+) +(?<cpu-idl>\S+) +(?<cpu-wai>\S+) +(?<cpu-hiq>\S+) +(?<cpu-siq>[^|]+)\S +(?<mem-used>\S+) +(?<mem-buff>\S+) +(?<mem-cach>\S+) +(?<mem-free>\S+)/

Sample string:

07-07 17:18:12|  0   0 100   0   0   0| 197M 48.9M  182M  546M

So I have written the following filter into my fluent.conf file

#filter dstat log into fields.
#----system---- ----total-cpu-usage---- ------memory-usage-----
#  date/time   |usr sys idl wai hiq siq| used  buff  cach  free
<filter input.dstat>
  @type parser
  format /^(?<logtime>[^\|]*)\S +(?<cpu-usr>\S+) +(?<cpu-sys>\S+) +(?<cpu-idl>\S+) +(?<cpu-wai>\S+) +(?<cpu-hiq>\S+) +(?<cpu-siq>[^|]+)\S +(?<mem-used>\S+) +(?<mem-buff>\S+) +(?<mem-cach>\S+) +(?<mem-free>\S+)/
  time_format %d-%m %H:%M:%S
  time_key logtime
  keep_time_key true
  key_name log
</filter>

However, I get the following error for this filter.

fluentd_1        | 2017-07-07 05:42:36 +0000 [warn]: invalid time format: value = 07-0, error_class = ArgumentError, error = invalid strptime format - `%d-%m %H:%M:%S'

I have already checked the regex and time format using http://fluentular.herokuapp.com/ and it seems to be ok according to that. How do I proceed with this? My current assumption is that the error is due to %Y or year being missing from the time format. However my log does not contain the year information.


问:
SML Match Redundant Error
Im writing some code for an insertion sort in SML. Here it is.

```<code>fun compare(x:real, y:real, F) = F(x, y);
fun isEqual(x:real, y:real) = ((x <= y) andalso (x >= y));

fun rinsert(x: real, L: real list, F) = [x]
    |rinsert(x, (y::ys), F) =
    if isEqual(x, y) then rinsert (x, ys, F)
    else if compare(x, y, F) then x::y::ys
            else y::(rinsert (x, ys, F));

fun rinsort(L : real list, F) = []
    |rinsort(x::xs, F) = rinsert(x, (rinsort (xs, F), F);
</code>```

For whatever reason i keep coming up with this error

```<code>- val compare = fn : real * real * (real * real -> 'a) -> 'a
val isEqual = fn : real * real -> bool
stdIn:4.6-8.42 Error: match redundant
          (x,L,F) => ...
    -->   (x,y :: ys,F) => ...
</code>```

I understand what it's saying, that I've got a repetitive line somewhere, but I'm not sure where the problem could be.

答:
The first line of rinsert has plain variables for each argument, so matches everything. Consequently, the second case is never reached. Same for rinsort.

To fix this, you'll need to replace the L parameter in both with the pattern [] for the empty list.

Title: SML Match Redundant Error

Body:
Im writing some code for an insertion sort in SML. Here it is.

fun compare(x:real, y:real, F) = F(x, y);
fun isEqual(x:real, y:real) = ((x <= y) andalso (x >= y));

fun rinsert(x: real, L: real list, F) = [x]
    |rinsert(x, (y::ys), F) =
    if isEqual(x, y) then rinsert (x, ys, F)
    else if compare(x, y, F) then x::y::ys
            else y::(rinsert (x, ys, F));

fun rinsort(L : real list, F) = []
    |rinsort(x::xs, F) = rinsert(x, (rinsort (xs, F), F);

For whatever reason i keep coming up with this error

- val compare = fn : real * real * (real * real -> 'a) -> 'a
val isEqual = fn : real * real -> bool
stdIn:4.6-8.42 Error: match redundant
          (x,L,F) => ...
    -->   (x,y :: ys,F) => ...

I understand what it's saying, that I've got a repetitive line somewhere, but I'm not sure where the problem could be.


问:
Tensorflow GPU cuDNn: How do I load cuDDN libraries?
I am trying to use tensorflow with gpu and installed CUDA 8.0 toolkit and cuDNn v5.1 libraries as described in nvidia website. But when I try to import tensorflow as module in python3.5, it does not load cuDNn libraries (outputs nothing, just loads tensorflow module). And I do not observe speed in processing (same speed I obtained when I use CPU) with GPU.</p>

答:
Fresh install is the key but there are some important points:
1. Install CUDA 8.0 toolkit
2. Install cuDNn 5.1 version (not 6.0)
3. Install from source(bazel) and configure to use ensorflow with CUDA

Above steps worked for me! Hope it helps anyone.


问:
How to force user to turn on gps to use app in ionic2
I want to force users to turn on GPS in ionic2 app for this I am using dpa99c/cordova-plugin-request-location-accuracy

I have installed this plugin but why it is saying plugin not installed.

this my function what I am trying to do if app loads this onLocate function will trigger and check whether GPS is on or Not if not on this will prompt to turn on GPS see this image

but if the user tapped on cancel button I want to re-run this function and prompt again to ask the user to turn on GPS as shown in above image until user tap on ok to start GPS then I want to reload window to get user location using GPS.

where I am wrong

```<code>onLoacte(){

 this.locationAccuracy.canRequest().then((canRequest: boolean) => {

      if(canRequest) {
        // the accuracy option will be ignored by iOS
          this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(
          () => console.log('Request successful'),
          error =>  location.reload(),
        );
      }

    });

}
</code>```

答:
You can call that function in a loop may be, till you get the locationAccuracy.request successfully.

Also give the users a button to stop looking for location or exit the app in doing so.

Body:
I want to force users to turn on GPS in ionic2 app for this I am using dpa99c/cordova-plugin-request-location-accuracy

I have installed this plugin but why it is saying plugin not installed.

this my function what I am trying to do if app loads this onLocate function will trigger and check whether GPS is on or Not if not on this will prompt to turn on GPS see this image

but if the user tapped on cancel button I want to re-run this function and prompt again to ask the user to turn on GPS as shown in above image until user tap on ok to start GPS then I want to reload window to get user location using GPS.

where I am wrong

onLoacte(){

 this.locationAccuracy.canRequest().then((canRequest: boolean) => {

      if(canRequest) {
        // the accuracy option will be ignored by iOS
          this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(
          () => console.log('Request successful'),
          error =>  location.reload(),
        );
      }

    });

}


问:
Multiple databases (mongodb[mongoengine] and sql ) with django 1.8
I am using mongoengine with Django and my project needs to connect to one instances of MongoDB while another with sql .How my databse section of setting.py should be like ?</p>

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'admin_db',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'localhost',
    },

}

from mongoengine import connect
connect(
db='pom',
username='admin',
password='root',
host='mongodb://admin:root@localhost'
)
</code>```

答:
You could add multiple databases for your app in your settings.py like,

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'admin_db',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'localhost',
    },

    'your_desired_db_name' : {
        'ENGINE' : 'django_mongodb_engine',
        'NAME' : 'db_name'
}
</code>```

For integration with mongodb, you may need to look up,

Django-nonrel

Django-MongoEngine

Also, you may need to look up Django documentation for multiple databases

Body:
I am using mongoengine with Django and my project needs to connect to one instances of MongoDB while another with sql .How my databse section of setting.py should be like ?

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'admin_db',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'localhost',
    },

}

from mongoengine import connect
connect(
db='pom',
username='admin',
password='root',
host='mongodb://admin:root@localhost'
)

Body:
You could add multiple databases for your app in your settings.py like,

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'admin_db',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'localhost',
    },

    'your_desired_db_name' : {
        'ENGINE' : 'django_mongodb_engine',
        'NAME' : 'db_name'
}

For integration with mongodb, you may need to look up,

Django-nonrel

Django-MongoEngine

Also, you may need to look up Django documentation for multiple databases


问:
apply normalisation on groupBy data in Pandas DataFrame
DataFrame columns:

```<code>['PercentSalaryHike', 'Attrition', 'EmployeeCountFraction']
</code>```

After Grouping by first two columns:
EmployeeCount shows the fraction of people whose attrition is 'yes' and rest 'No' for that particular PercentSalaryHike

After Resetting index, DataFrame looks like:

What I want exactly is to apply normalisation to simplify DataFrame.
Should look like:

```<code>PercentSalaryHike   Attrition-Yes    Attrition-No

11                    0.195238       0.804762
12                    0.166667       0.833333
13                    0.837321       0.163351
..
..
..
</code>```

The sample I have given applies groupBy on 2 fields. I want a general solution by which data grouped by n number of fields is normalised in such manner.

答:
I think you need unstack for reshape data, then add_prefix,  reset_index and last rename_axis:

```<code>df = df['EmployeeCountFraction'].unstack()
                                .add_prefix('Attrition-')
                                .reset_index()
                                .rename_axis(None, axis=1)
print (df)
   PercentSalaryHike  Attrition-No  Attrition-Yes
0                 11      0.804762       0.195238
1                 12      0.833333       0.166667
2                 13      0.837321       0.163351
</code>```

Body:
DataFrame columns:

['PercentSalaryHike', 'Attrition', 'EmployeeCountFraction']

After Grouping by first two columns:
EmployeeCount shows the fraction of people whose attrition is 'yes' and rest 'No' for that particular PercentSalaryHike

After Resetting index, DataFrame looks like:

What I want exactly is to apply normalisation to simplify DataFrame.
Should look like:

PercentSalaryHike   Attrition-Yes    Attrition-No

11                    0.195238       0.804762
12                    0.166667       0.833333
13                    0.837321       0.163351
..
..
..

The sample I have given applies groupBy on 2 fields. I want a general solution by which data grouped by n number of fields is normalised in such manner.

Body:
I think you need unstack for reshape data, then add_prefix,  reset_index and last rename_axis:

df = df['EmployeeCountFraction'].unstack()
                                .add_prefix('Attrition-')
                                .reset_index()
                                .rename_axis(None, axis=1)
print (df)
   PercentSalaryHike  Attrition-No  Attrition-Yes
0                 11      0.804762       0.195238
1                 12      0.833333       0.166667
2                 13      0.837321       0.163351


问:
What causes the "control.registerOnChange is not a function" error
I have a form using the reactive form approach. The form is created as follow in my pug:

```<code>form([formGroup]='form', novalidate='', (ngSubmit)='postSurvey(form.value, form.valid)')
</code>```

Everything works fine except when I try to change the form (which is a FormArray) in the javascript part. I get the following error:

```<code>EXCEPTION: Error in http://localhost:8080/app/components/fillForm.template.html:0:326 caused by: control.registerOnChange is not a function
core.umd.js:3497 TypeError: control.registerOnChange is not a function
    at setUpControl (http://localhost:8080/node_modules/@angular/forms/bundles/forms.umd.js:1634:17)
    at eval (http://localhost:8080/node_modules/@angular/forms/bundles/forms.umd.js:4752:25)
    at Array.forEach (native)
    at FormGroupDirective._updateDomValue (http://localhost:8080/node_modules/@angular/forms/bundles/forms.umd.js:4747:29)
    at FormGroupDirective.ngOnChanges (http://localhost:8080/node_modules/@angular/forms/bundles/forms.umd.js:4616:22)
    at Wrapper_FormGroupDirective.ngDoCheck (/ReactiveFormsModule/FormGroupDirective/wrapper.ngfactory.js:30:18)
    at View_FillFormComponent2.detectChangesInternal (/AppModule/FillFormComponent/component.ngfactory.js:275:32)
    at View_FillFormComponent2.AppView.detectChanges (http://localhost:8080/node_modules/@angular/core/bundles/core.umd.js:12592:18)
    at View_FillFormComponent2.DebugAppView.detectChanges (http://localhost:8080/node_modules/@angular/core/bundles/core.umd.js:12739:48)
    at ViewContainer.detectChangesInNestedViews (http://localhost:8080/node_modules/@angular/core/bundles/core.umd.js:12850:41)
    at CompiledTemplate.proxyViewClass.View_FillFormComponent0.detectChangesInternal (/AppModule/FillFormComponent/component.ngfactory.js:64:14)
    at CompiledTemplate.proxyViewClass.AppView.detectChanges (http://localhost:8080/node_modules/@angular/core/bundles/core.umd.js:12592:18)
    at CompiledTemplate.proxyViewClass.DebugAppView.detectChanges (http://localhost:8080/node_modules/@angular/core/bundles/core.umd.js:12739:48)
    at CompiledTemplate.proxyViewClass.AppView.internalDetectChanges (http://localhost:8080/node_modules/@angular/core/bundles/core.umd.js:12577:22)
    at CompiledTemplate.proxyViewClass.View_FillFormComponent_Host0.detectChangesInternal (/AppModule/FillFormComponent/host.ngfactory.js:29:19)
</code>```

My code to change the form is quite complex and I can't simplify it or reproduce it in a plunker. More than finding directly the solution (it's too difficult with so little details), I would like to understand what this error means? And what might cause this error.

I have figured out that the error occurs at [formGroup]='form' in my HTML.

Any suggestion will help.

Update I have filed an issue on angular github here and have proposed a fix here The plunker to reproduce the issue is here

答:
Maybe you have moved a control element outside the group in the template.

OK:

```<code><div formGroupName="passwordForm">
     Password: <input type="password" formControlName="password">
     Confirm: <input type="password" formControlName="confirmPassword">
</div>
</code>```

Not OK:

```<code>Password: <input type="password" formControlName="password">
<div formGroupName="passwordForm">
     Confirm: <input type="password" formControlName="confirmPassword">
</div>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a form using the reactive form approach. The form is created as follow in my pug:

form([formGroup]='form', novalidate='', (ngSubmit)='postSurvey(form.value, form.valid)')

Everything works fine except when I try to change the form (which is a FormArray) in the javascript part. I get the following error:

EXCEPTION: Error in http://localhost:8080/app/components/fillForm.template.html:0:326 caused by: control.registerOnChange is not a function
core.umd.js:3497 TypeError: control.registerOnChange is not a function
    at setUpControl (http://localhost:8080/node_modules/@angular/forms/bundles/forms.umd.js:1634:17)
    at eval (http://localhost:8080/node_modules/@angular/forms/bundles/forms.umd.js:4752:25)
    at Array.forEach (native)
    at FormGroupDirective._updateDomValue (http://localhost:8080/node_modules/@angular/forms/bundles/forms.umd.js:4747:29)
    at FormGroupDirective.ngOnChanges (http://localhost:8080/node_modules/@angular/forms/bundles/forms.umd.js:4616:22)
    at Wrapper_FormGroupDirective.ngDoCheck (/ReactiveFormsModule/FormGroupDirective/wrapper.ngfactory.js:30:18)
    at View_FillFormComponent2.detectChangesInternal (/AppModule/FillFormComponent/component.ngfactory.js:275:32)
    at View_FillFormComponent2.AppView.detectChanges (http://localhost:8080/node_modules/@angular/core/bundles/core.umd.js:12592:18)
    at View_FillFormComponent2.DebugAppView.detectChanges (http://localhost:8080/node_modules/@angular/core/bundles/core.umd.js:12739:48)
    at ViewContainer.detectChangesInNestedViews (http://localhost:8080/node_modules/@angular/core/bundles/core.umd.js:12850:41)
    at CompiledTemplate.proxyViewClass.View_FillFormComponent0.detectChangesInternal (/AppModule/FillFormComponent/component.ngfactory.js:64:14)
    at CompiledTemplate.proxyViewClass.AppView.detectChanges (http://localhost:8080/node_modules/@angular/core/bundles/core.umd.js:12592:18)
    at CompiledTemplate.proxyViewClass.DebugAppView.detectChanges (http://localhost:8080/node_modules/@angular/core/bundles/core.umd.js:12739:48)
    at CompiledTemplate.proxyViewClass.AppView.internalDetectChanges (http://localhost:8080/node_modules/@angular/core/bundles/core.umd.js:12577:22)
    at CompiledTemplate.proxyViewClass.View_FillFormComponent_Host0.detectChangesInternal (/AppModule/FillFormComponent/host.ngfactory.js:29:19)

My code to change the form is quite complex and I can't simplify it or reproduce it in a plunker. More than finding directly the solution (it's too difficult with so little details), I would like to understand what this error means? And what might cause this error.

I have figured out that the error occurs at [formGroup]='form' in my HTML.

Any suggestion will help.

Update I have filed an issue on angular github here and have proposed a fix here The plunker to reproduce the issue is here

Body:
Maybe you have moved a control element outside the group in the template.

OK:

<div formGroupName="passwordForm">
     Password: <input type="password" formControlName="password">
     Confirm: <input type="password" formControlName="confirmPassword">
</div>

Not OK:

Password: <input type="password" formControlName="password">
<div formGroupName="passwordForm">
     Confirm: <input type="password" formControlName="confirmPassword">
</div>


问:
Find a specified generic DbSet in a DbContext dynamically when I have an entity
I have following classes and DbContext:

```<code>public class Order : BaseEntity
{
    public Number {get; set;}
}
public class Product : BaseEntity;
{
    public Name {get; set;}
}

public class Context : DbContext
{
    ....
    public DbSet<Order> Orders { set; get; }
    public DbSet<Product> Products { set; get; }
    ....
}
</code>```

I have a list of objects that want to add to my context, too, but I don't know how can I find appropriate generic DbSet according each entity type dynamically.

```<code>IList<BaseEntity> list = new List<BaseEntity>();
Order o1 = new Order();
o1.Numner = "Ord1";
list.Add(o1);

Product p1 = new Product();
p1.Name = "Pencil";
list.Add(p1);

Context cntx = new Context();
foreach (BaseEntity entity in list)
{
      cntx.Set<?>().Add(entity);
}
</code>```

How can I do that?

答:
In addition to Pablo's answer, you can add a class to your project:

```<code>namespace System.Data.Entity
{
    public static class EntityFrameworkExtensions
    {
        public static IEnumerable<object> AsEnumerable(this DbSet set)
        {
            foreach (var entity in set)
            {
                yield return entity;
            }
        }
    }
}
</code>```

This class adds an extention method AsEnumerable to DbSet instance.

When you want to use it, for example to Count or filter a row:

```<code>var someDbSet = this.Set(typeof(SomeEntity));
var count = (from a in someDbSet.AsEnumerable() select a).Count();
</code>```

Body:
I have following classes and DbContext:

public class Order : BaseEntity
{
    public Number {get; set;}
}
public class Product : BaseEntity;
{
    public Name {get; set;}
}

public class Context : DbContext
{
    ....
    public DbSet<Order> Orders { set; get; }
    public DbSet<Product> Products { set; get; }
    ....
}

I have a list of objects that want to add to my context, too, but I don't know how can I find appropriate generic DbSet according each entity type dynamically.

IList<BaseEntity> list = new List<BaseEntity>();
Order o1 = new Order();
o1.Numner = "Ord1";
list.Add(o1);

Product p1 = new Product();
p1.Name = "Pencil";
list.Add(p1);

Context cntx = new Context();
foreach (BaseEntity entity in list)
{
      cntx.Set<?>().Add(entity);
}

How can I do that?

Body:
In addition to Pablo's answer, you can add a class to your project:

namespace System.Data.Entity
{
    public static class EntityFrameworkExtensions
    {
        public static IEnumerable<object> AsEnumerable(this DbSet set)
        {
            foreach (var entity in set)
            {
                yield return entity;
            }
        }
    }
}

This class adds an extention method AsEnumerable to DbSet instance.

When you want to use it, for example to Count or filter a row:

var someDbSet = this.Set(typeof(SomeEntity));
var count = (from a in someDbSet.AsEnumerable() select a).Count();


问:
Sum of List must be 16
I am stuck in this problem for 2 hours now! My problem in prolog is I am thinking in a declarative way!

So my issue is to make prolog generate a list equal to N!  The size of list is 5.

```<code>somme([],0) :- !.
somme([X|L],S) :- somme(L,S1), S is S1+X.

generateList(L,RES) :- C1 is random(4)+1,
              C2 is random(5)+1,
              C3 is random(6)+1,
              append(L,[C1,C2,C3],RES).

go(L) :- generateList([2,3],L), somme(L,S), S \==16, go(L).
go(L) :- generateList([2,3],L), somme(L,S), S == 16,write(L).
</code>```

We suppose that the 2 first element are 2 and 3.

答:
your program, amended:

```<code>somme([],0).  /* the cut is useless, since [] and [X|L] are distinguished */
somme([X|L],S) :- somme(L,S1), S is S1+X.

generateList(L,RES) :- C1 is random(4)+1,
              C2 is random(5)+1,
              C3 is random(6)+1,
              append(L,[C1,C2,C3],RES).

/* A variable can be assigned only once, then you must backtrack. */
/* So: repeat/0 introduces a backtrack point, going into a "failure driven loop" */
/* until the test succeeds */
go(L) :- repeat, generateList([2,3],L), somme(L,S), S == 16, !.
</code>```

test run

```<code>?- go(L).
L = [2, 3, 2, 4, 5].

?- go(L).
L = [2, 3, 2, 3, 6].
</code>```

Title: Sum of List must be 16

Body:
I am stuck in this problem for 2 hours now! My problem in prolog is I am thinking in a declarative way!

So my issue is to make prolog generate a list equal to N!  The size of list is 5.

somme([],0) :- !.
somme([X|L],S) :- somme(L,S1), S is S1+X.

generateList(L,RES) :- C1 is random(4)+1,
              C2 is random(5)+1,
              C3 is random(6)+1,
              append(L,[C1,C2,C3],RES).

go(L) :- generateList([2,3],L), somme(L,S), S \==16, go(L).
go(L) :- generateList([2,3],L), somme(L,S), S == 16,write(L).

We suppose that the 2 first element are 2 and 3.

Body:
your program, amended:

somme([],0).  /* the cut is useless, since [] and [X|L] are distinguished */
somme([X|L],S) :- somme(L,S1), S is S1+X.

generateList(L,RES) :- C1 is random(4)+1,
              C2 is random(5)+1,
              C3 is random(6)+1,
              append(L,[C1,C2,C3],RES).

/* A variable can be assigned only once, then you must backtrack. */
/* So: repeat/0 introduces a backtrack point, going into a "failure driven loop" */
/* until the test succeeds */
go(L) :- repeat, generateList([2,3],L), somme(L,S), S == 16, !.

test run

?- go(L).
L = [2, 3, 2, 4, 5].

?- go(L).
L = [2, 3, 2, 3, 6].


问:
I make a login page and I want to show user info name Address etc when I successfully login
This is controller code for Login,
This is User Login Controller code where I authenticating user Email ID and password when user login redirected to Home Controller where I want to show user info

```<code>[HttpPost]
[ValidateAntiForgeryToken]

public ActionResult Login(UserLogin login, string ReturnUrl = ""){
         string message = "";
         using (LoginEntities dc = new LoginEntities()){
              var v = dc.Users.Where(a => a.EmailID == login.EmailID).FirstOrDefault();
              var n = dc.Users.Where(a => a.Password == login.Password).FirstOrDefault();
              if (v != null || n != null ){
                   if (string.Compare(Crypto.Hash(login.Password), v.Password) == 0){
                        int timeout = login.RememberME ? 525600 : 20;
                        var ticket = new FormsAuthenticationTicket(login.EmailID,login.RememberME,timeout);
                        string encrypted = FormsAuthentication.Encrypt(ticket);
                        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                        cookie.Expires = DateTime.Now.AddMinutes(timeout);
                        cookie.HttpOnly = true;
                        Response.Cookies.Add(cookie);

                        if (Url.IsLocalUrl(ReturnUrl)){
                            return Redirect(ReturnUrl);
                        }
                        else{
                            return RedirectToAction("Index", "Home");
                        }
                    }
                    else{
                        message = "Invalid Credential Provided";
                    }
                }
                else {
                    message = "Invalid Credential Provided";
                }
            }
            ViewBag.Message = message;
            return View();
            }
</code>```

Home Controller and index action where I redirect when I login,
This is Home Controller Where I redirected After Logging successfully please some one give a code for home controller and index action where i can  Get Id of user That login and and and tell me how to show that in view

```<code>public class HomeController : Controller{
        LoginEntities db = new LoginEntities();
        // GET: Home
        [Authorize]
        public ActionResult Index(){
            if (Session.Contents.Count == 0){
                RedirectToAction("Login", "User");
            }

            return View();
        }
    }
</code>```

答:
Updated my code below, This might or might not work coz its coded here manually  not on  actual VS :P

// /Controller/TestController.cs

```<code>namespace XXXX.Controllers
{
   public class TestController : Controller
   {
        public ActionResult User()
        {
           String UserId = User.Identity.GetUserId().ToString();
           ApplicationDbContext db = new ApplicationDbContext();

            var rs = db.Users.Find(UserId);
            var model = new UserViewModel
            {
                UserName = rs.UserName,
                FirstName = rs.FirstName,
                LastName = rs.LastName,
                Email = rs.Email
             };
             db.Dispose();
             return View(model);
        }
   }
}
</code>```

// /Models/UserViewModel.cs

```<code>namespace XXXX.Models
{
   public class UserViewModel
  {
     public string Id { get; set; }
     public string UserName { get; set; }
     public string Email { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
  }
}
</code>```

// /Views/Test/User.cshtml

```<code>@model XXXX.Models.UsersCreateViewModel

<p>
  @Html.Raw(Model.FirstName)
</p>
</code>```

above is just a sample you can use the info further

Body:
This is controller code for Login,
This is User Login Controller code where I authenticating user Email ID and password when user login redirected to Home Controller where I want to show user info

[HttpPost]
[ValidateAntiForgeryToken]

public ActionResult Login(UserLogin login, string ReturnUrl = ""){
         string message = "";
         using (LoginEntities dc = new LoginEntities()){
              var v = dc.Users.Where(a => a.EmailID == login.EmailID).FirstOrDefault();
              var n = dc.Users.Where(a => a.Password == login.Password).FirstOrDefault();
              if (v != null || n != null ){
                   if (string.Compare(Crypto.Hash(login.Password), v.Password) == 0){
                        int timeout = login.RememberME ? 525600 : 20;
                        var ticket = new FormsAuthenticationTicket(login.EmailID,login.RememberME,timeout);
                        string encrypted = FormsAuthentication.Encrypt(ticket);
                        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                        cookie.Expires = DateTime.Now.AddMinutes(timeout);
                        cookie.HttpOnly = true;
                        Response.Cookies.Add(cookie);

                        if (Url.IsLocalUrl(ReturnUrl)){
                            return Redirect(ReturnUrl);
                        }
                        else{
                            return RedirectToAction("Index", "Home");
                        }
                    }
                    else{
                        message = "Invalid Credential Provided";
                    }
                }
                else {
                    message = "Invalid Credential Provided";
                }
            }
            ViewBag.Message = message;
            return View();
            }

Home Controller and index action where I redirect when I login,
This is Home Controller Where I redirected After Logging successfully please some one give a code for home controller and index action where i can  Get Id of user That login and and and tell me how to show that in view

public class HomeController : Controller{
        LoginEntities db = new LoginEntities();
        // GET: Home
        [Authorize]
        public ActionResult Index(){
            if (Session.Contents.Count == 0){
                RedirectToAction("Login", "User");
            }

            return View();
        }
    }

Body:
Updated my code below, This might or might not work coz its coded here manually  not on  actual VS :P

// /Controller/TestController.cs

namespace XXXX.Controllers
{
   public class TestController : Controller
   {
        public ActionResult User()
        {
           String UserId = User.Identity.GetUserId().ToString();
           ApplicationDbContext db = new ApplicationDbContext();

            var rs = db.Users.Find(UserId);
            var model = new UserViewModel
            {
                UserName = rs.UserName,
                FirstName = rs.FirstName,
                LastName = rs.LastName,
                Email = rs.Email
             };
             db.Dispose();
             return View(model);
        }
   }
}

// /Models/UserViewModel.cs

namespace XXXX.Models
{
   public class UserViewModel
  {
     public string Id { get; set; }
     public string UserName { get; set; }
     public string Email { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
  }
}

// /Views/Test/User.cshtml

@model XXXX.Models.UsersCreateViewModel

<p>
  @Html.Raw(Model.FirstName)
</p>

above is just a sample you can use the info further


问:
adding and deleting form rows with javascript
I created a form where add button adds another row with name, email and age in the form and delete deletes it.  However, jquery code does not work as intended. I am a beginner in jquery to figure out what mistake I have made. I looked through similar questions in Stackoverflow but could'nt figure it out.

$(document).ready(function(){
     var max_fields= 10;
     var wrapper  = $("#commentForm");
     var add_button = $("#addButton");
     var delete_button = $('#deleteButton')

     var x=1;
     add_button.click(function(e){
      e.preventDefault();

      if (x < max_fields){
       x++;
       $(wrapper).append('<input id="bname" name="name" minlength="2" type="text" required/>', '<input id="bemail" name="email" type="email" required/', '<input id="bage" name="age" type="number" required/>' )
      }

     });
      $(wrapper).on("click","#deleteButton", function(e){

       e.preventDefault();$(this).parent('p').remove();
       x--;

      })

     });
      ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body>
    <section class="container">
     <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
     <fieldset>
      <input type="checkbox"/>

      <p>
       <span> Name </span> <br>
       <label for="aname" ></label>
       <input id="bname" name="name" minlength="2" type="text" required/>
      </p>
      <p>
       <span> Email </span> <br>
       <label for="aemail" ></label>
       <input id="bemail" name="email" type="email" required/>
      </p>
      <p>
       <span> Age </span> <br>
       <label for="aage" ></label>
       <input id="bage" name="age" type="number" required/>
      </p>

      <div class="input_fields_wrap">

       <div class="addButton">
        <button  type="button" value="add">Add</button>
       </div>

       <div class="deleteButton">
        <button type="button" value="delete">Delete</button>
       </div>
      </div>

     </fieldset>
     </form>

     </section>

    </body></code>```

Thank you.

答:
You can do it like this</p>

```<code><body>
<section class="container">
    <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
    <fieldset>
        <input type="checkbox"/>
          <div id="rows">
        <P>
            <span> Name </span> </br>
            <label for="aname" ></label>
            <input id="bname" name="name" minlength="2" type="text" required/>
        </p>
        <P>
            <span> Email </span> </br>
            <label for="aemail" ></label>
            <input id="bemail" name="email" type="email" required/>
        </p>
        <p>
            <span> Age </span> </br>
            <label for="aage" ></label>
            <input id="bage" name="age" type="number" required/>
        </p>
        </div>

        <div class="input_fields_wrap">

            <div>
                <button id="addButton"  type="button" value="add">Add</button>
            </div>

            <div>
                <button  id="deleteButton" type="button" value="delete">Delete</button>
            </div>
        </div>

    </fieldset>
    </form>

    </section>

    <script>
    $(document).ready(function(){
    var max_fields= 10;
    var wrapper  = $("#commentForm");
    var add_button = $("#addButton");
    var delete_button = $('#deleteButton');
    var rows  = $("#rows");

    var x=1;
    add_button.click(function(e){
        e.preventDefault();

        if (x < max_fields){
            x++;
            rows.append('<p><input id="bname" name="name" minlength="2" type="text" required/>', '<input id="bemail" name="email" type="email" required/>', '<input id="bage" name="age" type="number" required/></p>' )
        }

    });
        delete_button.click(function(e){

            e.preventDefault();
            $( "#rows p" ).last().remove();
            x--;

        })

    });

    </script>

</body>
</code>```

Body:
I created a form where add button adds another row with name, email and age in the form and delete deletes it.  However, jquery code does not work as intended. I am a beginner in jquery to figure out what mistake I have made. I looked through similar questions in Stackoverflow but could'nt figure it out.

$(document).ready(function(){
     var max_fields= 10;
     var wrapper  = $("#commentForm");
     var add_button = $("#addButton");
     var delete_button = $('#deleteButton')

     var x=1;
     add_button.click(function(e){
      e.preventDefault();

      if (x < max_fields){
       x++;
       $(wrapper).append('<input id="bname" name="name" minlength="2" type="text" required/>', '<input id="bemail" name="email" type="email" required/', '<input id="bage" name="age" type="number" required/>' )
      }

     });
      $(wrapper).on("click","#deleteButton", function(e){

       e.preventDefault();$(this).parent('p').remove();
       x--;

      })

     });

     <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
     <fieldset>
      <input type="checkbox"/>

        Name

       <input id="bname" name="name" minlength="2" type="text" required/>

        Email

       <input id="bemail" name="email" type="email" required/>

        Age

       <input id="bage" name="age" type="number" required/>

        <button  type="button" value="add">Add</button>

        <button type="button" value="delete">Delete</button>

     </fieldset>
     </form>

Thank you.

Body:
You can do it like this

<body>
<section class="container">
    <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
    <fieldset>
        <input type="checkbox"/>
          <div id="rows">
        <P>
            <span> Name </span> </br>
            <label for="aname" ></label>
            <input id="bname" name="name" minlength="2" type="text" required/>
        </p>
        <P>
            <span> Email </span> </br>
            <label for="aemail" ></label>
            <input id="bemail" name="email" type="email" required/>
        </p>
        <p>
            <span> Age </span> </br>
            <label for="aage" ></label>
            <input id="bage" name="age" type="number" required/>
        </p>
        </div>

        <div class="input_fields_wrap">

            <div>
                <button id="addButton"  type="button" value="add">Add</button>
            </div>

            <div>
                <button  id="deleteButton" type="button" value="delete">Delete</button>
            </div>
        </div>

    </fieldset>
    </form>

    </section>

    <script>
    $(document).ready(function(){
    var max_fields= 10;
    var wrapper  = $("#commentForm");
    var add_button = $("#addButton");
    var delete_button = $('#deleteButton');
    var rows  = $("#rows");

    var x=1;
    add_button.click(function(e){
        e.preventDefault();

        if (x < max_fields){
            x++;
            rows.append('<p><input id="bname" name="name" minlength="2" type="text" required/>', '<input id="bemail" name="email" type="email" required/>', '<input id="bage" name="age" type="number" required/></p>' )
        }

    });
        delete_button.click(function(e){

            e.preventDefault();
            $( "#rows p" ).last().remove();
            x--;

        })

    });

    </script>

</body>


问:
In the grid layout , what the difference between the followings
```<code>Width="auto"
Width ="*"
Width ="100*"
</code>```

答:
```<code>Width="auto"
</code>```

Autosizing: Gives child elements the space they need - in case of a grid column, makes the column as wide as the widest contained element.

```<code>Width ="*"
Width = "100*"
</code>```

Proportional sizing or "star sizing": Divide the available space proportionally. For example, in order to divide the available into two columns at 20% and 80% of the grid width, you could use "20*"/"80*" or "2*"/"8*" or even "*"/"4*". "*" is equivalent to "1*".

ContentLicense: CC BY-SA 2.5

Body:
Width="auto"
Width ="*"
Width ="100*"

Body:
Width="auto"

Autosizing: Gives child elements the space they need - in case of a grid column, makes the column as wide as the widest contained element.

Width ="*"
Width = "100*"

Proportional sizing or "star sizing": Divide the available space proportionally. For example, in order to divide the available into two columns at 20% and 80% of the grid width, you could use "20*"/"80*" or "2*"/"8*" or even "*"/"4*". "*" is equivalent to "1*".


问:
Random number generator that returns unique entries in sorted order
I need a generator for many (up to one trillion, 10^12) unique random 64-bit numbers.
The generator needs to return the numbers in sorted order (Long.MIN_VALUE to Long.MAX_VALUE). The problem is that sorting $10^{12}$ numbers is slow. The use case is replicating a test that was run for BBHash (in the paper, 4.5 Indexing a trillion keys).

The straightforward solution is to create a set in memory, using a huge bit set or so
to ensure no duplicates are returned.
But that uses too much memory or I/O.
I'd like to use at most a few MB of internal state.

The generator should use a java.util.Random internally.
It should be as "fair" as possible (have the same statistical distribution as if generated otherwise). I would also like to have a version for 128-bit numbers (2 longs).

What I have so far is code to create a set in memory (Java code):

```<code>public static void main(String... args) {
    for(long x : randomSet(10, 0)) {
        System.out.println(x);
    }
}

static Iterable<Long> randomSet(int size, int seed) {
    Random r = new Random(seed);
    TreeSet<Long> set = new TreeSet<Long>();
    while (set.size() < size) {
        set.add(r.nextLong());
    }
    return set;
}

-8292973307042192125
-7423979211207825555
-6688467811848818630
-4962768465676381896
-2228689144322150137
-1083761183081836303
-279624296851435688
4437113781045784766
6146794652083548235
7105486291024734541
</code>```

The simplest (wrong) solution, which is not random, is to distribute the results evenly.
I don't think a solution along the line of "add a random gap" will work,
because it is slow, and the sum of such gaps, after 10^12, will not land where it should (well, maybe: remember how many numbers are left, then re-calculate the distribution...). I think the following should work, but is complex, and not sure what formulas to use: for each bit level,
recursively, calculating how many 0s / 1s will likely occur
(using the Binomial distribution or the approximation, the normal / Gaussian distribution, somehow).
Stop at some point (say, blocks of 1 million entries or less),
use the code above, for speed.
But maybe there is an elegant solution.
Maybe this is related to the Metropolis–Hastings algorithm, not sure.
I read "An Efficient Algorithm for Sequential Random Sampling",
but I think it is only for small n, and I find it hard to get to a simple algorithm from this.

Java code would be best, but C is fine (anyway at some point I might have to convert it to C / C++). I would like to not use too many libraries, to simplify porting.

答:
For the requirements

generate a sequence of random numbers r_i from a whole number interval I = [-(R+1), R], R > 0 with a statistical distribution like
  java.util.Random

the sequence r_i must be strictly increasing (r_i > r_j for i > j)

we could come up with a simple algorithm

```<code>A1:
 - draw a random number r_i from I via a library call
 - discard it, if it is less or equal the last draw, try another pick
</code>```

The possible complaint would be that this algorithm would probably give not the right number of generated r_i, there is a fuzzy requirement about N=10^12 expected numbers in total

"need a generator for many (up to one trillion, 10^12) unique random 64-bit numbers"

The solution for this would be

```<code>A2:
 - to generate N numbers and then
 - sort them
</code>```

However there is another requirement, that there is not enough memory available.

"I'd like to use at most a few MB of internal state."

My conjecture is that it is not possible to fulfill all these requirements at once.

As a compromise I suggest

```<code>A3:
 R=2^63 = 9 10^18
 N=1 Trillion = 10^12
 - divide the range I=[-R,R-1] into N intervals of length (2R+1)/N each
 - visit each of those intervals (visiting one interval after another)
 - draw a random number from that interval
</code>```

This will give N random numbers, in increasing order.

Update:

After skimming the BBHash paper and sources a couple of times this is my understanding:

Given some integer set I and a subset S with N=|S| elements, the BBHash procedure will calculate a function f which maps S to some permutation of {1,..,N} (what permutation seems to be implicitly decided by the BBHash procedure) and maps all other elements from I to a special value Imax from I.

Possible tests:

Given S and f one might check if membership in S for some arbitrary element from I is properly calculated.

One might also check if f(S) = {1,..,N}.

My guess is that the requested algorithm is intended to calculate a sample set S for N=10^12 on the fly under tight memory budget, needing uniqueness of the random number sequence rather than monotony.

To quote https://stackoverflow.com/a/35050835/2579220

Probabilistic data structures can't give you a definite answer,
  instead they provide you with a reasonable approximation of the answer
  and a way to approximate this estimation. They are extremely useful
  for big data and streaming application because they allow to
  dramatically decrease the amount of memory needed (in comparison to
  data structures that give you exact answers).

In majority of the cases these data structures use hash functions to
  randomize the items. Because they ignore collisions they keep the size
  constant, but this is also a reason why they can't give you exact
  values.

In case of BBHash a sequence of different hash functions h_i is used. One applies different h_i until no collision occurs. This only works if the input is unique. It will only work if the implementation has enough different h_i in store for the particular S.

Body:
I need a generator for many (up to one trillion, 10^12) unique random 64-bit numbers.
The generator needs to return the numbers in sorted order (Long.MIN_VALUE to Long.MAX_VALUE). The problem is that sorting $10^{12}$ numbers is slow. The use case is replicating a test that was run for BBHash (in the paper, 4.5 Indexing a trillion keys).

The straightforward solution is to create a set in memory, using a huge bit set or so
to ensure no duplicates are returned.
But that uses too much memory or I/O.
I'd like to use at most a few MB of internal state.

The generator should use a java.util.Random internally.
It should be as "fair" as possible (have the same statistical distribution as if generated otherwise). I would also like to have a version for 128-bit numbers (2 longs).

What I have so far is code to create a set in memory (Java code):

public static void main(String... args) {
    for(long x : randomSet(10, 0)) {
        System.out.println(x);
    }
}

static Iterable<Long> randomSet(int size, int seed) {
    Random r = new Random(seed);
    TreeSet<Long> set = new TreeSet<Long>();
    while (set.size() < size) {
        set.add(r.nextLong());
    }
    return set;
}

-8292973307042192125
-7423979211207825555
-6688467811848818630
-4962768465676381896
-2228689144322150137
-1083761183081836303
-279624296851435688
4437113781045784766
6146794652083548235
7105486291024734541

The simplest (wrong) solution, which is not random, is to distribute the results evenly.
I don't think a solution along the line of "add a random gap" will work,
because it is slow, and the sum of such gaps, after 10^12, will not land where it should (well, maybe: remember how many numbers are left, then re-calculate the distribution...). I think the following should work, but is complex, and not sure what formulas to use: for each bit level,
recursively, calculating how many 0s / 1s will likely occur
(using the Binomial distribution or the approximation, the normal / Gaussian distribution, somehow).
Stop at some point (say, blocks of 1 million entries or less),
use the code above, for speed.
But maybe there is an elegant solution.
Maybe this is related to the Metropolis–Hastings algorithm, not sure.
I read "An Efficient Algorithm for Sequential Random Sampling",
but I think it is only for small n, and I find it hard to get to a simple algorithm from this.

Java code would be best, but C is fine (anyway at some point I might have to convert it to C / C++). I would like to not use too many libraries, to simplify porting.

Body:
For the requirements

generate a sequence of random numbers r_i from a whole number interval I = [-(R+1), R], R > 0 with a statistical distribution like
  java.util.Random

the sequence r_i must be strictly increasing (r_i > r_j for i > j)

we could come up with a simple algorithm

A1:
 - draw a random number r_i from I via a library call
 - discard it, if it is less or equal the last draw, try another pick

The possible complaint would be that this algorithm would probably give not the right number of generated r_i, there is a fuzzy requirement about N=10^12 expected numbers in total

"need a generator for many (up to one trillion, 10^12) unique random 64-bit numbers"

The solution for this would be

A2:
 - to generate N numbers and then
 - sort them

However there is another requirement, that there is not enough memory available.

"I'd like to use at most a few MB of internal state."

My conjecture is that it is not possible to fulfill all these requirements at once.

As a compromise I suggest

A3:
 R=2^63 = 9 10^18
 N=1 Trillion = 10^12
 - divide the range I=[-R,R-1] into N intervals of length (2R+1)/N each
 - visit each of those intervals (visiting one interval after another)
 - draw a random number from that interval

This will give N random numbers, in increasing order.

Update:

After skimming the BBHash paper and sources a couple of times this is my understanding:

Given some integer set I and a subset S with N=|S| elements, the BBHash procedure will calculate a function f which maps S to some permutation of {1,..,N} (what permutation seems to be implicitly decided by the BBHash procedure) and maps all other elements from I to a special value Imax from I.

Possible tests:

Given S and f one might check if membership in S for some arbitrary element from I is properly calculated.

One might also check if f(S) = {1,..,N}.

My guess is that the requested algorithm is intended to calculate a sample set S for N=10^12 on the fly under tight memory budget, needing uniqueness of the random number sequence rather than monotony.

To quote https://stackoverflow.com/a/35050835/2579220

Probabilistic data structures can't give you a definite answer,
  instead they provide you with a reasonable approximation of the answer
  and a way to approximate this estimation. They are extremely useful
  for big data and streaming application because they allow to
  dramatically decrease the amount of memory needed (in comparison to
  data structures that give you exact answers).

In majority of the cases these data structures use hash functions to
  randomize the items. Because they ignore collisions they keep the size
  constant, but this is also a reason why they can't give you exact
  values.

In case of BBHash a sequence of different hash functions h_i is used. One applies different h_i until no collision occurs. This only works if the input is unique. It will only work if the implementation has enough different h_i in store for the particular S.


问:
Using redux with a local database
I have an offline React web app where all data is stored locally in indexedDB. There is no server other than the file hosting for static assets. I am getting to the point where I am starting to look into using redux now but I am trying to understand the tradeoffs between moving more data into the store and continuing to rely on the DB. What's the idiomatic way of using a local db with redux?

Currently my app is composed of several container components that each fetch data from the db in componentWillMount. One option for integrating redux is to keep this mostly the same, with the only difference being the state is kept in the store and data is fetched using actions and thunks.

Alternately, I have seen lots of example code that loads all the data into the store at launch. This makes the whole app more deterministic, easier to test and reproduce. Switching between the main components would happen instantly (at the expense of initial app load). But I lose the benefits the DB provides like indexes and nice queries.

It seems like it would be unreasonable load literally the whole db into the store, at least in my case, that would be about 10MB of data, maybe more. So I will always have at least some components which will need to continue fetching their data on mount. But there's a subset of data which is central to the app and can be argued that table should be loaded in its entirety (this would be about 5,000 to 10,000 objects, probably).

What's the idiomatic way to work with local storage and redux? I get the sense that async fetches in componentWillMount is not idiomatic if it can be avoided. Even in instances where the state is small enough that it can be fully loaded into the store, is it worth giving up the benefits of a nice efficient query interface?

Edit: I should mention: I am using Dexie, which is a really, really wonderful library for working with indexedDB. It's fast, has a nice query interface, handles migrations etc... I'd really like to continue using Dexie unless there's a really strong reason to do otherwise.

For reference, here's a discussion on this topic on Dexie's github. The general take away form that is "it depends". Not quite the answer I was looking for, so I am hoping to get more insight if possible.

答:
EDIT 2020-12-18: I recommend using dexie-react-hooks and the useLiveQuery() hook. It's an amazing experience to work with takes away all complexity around this. See also this blog post about it.

My old answer was:
This question is of large interest to me as well as I have been elaborating with react and dexie for the last project I've been in. I am personally examining how graphql could address this scenario, but I am still learning. I hope to provide an example of a graphql/dexie. Of what I understand, graphql would act as the service layer and its "schema" (backend store) would use the dexie queries required to produce the more flat an simplistic graphql data requirements. I will be looking at some ready-to-use grapql sample from Apollo or Facebook to get started and I believe it will be simple to use.
I generally don't think it scales to read entire db into memory. And I believe application startup is crucial to end users so I really hope to find a perfect architecture for this. And currently my hope goes to Graphql.

Title: Using redux with a local database


问:
Will applicationinsightConfig will cause application recycle
I am using application insight SDK for logging exceptions. I am setting the exclusion/inclusion event type list in the applicationisightconfig file.

My question is that if i change applicationinsightconfig file to update exclusion list event list in run-time, will it recycle the application domain.

答:
My question is that if i change applicationinsightconfig file to update exclusion list event list in run-time, will it recycle the application domain.

Based on my test, if you change the applicationinsightconfig to exclusion/inclusion event type list in the applicationisightconfig file. It will not affect you web application.

The web application will still work well.

The TelemetryConfiguration class will atuo get the parameter (you set in the .config) to run.

Update:

Based on my test, I found if you changed the setting in the applicationinsightconfig file, it will not be effective until the web application restart.

According to this article, I created a custom processor to filter telemetry and register it with the SDK. All telemetry goes through your processor, and you can choose to drop it from the stream, or add properties.

Some part of the SuccessfulDependencyFilter:

```<code>public class SuccessfulDependencyFilter : ITelemetryProcessor
  {

    private ITelemetryProcessor Next { get; set; }

    // You can pass values from .config
    public string MyParamFromConfigFile { get; set; }

  // Example: replace with your own modifiers.
    private void ModifyItem (ITelemetry item)
    {
        item.Context.Properties.Add("app-version", "1." + MyParamFromConfigFile);
    }
</code>```

The applicationinsightconfig file add below setting.

```<code><TelemetryProcessors>
      <Add Type="WebApplication9.SuccessfulDependencyFilter, WebApplication9">
         <!-- Set public property -->
         <MyParamFromConfigFile>2-beta</MyParamFromConfigFile>
      </Add>
    </TelemetryProcessors>
</code>```

It will add a custom type according to the applicationinsightconfig file.

After the application start I changed the setting as below:

But the custom property is still the "1.2-beta", not changed.

In my opinion, the applicationinsightconfig will be loaded when the application running. So if you changed the applicationinsightconfig setting, it will be effective after the application restarted.

Body:
My question is that if i change applicationinsightconfig file to update exclusion list event list in run-time, will it recycle the application domain.

Based on my test, if you change the applicationinsightconfig to exclusion/inclusion event type list in the applicationisightconfig file. It will not affect you web application.

The web application will still work well.

The TelemetryConfiguration class will atuo get the parameter (you set in the .config) to run.

Update:

Based on my test, I found if you changed the setting in the applicationinsightconfig file, it will not be effective until the web application restart.

According to this article, I created a custom processor to filter telemetry and register it with the SDK. All telemetry goes through your processor, and you can choose to drop it from the stream, or add properties.

Some part of the SuccessfulDependencyFilter:

public class SuccessfulDependencyFilter : ITelemetryProcessor
  {

    private ITelemetryProcessor Next { get; set; }

    // You can pass values from .config
    public string MyParamFromConfigFile { get; set; }

  // Example: replace with your own modifiers.
    private void ModifyItem (ITelemetry item)
    {
        item.Context.Properties.Add("app-version", "1." + MyParamFromConfigFile);
    }

The applicationinsightconfig file add below setting.

<TelemetryProcessors>
      <Add Type="WebApplication9.SuccessfulDependencyFilter, WebApplication9">
         <!-- Set public property -->
         <MyParamFromConfigFile>2-beta</MyParamFromConfigFile>
      </Add>
    </TelemetryProcessors>

It will add a custom type according to the applicationinsightconfig file.

After the application start I changed the setting as below:

But the custom property is still the "1.2-beta", not changed.

In my opinion, the applicationinsightconfig will be loaded when the application running. So if you changed the applicationinsightconfig setting, it will be effective after the application restarted.


问:
Oracle plsql how to select if two counts are equal
I wish to select data from a table if, and only if, the unique mobile numbers are equal to the total number of rows in a table (i.e. we dont have two different people with the same mobile number, and/or we don't have a row with null values in the mobile number column), where there is a specific area code, e.g. 4817.

At the moment, I have the query bellow (which does not work with the AND constraint). Does anyone have any tips on how to do this?

```<code>SELECT
  MOB_NUM   AS MOBILE_NUMBER,
  NAME      AS NAME,
  AREA_CODE AS AREA_CODE

  FROM DB_PHONEBOOK DBP
  WHERE DBP.AREA_CODE = 4817
  AND (COUNT(DISTINCT DBP.MOB_NUM ) = COUNT(DBP.MOB_NUM))
</code>```

答:
Individual rows/records are filtered using Where clause where as groups like count/Sum/Average/.. are filtered using Having clause

If am not wrong you are looking for something like this

```<code>SELECT DBP.MOB_NUM   AS MOBILE_NUMBER,
       DBP.NAME      AS NAME,
       DBP.AREA_CODE AS AREA_CODE
FROM   DB_PHONEBOOK DBP
       INNER JOIN (SELECT MOB_NUM
                   FROM   DB_PHONEBOOK DBP
                   WHERE  DBP.AREA_CODE = 4817
                   GROUP  BY MOB_NUM
                   HAVING Count(DISTINCT DBP.MOB_NUM) = Count(DBP.MOB_NUM)) C_DBP
               ON DBP.MOB_NUM = C_DBP.MOB_NUM
WHERE  DBP.AREA_CODE = 4817
</code>```

Body:
I wish to select data from a table if, and only if, the unique mobile numbers are equal to the total number of rows in a table (i.e. we dont have two different people with the same mobile number, and/or we don't have a row with null values in the mobile number column), where there is a specific area code, e.g. 4817.

At the moment, I have the query bellow (which does not work with the AND constraint). Does anyone have any tips on how to do this?

SELECT
  MOB_NUM   AS MOBILE_NUMBER,
  NAME      AS NAME,
  AREA_CODE AS AREA_CODE

  FROM DB_PHONEBOOK DBP
  WHERE DBP.AREA_CODE = 4817
  AND (COUNT(DISTINCT DBP.MOB_NUM ) = COUNT(DBP.MOB_NUM))

Body:
Individual rows/records are filtered using Where clause where as groups like count/Sum/Average/.. are filtered using Having clause

If am not wrong you are looking for something like this

SELECT DBP.MOB_NUM   AS MOBILE_NUMBER,
       DBP.NAME      AS NAME,
       DBP.AREA_CODE AS AREA_CODE
FROM   DB_PHONEBOOK DBP
       INNER JOIN (SELECT MOB_NUM
                   FROM   DB_PHONEBOOK DBP
                   WHERE  DBP.AREA_CODE = 4817
                   GROUP  BY MOB_NUM
                   HAVING Count(DISTINCT DBP.MOB_NUM) = Count(DBP.MOB_NUM)) C_DBP
               ON DBP.MOB_NUM = C_DBP.MOB_NUM
WHERE  DBP.AREA_CODE = 4817


问:
Is there an Ansible/Jinja2 subgroup variables unique filter?
We are using Ansible to generate some iptables rules from a Jinja2 template. The hosts are in nested groups, and their subnets are stored as variables in the child group variables within the inventory file like this:

```<code>[parent_group]
[parent_group:children]
child_group1
    [child_group1]
    FQDN1
    FQDN2
    [child_group1:vars]
    subnet=10.0.0.0/24
</code>```

We have many child groups, each with their own subnet/mask for their respective host groups. Most of the Ansible/Jinja2 documentation points to referencing the group variables by using a for-loop to iterate over their member hosts, which would result in duplicate lines in our template file. What is the best way to grab the child_group vars of parent_group only once? Is there a way to filter for unique values in a Jinja2 for-loop?

答:
Here is an expression to get a list of unique subnets for hosts in parent_group:

```<code>{{ groups['parent_group'] | map('extract',hostvars,'subnet') | list | unique }}
</code>```

This technique of value extraction is described here.

Body:
We are using Ansible to generate some iptables rules from a Jinja2 template. The hosts are in nested groups, and their subnets are stored as variables in the child group variables within the inventory file like this:

[parent_group]
[parent_group:children]
child_group1
    [child_group1]
    FQDN1
    FQDN2
    [child_group1:vars]
    subnet=10.0.0.0/24

We have many child groups, each with their own subnet/mask for their respective host groups. Most of the Ansible/Jinja2 documentation points to referencing the group variables by using a for-loop to iterate over their member hosts, which would result in duplicate lines in our template file. What is the best way to grab the child_group vars of parent_group only once? Is there a way to filter for unique values in a Jinja2 for-loop?

Body:
Here is an expression to get a list of unique subnets for hosts in parent_group:

{{ groups['parent_group'] | map('extract',hostvars,'subnet') | list | unique }}

This technique of value extraction is described here.


问:
php change filename from usb disk
The operating system is macOS. The local server environment is MAMP, and the usb path is /Volumes/USB_DISK.

Now I want to detect file change in usb disk and change it's name,like change 1.jpeg to a1.jpeg,the code:

```<code>function getFreshImage($dir, $prefix){
    $iterator = new FilesystemIterator($dir, FilesystemIterator::CURRENT_AS_PATHNAME);
    foreach ($iterator as $fileinfo) {
        $fullName = basename($iterator->current());
        $name = basename($iterator->current(), '.jpeg');
        if (strpos($name, '.') === false && strpos($name, $prefix) === false) {
            $newName = $prefix.$fullName;
            $bool = rename($dir.$fullName, $dir.$newName);  // always return false here
        }
    }
}

$fname = '/Volumes/USB_DISK';
$prefix = 'a';
getFreshImage($fname, $prefix);     // add prefix to fresh image
</code>```

I checked the directory, and the privileges is 777, anyone know how to do with this, should I config php.ini or something else?

答:
It seems  I made a foolish mistake, I try it in the common line  php scanFile.php, and it shows

```<code>Warning: rename(/Volumes/USB_DISKa1.jpeg,/Volumes/USB_DISKba1.jpeg): No such file or directory in /Applications/MAMP/htdocs/capture/scanFile.php on line 36
falseba3.jpeg<br><br>
</code>```

so I find that I passed a wrong dir params, the fname should be

```<code>$fname = '/Volumes/USB_DISK/';
</code>```

just a slash, now it works.

Title: php change filename from usb disk

Body:
The operating system is macOS. The local server environment is MAMP, and the usb path is /Volumes/USB_DISK.

Now I want to detect file change in usb disk and change it's name,like change 1.jpeg to a1.jpeg,the code:

function getFreshImage($dir, $prefix){
    $iterator = new FilesystemIterator($dir, FilesystemIterator::CURRENT_AS_PATHNAME);
    foreach ($iterator as $fileinfo) {
        $fullName = basename($iterator->current());
        $name = basename($iterator->current(), '.jpeg');
        if (strpos($name, '.') === false && strpos($name, $prefix) === false) {
            $newName = $prefix.$fullName;
            $bool = rename($dir.$fullName, $dir.$newName);  // always return false here
        }
    }
}

$fname = '/Volumes/USB_DISK';
$prefix = 'a';
getFreshImage($fname, $prefix);     // add prefix to fresh image

I checked the directory, and the privileges is 777, anyone know how to do with this, should I config php.ini or something else?

Body:
It seems  I made a foolish mistake, I try it in the common line  php scanFile.php, and it shows

Warning: rename(/Volumes/USB_DISKa1.jpeg,/Volumes/USB_DISKba1.jpeg): No such file or directory in /Applications/MAMP/htdocs/capture/scanFile.php on line 36
falseba3.jpeg<br><br>

so I find that I passed a wrong dir params, the fname should be

$fname = '/Volumes/USB_DISK/';

just a slash, now it works.


问:
Enable Tableview Scrolling but disable touches
I want to disable my tableview. Means that no button,TextFields and other controls can be touched but also i want that my tableview scroll should be working properly.

```<code>self.tableView.userInteractionEnabled=true;
</code>```

I have used this but this made scrolling also disable.

答:
try to override UITableView touchesShouldCancelInContentView method:

//OC code:

```<code>- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
    //when you want to scroll and touch event don't deliver to controls.
    if ([view isKindOfClass:[UIControl class])){
          return YES;
    }

    return [super touchesShouldCancelInContentView:view];
}
</code>```

Body:
I want to disable my tableview. Means that no button,TextFields and other controls can be touched but also i want that my tableview scroll should be working properly.

self.tableView.userInteractionEnabled=true;

I have used this but this made scrolling also disable.

Body:
try to override UITableView touchesShouldCancelInContentView method:

//OC code:

- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
    //when you want to scroll and touch event don't deliver to controls.
    if ([view isKindOfClass:[UIControl class])){
          return YES;
    }

    return [super touchesShouldCancelInContentView:view];
}


问:
Refresh page after bootstrap modal close
I am trying to refresh my current page after I close bootstrap modal.

```<code>$('#modal1').on('hide', function() {
window.location.href = 'current-page.php';
})
</code>```

Is there a way for refresh current page after closing modal.

答:
You can refresh current page after you close modal by this:</p>

```<code>$('#modal1').on('hide', function() {
window.location.reload();
});
</code>```

Body:
I am trying to refresh my current page after I close bootstrap modal.

$('#modal1').on('hide', function() {
window.location.href = 'current-page.php';
})

Is there a way for refresh current page after closing modal.

Body:
You can refresh current page after you close modal by this:

$('#modal1').on('hide', function() {
window.location.reload();
});


答:
10^12 is about 2^40, ie average step between sequential values will be 2^24.

Therefore, if goal is to generate unpredictable, but ordered hashes sequence, then it not possible, 2^24 is too easy for bruteforce

But if it not goal, then why not just join incremental 2^40 counter in top bits with 2^24 random value in lower bits?

Title: Random number generator that returns unique entries in sorted order


问:
How do I delete an item from a ListView without deleting it from the database?
I have implemented a snackbar in my app that has an Undo button to undo the delete. Currently how it works is, when the user deletes an item, I keep a cursor with the item by performing a query from the database, the item is then deleted from the database and the list is updated via notifyChange(). When the user taps on the Undo button on the snackbar, I extract the content from the saved cursor, create a new ContentValue and insert it into the database, again calling notifyChange() to update the list.

I dont like this approach. There is one too many database operation.

Is there any way I can just remove/hide an item from the ListView and only delete the item when the snackbar goes away?

I tried setting the visibility to GONE or INVISIBLE but that leaves a blank space in the middle of the ListView.

I am using a CursorAdapter to populate the ListView. There is a 3 dot menu on each list item that shows a delete option.

Here is my current CursorAdapter code

```<code>public class ProductCursorAdapter extends CursorAdapter {

private static final String LOG_TAG = ProductCursorAdapter.class.getSimpleName();
protected ContentResolver contentResolver;

public ProductCursorAdapter(Context context, Cursor c, ContentResolver contentResolver) {
    super(context, c);
    this.contentResolver = contentResolver;
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
}

@Override
public void bindView(final View view, final Context context, final Cursor cursor) {
    ImageView thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
    TextView name = (TextView) view.findViewById(R.id.name);
    TextView quantity = (TextView) view.findViewById(R.id.quantity);
    TextView price = (TextView) view.findViewById(R.id.price);
    TextView supplier = (TextView) view.findViewById(R.id.supplier);

    final long id = cursor.getLong(cursor.getColumnIndexOrThrow(ProductEntry._ID));

    ImageView threeDotMenu = (ImageView) view.findViewById(R.id.three_dot_menu);
    threeDotMenu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PopupMenu popup = new PopupMenu(context, v);
            popup.getMenuInflater().inflate(R.menu.list_item_context_menu, popup.getMenu());
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.context_delete_product:
                            //the uri of the product we're deleting
                            Uri currentProductUri = ContentUris.withAppendedId(ProductEntry.CONTENT_URI, id);
                            //What to extract from the database
                            String[] projection = {
                                    ProductEntry._ID,
                                    ProductEntry.COLUMN_NAME,
                                    ProductEntry.COLUMN_QUANTITY,
                                    ProductEntry.COLUMN_PRICE,
                                    ProductEntry.COLUMN_SUPPLIER,
                                    ProductEntry.COLUMN_IMAGE
                            };
                            //retrieve the product from the database before deleting in case
                            //we need to restore it later
                            Cursor cursor = contentResolver.query(currentProductUri,
                                    projection,
                                    null,
                                    null,
                                    null,
                                    null);
                            cursor.moveToFirst();
                            Snackbar snackbar = Snackbar.make(view.getRootView().findViewById(R.id.coordinator_layout), "Product Deleted", Snackbar.LENGTH_LONG);
                            snackbar.setAction("Undo", new MyUndoListener(cursor));
                            snackbar.show();
                            contentResolver.delete(currentProductUri, null, null);
                            return true;
                        default:
                            return false;
                    }
                }
            });
            popup.show();
        }
    });

    . . .

}

public class MyUndoListener implements View.OnClickListener {
    Cursor cursor = null;

    public MyUndoListener(Cursor cursor) {
        this.cursor = cursor;

    }

    @Override
    public void onClick(View v) {
        contentResolver.insert(ProductEntry.CONTENT_URI, extractFromCursor(cursor));
    }

    private ContentValues extractFromCursor(Cursor cursor) {

        int id = cursor.getInt(cursor.getColumnIndexOrThrow(ProductEntry._ID));

        String name = cursor.getString(cursor.getColumnIndexOrThrow(ProductEntry.COLUMN_NAME));

        int quantity = cursor.getInt(cursor.getColumnIndexOrThrow(ProductEntry.COLUMN_QUANTITY));

        int price = cursor.getInt(cursor.getColumnIndexOrThrow(ProductEntry.COLUMN_PRICE));

        String supplier = cursor.getString(cursor.getColumnIndexOrThrow(ProductEntry.COLUMN_SUPPLIER));

        byte[] image = cursor.getBlob(cursor.getColumnIndexOrThrow(ProductEntry.COLUMN_IMAGE));
        ContentValues value = new ContentValues();
        value.put(ProductEntry._ID, id);
        value.put(ProductEntry.COLUMN_NAME, name);
        value.put(ProductEntry.COLUMN_PRICE, price);
        value.put(ProductEntry.COLUMN_QUANTITY, quantity);
        value.put(ProductEntry.COLUMN_SUPPLIER, supplier);
        value.put(ProductEntry.COLUMN_IMAGE, image);
        cursor.close();
        return value;

    }

}
</code>```

}

答:
Well Nishan, For This make Arraylist of database values and then bind a listview. whenever you want to delete one item (Not from your database) then make a copy of arraylist without that item and again bind the listview.

Thus you have your database remains same and you can use it again in case of undo.
So what item you want to delete , bind a new arraylist from orignal arraylst without that item and use it.

Body:
I have implemented a snackbar in my app that has an Undo button to undo the delete. Currently how it works is, when the user deletes an item, I keep a cursor with the item by performing a query from the database, the item is then deleted from the database and the list is updated via notifyChange(). When the user taps on the Undo button on the snackbar, I extract the content from the saved cursor, create a new ContentValue and insert it into the database, again calling notifyChange() to update the list.

I dont like this approach. There is one too many database operation.

Is there any way I can just remove/hide an item from the ListView and only delete the item when the snackbar goes away?

I tried setting the visibility to GONE or INVISIBLE but that leaves a blank space in the middle of the ListView.

I am using a CursorAdapter to populate the ListView. There is a 3 dot menu on each list item that shows a delete option.

Here is my current CursorAdapter code

public class ProductCursorAdapter extends CursorAdapter {

private static final String LOG_TAG = ProductCursorAdapter.class.getSimpleName();
protected ContentResolver contentResolver;

public ProductCursorAdapter(Context context, Cursor c, ContentResolver contentResolver) {
    super(context, c);
    this.contentResolver = contentResolver;
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
}

@Override
public void bindView(final View view, final Context context, final Cursor cursor) {
    ImageView thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
    TextView name = (TextView) view.findViewById(R.id.name);
    TextView quantity = (TextView) view.findViewById(R.id.quantity);
    TextView price = (TextView) view.findViewById(R.id.price);
    TextView supplier = (TextView) view.findViewById(R.id.supplier);

    final long id = cursor.getLong(cursor.getColumnIndexOrThrow(ProductEntry._ID));

    ImageView threeDotMenu = (ImageView) view.findViewById(R.id.three_dot_menu);
    threeDotMenu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PopupMenu popup = new PopupMenu(context, v);
            popup.getMenuInflater().inflate(R.menu.list_item_context_menu, popup.getMenu());
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.context_delete_product:
                            //the uri of the product we're deleting
                            Uri currentProductUri = ContentUris.withAppendedId(ProductEntry.CONTENT_URI, id);
                            //What to extract from the database
                            String[] projection = {
                                    ProductEntry._ID,
                                    ProductEntry.COLUMN_NAME,
                                    ProductEntry.COLUMN_QUANTITY,
                                    ProductEntry.COLUMN_PRICE,
                                    ProductEntry.COLUMN_SUPPLIER,
                                    ProductEntry.COLUMN_IMAGE
                            };
                            //retrieve the product from the database before deleting in case
                            //we need to restore it later
                            Cursor cursor = contentResolver.query(currentProductUri,
                                    projection,
                                    null,
                                    null,
                                    null,
                                    null);
                            cursor.moveToFirst();
                            Snackbar snackbar = Snackbar.make(view.getRootView().findViewById(R.id.coordinator_layout), "Product Deleted", Snackbar.LENGTH_LONG);
                            snackbar.setAction("Undo", new MyUndoListener(cursor));
                            snackbar.show();
                            contentResolver.delete(currentProductUri, null, null);
                            return true;
                        default:
                            return false;
                    }
                }
            });
            popup.show();
        }
    });

    . . .

}

public class MyUndoListener implements View.OnClickListener {
    Cursor cursor = null;

    public MyUndoListener(Cursor cursor) {
        this.cursor = cursor;

    }

    @Override
    public void onClick(View v) {
        contentResolver.insert(ProductEntry.CONTENT_URI, extractFromCursor(cursor));
    }

    private ContentValues extractFromCursor(Cursor cursor) {

        int id = cursor.getInt(cursor.getColumnIndexOrThrow(ProductEntry._ID));

        String name = cursor.getString(cursor.getColumnIndexOrThrow(ProductEntry.COLUMN_NAME));

        int quantity = cursor.getInt(cursor.getColumnIndexOrThrow(ProductEntry.COLUMN_QUANTITY));

        int price = cursor.getInt(cursor.getColumnIndexOrThrow(ProductEntry.COLUMN_PRICE));

        String supplier = cursor.getString(cursor.getColumnIndexOrThrow(ProductEntry.COLUMN_SUPPLIER));

        byte[] image = cursor.getBlob(cursor.getColumnIndexOrThrow(ProductEntry.COLUMN_IMAGE));
        ContentValues value = new ContentValues();
        value.put(ProductEntry._ID, id);
        value.put(ProductEntry.COLUMN_NAME, name);
        value.put(ProductEntry.COLUMN_PRICE, price);
        value.put(ProductEntry.COLUMN_QUANTITY, quantity);
        value.put(ProductEntry.COLUMN_SUPPLIER, supplier);
        value.put(ProductEntry.COLUMN_IMAGE, image);
        cursor.close();
        return value;

    }

}

}