问:
Increment an attribute in postgresql function
Below is my function for inserting values in a table .. However i want the numofexisting attribute to be an increasing number so as to be unique .. how can I make it happen ?</p>

```<code> CREATE OR REPLACE FUNCTION insert_CourseRun()
    RETURNS VOID AS
    $$
    DECLARE curr_sem integer;
    DECLARE curr_season semester_season_type;
    DECLARE curr_year smallint ;
    DECLARE numofexisting integer;
    BEGIN
        numofexisting := (SELECT COUNT(*) FROM public."courserun") + 1 ;
        curr_sem := (SELECT s.semester_id FROM "semester" as s WHERE s.semester_status = 'present');
        if (curr_sem % 2 = 0) then
            curr_season = 'spring';
            curr_year = curr_sem /2;
        else
            curr_season = 'winter';
            curr_year = (curr_sem+1) /2;
        end if;

        INSERT INTO public."courserun"
        SELECT c.course_code, numofexisting, 5, 5, 2, curr_sem, labcode_for_course(c.course_code)
        FROM "Course" as c
        WHERE c.typical_season= curr_season and c.typical_year = curr_year;
    END;
    $$
    LANGUAGE 'plpgsql' VOLATILE;
</code>```

答:
Create a sequence:

```<code>/* instead of 42, use a value larger than the current maximim value */
CREATE SEQUENCE courserun_seq START 42;
</code>```

Then insert like this:

```<code>INSERT INTO courserun (..., numofexisting, ...)
   VALUES (..., nextval('courserun_seq'), ...);
</code>```

This would assume that all inserts into the tabe are done this way.

You can also change the table to automatically use a default value:

```<code>ALTER TABLE courserun
   ALTER numofexisting SET DEFAULT nextval('courserun_seq');
</code>```

Then you can either omit the column in the INSERT column list or use the value DEFAULT like this:

```<code>INSERT INTO courserun (..., numofexisting, ...)
   VALUES (..., DEFAULT, ...);
</code>```

Body:
Below is my function for inserting values in a table .. However i want the numofexisting attribute to be an increasing number so as to be unique .. how can I make it happen ?

 CREATE OR REPLACE FUNCTION insert_CourseRun()
    RETURNS VOID AS
    $$
    DECLARE curr_sem integer;
    DECLARE curr_season semester_season_type;
    DECLARE curr_year smallint ;
    DECLARE numofexisting integer;
    BEGIN
        numofexisting := (SELECT COUNT(*) FROM public."courserun") + 1 ;
        curr_sem := (SELECT s.semester_id FROM "semester" as s WHERE s.semester_status = 'present');
        if (curr_sem % 2 = 0) then
            curr_season = 'spring';
            curr_year = curr_sem /2;
        else
            curr_season = 'winter';
            curr_year = (curr_sem+1) /2;
        end if;

        INSERT INTO public."courserun"
        SELECT c.course_code, numofexisting, 5, 5, 2, curr_sem, labcode_for_course(c.course_code)
        FROM "Course" as c
        WHERE c.typical_season= curr_season and c.typical_year = curr_year;
    END;
    $$
    LANGUAGE 'plpgsql' VOLATILE;

Body:
Create a sequence:

/* instead of 42, use a value larger than the current maximim value */
CREATE SEQUENCE courserun_seq START 42;

Then insert like this:

INSERT INTO courserun (..., numofexisting, ...)
   VALUES (..., nextval('courserun_seq'), ...);

This would assume that all inserts into the tabe are done this way.

You can also change the table to automatically use a default value:

ALTER TABLE courserun
   ALTER numofexisting SET DEFAULT nextval('courserun_seq');

Then you can either omit the column in the INSERT column list or use the value DEFAULT like this:

INSERT INTO courserun (..., numofexisting, ...)
   VALUES (..., DEFAULT, ...);


来源: stackexchange

问:
Excel - COUNTIF and SUMIF across multiple rows
I have a sheet with multiple columns of "Yes" / "No". I need to count the number of rows that have >5 "Yes". Obviously determining if an individual row should be included is easy using countif, but I can't figure out how to make the row 'eligible to be counted' and then sum the number of rows that meet my criteria.</p>

答:
Assuming your range is A2:Z100 this array formula will count the number of rows with 5 or more "Yes" entries

=SUM((MMULT((A2:Z100="Yes")+0,TRANSPOSE(COLUMN(A2:Z100)^0))>=5)+0)

confirm with CTRL+SHIFT+ENTER

or you can use this version with FREQUENCY

=SUM(IF(FREQUENCY(IF(A2:Z100="Yes",ROW(A2:Z100)),ROW(A2:Z100))>=5,1))

....which also needs "array entry"

or a third approach with COUNTIF - doesn't need array entry

=SUMPRODUCT(0+(COUNTIF(OFFSET(A2:Z100,ROW(A2:A100)-ROW(A2),0,1),"Yes")>=5))

ContentLicense: CC BY-SA 3.0


问:
Bootstrap: How to make table shrink to screen?
When I shrink my browser screen to mimic a mobile display, the table acts like I want it to: it shrinks to fit. View here:

However, when I enter Responsive Design Mode on Safari (or when I visit the site on a mobile device), the table cuts off. View here:

As you can tell in the second photo, I have a
 wrapped around my table. This makes the table scrollable on a mobile display. I don't want a scroll, I want it to display everything, just shrunk a bit.

My data cells' widths are set to percentages (e.g. 5%, 10%, 30%) so it's not like the table is being forced into overflow.

Any help would be appreciated.

答:
Try using a media query for devices to change the CSS for only that device.
Something like...</p>

```<code>@media only screen
  and (min-device-width: 320px)
  and (max-device-width: 480px)
  and (-webkit-min-device-pixel-ratio: 2)
  and (orientation: portrait) {
// insert CSS here to make adjustments for this view

}
</code>```

Body:
Try using a media query for devices to change the CSS for only that device.
Something like...

@media only screen
  and (min-device-width: 320px)
  and (max-device-width: 480px)
  and (-webkit-min-device-pixel-ratio: 2)
  and (orientation: portrait) {
// insert CSS here to make adjustments for this view

}


问:
ng-click is not firing
adding the following 'hyperlink' to html like:

```<code><a style="color:white" ng-click="ClickMe()"><i class="fa fa-trash-o" style="color:white"></i>Click</a>
</code>```

and then use this code to trigger click event like

```<code> $scope.ClickMe = function () { alert("clicked"); }
</code>```

works fine, but this did not work when  'hyperlink' generated dynamically like

```<code> $('<a style="color:white" ng-click="ClickMe()"><i class="fa fa-trash-o" style="color:white"></i>Click</a>').insertAfter("#dashboard_link");
</code>```

Could anyone explain why did that happen?

答:
The problem is when you are using JQuery you haven't compiled it in a DOM.

You have to use $compile which Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

Means $compile compiles the new DOM and link it to the current scope.

Please refer to the AngularJs Docs for more detail.

Title: ng-click is not firing

Body:
adding the following 'hyperlink' to html like:

Click

and then use this code to trigger click event like

 $scope.ClickMe = function () { alert("clicked"); }

works fine, but this did not work when  'hyperlink' generated dynamically like

 $('Click').insertAfter("#dashboard_link");

Could anyone explain why did that happen?


问:
identifying the device for iPad iOS 4.2
I understood that iOS 4.2 is for iPad as well. The code below is the standard pattern which we all use for identifying the device. how will this change for the 4.2 iPad. Should i change the code to consider the device type rather than version ?</p>

```<code>#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
    CGRect frame = [[UIScreen mainScreen] bounds];
    self.view.frame = frame;
#else
    CGRect frame = [self.view bounds];
#endif
</code>```

答:
A better way would be [[UIDevice currentDevice] userInterfaceIdiom]

First check that the currentDevice responds to that selector. If not, then it's an iPhone/iPod running iOS 3.1.x or earlier.

If it does respond to that selector, then you can check the result for UIUserInterfaceIdiomPhone or UIUserInterfaceIdiomPad.

ContentLicense: CC BY-SA 2.5

Title: identifying the device for iPad iOS 4.2

Body:
I understood that iOS 4.2 is for iPad as well. The code below is the standard pattern which we all use for identifying the device. how will this change for the 4.2 iPad. Should i change the code to consider the device type rather than version ?

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
    CGRect frame = [[UIScreen mainScreen] bounds];
    self.view.frame = frame;
#else
    CGRect frame = [self.view bounds];
#endif


问:
Using php.net's password_verify" script as offered works, but fails if hash is read back from DB
php.net script: http://php.net/manual/en/function.password-hash.php
and: http://php.net/manual/en/function.password-verify.php

The apparent simplicity of this password verification routine is very appealing, but after a day of reading at stackoverflow and innumerable hacks, here is my very simple, not-at-all-secure, testing version:

```<code><?php

$p = "bumblebee";
$hash =  (password_hash($p, PASSWORD_DEFAULT));

echo ($p);
echo ($hash);

if (password_verify('bumblebee', $hash)) {
    echo 'Password is valid!';
    } else {
    echo 'Invalid password.';
    }

?>
</code>```

ABOVE RETURNS 'Password is valid!' (this is two scripts from PHP.net combined)

BELOW DOES NOT WORK (only diff is the hash is written to DB and read back, then converted to a string)

```<code><?php

$userName = $_REQUEST["userName"];
$passWord = $_REQUEST["passWord"];

// $p = "$passWord";
// $hash =  (password_hash($p, PASSWORD_DEFAULT));

    //set DB access variables
    require_once('./php/hs_DBlogin.php');

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $passWord_get = mysqli_query($conn, "SELECT passWordHash FROM hsUser WHERE userName='$userName' LIMIT 1");
    $passWord_out = mysqli_fetch_array($passWord_get);
    $hashAsStr = $passWord_out[0];

    echo ($hashAsStr);
    echo ($_REQUEST["passWord"]);

if (password_verify($_REQUEST["passWord"], $hashAsStr)) {
    echo 'Password is valid!';
    } else {
    echo 'Invalid password.';
    }

?>

Here is the insert to DB script:

// Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$passWordHash = password_hash('$passWord', PASSWORD_DEFAULT);

$sql = "INSERT INTO `hsUser`(`firstName`, `lastName`, `userName`, `passWordHash`,`hsStatus`) VALUES ('$firstName','$lastName','$userName','$passWordHash','$hsStatus')";
</code>```

答:
Please don't give up so fast, your alternative method using SHA256 is an extremely unsafe method to store your user's passwords.

As others already mentioned, it is recommended to use a varchar(255) field. According to your comments this is not the problem though.

If the code you are showing for the registration is exactly your working code, then the culprit is very likely this line:

```<code>$passWordHash = password_hash('$passWord', PASSWORD_DEFAULT);
</code>```

This statement will create a hash of the text '$passWord' and not from the variable $passWord, so instead it should be:

```<code>$passWordHash = password_hash($passWord, PASSWORD_DEFAULT);
</code>```

Body:
php.net script: http://php.net/manual/en/function.password-hash.php
and: http://php.net/manual/en/function.password-verify.php

The apparent simplicity of this password verification routine is very appealing, but after a day of reading at stackoverflow and innumerable hacks, here is my very simple, not-at-all-secure, testing version:

<?php

$p = "bumblebee";
$hash =  (password_hash($p, PASSWORD_DEFAULT));

echo ($p);
echo ($hash);

if (password_verify('bumblebee', $hash)) {
    echo 'Password is valid!';
    } else {
    echo 'Invalid password.';
    }

?>

ABOVE RETURNS 'Password is valid!' (this is two scripts from PHP.net combined)

BELOW DOES NOT WORK (only diff is the hash is written to DB and read back, then converted to a string)

<?php

$userName = $_REQUEST["userName"];
$passWord = $_REQUEST["passWord"];

// $p = "$passWord";
// $hash =  (password_hash($p, PASSWORD_DEFAULT));

    //set DB access variables
    require_once('./php/hs_DBlogin.php');

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $passWord_get = mysqli_query($conn, "SELECT passWordHash FROM hsUser WHERE userName='$userName' LIMIT 1");
    $passWord_out = mysqli_fetch_array($passWord_get);
    $hashAsStr = $passWord_out[0];

    echo ($hashAsStr);
    echo ($_REQUEST["passWord"]);

if (password_verify($_REQUEST["passWord"], $hashAsStr)) {
    echo 'Password is valid!';
    } else {
    echo 'Invalid password.';
    }

?>

Here is the insert to DB script:

// Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$passWordHash = password_hash('$passWord', PASSWORD_DEFAULT);

$sql = "INSERT INTO `hsUser`(`firstName`, `lastName`, `userName`, `passWordHash`,`hsStatus`) VALUES ('$firstName','$lastName','$userName','$passWordHash','$hsStatus')";

Body:
Please don't give up so fast, your alternative method using SHA256 is an extremely unsafe method to store your user's passwords.

As others already mentioned, it is recommended to use a varchar(255) field. According to your comments this is not the problem though.

If the code you are showing for the registration is exactly your working code, then the culprit is very likely this line:

$passWordHash = password_hash('$passWord', PASSWORD_DEFAULT);

This statement will create a hash of the text '$passWord' and not from the variable $passWord, so instead it should be:

$passWordHash = password_hash($passWord, PASSWORD_DEFAULT);


问:
How to resolve Duplicate files copied in APK META-INF/rxjava.properties
I am using rxjava and rxvolley on my android aplication. When I try to run it I get this error

```<code>Execution failed for task ':testapp:transformResourcesWithMergeJavaResForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/rxjava.properties
            File1: C:\Users\Daniel\.gradle\caches\modules-2\files-2.1\io.reactivex\rxjava\1.1.0\748f0546d5c3c27f1aef07270ffea0c45f0c42a4\rxjava-1.1.0.jar
            File2: C:\Users\Daniel\.gradle\caches\modules-2\files-2.1\io.reactivex.rxjava2\rxjava\2.0.3\d2f725668bd22e21170381b23f8fbdf72c69d886\rxjava-2.0.3.jar
</code>```

I have a exclude.gradle file like this

```<code>android {
packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/rxjava.properties'
    exclude 'META-INF/rxjava.PROPERTIES'
    exclude 'META-INF/RXJAVA.properties'
    exclude 'META-INF/RXJAVA.PROPERTIES'
    exclude 'META-INF/rxjava'
    exclude 'META-INF/RXJAVA'
}

lintOptions {
    abortOnError false
}
}
</code>```

How can I fix this problem?

答:
I had the same problem. The way I fixed it is adding the packagingOptions in app gradle as described in Duplicated file rxjava.properties

```<code>android {

    defaultConfig {
    }
    buildTypes {
    }
    packagingOptions{
        exclude 'META-INF/rxjava.properties'
    }
}
</code>```

Body:
I am using rxjava and rxvolley on my android aplication. When I try to run it I get this error

Execution failed for task ':testapp:transformResourcesWithMergeJavaResForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/rxjava.properties
            File1: C:\Users\Daniel\.gradle\caches\modules-2\files-2.1\io.reactivex\rxjava\1.1.0\748f0546d5c3c27f1aef07270ffea0c45f0c42a4\rxjava-1.1.0.jar
            File2: C:\Users\Daniel\.gradle\caches\modules-2\files-2.1\io.reactivex.rxjava2\rxjava\2.0.3\d2f725668bd22e21170381b23f8fbdf72c69d886\rxjava-2.0.3.jar

I have a exclude.gradle file like this

android {
packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/rxjava.properties'
    exclude 'META-INF/rxjava.PROPERTIES'
    exclude 'META-INF/RXJAVA.properties'
    exclude 'META-INF/RXJAVA.PROPERTIES'
    exclude 'META-INF/rxjava'
    exclude 'META-INF/RXJAVA'
}

lintOptions {
    abortOnError false
}
}

How can I fix this problem?

Body:
I had the same problem. The way I fixed it is adding the packagingOptions in app gradle as described in Duplicated file rxjava.properties

android {

    defaultConfig {
    }
    buildTypes {
    }
    packagingOptions{
        exclude 'META-INF/rxjava.properties'
    }
}

ContentLicense: CC BY-SA 4.0


问:
How do perform a "customized" running total in SQL Server?
I have temp table that I've populated with a running total. I used SQL Server windowing functions. The data in my temp table is in the following format:

```<code>|Day  | Sku  Nbr | CMQTY  |
| 1   |  f45     |   0    |
| 2   |  f45     |   2    |
| 3   |  f45     |   0    |
| 4   |  f45     |   7    |
| 5   |  f45     |   0    |
| 6   |  f45     |   0    |
| 7   |  f45     |   0    |
| 8   |  f45     |   13   |
| 9   |  f45     |  15    |
| 10  |  f45     |  21    |
</code>```

I would like to manipulate the data so that it displays like this:

```<code>|Day| Sku Nbr | CMQTY |
| 1 |  f45    | 0     |
| 2 |  f45    | 2     |
| 3 |  f45    | 2     |
| 4 |  f45    | 7     |
| 5   |  f45  |   7   |
| 6   |  f45  |   7   |
| 7   |  f45  |   7   |
| 8   |  f45  |   13  |
| 9   |  f45  |  15   |
| 10  |  f45  |  21   |
</code>```

I've tried using a lag function but there are issues when I have multiple days, in a row, with a 0 CMQTY. I've also tried using CASE WHEN logic but am failing.

答:
You can use row_number as below

```<code>;with cte as (
select *, sm = sum(case when cmqty>0 then 1 else 0 end) over (order by [day]) from #yoursum
)
select *, sum(cmqty) over(partition by sm order by [day]) from cte
</code>```

Your table structure

```<code>create table #yoursum ([day] int, sku_nbr varchar(10), CMQTY int)

insert into #yoursum
([Day]  , Sku_Nbr , CMQTY  )  values
 ( 1   ,'f45',   0  )
,( 2   ,'f45',   2  )
,( 3   ,'f45',   0  )
,( 4   ,'f45',   7  )
,( 5   ,'f45',   0  )
,( 6   ,'f45',   0  )
,( 7   ,'f45',   0  )
,( 8   ,'f45',   13 )
,( 9   ,'f45',  15  )
,( 10  ,'f45',  21  )
</code>```

Body:
I have temp table that I've populated with a running total. I used SQL Server windowing functions. The data in my temp table is in the following format:

|Day  | Sku  Nbr | CMQTY  |
| 1   |  f45     |   0    |
| 2   |  f45     |   2    |
| 3   |  f45     |   0    |
| 4   |  f45     |   7    |
| 5   |  f45     |   0    |
| 6   |  f45     |   0    |
| 7   |  f45     |   0    |
| 8   |  f45     |   13   |
| 9   |  f45     |  15    |
| 10  |  f45     |  21    |

I would like to manipulate the data so that it displays like this:

|Day| Sku Nbr | CMQTY |
| 1 |  f45    | 0     |
| 2 |  f45    | 2     |
| 3 |  f45    | 2     |
| 4 |  f45    | 7     |
| 5   |  f45  |   7   |
| 6   |  f45  |   7   |
| 7   |  f45  |   7   |
| 8   |  f45  |   13  |
| 9   |  f45  |  15   |
| 10  |  f45  |  21   |

I've tried using a lag function but there are issues when I have multiple days, in a row, with a 0 CMQTY. I've also tried using CASE WHEN logic but am failing.

Body:
You can use row_number as below

;with cte as (
select *, sm = sum(case when cmqty>0 then 1 else 0 end) over (order by [day]) from #yoursum
)
select *, sum(cmqty) over(partition by sm order by [day]) from cte

Your table structure

create table #yoursum ([day] int, sku_nbr varchar(10), CMQTY int)

insert into #yoursum
([Day]  , Sku_Nbr , CMQTY  )  values
 ( 1   ,'f45',   0  )
,( 2   ,'f45',   2  )
,( 3   ,'f45',   0  )
,( 4   ,'f45',   7  )
,( 5   ,'f45',   0  )
,( 6   ,'f45',   0  )
,( 7   ,'f45',   0  )
,( 8   ,'f45',   13 )
,( 9   ,'f45',  15  )
,( 10  ,'f45',  21  )


问:
Unable to run task The validated string is empty
I am trying to create as simple task for postgres sql on Amazon EC2 with the following JSON config:

```<code>{
  "requiresAttributes": [],
  "taskDefinitionArn": "arn:aws:ecs:us-east-1:870465292454:task-definition/Application:2",
  "networkMode": "bridge",
  "status": "ACTIVE",
  "revision": 2,
  "taskRoleArn": null,
  "containerDefinitions": [
    {
      "volumesFrom": [],
      "memory": 512,
      "extraHosts": null,
      "dnsServers": null,
      "disableNetworking": null,
      "dnsSearchDomains": null,
      "portMappings": [
        {
          "hostPort": 5432,
          "containerPort": 5432,
          "protocol": "tcp"
        }
      ],
      "hostname": null,
      "essential": true,
      "entryPoint": null,
      "mountPoints": [],
      "name": "postgres",
      "ulimits": null,
      "dockerSecurityOptions": null,
      "environment": [
        {
          "name": "POSTGRES_PASSWORD",
          "value": "*******"
        }
      ],
      "links": [],
      "workingDirectory": null,
      "readonlyRootFilesystem": null,
      "image": "postgres",
      "command": null,
      "user": null,
      "dockerLabels": null,
      "logConfiguration": null,
      "cpu": 0,
      "privileged": null,
      "memoryReservation": null
    }
  ],
  "placementConstraints": [],
  "volumes": [
    {
      "host": {
        "sourcePath": "/var/lib/postgresql/data"
      },
      "name": "PGDATA"
    }
  ],
  "family": "Application"
}
</code>```

But When I try to run this task, I get "Unable to run task The validated string is empty" as a response from the server.

Can someone please help me understand what I am missing here.

答: The error message is very wage... but I got this error message before I have configured my clusters. Make sure that you chose your cluster while creating the task.</p>

Body:
I am trying to create as simple task for postgres sql on Amazon EC2 with the following JSON config:

{
  "requiresAttributes": [],
  "taskDefinitionArn": "arn:aws:ecs:us-east-1:870465292454:task-definition/Application:2",
  "networkMode": "bridge",
  "status": "ACTIVE",
  "revision": 2,
  "taskRoleArn": null,
  "containerDefinitions": [
    {
      "volumesFrom": [],
      "memory": 512,
      "extraHosts": null,
      "dnsServers": null,
      "disableNetworking": null,
      "dnsSearchDomains": null,
      "portMappings": [
        {
          "hostPort": 5432,
          "containerPort": 5432,
          "protocol": "tcp"
        }
      ],
      "hostname": null,
      "essential": true,
      "entryPoint": null,
      "mountPoints": [],
      "name": "postgres",
      "ulimits": null,
      "dockerSecurityOptions": null,
      "environment": [
        {
          "name": "POSTGRES_PASSWORD",
          "value": "*******"
        }
      ],
      "links": [],
      "workingDirectory": null,
      "readonlyRootFilesystem": null,
      "image": "postgres",
      "command": null,
      "user": null,
      "dockerLabels": null,
      "logConfiguration": null,
      "cpu": 0,
      "privileged": null,
      "memoryReservation": null
    }
  ],
  "placementConstraints": [],
  "volumes": [
    {
      "host": {
        "sourcePath": "/var/lib/postgresql/data"
      },
      "name": "PGDATA"
    }
  ],
  "family": "Application"
}

But When I try to run this task, I get "Unable to run task The validated string is empty" as a response from the server.

Can someone please help me understand what I am missing here.


问:
Open Source Web Based Image Editor
I'm looking for image editor with the same functionality with Paint.

It should have at least basic features like:
1. Open image file from PC.
2. Pencil Freehand Draw
3. Draw Oval or Circle
4. Draw Rectangle

This question is related with:
Free Open Source In-browser image editors

But there is no accepted answer yet.

答:
Ajax-Image Editor is popular. Another one is Pixastic, which is JavaScript based. Then you have Canvas Paint as well.

Edit: Corrected the Pixastic link. Thanks @Kirby!

Title: Open Source Web Based Image Editor


问:
Is the use of serialization a serious issue?
I've created a class Message for a Chat program that contains all the information about a specific message. Instances of Message are sent back and forth between the server and the clients. I'm using serialization (ObjectInputStream/ObjectOutputStream) to exchange those messages.

I have no control over the process of serialization and deserialization. The biggest problem for me is if some attacker wants to send a really heavy message (say several gigabytes), I have no way to avoid it and I might get some serious memory problems. This could be used for deny of service and it is serious.

I took a look at a lot of different topics about serialization and its security issues but no one mentions how to avoid this trivial issue. I would like to be able to retrieve the data as a byte array using a buffer so that I can stop reading at any moment. But I couldn't find any way to do that with serialization. Question: Is this how I should handle that?

Also any comments on the security issues of serialization is welcome. I've heard that you can inject malicious code in an instance of a serializable class but how can this be possible since the definition of the class must be the same on the client and on the server?

Thanks in advance for any help!

答:
Why not write a FilterInputStream (http://docs.oracle.com/javase/6/docs/api/java/io/FilterInputStream.html) to throw an exception if it reads more than X bytes of data from its underlying stream?

There’s a method that you can use to replace calls to readObject on this page:

https://www.contrastsecurity.com/security-influencers/java-serialization-vulnerability-threatens-millions-of-applications

```<code>/**
 * A method to replace the unsafe ObjectInputStream.readObject() method built into Java. This method
 * checks to be sure the classes referenced are safe, the number of objects is limited to something sane,
 * and the number of bytes is limited to a reasonable number. The returned Object is also cast to the
 * specified type.
 *
 * @param type Class representing the object type expected to be returned
 * @param safeClasses List of Classes allowed in serialized object being read
 * @param maxObjects long representing the maximum number of objects allowed inside the serialized object being read
 * @param maxBytes long representing the maximum number of bytes allowed to be read from the InputStream
 * @param in InputStream containing an untrusted serialized object
 * @return Object read from the stream (cast to the Class of the type parameter)
 * @throws IOException
 * @throws ClassNotFoundException
 */

@SuppressWarnings("unchecked")
public static  T safeReadObject(Class<?> type, List<Class<?>> safeClasses, long maxObjects, long maxBytes, InputStream in ) throws IOException, ClassNotFoundException {
    // create an input stream limited to a certain number of bytes
    InputStream lis = new FilterInputStream( in ) {
        private long len = 0;
        public int read() throws IOException {
            int val = super.read();
            if (val != -1) {
                len++;
                checkLength();
            }
            return val;
        }
        public int read(byte[] b, int off, int len) throws IOException {
            int val = super.read(b, off, len);
            if (val > 0) {
                len += val;
                checkLength();
            }
            return val;
        }
        private void checkLength() throws IOException {
            if (len > maxBytes) {
                throw new SecurityException("Security violation: attempt to deserialize too many bytes from stream. Limit is " + maxBytes);
            }
        }
    };
    // create an object input stream that checks classes and limits the number of objects to read
    ObjectInputStream ois = new ObjectInputStream( lis ) {
        private int objCount = 0;
        boolean b = enableResolveObject(true);
        protected Object resolveObject(Object obj) throws IOException {
            if ( objCount++ > maxObjects ) throw new SecurityException( "Security violation: attempt to deserialize too many objects from stream. Limit is " + maxObjects );
            Object object = super.resolveObject(obj);
            return object;
        }
        protected Class<?> resolveClass(ObjectStreamClass osc) throws IOException, ClassNotFoundException {
            Class<?> clazz = super.resolveClass(osc);
            if (
                clazz.isArray() ||
                clazz.equals(type) ||
                clazz.equals(String.class) ||
                Number.class.isAssignableFrom(clazz) ||
                safeClasses.contains(clazz)
            ) return clazz;
            throw new SecurityException("Security violation: attempt to deserialize unauthorized " + clazz);
        }
    };
    // use the protected ObjectInputStream to read object safely and cast to T
    return (T)ois.readObject();
}
</code>```

Body:
Why not write a FilterInputStream (http://docs.oracle.com/javase/6/docs/api/java/io/FilterInputStream.html) to throw an exception if it reads more than X bytes of data from its underlying stream?

There’s a method that you can use to replace calls to readObject on this page:

https://www.contrastsecurity.com/security-influencers/java-serialization-vulnerability-threatens-millions-of-applications

/**
 * A method to replace the unsafe ObjectInputStream.readObject() method built into Java. This method
 * checks to be sure the classes referenced are safe, the number of objects is limited to something sane,
 * and the number of bytes is limited to a reasonable number. The returned Object is also cast to the
 * specified type.
 *
 * @param type Class representing the object type expected to be returned
 * @param safeClasses List of Classes allowed in serialized object being read
 * @param maxObjects long representing the maximum number of objects allowed inside the serialized object being read
 * @param maxBytes long representing the maximum number of bytes allowed to be read from the InputStream
 * @param in InputStream containing an untrusted serialized object
 * @return Object read from the stream (cast to the Class of the type parameter)
 * @throws IOException
 * @throws ClassNotFoundException
 */

@SuppressWarnings("unchecked")
public static  T safeReadObject(Class<?> type, List<Class<?>> safeClasses, long maxObjects, long maxBytes, InputStream in ) throws IOException, ClassNotFoundException {
    // create an input stream limited to a certain number of bytes
    InputStream lis = new FilterInputStream( in ) {
        private long len = 0;
        public int read() throws IOException {
            int val = super.read();
            if (val != -1) {
                len++;
                checkLength();
            }
            return val;
        }
        public int read(byte[] b, int off, int len) throws IOException {
            int val = super.read(b, off, len);
            if (val > 0) {
                len += val;
                checkLength();
            }
            return val;
        }
        private void checkLength() throws IOException {
            if (len > maxBytes) {
                throw new SecurityException("Security violation: attempt to deserialize too many bytes from stream. Limit is " + maxBytes);
            }
        }
    };
    // create an object input stream that checks classes and limits the number of objects to read
    ObjectInputStream ois = new ObjectInputStream( lis ) {
        private int objCount = 0;
        boolean b = enableResolveObject(true);
        protected Object resolveObject(Object obj) throws IOException {
            if ( objCount++ > maxObjects ) throw new SecurityException( "Security violation: attempt to deserialize too many objects from stream. Limit is " + maxObjects );
            Object object = super.resolveObject(obj);
            return object;
        }
        protected Class<?> resolveClass(ObjectStreamClass osc) throws IOException, ClassNotFoundException {
            Class<?> clazz = super.resolveClass(osc);
            if (
                clazz.isArray() ||
                clazz.equals(type) ||
                clazz.equals(String.class) ||
                Number.class.isAssignableFrom(clazz) ||
                safeClasses.contains(clazz)
            ) return clazz;
            throw new SecurityException("Security violation: attempt to deserialize unauthorized " + clazz);
        }
    };
    // use the protected ObjectInputStream to read object safely and cast to T
    return (T)ois.readObject();
}


问:
What are the guarantees for Apache Flume HDFS sink file writes?
Could somebody shed some light on what happens if the Flume agent gets killed in the middle of the HDFS file write (say using Avro format)? Will the file get corrupted and all events there lost? </p>

<p>I understand that there are transactions between different elements of the Flume data chain (source->channel->sink). But I believe that the HDFS files may stay open between consecutive channel->sink transactions (as .tmp). So if one transaction of say 100 events is successful (and the events are stored in a file, transaction committed) and the next one fails in the middle of the HDFS write could it be that the original 100 events from the first transaction are not readable (because the file corruption for instance?). How come Flume can assure that the original 100 events from the first transaction are not affected by this type of failure? Or maybe there is no guarantee there? </p>

答:
If the Flume agent is killed in the middle of HDFS file write , the file won't get corrupted and there will be no data loss.

IF flume is writing to a file say FlumeData123456789.tmp when the flume agent is killed, then all the records written into that file  up till that point will remain intact and the file will be saved as FlumeData123456789.

Body:
Could somebody shed some light on what happens if the Flume agent gets killed in the middle of the HDFS file write (say using Avro format)? Will the file get corrupted and all events there lost?

I understand that there are transactions between different elements of the Flume data chain (source->channel->sink). But I believe that the HDFS files may stay open between consecutive channel->sink transactions (as .tmp). So if one transaction of say 100 events is successful (and the events are stored in a file, transaction committed) and the next one fails in the middle of the HDFS write could it be that the original 100 events from the first transaction are not readable (because the file corruption for instance?). How come Flume can assure that the original 100 events from the first transaction are not affected by this type of failure? Or maybe there is no guarantee there?


问:
JqGrid with Google Fusion Tables
Trying to get jqGrid to work with Google fusion tables.

Can't seem to find the event in jqGrid that allows you to control where it gets data from.

Would accept an equivalent javascript table engine that does this job better.

If you could link to an example or provide one in your answer, thanks.

Edit: OK here is how far I've gotten

I know how to get jqGrid to request the Google fusion tables but I can't get it to parse the JSON.
I can't seem to find any decent documentation for the jsonreader part of jqGrid that explains what each variable does.

http://cablegate.politicswiki.ie/test.html is where I'm currently at.

答:
Seems to be quite a bit of flexibility:

http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:colmodel_options

Worse case scenario you can convert Google Fusion to XML or JSON in a script and render it that way.

OwnerDisplayName: Stephen Lacy

Title: JqGrid with Google Fusion Tables


问:
Merging same columns from a table with different conditions
I want to retrieve data from one table but the data is based on conditions this is my query:

```<code>Select
    Store_ID,
    (select Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
     from DailyStockHistory
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim'
       and Imported_Date = '3-15-2017'
       and Store_ID like 'S%'),
    (select Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
     from DailyStockHistory
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim'
       and Imported_Date = '3-22-2017'
       and Store_ID like 'S%')
from
    DailyStockHistory
</code>```

Any help please.

Thanks in advance.

答:
```<code>Select
    Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
From
    DailyStockHistory
Where
    Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim'
    And Store_ID Like 'S%'
    And (Imported_Date = '3-15-2017' Or Imported_Date = '3-22-2017)
</code>```

Body:
I want to retrieve data from one table but the data is based on conditions this is my query:

Select
    Store_ID,
    (select Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
     from DailyStockHistory
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim'
       and Imported_Date = '3-15-2017'
       and Store_ID like 'S%'),
    (select Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
     from DailyStockHistory
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim'
       and Imported_Date = '3-22-2017'
       and Store_ID like 'S%')
from
    DailyStockHistory

Any help please.

Thanks in advance.


问:
Variables created in Jquery not appearing in Debugger
I have written some code in Jquery that when a button is pressed, creates a new variable and displays it on the screen.  I'd like to take whatever data is entered into this new variable and store it in a database however before I get there I have to figure out to access the variables information properly.

In HTML I have 3 text boxes created and a button to add up to 7 more for a total of 10.  My code looks like this (and these store in the database just fine):

```<code><table style="width:90%" class="Long-Term-Conditions">
<center>
 <tr>
  <td><b><center>Long term condition 1:</center></b></td>
  <td><center><input type='text' id="Var1" name ='Var1' value='%Var1%' /></center></td>
 </tr>
 <tr>
  <td><b><center>Long term condition 2:</center></b></td>
  <td><center><input type='text' id="Var2" name ='Var2' value='%Var2%' /></center></td>
 </tr>
 <tr>
  <td><b><center>Long term condition 3:</center></b></td>
  <td><center><input type='text' id="Var3" name ='Var3' value='%Var3%' /></center></td>
 </tr>
</center>
</table>
<a href="#" title="" class="add-cond" id="add-cond">Add another long-term health condition</a>
<div id="Message"></div>
</code>```

My problem now is that my Jquery variables cant be inspected (says not available) and no data is passed to the database after.  My Jquery looks like this:

```<code><script>

  //Adds another row to the above table.
 var counter = 3;
 jQuery('a.add-cond').click(function(event){
    event.preventDefault();
    if (counter < 10) {
  counter++;
  var newRow = jQuery('<tr><td><b><center>'+ "Long term condition "+  counter + ":" + '</center></td> <td><center><input type="text" name="Var' +
    counter + '" id="Var' + counter + 'value="%Var' + counter + '%"/></center></b></td></tr>');
  jQuery('table.Long-Term-Conditions').append(newRow);
 }
  else
     {
  document.getElementById("add-cond").style.visibility = "hidden";
  document.getElementById("Message").innerHTML = '<font color="Red">Please
contact us</font>';
 }
});

</script>
</code>```

The code works in creating the new variable however any data entered into the newly created text box is never passed to the debugger or the database.  What am I doing wrong?  Any help is appreciated.

答:
I think you were just missing a " between the id and value of your new input

//Adds another row to the above table.
var counter = 3;
jQuery('a.add-cond').click(function(event) {
  event.preventDefault();
  if (counter < 10) {
    counter++;
    var newRow = jQuery('
' + "Long term condition " + counter + ":" + '	 <input type="text" name="Var' +
      counter + '" id="Var' + counter + '" value="%Var' + counter + '%"/>
');
    jQuery('table.Long-Term-Conditions').append(newRow);
  } else {
    document.getElementById("add-cond").style.visibility = "hidden";
    document.getElementById("Message").innerHTML = 'Please contact us ';
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:90%" class="Long-Term-Conditions">
  <center>
    <tr>
      <td><b><center>Long term condition 1:</center></b></td>
      <td>
        <center><input type='text' id="Var1" name='Var1' value='%Var1%' /></center>
      </td>
    </tr>
    <tr>
      <td><b><center>Long term condition 2:</center></b></td>
      <td>
        <center><input type='text' id="Var2" name='Var2' value='%Var2%' /></center>
      </td>
    </tr>
    <tr>
      <td><b><center>Long term condition 3:</center></b></td>
      <td>
        <center><input type='text' id="Var3" name='Var3' value='%Var3%' /></center>
      </td>
    </tr>
  </center>
</table>
Add another long-term health condition
<div id="Message"></div></code>```

Body:
I have written some code in Jquery that when a button is pressed, creates a new variable and displays it on the screen.  I'd like to take whatever data is entered into this new variable and store it in a database however before I get there I have to figure out to access the variables information properly.

In HTML I have 3 text boxes created and a button to add up to 7 more for a total of 10.  My code looks like this (and these store in the database just fine):

  Long term condition 1:
  <input type='text' id="Var1" name ='Var1' value='%Var1%' />

  Long term condition 2:
  <input type='text' id="Var2" name ='Var2' value='%Var2%' />

  Long term condition 3:
  <input type='text' id="Var3" name ='Var3' value='%Var3%' />

Add another long-term health condition

My problem now is that my Jquery variables cant be inspected (says not available) and no data is passed to the database after.  My Jquery looks like this:

The code works in creating the new variable however any data entered into the newly created text box is never passed to the debugger or the database.  What am I doing wrong?  Any help is appreciated.

Body:
I think you were just missing a " between the id and value of your new input

//Adds another row to the above table.
var counter = 3;
jQuery('a.add-cond').click(function(event) {
  event.preventDefault();
  if (counter < 10) {
    counter++;
    var newRow = jQuery('<tr><td><b><center>' + "Long term condition " + counter + ":" + '</center></td> <td><center><input type="text" name="Var' +
      counter + '" id="Var' + counter + '" value="%Var' + counter + '%"/></center></b></td></tr>');
    jQuery('table.Long-Term-Conditions').append(newRow);
  } else {
    document.getElementById("add-cond").style.visibility = "hidden";
    document.getElementById("Message").innerHTML = '<font color="Red">Please contact us </font>';
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:90%" class="Long-Term-Conditions">
  <center>
    <tr>
      <td><b><center>Long term condition 1:</center></b></td>
      <td>
        <center><input type='text' id="Var1" name='Var1' value='%Var1%' /></center>
      </td>
    </tr>
    <tr>
      <td><b><center>Long term condition 2:</center></b></td>
      <td>
        <center><input type='text' id="Var2" name='Var2' value='%Var2%' /></center>
      </td>
    </tr>
    <tr>
      <td><b><center>Long term condition 3:</center></b></td>
      <td>
        <center><input type='text' id="Var3" name='Var3' value='%Var3%' /></center>
      </td>
    </tr>
  </center>
</table>
<a href="#" title="" class="add-cond" id="add-cond">Add another long-term health condition</a>
<div id="Message"></div>


问:
jQuery slide repeated code
I would like top know if there is a way to create several slides and panels using minimal code and avoid this:

```<code>$(document).ready(function(){
    $("#slide1").click(function(){
        $("#panel1").slideToggle("slow");
    });
    $("#slide2").click(function(){
        $("#panel2").slideToggle("slow");
    });
});
</code>```

As you can see, for every pair of panel and slide I have to create 3 new lines of jQuery. Is there a way to avoid this? I'm open to solutions that use Javascript as well. The goal of this is to simply have a few lines of code, and for every panel and slide involved, I don't have to add any code whatsoever. I simply have to add a slide and panel, and it will function.

答:
I would add a data attribute on the click targets (the #slideXX) that points to the panel to toggle

```<code><div data-panel-target="#panel1"></div>
<div id="#panel1"></div>
</code>```

and use

```<code>$(document).ready(function(){
    $("[data-panel-target]").click(function(){
        var target = $(this).data('panel-target');
        $(target).slideToggle("slow");
    });
});
</code>```

Title: jQuery slide repeated code

Body:
I would like top know if there is a way to create several slides and panels using minimal code and avoid this:

$(document).ready(function(){
    $("#slide1").click(function(){
        $("#panel1").slideToggle("slow");
    });
    $("#slide2").click(function(){
        $("#panel2").slideToggle("slow");
    });
});

As you can see, for every pair of panel and slide I have to create 3 new lines of jQuery. Is there a way to avoid this? I'm open to solutions that use Javascript as well. The goal of this is to simply have a few lines of code, and for every panel and slide involved, I don't have to add any code whatsoever. I simply have to add a slide and panel, and it will function.

Body:
I would add a data attribute on the click targets (the #slideXX) that points to the panel to toggle

<div data-panel-target="#panel1"></div>
<div id="#panel1"></div>

and use

$(document).ready(function(){
    $("[data-panel-target]").click(function(){
        var target = $(this).data('panel-target');
        $(target).slideToggle("slow");
    });
});


问:
How does Google's custom iOS keyboard, Gboard, programmatically dismiss the frontmost app?
Google's custom iOS app, Gboard, has an interesting feature that can't be accomplished using public APIs for in the iOS SDK (as of iOS 10).  I'd like to know exactly how Google accomplishes the task of programmatically popping back one app in the App Switching stack in Gboard.

Custom iOS keyboards have two major components: the container app and the keyboard app extension.  The keyboard app extension runs in a separate OS process that is started up whenever a user is in any app on their phone that requires text input.

These are the approximate steps that can be followed, using Gboard, to see the effect of programmatically returning to a previous app:

A user starts the Apple Messages app on their iPhone and taps a text field to begin entering text.

The Gboard keyboard extension is launched and the users sees the Gboard custom keyboard (while they are still in the Apple Messages app).

The user taps the microphone key inside the Gboard keyboard extension to do voice-to-text input.

Gboard uses a custom url scheme to launch the Gboard container app.  The Gboard keyboard and Apple messages app are pushed down one layer in the App stack and the Gboard container app is now the frontmost app in the App stack.  The Gboard container app uses the microphone to listen to the user's speech and translates it into text which it places onto the screen.

The user taps the "Done" button when they are satisfied with the text input they see on the screen.

This is where the magic happens… as the text input screen is dismissed, the Gboard container app is also dismissed automatically.  The Gboard container app goes away and is replaced by the Apple Messages app (sometimes the Gboard keyboard extension process is still alive, sometimes it is relaunched, and sometimes it needs to be re-launched manually by tapping inside a text field.) . How does Google accomplish this?

Finally, the user sees the text that was just translated inserted automatically inside the text input field.  Presumably Google accomplishes this by sharing data between the Gboard container app and the keyboard extension.

I would assume that Google is using private APIs by exploring the status bar's view hierarchy using Objective-C runtime introspection and somehow synthesizing tap events or calling an exposed target / action.  I've explored this a very little and have been able to find interesting UIView subclasses inside the status bar, like UIStatusBarBreadcrumbItemView which contains an array of UISystemNavigationActions.  I'm continuing to explore these classes in the hope that I can find some way of replicating the user interaction.

I understand that using private APIs is a good way to get your app submission rejected from the App Store - this isn't a concern that I'd like to be addressed in the answer.  I'm looking primarily for specific answers about how exactly how Google accomplishes the task of programmatically popping back one app in the App Switching stack in Gboard.

答:
Your guess is correct — Gboard is using private API to do it.

… though not through exploring view hierarchy or event injection.

When the voice-to-text action is done, we can check the syslog from Xcode or Console that it calls the -[AVAudioSession setActive:withOptions:error:] method. So I've reverse-engineered the Gboard app and look for the stack trace related to this.

Climbing up the call stack we can find the -[GKBVoiceRecognitionViewController navigateBackToPreviousApp] method, and…

…_systemNavigationAction? Yep, definitely private API.

Since class_getInstanceVariable is a public API and "_systemNavigationAction" is a string literal, the automatic checker is not able to note the private API usage, and the human reviewers probably don't see anything wrong with the "jump back to the previous app" behavior. Or probably because they are Google and you are not…

The actual code that performs the "jump back to previous app" action is like this:

```<code>@import UIKit;
@import ObjectiveC.runtime;

@interface UISystemNavigationAction : NSObject
@property(nonatomic, readonly, nonnull) NSArray<NSNumber*>* destinations;
-(BOOL)sendResponseForDestination:(NSUInteger)destination;
@end

inline BOOL jumpBackToPreviousApp() {
    Ivar sysNavIvar = class_getInstanceVariable(UIApplication.class, "_systemNavigationAction");
    UIApplication* app = UIApplication.sharedApplication;
    UISystemNavigationAction* action = object_getIvar(app, sysNavIvar);
    if (!action) {
        return NO;
    }
    NSUInteger destination = action.destinations.firstObject.unsignedIntegerValue;
    return [action sendResponseForDestination:destination];
}
</code>```

In particular, the -sendResponseForDestination: method performs the actual "go back" action.

(Since the API is undocumented, Gboard is actually using the API incorrectly. They used the wrong signature -(void)sendResponseForDestination:(id)destination. But it happens that all numbers other than 1 will work the same, so the Google developers are lucky this time)

Body:
Your guess is correct — Gboard is using private API to do it.

… though not through exploring view hierarchy or event injection.

When the voice-to-text action is done, we can check the syslog from Xcode or Console that it calls the -[AVAudioSession setActive:withOptions:error:] method. So I've reverse-engineered the Gboard app and look for the stack trace related to this.

Climbing up the call stack we can find the -[GKBVoiceRecognitionViewController navigateBackToPreviousApp] method, and…

…_systemNavigationAction? Yep, definitely private API.

Since class_getInstanceVariable is a public API and "_systemNavigationAction" is a string literal, the automatic checker is not able to note the private API usage, and the human reviewers probably don't see anything wrong with the "jump back to the previous app" behavior. Or probably because they are Google and you are not…

The actual code that performs the "jump back to previous app" action is like this:

@import UIKit;
@import ObjectiveC.runtime;

@interface UISystemNavigationAction : NSObject
@property(nonatomic, readonly, nonnull) NSArray<NSNumber*>* destinations;
-(BOOL)sendResponseForDestination:(NSUInteger)destination;
@end

inline BOOL jumpBackToPreviousApp() {
    Ivar sysNavIvar = class_getInstanceVariable(UIApplication.class, "_systemNavigationAction");
    UIApplication* app = UIApplication.sharedApplication;
    UISystemNavigationAction* action = object_getIvar(app, sysNavIvar);
    if (!action) {
        return NO;
    }
    NSUInteger destination = action.destinations.firstObject.unsignedIntegerValue;
    return [action sendResponseForDestination:destination];
}

In particular, the -sendResponseForDestination: method performs the actual "go back" action.

(Since the API is undocumented, Gboard is actually using the API incorrectly. They used the wrong signature -(void)sendResponseForDestination:(id)destination. But it happens that all numbers other than 1 will work the same, so the Google developers are lucky this time)


问:
How to store the output come from cases just store into an object
Whenever i will call getJsonKeyValue it should print the output like below,How can i store the value of getJsonKeyValue and using accordingly.

```<code>      getJsonKeyValue(WithMap: Map[String, Any])

      def getJsonKeyValue(mapIs: Map[String, Any]) {

         mapIs.foreach {
            case (k: String, v: List[Map[String, Any]]) =>  v.foreach(x => getJsonKeyValue(x))
            case (k: String, v: Any) => (k + "=" + v)

      }

    }
</code>```

mapIs

```<code>Map(RedDef -> List(Map(RedTypP -> ^.{14}XY.*$, RedTypC -> XY, ExpNoOfAt -> 19, attributes -> List(Map(AttId -> 1, AttNa -> Pro Ty, AttMaxLen -> 1, DataTy -> Map(DataTyName -> AN)), Map(AttId -> 2, AttNa -> Pro Cod, AttMaxLen -> 6, DataTy -> Map(DataTyName -> AN)), Map(AttId -> 3, AttNa -> REQ CODE, AttMaxLen -> 7, DataTy -> Map(DataTyName -> AN))), RedLen -> 117, RedDeIn -> 2, MinNoOfAt -> 19), Map(RedTypP -> ^.{14}JK.*$, RedTypC -> JK, ExpNoOfAt -> 10, attributes -> List(Map(AttId -> 1, AttNa -> Log Si Ty, AttMaxLen -> 1, DataTy -> Map(DataTyName -> A)), Map(AttId -> 2, AttNa -> Log Si Cod, AttMaxLen -> 6, DataTy -> Map(DataTyName -> AN)), Map(AttId -> 3, AttNa -> Ex Qu Cod, AttMaxLen -> 7, DataTy -> Map(DataTyName -> AN))), RedDeIn -> 3, MinNoOfAt -> 10), Map(RedTypP -> ^.{14}FK.*$, RedTypC -> FK, ExpNoOfAt -> 33, attributes -> List(Map(AttId -> 1, AttNa -> Pro Ty, AttMaxLen -> 1, DataTy -> Map(DataTyName -> AN)), Map(AttId -> 2, AttNa -> Pro Cod, AttMaxLen -> 6, DataTy -> Map(DataTyName -> AN)), Map(AttId -> 3, AttNa -> REQ CDE, AttMaxLen -> 7, DataTy -> Map(DataTyName -> AN)), Map(AttId -> 4, AttNa -> RED Ty, AttMaxLen -> 2, DataTy -> Map(DataTyName -> AN))), RedLen -> 117, RedDeIn -> 4, MinNoOfAt -> 33)))
</code>```

The output come from getJsonKeyValue

```<code>RedTypP = ^.{14}XY.*$
RedTypC = XY
ExpNoOfAt = 19
AttId = 1
AttNa = Pro Ty
AttMaxLen =1
DataTyName = AN
AttId = 2
AttNa = Pro Cod
AttMaxLen = 6
DataName = AN
AttId = 3
AttNa = REQ CODE
AttMaxLen = 7
DataTyName = AN
RedLen = 117
RedDeIn = 2
MinNoOfAt =19
</code>```

答:
There are many problems in this poorly composed question.  I'll address them in order of severity.

case (k: String, v: Any) => (k + "=" + v)

This line returns a String but the surrounding foreach() returns Unit so this result string is thrown away. There are two easy solutions for this: 1) use map (or some other collection operation) instead of foreach in order to collect the result string, or 2) use println() to output the result string. println returns Unit, which matches the foreach result.

Unaccounted for data type.

Your sample data contains an entry of String->Map which your code, and expected output, doesn't account for.

Too much poorly formatted sample data.

You've provided more sample data than is needed to produce the desired output and way more than needed to illustrate your issues. (Please read this page on submitting MCV code examples.) It's also presented without the quote marks " so those have to be added before it can be used for testing.

With those things in mind, the following compiles with many warnings, but it produces output that appears to match what you're looking for.

```<code>def getJsonKeyValue(mapIs: Map[String, _]): Unit = {
  mapIs.foreach {
    case (k: String, v: List[Map[String, _]]) => v.foreach(getJsonKeyValue)
    case (k: String, v: Map[String, _])       => getJsonKeyValue(v)
    case (k: String, v)                       => println(k + "=" + v)
  }
}
</code>```

update

Here is a version that returns the string representations.

```<code>def getJsonKeyValue(mapIs: Map[String, _]): Iterable[String] = {
  mapIs.flatMap {
    case (k: String, v: List[Map[String, _]]) => v.flatMap(getJsonKeyValue)
    case (k: String, v: Map[String, _])       => getJsonKeyValue(v)
    case (k: String, v)                       => Iterable(k + "=" + v)
  }
}
</code>```

Body:
Whenever i will call getJsonKeyValue it should print the output like below,How can i store the value of getJsonKeyValue and using accordingly.

      getJsonKeyValue(WithMap: Map[String, Any])

      def getJsonKeyValue(mapIs: Map[String, Any]) {

         mapIs.foreach {
            case (k: String, v: List[Map[String, Any]]) =>  v.foreach(x => getJsonKeyValue(x))
            case (k: String, v: Any) => (k + "=" + v)

      }

    }

mapIs

Map(RedDef -> List(Map(RedTypP -> ^.{14}XY.*$, RedTypC -> XY, ExpNoOfAt -> 19, attributes -> List(Map(AttId -> 1, AttNa -> Pro Ty, AttMaxLen -> 1, DataTy -> Map(DataTyName -> AN)), Map(AttId -> 2, AttNa -> Pro Cod, AttMaxLen -> 6, DataTy -> Map(DataTyName -> AN)), Map(AttId -> 3, AttNa -> REQ CODE, AttMaxLen -> 7, DataTy -> Map(DataTyName -> AN))), RedLen -> 117, RedDeIn -> 2, MinNoOfAt -> 19), Map(RedTypP -> ^.{14}JK.*$, RedTypC -> JK, ExpNoOfAt -> 10, attributes -> List(Map(AttId -> 1, AttNa -> Log Si Ty, AttMaxLen -> 1, DataTy -> Map(DataTyName -> A)), Map(AttId -> 2, AttNa -> Log Si Cod, AttMaxLen -> 6, DataTy -> Map(DataTyName -> AN)), Map(AttId -> 3, AttNa -> Ex Qu Cod, AttMaxLen -> 7, DataTy -> Map(DataTyName -> AN))), RedDeIn -> 3, MinNoOfAt -> 10), Map(RedTypP -> ^.{14}FK.*$, RedTypC -> FK, ExpNoOfAt -> 33, attributes -> List(Map(AttId -> 1, AttNa -> Pro Ty, AttMaxLen -> 1, DataTy -> Map(DataTyName -> AN)), Map(AttId -> 2, AttNa -> Pro Cod, AttMaxLen -> 6, DataTy -> Map(DataTyName -> AN)), Map(AttId -> 3, AttNa -> REQ CDE, AttMaxLen -> 7, DataTy -> Map(DataTyName -> AN)), Map(AttId -> 4, AttNa -> RED Ty, AttMaxLen -> 2, DataTy -> Map(DataTyName -> AN))), RedLen -> 117, RedDeIn -> 4, MinNoOfAt -> 33)))

The output come from getJsonKeyValue

RedTypP = ^.{14}XY.*$
RedTypC = XY
ExpNoOfAt = 19
AttId = 1
AttNa = Pro Ty
AttMaxLen =1
DataTyName = AN
AttId = 2
AttNa = Pro Cod
AttMaxLen = 6
DataName = AN
AttId = 3
AttNa = REQ CODE
AttMaxLen = 7
DataTyName = AN
RedLen = 117
RedDeIn = 2
MinNoOfAt =19

Body:
There are many problems in this poorly composed question.  I'll address them in order of severity.

case (k: String, v: Any) => (k + "=" + v)

This line returns a String but the surrounding foreach() returns Unit so this result string is thrown away. There are two easy solutions for this: 1) use map (or some other collection operation) instead of foreach in order to collect the result string, or 2) use println() to output the result string. println returns Unit, which matches the foreach result.

Unaccounted for data type.

Your sample data contains an entry of String->Map which your code, and expected output, doesn't account for.

Too much poorly formatted sample data.

You've provided more sample data than is needed to produce the desired output and way more than needed to illustrate your issues. (Please read this page on submitting MCV code examples.) It's also presented without the quote marks " so those have to be added before it can be used for testing.

With those things in mind, the following compiles with many warnings, but it produces output that appears to match what you're looking for.

def getJsonKeyValue(mapIs: Map[String, _]): Unit = {
  mapIs.foreach {
    case (k: String, v: List[Map[String, _]]) => v.foreach(getJsonKeyValue)
    case (k: String, v: Map[String, _])       => getJsonKeyValue(v)
    case (k: String, v)                       => println(k + "=" + v)
  }
}

update

Here is a version that returns the string representations.

def getJsonKeyValue(mapIs: Map[String, _]): Iterable[String] = {
  mapIs.flatMap {
    case (k: String, v: List[Map[String, _]]) => v.flatMap(getJsonKeyValue)
    case (k: String, v: Map[String, _])       => getJsonKeyValue(v)
    case (k: String, v)                       => Iterable(k + "=" + v)
  }
}


问:
Showing a dynamic number of views in RecyclerView item?
I am trying to re-create this:

I have a list of data:

```<code>List<Block> blocks;
</code>```

And the Block.java class has a method getNumBlocks() which returns the number of blocks that item should show. The number of blocks can range from something as small as 1 block to something as large as 20 blocks.

I created a normal RecyclerView adapter, along with the ImageView layout for the block:

```<code>public class BlockAdapter extends RecyclerView.Adapter<BlockAdapter.ViewHolder> {

    private Context context;

    private List<Block> blocks;

    public BlockAdapter(Context context, List<Block> blocks) {
        this.context = context;
        this.blocks = blocks;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView block;

        public ViewHolder(View v) {
            super(v);

            block = (ImageView) v.findViewById(R.id.block);
        }
    }

    @Override
    public BlockAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);

        View view = inflater.inflate(R.layout.block_layout, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        Block block = blocks.get(position);

        // How to use block.getNumBlocks() to show the correct number of blocks?
    }

    @Override
    public int getItemCount() {
        return blocks.size();
    }

}
</code>```

Here is block_layout.xml (it's just an empty LinearLayout, the blocks should be added inside of this LinearLayout):

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/card_bg"
    android:padding="16dp">

</LinearLayout>
</code>```

And here is the block.xml layout:

```<code><ImageView
    android:id="@+id/block"
    android:layout_width="18dp"
    android:layout_height="18dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp" />
</code>```

So my question is, how can I implement this so that it shows the correct number of blocks for each RecyclerView item?

What is the best way to do this performance wise?

答:
First change your viewholader and get the reference of your root layout -

```<code> public class ViewHolder extends RecyclerView.ViewHolder {
    LinearLayout root;

    public ViewHolder(View v) {
        super(v);
        root = (LinearLayout) v.findViewById(R.id.root);
    }
}
</code>```

After that inside bindview holder iterate over a loop with size of blocks

```<code>for(int i=0;i<block.size;i++) {
        ImageView blockImg = new ImageView(context);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(left, top, right, bottom);
        blockImg.setLayoutParams(lp);
        holder.root.addView(blockImg);
    }
</code>```

Using LayoutParams you can give desired margin as well and apply it over imageview

Body:
I am trying to re-create this:

I have a list of data:

List<Block> blocks;

And the Block.java class has a method getNumBlocks() which returns the number of blocks that item should show. The number of blocks can range from something as small as 1 block to something as large as 20 blocks.

I created a normal RecyclerView adapter, along with the ImageView layout for the block:

public class BlockAdapter extends RecyclerView.Adapter<BlockAdapter.ViewHolder> {

    private Context context;

    private List<Block> blocks;

    public BlockAdapter(Context context, List<Block> blocks) {
        this.context = context;
        this.blocks = blocks;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView block;

        public ViewHolder(View v) {
            super(v);

            block = (ImageView) v.findViewById(R.id.block);
        }
    }

    @Override
    public BlockAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);

        View view = inflater.inflate(R.layout.block_layout, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        Block block = blocks.get(position);

        // How to use block.getNumBlocks() to show the correct number of blocks?
    }

    @Override
    public int getItemCount() {
        return blocks.size();
    }

}

Here is block_layout.xml (it's just an empty LinearLayout, the blocks should be added inside of this LinearLayout):

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/card_bg"
    android:padding="16dp">

</LinearLayout>

And here is the block.xml layout:

<ImageView
    android:id="@+id/block"
    android:layout_width="18dp"
    android:layout_height="18dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp" />

So my question is, how can I implement this so that it shows the correct number of blocks for each RecyclerView item?

What is the best way to do this performance wise?

Body:
First change your viewholader and get the reference of your root layout -

 public class ViewHolder extends RecyclerView.ViewHolder {
    LinearLayout root;

    public ViewHolder(View v) {
        super(v);
        root = (LinearLayout) v.findViewById(R.id.root);
    }
}

After that inside bindview holder iterate over a loop with size of blocks

for(int i=0;i<block.size;i++) {
        ImageView blockImg = new ImageView(context);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(left, top, right, bottom);
        blockImg.setLayoutParams(lp);
        holder.root.addView(blockImg);
    }

Using LayoutParams you can give desired margin as well and apply it over imageview


问:
Sum of total sales values for a given year
In the following example I get the sum of sales per car with the following query:

```<code>id | cars
1    Ford
2    BMW
3    Fiat

id | id_cars | sales | sale_date
1       1        20      2016
2       1        30      2017
3       2        25      2017
4       2        35      2016
5       3        15      2017

SELECT car.id, car.cars, SUM(sal.sales) AS value_sales
FROM cars car
LEFT JOIN sales_cars sal  ON  car.id = sal.id_cars
GROUP BY car.id
</code>```

If I use the following segment in the query, I get only the registrations of cars that have sales in 2017, but that's not what I want.

```<code>AND YEAR(sal.sale_date) = YEAR(CURRENT_DATE())
</code>```

What I want to achieve is to get all records of cars sold (as in the previous query) but only the sum of the values of the current year.

For example : 1 | Ford | 30   and not 50 (2016 and 2017)

What is the correct way to do this query?

EDITED

Get current year and total years (following juergen answer):

```<code>SELECT car.id, car.cars,
   SUM(case when YEAR(sal.sale_date) = YEAR(CURRENT_DATE())
            then sal.sales
            else 0
       end) AS value_sales
   SUM(sal.sales) AS value_sales_total_years
FROM cars car
LEFT JOIN sales_cars sal  ON  car.id = sal.id_cars
GROUP BY car.id
</code>```

答:
Conditions on the first table in a LEFT JOIN go in the WHERE clause.  Conditions on subsequent tables go in the ON clause.  So the best way to write this query is:

```<code>SELECT car.id, car.cars, SUM(sal.sales) AS value_sales
FROM cars car LEFT JOIN
     sales_cars sal
     ON  car.id = sal.id_cars AND YEAR(sal.sale_date) = YEAR(CURRENT_DATE())
GROUP BY car.id;
</code>```

For cars that have no sales in 2017, the LEFT JOIN will produce NULL values for sal.sale_date.  Your WHERE clause filters out such records.  The ON does not because of the LEFT JOIN.

Body:
In the following example I get the sum of sales per car with the following query:

id | cars
1    Ford
2    BMW
3    Fiat

id | id_cars | sales | sale_date
1       1        20      2016
2       1        30      2017
3       2        25      2017
4       2        35      2016
5       3        15      2017

SELECT car.id, car.cars, SUM(sal.sales) AS value_sales
FROM cars car
LEFT JOIN sales_cars sal  ON  car.id = sal.id_cars
GROUP BY car.id

If I use the following segment in the query, I get only the registrations of cars that have sales in 2017, but that's not what I want.

AND YEAR(sal.sale_date) = YEAR(CURRENT_DATE())

What I want to achieve is to get all records of cars sold (as in the previous query) but only the sum of the values of the current year.

For example : 1 | Ford | 30   and not 50 (2016 and 2017)

What is the correct way to do this query?

EDITED

Get current year and total years (following juergen answer):

SELECT car.id, car.cars,
   SUM(case when YEAR(sal.sale_date) = YEAR(CURRENT_DATE())
            then sal.sales
            else 0
       end) AS value_sales
   SUM(sal.sales) AS value_sales_total_years
FROM cars car
LEFT JOIN sales_cars sal  ON  car.id = sal.id_cars
GROUP BY car.id

Body:
Conditions on the first table in a LEFT JOIN go in the WHERE clause.  Conditions on subsequent tables go in the ON clause.  So the best way to write this query is:

SELECT car.id, car.cars, SUM(sal.sales) AS value_sales
FROM cars car LEFT JOIN
     sales_cars sal
     ON  car.id = sal.id_cars AND YEAR(sal.sale_date) = YEAR(CURRENT_DATE())
GROUP BY car.id;

For cars that have no sales in 2017, the LEFT JOIN will produce NULL values for sal.sale_date.  Your WHERE clause filters out such records.  The ON does not because of the LEFT JOIN.


问:
Tensorflow: trying to get toy neural network to 'learn'
Trying to get very simple ('toy') 2-layer neural network to build model, as a learning example to make sure the math flows correctly.

The model should learn that a '1' on the first and last feature equates to a '1' output.

```<code>features = []
features.append([[0, 0, 0, 0, 0], [0]])
features.append([[0, 0, 0, 0, 1], [0]])
features.append([[0, 0, 0, 1, 1], [0]])
features.append([[0, 0, 1, 1, 1], [0]])
features.append([[0, 1, 1, 1, 1], [0]])
features.append([[1, 1, 1, 1, 0], [0]])
features.append([[1, 1, 1, 0, 0], [0]])
features.append([[1, 1, 0, 0, 0], [0]])
features.append([[1, 0, 0, 0, 0], [0]])
features.append([[1, 0, 0, 1, 0], [0]])
features.append([[1, 0, 1, 1, 0], [0]])
features.append([[1, 1, 0, 1, 0], [0]])
features.append([[0, 1, 0, 1, 1], [0]])
features.append([[0, 0, 1, 0, 1], [0]])
# output of [1] of positions [0,4]==1
features.append([[1, 0, 0, 0, 1], [1]])
features.append([[1, 1, 0, 0, 1], [1]])
features.append([[1, 1, 1, 0, 1], [1]])
features.append([[1, 1, 1, 1, 1], [1]])
features.append([[1, 0, 0, 1, 1], [1]])
features.append([[1, 0, 1, 1, 1], [1]])
features.append([[1, 1, 0, 1, 1], [1]])
features.append([[1, 0, 1, 0, 1], [1]])
</code>```

However I cannot get any error/cost to show up...

```<code>Epoch 3 completed out of 10 cost: 0.0
Epoch 5 completed out of 10 cost: 0.0
Epoch 7 completed out of 10 cost: 0.0
Epoch 9 completed out of 10 cost: 0.0
Accuracy: 1.0
</code>```

Thanks in advance for having a quick look: here is the notebook...

答:
The problem turned out to be the output, it needed to be a 2-class array. Not sure why this is necessarily the case.

```<code>features.append([[0, 0, 0, 0, 0], [0,1]])
features.append([[0, 0, 0, 0, 1], [0,1]])
features.append([[0, 0, 0, 1, 1], [0,1]])
features.append([[0, 0, 1, 1, 1], [0,1]])
features.append([[0, 1, 1, 1, 1], [0,1]])
</code>```

the working notebook is here.

Body:
Trying to get very simple ('toy') 2-layer neural network to build model, as a learning example to make sure the math flows correctly.

The model should learn that a '1' on the first and last feature equates to a '1' output.

features = []
features.append([[0, 0, 0, 0, 0], [0]])
features.append([[0, 0, 0, 0, 1], [0]])
features.append([[0, 0, 0, 1, 1], [0]])
features.append([[0, 0, 1, 1, 1], [0]])
features.append([[0, 1, 1, 1, 1], [0]])
features.append([[1, 1, 1, 1, 0], [0]])
features.append([[1, 1, 1, 0, 0], [0]])
features.append([[1, 1, 0, 0, 0], [0]])
features.append([[1, 0, 0, 0, 0], [0]])
features.append([[1, 0, 0, 1, 0], [0]])
features.append([[1, 0, 1, 1, 0], [0]])
features.append([[1, 1, 0, 1, 0], [0]])
features.append([[0, 1, 0, 1, 1], [0]])
features.append([[0, 0, 1, 0, 1], [0]])
# output of [1] of positions [0,4]==1
features.append([[1, 0, 0, 0, 1], [1]])
features.append([[1, 1, 0, 0, 1], [1]])
features.append([[1, 1, 1, 0, 1], [1]])
features.append([[1, 1, 1, 1, 1], [1]])
features.append([[1, 0, 0, 1, 1], [1]])
features.append([[1, 0, 1, 1, 1], [1]])
features.append([[1, 1, 0, 1, 1], [1]])
features.append([[1, 0, 1, 0, 1], [1]])

However I cannot get any error/cost to show up...

Epoch 3 completed out of 10 cost: 0.0
Epoch 5 completed out of 10 cost: 0.0
Epoch 7 completed out of 10 cost: 0.0
Epoch 9 completed out of 10 cost: 0.0
Accuracy: 1.0

Thanks in advance for having a quick look: here is the notebook...

Body:
The problem turned out to be the output, it needed to be a 2-class array. Not sure why this is necessarily the case.

features.append([[0, 0, 0, 0, 0], [0,1]])
features.append([[0, 0, 0, 0, 1], [0,1]])
features.append([[0, 0, 0, 1, 1], [0,1]])
features.append([[0, 0, 1, 1, 1], [0,1]])
features.append([[0, 1, 1, 1, 1], [0,1]])

the working notebook is here.


问:
head is always null in linked list insert
I am trying to insert into my linked list. Here is what I wrote for the same:

```<code>#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};

void show_menu()
{
    printf("\nWhat do you want to do: \n");
    printf("1.Insert \n2.Delete \n3.Show");
    printf("\nEnter your choice: \n");
}

void insert(struct node *head)
{
    int new_numer;
    printf("Enter a number to insert in the linked list: \n");
    scanf("%d",&new_numer);

    if ( head == NULL )
    {
        head = (struct node *)malloc(sizeof(struct node));
        head->data = new_numer;
        head->next = NULL;
    }
    else
    {
        struct node *temp = head;

        struct node *new_node = (struct node *)malloc(sizeof(struct node));

        new_node -> data = new_numer;

        new_node -> next = NULL;

        while( temp -> next != NULL )
        {
            temp = temp -> next;
        }
        temp->next = new_node;
    }
}

void show(struct node *head)
{
    printf("\n The elements in the list are: \n");
    while ( head != NULL )
    {
        printf("%d\n", head->data);
        head = head -> next;
    }
}

int main(int argc, char const *argv[])
{
    int choice;

    struct node *head = NULL;

    while(1)
    {
        show_menu();
        scanf("%d",&choice);

        switch(choice)
        {
            case 1:
                insert(head);
                show(head);
            break;

            case 2:
                show(head);
            break;

            case 3:
            break;

            default:
                printf("Don't fuck with me.\n");
        }

    }

    return 0;
}
</code>```

On running the code, I got:

```<code>What do you want to do:
1.Insert
2.Delete
3.Show
Enter your choice:
1
Enter a number to insert in the linked list:
12

 The elements in the list are:

What do you want to do:
1.Insert
2.Delete
3.Show
Enter your choice:
</code>```

Why there is no element inserted in the list?

If I am moving

```<code>head = (struct node *)malloc(sizeof(struct node));
</code>```

to the main function, I am getting first element as zero and other inserted.

What am I missing here?

答:
The problem you are facing is that when you are inserting the first element, the head isn't changing. You have passed its values to the function.

What you need to do is pass the address of head i.e. struct node** head and then modify *head if it is the first element being inserted.

Body:
I am trying to insert into my linked list. Here is what I wrote for the same:

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};

void show_menu()
{
    printf("\nWhat do you want to do: \n");
    printf("1.Insert \n2.Delete \n3.Show");
    printf("\nEnter your choice: \n");
}

void insert(struct node *head)
{
    int new_numer;
    printf("Enter a number to insert in the linked list: \n");
    scanf("%d",&new_numer);

    if ( head == NULL )
    {
        head = (struct node *)malloc(sizeof(struct node));
        head->data = new_numer;
        head->next = NULL;
    }
    else
    {
        struct node *temp = head;

        struct node *new_node = (struct node *)malloc(sizeof(struct node));

        new_node -> data = new_numer;

        new_node -> next = NULL;

        while( temp -> next != NULL )
        {
            temp = temp -> next;
        }
        temp->next = new_node;
    }
}

void show(struct node *head)
{
    printf("\n The elements in the list are: \n");
    while ( head != NULL )
    {
        printf("%d\n", head->data);
        head = head -> next;
    }
}

int main(int argc, char const *argv[])
{
    int choice;

    struct node *head = NULL;

    while(1)
    {
        show_menu();
        scanf("%d",&choice);

        switch(choice)
        {
            case 1:
                insert(head);
                show(head);
            break;

            case 2:
                show(head);
            break;

            case 3:
            break;

            default:
                printf("Don't fuck with me.\n");
        }

    }

    return 0;
}

On running the code, I got:

What do you want to do:
1.Insert
2.Delete
3.Show
Enter your choice:
1
Enter a number to insert in the linked list:
12

 The elements in the list are:

What do you want to do:
1.Insert
2.Delete
3.Show
Enter your choice:

Why there is no element inserted in the list?

If I am moving

head = (struct node *)malloc(sizeof(struct node));

to the main function, I am getting first element as zero and other inserted.

What am I missing here?


问:
Linq to SQL: Is it better to have a small DataContext for each page or a global one?
I am trying out Linq to SQL in an ASP.NET application that uses a large database with lots of foreign keys (100+ tables).  I am impressed with how Linq permits you to create a datacontext with all of your relationships intact and to then create Linq statements that automatically join tables.  However, this leads to a question: if I am submitting a Linq statement that just works with one or two tables, is it better to have a datacontext that just has the necessary table/tables? It seems to me that if I build a datacontext with all of the tables in the database, it would be quite massive and loading it for every use of Linq would have a negative impact on performance.  Am I right?

Comment: I know to create the datacontext only as needed (but thank you nonetheless for mentioning it).  The question is really about whether I should have lots of little datacontexts or whether it would be Ok to build one big one.

答: This page http://www.albahari.com/nutshell/10linqmyths.aspx (see Myth #10) says it's better to use short-lived DataContext instances.</p>


问:
Strip comments in CSS using VIM
I think vim can really do this. I just don't know my way arround search and replace using regex. Can anyone help me around this one.

Update

Thanks to Chris below for helping me around this one. Here is the map.

```<code>map <leader>rc :%s@\v/\*([^*]\|[\r\n]\|(\*+([^*/]\|[\r\n])))*\*+/@@g<cr>
</code>```

答:
Here's a regex (from Stephen Ostermiller) that should match C style (e.g., /* ... */ and hence CSS) comments:

```<code>/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/
</code>```

Note: this will probably need adaptation to VIM's specific flavor of regex.

Title: Strip comments in CSS using VIM

Body:
I think vim can really do this. I just don't know my way arround search and replace using regex. Can anyone help me around this one.

Update

Thanks to Chris below for helping me around this one. Here is the map.

map <leader>rc :%s@\v/\*([^*]\|[\r\n]\|(\*+([^*/]\|[\r\n])))*\*+/@@g<cr>

Body:
Here's a regex (from Stephen Ostermiller) that should match C style (e.g., /* ... */ and hence CSS) comments:

/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/

Note: this will probably need adaptation to VIM's specific flavor of regex.


问:
Creating a .NET List<List<double>> to call a .NET DLL from MATLAB?
I have a .NET DLL I'm loading into MATLAB R2016B through the asm = NET.addAssembly('C:\My.dll')  It is fairly easy to create a  .NET list of doubles using netDouble = NET.createGeneric('System.Collections.Generic.List',{'System.Double'},1) which MATLAB shows as 1x1 List<System*Double>, but there is no tutorial out there that shows how to create a .NET List<List<double>> structure.  MATLAB can't access the code I need to run as a result - it shows the error as: Value must be
'System.Collections.Generic.List<System*Collections*Generic*List<System*Double>>'.

Anyone out there know how to create the above structure?  Much appreciated.

答:
Actually MATHWORKS tech support got back to me with a solution that works.  Since I don't see it documented anywhere, I'm posting this example in case someone else runs into this issue:

```<code>genCls = NET.GenericClass('System.Collections.Generic.List','System.Double');
obj = NET.createGeneric('System.Collections.Generic.List',{genCls},5);
</code>```

And how they explained it: In this method, we first create a generic class as List and this class is provided as an argument to the 'NET.createGeneric' method hence the created list is of type List<List<double>>

Then to populate it... here's a function I wrote to take the Matlab array and convert to the proper type all rolled into 1:

```<code>function [NETobj] = ML_NET_ListListDouble(MLarray)
genCls = NET.GenericClass('System.Collections.Generic.List','System.Double');
NETobj = NET.createGeneric('System.Collections.Generic.List',{genCls},size(MLarray,1));
for i=1:size(MLarray,1)
        obj1 = NET.createGeneric('System.Collections.Generic.List',{'System.Double'},size(MLarray,2));
        AddRange(obj1, NET.convertArray(MLarray(i,:))) %insert the current MATLAB row into the NET structure
    Add(NETobj, obj1)
end
end
</code>```

That function hopefully comes in useful for someone else - a brainless conversion from a MATLAB array to a .NET <List<List<double>>

Body:
Actually MATHWORKS tech support got back to me with a solution that works.  Since I don't see it documented anywhere, I'm posting this example in case someone else runs into this issue:

genCls = NET.GenericClass('System.Collections.Generic.List','System.Double');
obj = NET.createGeneric('System.Collections.Generic.List',{genCls},5);

And how they explained it: In this method, we first create a generic class as List and this class is provided as an argument to the 'NET.createGeneric' method hence the created list is of type List<List<double>>

Then to populate it... here's a function I wrote to take the Matlab array and convert to the proper type all rolled into 1:

function [NETobj] = ML_NET_ListListDouble(MLarray)
genCls = NET.GenericClass('System.Collections.Generic.List','System.Double');
NETobj = NET.createGeneric('System.Collections.Generic.List',{genCls},size(MLarray,1));
for i=1:size(MLarray,1)
        obj1 = NET.createGeneric('System.Collections.Generic.List',{'System.Double'},size(MLarray,2));
        AddRange(obj1, NET.convertArray(MLarray(i,:))) %insert the current MATLAB row into the NET structure
    Add(NETobj, obj1)
end
end

That function hopefully comes in useful for someone else - a brainless conversion from a MATLAB array to a .NET <List<List<double>>


问:
Convert String to DateTime keeping datetime unchanged
Have the below string which i want to convert to a DateTime in c# code.

```<code>string dateTime = "2017-03-29T17:51:44.8389637Z";
DateTime dt1 = Convert.ToDateTime(dateTime);
</code>```

The above code converts it to: 3/29/2017 10:51:44 AM
I lose about 7 hours with the conversion, how can i get the result as: 2017-03-29 17:51:44. I think it has something to do with culture..?

Please help.

答:
The reason for this happening is you have a date/time string that ends with a Z. This denotes that it is in UTC time. When you're converting to a DateTime, it is converting it to your local culture's time, so you're losing exactly seven hours, because your time zone is seven hours behind UTC.

According to this Wikipedia article,

If the time is in UTC, add a Z directly after the time without a space. Z is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would be "14:45:15Z" or "144515Z".

So, your 2017-03-29 17:51:44 string and your 3/29/2017 10:51:44 AM are the exact same time, in different time zones.

EDIT: as others have said, just use DateTime.Parse to specify how you want the DateTime to be created.

Body:
Have the below string which i want to convert to a DateTime in c# code.

string dateTime = "2017-03-29T17:51:44.8389637Z";
DateTime dt1 = Convert.ToDateTime(dateTime);

The above code converts it to: 3/29/2017 10:51:44 AM
I lose about 7 hours with the conversion, how can i get the result as: 2017-03-29 17:51:44. I think it has something to do with culture..?

Please help.


问:
How to make JOOQ to use arrays in the IN clause
I want JOOQ to generate ... in (?) and bind list as an array parameter (Postgres). My code looks like

```<code>.where(
   Tables.TABLE.FIELD.in(idsList)
)
</code>```

How can I do this?

Why it's not done by default since it's more efficient that generation (and parsing by PG) of the string in (?, ?, ?, ?, ...)

答:
How can I do this?

You can use the DSL.any(T[]) operator, e.g.

```<code>TABLE.FIELD.eq(any(1, 2, 3))
</code>```

This will bind only one array variable to the JDBC statement

Why it's not done by default since it's more efficient that generation (and parsing by PG) of the string

It might be worth thinking about a flag in Settings. I've registered a feature request for this: https://github.com/jOOQ/jOOQ/issues/6029

In general, jOOQ allows users to write exactly the SQL they want to send to the database server, so the automatic "optimisation" and rewriting of SQL might appear quite unexpected to some users. This is just a general rule of thumb in jOOQ. It's always worth thinking about optimisations and making them opt-in through Settings.

Caution about premature optimisation!

However, it's always important to actually measure these things. While there is certainly a bit less of a parsing and SQL generation overhead with your suggested approach, beware that an array's cardinality may be much harder to estimate correctly than a hard-wired IN list. Using an array for small lists can have negative effects on your execution plan. So, the few microseconds you're saving on the parser side will weigh against the few milliseconds (?) at the execution side!

I've benchmarked this in the following blog post:
https://blog.jooq.org/sql-in-predicate-with-in-list-or-with-array-which-is-faster/

The IN list seems to consistently outperform the array version (in my specific benchmark case) until a length of around 50

Body:
I want JOOQ to generate ... in (?) and bind list as an array parameter (Postgres). My code looks like

.where(
   Tables.TABLE.FIELD.in(idsList)
)

How can I do this?

Why it's not done by default since it's more efficient that generation (and parsing by PG) of the string in (?, ?, ?, ?, ...)

Body:
How can I do this?

You can use the DSL.any(T[]) operator, e.g.

TABLE.FIELD.eq(any(1, 2, 3))

This will bind only one array variable to the JDBC statement

Why it's not done by default since it's more efficient that generation (and parsing by PG) of the string

It might be worth thinking about a flag in Settings. I've registered a feature request for this: https://github.com/jOOQ/jOOQ/issues/6029

In general, jOOQ allows users to write exactly the SQL they want to send to the database server, so the automatic "optimisation" and rewriting of SQL might appear quite unexpected to some users. This is just a general rule of thumb in jOOQ. It's always worth thinking about optimisations and making them opt-in through Settings.

Caution about premature optimisation!

However, it's always important to actually measure these things. While there is certainly a bit less of a parsing and SQL generation overhead with your suggested approach, beware that an array's cardinality may be much harder to estimate correctly than a hard-wired IN list. Using an array for small lists can have negative effects on your execution plan. So, the few microseconds you're saving on the parser side will weigh against the few milliseconds (?) at the execution side!

I've benchmarked this in the following blog post:
https://blog.jooq.org/sql-in-predicate-with-in-list-or-with-array-which-is-faster/

The IN list seems to consistently outperform the array version (in my specific benchmark case) until a length of around 50


问:
java: maximum execution time within for-loop
I've got the folowing code:

```<code>    List<String> instances2 = Arrays.asList("instances/umps20.txt","instances/umps22.txt","instances/umps24.txt","instances/umps26.txt","instances/umps28.txt","instances/umps30.txt","instances/umps32.txt");
    List<Integer> qq1 = Arrays.asList(9,10,11,12,13,14,14);
    List<Integer> qq2 = Arrays.asList(4,4,5,5,5,5,6);

    for (int i = 0; i<7; i++) {
        Tournament t = p.process(instances2.get(i));
        int nTeams = t.getNTeams();
        int q1 = qq1.get(i);
        int q2 = qq2.get(i);
        UndirectedGraph graph = g.create(t, q1, q2);
        new Choco(graph, nTeams);
        }
    }
</code>```

Now i want to put a limit on each iteration. So after let's say 3h = 10 800 000ms, i would like for everything in the for-loop to stop and start the next iteration over the loop. Any ideas?

Thanks in advance!

Nicholas

答:
You will have to create a new thread which will run your loop, the ExecutorService will run this loop (or whatever code you put into the call() method) for the specified amount of time.

Here is a demo of a task which takes 5 seconds to run, it will be interrupted after 3 seconds:

```<code>import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class QuickTest {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(new Task());

        try {
            System.out.println("Started..");    // your task is running
            System.out.println(future.get(3, TimeUnit.SECONDS));    // enter the amount of time you want to allow your code to run
            System.out.println("Finished!");    // the task finished within the given time
        } catch (TimeoutException e) {
            future.cancel(true);
            System.out.println("Terminated!");  // the task took too long and was interrupted
        }

        executor.shutdownNow();
    }
}

class Task implements Callable<String> {
    @Override
    public String call() throws Exception {  // enter the code you want to run for x time in here
        Thread.sleep(5000); // Just to demo some code which takes 5 seconds to finish.
        return "Ready!";    // code finished and was not interrupted (you gave it enough time).
    }
}
</code>```

Body:
I've got the folowing code:

    List<String> instances2 = Arrays.asList("instances/umps20.txt","instances/umps22.txt","instances/umps24.txt","instances/umps26.txt","instances/umps28.txt","instances/umps30.txt","instances/umps32.txt");
    List<Integer> qq1 = Arrays.asList(9,10,11,12,13,14,14);
    List<Integer> qq2 = Arrays.asList(4,4,5,5,5,5,6);

    for (int i = 0; i<7; i++) {
        Tournament t = p.process(instances2.get(i));
        int nTeams = t.getNTeams();
        int q1 = qq1.get(i);
        int q2 = qq2.get(i);
        UndirectedGraph graph = g.create(t, q1, q2);
        new Choco(graph, nTeams);
        }
    }

Now i want to put a limit on each iteration. So after let's say 3h = 10 800 000ms, i would like for everything in the for-loop to stop and start the next iteration over the loop. Any ideas?

Thanks in advance!

Nicholas

Body:
You will have to create a new thread which will run your loop, the ExecutorService will run this loop (or whatever code you put into the call() method) for the specified amount of time.

Here is a demo of a task which takes 5 seconds to run, it will be interrupted after 3 seconds:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class QuickTest {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(new Task());

        try {
            System.out.println("Started..");    // your task is running
            System.out.println(future.get(3, TimeUnit.SECONDS));    // enter the amount of time you want to allow your code to run
            System.out.println("Finished!");    // the task finished within the given time
        } catch (TimeoutException e) {
            future.cancel(true);
            System.out.println("Terminated!");  // the task took too long and was interrupted
        }

        executor.shutdownNow();
    }
}

class Task implements Callable<String> {
    @Override
    public String call() throws Exception {  // enter the code you want to run for x time in here
        Thread.sleep(5000); // Just to demo some code which takes 5 seconds to finish.
        return "Ready!";    // code finished and was not interrupted (you gave it enough time).
    }
}


问:
Why does a AWS NAT Gateway require an ElasticIP?
While creating NAT Gateway an Elastic IP Address is created in AWS. The AWS documentation (1) also mentions the same. Why is an Elastic IP Address required for NAT Gateway?

答:
Simply stated, the EIP is required because that is the way the NAT Gateway feature was engineered.

It wouldn't make sense to have a dynamic address on a NAT device -- if the address changed, that would be guaranteed to break any sessions in progress... and the only way to allocate a static address is by allocating an Elastic IP address (EIP).

It's also common to have external vendors whitelist your servers (for access to their servers) by providing them with the EIP of your NAT Gateway, in which case a dynamic address from the public pool would be unacceptable.

There may also be internal, proprietary reasons related to the way EIPs function that made this requirement a necessity... but that is not documented, so such an assertion would be mere speculation.  An example of this: the public pool addresses (like those auto-assigned to EC2 instances configured with a public IP address from the pool, not an EIP) might be engineered to the specific availability zone, or even a subset of a single availability zone (they do, after all, change, when an instance is stopped/started, implying that they might be dedicated to specific server bays within an AZ), while EIPs can migrate anywhere from one zone to another within a region.  This strongly implies different internal topologies.

This requirement (constraint?), to me, seems insignificant: you shouldn't be charged for this EIP, and if you need to increase the maximum allowed number of EIPs in a region, you can submit a support request at no charge, describing your use case, to request a limit increase.