问:
How can I update keycloak's user details programmatically (java), without using rest admin api?
I want to update the user detail. e.g. I created user(k1) in "demo" realm from keycloak admin console. I have one java client and I want to update the user(k1) details like. Change Email address of user k1.

I did using Admin client(Rest API) as below.

```<code>public void updateEmail(final String newEmailAddress) {
    try {
        final AccessToken accessToken = getToken();
        Keycloak keycloak = KeycloakBuilder.builder().serverUrl(this.getDeployment().getAuthServerBaseUrl())
                .realm(this.getDeployment().getRealm()).username("k1").password("123").clientId(ADMIN_CLIENT)
                .resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build()).build();

        UserResource userResource = keycloak.realm(this.getDeployment().getRealm()).users()
                .get(accessToken.getSubject());
        UserRepresentation user = userResource.toRepresentation();
        user.setEmail(newEmailAddress);
        userResource.update(user);

    } catch (Exception exception) {
        exception.printStackTrace();
    }
}
</code>```

But I want do the same without using Admin client.

答:
you can use jsoup-1.6.0.jar for updating any user's detail as follow.

```<code>public boolean updateAccountDetails(String name, String value)
{
String url= getKeycloakAdapter().getDeployment().getAccountUrl();

Document document = Jsoup.connect(url).get();
if (document != null) {
  String formQuery = String.format("form[action^=%s]", url);
  Elements form = document.select(formQuery);
  if (!form.isEmpty()) {
    Elements inputs = form.select("input[value], input:not([disabled])");
    Element saveAction = form.select("button[value=Save]").first();
    inputs.add(saveAction);
    Map<String, String> mandatoryArguments = new HashMap<>();
    for (Element input : inputs) {
      mandatoryArguments.put(input.attr("name"), input.attr("value"));
    }
    mandatoryArguments.put(attributeName, newValue);
    Response response = Jsoup.connect(accountUrl)
        .data(mandatoryArguments)
        .method(Method.POST)
        .execute();

    Document finalDoc = response.parse();
    if (finalDoc != null) {
      Elements finalForm = finalDoc.select(formQuery);
      if (finalForm != null) {
        String newValueQuery = String.format("input[name=%s], input[value=%s]", name, value);
        Elements finalInputs = finalForm.select(newValueQuery);
        if (finalInputs != null) {
          return !finalInputs.isEmpty();
        }
      }
    }
  }
}
throw new IOException("Account page not found");
</code>```

}

Body:
I want to update the user detail. e.g. I created user(k1) in "demo" realm from keycloak admin console. I have one java client and I want to update the user(k1) details like. Change Email address of user k1.

I did using Admin client(Rest API) as below.

public void updateEmail(final String newEmailAddress) {
    try {
        final AccessToken accessToken = getToken();
        Keycloak keycloak = KeycloakBuilder.builder().serverUrl(this.getDeployment().getAuthServerBaseUrl())
                .realm(this.getDeployment().getRealm()).username("k1").password("123").clientId(ADMIN_CLIENT)
                .resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build()).build();

        UserResource userResource = keycloak.realm(this.getDeployment().getRealm()).users()
                .get(accessToken.getSubject());
        UserRepresentation user = userResource.toRepresentation();
        user.setEmail(newEmailAddress);
        userResource.update(user);

    } catch (Exception exception) {
        exception.printStackTrace();
    }
}

But I want do the same without using Admin client.

Body:
you can use jsoup-1.6.0.jar for updating any user's detail as follow.

public boolean updateAccountDetails(String name, String value)
{
String url= getKeycloakAdapter().getDeployment().getAccountUrl();

Document document = Jsoup.connect(url).get();
if (document != null) {
  String formQuery = String.format("form[action^=%s]", url);
  Elements form = document.select(formQuery);
  if (!form.isEmpty()) {
    Elements inputs = form.select("input[value], input:not([disabled])");
    Element saveAction = form.select("button[value=Save]").first();
    inputs.add(saveAction);
    Map<String, String> mandatoryArguments = new HashMap<>();
    for (Element input : inputs) {
      mandatoryArguments.put(input.attr("name"), input.attr("value"));
    }
    mandatoryArguments.put(attributeName, newValue);
    Response response = Jsoup.connect(accountUrl)
        .data(mandatoryArguments)
        .method(Method.POST)
        .execute();

    Document finalDoc = response.parse();
    if (finalDoc != null) {
      Elements finalForm = finalDoc.select(formQuery);
      if (finalForm != null) {
        String newValueQuery = String.format("input[name=%s], input[value=%s]", name, value);
        Elements finalInputs = finalForm.select(newValueQuery);
        if (finalInputs != null) {
          return !finalInputs.isEmpty();
        }
      }
    }
  }
}
throw new IOException("Account page not found");

}


来源: stackexchange

问:
EF Core LINQ exclude column from included entity
I'm using ASP.Net Core 2.0 with Entity Framework and I am trying to return a model to a page that contains the Employment entity with it's collection of EmploymentDocument entities also included. For the latter I do not want to load the data (byte[]) column but I do want all the other columns, most importantly FileName.

The linq query I have which loads everything including the data column is:

```<code>var employment = await _context.Employment
    .Include(e => e.EmploymentDocuments) // will load all associated document data
    .SingleOrDefaultAsync(m => m.EmploymentID == id);
</code>```

The purpose here is to be able to show a list of all the document names on the page with links that can then be used to download the data for the file selected.

答:
Select all data you need by hands and store it in some Dto object:</p>

```<code>var employment = await _context.Employment
    .Where(m => m.EmploymentID == id)
    .Select(e => new EmploymentDto
    {
        ID = e.EmploymentID,
        Docs = e.EmploymentDocuments.Select(o => o.FileName)
    })
    .SingleOrDefaultAsync();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using ASP.Net Core 2.0 with Entity Framework and I am trying to return a model to a page that contains the Employment entity with it's collection of EmploymentDocument entities also included. For the latter I do not want to load the data (byte[]) column but I do want all the other columns, most importantly FileName.

The linq query I have which loads everything including the data column is:

var employment = await _context.Employment
    .Include(e => e.EmploymentDocuments) // will load all associated document data
    .SingleOrDefaultAsync(m => m.EmploymentID == id);

The purpose here is to be able to show a list of all the document names on the page with links that can then be used to download the data for the file selected.

Body:
Select all data you need by hands and store it in some Dto object:

var employment = await _context.Employment
    .Where(m => m.EmploymentID == id)
    .Select(e => new EmploymentDto
    {
        ID = e.EmploymentID,
        Docs = e.EmploymentDocuments.Select(o => o.FileName)
    })
    .SingleOrDefaultAsync();


问:
Angular 4 Component is rendered as empty
I am new to Angular, I am trying to define a component and use it in my main page.

The thing is that when using the component in index.html all I can see is my <custom-component></custom-component> empty, nothing inside it.

So what I did is:

in Angular cli: ng generate component custom.

in custom.component.html I have just a text inside paragraph tag.

in index.html I inserted the selector found in custom.component.ts (app-custom) as tag.

in app.module.ts I imported the custom component.

ng serve outputs only app-custom tag without the paragraph tag that should be inside it.

What did I miss?

Update:
Code of my component:

custom.component.html

```<code><p>
 component works!
</p>
</code>```

custom.component.ts

```<code>import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-custom',
  templateUrl: './custom.component.html',
  styleUrls: ['./custom.component.css']
})
export class CustomComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}
</code>```

index.html

```<code><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>TestApp</title>
  <base href="/">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-custom></app-custom>
</body>
</html>
</code>```

app.module.ts:

```<code>import { CustomComponent } from './custom/custom.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { FlexLayoutModule } from '@angular/flex-layout';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    CustomComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
     BrowserAnimationsModule,
    FlexLayoutModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答: Try this in index.html add the Appcomponent selector tag and inside Appcomponent template refer your custom component selector and don't forgot to import and declare the custom component in app module and bootstrap the Appcomponent so it renders the app component on load which internally refers your custom component. There are many tutorials outside just start with a single component if you are using AngularCli everything is made easy for you.</p>

Body:
I am new to Angular, I am trying to define a component and use it in my main page.

The thing is that when using the component in index.html all I can see is my <custom-component></custom-component> empty, nothing inside it.

So what I did is:

in Angular cli: ng generate component custom.

in custom.component.html I have just a text inside paragraph tag.

in index.html I inserted the selector found in custom.component.ts (app-custom) as tag.

in app.module.ts I imported the custom component.

ng serve outputs only app-custom tag without the paragraph tag that should be inside it.

What did I miss?

Update:
Code of my component:

custom.component.html

 component works!

custom.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-custom',
  templateUrl: './custom.component.html',
  styleUrls: ['./custom.component.css']
})
export class CustomComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

index.html

<!doctype html>

  <meta charset="utf-8">
  <title>TestApp</title>
  <base href="/">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-custom></app-custom>

app.module.ts:

import { CustomComponent } from './custom/custom.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { FlexLayoutModule } from '@angular/flex-layout';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    CustomComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
     BrowserAnimationsModule,
    FlexLayoutModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


问:
Is there a shorter way for if-else chains?
```<code>if (80 <= m <= 100):
    g = "A"
elif (70 <= m < 80):
    g = "B"
elif (60 <= m < 70):
    g = "C"
elif (50 <= m < 60):
    g = "D"
elif (m < 50):
    g = "U"
</code>```

This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose?

Thanks in advance.

答:
Firstly, you can simplify by removing one of the bounds:

```<code>if m >= 80:
    g = "A"
elif m >= 70:
    g = "B"
elif m >= 60:
    g = "C"
elif m >= 50:
    g = "D"
else:  # default catch-all
    g = "U"
</code>```

Secondly, you could capture the repetitive nature of the process by a loop (with the default case presenting an option for a for-else construct):

```<code># iterator: ('A', 80) -> ('B', 70) -> ...
for grade, score in zip('ABCD', (80, 70, 60, 50)):
    if m >= score:
        g = grade
        break
else:  # executed if for-loop isn't 'break'-ed out of
    g = 'U'
</code>```

Body:
if (80 <= m <= 100):
    g = "A"
elif (70 <= m < 80):
    g = "B"
elif (60 <= m < 70):
    g = "C"
elif (50 <= m < 60):
    g = "D"
elif (m < 50):
    g = "U"

This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose?

Thanks in advance.

Body:
Firstly, you can simplify by removing one of the bounds:

if m >= 80:
    g = "A"
elif m >= 70:
    g = "B"
elif m >= 60:
    g = "C"
elif m >= 50:
    g = "D"
else:  # default catch-all
    g = "U"

Secondly, you could capture the repetitive nature of the process by a loop (with the default case presenting an option for a for-else construct):

# iterator: ('A', 80) -> ('B', 70) -> ...
for grade, score in zip('ABCD', (80, 70, 60, 50)):
    if m >= score:
        g = grade
        break
else:  # executed if for-loop isn't 'break'-ed out of
    g = 'U'


问:
selenium 2 web driver save as dialog
using selenium 2 with webdriver one of my scripts needs to save a report in pdf or csv both just bring up a save as dialog.  I do not know how to interact with it.  im trying in firefox for now but would like to get it working in all browsers.

I read a few posts from 2009 that webDriver and selenium could not access save as dialogs but was wondering if there is a workaround floating around now.

I just need to click the save radio button so it does not try to open it then click the save button

答: Only solution I know of is Firefox only. You can tweak the profile preferences to automatically download some MIME types to a directory of your choice. See my answer here. </p>

ContentLicense: CC BY-SA 2.5

Title: selenium 2 web driver save as dialog


问:
Image doesn't show up in iPhone Launch screen
I have images that don't show up when I use it in:

(iPhone) launch-screen

But images show up in:

(simulator) random views of the storyboard

(simulator) launch-screen

(iPhone) random views of the storyboard

It looks like I messed up with my Assests folder(s), moreover I checked and normally in Copy bundle resources there is 3 items (launchscreen, main.storyboard, Assets.xcassets)

In my case there is only the Launch-screen one.

In parenthesis there is written (1 of 3)? What does it mean?

When I try to add the missing ones to this list, it doesn't show up (main.storyboard file neither Assets.xcassets)

How can I add this back to the list?

Is this related to my problem with images that doesn't show up in the launch-screen?

Do you have any explanation (or a link?) on how xCode(9) is doing the work behind the compilation-load-bar, related to:

the Copy bundle resources settings?

the assets?

答:
click + button under "Copy bundle resource" and add both main.storyboard and Assets.xcassets from the pop up.

EDIT:
in case the sources are not available in the pop up. search them in finder and drag and drop to project to add them again. (since those might have got deleted with their reference.)


问:
Linq get parent and child in one table and calculate their values in another table
I have 2 tables:

```
ParentID | ChildID
--------   -------
91209      91210
91209      91211
91212      91213
91212      91214
```

```
RecordID | Quantity
--------   ---------
91209      1500
91210      2500
91211      7200
91212      6000
91213      5000
91214      6000
```

I would like the result to be:

```
RecordId | Total Quantity
--------   --------------
91209      11200
91212      17000
```

I have tried some complicated join queries but I don't seem to get the result I need. Any suggestion will be much appreciated.

答:
Assuming the table names acc.</p>

```<code>var parentRecords = records.Select(x =>
        new Record { RecordID = parents.FirstOrDefault(y => y.ChildID == x.RecordID || y.ParentID == x.RecordID).ParentID, Quantity = x.Quantity});

    var result = parentRecords.GroupBy(z => z.RecordID,
        (key, value) => new { RecordID= key, TotalQuantity= value.Sum(a => a.Quantity) });
</code>```

Body:
I have 2 tables:

ParentID | ChildID
--------   -------
91209      91210
91209      91211
91212      91213
91212      91214

RecordID | Quantity
--------   ---------
91209      1500
91210      2500
91211      7200
91212      6000
91213      5000
91214      6000

I would like the result to be:

RecordId | Total Quantity
--------   --------------
91209      11200
91212      17000

I have tried some complicated join queries but I don't seem to get the result I need. Any suggestion will be much appreciated.

Body:
Assuming the table names acc.

var parentRecords = records.Select(x =>
        new Record { RecordID = parents.FirstOrDefault(y => y.ChildID == x.RecordID || y.ParentID == x.RecordID).ParentID, Quantity = x.Quantity});

    var result = parentRecords.GroupBy(z => z.RecordID,
        (key, value) => new { RecordID= key, TotalQuantity= value.Sum(a => a.Quantity) });


问:
SQL Query to find out specific column from all database
I wanted to find out the columns which contains the word "VAP" or cancellation. but the problem is we have several number of databases in our server. I wanted to know in which database/table contains the columns name which consist these words. Can anyone let us know if there is any query which can be used to search column name from all databases? I have tried below query but it will only help to find from a single database.</p>

```<code>select distinct
    t.name as TableName,
    SCHEMA_NAME(t.schema_id)   as TableSchema,
    c.name as ColumnName,
    ct.name as ColumnDataType,
    c.is_nullable as IsNullable
from
    sys.tables t with(nolock)
inner join
    sys.columns c with(nolock) on t.object_id = c.object_id
inner join
    sys.types ct with(nolock) on ct.system_type_id = c.system_type_id
where
    c.name like '%VAP%'
order by
    t.name
</code>```

答:
I know this is little lengthy, But You can use this query if  you do not wish to use any third party applications</p>

```<code>USE [master]
GO
DECLARE @Search VARCHAR(50)='A',@SQL VARCHAR(MAX)
DECLARE @Min INT,@Max INT
DECLARE @Table TABLE
(
    SeqNo INT IDENTITY(1,1),
    DatabaseNm VARCHAR(255),
    TableName VARCHAR(255),
    ColumnName VARCHAR(255)
)
DECLARE @TEMP TABLE
(
    SeqNo INT IDENTITY(1,1),
    Qry VARCHAR(MAX)
)

INSERT INTO @TEMP
(
    Qry
)
SELECT
    Qry = 'SELECT
        DbNm = '''+name+''',
        TblNm = [TABLE_SCHEMA]+''.''+[TABLE_NAME],
        COlNm = COLUMN_NAME
        FROM ['+name+'].INFORMATION_SCHEMA.COLUMNS
            WHERE COLUMN_NAME LIKE ''%'+ISNULL(@Search,'')+'%'''
    FROM sys.databases

SELECT
    @Min = MIN(SeqNo),
    @Max = MAX(SeqNo)
    FROM @TEMP

WHILE ISNULL(@Min,0)<=ISNULL(@Max,0)
BEGIN

    SELECT
        @SQL = Qry
        FROM @TEMP
            WHERE SeqNo = @Min

    INSERT INTO @Table
    (
        DatabaseNm,
        TableName,
        ColumnName
    )
    EXEC(@SQL)

    SELECT
        @Min = ISNULL(@Min,0)+1
END

SELECT
    *
    FROM @Table
</code>```

Body:
I wanted to find out the columns which contains the word "VAP" or cancellation. but the problem is we have several number of databases in our server. I wanted to know in which database/table contains the columns name which consist these words. Can anyone let us know if there is any query which can be used to search column name from all databases? I have tried below query but it will only help to find from a single database.

select distinct
    t.name as TableName,
    SCHEMA_NAME(t.schema_id)   as TableSchema,
    c.name as ColumnName,
    ct.name as ColumnDataType,
    c.is_nullable as IsNullable
from
    sys.tables t with(nolock)
inner join
    sys.columns c with(nolock) on t.object_id = c.object_id
inner join
    sys.types ct with(nolock) on ct.system_type_id = c.system_type_id
where
    c.name like '%VAP%'
order by
    t.name

Body:
I know this is little lengthy, But You can use this query if  you do not wish to use any third party applications

USE [master]
GO
DECLARE @Search VARCHAR(50)='A',@SQL VARCHAR(MAX)
DECLARE @Min INT,@Max INT
DECLARE @Table TABLE
(
    SeqNo INT IDENTITY(1,1),
    DatabaseNm VARCHAR(255),
    TableName VARCHAR(255),
    ColumnName VARCHAR(255)
)
DECLARE @TEMP TABLE
(
    SeqNo INT IDENTITY(1,1),
    Qry VARCHAR(MAX)
)

INSERT INTO @TEMP
(
    Qry
)
SELECT
    Qry = 'SELECT
        DbNm = '''+name+''',
        TblNm = [TABLE_SCHEMA]+''.''+[TABLE_NAME],
        COlNm = COLUMN_NAME
        FROM ['+name+'].INFORMATION_SCHEMA.COLUMNS
            WHERE COLUMN_NAME LIKE ''%'+ISNULL(@Search,'')+'%'''
    FROM sys.databases

SELECT
    @Min = MIN(SeqNo),
    @Max = MAX(SeqNo)
    FROM @TEMP

WHILE ISNULL(@Min,0)<=ISNULL(@Max,0)
BEGIN

    SELECT
        @SQL = Qry
        FROM @TEMP
            WHERE SeqNo = @Min

    INSERT INTO @Table
    (
        DatabaseNm,
        TableName,
        ColumnName
    )
    EXEC(@SQL)

    SELECT
        @Min = ISNULL(@Min,0)+1
END

SELECT
    *
    FROM @Table


问:
Qt & QWT: QwtPlotCurve - Curve not showing up
I want to show a simple graph using QWT and Qt Creator:

Qt version: 4.8.2, Qt Creator: 2.5.2,  QWT version: 6.0.0

I added a QwtPlot to my MainWindow (called "myPlot" in the example). Then I have a callback function which is called each time I press a button:

```<code>void MainWindow::forwardPlot()
{
    double x[9] = {1,20,30,40,50,60,70,200,500};
    double y[9] = {1,500,3,1,200,100,2,1,0};
    QwtPlotCurve *curve = new QwtPlotCurve();
    curve->setRawSamples(x,y,9);
    curve->attach( ui->myPlot );
    curve->show();
    ui->myPlot->replot();
    ui->label->setText("bla");
}
</code>```

Compiling works fine...
The label is set to "bla", so I know that the callback function is called. But the curve is not displayed. I am able to resize myPlot for example. But showing the curve does not work. Any hints?

答: Your point arrays are on the stack and will be gone after leaving forwardPlot().</p>

Body:
I want to show a simple graph using QWT and Qt Creator:

Qt version: 4.8.2, Qt Creator: 2.5.2,  QWT version: 6.0.0

I added a QwtPlot to my MainWindow (called "myPlot" in the example). Then I have a callback function which is called each time I press a button:

void MainWindow::forwardPlot()
{
    double x[9] = {1,20,30,40,50,60,70,200,500};
    double y[9] = {1,500,3,1,200,100,2,1,0};
    QwtPlotCurve *curve = new QwtPlotCurve();
    curve->setRawSamples(x,y,9);
    curve->attach( ui->myPlot );
    curve->show();
    ui->myPlot->replot();
    ui->label->setText("bla");
}

Compiling works fine...
The label is set to "bla", so I know that the callback function is called. But the curve is not displayed. I am able to resize myPlot for example. But showing the curve does not work. Any hints?


问:
how to delete previous uploaded file from directory if user upload a new file in asp.net
I am new to asp.net I have upload file control in .aspx page it works fine.
However, I want to delete previous uploaded file from directory if user uploaded a new file.

So this is the abstract code of my code behind file:

```<code>public partial class mypage : System.Web.UI.Page
{
   //I cannot access upload label control value here
    string lblValue = lbluploadFile.Text   //this global variable doesn't work

 protected void Page_Load(object sender, EventArgs e)
 {
   // I can access asp.net label control value in page load

   lbluploadFile.Text

 }

 protected void btnAttachment_Click(object sender, EventArgs e)
 {
  File.Delete(ConfigurationManager.AppSettings["UploadFolder"].ToString() + lblValue);
 }

}
</code>```

答:
How to delete all files and folders in a directory?

you need to get file first with server path (physical path) then you can perform any operation like delete move or change meta data.

combine server path (directory) where you uploaded file with the name of file to get file.

if you need to upload new file in same folder and you want to delete previous one then shortest solution would be just upload new file with the previous name (considering you are uploading same mime type extension file again in case if name is different you can change to previous name) it will auto replace the previous file.

for Ref:How to: Copy, Delete, and Move Files and Folders

Body:
I am new to asp.net I have upload file control in .aspx page it works fine.
However, I want to delete previous uploaded file from directory if user uploaded a new file.

So this is the abstract code of my code behind file:

public partial class mypage : System.Web.UI.Page
{
   //I cannot access upload label control value here
    string lblValue = lbluploadFile.Text   //this global variable doesn't work

 protected void Page_Load(object sender, EventArgs e)
 {
   // I can access asp.net label control value in page load

   lbluploadFile.Text

 }

 protected void btnAttachment_Click(object sender, EventArgs e)
 {
  File.Delete(ConfigurationManager.AppSettings["UploadFolder"].ToString() + lblValue);
 }

}


答:
Shorter and less Pythonic? Definitely:

```<code>g='UUUUUDCBAAA'[int(m)//10]
</code>```

Practically, I think your code conveys its intent well and is easy to read. Most other solutions will not be.

You could also do something like this:

```<code>GRADES = {
    'A': (80, float('+inf')),
    'B': (70,  80),
    'C': (60,  70),
    'D': (50,  60),
    'U': ( 0,  50),
}

def letter_grade(points):
    return next(g for g, (start, end) in GRADES.items() if start <= points < end)
</code>```

I think it is straightforward and can be read the first time through (although I might be biased).

Title: Is there a shorter way for if-else chains?

Body:
Shorter and less Pythonic? Definitely:

g='UUUUUDCBAAA'[int(m)//10]

Practically, I think your code conveys its intent well and is easy to read. Most other solutions will not be.

You could also do something like this:

GRADES = {
    'A': (80, float('+inf')),
    'B': (70,  80),
    'C': (60,  70),
    'D': (50,  60),
    'U': ( 0,  50),
}

def letter_grade(points):
    return next(g for g, (start, end) in GRADES.items() if start <= points < end)

I think it is straightforward and can be read the first time through (although I might be biased).


问:
Is it possible to install localhost server in one pc and to access on multiple computers on a same network.?
We are building php web application while i am a designers and my friend is developer we work on different pcs we want to test the file by runnig on localhost on both of our pc how can we reach it. I have gone through some of concepts in internet but didn't get proper info. </p>

答:
Yes. You need to create a firewall rule to allow access through whatever port you are serving on, probably 8080.

Here is how to create an inbound port rule in windows

Then they should be able to access your server by simply using your ip


问:
.NET Delegate weird optimization
While browsing through the .NET Reference source I found the following piece of code, copied from https://referencesource.microsoft.com/#mscorlib/system/delegate.cs,196.

```<code>    public static Delegate Combine(Delegate a, Delegate b)
    {
        if ((Object)a == null) // cast to object for a more efficient test
            return b;

        return  a.CombineImpl(b);
    }
</code>```

Notice the cast to (Object) which is weird. The reason this is done I'm assuming is not to use to use the == operator override of Delegate but the one from Object. However when browsing the code of Object I cannot find the definition of ==.

Question is then:

== on Object, where is it defined, what's it behavior?

答:
From docs:

For reference types other than string, == returns true if its two operands refer to the same object.

```<code>// Reference equality: different objects,
// same boxed value: False.
object s = 1;
object t = 1;
Console.WriteLine(s == t);
</code>```

Title: .NET Delegate weird optimization

Body:
While browsing through the .NET Reference source I found the following piece of code, copied from https://referencesource.microsoft.com/#mscorlib/system/delegate.cs,196.

    public static Delegate Combine(Delegate a, Delegate b)
    {
        if ((Object)a == null) // cast to object for a more efficient test
            return b;

        return  a.CombineImpl(b);
    }

Notice the cast to (Object) which is weird. The reason this is done I'm assuming is not to use to use the == operator override of Delegate but the one from Object. However when browsing the code of Object I cannot find the definition of ==.

Question is then:

== on Object, where is it defined, what's it behavior?

Body:
From docs:

For reference types other than string, == returns true if its two operands refer to the same object.

// Reference equality: different objects,
// same boxed value: False.
object s = 1;
object t = 1;
Console.WriteLine(s == t);


问:
The represetaion of vector in numpy: is the return of np.array() a row vector?
I am new to numpy, I guess the return of np.array() is a row vector, Because the dot product between two vectors is commutative, is my guess right? Any respone is grateful.</p>

```<code>vx = np.array([1, 2])
vw = np.array([3, 5])
np.dot(vx, vw)
np.dot(vw, vx)
</code>```

答:
The arrays are 1d ('vectors', not row/column vectors).

First paragraph from dot docuentation:

For 2-D arrays it is equivalent to matrix multiplication, and for 1-D
  arrays to inner product of vectors (without complex conjugation). For
  N dimensions it is a sum product over the last axis of a and
  the second-to-last of b

So you are getting the inner product, which is commutative.

```<code>In [118]: vx = np.array([1, 2])
In [119]: vx.shape
Out[119]: (2,)
</code>```

dot returns a scalar:

```<code>In [120]: np.dot(vx,vx)
Out[120]: 5
</code>```

For a 2d 'row vector', shape matters.  dot is matrix multiplication, and last dim as to match 2nd to the last, e.g. 2 matches with 2.

```<code>In [121]: vx2 = np.array([[1,2]])
In [122]: vx2.shape
Out[122]: (1, 2)
In [123]: np.dot(vx2, vx2)
...
ValueError: shapes (1,2) and (1,2) not aligned: 2 (dim 1) != 1 (dim 0)
In [124]: np.dot(vx2, vx2.T)
Out[124]: array([[5]])
</code>```

In this case the result is 2d (1,1).

Body:
I am new to numpy, I guess the return of np.array() is a row vector, Because the dot product between two vectors is commutative, is my guess right? Any respone is grateful.

vx = np.array([1, 2])
vw = np.array([3, 5])
np.dot(vx, vw)
np.dot(vw, vx)

Body:
The arrays are 1d ('vectors', not row/column vectors).

First paragraph from dot docuentation:

For 2-D arrays it is equivalent to matrix multiplication, and for 1-D
  arrays to inner product of vectors (without complex conjugation). For
  N dimensions it is a sum product over the last axis of a and
  the second-to-last of b

So you are getting the inner product, which is commutative.

In [118]: vx = np.array([1, 2])
In [119]: vx.shape
Out[119]: (2,)

dot returns a scalar:

In [120]: np.dot(vx,vx)
Out[120]: 5

For a 2d 'row vector', shape matters.  dot is matrix multiplication, and last dim as to match 2nd to the last, e.g. 2 matches with 2.

In [121]: vx2 = np.array([[1,2]])
In [122]: vx2.shape
Out[122]: (1, 2)
In [123]: np.dot(vx2, vx2)
...
ValueError: shapes (1,2) and (1,2) not aligned: 2 (dim 1) != 1 (dim 0)
In [124]: np.dot(vx2, vx2.T)
Out[124]: array([[5]])

In this case the result is 2d (1,1).


问:
Select Distinct Field on Join
I am joining two large tables in MySQL based on a unique identifier they both share. Because there are a large number of fields, I do not want to list out all fields after SELECT. Instead I want to select all fields, but I do not want recurring fields (the shared unique identifier in this case) to be repeated.

With this example query:

```<code>SELECT *
FROM Gr3_PracMath_Jan11_D1 as a, student_list_011811 as b
WHERE a.StudentID = b.StudentID
</code>```

The field StudentID is repeated. Is there a way to prevent this?

答:
I don't think there is. You might cut your work by listing only half the fields:</p>

```<code>SELECT a.*, b.Field1, b.Field2...
</code>```

ContentLicense: CC BY-SA 4.0

Title: Select Distinct Field on Join

Body:
I am joining two large tables in MySQL based on a unique identifier they both share. Because there are a large number of fields, I do not want to list out all fields after SELECT. Instead I want to select all fields, but I do not want recurring fields (the shared unique identifier in this case) to be repeated.

With this example query:

SELECT *
FROM Gr3_PracMath_Jan11_D1 as a, student_list_011811 as b
WHERE a.StudentID = b.StudentID

The field StudentID is repeated. Is there a way to prevent this?

Body:
I don't think there is. You might cut your work by listing only half the fields:

SELECT a.*, b.Field1, b.Field2...


问:
How do I update the state of a disable bootstrap toggle?
I have a read only bootstrap toggle that is supposed to reflect the state of a system (enabled/disabled). It's supposed to update every time the following getCall() is run. When I read the console, the var data will be true but the toggle won't reflect it. I've tried changing the value of a disabled toggle but that doesn't work. What's the proper way to do this?</p>

```<code>function getCall(toggle_id){
    $.ajax({
        url: URL,
        type: "GET"
    }).done(function(data) {
            console.log("should be", data)
            $(toggle_id).bootstrapToggle("enable");
            $(toggle_id).bootstrapToggle("on", data);
            $(toggle_id).bootstrapToggle("disable");
            $(toggle_id).bootstrapToggle();
    }).fail(function(data,textStatus,errorThrown) {
        alert(errorThrown);
    });
}
</code>```

答:
I changed the following line and it worked:

from

```<code>$(toggle_id).bootstrapToggle("on", data);
</code>```

to

```<code>data ? $(toggle_id).bootstrapToggle("on"): $(toggle_id).bootstrapToggle("off");
</code>```

Body:
I have a read only bootstrap toggle that is supposed to reflect the state of a system (enabled/disabled). It's supposed to update every time the following getCall() is run. When I read the console, the var data will be true but the toggle won't reflect it. I've tried changing the value of a disabled toggle but that doesn't work. What's the proper way to do this?

function getCall(toggle_id){
    $.ajax({
        url: URL,
        type: "GET"
    }).done(function(data) {
            console.log("should be", data)
            $(toggle_id).bootstrapToggle("enable");
            $(toggle_id).bootstrapToggle("on", data);
            $(toggle_id).bootstrapToggle("disable");
            $(toggle_id).bootstrapToggle();
    }).fail(function(data,textStatus,errorThrown) {
        alert(errorThrown);
    });
}

Body:
I changed the following line and it worked:

from

$(toggle_id).bootstrapToggle("on", data);

to

data ? $(toggle_id).bootstrapToggle("on"): $(toggle_id).bootstrapToggle("off");


问:
C# how calculate my price in my listbox
I am a beginner and trying to create a simple inventory for our future business :)

How can I do to this problem ?

I want to calculate the price when I click every button to my listbox.

Example:

When I add items and the price is 6 he display to the bottom (Total) 6 and when I add another and the price is 7 is added to 6 so the total will 13 what can I do to this scenario can I use foreach or something or I revise my code ? help guys thank you :)

enter image description here

```<code>private void button4_Click(object sender, EventArgs e)
{
    int sum = 0;
    if (listBox1.Items.Count >= 0)
    {
        listBox1.Items.Add(dataGridView1.CurrentRow.Cells[0].Value.ToString() + "                 " + dataGridView1.CurrentRow.Cells[1].Value.ToString() + "                                                      " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[2].Value.ToString()) + "                        " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString()));
        sum += Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString());

    }
    label7.Text = sum.ToString();
}
</code>```

and I cannot deduct when I void the list of transaction

```<code>private void button6_Click(object sender, EventArgs e)
{
    if (listBox1.SelectedIndex != -1)
    {
        listBox1.Items.RemoveAt(listBox1.SelectedIndex);
        sum -= Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString());
    }
}
</code>```

答:
You can create a new class, for example, it could be Item and add some rows to it.</p>

```<code>class Item
{
    public static List<Item> Inventory = new List<Item>();

    public Int32 Id { get; set; }
    public Int32 Price { get; set; }
    public String ItemName { get; set; }

    private static Int32 NextId { get; set; } = 0;
    private static Int32 TotalPrice { get; set; }

    public Item(Int32 price, String name)
    {
        this.Price = price;
        this.ItemName = name;
        this.Id = NextId;

        Item.Inventory.Add(this);
        Item.TotalPrice += price;

        Item.NextId++;
        // add to listbox or anything
        // like listBox1.Items.Add($"{this.Id} | {this.ItemName} / {this.Price}");
    }

    public static Int32 GetTotalPrice()
    {
        return Item.TotalPrice;
    }

    public static void RemoveItem(Int32 Id)
    {
        foreach ( Item _item in Item.Inventory )
        {
            if(_item.Id.Equals(Id))
            {
                Item.Inventory.Remove(_item);
                break;
            }
        }
    }
}
</code>```

Title: C# how calculate my price in my listbox

Body:
I am a beginner and trying to create a simple inventory for our future business :)

How can I do to this problem ?

I want to calculate the price when I click every button to my listbox.

Example:

When I add items and the price is 6 he display to the bottom (Total) 6 and when I add another and the price is 7 is added to 6 so the total will 13 what can I do to this scenario can I use foreach or something or I revise my code ? help guys thank you :)

enter image description here

private void button4_Click(object sender, EventArgs e)
{
    int sum = 0;
    if (listBox1.Items.Count >= 0)
    {
        listBox1.Items.Add(dataGridView1.CurrentRow.Cells[0].Value.ToString() + "                 " + dataGridView1.CurrentRow.Cells[1].Value.ToString() + "                                                      " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[2].Value.ToString()) + "                        " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString()));
        sum += Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString());

    }
    label7.Text = sum.ToString();
}

and I cannot deduct when I void the list of transaction

private void button6_Click(object sender, EventArgs e)
{
    if (listBox1.SelectedIndex != -1)
    {
        listBox1.Items.RemoveAt(listBox1.SelectedIndex);
        sum -= Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString());
    }
}

Body:
You can create a new class, for example, it could be Item and add some rows to it.

class Item
{
    public static List<Item> Inventory = new List<Item>();

    public Int32 Id { get; set; }
    public Int32 Price { get; set; }
    public String ItemName { get; set; }

    private static Int32 NextId { get; set; } = 0;
    private static Int32 TotalPrice { get; set; }

    public Item(Int32 price, String name)
    {
        this.Price = price;
        this.ItemName = name;
        this.Id = NextId;

        Item.Inventory.Add(this);
        Item.TotalPrice += price;

        Item.NextId++;
        // add to listbox or anything
        // like listBox1.Items.Add($"{this.Id} | {this.ItemName} / {this.Price}");
    }

    public static Int32 GetTotalPrice()
    {
        return Item.TotalPrice;
    }

    public static void RemoveItem(Int32 Id)
    {
        foreach ( Item _item in Item.Inventory )
        {
            if(_item.Id.Equals(Id))
            {
                Item.Inventory.Remove(_item);
                break;
            }
        }
    }
}


问:
Support library VectorDrawable Resources$NotFoundException
I am using Design Support Library version 23.4.0. I have enabled the gradle flag:

```<code>defaultConfig {
    vectorDrawables.useSupportLibrary = true
}
</code>```

I am using build tools version 23.0.2, but still, I am getting Resources$NotFoundException on KitKat or lower.

It is occurring when I use android:drawableLeft or imageView.setImageResource(R.drawable.drawable_image).

And yes, I am putting this on every activity where I am using drawables

```<code>static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
</code>```

Is this a bug of the support library?

答:
Do not put your vectors in drawable-anydpi
, old devices does not support that

put them in drawable

Body:
I am using Design Support Library version 23.4.0. I have enabled the gradle flag:

defaultConfig {
    vectorDrawables.useSupportLibrary = true
}

I am using build tools version 23.0.2, but still, I am getting Resources$NotFoundException on KitKat or lower.

It is occurring when I use android:drawableLeft or imageView.setImageResource(R.drawable.drawable_image).

And yes, I am putting this on every activity where I am using drawables

static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}

Is this a bug of the support library?


问:
django template inheritance and context
I am reading the definitive guide to django and am in Chapter 4 on template inheritance. It seems that I am not doing something as elegant as should be possible as I am having to duplicate some code for the context to appear when calling the child view.  Here is the code in views.py:

```<code>def homepage(request):
    current_date = datetime.datetime.now()
    current_section = 'Temporary Home Page'
    return render_to_response("base.html", locals())
def contact(request):
    current_date = datetime.datetime.now()
    current_section = 'Contact page'
    return render_to_response("contact.html", locals())
</code>```

It seems redundant to have to include the current_date line in each function.

Here is the base html file that homepage calls:

```<code><html lang= "en">
<head>
    <title>{% block title %}Home Page{% endblock %}</title>
</head>
<body>
    <h1>The Site</h1>
    {% block content %}
        <p> The Current section is {{ current_section }}.</p>
    {% endblock %}

    {% block footer %}
    <p>The current time is {{ current_date }}</p>
    {% endblock %}
</body>
</html>
</code>```

and a child template file:

```<code>{% extends "base.html" %}

{% block title %}Contact{% endblock %}

{% block content %}
<p>Contact information goes here...</p>
    <p>You are in the section {{ current_section }}</p>
{% endblock %}
</code>```

If I don't include the current_date line when calling the child file, where that variable should appear is blank.

答:
For django v1.8+ variables returned inside context processor can be accessed.

1. Add the context processor to your TEMPLATES list inside settings.py

```<code>TEMPLATES = [
   {
       'BACKEND': 'django.template.backends.django.DjangoTemplates',
       'DIRS': [],
       'APP_DIRS': True,
       'OPTIONS': {
           'context_processors': [
               'django.template.context_processors.debug',
               'django.template.context_processors.request',
               'django.contrib.auth.context_processors.auth',
               'django.contrib.messages.context_processors.messages',

               'your_app.context_processor_file.func_name',  # add this line

           ],
       },
   },
]
</code>```

2. Create new file for context processor and define method for context

context_processor_file.py

```<code>def func_name(request):
  test_var = "hi, this is a variable from context processor"
  return {
    "var_for_template" : test_var,
  }
</code>```

3. Now you can get the var_for_template in any templates

for example, add this line inside: base.html

```<code><h1>{{ var_for_template }}</h1>
</code>```

this will render:

hi, this is a variable from context processor
```

for updating templates to django 1.8+ follow this django doc

Title: django template inheritance and context

Body:
I am reading the definitive guide to django and am in Chapter 4 on template inheritance. It seems that I am not doing something as elegant as should be possible as I am having to duplicate some code for the context to appear when calling the child view.  Here is the code in views.py:

def homepage(request):
    current_date = datetime.datetime.now()
    current_section = 'Temporary Home Page'
    return render_to_response("base.html", locals())
def contact(request):
    current_date = datetime.datetime.now()
    current_section = 'Contact page'
    return render_to_response("contact.html", locals())

It seems redundant to have to include the current_date line in each function.

Here is the base html file that homepage calls:

    <title>{% block title %}Home Page{% endblock %}</title>

The Site

    {% block content %}

 The Current section is {{ current_section }}.

    {% endblock %}

    {% block footer %}

The current time is {{ current_date }}

    {% endblock %}

and a child template file:

{% extends "base.html" %}

{% block title %}Contact{% endblock %}

{% block content %}

Contact information goes here...

You are in the section {{ current_section }}

{% endblock %}

If I don't include the current_date line when calling the child file, where that variable should appear is blank.

Body:
For django v1.8+ variables returned inside context processor can be accessed.

1. Add the context processor to your TEMPLATES list inside settings.py

TEMPLATES = [
   {
       'BACKEND': 'django.template.backends.django.DjangoTemplates',
       'DIRS': [],
       'APP_DIRS': True,
       'OPTIONS': {
           'context_processors': [
               'django.template.context_processors.debug',
               'django.template.context_processors.request',
               'django.contrib.auth.context_processors.auth',
               'django.contrib.messages.context_processors.messages',

               'your_app.context_processor_file.func_name',  # add this line

           ],
       },
   },
]

2. Create new file for context processor and define method for context

context_processor_file.py

def func_name(request):
  test_var = "hi, this is a variable from context processor"
  return {
    "var_for_template" : test_var,
  }

3. Now you can get the var_for_template in any templates

for example, add this line inside: base.html

<h1>{{ var_for_template }}</h1>

this will render:

<h1>hi, this is a variable from context processor</h1>

for updating templates to django 1.8+ follow this django doc


问:
T-SQL query to return the number of users assigned to the role with the RoleName ‘Administrators’
I need help with the problem in the title. I have tried lots of different things to get this query to work but I cannot get it quite right. This is one of my attempts:

```<code>SELECT r.RoleName, COUNT(u.UserID) AS NumberOfUsers
FROM Roles r INNER JOIN UserRoles u ON u.UserRoleID = r.RoleID
WHERE r.RoleName ='Administators'
GROUP BY r.RoleName;
</code>```

Thanks in advance!

答:
Have you tried changing the ID where you try to match the tables on?

```<code>SELECT r.RoleName, COUNT(u.UserID) AS NumberOfUsers
FROM Roles r
INNER JOIN UserRoles u
ON r.RoleID = u.RoleID
WHERE r.RoleName ='Administators'
GROUP BY r.RoleName;
</code>```

If this does not work, what output do you get when running this query?

Body:
I need help with the problem in the title. I have tried lots of different things to get this query to work but I cannot get it quite right. This is one of my attempts:

SELECT r.RoleName, COUNT(u.UserID) AS NumberOfUsers
FROM Roles r INNER JOIN UserRoles u ON u.UserRoleID = r.RoleID
WHERE r.RoleName ='Administators'
GROUP BY r.RoleName;

Thanks in advance!

Body:
Have you tried changing the ID where you try to match the tables on?

SELECT r.RoleName, COUNT(u.UserID) AS NumberOfUsers
FROM Roles r
INNER JOIN UserRoles u
ON r.RoleID = u.RoleID
WHERE r.RoleName ='Administators'
GROUP BY r.RoleName;

If this does not work, what output do you get when running this query?


问:
IE not returning results from jQuery ajax() call
First off I must apologise, I know questions similar to what I'm about to ask have been asked before, but none of the answers or suggestions given in those questions are working for me.

Heres the story:

I have written a function that sends an ajax request to the server which in turn runs a php script which performs a query on a database and returns an html element, specifically it returns: Click here. This is my code:

```<code>$('#txtHint').hide();

    function showReviews(str) {
        $.ajax({
            xhr: function() {
                 if ($.browser.msie)
                 {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                 }
                 else
                 {
                     return new XMLHttpRequest();
                 }
            },
            url: "dropsearch.php",
            cache: false,
            type: "post",
            data: "q=" + str,
            dataType: "html",

    success: function(data) {
      $('#txtHint').append(data);
      $('#txtHint').show();
      window.alert(data);
    }
  });
}
</code>```

Now, this works perfectly fine in normal browsers, the a tag is returned in the response header and appended to the txtHint div.  However, with Internet Explorer, the response header isn't returning anything.  I've even used firebug and fiddler to see exactly what the headers are sending and returning, and for some reason although IE is sending the correct header and receiving one back, it's not receiving the content. The window.alert() call just displays an empty alert box in IE.

I've been reading that IE has problems with cache when it comes to ajax calls; however, ensuring the request isn't cahced doesn't work.

Does any body have any idea why this is happening?  It's been driving me absolutely nuts!

Any advice would be much appreciated.

Cheers

答:
IE does cache similar ajax requests.  The workaround I always use is to add a random variable to ajax calls that need caching turned off:

```<code>$('#txtHint').hide();

    function showReviews(str) {
        $.ajax({

            url: "dropsearch.php",
            cache: false,
            type: "post",
            data: "q=" + str+"&r="+Math.random(),
            dataType: "html",

    success: function(data) {
      $('#txtHint').append(data);
      $('#txtHint').show();
      window.alert(data);
    }
  });
}
</code>```

Also, like @Jacob said you have no need to select what type of request $.ajax is using.

Body:
First off I must apologise, I know questions similar to what I'm about to ask have been asked before, but none of the answers or suggestions given in those questions are working for me.

Heres the story:

I have written a function that sends an ajax request to the server which in turn runs a php script which performs a query on a database and returns an html element, specifically it returns: Click here. This is my code:

$('#txtHint').hide();

    function showReviews(str) {
        $.ajax({
            xhr: function() {
                 if ($.browser.msie)
                 {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                 }
                 else
                 {
                     return new XMLHttpRequest();
                 }
            },
            url: "dropsearch.php",
            cache: false,
            type: "post",
            data: "q=" + str,
            dataType: "html",

    success: function(data) {
      $('#txtHint').append(data);
      $('#txtHint').show();
      window.alert(data);
    }
  });
}

Now, this works perfectly fine in normal browsers, the a tag is returned in the response header and appended to the txtHint div.  However, with Internet Explorer, the response header isn't returning anything.  I've even used firebug and fiddler to see exactly what the headers are sending and returning, and for some reason although IE is sending the correct header and receiving one back, it's not receiving the content. The window.alert() call just displays an empty alert box in IE.

I've been reading that IE has problems with cache when it comes to ajax calls; however, ensuring the request isn't cahced doesn't work.

Does any body have any idea why this is happening?  It's been driving me absolutely nuts!

Any advice would be much appreciated.

Cheers

Body:
IE does cache similar ajax requests.  The workaround I always use is to add a random variable to ajax calls that need caching turned off:

$('#txtHint').hide();

    function showReviews(str) {
        $.ajax({

            url: "dropsearch.php",
            cache: false,
            type: "post",
            data: "q=" + str+"&r="+Math.random(),
            dataType: "html",

    success: function(data) {
      $('#txtHint').append(data);
      $('#txtHint').show();
      window.alert(data);
    }
  });
}

Also, like @Jacob said you have no need to select what type of request $.ajax is using.


问:
start date should not be greater than end date bootstrap date picker
I need to disable past dates and also should not allow to select end date less than start date and start date greater than end date.

```<code>*css included*
<link rel="stylesheet" href="{{ asset('assets/css/bootstrap-datepicker3.css') }}">
</code>```

HTML Included
It is my laravel project.

```<code><div class="col-lg-4 col-md-3">
    <div class='input-group date' data-provide="datepicker" id='fromdatepicker' >
        {!! Form::text('from_date', null,['id' => 'from_date', 'class' => 'form-control', 'placeholder'=> '-From Date-']) !!}
        <span class="input-group-addon">
            <span class="calendar-icon-bg"> </span>
            <i class="glyphicon glyphicon-calendar"></i>
        </span>
     </div>
</div>
<div class="col-lg-4 col-md-3">
    <div class='input-group date' data-provide="datepicker" id='todatepicker' >
        {!! Form::text('to_date', null,['id' => 'to_date', 'class' => 'form-control', 'placeholder'=> '-To Date-']) !!}
         <span class="input-group-addon">
             <span class="calendar-icon-bg"></span>
             <i class="glyphicon glyphicon-calendar"></i>
         </span>
     </div>
</div>
</code>```

js

```<code><script src="{{ asset('assets/js/bootstrap-datepicker.js') }}"></script>
<script>
$(function () {
    var nowDate = new Date();
    var today = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 0, 0, 0, 0);
    $("#fromdatepicker").datepicker({
        startDate: today,
        autoclose: true,
        numberOfMonths: 1,
        onSelected: function(selected) {
            $("#todatepicker").datepicker("option","minDate", selected)
        }
  });
  $("#todatepicker").datepicker({
      autoclose: true,
      numberOfMonths: 1,
      onSelected: function(selected) {
          $("#fromdatepicker").datepicker("option","maxDate", selected)
      }
  });
});
</script>
</code>```

Please help me.

答:
Here is a simple example based on your requirements. End date will never be same or before start date. And past dates are disabled.

function populateEndDate() {
  var date2 = $('#dateStart').datepicker('getDate');
  date2.setDate(date2.getDate() + 1);
  $('#dateEnd').datepicker('setDate', date2);
  $("#dateEnd").datepicker("option", "minDate", date2);
}

$(document).ready(function() {

  $("#dateStart").datepicker({
    dateFormat: "dd-M-yy",
    minDate: 'dateToday',
    onSelect: function(date) {
      populateEndDate();
    }
  }).datepicker("setDate", new Date());
  $('#dateEnd').datepicker({
    dateFormat: "dd-M-yy",
    minDate: 1,
    onClose: function() {
      var dt1 = $('#dateStart').datepicker('getDate');
      var dt2 = $('#dateEnd').datepicker('getDate');
      if (dt2 <= dt1) {
        var minDate = $('#dateEnd').datepicker('option', 'minDate');
        $('#dateEnd').datepicker('setDate', minDate);
      }
    }
  }).datepicker("setDate", new Date());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" />

<label for="">start</label>
<input type="text" class="form-control" id="dateStart" name="start">
<label for="">end</label>
<input type="text" class="form-control" id="dateEnd" name="end"></code>```

Body:
I need to disable past dates and also should not allow to select end date less than start date and start date greater than end date.

*css included*
<link rel="stylesheet" href="{{ asset('assets/css/bootstrap-datepicker3.css') }}">

HTML Included
It is my laravel project.

        {!! Form::text('from_date', null,['id' => 'from_date', 'class' => 'form-control', 'placeholder'=> '-From Date-']) !!}

        {!! Form::text('to_date', null,['id' => 'to_date', 'class' => 'form-control', 'placeholder'=> '-To Date-']) !!}

js

Please help me.

Body:
Here is a simple example based on your requirements. End date will never be same or before start date. And past dates are disabled.

function populateEndDate() {
  var date2 = $('#dateStart').datepicker('getDate');
  date2.setDate(date2.getDate() + 1);
  $('#dateEnd').datepicker('setDate', date2);
  $("#dateEnd").datepicker("option", "minDate", date2);
}

$(document).ready(function() {

  $("#dateStart").datepicker({
    dateFormat: "dd-M-yy",
    minDate: 'dateToday',
    onSelect: function(date) {
      populateEndDate();
    }
  }).datepicker("setDate", new Date());
  $('#dateEnd').datepicker({
    dateFormat: "dd-M-yy",
    minDate: 1,
    onClose: function() {
      var dt1 = $('#dateStart').datepicker('getDate');
      var dt2 = $('#dateEnd').datepicker('getDate');
      if (dt2 <= dt1) {
        var minDate = $('#dateEnd').datepicker('option', 'minDate');
        $('#dateEnd').datepicker('setDate', minDate);
      }
    }
  }).datepicker("setDate", new Date());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" />

<label for="">start</label>
<input type="text" class="form-control" id="dateStart" name="start">
<label for="">end</label>
<input type="text" class="form-control" id="dateEnd" name="end">


问:
mapping drop down field with Set<Object> via @ModelAttribute Spring mvc
Follwoing is my Pojo Classes to which form field is mapped via @ModelAttribute:-

```<code> public class WebUsers extends BaseDomain {

    private int webUserId;
    private String firstName;
    private String lastName;
    private String userLogin;
    private String password;
    private UserDetail userDetail;
    private Set<Roles> roles;
    private boolean isTestUser;
    private boolean isActive;

    public int getWebUserId() {
        return webUserId;
    }
    public void setWebUserId(int webUserId) {
        this.webUserId = webUserId;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getUserLogin() {
        return userLogin;
    }
    public void setUserLogin(String userLogin) {
        this.userLogin = userLogin;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public UserDetail getUserDetail() {
        return userDetail;
    }
    public void setUserDetail(UserDetail userDetail) {
        this.userDetail = userDetail;
    }

    public Set<Roles> getRoles() {
        return roles;
    }
    public void setRoles(Set<Roles> roles) {
        this.roles = roles;
    }
    public boolean isTestUser() {
        return isTestUser;
    }
    public void setTestUser(boolean isTestUser) {
        this.isTestUser = isTestUser;
    }
    public boolean isActive() {
        return isActive;
    }
    public void setActive(boolean isActive) {
        this.isActive = isActive;
    }

}
</code>```

Roles Pojo:-

```<code>public class Roles extends BaseDomain{

    @NotBlank
    private int id;
    private String role;
    private String roleDescription;
    private boolean isActive;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public String getRoleDescription() {
        return roleDescription;
    }

    public void setRoleDescription(String roleDescription) {
        this.roleDescription = roleDescription;
    }

    public boolean isActive() {
        return isActive;
    }

    public void setActive(boolean isActive) {
        this.isActive = isActive;
    }
</code>```

Following is the form :-

```<code><form role="form" method="post" action="registerWebUser">
    <div class="form-group">
    <label>First Name</label>
    <input class="form-control" name="firstName">
     </div>
     <div class="form-group">
     <label>Last Name</label>
     <input class="form-control" name="lastName">
     </div>
     <div class="form-group">
     <label>Email Id</label>
     <input class="form-control" type="email" name="userDetail.emailId">
     <p class="help-block">use it as user login</p>
     </div>
     <div class="form-group">
     <label>Password</label>
     <input class="form-control" name="password">
     </div>
     <div class="form-group">
     <label>Select Role</label>
     <select class="form-control" name="roles.id">
     <option value="1">Super Admin</option>
     <option value="3">Admin</option>
     <option value="4">Manager</option>
     <option value="5">Android Developer</option>

      </select>
      </div>

     <button type="submit" class="btn btn-default">Register</button>
     <button type="reset" class="btn btn-default">Reset Form</button>
     </form>
</code>```

And Below is my Controller:-

```<code>@RequestMapping(value = "/registerWebUser", method = RequestMethod.POST)
public ModelAndView registerWebUserHandler(@ModelAttribute WebUsers webUsers) {
        getLogger().info("roles object ==  " + webUsers.getRoles());
        WebUsersDTO dto = copyDtoInDomain(webUsers);
        int id = adminService.createAdminService(dto);

        Map<String, String> responseMap = new HashMap<String, String>();
        if (id != 0) {
            responseMap.put("response", "Successfully Registered");
        } else {
            responseMap.put("response", "failed");
        }

        return new ModelAndView("registration-success", responseMap);
    }
</code>```

Problem is every form field is mapped with variable of Pojo class but Set is not getting mapped. it is making an empty object of Collection Set. I want to map the value of drop down with id of Roles. Please help

答:
I did it.
Actually @ModelArttribute do not map nested objects with Set collection. I replace the Set with List and rename the form field like roles[0].id where id is variable of Roles pojo class.</p>

Body:
Follwoing is my Pojo Classes to which form field is mapped via @ModelAttribute:-

 public class WebUsers extends BaseDomain {

    private int webUserId;
    private String firstName;
    private String lastName;
    private String userLogin;
    private String password;
    private UserDetail userDetail;
    private Set<Roles> roles;
    private boolean isTestUser;
    private boolean isActive;

    public int getWebUserId() {
        return webUserId;
    }
    public void setWebUserId(int webUserId) {
        this.webUserId = webUserId;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getUserLogin() {
        return userLogin;
    }
    public void setUserLogin(String userLogin) {
        this.userLogin = userLogin;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public UserDetail getUserDetail() {
        return userDetail;
    }
    public void setUserDetail(UserDetail userDetail) {
        this.userDetail = userDetail;
    }

    public Set<Roles> getRoles() {
        return roles;
    }
    public void setRoles(Set<Roles> roles) {
        this.roles = roles;
    }
    public boolean isTestUser() {
        return isTestUser;
    }
    public void setTestUser(boolean isTestUser) {
        this.isTestUser = isTestUser;
    }
    public boolean isActive() {
        return isActive;
    }
    public void setActive(boolean isActive) {
        this.isActive = isActive;
    }

}

Roles Pojo:-

public class Roles extends BaseDomain{

    @NotBlank
    private int id;
    private String role;
    private String roleDescription;
    private boolean isActive;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public String getRoleDescription() {
        return roleDescription;
    }

    public void setRoleDescription(String roleDescription) {
        this.roleDescription = roleDescription;
    }

    public boolean isActive() {
        return isActive;
    }

    public void setActive(boolean isActive) {
        this.isActive = isActive;
    }

Following is the form :-

<form role="form" method="post" action="registerWebUser">

    First Name
    <input class="form-control" name="firstName">

     Last Name
     <input class="form-control" name="lastName">

     Email Id
     <input class="form-control" type="email" name="userDetail.emailId">

use it as user login

     Password
     <input class="form-control" name="password">

     Select Role
     <select class="form-control" name="roles.id">
     <option value="1">Super Admin</option>
     <option value="3">Admin</option>
     <option value="4">Manager</option>
     <option value="5">Android Developer</option>

      </select>

     <button type="submit" class="btn btn-default">Register</button>
     <button type="reset" class="btn btn-default">Reset Form</button>
     </form>

And Below is my Controller:-

@RequestMapping(value = "/registerWebUser", method = RequestMethod.POST)
public ModelAndView registerWebUserHandler(@ModelAttribute WebUsers webUsers) {
        getLogger().info("roles object ==  " + webUsers.getRoles());
        WebUsersDTO dto = copyDtoInDomain(webUsers);
        int id = adminService.createAdminService(dto);

        Map<String, String> responseMap = new HashMap<String, String>();
        if (id != 0) {
            responseMap.put("response", "Successfully Registered");
        } else {
            responseMap.put("response", "failed");
        }

        return new ModelAndView("registration-success", responseMap);
    }

Problem is every form field is mapped with variable of Pojo class but Set is not getting mapped. it is making an empty object of Collection Set. I want to map the value of drop down with id of Roles. Please help


问:
Moving from a one-to-one relationship into a many-to-many relationship in rails
Like the title says, I want to move from a one-to-one relationship into a many-to-many relationship in my rails 3 app.

I'm fairly good with rails now but I lack a good understanding of databases and migrations.

Currently, I have a Project and User model. A Project belongs_to a User and a User has_many Projects.
I want to move into a situation where a project can have many users collaborating on it at once.

I'm pretty sure I need to set up a has_many :through type of relationship, but I am also curious as to how I can migrate all of my existing projects and users into this type of system.

Thanks!

答:
You need another table that links the two tables together.  This is how to support many to many relationships.

e.g.  Say you have two tables like this:

```<code>Projects
----------
projectid
{other columns}

Users
-------
userid
{other columns}
</code>```

The new table will look something like this:
    New Table

```<code>Projects_Users
--------------
projectid
userid
</code>```

Now you can add another user to a project by simply adding the userid and projectid to
the Projects_Users table.  Similarly you will be able to add several users to the one project in the same table.

The primary key on that table is the composite key projectid & userid.

Body:
You need another table that links the two tables together.  This is how to support many to many relationships.

e.g.  Say you have two tables like this:

Projects
----------
projectid
{other columns}

Users
-------
userid
{other columns}

The new table will look something like this:
    New Table

Projects_Users
--------------
projectid
userid

Now you can add another user to a project by simply adding the userid and projectid to
the Projects_Users table.  Similarly you will be able to add several users to the one project in the same table.

The primary key on that table is the composite key projectid & userid.


问:
To GET Names of days between two days in mysql
Is there any method in MySql which can return the name of days between two dates. For example 06/11/207 is start date and 12/11/2017 is end  date then I need to get the output as:

monday,tuesday,wednesday,thursday,friday,saturday,sunday

答:
you can try this :

you can take F_TABLE_NUMBER_RANGE function from this link:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=47685

```<code>declare @start_date     datetime
declare @end_date       datetime
declare @days           int

select @start_date  = '06/11/2017'
select @end_date    = '12/11/2017'

select @days = datediff(dd,@start_date,@end_date) +1

select
    [Date]      = dateadd(dd,number-1,@start_date),
    [Day of Week]   = datename(weekday,dateadd(dd,number-1,@start_date))
from
    dbo.F_TABLE_NUMBER_RANGE( 1, @days )
order by
    number
</code>```

This I have tried and working for me cheers !

Body:
you can try this :

you can take F_TABLE_NUMBER_RANGE function from this link:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=47685

declare @start_date     datetime
declare @end_date       datetime
declare @days           int

select @start_date  = '06/11/2017'
select @end_date    = '12/11/2017'

select @days = datediff(dd,@start_date,@end_date) +1

select
    [Date]      = dateadd(dd,number-1,@start_date),
    [Day of Week]   = datename(weekday,dateadd(dd,number-1,@start_date))
from
    dbo.F_TABLE_NUMBER_RANGE( 1, @days )
order by
    number

This I have tried and working for me cheers !


问:
Choose file inside webview
I create code webview in Android Studio. When try to run an application (webview apps) and click a link to download a file nothing happens. what should i do?`

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

    WebView webView = (WebView) findViewById(R.id.webView);
    webView.loadUrl("http://my-url/");
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient());
}
</code>```

`

答:
```<code>Try to add these lines it may work

mWebView.getSettings().setJavaScriptEnabled(true);
    // Other webview options
    mWebView.getSettings().setLoadWithOverviewMode(true);
    mWebView.setScrollbarFadingEnabled(false);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
    mWebView.getSettings().setAllowFileAccess(true);
    mWebView.getSettings().setSupportZoom(false);
    mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    mWebView.getSettings().setAppCacheEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
</code>```

these lines may help you

Title: Choose file inside webview

Body:
I create code webview in Android Studio. When try to run an application (webview apps) and click a link to download a file nothing happens. what should i do?`

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

    WebView webView = (WebView) findViewById(R.id.webView);
    webView.loadUrl("http://my-url/");
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient());
}

`

Body:
Try to add these lines it may work

mWebView.getSettings().setJavaScriptEnabled(true);
    // Other webview options
    mWebView.getSettings().setLoadWithOverviewMode(true);
    mWebView.setScrollbarFadingEnabled(false);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
    mWebView.getSettings().setAllowFileAccess(true);
    mWebView.getSettings().setSupportZoom(false);
    mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    mWebView.getSettings().setAppCacheEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);

these lines may help you


问:
Function composition errors
I'm learning Haskell and I came across a situation in which I'm not entirely sure what is going on.

I'm working on a bigger project, and have been trying to 'simplify' my code. I'd learnt about function composition and I think I mostly understand it. However, whilst pushing the limits of this, I encountered a situation I'm not sure how to explain.

After a few hours of fiddling about with it, I boiled it down to this:

```<code>foo1 x y z = x == (y && z)
foo2 x y z = (x ==) . (&&) y z     -- Error
foo3 x y   = (x ==) . (&&) y
foo4 x     = (x ==) . (&&)         -- Error
</code>```

Why do foo1 and foo3 work, whilst foo2 and foo4 give errors when I try to define them? As far as I know, there's no reason adding or removing equivalent arguments to both the input and output should change the function.

Edit: Include errors

foo2 yields the error:

```<code><interactive>:1:23: error:
    • Couldn't match expected type ‘a -> a1’ with actual type ‘Bool’
    • Possible cause: ‘(&&)’ is applied to too many arguments
      In the second argument of ‘(.)’, namely ‘(&&) y z’
      In the expression: (x ==) . (&&) y z
      In an equation for ‘foo2’: foo2 x y z = (x ==) . (&&) y z
    • Relevant bindings include
        x :: a1 (bound at <interactive>:1:6)
        foo2 :: a1 -> Bool -> Bool -> a -> Bool
          (bound at <interactive>:1:1)
</code>```

Whilst foo4 gives the error:

```<code><interactive>:2:15: error:
    • No instance for (Eq (Bool -> Bool))
        arising from an operator section
        (maybe you haven't applied a function to enough arguments?)
    • In the first argument of ‘(.)’, namely ‘(x ==)’
      In the expression: (x ==) . (&&)
      In an equation for ‘foo4’: foo4 x = (x ==) . (&&)
</code>```

答:
function application

Let's start with function application.

a b is an application of a function a to one arguments b.

a b c is an application of a function a to two arguments b and c.

a b c d is an application of a function a to three arguments b, c, and d.

(&&) and (.)'s type signature

Then look at these two functions' type signature.

```<code>(&&) :: Bool -> Bool -> Bool
</code>```

takes two arguments

```<code>(.) :: (b -> c) -> (a -> b) -> a -> c
</code>```

takes three arguments, two of them functions

Then we look into these four cases.

foo1

```<code>foo1 x y z = x == (y && z)
</code>```

(y && z) is (&&) y z, fully applied. So the result is a Bool type.

x == Bool is (==) x Bool. So x is a Bool type.

It works.

foo2

```<code>foo2 x y z = (x ==) . (&&) y z
</code>```

(x ==) is a function that expects one argument.

so (x ==) . :: (a -> b) -> a -> c

However, as @Carcigenicate says, your (&&) is fully applied.

Hence, compiler say, "Couldn't match expected type ‘a -> a1’ with actual type ‘Bool’"

foo3

```<code>foo3 x y   = (x ==) . (&&) y

(.) :: (b -> c) -> (a -> b) -> a -> c
</code>```

(.) function composition takes function ( x==) and (&&) y

and all it need now is another a to produce c.

so foo3 is just foo1's point-free style.

It works, too.

foo4

```<code>foo4 x     = (x ==) . (&&)
</code>```

So we already meet (x ==) .

its type signature is (a -> b) -> a -> c

However, (&&) :: Bool -> Bool -> Bool

Although it can be seen as Bool -> (Bool -> Bool), a function that takes one argument and produce a Bool -> Bool function.

(Bool->Bool) is not an instance for Eq. It doesn't have (==).

Thus the compiler says "No instance for (Eq (Bool -> Bool))"

Point-free style

As far as I know, there's no reason adding or removing equivalent
  arguments to both the input and output should change the function.

It holds true when they are on the same level.

name b c d = function b c d --fully applied

name b c = function b c --wait one argument

name b = function b --wait two arguments

name = function --wait three/all arguments

but function composition needs to compose two one-argument functions into one-argument function(and the right one's output type need to match the left one's input type.)

So the order is function application first, then (.) / function composition second. And you need to feed (b->c) and (a->b) to (.) to get a new (a->c) function.

Title: Function composition errors

Body:
I'm learning Haskell and I came across a situation in which I'm not entirely sure what is going on.

I'm working on a bigger project, and have been trying to 'simplify' my code. I'd learnt about function composition and I think I mostly understand it. However, whilst pushing the limits of this, I encountered a situation I'm not sure how to explain.

After a few hours of fiddling about with it, I boiled it down to this:

foo1 x y z = x == (y && z)
foo2 x y z = (x ==) . (&&) y z     -- Error
foo3 x y   = (x ==) . (&&) y
foo4 x     = (x ==) . (&&)         -- Error

Why do foo1 and foo3 work, whilst foo2 and foo4 give errors when I try to define them? As far as I know, there's no reason adding or removing equivalent arguments to both the input and output should change the function.

Edit: Include errors

foo2 yields the error:

<interactive>:1:23: error:
    • Couldn't match expected type ‘a -> a1’ with actual type ‘Bool’
    • Possible cause: ‘(&&)’ is applied to too many arguments
      In the second argument of ‘(.)’, namely ‘(&&) y z’
      In the expression: (x ==) . (&&) y z
      In an equation for ‘foo2’: foo2 x y z = (x ==) . (&&) y z
    • Relevant bindings include
        x :: a1 (bound at <interactive>:1:6)
        foo2 :: a1 -> Bool -> Bool -> a -> Bool
          (bound at <interactive>:1:1)

Whilst foo4 gives the error:

<interactive>:2:15: error:
    • No instance for (Eq (Bool -> Bool))
        arising from an operator section
        (maybe you haven't applied a function to enough arguments?)
    • In the first argument of ‘(.)’, namely ‘(x ==)’
      In the expression: (x ==) . (&&)
      In an equation for ‘foo4’: foo4 x = (x ==) . (&&)

Body:
function application

Let's start with function application.

a b is an application of a function a to one arguments b.

a b c is an application of a function a to two arguments b and c.

a b c d is an application of a function a to three arguments b, c, and d.

(&&) and (.)'s type signature

Then look at these two functions' type signature.

(&&) :: Bool -> Bool -> Bool

takes two arguments

(.) :: (b -> c) -> (a -> b) -> a -> c

takes three arguments, two of them functions

Then we look into these four cases.

foo1

foo1 x y z = x == (y && z)

(y && z) is (&&) y z, fully applied. So the result is a Bool type.

x == Bool is (==) x Bool. So x is a Bool type.

It works.

foo2

foo2 x y z = (x ==) . (&&) y z

(x ==) is a function that expects one argument.

so (x ==) . :: (a -> b) -> a -> c

However, as @Carcigenicate says, your (&&) is fully applied.

Hence, compiler say, "Couldn't match expected type ‘a -> a1’ with actual type ‘Bool’"

foo3

foo3 x y   = (x ==) . (&&) y

(.) :: (b -> c) -> (a -> b) -> a -> c

(.) function composition takes function ( x==) and (&&) y

and all it need now is another a to produce c.

so foo3 is just foo1's point-free style.

It works, too.

foo4

foo4 x     = (x ==) . (&&)

So we already meet (x ==) .

its type signature is (a -> b) -> a -> c

However, (&&) :: Bool -> Bool -> Bool

Although it can be seen as Bool -> (Bool -> Bool), a function that takes one argument and produce a Bool -> Bool function.

(Bool->Bool) is not an instance for Eq. It doesn't have (==).

Thus the compiler says "No instance for (Eq (Bool -> Bool))"

Point-free style

As far as I know, there's no reason adding or removing equivalent
  arguments to both the input and output should change the function.

It holds true when they are on the same level.

name b c d = function b c d --fully applied

name b c = function b c --wait one argument

name b = function b --wait two arguments

name = function --wait three/all arguments

but function composition needs to compose two one-argument functions into one-argument function(and the right one's output type need to match the left one's input type.)

So the order is function application first, then (.) / function composition second. And you need to feed (b->c) and (a->b) to (.) to get a new (a->c) function.


问:
Angular does not execute bindings, directive and ngOnInit when route change
In my application, I am facing problems with Angular not binding properties. It also does not call ngOnInit and ngAfterViewInit or execute directives.

Here is partial LoginComponent code:

```<code>@Component({
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit

//.....

    public test: string = 'some dummy test';

    constructor(
        private cd: ChangeDetectorRef,
        private fb: FormBuilder, private router: Router, private route: ActivatedRoute,
        private authService: AuthService,
        private usersService: UserService,
        private notificationsService: NotificationsService
    )
    {
        this.loginForm = fb.group({
            email: ["", Validators.required],
            password: ["", Validators.required]
        });
        console.info("constructor");
    }

    ngOnInit()
    {
        console.info("ngOnInit");
        this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
    }

    ngAfterViewInit()
    {
        this.initGapi();
        console.info("afterviewinit");
    }
</code>```

Strange is that this works when I open page, or HMR refresh page, but not when I login and logout.

Here is the logout code:

```<code>logout(): boolean
{
    this.authService.logout();
}

//authservice.ts
logout()
{
    localStorage.removeItem("token");
    localStorage.removeItem("refresh_token");
    localStorage.removeItem("profile");

    if (gapi.auth2)
    {
        const instance = gapi.auth2.getAuthInstance();
        if (instance)
        {
            instance.signOut().then(() =>
            {
                this.router.navigate(["login"]);
            });
            return;
        }
    }
    this.router.navigate(["login"]);
}
</code>```

The differences when I logout and binding not occur are:

Button is not styled. This should do kendoButton directive <button class="center" kendoButton type="submit">

Binding to test (some dummy test) is missing

ngOnInit and ngAfterViewInit is not called.

There is no error in console. I also record screen (it starts with empty page). I have the latest Chrome and Firefox, and same problem is in both browsers.

Does anybody have any idea what is wrong or what else can I try?

答:
Problem is in Google gapi library:

```<code>const instance = gapi.auth2.getAuthInstance();
if (instance)
{
    instance.signOut().then(() =>
    {
        this.router.navigate(["login"]);    //This is runned outside Angular's context.
    });
    return;
}
</code>```

Callback of instance.signOut runs outside Angular's context.
Solution is to place navigate outside google.gapi callback:

```<code>const instance = gapi.auth2.getAuthInstance();
if (instance)
{
    instance.signOut();
    this.router.navigate(["login"]);
}
</code>```

Or if you wish to navigate after signOut from Google, use zones. This may help.

Body:
In my application, I am facing problems with Angular not binding properties. It also does not call ngOnInit and ngAfterViewInit or execute directives.

Here is partial LoginComponent code:

@Component({
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit

//.....

    public test: string = 'some dummy test';

    constructor(
        private cd: ChangeDetectorRef,
        private fb: FormBuilder, private router: Router, private route: ActivatedRoute,
        private authService: AuthService,
        private usersService: UserService,
        private notificationsService: NotificationsService
    )
    {
        this.loginForm = fb.group({
            email: ["", Validators.required],
            password: ["", Validators.required]
        });
        console.info("constructor");
    }

    ngOnInit()
    {
        console.info("ngOnInit");
        this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
    }

    ngAfterViewInit()
    {
        this.initGapi();
        console.info("afterviewinit");
    }

Strange is that this works when I open page, or HMR refresh page, but not when I login and logout.

Here is the logout code:

logout(): boolean
{
    this.authService.logout();
}

//authservice.ts
logout()
{
    localStorage.removeItem("token");
    localStorage.removeItem("refresh_token");
    localStorage.removeItem("profile");

    if (gapi.auth2)
    {
        const instance = gapi.auth2.getAuthInstance();
        if (instance)
        {
            instance.signOut().then(() =>
            {
                this.router.navigate(["login"]);
            });
            return;
        }
    }
    this.router.navigate(["login"]);
}

The differences when I logout and binding not occur are:

Button is not styled. This should do kendoButton directive <button class="center" kendoButton type="submit">

Binding to test (some dummy test) is missing

ngOnInit and ngAfterViewInit is not called.

There is no error in console. I also record screen (it starts with empty page). I have the latest Chrome and Firefox, and same problem is in both browsers.

Does anybody have any idea what is wrong or what else can I try?

Body:
Problem is in Google gapi library:

const instance = gapi.auth2.getAuthInstance();
if (instance)
{
    instance.signOut().then(() =>
    {
        this.router.navigate(["login"]);    //This is runned outside Angular's context.
    });
    return;
}

Callback of instance.signOut runs outside Angular's context.
Solution is to place navigate outside google.gapi callback:

const instance = gapi.auth2.getAuthInstance();
if (instance)
{
    instance.signOut();
    this.router.navigate(["login"]);
}

Or if you wish to navigate after signOut from Google, use zones. This may help.


问:
Bash addition by the first column, if data in second column is the same
I have a list with delimiters |

```<code>40|192.168.1.2|user4
42|192.168.1.25|user2
58|192.168.1.55|user3
118|192.168.1.3|user11
67|192.168.1.25|user2
</code>```

As you can see, I have the same ip in the field 42|192.168.1.25|user2 and in the field 67|192.168.1.25|user2. How can I append these lines between them ? Can you give me a solution using awk. Can you give me some examples ?

I need in a result something like this:

```<code>40|192.168.1.2|user4
58|192.168.1.55|user3
109|192.168.1.25|user2
118|192.168.1.3|user11
</code>```

How you can see, we have counted the numbers from first column.

答:
Another idea on the same path but allows for different users:

```<code>awk -F'|' '{c[$2] += $1}u[$2] !~ $3{u[$2] = (u[$2]?u[$2]",":"")$3}END{for(i in c)print c[i],i,u[i]}' OFS='|' input_file
</code>```

If multiple users they will be separated by a comma

Body:
I have a list with delimiters |

40|192.168.1.2|user4
42|192.168.1.25|user2
58|192.168.1.55|user3
118|192.168.1.3|user11
67|192.168.1.25|user2

As you can see, I have the same ip in the field 42|192.168.1.25|user2 and in the field 67|192.168.1.25|user2. How can I append these lines between them ? Can you give me a solution using awk. Can you give me some examples ?

I need in a result something like this:

40|192.168.1.2|user4
58|192.168.1.55|user3
109|192.168.1.25|user2
118|192.168.1.3|user11

How you can see, we have counted the numbers from first column.

Body:
Another idea on the same path but allows for different users:

awk -F'|' '{c[$2] += $1}u[$2] !~ $3{u[$2] = (u[$2]?u[$2]",":"")$3}END{for(i in c)print c[i],i,u[i]}' OFS='|' input_file

If multiple users they will be separated by a comma