问:
Asp.Net MVC 2 - Bind a model's property to a different named value
Update (21st Sept 2016) - Thanks to Digbyswift for commenting that this solution still works in MVC5 also.

Update (30th April 2012) - Note to people stumbling across this question from searches etc - the accepted answer is not how I ended up doing this - but I left it accepted because it might have worked in some cases.  My own answer contains the final solution I used, which is reusable and will apply to any project.

It's also confirmed to work in v3 and v4 of the MVC framework.

I have the following model type (the names of the class and its properties have been changed to protect their identities):

```<code>public class MyExampleModel
{
  public string[] LongPropertyName { get; set; }
}
</code>```

This property is then bound to a bunch (>150) of check boxes, where each one's input name is of course LongPropertyName.

The form submits to url with an HTTP GET, and say the user selects three of those checkboxes - the url will have the query string ?LongPropertyName=a&LongPropertyName=b&LongPropertyName=c

Big problem then is that if I select all (or even just over half!) the checkboxes, I exceed the maximum query string length enforced by the request filter on IIS!

I do not want to extend that - so I want a way to trim down this query string (I know I can just switch to a POST - but even so I still want to minimize the amount of fluff in the data sent by the client).

What I want to do is have the LongPropertyName bound to simply 'L' so the query string would become ?L=a&L=b&L=c but without changing the property name in code.

The type in question already has a custom model binder (deriving from DefaultModelBinder), but it's attached to its base class - so I don't want to put code in there for a derived class.  All the property binding is currently performed by the standard DefaultModelBinder logic, which I know uses TypeDescriptors and Property Descriptors etc from System.ComponentModel.

I was kinda hoping that there might be an attribute I could apply to the property to make this work - is there?  Or should I be looking at implementing ICustomTypeDescriptor?

答:
You can use the BindAttribute to accomplish this.

```<code>public ActionResult Submit([Bind(Prefix = "L")] string[] longPropertyName) {

}
</code>```

Update

Since the 'longPropertyName' parameter is part of the model object, and not an independent parameter of the controller action, you have a couple of other choices.

You could keep the model and the property as independent parameters to your action and then manually merge the data together in the action method.

```<code>public ActionResult Submit(MyModel myModel, [Bind(Prefix = "L")] string[] longPropertyName) {
    if(myModel != null) {
        myModel.LongPropertyName = longPropertyName;
    }
}
</code>```

Another option would be implementing a custom Model Binder that performs the parameter value assignment (as above) manually, but that is most likely overkill. Here's an example of one, if you're interested: Flags Enumeration Model Binder.

Body:
Update (21st Sept 2016) - Thanks to Digbyswift for commenting that this solution still works in MVC5 also.

Update (30th April 2012) - Note to people stumbling across this question from searches etc - the accepted answer is not how I ended up doing this - but I left it accepted because it might have worked in some cases.  My own answer contains the final solution I used, which is reusable and will apply to any project.

It's also confirmed to work in v3 and v4 of the MVC framework.

I have the following model type (the names of the class and its properties have been changed to protect their identities):

public class MyExampleModel
{
  public string[] LongPropertyName { get; set; }
}

This property is then bound to a bunch (>150) of check boxes, where each one's input name is of course LongPropertyName.

The form submits to url with an HTTP GET, and say the user selects three of those checkboxes - the url will have the query string ?LongPropertyName=a&LongPropertyName=b&LongPropertyName=c

Big problem then is that if I select all (or even just over half!) the checkboxes, I exceed the maximum query string length enforced by the request filter on IIS!

I do not want to extend that - so I want a way to trim down this query string (I know I can just switch to a POST - but even so I still want to minimize the amount of fluff in the data sent by the client).

What I want to do is have the LongPropertyName bound to simply 'L' so the query string would become ?L=a&L=b&L=c but without changing the property name in code.

The type in question already has a custom model binder (deriving from DefaultModelBinder), but it's attached to its base class - so I don't want to put code in there for a derived class.  All the property binding is currently performed by the standard DefaultModelBinder logic, which I know uses TypeDescriptors and Property Descriptors etc from System.ComponentModel.

I was kinda hoping that there might be an attribute I could apply to the property to make this work - is there?  Or should I be looking at implementing ICustomTypeDescriptor?

Body:
You can use the BindAttribute to accomplish this.

public ActionResult Submit([Bind(Prefix = "L")] string[] longPropertyName) {

}

Update

Since the 'longPropertyName' parameter is part of the model object, and not an independent parameter of the controller action, you have a couple of other choices.

You could keep the model and the property as independent parameters to your action and then manually merge the data together in the action method.

public ActionResult Submit(MyModel myModel, [Bind(Prefix = "L")] string[] longPropertyName) {
    if(myModel != null) {
        myModel.LongPropertyName = longPropertyName;
    }
}

Another option would be implementing a custom Model Binder that performs the parameter value assignment (as above) manually, but that is most likely overkill. Here's an example of one, if you're interested: Flags Enumeration Model Binder.


来源: stackexchange

问:
CROSS JOIN columns of a table with its data

Problem description with an example

Assuming I have a table like this:

```<code>CREATE TABLE MyData(
    Id INT PRIMARY KEY,
    NotUniqueCol INT,
    ColA NVARCHAR(128),
    ColB NVARCHAR(128)
)
INSERT INTO MyData (Id, NotUniqueCol, ColA, ColB)
VALUES (1, 1, 'a', 'A')
     , (2, 1, 'b', 'B')
     , (3, 2, 'c', 'C')
</code>```

And a stored procedure which takes a table name, a column name and a column value:

```<code>CREATE PROCEDURE GetData
(
    @tableName NVARCHAR(128),
    @columnName NVARCHAR(128),
    @id INT,
)
</code>```

And I execute it

```<code>EXEC GetData 'MyData', 'NotUniqueCol', 1
</code>```

It should return something like this:

```<code> RowNumber  │  ColumnName    │ ColumnValue
────────────┼────────────────┼──────────────────
 1          │ 'Id'           │ 1
 1          │ 'NotUniqueCol' │ 1
 1          │ 'ColA'         │ 'a'
 1          │ 'ColB'         │ 'A'
 2          │ 'Id'           │ 2
 2          │ 'NotUniqueCol' │ 1
 2          │ 'ColA'         │ 'b'
 2          │ 'ColB'         │ 'B'
</code>```

Outline Solution

The problem is the body of GetData because everything must be generic.

My idea are these steps:

Get all table names and join them to the columns and filter the result.

Execute a dynamic query which selects the matching data from the table and numerate the rows.

Do a CROSS JOIN with the results of 2. und 3.

Snippets

Step 1

```<code>SELECT c.[name]
FROM sys.tables AS t
INNER JOIN sys.columns AS c ON c.[object_id] = t.[object_id]
WHERE t.[name] = @tableName
</code>```

Step 2

```<code>DECLARE @query NVARCHAR(MAX)
    = ' SELECT ROW_NUMBER() OVER(ORDER BY myTable.' + QUOTENAME(@columnName) + ' DESC) AS [RowNumber], myTable.*'
    + ' FROM ' + QUOTENAME(@tableName) + ' AS myTable'
    + ' WHERE myTable.' + QUOTENAME(@columnName) + ' = ' + CAST(@id AS NVARCHAR(16))
PRINT @query
EXEC sp_sqlexec @query
</code>```

Get the result using a cursor

This code works, but I do not like it because of the cursor.

```<code>-- The parameters from the SP
DECLARE  @tableName NVARCHAR(128)='MyData',
         @columnName NVARCHAR(128)='NotUniqueCol',
         @id INT=1

--The body of the SP
CREATE TABLE #result (RowNumber INT, ColumnName NVARCHAR(128), ColumnValue SQL_VARIANT)

DECLARE @column NVARCHAR(128);
DECLARE myCursor CURSOR
FOR
    SELECT c.[name]
    FROM sys.tables AS t
    INNER JOIN sys.columns AS c ON c.[object_id] = t.[object_id]
    WHERE t.[name] = @tableName
OPEN myCursor
FETCH NEXT FROM myCursor
INTO @column

WHILE @@FETCH_STATUS = 0
BEGIN
    DECLARE @query NVARCHAR(MAX)
        = ' SELECT ROW_NUMBER() OVER(ORDER BY myTable.' + QUOTENAME(@columnName) + ' DESC) AS [RowNumber], ''' + @column + ''' AS [ColumnName], myTable.' + QUOTENAME(@column)
        + ' FROM ' + QUOTENAME(@tableName) + ' AS myTable'
        + ' WHERE myTable.' + QUOTENAME(@columnName) + ' = ' + CAST(@id AS NVARCHAR(16))
    PRINT @query

    INSERT INTO #result(RowNumber, ColumnName, ColumnValue)
    EXEC sp_sqlexec @query

    FETCH NEXT FROM myCursor
    INTO @column
END
CLOSE myCursor;
DEALLOCATE myCursor;

SELECT * FROM #result
ORDER BY RowNumber, ColumnName

DROP TABLE #result
</code>```

Final Question

I have not a good idea for Step 3 which do not use a cursor. It works well, but is there a solution using a CROSS JOIN or something else?

答:
Here is a Table-Valued-Function which will convert virtually any Table, Query, or Row into an EAV Structure.

The First column in the query (or table) will be the ENTITY and please note that it will be excluded from the the values (optional)

Certainly, UNPIVOT is more performant, but this does not require Dynamic SQL, and there are no datatype conflicts, and the performance is very respectable.

I should add that NULL values WILL be excluded.  I'm at a loss on how to include them.

Example 1

```<code>Select * From [dbo].[udf-EAV]((Select * From MyData for XML RAW))
</code>```

Returns

```<code>Entity  Attribute       Value
1       NotUniqueCol    1      --<< Notice ID is NOT a row
1       ColA            a
1       ColB            A
2       NotUniqueCol    1
2       ColA            b
2       ColB            B
3       NotUniqueCol    2
3       ColA            c
3       ColB            C
</code>```

Example 2 -- With Row_Number() as the ENTITY

```<code>Select * From [dbo].[udf-EAV]((Select RowNumber=Row_Number() over (Order By ID),* From MyData for XML RAW))
</code>```

Returns

```<code>Entity  Attribute       Value
1       Id              1      --<< Notice ID IS a row ... 1st column is Row_Number()
1       NotUniqueCol    1
1       ColA            a
1       ColB            A
2       Id              2
2       NotUniqueCol    1
2       ColA            b
2       ColB            B
3       Id              3
3       NotUniqueCol    2
3       ColA            c
3       ColB            C
</code>```

Example 3 with CROSS APPLY - Especially for Larger Tables

```<code>Select B.*
 From  MyData A
 Cross Apply [dbo].[udf-EAV]((Select A.* for XML RAW)) B
</code>```

Returns

```<code>Entity  Attribute       Value
1       NotUniqueCol    1
1       ColA            a
1       ColB            A
2       NotUniqueCol    1
2       ColA            b
2       ColB            B
3       NotUniqueCol    2
3       ColA            c
3       ColB            C
</code>```

The UDF if Interested

```<code>CREATE FUNCTION [dbo].[udf-EAV](@XML xml)
Returns Table
As
Return (
    with cteKey(k) as (Select Top 1 xAtt.value('local-name(.)','varchar(100)') From @XML.nodes('/row') As A(xRow) Cross Apply A.xRow.nodes('./@*') As B(xAtt))

    Select Entity    = xRow.value('@*[1]','varchar(50)')
          ,Attribute = xAtt.value('local-name(.)','varchar(100)')
          ,Value     = xAtt.value('.','varchar(max)')
    From  @XML.nodes('/row') As A(xRow)
    Cross Apply A.xRow.nodes('./@*') As B(xAtt)
    Where xAtt.value('local-name(.)','varchar(100)') Not In (Select k From cteKey)
)
-- Notes:  First Field in Query will be the Entity
-- Select * From [dbo].[udf-EAV]((Select UTCDate=GetUTCDate(),* From sys.dm_os_sys_info for XML RAW))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Problem description with an example

Assuming I have a table like this:

CREATE TABLE MyData(
    Id INT PRIMARY KEY,
    NotUniqueCol INT,
    ColA NVARCHAR(128),
    ColB NVARCHAR(128)
)
INSERT INTO MyData (Id, NotUniqueCol, ColA, ColB)
VALUES (1, 1, 'a', 'A')
     , (2, 1, 'b', 'B')
     , (3, 2, 'c', 'C')

And a stored procedure which takes a table name, a column name and a column value:

CREATE PROCEDURE GetData
(
    @tableName NVARCHAR(128),
    @columnName NVARCHAR(128),
    @id INT,
)

And I execute it

EXEC GetData 'MyData', 'NotUniqueCol', 1

It should return something like this:

 RowNumber  │  ColumnName    │ ColumnValue
────────────┼────────────────┼──────────────────
 1          │ 'Id'           │ 1
 1          │ 'NotUniqueCol' │ 1
 1          │ 'ColA'         │ 'a'
 1          │ 'ColB'         │ 'A'
 2          │ 'Id'           │ 2
 2          │ 'NotUniqueCol' │ 1
 2          │ 'ColA'         │ 'b'
 2          │ 'ColB'         │ 'B'

Outline Solution

The problem is the body of GetData because everything must be generic.

My idea are these steps:

Get all table names and join them to the columns and filter the result.

Execute a dynamic query which selects the matching data from the table and numerate the rows.

Do a CROSS JOIN with the results of 2. und 3.

Snippets

Step 1

SELECT c.[name]
FROM sys.tables AS t
INNER JOIN sys.columns AS c ON c.[object_id] = t.[object_id]
WHERE t.[name] = @tableName

Step 2

DECLARE @query NVARCHAR(MAX)
    = ' SELECT ROW_NUMBER() OVER(ORDER BY myTable.' + QUOTENAME(@columnName) + ' DESC) AS [RowNumber], myTable.*'
    + ' FROM ' + QUOTENAME(@tableName) + ' AS myTable'
    + ' WHERE myTable.' + QUOTENAME(@columnName) + ' = ' + CAST(@id AS NVARCHAR(16))
PRINT @query
EXEC sp_sqlexec @query

Get the result using a cursor

This code works, but I do not like it because of the cursor.

-- The parameters from the SP
DECLARE  @tableName NVARCHAR(128)='MyData',
         @columnName NVARCHAR(128)='NotUniqueCol',
         @id INT=1

--The body of the SP
CREATE TABLE #result (RowNumber INT, ColumnName NVARCHAR(128), ColumnValue SQL_VARIANT)

DECLARE @column NVARCHAR(128);
DECLARE myCursor CURSOR
FOR
    SELECT c.[name]
    FROM sys.tables AS t
    INNER JOIN sys.columns AS c ON c.[object_id] = t.[object_id]
    WHERE t.[name] = @tableName
OPEN myCursor
FETCH NEXT FROM myCursor
INTO @column

WHILE @@FETCH_STATUS = 0
BEGIN
    DECLARE @query NVARCHAR(MAX)
        = ' SELECT ROW_NUMBER() OVER(ORDER BY myTable.' + QUOTENAME(@columnName) + ' DESC) AS [RowNumber], ''' + @column + ''' AS [ColumnName], myTable.' + QUOTENAME(@column)
        + ' FROM ' + QUOTENAME(@tableName) + ' AS myTable'
        + ' WHERE myTable.' + QUOTENAME(@columnName) + ' = ' + CAST(@id AS NVARCHAR(16))
    PRINT @query

    INSERT INTO #result(RowNumber, ColumnName, ColumnValue)
    EXEC sp_sqlexec @query

    FETCH NEXT FROM myCursor
    INTO @column
END
CLOSE myCursor;
DEALLOCATE myCursor;

SELECT * FROM #result
ORDER BY RowNumber, ColumnName

DROP TABLE #result

Final Question

I have not a good idea for Step 3 which do not use a cursor. It works well, but is there a solution using a CROSS JOIN or something else?

Body:
Here is a Table-Valued-Function which will convert virtually any Table, Query, or Row into an EAV Structure.

The First column in the query (or table) will be the ENTITY and please note that it will be excluded from the the values (optional)

Certainly, UNPIVOT is more performant, but this does not require Dynamic SQL, and there are no datatype conflicts, and the performance is very respectable.

I should add that NULL values WILL be excluded.  I'm at a loss on how to include them.

Example 1

Select * From [dbo].[udf-EAV]((Select * From MyData for XML RAW))

Returns

Entity  Attribute       Value
1       NotUniqueCol    1      --<< Notice ID is NOT a row
1       ColA            a
1       ColB            A
2       NotUniqueCol    1
2       ColA            b
2       ColB            B
3       NotUniqueCol    2
3       ColA            c
3       ColB            C

Example 2 -- With Row_Number() as the ENTITY

Select * From [dbo].[udf-EAV]((Select RowNumber=Row_Number() over (Order By ID),* From MyData for XML RAW))

Returns

Entity  Attribute       Value
1       Id              1      --<< Notice ID IS a row ... 1st column is Row_Number()
1       NotUniqueCol    1
1       ColA            a
1       ColB            A
2       Id              2
2       NotUniqueCol    1
2       ColA            b
2       ColB            B
3       Id              3
3       NotUniqueCol    2
3       ColA            c
3       ColB            C

Example 3 with CROSS APPLY - Especially for Larger Tables

Select B.*
 From  MyData A
 Cross Apply [dbo].[udf-EAV]((Select A.* for XML RAW)) B

Returns

Entity  Attribute       Value
1       NotUniqueCol    1
1       ColA            a
1       ColB            A
2       NotUniqueCol    1
2       ColA            b
2       ColB            B
3       NotUniqueCol    2
3       ColA            c
3       ColB            C

The UDF if Interested

CREATE FUNCTION [dbo].[udf-EAV](@XML xml)
Returns Table
As
Return (
    with cteKey(k) as (Select Top 1 xAtt.value('local-name(.)','varchar(100)') From @XML.nodes('/row') As A(xRow) Cross Apply A.xRow.nodes('./@*') As B(xAtt))

    Select Entity    = xRow.value('@*[1]','varchar(50)')
          ,Attribute = xAtt.value('local-name(.)','varchar(100)')
          ,Value     = xAtt.value('.','varchar(max)')
    From  @XML.nodes('/row') As A(xRow)
    Cross Apply A.xRow.nodes('./@*') As B(xAtt)
    Where xAtt.value('local-name(.)','varchar(100)') Not In (Select k From cteKey)
)
-- Notes:  First Field in Query will be the Entity
-- Select * From [dbo].[udf-EAV]((Select UTCDate=GetUTCDate(),* From sys.dm_os_sys_info for XML RAW))


问:
MySQL Error - Commands out of sync; you can't run this command now
I am using MySQL with PHP, Codeigniter. I had a question which was answered by bluefeet in the post here

I created a stored procedure for the second solution by bluefeet. It works perfect, however, while the procedure is called in the production environment, all the other users get the error

Commands out of sync; you can't run this command now

Not sure how can i overcome with this error. I also tried closing the connection after the procedure is called, however, Queries from other users are executed before the connection is closed. Any work-around for this issue?

Below is the stored procedure that i have used

```<code>DROP PROCEDURE IF EXISTS mailbox.circle_pending_p;
CREATE PROCEDURE mailbox.`circle_pending_p`()
BEGIN
SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(CASE WHEN maildate = ''',
      date_format(mailtime, '%e-%b'),
      ''' THEN 1 else 0 END) AS `',
      date_format(mailtime, '%e-%b'), '`'
    )
  ) INTO @sql
FROM circle_pending_temp
WHERE mailtime >= (select date_sub(max(mailtime), interval 8 DAY)
                   from circle_pending_temp);

SET @sql
  = CONCAT('SELECT coalesce(email_Circle, ''Grand Total'') Circle,
              max(`< 9 days`) `< 9 days`, ', @sql, ' ,
              count(*) GrandTotal
            from
            (
              select c.email_Circle,
                date_format(c.mailtime, ''%e-%b'') maildate,
                coalesce(o.`< 9 days`, 0) `< 9 days`
              from circle_pending_temp c
              left join
              (
                select email_Circle,
                  count(*) `< 9 days`
                from circle_pending_temp
                where mailtime <= (select date_sub(max(mailtime), interval 8 DAY)
                                    from circle_pending_temp)
              ) o
                on c.email_Circle = o.email_Circle
              where c.mailtime >= (select date_sub(max(mailtime), interval 8 DAY)
                                      from circle_pending_temp)
            ) d
            group by email_Circle with rollup ');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
</code>```

The PHP that i use for calling this procedure is

```<code>    $db = $this->load->database('mailbox',TRUE);
    $res = $db->query('Call circle_pending_p()');
    echo $db->_error_message();
    $db->close();
    $db = $this->load->database('mailbox',TRUE);
    if ($res->num_rows() > 0) {
        return $res->result_array();
    } else {
        return 0;
    }
</code>```

答:
I faced similary problem when I was running stored procedure in a loop. The below code I was using:

```<code>foreach ($month_list as $month_row)
{

  $start_date = $month_row->adate;
  $end_date = date("Y-m-d", strtotime("last day of " . date("F", strtotime($start_date)) . " " . date("Y", strtotime($start_date))));

  $qry_res = $this->db->query("call staff_attendance('$start_date', '$end_date')");

  $res = $qry_res->result();

  $qry_res->next_result();
  $qry_res->free_result();

  $compiled_months[] = $res;

}
</code>```

In this case the temporary table I created was being complained as table already exists.

So, used this approach instead:

```<code>foreach ($month_list as $month_row)
{

  $start_date = $month_row->adate;
  $end_date = date("Y-m-d", strtotime("last day of " . date("F", strtotime($start_date)) . " " . date("Y", strtotime($start_date))));

  $compiled_months[] = $this->db->query("call staff_attendance('$start_date', '$end_date')")->result();
  $this->db->close();
  $this->db->initialize();

}
</code>```

Now execution was perfect

Body:
I am using MySQL with PHP, Codeigniter. I had a question which was answered by bluefeet in the post here

I created a stored procedure for the second solution by bluefeet. It works perfect, however, while the procedure is called in the production environment, all the other users get the error

Commands out of sync; you can't run this command now

Not sure how can i overcome with this error. I also tried closing the connection after the procedure is called, however, Queries from other users are executed before the connection is closed. Any work-around for this issue?

Below is the stored procedure that i have used

DROP PROCEDURE IF EXISTS mailbox.circle_pending_p;
CREATE PROCEDURE mailbox.`circle_pending_p`()
BEGIN
SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(CASE WHEN maildate = ''',
      date_format(mailtime, '%e-%b'),
      ''' THEN 1 else 0 END) AS `',
      date_format(mailtime, '%e-%b'), '`'
    )
  ) INTO @sql
FROM circle_pending_temp
WHERE mailtime >= (select date_sub(max(mailtime), interval 8 DAY)
                   from circle_pending_temp);

SET @sql
  = CONCAT('SELECT coalesce(email_Circle, ''Grand Total'') Circle,
              max(`< 9 days`) `< 9 days`, ', @sql, ' ,
              count(*) GrandTotal
            from
            (
              select c.email_Circle,
                date_format(c.mailtime, ''%e-%b'') maildate,
                coalesce(o.`< 9 days`, 0) `< 9 days`
              from circle_pending_temp c
              left join
              (
                select email_Circle,
                  count(*) `< 9 days`
                from circle_pending_temp
                where mailtime <= (select date_sub(max(mailtime), interval 8 DAY)
                                    from circle_pending_temp)
              ) o
                on c.email_Circle = o.email_Circle
              where c.mailtime >= (select date_sub(max(mailtime), interval 8 DAY)
                                      from circle_pending_temp)
            ) d
            group by email_Circle with rollup ');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;

The PHP that i use for calling this procedure is

    $db = $this->load->database('mailbox',TRUE);
    $res = $db->query('Call circle_pending_p()');
    echo $db->_error_message();
    $db->close();
    $db = $this->load->database('mailbox',TRUE);
    if ($res->num_rows() > 0) {
        return $res->result_array();
    } else {
        return 0;
    }

Body:
I faced similary problem when I was running stored procedure in a loop. The below code I was using:

foreach ($month_list as $month_row)
{

  $start_date = $month_row->adate;
  $end_date = date("Y-m-d", strtotime("last day of " . date("F", strtotime($start_date)) . " " . date("Y", strtotime($start_date))));

  $qry_res = $this->db->query("call staff_attendance('$start_date', '$end_date')");

  $res = $qry_res->result();

  $qry_res->next_result();
  $qry_res->free_result();

  $compiled_months[] = $res;

}

In this case the temporary table I created was being complained as table already exists.

So, used this approach instead:

foreach ($month_list as $month_row)
{

  $start_date = $month_row->adate;
  $end_date = date("Y-m-d", strtotime("last day of " . date("F", strtotime($start_date)) . " " . date("Y", strtotime($start_date))));

  $compiled_months[] = $this->db->query("call staff_attendance('$start_date', '$end_date')")->result();
  $this->db->close();
  $this->db->initialize();

}

Now execution was perfect


问:
How can I use Scanner on switch case for String of array so that case takes in value from String b
How can I use Scanner class in "switch case" to determine the result;

Goal is to be able to use Scanner to determine the case. When user will input value in the scanner the select case will be able to use that String value (e.g if user type Mocking Bird in the Scanner it will be recognized in the switch case and out the code

```<code>    import java.util.Scanner;

    Scanner input = new Scanner(System.in);
    String b = input.next();

    String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };

    for (int t = 0; t < Books.length; t++) {

      switch (Books[t]) {

        case "Harry Potter":
         System.out.println("Getting from switch case " + t + " " + Books[t]);
             break;

        case "To Kill a Mocking Bird"
         System.out.println("Getting from switch case " + t + " " + Books[t]);
              break;

        default:
            break;
        }
     }
</code>```

答:
According to java documentation switch statement works on specific paths:

Unlike if-then and if-then-else statements, the switch statement can
  have a number of possible execution paths. A switch works with the
  byte, short, char, and int primitive data types. It also works with
  enumerated types (discussed in Enum Types), the String class, and a
  few special classes that wrap certain primitive types: Character,
  Byte, Short, and Integer.

in your case you have more than one option to solve your problem either use if statement which is the better solution or use switch statement but you should put all cases of your Books array in the switch statement:

Option1 if statement:

```<code>    Scanner input = new Scanner(System.in);
    String b = input.nextLine();
    String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };

    for (int t = 0; t < Books.length; t++) {
        if(b.equals(Books[t])){
            System.out.println("Getting from switch case " + t+1 + " " + Books[t]);
        }
    }
</code>```

Option2 switch statement:

```<code>    Scanner input = new Scanner(System.in);
    String b = input.nextLine();

    switch (b) {
        case "Harry Potter":
         System.out.println("Getting from switch case 1 Harry Potter");
             break;

        case "To Kill a Mocking Bird":
         System.out.println("Getting from switch case 2 To Kill a Mocking Bird" );
              break;

        case "Hunger Games":
         System.out.println("Getting from switch case 3 Hunger Games" );
              break;

        default:
          break;
    }
</code>```

note that in switch case solution no need to use array Books because it's not suitable in this case.

hope this would help you.

Body:
How can I use Scanner class in "switch case" to determine the result;

Goal is to be able to use Scanner to determine the case. When user will input value in the scanner the select case will be able to use that String value (e.g if user type Mocking Bird in the Scanner it will be recognized in the switch case and out the code

    import java.util.Scanner;

    Scanner input = new Scanner(System.in);
    String b = input.next();

    String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };

    for (int t = 0; t < Books.length; t++) {

      switch (Books[t]) {

        case "Harry Potter":
         System.out.println("Getting from switch case " + t + " " + Books[t]);
             break;

        case "To Kill a Mocking Bird"
         System.out.println("Getting from switch case " + t + " " + Books[t]);
              break;

        default:
            break;
        }
     }

Body:
According to java documentation switch statement works on specific paths:

Unlike if-then and if-then-else statements, the switch statement can
  have a number of possible execution paths. A switch works with the
  byte, short, char, and int primitive data types. It also works with
  enumerated types (discussed in Enum Types), the String class, and a
  few special classes that wrap certain primitive types: Character,
  Byte, Short, and Integer.

in your case you have more than one option to solve your problem either use if statement which is the better solution or use switch statement but you should put all cases of your Books array in the switch statement:

Option1 if statement:

    Scanner input = new Scanner(System.in);
    String b = input.nextLine();
    String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };

    for (int t = 0; t < Books.length; t++) {
        if(b.equals(Books[t])){
            System.out.println("Getting from switch case " + t+1 + " " + Books[t]);
        }
    }

Option2 switch statement:

    Scanner input = new Scanner(System.in);
    String b = input.nextLine();

    switch (b) {
        case "Harry Potter":
         System.out.println("Getting from switch case 1 Harry Potter");
             break;

        case "To Kill a Mocking Bird":
         System.out.println("Getting from switch case 2 To Kill a Mocking Bird" );
              break;

        case "Hunger Games":
         System.out.println("Getting from switch case 3 Hunger Games" );
              break;

        default:
          break;
    }

note that in switch case solution no need to use array Books because it's not suitable in this case.

hope this would help you.


问:
CSS3/HTML animate position:fixed div onto page
I have a little pseudo modal I am building for my app that takes over the screen for a moment when a user clicks the button. I have it set as position fixed so it can overtake the entire screen infront of the user. I have it show and hiding right now with just toggling between display: block and display: none, my css right now just looks like so :

(SCSS) :

```<code> .sort-fullscreen {
    display: none;
    top: 0;
    left: 0;
    right: 0;
    height: 100vh;
    width: 100vw;
    background-color: $modal-bg-color;
    position: fixed;
    z-index: 101;
    transition: all 0.5;

    &.open {
      display: block;
    }
}
</code>```

And there is just a

```<code><div class="sort-fullscreen">
  ... users content
</div>
</code>```

Sitting at the bottom of my page.

So this works fine, however I am trying to figure out if there is a way to animate the position fixed coming onto the page - perhaps sliding on and off?

Initially - I tried something like this

```<code>.sort-fullscreen {
    display: block;
    top: 0;
    left: -100%;
    right: 0;
    height: 100vh;
    width: 100vw;
    background-color: $modal-bg-color;
    position: fixed;
    z-index: 101;
    transition: all 0.5;

    &.open {
       left: 0%;
    }
}
</code>```

However, this does not seem to work for me. I cannot seem to find a clean way to animate a position fixed onto the page. Any help on how to achieve this would be appreciated. Thanks!

答:
Your code seemed to work for me, albeit after adding 's' in your transition time:

```<code>transition: all 0.5s;
</code>```

Fiddle: https://jsfiddle.net/dt2j6872/1/

Body:
I have a little pseudo modal I am building for my app that takes over the screen for a moment when a user clicks the button. I have it set as position fixed so it can overtake the entire screen infront of the user. I have it show and hiding right now with just toggling between display: block and display: none, my css right now just looks like so :

(SCSS) :

 .sort-fullscreen {
    display: none;
    top: 0;
    left: 0;
    right: 0;
    height: 100vh;
    width: 100vw;
    background-color: $modal-bg-color;
    position: fixed;
    z-index: 101;
    transition: all 0.5;

    &.open {
      display: block;
    }
}

And there is just a

  ... users content

Sitting at the bottom of my page.

So this works fine, however I am trying to figure out if there is a way to animate the position fixed coming onto the page - perhaps sliding on and off?

Initially - I tried something like this

.sort-fullscreen {
    display: block;
    top: 0;
    left: -100%;
    right: 0;
    height: 100vh;
    width: 100vw;
    background-color: $modal-bg-color;
    position: fixed;
    z-index: 101;
    transition: all 0.5;

    &.open {
       left: 0%;
    }
}

However, this does not seem to work for me. I cannot seem to find a clean way to animate a position fixed onto the page. Any help on how to achieve this would be appreciated. Thanks!

Body:
Your code seemed to work for me, albeit after adding 's' in your transition time:

transition: all 0.5s;

Fiddle: https://jsfiddle.net/dt2j6872/1/


问:
array push of records obtained from mongo db
In MEAN stack, I am trying to store the records obtained from mongo db in an array, but I am not able to store the record in an array.

This is my code, I am trying to push the records obtained from projectimage to fulldetails[] array, but it failed. Suggest me the possible solution to store the mongo db records to array

```<code>    var express = require("express"),
     router = express.Router(),
     project = require("../../models/project.js"),
     projectimage = require("../../models/projectimages.js"),

             var details=data;
                 var fulldetails=[];

for (var i = 0; i < details.length; i++) {
    var prjct_id=details[i]._id;
    console.log('below'+i);
    fulldetails.push(details[i]);
    projectimage.findOne({projectId: prjct_id}, function(err, data){
       fulldetails.concat(data);
                   });
    console.log(fulldetails);
       return false;
}
</code>```

答:
I think you're trying to get a flat array of full details. If my assumption is correct, you could try my solution here:</p>

```<code>var fulldetails=[];

for (var i = 0; i < details.length; i++) {

    var prjct_id=details[i]._id;

    projectimage.find({projectId: prjct_id}).toArray(function(err, data){ //convert data to array first
        console.log(data);
        fulldetails.concat(data); // concat data to fulldetails to get a flat array
    });
}
</code>```

Body:
In MEAN stack, I am trying to store the records obtained from mongo db in an array, but I am not able to store the record in an array.

This is my code, I am trying to push the records obtained from projectimage to fulldetails[] array, but it failed. Suggest me the possible solution to store the mongo db records to array

    var express = require("express"),
     router = express.Router(),
     project = require("../../models/project.js"),
     projectimage = require("../../models/projectimages.js"),

             var details=data;
                 var fulldetails=[];

for (var i = 0; i < details.length; i++) {
    var prjct_id=details[i]._id;
    console.log('below'+i);
    fulldetails.push(details[i]);
    projectimage.findOne({projectId: prjct_id}, function(err, data){
       fulldetails.concat(data);
                   });
    console.log(fulldetails);
       return false;
}

Body:
I think you're trying to get a flat array of full details. If my assumption is correct, you could try my solution here:

var fulldetails=[];

for (var i = 0; i < details.length; i++) {

    var prjct_id=details[i]._id;

    projectimage.find({projectId: prjct_id}).toArray(function(err, data){ //convert data to array first
        console.log(data);
        fulldetails.concat(data); // concat data to fulldetails to get a flat array
    });
}


问:
Read and Writing Files Dropbox API V2
I am try to read and write to a file on my Dropbox using the new Drobox API, I have already created a variable that can access my account and have been able to list the contents of my Dropbox, but so far I have not been able to get a specific files contents. What I recieve in the console output is,

todocl.file - The file path, which is 'Test.txt' (I have tried '/Test.txt', that just gives a 409 error, path not found.)

and

Dropbox-sdk.min.js:8 Uncaught DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

```<code>function readFiles() {
    todocl.dbx.filesDownload({
        path: '/Help.txt'
    }).then(function (response) {
        var text = response.fileBlob;
        var reader = new FileEventListener("loadend", function () {
            console.log(reader.result);
        });
        reader.readAsText(text);
    }).catch(function (error) {
        console.error(error);
    });
}
</code>```

Dropbox Api
http://dropbox.github.io/dropbox-sdk-js/Dropbox.html

Any help would be great!

答:
Turns out I needed the root for the file path and the corretc setu for the filee reader.</p>

```<code>function readFiles() {
    todocl.dbx.filesDownload({
        path: todocl.file
    }).then(function (data) {
        var blob = data.fileBlob;
        var reader = new FileReader()
        reader.addEventListener("loadend", function () {
            console.log(reader.result);
        })
        reader.readAsText(blob);
    }).catch(function (error) {
        console.error(error);
    });
}
</code>```

Title: Read and Writing Files Dropbox API V2

Body:
I am try to read and write to a file on my Dropbox using the new Drobox API, I have already created a variable that can access my account and have been able to list the contents of my Dropbox, but so far I have not been able to get a specific files contents. What I recieve in the console output is,

todocl.file - The file path, which is 'Test.txt' (I have tried '/Test.txt', that just gives a 409 error, path not found.)

and

Dropbox-sdk.min.js:8 Uncaught DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

function readFiles() {
    todocl.dbx.filesDownload({
        path: '/Help.txt'
    }).then(function (response) {
        var text = response.fileBlob;
        var reader = new FileEventListener("loadend", function () {
            console.log(reader.result);
        });
        reader.readAsText(text);
    }).catch(function (error) {
        console.error(error);
    });
}

Dropbox Api
http://dropbox.github.io/dropbox-sdk-js/Dropbox.html

Any help would be great!

Body:
Turns out I needed the root for the file path and the corretc setu for the filee reader.

function readFiles() {
    todocl.dbx.filesDownload({
        path: todocl.file
    }).then(function (data) {
        var blob = data.fileBlob;
        var reader = new FileReader()
        reader.addEventListener("loadend", function () {
            console.log(reader.result);
        })
        reader.readAsText(blob);
    }).catch(function (error) {
        console.error(error);
    });
}


问:
How to compile threads program?
I am trying to compile a hello world program using threads. But i keep getting the same error, ive tried it different ways but no luck.</p>

```<code>gcc hello.c -o hello -lpthread      // command line compilation
./hello.c                            // execution
-bash: ./hello.c: Permission denied // error message
</code>```

答: the -o option renames the executable to whatever you write next (in this case 'hello'). You need to execute as ./hello not ./hello.c.</p>

Title: How to compile threads program?

Body:
I am trying to compile a hello world program using threads. But i keep getting the same error, ive tried it different ways but no luck.

gcc hello.c -o hello -lpthread      // command line compilation
./hello.c                            // execution
-bash: ./hello.c: Permission denied // error message


问:
Xamarin Forms Padding in StaticResource
I want to build few pages with specific Padding in sytacklayout. I do not want to wrote it in every pages. And its not good design considering if I want to change it in future. Is there a way to define padding in static resource? So that I can define it in one place App.xml and use it in other pages.

I have tried

```<code><ContentPage.Resources>
    <ResourceDictionary>
        <x:String x:Key="padding">45, 0, 45, 0</x:String>
    </ResourceDictionary>
</ContentPage.Resources>
<StackLayout Padding="{StaticResource padding}">
    <Label Text="{StaticResource padding}"/>
</StackLayout>
</code>```

答:
As said, you should use Thickness. In addition, for setting your resource at the Application level, put it in your App.xaml file:

```<code><Application ...>
 <Application.Resources>
        <ResourceDictionary>
            <Thickness x:Key="padding">45,0, 45, 0</Thickness>
            // some others resources...
        </ResourceDictionary>
    </Application.Resources>
</Application>
</code>```

Then call it from your different pages:

```<code><ContentPage>
    <StackLayout Padding="{StaticResource padding}">
        <Label Text="{StaticResource padding}"/>
    </StackLayout>
    ...
</code>```

link to documentation

Hope it helps!

Title: Xamarin Forms Padding in StaticResource

Body:
I want to build few pages with specific Padding in sytacklayout. I do not want to wrote it in every pages. And its not good design considering if I want to change it in future. Is there a way to define padding in static resource? So that I can define it in one place App.xml and use it in other pages.

I have tried

<ContentPage.Resources>
    <ResourceDictionary>
        <x:String x:Key="padding">45, 0, 45, 0</x:String>
    </ResourceDictionary>
</ContentPage.Resources>
<StackLayout Padding="{StaticResource padding}">

</StackLayout>

Body:
As said, you should use Thickness. In addition, for setting your resource at the Application level, put it in your App.xaml file:

<Application ...>
 <Application.Resources>
        <ResourceDictionary>
            <Thickness x:Key="padding">45,0, 45, 0</Thickness>
            // some others resources...
        </ResourceDictionary>
    </Application.Resources>
</Application>

Then call it from your different pages:

<ContentPage>
    <StackLayout Padding="{StaticResource padding}">
        <Label Text="{StaticResource padding}"/>
    </StackLayout>
    ...

link to documentation

Hope it helps!


问:
c# - Cross-thread operation not valid
i was facing the exception Cross-thread error on my methods (void) i solved them by :

```<code>public delegate void onitemAdd(ListViewItem client);
public void OnItemAdd(ListViewItem itemtoadd)
{
    if (this.InvokeRequired)
    {
        onitemAdd adder = new onitemAdd(OnItemAdd);
        this.Invoke(adder, new object[] { itemtoadd });
    }
    else
    {
        if (itemtoadd != null)
        ClientsView.Items.Add(itemtoadd);
    }
}
</code>```

but i don't know how can i do the same but to return the value returned in :

```<code>public delegate ListViewItem ItemReturn(Client client);
public ListViewItem OnReturnitem(Client client)
{
    if (this.InvokeRequired)
    {
        ItemReturn itm = new Zserver.Form1.ItemReturn(OnReturnitem);
        this.Invoke(itm, new object[] { client });
        // need to return a value of the invoked method
    }
    else
    {
        ListViewItem item = ClientsView.Items
         .Cast<ListViewItem>()
         .FirstOrDefault(x => x.SubItems[1].Text == client.IPadress);
        return item;
    }
}
</code>```

答:
Solved by : </p>

```<code>object ob = this.Invoke(itm, new object[] { client });
return ob as ListViewItem;
</code>```

Title: c# - Cross-thread operation not valid

Body:
i was facing the exception Cross-thread error on my methods (void) i solved them by :

public delegate void onitemAdd(ListViewItem client);
public void OnItemAdd(ListViewItem itemtoadd)
{
    if (this.InvokeRequired)
    {
        onitemAdd adder = new onitemAdd(OnItemAdd);
        this.Invoke(adder, new object[] { itemtoadd });
    }
    else
    {
        if (itemtoadd != null)
        ClientsView.Items.Add(itemtoadd);
    }
}

but i don't know how can i do the same but to return the value returned in :

public delegate ListViewItem ItemReturn(Client client);
public ListViewItem OnReturnitem(Client client)
{
    if (this.InvokeRequired)
    {
        ItemReturn itm = new Zserver.Form1.ItemReturn(OnReturnitem);
        this.Invoke(itm, new object[] { client });
        // need to return a value of the invoked method
    }
    else
    {
        ListViewItem item = ClientsView.Items
         .Cast<ListViewItem>()
         .FirstOrDefault(x => x.SubItems[1].Text == client.IPadress);
        return item;
    }
}

Body:
Solved by :

object ob = this.Invoke(itm, new object[] { client });
return ob as ListViewItem;


问:
Displaying and hiding content when div with a certain class or id is clicked
I have a 4 divs that are stacked on top of each other. When I click on a given div, I want it to show a content section below it and above the other three divs. When I click the div again, it should hide the content section associated with it. My current code is able to display the content on click but I can't find anything on how to hide that content when I click on the div again.

Here is my code for example

HTML

```<code>                <div class="dropItem wow fadeInLeft">Nature <b class="caret"></b></div>
                <div id="show">
                    <p>Some text here</p>
                </div>

                <div class="dropItem2 wow fadeInLeft">Discovery <b class="caret"></b></div>
                <div id="show2">
                    <p>Some text here</p>
                </div>

                <div class="dropItem3 wow fadeInLeft">Perspective <b class="caret"></b></div>
                <div id="show3">
                    <p>Some text here</p>
                </div>

                <div class="dropItem4 wow fadeInLeft">Mindfullness <b class="caret"></b></div>
                <div id="show4">
                    <p>Some text here</p>
                </div>

            </div>
        </div><!--end about column-->
</code>```

Javascript

```<code>$(document).ready(function(){
    //hide content sections at first
    $("#show").hide();
    $("#show2").hide();
    $("#show3").hide();
   $("#show4").hide();

 //display each content section when corresponding div is clicked
    $(".dropItem").click(function(){
        $("#show").show();
    });

    $(".dropItem2").click(function(){
       $("#show2").show();
    });

    $(".dropItem3").click(function(){
        $("#show3").show();
     });

     $(".dropItem4").click(function(){
         $("#show4").show();
      });

});
</code>```

CSS

```<code>.dropItem, .dropItem2, .dropItem3, .dropItem4 {
 width: 100%;
 height: 25%;
 padding-top: 4%;
 text-align: center;
 border-top: 1px solid #000;
 font-weight: bold;
}

.caret {
 color: teal;
}

#show, #show2, #show3, #show4 {
 width: 100%;
 height: 250px;
 background-color: teal;
 color: #FFFFFF;
 border: 1px solid teal;
}
</code>```

Link to site for example
http://jackloudphoto.com/

答:
Fast and easy answer:    </p>

```<code>var one = -1,
    two = -1,
    three = -1,
    four = -1;

     //hide content sections at first
     $("#show").hide();
     $("#show2").hide();
     $("#show3").hide();
     $("#show4").hide();

     //display each content section when corresponding div is clicked
     $(".dropItem").click(function(){
         if(one == -1)
         $("#show").show();
         else
          $("#show").hide();

          one *= -1;
     });

     $(".dropItem2").click(function(){
        if(two == -1)
         $("#show2").show();
         else
          $("#show2").hide();

          two *= -1;
     });

     $(".dropItem3").click(function(){
         if(three == -1)
         $("#show3").show();
         else
          $("#show3").hide();

          three *= -1;
     });

     $(".dropItem4").click(function(){
         if(four == -1)
         $("#show4").show();
         else
          $("#show4").hide();

          four *= -1;
     });
</code>```

Body:
I have a 4 divs that are stacked on top of each other. When I click on a given div, I want it to show a content section below it and above the other three divs. When I click the div again, it should hide the content section associated with it. My current code is able to display the content on click but I can't find anything on how to hide that content when I click on the div again.

Here is my code for example

HTML

Nature

Some text here

Discovery

Some text here

Perspective

Some text here

Mindfullness

Some text here

Javascript

$(document).ready(function(){
    //hide content sections at first
    $("#show").hide();
    $("#show2").hide();
    $("#show3").hide();
   $("#show4").hide();

 //display each content section when corresponding div is clicked
    $(".dropItem").click(function(){
        $("#show").show();
    });

    $(".dropItem2").click(function(){
       $("#show2").show();
    });

    $(".dropItem3").click(function(){
        $("#show3").show();
     });

     $(".dropItem4").click(function(){
         $("#show4").show();
      });

});

CSS

.dropItem, .dropItem2, .dropItem3, .dropItem4 {
 width: 100%;
 height: 25%;
 padding-top: 4%;
 text-align: center;
 border-top: 1px solid #000;
 font-weight: bold;
}

.caret {
 color: teal;
}

#show, #show2, #show3, #show4 {
 width: 100%;
 height: 250px;
 background-color: teal;
 color: #FFFFFF;
 border: 1px solid teal;
}

Link to site for example
http://jackloudphoto.com/

Body:
Fast and easy answer:

var one = -1,
    two = -1,
    three = -1,
    four = -1;

     //hide content sections at first
     $("#show").hide();
     $("#show2").hide();
     $("#show3").hide();
     $("#show4").hide();

     //display each content section when corresponding div is clicked
     $(".dropItem").click(function(){
         if(one == -1)
         $("#show").show();
         else
          $("#show").hide();

          one *= -1;
     });

     $(".dropItem2").click(function(){
        if(two == -1)
         $("#show2").show();
         else
          $("#show2").hide();

          two *= -1;
     });

     $(".dropItem3").click(function(){
         if(three == -1)
         $("#show3").show();
         else
          $("#show3").hide();

          three *= -1;
     });

     $(".dropItem4").click(function(){
         if(four == -1)
         $("#show4").show();
         else
          $("#show4").hide();

          four *= -1;
     });


问:
Modifying assembly instructions before loading
I have a DLL that I need to load (I have written it and compiled it), and I would like to insert instructions between existing instructions of the assembly code before loading the DLL into memory. Of course, you can't just read every byte and insert them between there because instructions sometimes are multiple bytes.

I was thinking of using something like Udis86 and reading instructions one by one and then writing them to memory, and between them writing my other instructions. Is this a good approach or is there something better?

答:
Shifting instructions is not a good idea. Many x86 instructions are dependent on their position, so if you shift them you'll likely break a lot of things.

What you could do instead is copy the instruction at the place you need to patch; patch there a jmp to some free area, then in that free area put the copied instruction, your extra code and then finally a jmp back to the original code. Not trivial but doable. Check this and this for possible implementations.

That said, why do you need to modify the binary when you could just modify the source instead? You should ask the actual question, not "how to do X [because I decided I need X to solve my problem]".

ContentLicense: CC BY-SA 2.5


问:
Anything in AWS Data Pipeline to stop execution of a certain activity with a decision making script?
we have 5 pipes in our data pipeline which execute on following basis:
pipe 1 - pipe 4 = daily basis
pipe 5 - end of the month.

we are considering an option to create separate pipeline for pipe 5 as it doesn't have any dependency on other pipes.
Is there any way possible I can execute all pipes except pipe 5 with likes of a  decision variable as we have in OOZIE which can successfully ignore the execution of pipe 5 and complete the pipeline without any status of "error"/"Waiting on dependencies"?

答: You're probably better off creating multiple pipelines and setting them on different schedules. If you'd like you spice things up you can use Cloudwatch scheduling and AWS Lambda to schedule pipeline creation/deletion in a cron-like way. You could also use AWS Step functions to define the workflow of each component.</p>


问:
How to use awk to search for min and max values of column in certain files
I know that awk is helpful in trying to find certain things in columns in files, but I'm not sure how to use it to find the min and max values of a column in a group of files. Any advice? To be specific I have four files in a directory that I want to go through awk with.</p>

答:
sort can do the sorting and you can pick up the first and last by any means, for example, with awk

```<code>sort -nk2 file{1..4} | awk 'NR==1{print "min:"$2} END{print "max:"$2}'
</code>```

sorts numerically by the second field of files file1,file2,file3,file4 and print the min and max values.

Since you didn't provide any input files, here is a worked example, for the files

```<code>==> file_0 <==
23 29 84
15 58 19
81 17 48
15 36 49
91 26 89

==> file_1 <==
22 63 57
33 10 50
56 85 4
10 63 1
72 10 48

==> file_2 <==
25 67 89
75 72 90
92 37 89
77 32 19
99 16 70

==> file_3 <==
50 93 71
10 20 55
70 7 51
19 27 63
44 3 46
</code>```

if you run the script, now with a variable column number n

```<code>n=1; sort -k${n}n file_{0..3} |
awk -v n=$n 'NR==1{print "min ("n"):",$n} END{print "max ("n"):",$n}'
</code>```

you'll get

```<code>min (1): 10
max (1): 99
</code>```

and for the other values of n

```<code>n=2; sort ...

min (2): 3
max (2): 93

n=3; sort ...

min (3): 1
max (3): 90
</code>```

Body:
sort can do the sorting and you can pick up the first and last by any means, for example, with awk

sort -nk2 file{1..4} | awk 'NR==1{print "min:"$2} END{print "max:"$2}'

sorts numerically by the second field of files file1,file2,file3,file4 and print the min and max values.

Since you didn't provide any input files, here is a worked example, for the files

==> file_0 <==
23 29 84
15 58 19
81 17 48
15 36 49
91 26 89

==> file_1 <==
22 63 57
33 10 50
56 85 4
10 63 1
72 10 48

==> file_2 <==
25 67 89
75 72 90
92 37 89
77 32 19
99 16 70

==> file_3 <==
50 93 71
10 20 55
70 7 51
19 27 63
44 3 46

if you run the script, now with a variable column number n

n=1; sort -k${n}n file_{0..3} |
awk -v n=$n 'NR==1{print "min ("n"):",$n} END{print "max ("n"):",$n}'

you'll get

min (1): 10
max (1): 99

and for the other values of n

n=2; sort ...

min (2): 3
max (2): 93

n=3; sort ...

min (3): 1
max (3): 90


问:
create constructor for a class extending JsonRequest<JSONObject>
I have created a class in android studio which extends JsonRequest
but android studio gives me an error and wants me to create a constructor because there is no default constructor in the library (volley library) for that.
Actually I'm using volley library to parse a json file in a listview in android.
Cause the json is all Persian text I have created this class to change it to utf-8 encoding.
Please show me how the needed constructor should be like. I have tried some but wasn't correct.</p>

```<code>public class Utf8JsonRequest extends JsonRequest<JSONObject> {
    ...
    @Override
    protected Response<JSONObject> parseNetworkResponse (NetworkResponse   response) {
        try {
            String utf8String = new String(response.data, "UTF-8");
            return Response.success(new JSONObject(utf8String),   HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            // log error
            return Response.error(new ParseError(e));
        } catch (JSONException e) {
            // log error
            return Response.error(new ParseError(e));
        }
    }
}
</code>```

答:
It is the same constructor as JsonRequest :

JsonRequest(int method, String url, String requestBody, Response.Listener listener, Response.ErrorListener errorListener)

Body:
I have created a class in android studio which extends JsonRequest
but android studio gives me an error and wants me to create a constructor because there is no default constructor in the library (volley library) for that.
Actually I'm using volley library to parse a json file in a listview in android.
Cause the json is all Persian text I have created this class to change it to utf-8 encoding.
Please show me how the needed constructor should be like. I have tried some but wasn't correct.

public class Utf8JsonRequest extends JsonRequest<JSONObject> {
    ...
    @Override
    protected Response<JSONObject> parseNetworkResponse (NetworkResponse   response) {
        try {
            String utf8String = new String(response.data, "UTF-8");
            return Response.success(new JSONObject(utf8String),   HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            // log error
            return Response.error(new ParseError(e));
        } catch (JSONException e) {
            // log error
            return Response.error(new ParseError(e));
        }
    }
}


问:
Extracting PDF rows to Rails db?
My source contains only 1,500 objects. At most it may grow to 2,000. I'm obtaining the objects via PDF and parsing with PDF Reader. They are parsed and returned by rows as String objects:

```<code>file = File.open("app/assets/images/file.pdf")
reader = PDF::Reader.new(file)
page = reader.pages[0]
rows = page.text.scan(/^.+/) #String Objects
rows.slice!(0..3)    #Removes Header Info
Sample object :

=> ["1", "3", "215", "06/02/83", "Law,", "Steve"]
</code>```

Then I remove the "," appended to last name and split the String object thus creating a Array Object:

```<code>row = @rows[0].tr(',', '').split #Array Objects
=> ["1", "3", "215", "06/02/83", "Law", "Steve"]   #Array Object
</code>```

I want to iterate through each row and insert into User table via console or form. What methods should I consider?

Thanks!

答:
Lets assume you have mysql with users table in it and active_record gem installed.

If you writing just plain ruby script first you need to require active_record(commonly used ORM in rails), establish connection to db and create User model to get access to the users table via ActiveRecord:

```<code>require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(
  :adapter => 'mysql',
  :host => 'localhost',
  :database => 'your_db_name'
)

class User < ActiveRecord::Base
end
</code>```

So now all you need to do is to iterate over the rows and call User.create method:

```<code>rows.slice!(0..3).each do |row|
  row.reverse! # reverse array so we can easily access its elements with ruby Array methods
  first_name = row.first
  last_name = row.second.sub(/,/, '') # remove ',' symbol
  birth_date = row.third
  ...
  User.create(:first_name => first_name, :last_name => last_name, :birth_date => birth_date, ...) # I assumed you have first_name, last_name, ..., columns in your users table
end
</code>```

Its all can be done in one file.

If you writing something like a rake task in your Rails environment you need to configure db connection in config/database.yml and create User model in app/models dir.

Title: Extracting PDF rows to Rails db?

Body:
My source contains only 1,500 objects. At most it may grow to 2,000. I'm obtaining the objects via PDF and parsing with PDF Reader. They are parsed and returned by rows as String objects:

file = File.open("app/assets/images/file.pdf")
reader = PDF::Reader.new(file)
page = reader.pages[0]
rows = page.text.scan(/^.+/) #String Objects
rows.slice!(0..3)    #Removes Header Info
Sample object :

=> ["1", "3", "215", "06/02/83", "Law,", "Steve"]

Then I remove the "," appended to last name and split the String object thus creating a Array Object:

row = @rows[0].tr(',', '').split #Array Objects
=> ["1", "3", "215", "06/02/83", "Law", "Steve"]   #Array Object

I want to iterate through each row and insert into User table via console or form. What methods should I consider?

Thanks!

Body:
Lets assume you have mysql with users table in it and active_record gem installed.

If you writing just plain ruby script first you need to require active_record(commonly used ORM in rails), establish connection to db and create User model to get access to the users table via ActiveRecord:

require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(
  :adapter => 'mysql',
  :host => 'localhost',
  :database => 'your_db_name'
)

class User < ActiveRecord::Base
end

So now all you need to do is to iterate over the rows and call User.create method:

rows.slice!(0..3).each do |row|
  row.reverse! # reverse array so we can easily access its elements with ruby Array methods
  first_name = row.first
  last_name = row.second.sub(/,/, '') # remove ',' symbol
  birth_date = row.third
  ...
  User.create(:first_name => first_name, :last_name => last_name, :birth_date => birth_date, ...) # I assumed you have first_name, last_name, ..., columns in your users table
end

Its all can be done in one file.

If you writing something like a rake task in your Rails environment you need to configure db connection in config/database.yml and create User model in app/models dir.


问:
Python 3 Update MySQL database table
I have just found the pymysql module for connecting Python to a MySQL database.  I have a database set up with a table named 'loot', loot contains a column called 'wins'.  My code contains a variable named 'won' that is given a value right before the SQL line.  I want the variable 'won' to be entered into the 'wins' column where id=1.  The id=1 row already exists in the database.

The code below throws an error pymysql.err.InternalError: (1054, "Unknown column 'won' in 'field list'")

My Question: Why am I getting this error and what am I doing incorrectly?

The Code:

```<code>import pymysql

# Open database connection
db = pymysql.connect(host='*******',user='******',password='*****',db='******')

# prepare a cursor object using cursor() method
cursor = db.cursor()

won=1

# Prepare SQL query to UPDATE required records
sql = "UPDATE loot SET wins = won WHERE id = 1"

# Execute the SQL command
cursor.execute(sql)

# Commit your changes in the database
db.commit()

# disconnect from server
db.close()
</code>```

答:
MySQL isn't able to read the variable won so you must pass it in as an argument to .execute():

```<code>won = 1
sql = "UPDATE loot SET win = %s WHERE id = %s"
cursor.execute(sql,(won,1))
db.commit()
</code>```

Please note that you have to have a container of some sort as the second argument to .execute(). In this case it is a tuple.

Title: Python 3 Update MySQL database table

Body:
I have just found the pymysql module for connecting Python to a MySQL database.  I have a database set up with a table named 'loot', loot contains a column called 'wins'.  My code contains a variable named 'won' that is given a value right before the SQL line.  I want the variable 'won' to be entered into the 'wins' column where id=1.  The id=1 row already exists in the database.

The code below throws an error pymysql.err.InternalError: (1054, "Unknown column 'won' in 'field list'")

My Question: Why am I getting this error and what am I doing incorrectly?

The Code:

import pymysql

# Open database connection
db = pymysql.connect(host='*******',user='******',password='*****',db='******')

# prepare a cursor object using cursor() method
cursor = db.cursor()

won=1

# Prepare SQL query to UPDATE required records
sql = "UPDATE loot SET wins = won WHERE id = 1"

# Execute the SQL command
cursor.execute(sql)

# Commit your changes in the database
db.commit()

# disconnect from server
db.close()

Body:
MySQL isn't able to read the variable won so you must pass it in as an argument to .execute():

won = 1
sql = "UPDATE loot SET win = %s WHERE id = %s"
cursor.execute(sql,(won,1))
db.commit()

Please note that you have to have a container of some sort as the second argument to .execute(). In this case it is a tuple.


问:
An error occurred while installing actionpack (5.0.2), and Bundler cannot continue
I get a error when I execute rails new myprojectname:

Gem::RemoteFetcher::FetchError: Errno::ETIMEDOUT: Operation timed out -
  SSL_connect (https://rubygems.org/gems/actionpack-5.0.2.gem)

  An error occurred while installing actionpack (5.0.2), and Bundler
  cannot continue.

  Make sure that gem install actionpack -v '5.0.2' succeeds before bundling.

答:
The error information points out:

Make sure that gem install actionpack -v '5.0.2' succeeds before bundling.

So, in your terminal you should execute the:

```<code>$ gem install actionpack -v '5.0.2'
</code>```

Then you rails new your project name again. and overwrite the conflict place.

Body:
The error information points out:

Make sure that gem install actionpack -v '5.0.2' succeeds before bundling.

So, in your terminal you should execute the:

$ gem install actionpack -v '5.0.2'

Then you rails new your project name again. and overwrite the conflict place.


问:
Access_log coming with date and time
I need to use access_log for some automation purpose.
After sometime access_logs are coming with date and time, i want to keep it with the name access_log only.
I have given the name in squid.conf but that is not working for me.
please suggest.</p>

答:
First, check your Squid configuration file and make sure there is no logfile_rotate parameter specified.

Then, check your operating system's logrotate.d folder for a configuration file directing it to rotate Squid's configuration file, and either remove the file completely, or rename it so it has a ".disabled" extension (may not work on all distributions).

On CentOS the logrotate configuration can be found at /etc/logrotate.d/squid.

Title: Access_log coming with date and time


问:
Hiding a subview from another subview class
I am very new to Cocoa and Ojective-C.  "Learning as you go is my philosophy".  This is my first Cocoa project.

Basically, I used Interface Builder to create a main NSView (let's call it MainView), in it I have two sub-NSView (let's call it ViewNS1 and ViewNS2).  And ViewNS1 is bound view1 class and ViewNS2 is bound to view2 class.

When I click on ViewNS1, I would like hide the ViewNS2 view.  In my view1 class view1.m file, I have this [viewNS2 setHidden:YES] in my - (void)mouseDown:(NSEvent *)event.  There was no error when running but it does not work.  I can however successfully do a [viewNS2 setHidden:YES] from within my MainView.m and it worked fine.  Also if I do a [viewNS1 setHidden:YES] from the view1.m then it will hide its own view.

I think this is very fundamental and basic...  But could not find a solution.

"A teaching moment" anyone?

答:
I found the answer from another posting on this site.  This is my solution:
I use this [self.superview hideViews1] in my mouseDown event in view1.m.  Where hideViews1 is a method from MainView.m that will hide all views that are needed to be hidden, [viewNS2 setHidden:YES] etc.</p>


问:
EasyUI change option 'required' dynamically
in html:

```<code> <input id="iCheck"
    class="easyui-switchbutton"
    data-options="onChange:iCheckChange"
 >
 <input id="iCombo"
    class="easyui-combobox"
    data-options="mode:'remote'
                , disabled: true
                , required: false
                , loader: ...
                "
  >
</code>```

in script

```<code>function iCheckChange(aChecked){
  $('#iCombo').combobox(aChecked?'enable':'disable').combobox('options').required = aChecked;
};
</code>```

Code: https://jsfiddle.net/0dbog4of/4/

How repaint iCombo as iCombo2 ?
change 'required' option don`t redraw component :(

答:
```<code><script>
  function iCheckChange(aChecked){
   $('#iCombo').combobox(aChecked?'enable':'disable');
   $('#iCombo').combobox('options').required = aChecked;
   $('#iCombo').combobox('textbox').validatebox('options').required = aChecked;
   $('#iCombo').combobox('validate');
};
</script>
</code>```

http://www.jeasyui.com/forum/index.php?topic=6593.0

Body:
in html:

 <input id="iCheck"
    class="easyui-switchbutton"
    data-options="onChange:iCheckChange"
 >
 <input id="iCombo"
    class="easyui-combobox"
    data-options="mode:'remote'
                , disabled: true
                , required: false
                , loader: ...
                "
  >

in script

function iCheckChange(aChecked){
  $('#iCombo').combobox(aChecked?'enable':'disable').combobox('options').required = aChecked;
};

Code: https://jsfiddle.net/0dbog4of/4/

How repaint iCombo as iCombo2 ?
change 'required' option don`t redraw component :(

Body:
<script>
  function iCheckChange(aChecked){
   $('#iCombo').combobox(aChecked?'enable':'disable');
   $('#iCombo').combobox('options').required = aChecked;
   $('#iCombo').combobox('textbox').validatebox('options').required = aChecked;
   $('#iCombo').combobox('validate');
};
</script>

http://www.jeasyui.com/forum/index.php?topic=6593.0


问:
pypdf Merging multiple pdf files into one pdf
If I have 1000+ pdf files need to be merged into one pdf,

from PyPDF2 import PdfReader, PdfWriter

writer = PdfWriter()

for i in range(1000):
    filepath = f"my/pdfs/{i}.pdf"
    reader = PdfReader(open(filepath, "rb"))
    for page in reader.pages:
        writer.add_page(page)

with open("document-output.pdf", "wb") as fh:
    writer.write(fh)
```

Execute the above code，when reader = PdfReader(open(filepath, "rb")),

An error message：
IOError: [Errno 24] Too many open files:

I think this is a bug, If not, What should I do？

答:
The pdfrw package reads each file all in one go, so will not suffer from the problem of too many open files.  Here is an example concatenation script.

The relevant part -- assumes inputs is a list of input filenames, and outfn is an output file name:

```<code>from pdfrw import PdfReader, PdfWriter

writer = PdfWriter()
for inpfn in inputs:
    writer.addpages(PdfReader(inpfn).pages)
writer.write(outfn)
</code>```

Disclaimer:  I am the primary pdfrw author.

ContentLicense: CC BY-SA 4.0

Body:
If I have 1000+ pdf files need to be merged into one pdf,

from PyPDF2 import PdfReader, PdfWriter

writer = PdfWriter()

for i in range(1000):
    filepath = f"my/pdfs/{i}.pdf"
    reader = PdfReader(open(filepath, "rb"))
    for page in reader.pages:
        writer.add_page(page)

with open("document-output.pdf", "wb") as fh:
    writer.write(fh)

Execute the above code，when reader = PdfReader(open(filepath, "rb")),

An error message：
IOError: [Errno 24] Too many open files:

I think this is a bug, If not, What should I do？

Body:
The pdfrw package reads each file all in one go, so will not suffer from the problem of too many open files.  Here is an example concatenation script.

The relevant part -- assumes inputs is a list of input filenames, and outfn is an output file name:

from pdfrw import PdfReader, PdfWriter

writer = PdfWriter()
for inpfn in inputs:
    writer.addpages(PdfReader(inpfn).pages)
writer.write(outfn)

Disclaimer:  I am the primary pdfrw author.


问:
Can GCC cross-compile for AIX?
I'm trying to build GCC as a cross-compiler for AIX; the host and the build platforms are Linux x86_64, the target is powerpc-aix5.2.0.  I've managed to cross-compile Binutils 2.20.1 and GCC 4.4.7 with native AIX 6.1 headers (from /usr/include) and libs (only /usr/lib/{crt0.o,crt0_64.o,libc.a,libc_r.a,libpthreads.a}).  Then gcc correctly cross-builds simple C code (such as "Hello, world!") into stand-alone executables but it refuses to cross-build shared objects:

collect2: init function found in object < path to cross-compiled libgcc_s.a >

I tried using newer versions of Binutils up to 2.26 with the same result.

Then I found the following comment:

Binutils was updated to support AIX 4.3.3, but has not been maintained, improved, or updated for AIX 5.  It can do simple things, but does not fully support more advanced features.  For instance, some aspects of shared object creation are not complete.

So I tried re-building the above toolchain with target=powerpc-aix4.3.0 (the only difference this time was that I configured GCC with --disable-multilib to avoid the error "Unrecognized opcode: `fmsub'").  I tried both Binutils 2.20.1 and Binutils 2.26 but I still got the error init function found in object libgcc_s.a.

Now I wonder if there is a version of AIX for which cross-compilation, esp. of shared objects, is supported by GCC and Binutils.

答: The answer to your question is "no".  As the comment says, the GCC version of the linker (ld) does not really work for AIX.  All of the open source code that I compile on AIX I use GCC but I use the native ld command.</p>

Title: Can GCC cross-compile for AIX?


问:
Can I send messages to another XboxLiveUser within the Creators Program Xbox Live API?
I want to send a text message from the logged in Xbox Live User to another User. Can i do it with the current available API (C#) and how?

Have scanned the source files but did not find something. May I overlooked?

Edited:
I have added a new idea to Xbox User Voice to include Xbox Live Messaging into the APIS. For people looking into this question please vote for it too Xbox User Voice

答:
No, User Messaging is not supported with the Xbox Creators Program.

You can add this as an idea to the Xbox User Voice (make sure to put it in the Xbox Live Creators Program category) so that we can track interest and update you when any changes occur.


问:
Show Decimal Keyboard in HTML5 iOS 7 / iOS 8
I just have a simple question after having searched for hours now: Is there any possibility to show the decimal keyboard in webbrowsers input fields? input type="number" only shows numbers but i need a comma or dot instead in the bottom left corner.

I tried anything, pattern, step etc., but nothing brings up the decimal keyboard. I only need the numbers and a dot or comma, no A-Z or a-z or anything else.

```<code><input type="number" id="inputNumbers" pattern="[0-9]*" size="30" min="1" max="5">
</code>```

This is what i get:

This is what i want:

答:
https://github.com/mrchandoo/cordova-plugin-decimal-keyboard

Lets you configure the decimal character(instead of . you can change to , )

Body:
I just have a simple question after having searched for hours now: Is there any possibility to show the decimal keyboard in webbrowsers input fields? input type="number" only shows numbers but i need a comma or dot instead in the bottom left corner.

I tried anything, pattern, step etc., but nothing brings up the decimal keyboard. I only need the numbers and a dot or comma, no A-Z or a-z or anything else.

<input type="number" id="inputNumbers" pattern="[0-9]*" size="30" min="1" max="5">

This is what i get:

This is what i want:


问:
how to display name after login php in all other pages not only homepage
I'm having trouble to display my name in all the pages that I have after login in the website :

AuthentificationController.php

```<code> public  function Connex($db,$login,$mdp)
 {

$requser = $db->prepare("SELECT * FROM users WHERE login = ? AND motdepasse
 = ?");
$requser->execute(array($login,$mdp));
$userexist = $requser->rowCount();
if($userexist == 1)
{
$userinfo = $requser->fetch();
$_SESSION['login'] = $userinfo['login'];
$_SESSION['motdepasse'] = $userinfo['motdepasse'];
if($userinfo['role']=="admin")
{
session_start();
header("Location:/ProjetWeb2A1 - Copie/account.php?id=".$_SESSION['login']);
}

else if($userinfo['role']=="client")
{
session_start();

header("Location:/ProjetWeb2A1 - Copie/accueil.php?id=".$_SESSION['login']);
}
}
</code>```

Homepage.php

```<code><div class="header">
        <div class="header-left">
            <ul>
                <li><a href="account.php">Inscription</a></li>
                <li class="login">
                    <div id="loginContainer"><a id="loginButton"><span>Se Connecter</span></a>
                        <div id="loginBox" style="display: none;">
                            <form id="loginForm"  method="POST" action="\ProjetWeb2A1 - Copie\controllers\Authentification_controller.php">
                                        <label>Login</label>
                                        <input type="text" name="login" id="email" >
                                        <label for="password">Mot de passe</label>
                                        <input type="password" name="password" id="password">
                                    <input type="submit" id="login" value="Connexion" name="xxl1">
                                    <label for="checkbox"><input type="checkbox" id="checkbox"> <i>Rester Connecté</i></label>
                                <span><a href="#">Mot de passe oublié?</a></span>
                            </form>
                        </div>
                    </div>
                </li>
            </ul>
        </div>
</code>```

If someone could answer me what i need to do to change that Inscription and Se

Connecter with my username in all my other pages please

答:
You can do it like this :

Add a php file (functions.php in this example) with this content

```<code><?php
    function logged_in () {
        if (isset($_SESSION['login'])) {
            return true;
        } else {
            return false;
        }
    }

    function redirect_to ($url) {
        header("Location: {$url}");
    }
?>
</code>```

Then, in your Homepage.php, import the saved file and check if the user is connected like this

```<code>require_once("functions.php");
<div class="header-left">
      <?php if (logged_in() == false) { ?>
        <ul>
            <li><a href="account.php">Inscription</a></li>
            <li class="login">
                <div id="loginContainer"><a id="loginButton"><span>Se Connecter</span></a>
                    <div id="loginBox" style="display: none;">
                        <form id="loginForm"  method="POST" action="\ProjetWeb2A1 - Copie\controllers\Authentification_controller.php">
                                    <label>Login</label>
                                    <input type="text" name="login" id="email" >
                                    <label for="password">Mot de passe</label>
                                    <input type="password" name="password" id="password">
                                <input type="submit" id="login" value="Connexion" name="xxl1">
                                <label for="checkbox"><input type="checkbox" id="checkbox"> <i>Rester Connecté</i></label>
                            <span><a href="#">Mot de passe oublié?</a></span>
                        </form>
                    </div>
                </div>
            </li>
        </ul>
        <?php } else { $name = $_SESSION['name']; ?>
            <h1> Hello <?=$name?> </h1>
         <?php } ?>
    </div>
</code>```

You should save the $_SESSION['name'] in your AuthentificationController.php

Body:
I'm having trouble to display my name in all the pages that I have after login in the website :

AuthentificationController.php

 public  function Connex($db,$login,$mdp)
 {

$requser = $db->prepare("SELECT * FROM users WHERE login = ? AND motdepasse
 = ?");
$requser->execute(array($login,$mdp));
$userexist = $requser->rowCount();
if($userexist == 1)
{
$userinfo = $requser->fetch();
$_SESSION['login'] = $userinfo['login'];
$_SESSION['motdepasse'] = $userinfo['motdepasse'];
if($userinfo['role']=="admin")
{
session_start();
header("Location:/ProjetWeb2A1 - Copie/account.php?id=".$_SESSION['login']);
}

else if($userinfo['role']=="client")
{
session_start();

header("Location:/ProjetWeb2A1 - Copie/accueil.php?id=".$_SESSION['login']);
}
}

Homepage.php

Inscription

Se Connecter

                            <form id="loginForm"  method="POST" action="\ProjetWeb2A1 - Copie\controllers\Authentification_controller.php">
                                        Login
                                        <input type="text" name="login" id="email" >
                                        Mot de passe
                                        <input type="password" name="password" id="password">
                                    <input type="submit" id="login" value="Connexion" name="xxl1">
                                    <input type="checkbox" id="checkbox"> Rester Connecté
                                Mot de passe oublié?
                            </form>

If someone could answer me what i need to do to change that Inscription and Se

Connecter with my username in all my other pages please

Body:
You can do it like this :

Add a php file (functions.php in this example) with this content

<?php
    function logged_in () {
        if (isset($_SESSION['login'])) {
            return true;
        } else {
            return false;
        }
    }

    function redirect_to ($url) {
        header("Location: {$url}");
    }
?>

Then, in your Homepage.php, import the saved file and check if the user is connected like this

require_once("functions.php");
<div class="header-left">
      <?php if (logged_in() == false) { ?>
        <ul>
            <li><a href="account.php">Inscription</a></li>
            <li class="login">
                <div id="loginContainer"><a id="loginButton"><span>Se Connecter</span></a>
                    <div id="loginBox" style="display: none;">
                        <form id="loginForm"  method="POST" action="\ProjetWeb2A1 - Copie\controllers\Authentification_controller.php">
                                    <label>Login</label>
                                    <input type="text" name="login" id="email" >
                                    <label for="password">Mot de passe</label>
                                    <input type="password" name="password" id="password">
                                <input type="submit" id="login" value="Connexion" name="xxl1">
                                <label for="checkbox"><input type="checkbox" id="checkbox"> <i>Rester Connecté</i></label>
                            <span><a href="#">Mot de passe oublié?</a></span>
                        </form>
                    </div>
                </div>
            </li>
        </ul>
        <?php } else { $name = $_SESSION['name']; ?>
            <h1> Hello <?=$name?> </h1>
         <?php } ?>
    </div>

You should save the $_SESSION['name'] in your AuthentificationController.php


问:
Asp.Net MVC 2 - Bind a model's property to a different named value
Update (21st Sept 2016) - Thanks to Digbyswift for commenting that this solution still works in MVC5 also.

Update (30th April 2012) - Note to people stumbling across this question from searches etc - the accepted answer is not how I ended up doing this - but I left it accepted because it might have worked in some cases.  My own answer contains the final solution I used, which is reusable and will apply to any project.

It's also confirmed to work in v3 and v4 of the MVC framework.

I have the following model type (the names of the class and its properties have been changed to protect their identities):

```<code>public class MyExampleModel
{
  public string[] LongPropertyName { get; set; }
}
</code>```

This property is then bound to a bunch (>150) of check boxes, where each one's input name is of course LongPropertyName.

The form submits to url with an HTTP GET, and say the user selects three of those checkboxes - the url will have the query string ?LongPropertyName=a&LongPropertyName=b&LongPropertyName=c

Big problem then is that if I select all (or even just over half!) the checkboxes, I exceed the maximum query string length enforced by the request filter on IIS!

I do not want to extend that - so I want a way to trim down this query string (I know I can just switch to a POST - but even so I still want to minimize the amount of fluff in the data sent by the client).

What I want to do is have the LongPropertyName bound to simply 'L' so the query string would become ?L=a&L=b&L=c but without changing the property name in code.

The type in question already has a custom model binder (deriving from DefaultModelBinder), but it's attached to its base class - so I don't want to put code in there for a derived class.  All the property binding is currently performed by the standard DefaultModelBinder logic, which I know uses TypeDescriptors and Property Descriptors etc from System.ComponentModel.

I was kinda hoping that there might be an attribute I could apply to the property to make this work - is there?  Or should I be looking at implementing ICustomTypeDescriptor?

答:
In response to michaelalm's answer and request - here's what I've ended up doing.  I've left the original answer ticked mainly out of courtesy since one of the solutions suggested by Nathan would have worked.

The output of this is a replacement for DefaultModelBinder class which you can either register globally (thereby allowing all model types to take advantage of aliasing) or selectively inherit for custom model binders.

It all starts, predictably with:

```<code>/// <summary>
/// Allows you to create aliases that can be used for model properties at
/// model binding time (i.e. when data comes in from a request).
///
/// The type needs to be using the DefaultModelBinderEx model binder in
/// order for this to work.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class BindAliasAttribute : Attribute
{
  public BindAliasAttribute(string alias)
  {
    //ommitted: parameter checking
    Alias = alias;
  }
  public string Alias { get; private set; }
}
</code>```

And then we get this class:

```<code>internal sealed class AliasedPropertyDescriptor : PropertyDescriptor
{
  public PropertyDescriptor Inner { get; private set; }

  public AliasedPropertyDescriptor(string alias, PropertyDescriptor inner)
    : base(alias, null)
  {
    Inner = inner;
  }

  public override bool CanResetValue(object component)
  {
    return Inner.CanResetValue(component);
  }

  public override Type ComponentType
  {
    get { return Inner.ComponentType; }
  }

  public override object GetValue(object component)
  {
    return Inner.GetValue(component);
  }

  public override bool IsReadOnly
  {
    get { return Inner.IsReadOnly; }
  }

  public override Type PropertyType
  {
    get { return Inner.PropertyType; }
  }

  public override void ResetValue(object component)
  {
    Inner.ResetValue(component);
  }

  public override void SetValue(object component, object value)
  {
    Inner.SetValue(component, value);
  }

  public override bool ShouldSerializeValue(object component)
  {
    return Inner.ShouldSerializeValue(component);
  }
}
</code>```

This proxies a 'proper' PropertyDescriptor that is normally found by the DefaultModelBinder but presents its name as the alias.

Next we have the new model binder class:

UPDATED WITH @jsabrooke's suggestion below

```<code>public class DefaultModelBinderEx : DefaultModelBinder
{
  protected override System.ComponentModel.PropertyDescriptorCollection
    GetModelProperties(ControllerContext controllerContext,
                      ModelBindingContext bindingContext)
  {
    var toReturn = base.GetModelProperties(controllerContext, bindingContext);

    List<PropertyDescriptor> additional = new List<PropertyDescriptor>();

    //now look for any aliasable properties in here
    foreach (var p in
      this.GetTypeDescriptor(controllerContext, bindingContext)
      .GetProperties().Cast<PropertyDescriptor>())
    {
      foreach (var attr in p.Attributes.OfType<BindAliasAttribute>())
      {
        additional.Add(new AliasedPropertyDescriptor(attr.Alias, p));

        if (bindingContext.PropertyMetadata.ContainsKey(p.Name)
            && !string.Equals(p.Name, attr.Alias, StringComparison.OrdinalIgnoreCase)))
        {
            bindingContext.PropertyMetadata.Add(
                attr.Alias,
                bindingContext.PropertyMetadata[p.Name]);
        }
      }
    }

    return new PropertyDescriptorCollection
      (toReturn.Cast<PropertyDescriptor>().Concat(additional).ToArray());
  }
}
</code>```

And, then technically, that's all there is to it.  You can now register this DefaultModelBinderEx class as the default using the solution posted as the answer in this SO: Change the default model binder in asp.net MVC, or you can use it as a base for your own model binder.

Once you've selected your pattern for how you want the binder to kick in, you simply apply it to a model type as follows:

```<code>public class TestModelType
{
    [BindAlias("LPN")]
    //and you can add multiple aliases
    [BindAlias("L")]
    //.. ad infinitum
    public string LongPropertyName { get; set; }
}
</code>```

The reason I chose this code was because I wanted something that would work with custom type descriptors as well as being able to work with any type.  Equally, I wanted the value provider system to be used still in sourcing the model property values.  So I've changed the meta data that the DefaultModelBinder sees when it starts binding.  It's a slightly more long-winded approach - but conceptually it's doing at the meta data level exactly what you want it to do.

One potentially interesting, and slightly annoying, side effect will be if the ValueProvider contains values for more than one alias, or an alias and the property by it's name.  In this case, only one of the retrieved values will be used.  Difficult to think of a way of merging them all in a type-safe way when you're just working with objects though.  This is similar, though, to supplying a value in both a form post and query string - and I'm not sure exactly what MVC does in that scenario - but I don't think it's recommended practise.

Another problem is, of course, that you must not create an alias that equals another alias, or indeed the name of an actual property.

I like to apply my model binders, in general, using the CustomModelBinderAttribute class.  The only problem with this can be if you need to derive from the model type and change it's binding behaviour - since the CustomModelBinderAttribute is inherited in the attribute search performed by MVC.

In my case this is okay, I'm developing a new site framework and am able to push new extensibility into my base binders using other mechanisms to satisfy these new types; but that won't be the case for everybody.

Body:
Update (21st Sept 2016) - Thanks to Digbyswift for commenting that this solution still works in MVC5 also.

Update (30th April 2012) - Note to people stumbling across this question from searches etc - the accepted answer is not how I ended up doing this - but I left it accepted because it might have worked in some cases.  My own answer contains the final solution I used, which is reusable and will apply to any project.

It's also confirmed to work in v3 and v4 of the MVC framework.

I have the following model type (the names of the class and its properties have been changed to protect their identities):

public class MyExampleModel
{
  public string[] LongPropertyName { get; set; }
}

This property is then bound to a bunch (>150) of check boxes, where each one's input name is of course LongPropertyName.

The form submits to url with an HTTP GET, and say the user selects three of those checkboxes - the url will have the query string ?LongPropertyName=a&LongPropertyName=b&LongPropertyName=c

Big problem then is that if I select all (or even just over half!) the checkboxes, I exceed the maximum query string length enforced by the request filter on IIS!

I do not want to extend that - so I want a way to trim down this query string (I know I can just switch to a POST - but even so I still want to minimize the amount of fluff in the data sent by the client).

What I want to do is have the LongPropertyName bound to simply 'L' so the query string would become ?L=a&L=b&L=c but without changing the property name in code.

The type in question already has a custom model binder (deriving from DefaultModelBinder), but it's attached to its base class - so I don't want to put code in there for a derived class.  All the property binding is currently performed by the standard DefaultModelBinder logic, which I know uses TypeDescriptors and Property Descriptors etc from System.ComponentModel.

I was kinda hoping that there might be an attribute I could apply to the property to make this work - is there?  Or should I be looking at implementing ICustomTypeDescriptor?

Body:
In response to michaelalm's answer and request - here's what I've ended up doing.  I've left the original answer ticked mainly out of courtesy since one of the solutions suggested by Nathan would have worked.

The output of this is a replacement for DefaultModelBinder class which you can either register globally (thereby allowing all model types to take advantage of aliasing) or selectively inherit for custom model binders.

It all starts, predictably with:

/// <summary>
/// Allows you to create aliases that can be used for model properties at
/// model binding time (i.e. when data comes in from a request).
///
/// The type needs to be using the DefaultModelBinderEx model binder in
/// order for this to work.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class BindAliasAttribute : Attribute
{
  public BindAliasAttribute(string alias)
  {
    //ommitted: parameter checking
    Alias = alias;
  }
  public string Alias { get; private set; }
}

And then we get this class:

internal sealed class AliasedPropertyDescriptor : PropertyDescriptor
{
  public PropertyDescriptor Inner { get; private set; }

  public AliasedPropertyDescriptor(string alias, PropertyDescriptor inner)
    : base(alias, null)
  {
    Inner = inner;
  }

  public override bool CanResetValue(object component)
  {
    return Inner.CanResetValue(component);
  }

  public override Type ComponentType
  {
    get { return Inner.ComponentType; }
  }

  public override object GetValue(object component)
  {
    return Inner.GetValue(component);
  }

  public override bool IsReadOnly
  {
    get { return Inner.IsReadOnly; }
  }

  public override Type PropertyType
  {
    get { return Inner.PropertyType; }
  }

  public override void ResetValue(object component)
  {
    Inner.ResetValue(component);
  }

  public override void SetValue(object component, object value)
  {
    Inner.SetValue(component, value);
  }

  public override bool ShouldSerializeValue(object component)
  {
    return Inner.ShouldSerializeValue(component);
  }
}

This proxies a 'proper' PropertyDescriptor that is normally found by the DefaultModelBinder but presents its name as the alias.

Next we have the new model binder class:

UPDATED WITH @jsabrooke's suggestion below

public class DefaultModelBinderEx : DefaultModelBinder
{
  protected override System.ComponentModel.PropertyDescriptorCollection
    GetModelProperties(ControllerContext controllerContext,
                      ModelBindingContext bindingContext)
  {
    var toReturn = base.GetModelProperties(controllerContext, bindingContext);

    List<PropertyDescriptor> additional = new List<PropertyDescriptor>();

    //now look for any aliasable properties in here
    foreach (var p in
      this.GetTypeDescriptor(controllerContext, bindingContext)
      .GetProperties().Cast<PropertyDescriptor>())
    {
      foreach (var attr in p.Attributes.OfType<BindAliasAttribute>())
      {
        additional.Add(new AliasedPropertyDescriptor(attr.Alias, p));

        if (bindingContext.PropertyMetadata.ContainsKey(p.Name)
            && !string.Equals(p.Name, attr.Alias, StringComparison.OrdinalIgnoreCase)))
        {
            bindingContext.PropertyMetadata.Add(
                attr.Alias,
                bindingContext.PropertyMetadata[p.Name]);
        }
      }
    }

    return new PropertyDescriptorCollection
      (toReturn.Cast<PropertyDescriptor>().Concat(additional).ToArray());
  }
}

And, then technically, that's all there is to it.  You can now register this DefaultModelBinderEx class as the default using the solution posted as the answer in this SO: Change the default model binder in asp.net MVC, or you can use it as a base for your own model binder.

Once you've selected your pattern for how you want the binder to kick in, you simply apply it to a model type as follows:

public class TestModelType
{
    [BindAlias("LPN")]
    //and you can add multiple aliases
    [BindAlias("L")]
    //.. ad infinitum
    public string LongPropertyName { get; set; }
}

The reason I chose this code was because I wanted something that would work with custom type descriptors as well as being able to work with any type.  Equally, I wanted the value provider system to be used still in sourcing the model property values.  So I've changed the meta data that the DefaultModelBinder sees when it starts binding.  It's a slightly more long-winded approach - but conceptually it's doing at the meta data level exactly what you want it to do.

One potentially interesting, and slightly annoying, side effect will be if the ValueProvider contains values for more than one alias, or an alias and the property by it's name.  In this case, only one of the retrieved values will be used.  Difficult to think of a way of merging them all in a type-safe way when you're just working with objects though.  This is similar, though, to supplying a value in both a form post and query string - and I'm not sure exactly what MVC does in that scenario - but I don't think it's recommended practise.

Another problem is, of course, that you must not create an alias that equals another alias, or indeed the name of an actual property.

I like to apply my model binders, in general, using the CustomModelBinderAttribute class.  The only problem with this can be if you need to derive from the model type and change it's binding behaviour - since the CustomModelBinderAttribute is inherited in the attribute search performed by MVC.

In my case this is okay, I'm developing a new site framework and am able to push new extensibility into my base binders using other mechanisms to satisfy these new types; but that won't be the case for everybody.