问:
How to find week date ranges for a given month
I need to display a range of dates in corresponding week for selected month.
Suppose the selected values are $month=2 and $year=2017.
The output should show a list of ranged dates for weeks in that particular month selected.

```<code>$month = $_GET['month'];
$year = $_GET['year'];
 ...

Output:
Week 1: 01/02/2017 - 05/02/2017
Week 2: 06/02/2017 - 12/02/2017
Week 3: 13/02/2017 - 19/02/2017
Week 4: 20/02/2017 - 26/02/2017
Week 5: 27/02/2017 - 28/02/2017
</code>```

Ive look through Split the current month in to weeks in php , Get week number in month from date in PHP? and Split date ranges into corresponding weeks , but none of them working for me.

Thanks.

答:
This method can show weeks including day of week to break that week

Show test

```<code>$month = '2';
$year = '2017';
$lastDayOfWeek = '7'; //1 (for monday) to 7 (for sunday)

function getWeeksInMonth($year, $month, $lastDayOfWeek)
{
    $aWeeksOfMonth = [];
    $date = new DateTime("{$year}-{$month}-01");
    $iDaysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    $aOneWeek = [$date->format('Y-m-d')];
    $weekNumber = 1;
    for ($i = 1; $i <= $iDaysInMonth; $i++)
    {
        if ($lastDayOfWeek == $date->format('N') || $i == $iDaysInMonth)
        {
            $aOneWeek[]      = $date->format('Y-m-d');
            $aWeeksOfMonth[$weekNumber++] = $aOneWeek;
            $date->add(new DateInterval('P1D'));
            $aOneWeek = [$date->format('Y-m-d')];
            $i++;

        }
        $date->add(new DateInterval('P1D'));
    }
    return $aWeeksOfMonth;
}

$weeks = getWeeksInMonth($year, $month, $lastDayOfWeek);

foreach($weeks as $weekNumber => $week){
    echo "Week {$weekNumber}: {$week[0]} - {$week[1]}\r\n";
}
</code>```

Output

Week 1: 2017/02/01 - 2017/02/05

  Week 2: 2017/02/06 - 2017/02/12

  Week 3: 2017/02/13 - 2017/02/19

  Week 4: 2017/02/20 - 2017/02/26

  Week 5: 2017/02/27 - 2017/02/28

Body:
I need to display a range of dates in corresponding week for selected month.
Suppose the selected values are $month=2 and $year=2017.
The output should show a list of ranged dates for weeks in that particular month selected.

$month = $_GET['month'];
$year = $_GET['year'];
 ...

Output:
Week 1: 01/02/2017 - 05/02/2017
Week 2: 06/02/2017 - 12/02/2017
Week 3: 13/02/2017 - 19/02/2017
Week 4: 20/02/2017 - 26/02/2017
Week 5: 27/02/2017 - 28/02/2017

Ive look through Split the current month in to weeks in php , Get week number in month from date in PHP? and Split date ranges into corresponding weeks , but none of them working for me.

Thanks.

Body:
This method can show weeks including day of week to break that week

Show test

$month = '2';
$year = '2017';
$lastDayOfWeek = '7'; //1 (for monday) to 7 (for sunday)

function getWeeksInMonth($year, $month, $lastDayOfWeek)
{
    $aWeeksOfMonth = [];
    $date = new DateTime("{$year}-{$month}-01");
    $iDaysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    $aOneWeek = [$date->format('Y-m-d')];
    $weekNumber = 1;
    for ($i = 1; $i <= $iDaysInMonth; $i++)
    {
        if ($lastDayOfWeek == $date->format('N') || $i == $iDaysInMonth)
        {
            $aOneWeek[]      = $date->format('Y-m-d');
            $aWeeksOfMonth[$weekNumber++] = $aOneWeek;
            $date->add(new DateInterval('P1D'));
            $aOneWeek = [$date->format('Y-m-d')];
            $i++;

        }
        $date->add(new DateInterval('P1D'));
    }
    return $aWeeksOfMonth;
}

$weeks = getWeeksInMonth($year, $month, $lastDayOfWeek);

foreach($weeks as $weekNumber => $week){
    echo "Week {$weekNumber}: {$week[0]} - {$week[1]}\r\n";
}

Output

Week 1: 2017/02/01 - 2017/02/05

  Week 2: 2017/02/06 - 2017/02/12

  Week 3: 2017/02/13 - 2017/02/19

  Week 4: 2017/02/20 - 2017/02/26

  Week 5: 2017/02/27 - 2017/02/28


来源: stackexchange

问:
In SQL how to split an select a string which is not present i a table?
Here is my query I used to get UserID present in both where condition and TSTable

```<code>                    SELECT  UserID
                    FROM    TSTable
                    WHERE UserID IN (@UserID)
</code>```

I need to to get the UserId from @UserID

```<code>  where    @UserID = ''IMS080'',''IMS108'',''IMS218''
</code>```

which are not present in TSTable. How can I do this?
For example, if I Execute the Query it should return value from IN condition
'IMS080' which is not present in TSTable.

Thanks in Advance

答:
Is this what you're looking for?</p>

```<code>select 'IMS080' as UserID
  union
select 'IMS108'
  union
select 'IMS218';
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is my query I used to get UserID present in both where condition and TSTable

                    SELECT  UserID
                    FROM    TSTable
                    WHERE UserID IN (@UserID)

I need to to get the UserId from @UserID

  where    @UserID = ''IMS080'',''IMS108'',''IMS218''

which are not present in TSTable. How can I do this?
For example, if I Execute the Query it should return value from IN condition
'IMS080' which is not present in TSTable.

Thanks in Advance

Body:
Is this what you're looking for?

select 'IMS080' as UserID
  union
select 'IMS108'
  union
select 'IMS218';


问:
Angular 4 | Change detection of an array
How can I manage my array when it is updated or not? My data comes from an API.

I set interval for every 10 seconds so it will get data to a new one.

```<code>counter = 10;
ngOnInit() {
    this.getVoicepickData();
    // subscribe to API data every 10 seconds
    this.apiTimer = setInterval(() => {
        this.getVoicepickData();
    }, (this.counter*1000));
}

getData(){
    // set headers [token]
    let headers = new Headers({
        'token': "My TOKEN",
        'Content-Type': 'application/json'
    });
    let options: RequestOptions = new RequestOptions({ headers: headers });
    return this.http.get('http://api.com/mydata/', options)
        .map((res: Response) => res.json())
}

//subscribe to API Data
getVoicepickData() {
    this.showLoader();
    this.getData().subscribe(data => {
        this.data = data

        //distribute the api data according to what zone they belong, for ease in manipulatation of data
        for(let mydata of this.data){
            if (mydata.Zone == 1) {
                this.zoneOne.push(mydata);

            }
            if (mydata.Zone == 2) {
                this.zoneTwo.push(mydata);

            }
            if (mydata.Zone == 3) {
                this.zoneThree.push(mydata);

            }
            if (mydata.Zone == 4) {
                this.zoneFour.push(mydata);

            }
            if (mydata.Zone == 5) {
                this.zoneFive.push(mydata);

            }
            if (mydata.Zone == 6) {
                this.zoneSix.push(mydata);

            }
            if (mydata.Zone == 7) {
                this.zoneSeven.push(mydata);

            }
            if (mydata.Zone == 8) {
                this.zoneEight.push(mydata);

            }
        }
        this.hideLoader();
    },
    () => {
        console.log('Error');
    },
    () => {
        console.log('Complete');
    }
    );
}
</code>```

I want to know how can I manage my api data when there are changes to it, like trigger if my data has new record it will replace my old array to a new one with the latest record on it.

But in my above code, it just keeps pushing the api data everytime my interval occur and get repeated data displayed on my screen.

How can I achieve something like evaluating first my api data if there is a new record or none, and if it has a new record it simply update my array.

答:
Run change detection manually

```<code>import { Component, ChangeDetectorRef } from '@angular/core';

@Component({
  (...)
})
export class MyComponent {
  constructor(private change:ChangeDetectorRef) {
  }

  myMethod() {
    this.change.detectChanges();
  }
}
</code>```

More on Change Detection

ContentLicense: CC BY-SA 4.0

Body:
How can I manage my array when it is updated or not? My data comes from an API.

I set interval for every 10 seconds so it will get data to a new one.

counter = 10;
ngOnInit() {
    this.getVoicepickData();
    // subscribe to API data every 10 seconds
    this.apiTimer = setInterval(() => {
        this.getVoicepickData();
    }, (this.counter*1000));
}

getData(){
    // set headers [token]
    let headers = new Headers({
        'token': "My TOKEN",
        'Content-Type': 'application/json'
    });
    let options: RequestOptions = new RequestOptions({ headers: headers });
    return this.http.get('http://api.com/mydata/', options)
        .map((res: Response) => res.json())
}

//subscribe to API Data
getVoicepickData() {
    this.showLoader();
    this.getData().subscribe(data => {
        this.data = data

        //distribute the api data according to what zone they belong, for ease in manipulatation of data
        for(let mydata of this.data){
            if (mydata.Zone == 1) {
                this.zoneOne.push(mydata);

            }
            if (mydata.Zone == 2) {
                this.zoneTwo.push(mydata);

            }
            if (mydata.Zone == 3) {
                this.zoneThree.push(mydata);

            }
            if (mydata.Zone == 4) {
                this.zoneFour.push(mydata);

            }
            if (mydata.Zone == 5) {
                this.zoneFive.push(mydata);

            }
            if (mydata.Zone == 6) {
                this.zoneSix.push(mydata);

            }
            if (mydata.Zone == 7) {
                this.zoneSeven.push(mydata);

            }
            if (mydata.Zone == 8) {
                this.zoneEight.push(mydata);

            }
        }
        this.hideLoader();
    },
    () => {
        console.log('Error');
    },
    () => {
        console.log('Complete');
    }
    );
}

I want to know how can I manage my api data when there are changes to it, like trigger if my data has new record it will replace my old array to a new one with the latest record on it.

But in my above code, it just keeps pushing the api data everytime my interval occur and get repeated data displayed on my screen.

How can I achieve something like evaluating first my api data if there is a new record or none, and if it has a new record it simply update my array.

Body:
Run change detection manually

import { Component, ChangeDetectorRef } from '@angular/core';

@Component({
  (...)
})
export class MyComponent {
  constructor(private change:ChangeDetectorRef) {
  }

  myMethod() {
    this.change.detectChanges();
  }
}

More on Change Detection


问:
Error when trying to create DB: A network-related or instance-specific error occurred while establishing a connection to SQL Server
I am trying to write application in ASP.NET, already created Models, Context and want to create DB with EF Code-First approach, but it does not work.

Additionally, folder App_Data is empty. I have installed SQL Server 2017 Express.

I tried every possible solution I could find, still, nothing worked.

Connection string:

```<code><connectionStrings>
    <add name="DefaultConnection"
         connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-BM-20171207072135.mdf;Initial Catalog=aspnet-BM-20171207072135;Integrated Security=True"
         providerName="System.Data.SqlClient" />
</connectionStrings>
</code>```

However, I get this error:

```<code>PM> update-database

> Specify the '-Verbose' flag to view the SQL
> statements being applied to the target database
</code>```

System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50

  Local Database Runtime error occurred. Error occurred during LocalDB instance startup: SQL Server process failed to start.

Errors:

  at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)
         at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
         at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
         at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
         at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
         at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
         at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
         at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
         at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry)
         at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry)
         at System.Data.SqlClient.SqlConnection.Open()
         at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.b__36(DbConnection t, DbConnectionInterceptionContext c)
         at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action2 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed)
         at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
         at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.b__32()
         at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.b__0()
         at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation)
         at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
         at System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action1 act)
         at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action1 act)
         at System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)
         at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection)
         at System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection)
         at System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase()
         at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)
         at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
         at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
         at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
         at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
         at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
         at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
      ClientConnectionId:00000000-0000-0000-0000-000000000000

>

Error Number:-1983577846,State:0,Class:20

  A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Error occurred during LocalDB instance startup: SQL Server process failed to start)

答:
Make sure your sql server is up and running. Look from windows services (services.msc). Or to make sure, try to connect first manually using VS DB connection or SSMS.

Try to check this this (below) from your sql service properties too.

Body:
I am trying to write application in ASP.NET, already created Models, Context and want to create DB with EF Code-First approach, but it does not work.

Additionally, folder App_Data is empty. I have installed SQL Server 2017 Express.

I tried every possible solution I could find, still, nothing worked.

Connection string:

<connectionStrings>
    <add name="DefaultConnection"
         connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-BM-20171207072135.mdf;Initial Catalog=aspnet-BM-20171207072135;Integrated Security=True"
         providerName="System.Data.SqlClient" />
</connectionStrings>

However, I get this error:

PM> update-database

> Specify the '-Verbose' flag to view the SQL
> statements being applied to the target database

System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50

  Local Database Runtime error occurred. Error occurred during LocalDB instance startup: SQL Server process failed to start.

Errors:

  at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)
         at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
         at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
         at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
         at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
         at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
         at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
         at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
         at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry)
         at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry)
         at System.Data.SqlClient.SqlConnection.Open()
         at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.b__36(DbConnection t, DbConnectionInterceptionContext c)
         at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action2 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed)
         at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
         at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.b__32()
         at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.b__0()
         at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation)
         at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
         at System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action1 act)
         at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action1 act)
         at System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)
         at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection)
         at System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection)
         at System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase()
         at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)
         at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
         at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
         at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
         at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
         at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
         at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
      ClientConnectionId:00000000-0000-0000-0000-000000000000

>

Error Number:-1983577846,State:0,Class:20

  A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Error occurred during LocalDB instance startup: SQL Server process failed to start)


问:
How to create a controlled form in react that allows upper case letters only?
Sorry for the long explanation, the question is at the end.

There is an example given on the reactjs site ( https://reactjs.org/docs/forms.html ) that looks like this:

```<code>handleChange(event) {
  this.setState({value: event.target.value.toUpperCase()});
}
</code>```

These tutorials usually say that in controlled forms (say in an input field) when you press a key, then onChange is called, that calls the handleChange event, that calls setState, and that re-renders the component, that will show the changed value. But this is not the whole truth. By the time the native DOM input field calls onChange, the input field was already "rendered" by the browser, and React does not re-render it. Actually it compares the state of the (re-rendered) virtual DOM element with the state of the native DOM element, and then it finds out that there is no difference, so it does nothing. In this case, the action has no side effect (other than changing the component's state).

I know that for a beginner, in the beginning of the tutorial, it may be confusing to tell the whole story at once. But this "toUpperCase()" example in the tutorial is misleading, because it suggests that by changing the value to value.toUpperCase() in handleChange will make the component only accept captialized letters, without side effects. But this is not true, and anyone can try this: just select a part of the text in the middle of the input field, and press a key. It will surely be converted to upper case, but in this case React will re-set the value attribute of the input, causing the text cursor (insertion point) to move to the end of the text. Which is a side effect, that can be very distrubing. For example, if the user wanted to replace a word in the middle of the text, then he just can't do it in any practical way. He will say that this is wrong, it is not working - and he will be damn right. In this particular case, I know that I can set text-transform:uppercase and store the lower case version in the store, but that is faulty too: if I need it to be upper case, then of course it should be in upper case in the store. The behaviour of the view must not determine the data representation in the store. Views should only be views, and nothing else.

I have checked many React related tutorials, and all of them have this "flaw". For example, here is a diagram from reactjs.org that shows Flux in action:

It suggests that the View is rendered after the action went through the dispatcher, the stores, then the controller-view. But the reality is that the View not only emits an action. It will also change its appearance before the action is emitted. React wants to see DOM elements as views that emit actions, but in reality they do other things.

The very same mistake appears in the reactjs tutorial, with the select element. ( https://reactjs.org/docs/forms.html ) They just say that by changing the "multiple={true}" attribute, you can have a multi select. No you can't, it just does not work. When you select multiple items in a multi select, the browser will call the onChange event multiple times: a separate call for every item selected. As a result, it will be impossible to set the state of the component to the set of selected items (at least not from the event handler). I COULD setup a timer, collect all changes emitted from onChange, and the finally call setState() with the collected items. But that is against React's rules, because there should be a single source of truth. And in this case, there will be multiple sources (at least for a while, until all events are collected). And anyone can see that in a complex application with many async handlers, this will eventually lead to bugs which are hard to debug.

A very simple thing ("only accept upper case letters in an input box") appears to me a hard thing to do correctly. Either I have to implement my own input box in JavaScript, or write a custom rendering method for input fields that keeps the cursor position at the correct place when value changes. Both seem to be bad ideas.

After Googling around, I have noticed that there are tons of components re-implementing native elements. There are literally hundreds of select and multiselect components written for React, and I suspect that this is partly because of how native DOM elements behave. (E.g. they are not pure views.)

Question: does anyone use react with native DOM components? And if so, how do you achieve the true "controlled" behaviour without the side effects? Is it possible? Or should I not care, and choose some kind of UI toolkit that was written specifically for React? (But even with those, implementing an "upper case input field" may require extra programming.)

答:
You are right in what you observe but the issue does not come from React, it comes from the browser itself.

Consider the following example:

function handler() {
  const elt = document.getElementById('test');
  elt.value = elt.value.toUpperCase();
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<input id="test" type="text" value="default value" onKeyPress="handler();" />
</body>
</html></code>```

How would you make it work even before talking about React ? React can't override the browser behavior.

If you want to uppercase everything while keeping the cursor position, you could  look at rich text editing with draft js for example.

Body:
Sorry for the long explanation, the question is at the end.

There is an example given on the reactjs site ( https://reactjs.org/docs/forms.html ) that looks like this:

handleChange(event) {
  this.setState({value: event.target.value.toUpperCase()});
}

These tutorials usually say that in controlled forms (say in an input field) when you press a key, then onChange is called, that calls the handleChange event, that calls setState, and that re-renders the component, that will show the changed value. But this is not the whole truth. By the time the native DOM input field calls onChange, the input field was already "rendered" by the browser, and React does not re-render it. Actually it compares the state of the (re-rendered) virtual DOM element with the state of the native DOM element, and then it finds out that there is no difference, so it does nothing. In this case, the action has no side effect (other than changing the component's state).

I know that for a beginner, in the beginning of the tutorial, it may be confusing to tell the whole story at once. But this "toUpperCase()" example in the tutorial is misleading, because it suggests that by changing the value to value.toUpperCase() in handleChange will make the component only accept captialized letters, without side effects. But this is not true, and anyone can try this: just select a part of the text in the middle of the input field, and press a key. It will surely be converted to upper case, but in this case React will re-set the value attribute of the input, causing the text cursor (insertion point) to move to the end of the text. Which is a side effect, that can be very distrubing. For example, if the user wanted to replace a word in the middle of the text, then he just can't do it in any practical way. He will say that this is wrong, it is not working - and he will be damn right. In this particular case, I know that I can set text-transform:uppercase and store the lower case version in the store, but that is faulty too: if I need it to be upper case, then of course it should be in upper case in the store. The behaviour of the view must not determine the data representation in the store. Views should only be views, and nothing else.

I have checked many React related tutorials, and all of them have this "flaw". For example, here is a diagram from reactjs.org that shows Flux in action:

It suggests that the View is rendered after the action went through the dispatcher, the stores, then the controller-view. But the reality is that the View not only emits an action. It will also change its appearance before the action is emitted. React wants to see DOM elements as views that emit actions, but in reality they do other things.

The very same mistake appears in the reactjs tutorial, with the select element. ( https://reactjs.org/docs/forms.html ) They just say that by changing the "multiple={true}" attribute, you can have a multi select. No you can't, it just does not work. When you select multiple items in a multi select, the browser will call the onChange event multiple times: a separate call for every item selected. As a result, it will be impossible to set the state of the component to the set of selected items (at least not from the event handler). I COULD setup a timer, collect all changes emitted from onChange, and the finally call setState() with the collected items. But that is against React's rules, because there should be a single source of truth. And in this case, there will be multiple sources (at least for a while, until all events are collected). And anyone can see that in a complex application with many async handlers, this will eventually lead to bugs which are hard to debug.

A very simple thing ("only accept upper case letters in an input box") appears to me a hard thing to do correctly. Either I have to implement my own input box in JavaScript, or write a custom rendering method for input fields that keeps the cursor position at the correct place when value changes. Both seem to be bad ideas.

After Googling around, I have noticed that there are tons of components re-implementing native elements. There are literally hundreds of select and multiselect components written for React, and I suspect that this is partly because of how native DOM elements behave. (E.g. they are not pure views.)

Question: does anyone use react with native DOM components? And if so, how do you achieve the true "controlled" behaviour without the side effects? Is it possible? Or should I not care, and choose some kind of UI toolkit that was written specifically for React? (But even with those, implementing an "upper case input field" may require extra programming.)

Body:
You are right in what you observe but the issue does not come from React, it comes from the browser itself.

Consider the following example:

function handler() {
  const elt = document.getElementById('test');
  elt.value = elt.value.toUpperCase();
};

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<input id="test" type="text" value="default value" onKeyPress="handler();" />
</body>
</html>

How would you make it work even before talking about React ? React can't override the browser behavior.

If you want to uppercase everything while keeping the cursor position, you could  look at rich text editing with draft js for example.


问:
A table with a composite Primary key, one of the fields with autoincrement
Im using a table constraint to create a composite primary key,  I would like the id field to autoincrement, is this possible? or what are the alternatives?

```<code>   CREATE TABLE IF NOT EXISTS atable(
        id          INTEGER NOT NULL, --I want to autoincrement this one
        name     TEXT NOT NULL,
        anotherCol  TEXT,

    PRIMARY KEY(id, name));
</code>```

答:
No, there's only one primary key: that's the composite of id and name.

If you mean that you want id to be the primary key, and name to be an indexed alternate key, I'd say that you should give name a unique constraint and make id the primary key.

ContentLicense: CC BY-SA 2.5

Body:
Im using a table constraint to create a composite primary key,  I would like the id field to autoincrement, is this possible? or what are the alternatives?

   CREATE TABLE IF NOT EXISTS atable(
        id          INTEGER NOT NULL, --I want to autoincrement this one
        name     TEXT NOT NULL,
        anotherCol  TEXT,

    PRIMARY KEY(id, name));


问:
how to notify a UIViewController that a button was clicked in a xib file using a delegate in swift?
I'm a bit stuck.
I have a UIViewController and a custom pop.xib that extends UIView.
pop.xib is connected to pop.swift.
In the UIViewController a button makes the .xib file pop up.

And in pop.xib there is a button that is clicked to send some data to the database.

But when that button is clicked in pop.xib to send data I want the UIViewController to

a) know when the @IBAction func sendDataToDbAction(_ sender: Any) is clicked and

b) when the if statement returns false from inside sendDataToDbAction then present an alert on the UIViewController

```<code>//pop.swift

     class Pop: UIView {

            @IBOutlet var delegate: AnswerDelegate?

            @IBAction func sendDataToDbAction(_ sender: Any)
            {
                     if(answer == false)
                     {
                          don't send to db
                          alert pops up saying answer is false
                     }
                     else
                     {

                     }

            }
         }
</code>```

I've set up a delegate in pop.swift

```<code>//pop.swift

@objc protocol AnswerDelegate {

    func isCorrectAnswer()
}

//UIViewController

extension UIViewController:AnswerDelegate{

//set the pop.xib delegate to self
// implement func isCorrectAnswer

}
</code>```

I'm just not sure how I can use the delegate to do what I want.

Thanks.

答:
I'm not so sure you can do this on an extension, as you need to set the delegate somewhere in your view controller.

Adjust your pop.swift to call the delegate function as below:

```<code>@IBAction func sendDataToDbAction(_ sender: Any) {
  if(answer == false) {
    // show alert
  } else {
    delegate?.isCorrectAnswer()
  }
}
</code>```

In your view controller, set the delegate and add the function as below:

```<code>class MyViewController: UIViewController, AnswerDelegate {

  override func viewDidLoad() {
    super.viewDidLoad()
    pop.delegate = self
  }

  func isCorrectAnswer() {
  }
}
</code>```

Body:
I'm a bit stuck.
I have a UIViewController and a custom pop.xib that extends UIView.
pop.xib is connected to pop.swift.
In the UIViewController a button makes the .xib file pop up.

And in pop.xib there is a button that is clicked to send some data to the database.

But when that button is clicked in pop.xib to send data I want the UIViewController to

a) know when the @IBAction func sendDataToDbAction(_ sender: Any) is clicked and

b) when the if statement returns false from inside sendDataToDbAction then present an alert on the UIViewController

//pop.swift

     class Pop: UIView {

            @IBOutlet var delegate: AnswerDelegate?

            @IBAction func sendDataToDbAction(_ sender: Any)
            {
                     if(answer == false)
                     {
                          don't send to db
                          alert pops up saying answer is false
                     }
                     else
                     {

                     }

            }
         }

I've set up a delegate in pop.swift

//pop.swift

@objc protocol AnswerDelegate {

    func isCorrectAnswer()
}

//UIViewController

extension UIViewController:AnswerDelegate{

//set the pop.xib delegate to self
// implement func isCorrectAnswer

}

I'm just not sure how I can use the delegate to do what I want.

Thanks.

Body:
I'm not so sure you can do this on an extension, as you need to set the delegate somewhere in your view controller.

Adjust your pop.swift to call the delegate function as below:

@IBAction func sendDataToDbAction(_ sender: Any) {
  if(answer == false) {
    // show alert
  } else {
    delegate?.isCorrectAnswer()
  }
}

In your view controller, set the delegate and add the function as below:

class MyViewController: UIViewController, AnswerDelegate {

  override func viewDidLoad() {
    super.viewDidLoad()
    pop.delegate = self
  }

  func isCorrectAnswer() {
  }
}


问:
Is it allowed to access memory that spans the zero boundary in x86?
Is it allowed for a single access to span the bounary between 0 and 0xFFFFFF... in x861?

For example given that eax (rax in 64-bit) is zero, is the following access allowed:

```<code>mov ebx, DWORD [eax - 2]
</code>```

I'm interested in both x86 (32-bit) and x86-64 in case the answers are different.

1 Of course given that the region is mapped in your process etc.

答:
This is not really a new answer but was too big for a comment. This is @prl's code converted so that it should run with the basic gnu-efipackage available on many Linux distros. File wraptest.c:

```<code>#include <efi.h>
#include <efiapi.h>
#include <efilib.h>
#include <inttypes.h>
#include <stdint.h>

uint8_t *p = (uint8_t *)0xfffffffffffffffcULL;

EFI_STATUS
EFIAPI
efi_main (EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *SystemTable)
{
    uint64_t cr3;

    InitializeLib(ImageHandle, SystemTable);
    asm("mov %%cr3, %0" : "=r"(cr3));
    uint64_t *pml4 = (uint64_t *)(cr3 & ~0xfffULL);

    Print(L"cr3 %lx\n", cr3);
    Print(L"pml4[0] %lx\n", pml4[0]);
    uint64_t *pdpt = (uint64_t *)(pml4[0] & ~0xfffULL);
    Print(L"pdpt[0] %lx\n", pdpt[0]);
    if (!(pdpt[0] & 1)) {
        uefi_call_wrapper(BS->AllocatePages, 4, AllocateAnyPages, \
                          EfiBootServicesData, 1, &pdpt[0]);
        pdpt[0] |= 0x03;
        Print(L"pdpt[0] %lx\n", pdpt[0]);
    }
    uint64_t *pd = (uint64_t *)(pdpt[0] & ~0xfffULL);
    Print(L"pd[0] %lx\n", pd[0]);
    if (!(pd[0] & 1)) {
        uefi_call_wrapper(BS->AllocatePages, 4, AllocateAnyPages, \
                          EfiBootServicesData, 1, &pd[0]);
        pd[0] |= 0x03;
        Print(L"pd[0] %lx\n", pd[0]);
    }
    if (!(pd[0] & 0x80)) {
        uint64_t *pt = (uint64_t *)(pd[0] & ~0xfffULL);
        Print(L"pt[0] %lx\n", pt[0]);
        if (!(pt[0] & 1)) {
            uefi_call_wrapper(BS->AllocatePages, 4, AllocateAnyPages, \
                              EfiBootServicesData, 1, &pt[0]);
            pt[0] |= 0x03;
            Print(L"pt[0] %lx\n", pt[0]);
        }
    }

    Print(L"[0] = %08x\n", *(uint32_t *)(p+4));

    Print(L"pml4[0x1ff] %lx\n", pml4[0x1ff]);
    if (pml4[0x1ff] == 0) {
        uint64_t *pt;
        uefi_call_wrapper(BS->AllocatePages, 4, AllocateAnyPages, \
                          EfiBootServicesData, 4, &pt);
        uint64_t x = (uint64_t)pt;

        Print(L"pt = %lx\n", pt);

        pml4[0x1ff] = x | 0x3;
        pt[0x1ff] = (x + 0x1000) | 0x3;
        pt[0x3ff] = (x + 0x2000) | 0x3;
        pt[0x5ff] = (x + 0x3000) | 0x3;

        *(uint32_t *)p = 0xabcdabcd;
        *(uint32_t *)(p + 4) = 0x12341234;

        Print(L"[0] = %08x\n", *(uint32_t *)(p+4));
        Print(L"[fffffffffffc] = %08x\n", *(uint32_t *)(x + 0x3ffc));

        /* This write should place 0x5678 in the last 16-bit word of memory
         * and 0x5678 at the first 16-bit word in memory. If the wrapping
         * works as expected p[0] should be 0x5678ABCD and
         * p[1] should be 0x12345678 when displayed. */
        *(uint32_t *)(p + 2) = 0x56785678;

        Print(L"p[0] = %08x\n", ((uint32_t *)p)[0]);
        Print(L"p[1] = %08x\n", ((uint32_t *)p)[1]);
    }

    return 0;
}
</code>```

A Makefile that should work on 64-bit Ubuntu and 64-bit Debian could look like this:

```<code>ARCH            ?= $(shell uname -m | sed s,i[3456789]86,ia32,)
ifneq ($(ARCH),x86_64)
LIBDIR          = /usr/lib32
else
LIBDIR          = /usr/lib
endif

OBJS            = wraptest.o
TARGET          = wraptest.efi

EFIINC          = /usr/include/efi
EFIINCS         = -I$(EFIINC) -I$(EFIINC)/$(ARCH) -I$(EFIINC)/protocol
LIB             = $(LIBDIR)
EFILIB          = $(LIBDIR)
EFI_CRT_OBJS    = $(EFILIB)/crt0-efi-$(ARCH).o
EFI_LDS         = $(EFILIB)/elf_$(ARCH)_efi.lds

CFLAGS          = $(EFIINCS) -fno-stack-protector -fpic \
                  -fshort-wchar -mno-red-zone -Wall -O3
ifeq ($(ARCH),x86_64)
  CFLAGS += -DEFI_FUNCTION_WRAPPER
endif

LDFLAGS         = -nostdlib -znocombreloc -T $(EFI_LDS) -shared \
                  -Bsymbolic -L $(EFILIB) -L $(LIB) $(EFI_CRT_OBJS)

all: $(TARGET)

wraptest.so: $(OBJS)
        ld $(LDFLAGS) $(OBJS) -o $@ -lefi -lgnuefi

%.efi: %.so
        objcopy -j .text -j .sdata -j .data -j .dynamic \
                -j .dynsym  -j .rel -j .rela -j .reloc \
                --target=efi-app-$(ARCH) $^ $@
</code>```

The code as written will only work properly if compiled for x86-64. You can make this EFI application with the command:

```<code>make ARCH=x86_64
</code>```

The resulting file should be wraptest.efi that can be copied to your EFI System Partition. The make file was based on Roderick Smith's tutorial

Body:
Is it allowed for a single access to span the bounary between 0 and 0xFFFFFF... in x861?

For example given that eax (rax in 64-bit) is zero, is the following access allowed:

mov ebx, DWORD [eax - 2]

I'm interested in both x86 (32-bit) and x86-64 in case the answers are different.

1 Of course given that the region is mapped in your process etc.

Body:
This is not really a new answer but was too big for a comment. This is @prl's code converted so that it should run with the basic gnu-efipackage available on many Linux distros. File wraptest.c:

#include <efi.h>
#include <efiapi.h>
#include <efilib.h>
#include <inttypes.h>
#include <stdint.h>

uint8_t *p = (uint8_t *)0xfffffffffffffffcULL;

EFI_STATUS
EFIAPI
efi_main (EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *SystemTable)
{
    uint64_t cr3;

    InitializeLib(ImageHandle, SystemTable);
    asm("mov %%cr3, %0" : "=r"(cr3));
    uint64_t *pml4 = (uint64_t *)(cr3 & ~0xfffULL);

    Print(L"cr3 %lx\n", cr3);
    Print(L"pml4[0] %lx\n", pml4[0]);
    uint64_t *pdpt = (uint64_t *)(pml4[0] & ~0xfffULL);
    Print(L"pdpt[0] %lx\n", pdpt[0]);
    if (!(pdpt[0] & 1)) {
        uefi_call_wrapper(BS->AllocatePages, 4, AllocateAnyPages, \
                          EfiBootServicesData, 1, &pdpt[0]);
        pdpt[0] |= 0x03;
        Print(L"pdpt[0] %lx\n", pdpt[0]);
    }
    uint64_t *pd = (uint64_t *)(pdpt[0] & ~0xfffULL);
    Print(L"pd[0] %lx\n", pd[0]);
    if (!(pd[0] & 1)) {
        uefi_call_wrapper(BS->AllocatePages, 4, AllocateAnyPages, \
                          EfiBootServicesData, 1, &pd[0]);
        pd[0] |= 0x03;
        Print(L"pd[0] %lx\n", pd[0]);
    }
    if (!(pd[0] & 0x80)) {
        uint64_t *pt = (uint64_t *)(pd[0] & ~0xfffULL);
        Print(L"pt[0] %lx\n", pt[0]);
        if (!(pt[0] & 1)) {
            uefi_call_wrapper(BS->AllocatePages, 4, AllocateAnyPages, \
                              EfiBootServicesData, 1, &pt[0]);
            pt[0] |= 0x03;
            Print(L"pt[0] %lx\n", pt[0]);
        }
    }

    Print(L"[0] = %08x\n", *(uint32_t *)(p+4));

    Print(L"pml4[0x1ff] %lx\n", pml4[0x1ff]);
    if (pml4[0x1ff] == 0) {
        uint64_t *pt;
        uefi_call_wrapper(BS->AllocatePages, 4, AllocateAnyPages, \
                          EfiBootServicesData, 4, &pt);
        uint64_t x = (uint64_t)pt;

        Print(L"pt = %lx\n", pt);

        pml4[0x1ff] = x | 0x3;
        pt[0x1ff] = (x + 0x1000) | 0x3;
        pt[0x3ff] = (x + 0x2000) | 0x3;
        pt[0x5ff] = (x + 0x3000) | 0x3;

        *(uint32_t *)p = 0xabcdabcd;
        *(uint32_t *)(p + 4) = 0x12341234;

        Print(L"[0] = %08x\n", *(uint32_t *)(p+4));
        Print(L"[fffffffffffc] = %08x\n", *(uint32_t *)(x + 0x3ffc));

        /* This write should place 0x5678 in the last 16-bit word of memory
         * and 0x5678 at the first 16-bit word in memory. If the wrapping
         * works as expected p[0] should be 0x5678ABCD and
         * p[1] should be 0x12345678 when displayed. */
        *(uint32_t *)(p + 2) = 0x56785678;

        Print(L"p[0] = %08x\n", ((uint32_t *)p)[0]);
        Print(L"p[1] = %08x\n", ((uint32_t *)p)[1]);
    }

    return 0;
}

A Makefile that should work on 64-bit Ubuntu and 64-bit Debian could look like this:

ARCH            ?= $(shell uname -m | sed s,i[3456789]86,ia32,)
ifneq ($(ARCH),x86_64)
LIBDIR          = /usr/lib32
else
LIBDIR          = /usr/lib
endif

OBJS            = wraptest.o
TARGET          = wraptest.efi

EFIINC          = /usr/include/efi
EFIINCS         = -I$(EFIINC) -I$(EFIINC)/$(ARCH) -I$(EFIINC)/protocol
LIB             = $(LIBDIR)
EFILIB          = $(LIBDIR)
EFI_CRT_OBJS    = $(EFILIB)/crt0-efi-$(ARCH).o
EFI_LDS         = $(EFILIB)/elf_$(ARCH)_efi.lds

CFLAGS          = $(EFIINCS) -fno-stack-protector -fpic \
                  -fshort-wchar -mno-red-zone -Wall -O3
ifeq ($(ARCH),x86_64)
  CFLAGS += -DEFI_FUNCTION_WRAPPER
endif

LDFLAGS         = -nostdlib -znocombreloc -T $(EFI_LDS) -shared \
                  -Bsymbolic -L $(EFILIB) -L $(LIB) $(EFI_CRT_OBJS)

all: $(TARGET)

wraptest.so: $(OBJS)
        ld $(LDFLAGS) $(OBJS) -o $@ -lefi -lgnuefi

%.efi: %.so
        objcopy -j .text -j .sdata -j .data -j .dynamic \
                -j .dynsym  -j .rel -j .rela -j .reloc \
                --target=efi-app-$(ARCH) $^ $@

The code as written will only work properly if compiled for x86-64. You can make this EFI application with the command:

make ARCH=x86_64

The resulting file should be wraptest.efi that can be copied to your EFI System Partition. The make file was based on Roderick Smith's tutorial


问:
How to use simple-injector with multiple projects and pass to resolve the dependencies
I have 4 projects in my solution,
1. MyApp.UI (MVC)
2. MyApp.Core (ClassLibrary)
3. MyApp.Data (ClassLibrary with EF implementation) and
4. MyApp.Tests

In my Data project I have 4 repository implementations and all 4 repositories are implemented IRepositoryBase interface and their own  repository interface Example,

```<code>public class RepositoryA: IRepositoryBase, IRepositoryA
{
.....
}
public class RepositoryB: IRepositoryBase, IRepositoryB
{
.....
}
</code>```

Now in my Data project I want to create abstract Repository Factory which returns the concrete implementations of corresponding repository interfaces and this class used only inside MyApp.Data project,
For example RepositoryFactory.GetRepository<IRepositoryA>() must returns instance of RepositoryA class or RepositoryFactory.GetRepository<IRepositoryB>() must returns instance of RepositoryB class

My concerns are ,

How I can achieve this ? I want to use RepositoryFactory to get the Repository implementations only inside MyApp.Data project.

Since my UI (MVC) application already doing the boot strap do i need to pass the container to MyApp.Data project or Data project need its own container registration logic?.

I also want to test my MyApp.Data project separately (without UI project dependency).

If possible please give an working code for this scenario.

Thanks in Advance

答:
I found a solution to use AbstractFactory pattern to use in conjunction with simple-injector container class for this problem .

I still not sure whether this is a appropriate solution for this problem

DataRepositoryFactory implementations,

```<code>//Abstract data repository factory
public interface IDataRepositoryFactory
{
    T GetDataRepository<T>() where T : IDataRepository;
}
public class DataRepositoryFactory : IDataRepositoryFactory
{
    T IDataRepositoryFactory.GetDataRepository<T>()
    {
        return (T)DataBootStraper
                 .DataDIContainer
                 .GetInstance(typeof(T));
    }
}
</code>```

in MyApp.Data project I created static Bootstrap class which use to register the data layer dependencies.

```<code>public static class DataBootStraper
{
    public static void BootStrap(Container container)
    {
        container.Register<IRepositoryA, RepositoryA>();
        container.Register<IRepositoryB, RepositoryB>();
        container.Register<IRepositoryC, RepositoryC>();
        //Register the DataRepositoryFactory also with container
        container.Register<IDataRepositoryFactory, DataRepositoryFactory>();
    }
}
</code>```

So this can be called from my Unit test cases as well as UI bootstraper.

Below is the example of the usage of factory

```<code>public class DataRepositoryFactoryTest
{
    private readonly IDataRepositoryFactory _repositoryFactory;
    public DataRepositoryFactoryTest(IDataRepositoryFactory repositoryFactory)
    {
        _repositoryFactory = repositoryFactory;
    }
    public IEnumerable<RepoAEntities> GetEntitiesFromRepoA()
    {
        return _repositoryFactory.GetDataRepository<IRepositoryA>().GetEntities();
    }
    public IEnumerable<RepoBEntities> GetEntitiesFromRepoB()
    {
        return _repositoryFactory.GetDataRepository<IRepositoryB>().GetEntities();
    }
    public IEnumerable<RepoCEntities> GetEntitiesFromRepoC()
    {
        return _repositoryFactory.GetDataRepository<IRepositoryC>().GetEntities();
    }
}
</code>```

Body:
I have 4 projects in my solution,
1. MyApp.UI (MVC)
2. MyApp.Core (ClassLibrary)
3. MyApp.Data (ClassLibrary with EF implementation) and
4. MyApp.Tests

In my Data project I have 4 repository implementations and all 4 repositories are implemented IRepositoryBase interface and their own  repository interface Example,

public class RepositoryA: IRepositoryBase, IRepositoryA
{
.....
}
public class RepositoryB: IRepositoryBase, IRepositoryB
{
.....
}

Now in my Data project I want to create abstract Repository Factory which returns the concrete implementations of corresponding repository interfaces and this class used only inside MyApp.Data project,
For example RepositoryFactory.GetRepository<IRepositoryA>() must returns instance of RepositoryA class or RepositoryFactory.GetRepository<IRepositoryB>() must returns instance of RepositoryB class

My concerns are ,

How I can achieve this ? I want to use RepositoryFactory to get the Repository implementations only inside MyApp.Data project.

Since my UI (MVC) application already doing the boot strap do i need to pass the container to MyApp.Data project or Data project need its own container registration logic?.

I also want to test my MyApp.Data project separately (without UI project dependency).

If possible please give an working code for this scenario.

Thanks in Advance

Body:
I found a solution to use AbstractFactory pattern to use in conjunction with simple-injector container class for this problem .

I still not sure whether this is a appropriate solution for this problem

DataRepositoryFactory implementations,

//Abstract data repository factory
public interface IDataRepositoryFactory
{
    T GetDataRepository<T>() where T : IDataRepository;
}
public class DataRepositoryFactory : IDataRepositoryFactory
{
    T IDataRepositoryFactory.GetDataRepository<T>()
    {
        return (T)DataBootStraper
                 .DataDIContainer
                 .GetInstance(typeof(T));
    }
}

in MyApp.Data project I created static Bootstrap class which use to register the data layer dependencies.

public static class DataBootStraper
{
    public static void BootStrap(Container container)
    {
        container.Register<IRepositoryA, RepositoryA>();
        container.Register<IRepositoryB, RepositoryB>();
        container.Register<IRepositoryC, RepositoryC>();
        //Register the DataRepositoryFactory also with container
        container.Register<IDataRepositoryFactory, DataRepositoryFactory>();
    }
}

So this can be called from my Unit test cases as well as UI bootstraper.

Below is the example of the usage of factory

public class DataRepositoryFactoryTest
{
    private readonly IDataRepositoryFactory _repositoryFactory;
    public DataRepositoryFactoryTest(IDataRepositoryFactory repositoryFactory)
    {
        _repositoryFactory = repositoryFactory;
    }
    public IEnumerable<RepoAEntities> GetEntitiesFromRepoA()
    {
        return _repositoryFactory.GetDataRepository<IRepositoryA>().GetEntities();
    }
    public IEnumerable<RepoBEntities> GetEntitiesFromRepoB()
    {
        return _repositoryFactory.GetDataRepository<IRepositoryB>().GetEntities();
    }
    public IEnumerable<RepoCEntities> GetEntitiesFromRepoC()
    {
        return _repositoryFactory.GetDataRepository<IRepositoryC>().GetEntities();
    }
}


问:
Spring ModelAndView not working with ajax call
Ajax calls a Spring Controller employee_edit but the ModelAndView is not working. It does not redirect to jsp page with object.I want to redirect to the page employee_registration.jsp with the object employee. Code has no error.

Ajax

```<code> $('#example1 tbody').on( 'click', 'button1', function () {
                var eid = table.row( $(this).parents('tr') ).data().eid;
                $.ajax({
                    type:"GET",
                    url:"employee_edit?eid="+eid
                });
</code>```

Controller

```<code>@RequestMapping(value="/employee_edit", method=RequestMethod.GET)
public ModelAndView RegitrationEdit(@RequestParam("eid") long eid)
{
  Employee employee=employeeService.getEmployee(eid);
  ModelAndView mv=new ModelAndView();
  mv.setViewName("employee/employee_registration");
  mv.addObject("employee",employee);
  return mv;
}
</code>```

After running the code it does not show any error. Going through the  code ModelAndView("employee/employee_registration","employee",employee); but nothing happens.
Thanks in advance.

答:
When calling from ajax, ModelAndView will not work. You need to return the employee object as json by marking the the return type with annotation @ResponseBody

```<code>@RequestMapping(value="/employee_edit", method=RequestMethod.GET)
public @ResponseBody Employee RegitrationEdit(@RequestParam("eid") long eid)
{
  Employee employee=employeeService.getEmployee(eid);
  return employee;
}
</code>```

After that upon successful call, you will get the response inside success callback.

```<code>$.ajax({
    type:"GET",
    url:"employee_edit?eid="+eid,
    success: function(data) {
        //here data is the employee object
        //process it here and redirect using window.location
    }
});
</code>```

Body:
Ajax calls a Spring Controller employee_edit but the ModelAndView is not working. It does not redirect to jsp page with object.I want to redirect to the page employee_registration.jsp with the object employee. Code has no error.

Ajax

 $('#example1 tbody').on( 'click', 'button1', function () {
                var eid = table.row( $(this).parents('tr') ).data().eid;
                $.ajax({
                    type:"GET",
                    url:"employee_edit?eid="+eid
                });

Controller

@RequestMapping(value="/employee_edit", method=RequestMethod.GET)
public ModelAndView RegitrationEdit(@RequestParam("eid") long eid)
{
  Employee employee=employeeService.getEmployee(eid);
  ModelAndView mv=new ModelAndView();
  mv.setViewName("employee/employee_registration");
  mv.addObject("employee",employee);
  return mv;
}

After running the code it does not show any error. Going through the  code ModelAndView("employee/employee_registration","employee",employee); but nothing happens.
Thanks in advance.

Body:
When calling from ajax, ModelAndView will not work. You need to return the employee object as json by marking the the return type with annotation @ResponseBody

@RequestMapping(value="/employee_edit", method=RequestMethod.GET)
public @ResponseBody Employee RegitrationEdit(@RequestParam("eid") long eid)
{
  Employee employee=employeeService.getEmployee(eid);
  return employee;
}

After that upon successful call, you will get the response inside success callback.

$.ajax({
    type:"GET",
    url:"employee_edit?eid="+eid,
    success: function(data) {
        //here data is the employee object
        //process it here and redirect using window.location
    }
});


问:
custom child components in angularjs2
I currently developing angular2 application . I would like to know how to add html attributes to custom components.

For example  lets assume i have custom dropdown component and am re-using in same page on many places. If i would like to develop some dropdowns as multiselect and some of them single select, Could you please tell me how to that. If I add mutiple on component template it is showing multiselect for all dropdowns. If I add to each component individually where am using, it is not understanding that "Multiple" attribute.

答:
If i would like to develop some dropdowns as multiselect and some of
  them single select, Could you please tell me how to that.

You should be using a boolean @Input decorator defined in your custom component  (Question seems unclear and i am assuming that you didn't ask for an implementation logic of multi select and single select). Below gives an example of adding a multiselect check for your custom component and how parent should bind value to that attribute when rendering the custom component

In your custom component.ts class

```<code> @Input() multiple: boolean = false;
</code>```

In your custom html class

```<code><div *ngIf="!multiple">
// render your single select html
</div>

<div *ngIf="multiple">
//render your multiple select html
</div>
</code>```

In the parent html while rendering the custom component (assumpe selector as the name of the component)

```<code>// for multi select
<selector [multiple]=true> </select>
// for single select
<selector [multipl]=false> </select>
</code>```

If your struggling to make a generic component supporting both single and multi select check this open source component ng-select

If you have no idea on @Input and @Output decorators in angular2 check this article

Title: custom child components in angularjs2

Body:
If i would like to develop some dropdowns as multiselect and some of
  them single select, Could you please tell me how to that.

You should be using a boolean @Input decorator defined in your custom component  (Question seems unclear and i am assuming that you didn't ask for an implementation logic of multi select and single select). Below gives an example of adding a multiselect check for your custom component and how parent should bind value to that attribute when rendering the custom component

In your custom component.ts class

 @Input() multiple: boolean = false;

In your custom html class

<div *ngIf="!multiple">
// render your single select html
</div>

<div *ngIf="multiple">
//render your multiple select html
</div>

In the parent html while rendering the custom component (assumpe selector as the name of the component)

// for multi select
<selector [multiple]=true> </select>
// for single select
<selector [multipl]=false> </select>

If your struggling to make a generic component supporting both single and multi select check this open source component ng-select

If you have no idea on @Input and @Output decorators in angular2 check this article


问:
Android instance app feature module fails to find a layout resource in the same module
I have the following project structure which I want to convert to a instant apps. The installed project works fine, but when I want to runt the instant app version, the base feature module loads perfectly, but when it comes to the feature module, then it fails to find the resources from its module. When I move the resources from feature module to base module, then it recognizes them with the full package name of the base feature module.

The project structure is the following:
 - app module
 - instant app module

 - base feature module  - com.app.base.feature
 - feature module       - com.app.feature.

in feature module when the resource is located in feature module itself the resources are not found, but they are found when I move the resource into the base feature module and reference them as following com.app.base.feature.R.layout.sample_layout.

EDIT: No known package when getting value for resource number 0x80060009.

Any kind of help would be appreciated :)

答:
The latest build-tools have been patched in with a fix for this issue.

Please update your Android SDK Build-Tools to 27.0.2 version.

Ensure you are on Android Studio 3.0.1 or newer.

The Google issue tracker post regarding the Android Instant Application error crash has also been updated.

Note: Bug link: issuetracker.google.com/issues/62935326 might also be resolved in the latest Android Build-Tools 27.0.2 roll-out, since it is also related to missing/misreferenced resources.


问:
How to display Edittext in Android
I have an EditText that looks like this:

When doing an action in the EditText the background is changed with the following code:

```<code>edtCampo.setBackgroundColor(Color.RED);
</code>```

Then another action is made and the EditText background is changed again with the following code:

```<code>edtCampo.setBackgroundColor(Color.TRANSPARENT);
</code>```

The problem is that in the EditText I do not see the line below, what property should I give to make it look like the first image ?

答:
Try to use,

```<code>android:backgroundTint="@color/red"
</code>```

To achieve pro-grammatically,

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    edt1.setBackgroundTintList(getResources().getColorStateList(R.color.red));
}
</code>```

Result,

Title: How to display Edittext in Android

Body:
I have an EditText that looks like this:

When doing an action in the EditText the background is changed with the following code:

edtCampo.setBackgroundColor(Color.RED);

Then another action is made and the EditText background is changed again with the following code:

edtCampo.setBackgroundColor(Color.TRANSPARENT);

The problem is that in the EditText I do not see the line below, what property should I give to make it look like the first image ?

Body:
Try to use,

android:backgroundTint="@color/red"

To achieve pro-grammatically,

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    edt1.setBackgroundTintList(getResources().getColorStateList(R.color.red));
}

Result,


问:
Meteor app hosted on Cloud9 - How to connect to the MongoDB with Robomongo?
I have an app built with Meteor in Cloud9. And i want to connect to the MongoDB database of the the app using Robomongo, but i cant get it working..

I run the app by typing "meteor --port $IP:$PORT", and it runs ok.

When i type "meteor mongo" in the Cloud9 terminal it shows:

So i figure the MongoDB is running on port 8081?

Then on Robomongo, i enter the actual app URL and port, but it fails.

This is the error i get:

And this is when i click "Show error details":

答:
Remove the fully qualified URL from the address. In your case, only have meteor-appname-username.c9users.io instead of https://meteor-appname-username.c9users.io/

In the advanced tab, give in the default database name (in your case: meteor)

Source


问:
What is the idiomatic way to compare two lists for equality?
I have two lists I need to check whether their elements are equal (not shallow check, for elements I might rely on Kernel.==/2.)

Currently, I have:

```<code>[l1 -- l2] ++ [l2 -- l1] == []
</code>```

It looks a bit overcomplicated and not quite idiomatic to me. Am I missing something? Is there a better way to compare two lists for equality?

答:
Dogbert's solution is apt, but it is still in Orcish.

In Erlang this would be:

```<code>lists:sort(List1) == lists:sort(List2)
</code>```

A deep comparison looks very nearly the same, but of course must traverse the structures within each list.

One factor to consider is that very often the ordering of a list is its meaning. Strings are a good example, so are player ranks, start positions, game hotkey locations, and last-used-longest-kept cache lists. So do keep in mind the meaning of the comparison: "Do these two lists contain the same number and type of things?" is not the same as "Are these two lists semantically identical?"

Consider comparing anagrams:

```<code>lists:sort("AT ERR GET VICE") == lists:sort("IT ERR ETC GAVE")
</code>```

That works fine as an anagram comparison, but not at all as a semantic one.

Body:
I have two lists I need to check whether their elements are equal (not shallow check, for elements I might rely on Kernel.==/2.)

Currently, I have:

[l1 -- l2] ++ [l2 -- l1] == []

It looks a bit overcomplicated and not quite idiomatic to me. Am I missing something? Is there a better way to compare two lists for equality?

Body:
Dogbert's solution is apt, but it is still in Orcish.

In Erlang this would be:

lists:sort(List1) == lists:sort(List2)

A deep comparison looks very nearly the same, but of course must traverse the structures within each list.

One factor to consider is that very often the ordering of a list is its meaning. Strings are a good example, so are player ranks, start positions, game hotkey locations, and last-used-longest-kept cache lists. So do keep in mind the meaning of the comparison: "Do these two lists contain the same number and type of things?" is not the same as "Are these two lists semantically identical?"

Consider comparing anagrams:

lists:sort("AT ERR GET VICE") == lists:sort("IT ERR ETC GAVE")

That works fine as an anagram comparison, but not at all as a semantic one.


问:
php show array value for variable key
I am trying to make a site multi lingual. by building a language dictionary array ( if it is not the best way please don't hesitate to let me know )

```<code>$fr=array();

$fr['hello']="Bonjour";
</code>```

I would like to make a function that does the following :

for every word and language  function ( $word ="hello",$language="fr")

it would return the right value. So far the way I am doing isn't working

```<code>echo $$language[$word];
</code>```

any ideas?
thank you

答:
$$language[$word] didn't work

the work around was

$arr=$$language;

$arr[$word];

Title: php show array value for variable key

Body:
I am trying to make a site multi lingual. by building a language dictionary array ( if it is not the best way please don't hesitate to let me know )

$fr=array();

$fr['hello']="Bonjour";

I would like to make a function that does the following :

for every word and language  function ( $word ="hello",$language="fr")

it would return the right value. So far the way I am doing isn't working

echo $$language[$word];

any ideas?
thank you


问:
Replace placeholder text in embedded javascript code
I have a pop-up window (it's a mailchimp singup pop-up) and there is placeholder text I would like to replace. This could theoretically be done with jquery text function, but the problem is the pop up is embeded to the site with this code

```<code><script type="text/javascript" src="//downloads.mailchimp.com/js/signup-forms/popup/embed.js" data-dojo-config="usePlainJson: true, isDebug: false"></script>
<script type="text/javascript">require(["mojo/signup-forms/Loader"], function(L) { L.start({"baseUrl":"mc.us15.list-manage.com","uuid":"9f9db56c3e8da76e10b1d9c12","lid":"9aabbe0a76"}) })</script>
</code>```

This means there's no actual markup in the code to target and I'm not sure jquery can work this way. Code that is generated is

```<code><input type="email" name="EMAIL" value="" id="mc-EMAIL" placeholder="Enter your email">
</code>```

and I need to replace the placeholder text for something else.

Any help would be appreciated

答:
Try this , If you just want to change the placeholder you can write following JQuery code</p>

```<code>$("#mc-EMAIL").attr("placeholder","Your Placeholder.... ");
</code>```

Body:
I have a pop-up window (it's a mailchimp singup pop-up) and there is placeholder text I would like to replace. This could theoretically be done with jquery text function, but the problem is the pop up is embeded to the site with this code

This means there's no actual markup in the code to target and I'm not sure jquery can work this way. Code that is generated is

<input type="email" name="EMAIL" value="" id="mc-EMAIL" placeholder="Enter your email">

and I need to replace the placeholder text for something else.

Any help would be appreciated

Body:
Try this , If you just want to change the placeholder you can write following JQuery code

$("#mc-EMAIL").attr("placeholder","Your Placeholder.... ");


问:
Onclick function button inside a javascript
I want to direct the button to another page

```<code>function showInput() {
    document.getElementById("demo").innerHTML = '<input type="submit"
    onclick="location.href = "addnewcustomer.php";" id ="newcust"
    class="btnRegister" value = "New Customer">';
}
</code>```

I want when i click the New Customer button, it will redirect to addnewcustomer.php but when i run the code, nothing happened.

There are no errors. Just the button didn't function the way i want it to

答:
Try the code below, the inner html text is missing with escape string. Call window.onload to trigger your method and display your button. HTH.</p>

```<code><head>
<script type="text/javascript">
    function showInput() {
        document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = \'addnewcustomer.php\';" id ="newcust" class="btnRegister" value = "New Customer">';
    }
    window.onload = showInput;
    </script>
</head>
<body>
<p id="demo"></p>
</body>
</code>```

Body:
I want to direct the button to another page

function showInput() {
    document.getElementById("demo").innerHTML = '<input type="submit"
    onclick="location.href = "addnewcustomer.php";" id ="newcust"
    class="btnRegister" value = "New Customer">';
}

I want when i click the New Customer button, it will redirect to addnewcustomer.php but when i run the code, nothing happened.

There are no errors. Just the button didn't function the way i want it to

Body:
Try the code below, the inner html text is missing with escape string. Call window.onload to trigger your method and display your button. HTH.

<head>
<script type="text/javascript">
    function showInput() {
        document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = \'addnewcustomer.php\';" id ="newcust" class="btnRegister" value = "New Customer">';
    }
    window.onload = showInput;
    </script>
</head>
<body>
<p id="demo"></p>
</body>


问:
Bankers algorithm in cobol
The issue I am getting is that line COLUMNS that i define in the working storage
section and when it is used within the 200-BANKER-FILL section is giving me a
syntax error in which COLUMNS is unexpected. the actual error is

'error: syntax error, unexpected COLUMNS'

I cannot seem to understand how the declaration of COLUMNS within the working storage section would be considered unexpected, any help would be great

```<code>   IDENTIFICATION DIVISION.
   PROGRAM-ID.BankerAlgoritm.
   ENVIRONMENT DIVISION.
   INPUT-OUTPUT SECTION.
   FILE-CONTROL.
       SELECT BANKER-FILE-IN  ASSIGN TO 's1.txt'
           ORGANIZATION IS LINE SEQUENTIAL.

   *> FUNCTION NUMVAL (STRING)

   DATA DIVISION.
   FILE SECTION.
   FD  BANKER-FILE-IN.
   01  BANKER-LINE                   PIC X(9).
   WORKING-STORAGE SECTION.
   01  ARE-THERE-MORE-RECORDS        PIC X(3)        VALUE 'YES'.
           88  NO-MORE-RECORDS                       VALUE 'NO '.
   01  ROWS                          PIC 9.
   01  COLUMNS                       PIC 9.
   01   BANKER-TABLE-ASSIGN.
        05   ASSIGN-ROW OCCURS 5 TIMES INDEXED BY X.
            10   ASSIGN-COLUMN OCCURS 4 TIMES INDEXED BY Y.
                20  ASSIGN-RESOURCE         PIC 9.
   01   BANKER-TABLE-MAX.
        05   MAX-ROW OCCURS 5 TIMES INDEXED BY X.
            10   MAX-COLUMN OCCURS 4 TIMES INDEXED BY Y.
                20  MAX-RESOURCE         PIC 9.
   01   BANKER-TABLE-AVAL.
        05   AVAL-COLUMN OCCURS 4 TIMES INDEXED BY Y.
            10  AVAL-RESOURCE            PIC 9.
   01   BANKER-TABLE-REQUEST.
        05   REQUEST-COLUMN OCCURS 4 TIMES INDEXED BY Y.
            10  REQUEST-RESOURCE         PIC 9.
   01   BANKER-REQUEST-LINE.
        05  REQUEST-LINE                 PIC 9.
        05  SPACER                       PIC X.
        05  REQUEST-ONE                  PIC 9.
        05                               PIC X.
        05  REQUEST-TWO                  PIC 9.
        05                               PIC X.
        05  REQUEST-THREE                PIC 9.
        05                               PIC X.
        05  REQUEST-FOUR                 PIC 9.
   01   MATRIX.
        05  ONE                          PIC 9.
        05                               PIC X.
        05  TWO                          PIC 9.
        05                               PIC X.
        05  THREE                        PIC 9.
        05                               PIC X.
        05  FOUR                         PIC 9.
   01   HOLDING-VAL-SINGLE               PIC 9.
   01   LINE-COUNT                       PIC 99 VALUE 0.
   01   SAFE-STATE                       PIC XXXXX VALUE 'FALSE'.
   PROCEDURE DIVISION.
  *>****************************************
  *>  Controls direction of program logic  *
  *>  and reads the first record.          *
  *>****************************************
   100-MAIN-MODULE.
       PERFORM UNTIL NO-MORE-RECORDS
           READ BANKER-FILE-IN
               AT END
                 MOVE 'NO ' TO ARE-THERE-MORE-RECORDS
               NOT AT END
                 PERFORM 200-BANKER-FILL
           END-READ
       END-PERFORM
      *> PERFORM 300-FILL-NEED
      *> PERFORM 400-SAFE-STATE
      *>IF SAFE-STATE = 'TRUE'
        *>  PERFORM 500-REQUEST
    *>   PERFORM 600-END-OF-JOB-RTN
       STOP RUN.
  200-BANKER-FILL.
        ADD 1 TO LINE-COUNT
        IF LINE-COUNT IS EQUAL TO 1
            MOVE BANKER-LINE TO ROWS
        END-IF
        IF LINE-COUNT IS EQUAL TO 3
            MOVE BANKER-LINE TO COLUMNS
        END-IF
        IF LINE-COUNT >= 5 AND <= 10
        *>FILL ASSIGNED MATRIX
            MOVE BANKER-LINE TO MATRIX
            MOVE ONE TO ASSIGN-COLUMN(LINE-COUNT - 4, 1)
            MOVE TWO TO ASSIGN-COLUMN(LINE-COUNT - 4, 2)
            MOVE THREE TO ASSIGN-COLUMN(LINE-COUNT - 4, 3)
            MOVE FOUR TO ASSIGN-COLUMN(LINE-COUNT - 4, 4)
        END-IF
        IF LINE-COUNT >= 12 AND <= 17
        *>FILL IN MAX MATRIX
            MOVE BANKER-LINE TO MATRIX
            MOVE ONE TO MAX-COLUMN(LINE-COUNT - 11, 1)
            MOVE TWO TO MAX-COLUMN(LINE-COUNT - 11, 2)
            MOVE THREE TO MAX-COLUMN(LINE-COUNT - 11, 3)
            MOVE FOUR TO MAX-COLUMN(LINE-COUNT - 11, 4)
        END-IF
        IF LINE-COUNT = 19
        *> FILL IN AVAILIBLE MATRIX
            MOVE BANKER-LINE TO MATRIX
            MOVE ONE TO AVAL-COLUMN(1)
            MOVE TWO TO AVAL-COLUMN(2)
            MOVE THREE TO AVAL-COLUMN(3)
            MOVE FOUR TO AVAL-COLUMN(4)
        END-IF
        IF LINE-COUNT = 21
        *> FILL IN REQUEST
            MOVE BANKER-LINE TO BANKER-REQUEST-LINE
        END-IF.
  *>*************************************************
  *>  Performed from 100-MAIN-MODULE. Closes files  *
  *>*************************************************
   600-END-OF-JOB-RTN.
       CLOSE BANKER-FILE-IN.
</code>```

the next part is the input file

```<code>5

4

0 0 1 2
1 0 0 0
1 3 5 4
0 6 3 2
0 0 1 4

0 0 1 2
1 7 5 0
2 3 5 6
0 6 5 2
0 6 5 6

1 5 2 0

1:0 4 2 0
</code>```

答:
COLUMN is a reserved word in COBOL.
Here is a list of reserved words for future reference.</p>

Title: Bankers algorithm in cobol

Body:
The issue I am getting is that line COLUMNS that i define in the working storage
section and when it is used within the 200-BANKER-FILL section is giving me a
syntax error in which COLUMNS is unexpected. the actual error is

'error: syntax error, unexpected COLUMNS'

I cannot seem to understand how the declaration of COLUMNS within the working storage section would be considered unexpected, any help would be great

   IDENTIFICATION DIVISION.
   PROGRAM-ID.BankerAlgoritm.
   ENVIRONMENT DIVISION.
   INPUT-OUTPUT SECTION.
   FILE-CONTROL.
       SELECT BANKER-FILE-IN  ASSIGN TO 's1.txt'
           ORGANIZATION IS LINE SEQUENTIAL.

   *> FUNCTION NUMVAL (STRING)

   DATA DIVISION.
   FILE SECTION.
   FD  BANKER-FILE-IN.
   01  BANKER-LINE                   PIC X(9).
   WORKING-STORAGE SECTION.
   01  ARE-THERE-MORE-RECORDS        PIC X(3)        VALUE 'YES'.
           88  NO-MORE-RECORDS                       VALUE 'NO '.
   01  ROWS                          PIC 9.
   01  COLUMNS                       PIC 9.
   01   BANKER-TABLE-ASSIGN.
        05   ASSIGN-ROW OCCURS 5 TIMES INDEXED BY X.
            10   ASSIGN-COLUMN OCCURS 4 TIMES INDEXED BY Y.
                20  ASSIGN-RESOURCE         PIC 9.
   01   BANKER-TABLE-MAX.
        05   MAX-ROW OCCURS 5 TIMES INDEXED BY X.
            10   MAX-COLUMN OCCURS 4 TIMES INDEXED BY Y.
                20  MAX-RESOURCE         PIC 9.
   01   BANKER-TABLE-AVAL.
        05   AVAL-COLUMN OCCURS 4 TIMES INDEXED BY Y.
            10  AVAL-RESOURCE            PIC 9.
   01   BANKER-TABLE-REQUEST.
        05   REQUEST-COLUMN OCCURS 4 TIMES INDEXED BY Y.
            10  REQUEST-RESOURCE         PIC 9.
   01   BANKER-REQUEST-LINE.
        05  REQUEST-LINE                 PIC 9.
        05  SPACER                       PIC X.
        05  REQUEST-ONE                  PIC 9.
        05                               PIC X.
        05  REQUEST-TWO                  PIC 9.
        05                               PIC X.
        05  REQUEST-THREE                PIC 9.
        05                               PIC X.
        05  REQUEST-FOUR                 PIC 9.
   01   MATRIX.
        05  ONE                          PIC 9.
        05                               PIC X.
        05  TWO                          PIC 9.
        05                               PIC X.
        05  THREE                        PIC 9.
        05                               PIC X.
        05  FOUR                         PIC 9.
   01   HOLDING-VAL-SINGLE               PIC 9.
   01   LINE-COUNT                       PIC 99 VALUE 0.
   01   SAFE-STATE                       PIC XXXXX VALUE 'FALSE'.
   PROCEDURE DIVISION.
  *>****************************************
  *>  Controls direction of program logic  *
  *>  and reads the first record.          *
  *>****************************************
   100-MAIN-MODULE.
       PERFORM UNTIL NO-MORE-RECORDS
           READ BANKER-FILE-IN
               AT END
                 MOVE 'NO ' TO ARE-THERE-MORE-RECORDS
               NOT AT END
                 PERFORM 200-BANKER-FILL
           END-READ
       END-PERFORM
      *> PERFORM 300-FILL-NEED
      *> PERFORM 400-SAFE-STATE
      *>IF SAFE-STATE = 'TRUE'
        *>  PERFORM 500-REQUEST
    *>   PERFORM 600-END-OF-JOB-RTN
       STOP RUN.
  200-BANKER-FILL.
        ADD 1 TO LINE-COUNT
        IF LINE-COUNT IS EQUAL TO 1
            MOVE BANKER-LINE TO ROWS
        END-IF
        IF LINE-COUNT IS EQUAL TO 3
            MOVE BANKER-LINE TO COLUMNS
        END-IF
        IF LINE-COUNT >= 5 AND <= 10
        *>FILL ASSIGNED MATRIX
            MOVE BANKER-LINE TO MATRIX
            MOVE ONE TO ASSIGN-COLUMN(LINE-COUNT - 4, 1)
            MOVE TWO TO ASSIGN-COLUMN(LINE-COUNT - 4, 2)
            MOVE THREE TO ASSIGN-COLUMN(LINE-COUNT - 4, 3)
            MOVE FOUR TO ASSIGN-COLUMN(LINE-COUNT - 4, 4)
        END-IF
        IF LINE-COUNT >= 12 AND <= 17
        *>FILL IN MAX MATRIX
            MOVE BANKER-LINE TO MATRIX
            MOVE ONE TO MAX-COLUMN(LINE-COUNT - 11, 1)
            MOVE TWO TO MAX-COLUMN(LINE-COUNT - 11, 2)
            MOVE THREE TO MAX-COLUMN(LINE-COUNT - 11, 3)
            MOVE FOUR TO MAX-COLUMN(LINE-COUNT - 11, 4)
        END-IF
        IF LINE-COUNT = 19
        *> FILL IN AVAILIBLE MATRIX
            MOVE BANKER-LINE TO MATRIX
            MOVE ONE TO AVAL-COLUMN(1)
            MOVE TWO TO AVAL-COLUMN(2)
            MOVE THREE TO AVAL-COLUMN(3)
            MOVE FOUR TO AVAL-COLUMN(4)
        END-IF
        IF LINE-COUNT = 21
        *> FILL IN REQUEST
            MOVE BANKER-LINE TO BANKER-REQUEST-LINE
        END-IF.
  *>*************************************************
  *>  Performed from 100-MAIN-MODULE. Closes files  *
  *>*************************************************
   600-END-OF-JOB-RTN.
       CLOSE BANKER-FILE-IN.

the next part is the input file

5

4

0 0 1 2
1 0 0 0
1 3 5 4
0 6 3 2
0 0 1 4

0 0 1 2
1 7 5 0
2 3 5 6
0 6 5 2
0 6 5 6

1 5 2 0

1:0 4 2 0


问:
Nested Listview with vertical Alignment
I want to show nested listview in a manner that the sub items of main item should display on right side of Main Items. And subitems should display if user clicks on any Main items only.

```<code> <ListView x:Name="list1" Background="Blue" Width="200" Height="300" VerticalAlignment="Bottom">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:Main">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>
                    <TextBlock Text="{x:Bind ItemName}" />
                    <ListView x:Name="list2" ItemsSource="{x:Bind SubItemsList}" Grid.Row="1">
                        <ListView.ItemTemplate>
                            <DataTemplate x:DataType="local:Sub">
                                <TextBlock Foreground="Red" Text="{x:Bind SubItemName}"/>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</code>```

When using above code I'm getting Main items in a row and it's subitems in another row.

```<code>Main 1
 Sub 1
 Sub 1
Main 2
 Sub 2
 Sub 2
</code>```

But my output should be

```<code>Main Items    Sub Items
Main 1        Sub 1
              Sub 1
Main 2        Sub 2
              Sub 2
</code>```

If user clicks on Main 1, it should display its Sub items and so on. otherwise no need to display Sub Items. Is it possible by making any changes on above code?

答:
You have to use FlyoutMenu control for that, as the requirement you are asking cannot be fulfilled by using a ListView. A ListView will display all the Main and SubItems irrespective of it being clicked or not. A FlyoutMenu, however, works exactly as you have asked here. It displays the SubItems on being clicked, with the provision to display it on the right side (or any side you choose to).

The microsoft link for the basic idea of Flyout menu

A video tutorial to get you up and running with it right away

Hope this helped you !!

Title: Nested Listview with vertical Alignment

Body:
I want to show nested listview in a manner that the sub items of main item should display on right side of Main Items. And subitems should display if user clicks on any Main items only.

 <ListView x:Name="list1" Background="Blue" Width="200" Height="300" VerticalAlignment="Bottom">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:Main">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>
                    <TextBlock Text="{x:Bind ItemName}" />
                    <ListView x:Name="list2" ItemsSource="{x:Bind SubItemsList}" Grid.Row="1">
                        <ListView.ItemTemplate>
                            <DataTemplate x:DataType="local:Sub">
                                <TextBlock Foreground="Red" Text="{x:Bind SubItemName}"/>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

When using above code I'm getting Main items in a row and it's subitems in another row.

Main 1
 Sub 1
 Sub 1
Main 2
 Sub 2
 Sub 2

But my output should be

Main Items    Sub Items
Main 1        Sub 1
              Sub 1
Main 2        Sub 2
              Sub 2

If user clicks on Main 1, it should display its Sub items and so on. otherwise no need to display Sub Items. Is it possible by making any changes on above code?


问:
Create Custom Scroll Bar in Android Wear 2.0
Is there any way to create a WearableRecyclerView with a custom scroll bar in Android Wear 2.0 like this?

答:
To create a curved layout for scrollable items in your wearable app check below link:

https://developer.android.com/training/wearables/ui/lists.html#creating

use

val layoutManager = CurvedChildLayoutManager(this)
recyclerView.layoutManager = layoutManager

PS: as for topic question, you dont need app:layout_box just use android:scrollbars="vertical" on your WearableRecyclerView

https://developer.android.com/reference/android/support/wearable/view/CurvedChildLayoutManager.html


问:
Promo Code Validation
I need to validate a Promo Code for one of my html Booking form field. If the entered promo code is correct, users can submit the Booking details. Only one unique promo code. Something like "15OFFNOW" How should I do it? Please help.

Thanks.

答:
First, don't put the promo code in your page. Anyone can see it.

I would do this, but it depends on actually functionality.

Do client side check (this can be bypassed by a malicious user)

Do server side check

Do client side check

Use a good non-reversible hashing algorithm and verify what you have in the prom text box to the hash you have stored in a JavaScript variable or in a data-hash attribute.

So if hash(text box value) == valueOf(data-hash), then proceed to sever validation.

Do server side check

In server no need of hash. Just check the post string with the promo code you have.

Title: Promo Code Validation


问:
Filtering out top_hits subaggregation based on total documents
I'm doing map clustering using Elasticsearch GeoHash grid aggregation.
The query returns on average 100-200 buckets.
Each of the bucket uses the top_hits aggregation which I use to return 3 documents for each aggregated cluster.

The problem is that I want to return top_hits only when the parent aggregation (GeoHash) aggregates no more than 3 documents.

If a cluster aggregates more than 3 documents I don't want ES to return any documents for this cluster (because I'm not gonna use them).

I've tried to use Bucket Selector Aggregation, but didn't manage to construct a correct bucket_path.
I use bucket selector aggregation on the same level as top_hits aggregation.
The number of total documents for a bucket is available at top_hits.hits.total but what I'm getting is reason=path not supported for [top_hits]: [hits.total].

Is this possible in elasticsearch?
It's important for me, because in most of the queries only small percentage of buckets will have less than 3 documents. But top hits subaggregation is always returning top 3 documents even for clusters of 1000 documents.
If a result of a query return 200 buckets and only 5 of them are aggregating <= 3 documents so I want to return only 5*3 documents, not 200*3 (Te response is 10MB in this case).

Here is the aggs part of my query:

```<code>"clusters": {
  "geohash_grid": {
    "field": "coordinates",
    "precision": 3
  },
  "aggs": {
    "top_hits": {
      "top_hits": {
        "size": 3
      }
    },
    "top_hits_filter": {
      "bucket_selector": {
        "buckets_path": {
          "total_hits": "top_hits._count" // tried top_hits.hits.total
        },
        "script": {
          "inline": "total_hits <= 3"
        }
      }
    }
  }
}
</code>```

答:
Try this @ilivewithian :</p>

```<code>  "aggs": {
    "clusters": {
      "geohash_grid": {
        "field": "coordinates",
        "precision": 3
      },
      "aggs": {
        "top_hits": {
          "top_hits": {
            "size": 3
          }
        },
        "top_hits_filter": {
          "bucket_selector": {
            "buckets_path": {
              "total_hits": "_count"
            },
            "script": {
              "inline": "params.total_hits <= 3"
            }
          }
        }
      }
    }
  }
</code>```

Body:
I'm doing map clustering using Elasticsearch GeoHash grid aggregation.
The query returns on average 100-200 buckets.
Each of the bucket uses the top_hits aggregation which I use to return 3 documents for each aggregated cluster.

The problem is that I want to return top_hits only when the parent aggregation (GeoHash) aggregates no more than 3 documents.

If a cluster aggregates more than 3 documents I don't want ES to return any documents for this cluster (because I'm not gonna use them).

I've tried to use Bucket Selector Aggregation, but didn't manage to construct a correct bucket_path.
I use bucket selector aggregation on the same level as top_hits aggregation.
The number of total documents for a bucket is available at top_hits.hits.total but what I'm getting is reason=path not supported for [top_hits]: [hits.total].

Is this possible in elasticsearch?
It's important for me, because in most of the queries only small percentage of buckets will have less than 3 documents. But top hits subaggregation is always returning top 3 documents even for clusters of 1000 documents.
If a result of a query return 200 buckets and only 5 of them are aggregating <= 3 documents so I want to return only 5*3 documents, not 200*3 (Te response is 10MB in this case).

Here is the aggs part of my query:

"clusters": {
  "geohash_grid": {
    "field": "coordinates",
    "precision": 3
  },
  "aggs": {
    "top_hits": {
      "top_hits": {
        "size": 3
      }
    },
    "top_hits_filter": {
      "bucket_selector": {
        "buckets_path": {
          "total_hits": "top_hits._count" // tried top_hits.hits.total
        },
        "script": {
          "inline": "total_hits <= 3"
        }
      }
    }
  }
}

Body:
Try this @ilivewithian :

  "aggs": {
    "clusters": {
      "geohash_grid": {
        "field": "coordinates",
        "precision": 3
      },
      "aggs": {
        "top_hits": {
          "top_hits": {
            "size": 3
          }
        },
        "top_hits_filter": {
          "bucket_selector": {
            "buckets_path": {
              "total_hits": "_count"
            },
            "script": {
              "inline": "params.total_hits <= 3"
            }
          }
        }
      }
    }
  }


问:
Which one to go first, Grails or Groovy?
I wanted to create a web application. I thought of selecting Groovy or Grails. But I don't know from where to start! To start with Groovy or Grails?</p>

答:
As a learner like you, here is what I've got in few last weeks.

Even if you're familiar with Java, Grails auto-generates templates of code, and knowing Groovy syntax helps to understand it better.

I very suggest books by Scott Davis, they are just brilliant -- short, clear, and straightforward.
Start from "Groovy Recipes", and then take a look at "Getting Started with Grails".

Gaelyk is good for some very custom webapps, but if you're doing ordinary dynamic website, then too much code has to be written manually, and from scratch. Grails provides much more help here.


问:
SQL Server : SELECT * FROM [dbo].[Table] WHERE
I'm new to SQL Server, and I'm trying to select a range between two dates.

My column is varchar (format: dd.mm.yyyy hh:mm:ss), but if I use

```<code>SELECT *
FROM [dbo].[Table]
WHERE [Column] BETWEEN 'lower date' AND 'max date'
</code>```

the result is every date that begins with the first two search option. In my case "dd" (dd.mm.yyyy hh:mm:ss).

Is there a solution, without changing the column from varchar to datetime?

答:
Is there a solution, without changing the column from varchar to datetime?

It depends what you mean by this statement. All the other answers here work by changing the column data from string to datetime every time the query is run, and doing this every time this is massively resource wasteful and needlessly slow compared to the correct alternative.

If you want a solution that doesn't mention the word datetime at all (I.e. By "without changing the column" means no type conversion of the column data shall be performed) then you're going to have to use  SUBSTR to cut your string up and rearrange it to be yyyymmddhhmmss or similar, then it will work for a BETWEEN with string arguments of dates. But even doing that is manipulating table data which automatically means indexes become unusable. The whole purpose of an index is to make searches lookups quick; here you're going out of your way to defeat that mechanism and make your lookups slow, while clearly writing code whose only purpose is to perform a lookup - building poor performance into an application should be avoided, because you may reach a state one day where fixing it is very hard indeed

If all you're trying to do is avoid converting the data type of the column, even though you appreciate that's what you should be doing, I beg you not to do this - you've stated you're new, and learning. You've a responsibility to yourself and to all the users of your software to learn how to do it right, from the start. Please don't be another one of those coders who takes some poor quality way out and end up writing a system  with serious performance and security flaws (this case isn't necessarily a security risk, but if this apparent lack of a desire to do things properly one day also extends to security considerations, that's an even bigger problem)

Ultimately the real answer here, as I've no doubt detected I'm passionate that you implement, is to add another column to your table, use any one of these answers to run an update statement that populates the new column with the datetime equivalent of the string data, and drop the old column. Answers that solve a problem as stated often only invest in the immediate context; I'm hoping to invest in your software engineering future

Body:
I'm new to SQL Server, and I'm trying to select a range between two dates.

My column is varchar (format: dd.mm.yyyy hh:mm:ss), but if I use

SELECT *
FROM [dbo].[Table]
WHERE [Column] BETWEEN 'lower date' AND 'max date'

the result is every date that begins with the first two search option. In my case "dd" (dd.mm.yyyy hh:mm:ss).

Is there a solution, without changing the column from varchar to datetime?