问:
Unable to access the elements of a pointer to an array
I have a following array which I am passing as a pointer. BTW, I am new to C++ and just started pointers.

```<code>int arr[3][4]= {{2,3,4,8},{5,7,9,12},{1, 0, 6, 10}};
    //int *a = &arr[0][0];
    BuildStringFromMatrix((int *)arr, 3, 4);
</code>```

I have a a following function with which I wanna access the elements of the passed array.

```<code>void BuildStringFromMatrix(int *a, int height, int width);
</code>```

My implementation of the accessing the element is as follows

```<code>for(int i=0; i<height; i++){
      for(int j=0; i<width; j++){
        int x = *(*(a+i) + j);
        std::cout<<x;
      }
    }
</code>```

While using this implementation I am getting an error

```<code>invalid type argument of unary ‘*’ (have ‘int’
)
         int x = *(*(a+i) + j);
</code>```

How can I fix this issue.

P.S - I wanna implement this using single pointer.

答:
Your function receives a pointer to int. It doesn't "remember" that it is actually pointing to an int that is in a 2-D array (let alone what the array dimensions are).

So if you want to access a certain element of the 2-D array you must perform a calculation to find how many units to offset from the pointer to get to the intended element.  (This is sometimes called "flattening an array").

Typically row * row_length + column is the offset for a particular row-column entry, so in your case int x = a[i*width + j]; is the right statement to use.

If this is still unclear I suggest printing out the value of i*width+j at each iteration and seeing how it iterates over the array (or follow in your debugger).

Body:
I have a following array which I am passing as a pointer. BTW, I am new to C++ and just started pointers.

int arr[3][4]= {{2,3,4,8},{5,7,9,12},{1, 0, 6, 10}};
    //int *a = &arr[0][0];
    BuildStringFromMatrix((int *)arr, 3, 4);

I have a a following function with which I wanna access the elements of the passed array.

void BuildStringFromMatrix(int *a, int height, int width);

My implementation of the accessing the element is as follows

for(int i=0; i<height; i++){
      for(int j=0; i<width; j++){
        int x = *(*(a+i) + j);
        std::cout<<x;
      }
    }

While using this implementation I am getting an error

invalid type argument of unary ‘*’ (have ‘int’
)
         int x = *(*(a+i) + j);

How can I fix this issue.

P.S - I wanna implement this using single pointer.


来源: stackexchange

问:
Filtering in Scala
So suppose I have the following data (only the first few rows, this data covers an entire year) -

```<code>(2014-08-31T00:05:00.000+01:00, John)
(2014-08-31T00:11:00.000+01:00, Sarah)
(2014-08-31T00:12:00.000+01:00, George)
(2014-08-31T00:05:00.000+01:00, John)
(2014-09-01T00:05:00.000+01:00, Sarah)
(2014-09-01T00:05:00.000+01:00, George)
(2014-09-01T00:05:00.000+01:00, Jason)
</code>```

I would like to filter the data so that I only see what the names are for a specific date (say, 2014-09-05). I've tried doing this using the filter function in Scala but I keep receiving the following error -

```<code>error: value xxxx is not a member of (org.joda.time.DateTime, String)
</code>```

Is there another way of doing this?

答:
I presume from the tag your question is in the context of Spark and not pure Scala. Given that, you could filter a dataframe on a date and get the associated name(s) like this:

```<code>import org.apache.spark.sql.functions._
import sparkSession.implicits._

Seq(
  ("2014-08-31T00:05:00.000+01:00", "John"),
  ("2014-08-31T00:11:00.000+01:00", "Sarah")
...
)
.toDF("date", "name")
.filter(to_date('date).equalTo(Date.valueOf("2014-09-05")))
.select("name")
</code>```

Note that the Date above is java.sql.Date.

ContentLicense: CC BY-SA 3.0

Title: Filtering in Scala

Body:
So suppose I have the following data (only the first few rows, this data covers an entire year) -

(2014-08-31T00:05:00.000+01:00, John)
(2014-08-31T00:11:00.000+01:00, Sarah)
(2014-08-31T00:12:00.000+01:00, George)
(2014-08-31T00:05:00.000+01:00, John)
(2014-09-01T00:05:00.000+01:00, Sarah)
(2014-09-01T00:05:00.000+01:00, George)
(2014-09-01T00:05:00.000+01:00, Jason)

I would like to filter the data so that I only see what the names are for a specific date (say, 2014-09-05). I've tried doing this using the filter function in Scala but I keep receiving the following error -

error: value xxxx is not a member of (org.joda.time.DateTime, String)

Is there another way of doing this?

Body:
I presume from the tag your question is in the context of Spark and not pure Scala. Given that, you could filter a dataframe on a date and get the associated name(s) like this:

import org.apache.spark.sql.functions._
import sparkSession.implicits._

Seq(
  ("2014-08-31T00:05:00.000+01:00", "John"),
  ("2014-08-31T00:11:00.000+01:00", "Sarah")
...
)
.toDF("date", "name")
.filter(to_date('date).equalTo(Date.valueOf("2014-09-05")))
.select("name")

Note that the Date above is java.sql.Date.


问:
Javascript increment and decrement YYYY-MM-DD by 1 day
I got this from another stack question

```<code>incr_date(date_str){
    let parts = date_str.split("-");
    let dt = new Date(
    parseInt(parts[0], 10),      // year
    parseInt(parts[1], 10) - 1,  // month (starts with 0)
    parseInt(parts[2], 10)       // date
    );
    dt.setDate(dt.getDate() + 1);
    parts[0] = "" + dt.getFullYear();
    parts[1] = "" + (dt.getMonth() + 1);
    if (parts[1].length < 2) {
    parts[1] = "0" + parts[1];
    }
    parts[2] = "" + dt.getDate();
    if (parts[2].length < 2) {
    parts[2] = "0" + parts[2];
    }
    return parts.join("-");
}
</code>```

It works but how can I convert this function to decrement the date instead of increment?

I'm doing this on a react native component so I dont want to import any javascript libraries like moment.js

答:
function dateAdd(dte){
var date = new Date(dte);
date.setDate(date.getDate() + 1);
console.log("add one day= "+date)
}
function datesub(dte){
var date = new Date(dte);
date.setDate(date.getDate() - 1);
console.log("minus one day = "+ date)
}
dateAdd("01-01-2017")
datesub("01-01-2017")```

Body:
I got this from another stack question

incr_date(date_str){
    let parts = date_str.split("-");
    let dt = new Date(
    parseInt(parts[0], 10),      // year
    parseInt(parts[1], 10) - 1,  // month (starts with 0)
    parseInt(parts[2], 10)       // date
    );
    dt.setDate(dt.getDate() + 1);
    parts[0] = "" + dt.getFullYear();
    parts[1] = "" + (dt.getMonth() + 1);
    if (parts[1].length < 2) {
    parts[1] = "0" + parts[1];
    }
    parts[2] = "" + dt.getDate();
    if (parts[2].length < 2) {
    parts[2] = "0" + parts[2];
    }
    return parts.join("-");
}

It works but how can I convert this function to decrement the date instead of increment?

I'm doing this on a react native component so I dont want to import any javascript libraries like moment.js


问:
Showing validation error
Is it possible to show the request validation error message in the error page of my ASP.NET Core app when for instance Identity Server sends a: Requested scope not allowed: {myscope} ?

As it is now, all validation errors just show the /home/error?errorId=12345 page without further information.

So basically my question is: How do I get more details of the validation error?

答:
You are not supposed to show detailed error messages to the end user - this is a security risk.

Use the log to find out exactly what is wrong.

Title: Showing validation error


问:
SQL - select max value of only rows from join tables
I want to get the max value from koderpm column of rincianpembayaran table and rpembayaran_tmp. Is join be a solution for it?

I've tried this but it's not work

```<code>Select max(a.koderpem)
from rincianpembayaran as a
inner join rpembayaran_tmp as b on a.koderpem = b.koderpem
</code>```

答:
Maximum Value Common to Both Tables

If you want the maximum koderpem value common to both tables, then your query would be correct.

e.g. If rincianpembayaran has koderpem values of 3, 4, 5 and rpembayaran_tmp has values 3, 4; then your query will return 4, since that is the largest value common to both tables.

Maximum Value Across Both Tables

However, if you want the maximum koderpem value across both tables, then you can use:

```<code>SELECT MAX(max_koderpem) FROM (
  SELECT MAX(koderpem) AS max_koderpem FROM rincianpembayaran
  UNION
  SELECT MAX(koderpem) AS max_koderpem FROM rpembayaran_tmp
) AS x
</code>```

e.g. Using the same example where rincianpembayaran has koderpem values of 3, 4, 5 and rpembayaran_tmp has values 3, 4; the above query will return 5.

Explanation of Query

There are two separate queries which return the maximum value of koderpem for each individual table. Then the outer query picks the largest among these values.

```<code>-- Explanation of how the query works:

-- 1. This query gets the maximum value among 3, 4, 5
  SELECT MAX(koderpem) AS max_koderpem FROM rincianpembayaran -- returns 5

-- 2. This query gets the maximum value among 3, 4
  SELECT MAX(koderpem) AS max_koderpem FROM rpembayaran_tmp   -- returns 4

-- 3. This query merges both the above answers, to get 5, 4
  SELECT MAX(koderpem) AS max_koderpem FROM rincianpembayaran
  UNION
  SELECT MAX(koderpem) AS max_koderpem FROM rpembayaran_tmp   -- returns 5, 4

-- 4. This query picks the maximum among the 2 values 5, 4; thereby returning 5.
SELECT MAX(max_koderpem) FROM (
  SELECT MAX(koderpem) AS max_koderpem FROM rincianpembayaran
  UNION
  SELECT MAX(koderpem) AS max_koderpem FROM rpembayaran_tmp
) AS x
</code>```

Body:
I want to get the max value from koderpm column of rincianpembayaran table and rpembayaran_tmp. Is join be a solution for it?

I've tried this but it's not work

Select max(a.koderpem)
from rincianpembayaran as a
inner join rpembayaran_tmp as b on a.koderpem = b.koderpem

Body:
Maximum Value Common to Both Tables

If you want the maximum koderpem value common to both tables, then your query would be correct.

e.g. If rincianpembayaran has koderpem values of 3, 4, 5 and rpembayaran_tmp has values 3, 4; then your query will return 4, since that is the largest value common to both tables.

Maximum Value Across Both Tables

However, if you want the maximum koderpem value across both tables, then you can use:

SELECT MAX(max_koderpem) FROM (
  SELECT MAX(koderpem) AS max_koderpem FROM rincianpembayaran
  UNION
  SELECT MAX(koderpem) AS max_koderpem FROM rpembayaran_tmp
) AS x

e.g. Using the same example where rincianpembayaran has koderpem values of 3, 4, 5 and rpembayaran_tmp has values 3, 4; the above query will return 5.

Explanation of Query

There are two separate queries which return the maximum value of koderpem for each individual table. Then the outer query picks the largest among these values.

-- Explanation of how the query works:

-- 1. This query gets the maximum value among 3, 4, 5
  SELECT MAX(koderpem) AS max_koderpem FROM rincianpembayaran -- returns 5

-- 2. This query gets the maximum value among 3, 4
  SELECT MAX(koderpem) AS max_koderpem FROM rpembayaran_tmp   -- returns 4

-- 3. This query merges both the above answers, to get 5, 4
  SELECT MAX(koderpem) AS max_koderpem FROM rincianpembayaran
  UNION
  SELECT MAX(koderpem) AS max_koderpem FROM rpembayaran_tmp   -- returns 5, 4

-- 4. This query picks the maximum among the 2 values 5, 4; thereby returning 5.
SELECT MAX(max_koderpem) FROM (
  SELECT MAX(koderpem) AS max_koderpem FROM rincianpembayaran
  UNION
  SELECT MAX(koderpem) AS max_koderpem FROM rpembayaran_tmp
) AS x


问:
Are there any pre-made programs to do multiplication on numbers with 10^6+ digits?
As stated, I'm interested in programs for multiplying and dividing large numbers. I am hardly a novice coder so I can't yet prepare such algorithms myself, and I couldn't find anything on google. As a side question, what are some ballpark estimates of time for multiplying two numbers with say a million plus digits?</p>

答:
Programming languages with built-in big integers are convenient for this. Here’s Python, for example:

```<code>>>> import random
>>> a = random.randrange(10**(10**6), 10**(10**6 + 1))
>>> b = random.randrange(10**(10**6), 10**(10**6 + 1))
>>> c = a * b
</code>```

The multiplication itself takes about half a second on my device (with an i5-7500 processor). Converting the result to a decimal string stored in memory takes somewhat longer, clocking in at around 48 seconds. (If you don’t need decimal, using a base with an efficient conversion from Python’s internal representation will be much faster; hex(c), for example, is instant.) Writing the result to disk will take about 30 seconds if you use two 1.44 MB floppies and aren’t very fast at ejecting/inserting them.

The algorithm behind this is usually Schönhage–Strassen.

Body:
Programming languages with built-in big integers are convenient for this. Here’s Python, for example:

>>> import random
>>> a = random.randrange(10**(10**6), 10**(10**6 + 1))
>>> b = random.randrange(10**(10**6), 10**(10**6 + 1))
>>> c = a * b

The multiplication itself takes about half a second on my device (with an i5-7500 processor). Converting the result to a decimal string stored in memory takes somewhat longer, clocking in at around 48 seconds. (If you don’t need decimal, using a base with an efficient conversion from Python’s internal representation will be much faster; hex(c), for example, is instant.) Writing the result to disk will take about 30 seconds if you use two 1.44 MB floppies and aren’t very fast at ejecting/inserting them.

The algorithm behind this is usually Schönhage–Strassen.


问:
AWK - error in script with count variable OR error in AWK Implementation / version?

Awk version: GNU Awk 3.1.1

Platform: OpenVMS 8.4-L1

Awk knowledge: limited

Script (Awk one liner).
NOTE: OpenVMS parameter parsing requires quotes

```<code>gawk "-F" ";" "BEGIN {x = 0} ; x++ {print $0,$1"";""x}" in.file > out.file

**in.file**
file.log;2000
file.log;1999
file.log;1998
file.log;1997

**out.file**
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4
</code>```

I wanted the following instead

```<code>file.log;2000 file.log;1
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4
</code>```

If I change the awk command above to: ...{x = -1}... I get

```<code>**out.file**
file.log;2000 file.log;0
file.log;1998 file.log;2
file.log;1997 file.log;3
</code>```

What I am wondering is

Can someone else using a different platform test this to see if it produces the same output?

Could it be the awk version I am running that is at fault OR is there something wrong with my awk script that I am not understanding

It really seems to me that it should produce a file.log;1999 file.log;1 line but it doesn't. I'm at a loss and need some pointers / awk education

Thanks in advance :-)

答:
For understanding what happened, you can put additional output.

```<code>$ gawk -F\; 'BEGIN {x = 0} {print "step 1: "x} x++ {print "step 2: "x; print $0,$1";"x} {print "step 3: "x"\n"}' in.file
step 1: 0
step 3: 1

step 1: 1
step 2: 2
file.log;1999 file.log;2
step 3: 2

step 1: 2
step 2: 3
file.log;1998 file.log;3
step 3: 3

step 1: 3
step 2: 4
file.log;1997 file.log;4
step 3: 4
</code>```

So there is the effect of the post-increment.

x {something} is same as {if(x){something}}. So value of x will be use as condition for calling block {something}.

On first line, on step 1, x++ will return 0 and increment 'x', which will skip step 2. But on step 3 'x' will be 1.

On second line, on step 1, x++ will return 1 and increment 'x'. On step 2, x will be already '2'. That's what you get.

You can fix it like this:

```<code>gawk -F\; 'BEGIN {x = 0} {print $0,$1";"++x}' in.file
</code>```

Body:
Awk version: GNU Awk 3.1.1

Platform: OpenVMS 8.4-L1

Awk knowledge: limited

Script (Awk one liner).
NOTE: OpenVMS parameter parsing requires quotes

gawk "-F" ";" "BEGIN {x = 0} ; x++ {print $0,$1"";""x}" in.file > out.file

**in.file**
file.log;2000
file.log;1999
file.log;1998
file.log;1997

**out.file**
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4

I wanted the following instead

file.log;2000 file.log;1
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4

If I change the awk command above to: ...{x = -1}... I get

**out.file**
file.log;2000 file.log;0
file.log;1998 file.log;2
file.log;1997 file.log;3

What I am wondering is

Can someone else using a different platform test this to see if it produces the same output?

Could it be the awk version I am running that is at fault OR is there something wrong with my awk script that I am not understanding

It really seems to me that it should produce a file.log;1999 file.log;1 line but it doesn't. I'm at a loss and need some pointers / awk education

Thanks in advance :-)

Body:
For understanding what happened, you can put additional output.

$ gawk -F\; 'BEGIN {x = 0} {print "step 1: "x} x++ {print "step 2: "x; print $0,$1";"x} {print "step 3: "x"\n"}' in.file
step 1: 0
step 3: 1

step 1: 1
step 2: 2
file.log;1999 file.log;2
step 3: 2

step 1: 2
step 2: 3
file.log;1998 file.log;3
step 3: 3

step 1: 3
step 2: 4
file.log;1997 file.log;4
step 3: 4

So there is the effect of the post-increment.

x {something} is same as {if(x){something}}. So value of x will be use as condition for calling block {something}.

On first line, on step 1, x++ will return 0 and increment 'x', which will skip step 2. But on step 3 'x' will be 1.

On second line, on step 1, x++ will return 1 and increment 'x'. On step 2, x will be already '2'. That's what you get.

You can fix it like this:

gawk -F\; 'BEGIN {x = 0} {print $0,$1";"++x}' in.file


问:
Postman: How to check whether the field is returning null in the Postman automation
I have tried with !== null, but it is returning PASS even when the field is returning 0 or empty string.

答:
I have done similar, this is one part of the code and its works well
Check this code</p>

```<code>var jsonData = JSON.parse(responseBody);

for(i=0; i<jsonData.data.length; i++){
tests["due date is between given date range"] = jsonData.data[i].duedate < environment.Cenddate && jsonData.data[i].duedate > environment.Cstartdate;

tests["response body has department name"] = jsonData.data[i].department.name !== null;

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have done similar, this is one part of the code and its works well
Check this code

var jsonData = JSON.parse(responseBody);

for(i=0; i<jsonData.data.length; i++){
tests["due date is between given date range"] = jsonData.data[i].duedate < environment.Cenddate && jsonData.data[i].duedate > environment.Cstartdate;

tests["response body has department name"] = jsonData.data[i].department.name !== null;

}


问:
Powershell - "Invalid assignment expression." error
I've got a couple things that i'm working on. One of them is sort of an import/export thing i found on here. but i'm getting the following error

PS C:\Users\joeblogs> C:\Users\joeblogs\Scripts\Copy user data.ps1 Invalid assignment expression. The left hand side of an assignment
  operator needs to be something that can be assigned to like a variable
  or a property. At C:\Users\delpillay\Documents\Scripts\Copy user
  data.ps1:16 char:12
  + $username = <<<<  gc env:userame
      + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
      + FullyQualifiedErrorId : InvalidLeftHandSide

I don't know where to start and i'm not sure what to try...

Below is the code:

```<code>$destination = "E:\Users\%username%\Backup"
$folder = "Desktop",
#"Downloads",
"Favorites",
"My Documents",
#"Music",
#"Pictures",
#"Videos",
#"AppData\Local\Mozilla",
#"AppData\Local\Google",
#"AppData\Roaming\Mozilla"

######################################

$username = gc env:userame
$userprofile = gc env:userprofile
##$appData = gc env:localAPPDATA

###### Restore data section ######
if ([IO.Directory]::Exists($destination + "\" + $username + "\"))
{

$caption = "Choose Action";
$message = "A backup folder for $username already exists, would you like to      restore the data to the local machine?";
$Yes = new-Object System.Management.Automation.Host.ChoiceDescription  "&Yes","Yes";
$No = new-Object System.Management.Automation.Host.ChoiceDescription "&No","No";
$choices = [System.Management.Automation.Host.ChoiceDescription[]]($Yes,$No);
$answer = $host.ui.PromptForChoice($caption,$message,$choices,0)

if ($answer -eq 0)
{

    write-host -ForegroundColor green "Restoring data to local machine for  $username"
    foreach ($f in $folder)
    {
        $currentLocalFolder = $userprofile + "\" + $f
        $currentRemoteFolder = $destination + "\" + $username + "\" + $f
        write-host -ForegroundColor cyan "  $f..."
        Copy-Item -ErrorAction silentlyContinue -recurse $currentRemoteFolder $userprofile

        if ($f -eq "AppData\Local\Mozilla") { rename-item $currentLocalFolder "$currentLocalFolder.old" }
        if ($f -eq "AppData\Roaming\Mozilla") { rename-item $currentLocalFolder "$currentLocalFolder.old" }
        if ($f -eq "AppData\Local\Google") { rename-item $currentLocalFolder "$currentLocalFolder.old" }

    }
    rename-item "$destination\$username" "$destination\$username.restored"
    write-host -ForegroundColor green "Restore Complete!"
}

else
{
    write-host -ForegroundColor yellow "Aborting process"
    exit
}

}

###### Backup Data section ########
#else
{

Write-Host -ForegroundColor green "Outlook is about to close, save any unsaved emails then press any key to continue ..."

$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Get-Process | Where { $_.Name -Eq "OUTLOOK" } | Kill

write-host -ForegroundColor green "Backing up data from local machine for $username"

foreach ($f in $folder)
{
    $currentLocalFolder = $userprofile + "\" + $f
    $currentRemoteFolder = $destination + "\" + $username + "\" + $f
    $currentFolderSize = (Get-ChildItem -ErrorAction silentlyContinue $currentLocalFolder -Recurse -Force | Measure-Object -ErrorAction silentlyContinue -Property Length -Sum ).Sum / 1MB
    $currentFolderSizeRounded = [System.Math]::Round($currentFolderSize)
    write-host -ForegroundColor cyan "  $f... ($currentFolderSizeRounded MB)"
    Copy-Item -ErrorAction silentlyContinue -recurse $currentLocalFolder $currentRemoteFolder
}

$oldStylePST = [IO.Directory]::GetFiles($appData + "\Microsoft\Outlook", "*.pst")
foreach($pst in $oldStylePST)
{
    if ((test-path -path ($destination + "\" + $username + "\Documents\Outlook Files\oldstyle")) -eq 0){new-item -type directory -path ($destination + "\" + $username + "\Documents\Outlook Files\oldstyle") | out-null}
    write-host -ForegroundColor yellow "  $pst..."
    Copy-Item $pst ($destination + "\" + $username + "\Documents\Outlook Files\oldstyle")
}

write-host -ForegroundColor green "Backup complete!"

}
</code>```

答:
Few observations:

You are not commenting the Favourites and My Documents. If you want to use them then use comma separated directly.

Use this:

```<code>$destination = "E:\Users\%username%\Backup"
$folder = "Desktop","Favorites","My Documents"
#"Downloads",
#"Favorites",
#"My Documents",
#"Music",
#"Pictures",
#"Videos",
#"AppData\Local\Mozilla",
#"AppData\Local\Google",
#"AppData\Roaming\Mozilla"
</code>```

You have missed the n in username:

```<code>$username = gc env:username
</code>```

Donot use gc env:username. Instead directly access them like this below: Completely reframed:

```<code>$destination = "E:\Users\%username%\Backup"
$folder = "Desktop","Favorites","My Documents"
#"Downloads",
#"Favorites",
#"My Documents",
#"Music",
#"Pictures",
#"Videos",
#"AppData\Local\Mozilla",
#"AppData\Local\Google",
#"AppData\Roaming\Mozilla"

######################################

$username = $env:username
$userprofile = $env:userprofile
##$appData = gc env:localAPPDATA
</code>```

These are the major things that have been fixed. Hope it helps you.

Body:
I've got a couple things that i'm working on. One of them is sort of an import/export thing i found on here. but i'm getting the following error

PS C:\Users\joeblogs> C:\Users\joeblogs\Scripts\Copy user data.ps1 Invalid assignment expression. The left hand side of an assignment
  operator needs to be something that can be assigned to like a variable
  or a property. At C:\Users\delpillay\Documents\Scripts\Copy user
  data.ps1:16 char:12
  + $username = <<<<  gc env:userame
      + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
      + FullyQualifiedErrorId : InvalidLeftHandSide

I don't know where to start and i'm not sure what to try...

Below is the code:

$destination = "E:\Users\%username%\Backup"
$folder = "Desktop",
#"Downloads",
"Favorites",
"My Documents",
#"Music",
#"Pictures",
#"Videos",
#"AppData\Local\Mozilla",
#"AppData\Local\Google",
#"AppData\Roaming\Mozilla"

######################################

$username = gc env:userame
$userprofile = gc env:userprofile
##$appData = gc env:localAPPDATA

###### Restore data section ######
if ([IO.Directory]::Exists($destination + "\" + $username + "\"))
{

$caption = "Choose Action";
$message = "A backup folder for $username already exists, would you like to      restore the data to the local machine?";
$Yes = new-Object System.Management.Automation.Host.ChoiceDescription  "&Yes","Yes";
$No = new-Object System.Management.Automation.Host.ChoiceDescription "&No","No";
$choices = [System.Management.Automation.Host.ChoiceDescription[]]($Yes,$No);
$answer = $host.ui.PromptForChoice($caption,$message,$choices,0)

if ($answer -eq 0)
{

    write-host -ForegroundColor green "Restoring data to local machine for  $username"
    foreach ($f in $folder)
    {
        $currentLocalFolder = $userprofile + "\" + $f
        $currentRemoteFolder = $destination + "\" + $username + "\" + $f
        write-host -ForegroundColor cyan "  $f..."
        Copy-Item -ErrorAction silentlyContinue -recurse $currentRemoteFolder $userprofile

        if ($f -eq "AppData\Local\Mozilla") { rename-item $currentLocalFolder "$currentLocalFolder.old" }
        if ($f -eq "AppData\Roaming\Mozilla") { rename-item $currentLocalFolder "$currentLocalFolder.old" }
        if ($f -eq "AppData\Local\Google") { rename-item $currentLocalFolder "$currentLocalFolder.old" }

    }
    rename-item "$destination\$username" "$destination\$username.restored"
    write-host -ForegroundColor green "Restore Complete!"
}

else
{
    write-host -ForegroundColor yellow "Aborting process"
    exit
}

}

###### Backup Data section ########
#else
{

Write-Host -ForegroundColor green "Outlook is about to close, save any unsaved emails then press any key to continue ..."

$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Get-Process | Where { $_.Name -Eq "OUTLOOK" } | Kill

write-host -ForegroundColor green "Backing up data from local machine for $username"

foreach ($f in $folder)
{
    $currentLocalFolder = $userprofile + "\" + $f
    $currentRemoteFolder = $destination + "\" + $username + "\" + $f
    $currentFolderSize = (Get-ChildItem -ErrorAction silentlyContinue $currentLocalFolder -Recurse -Force | Measure-Object -ErrorAction silentlyContinue -Property Length -Sum ).Sum / 1MB
    $currentFolderSizeRounded = [System.Math]::Round($currentFolderSize)
    write-host -ForegroundColor cyan "  $f... ($currentFolderSizeRounded MB)"
    Copy-Item -ErrorAction silentlyContinue -recurse $currentLocalFolder $currentRemoteFolder
}

$oldStylePST = [IO.Directory]::GetFiles($appData + "\Microsoft\Outlook", "*.pst")
foreach($pst in $oldStylePST)
{
    if ((test-path -path ($destination + "\" + $username + "\Documents\Outlook Files\oldstyle")) -eq 0){new-item -type directory -path ($destination + "\" + $username + "\Documents\Outlook Files\oldstyle") | out-null}
    write-host -ForegroundColor yellow "  $pst..."
    Copy-Item $pst ($destination + "\" + $username + "\Documents\Outlook Files\oldstyle")
}

write-host -ForegroundColor green "Backup complete!"

}

Body:
Few observations:

You are not commenting the Favourites and My Documents. If you want to use them then use comma separated directly.

Use this:

$destination = "E:\Users\%username%\Backup"
$folder = "Desktop","Favorites","My Documents"
#"Downloads",
#"Favorites",
#"My Documents",
#"Music",
#"Pictures",
#"Videos",
#"AppData\Local\Mozilla",
#"AppData\Local\Google",
#"AppData\Roaming\Mozilla"

You have missed the n in username:

$username = gc env:username

Donot use gc env:username. Instead directly access them like this below: Completely reframed:

$destination = "E:\Users\%username%\Backup"
$folder = "Desktop","Favorites","My Documents"
#"Downloads",
#"Favorites",
#"My Documents",
#"Music",
#"Pictures",
#"Videos",
#"AppData\Local\Mozilla",
#"AppData\Local\Google",
#"AppData\Roaming\Mozilla"

######################################

$username = $env:username
$userprofile = $env:userprofile
##$appData = gc env:localAPPDATA

These are the major things that have been fixed. Hope it helps you.


问:
How to turn off HTML input form field suggestions?
By suggestions, I mean the drop down menu appear when you start typing, and it's suggestions are based on what you've typed before:

For example, when I type 'a' in title field, it will give me a ton of suggestions which is pretty annoying.

How can this be turned off?

答:
What you want is to disable HTML  autocomplete Attribute.

Setting autocomplete="off" here has two effects:

It stops the browser from saving field data for later autocompletion
  on similar forms though heuristics that vary by browser. It stops the
  browser from caching form data in session history. When form data is
  cached in session history, the information filled in by the user will
  be visible after the user has submitted the form and clicked on the
  Back button to go back to the original form page.

Read more on MDN Network

Here's an example how to do it.

<form action="#" autocomplete="on">
  First name:<input type="text" name="fname">

  Last name: <input type="text" name="lname">

  E-mail: <input type="email" name="email" autocomplete="off">

  <input type="submit">
</form>```
</div>
</div>
</p>

<p>If it's on React framework then use as follows:</p>

```<input
    id={field.name}
    className="form-control"
    type="text"
    placeholder={field.name}
    autoComplete="off"
    {...fields}/>
```

<p>Link to react docs</p>

<p><strong>Update</strong></p>

<p>Here's an update to fix some browsers skipping "autocomplete=off" flag.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="#" autocomplete="off">
  First name: <input type="text" name="fname" autocomplete="off" readonly onfocus="this.removeAttribute('readonly');"><br> Last name: <input type="text" name="lname" autocomplete="off" readonly onfocus="this.removeAttribute('readonly');"><br> E-mail:
  <input type="email" name="email" autocomplete="off" readonly onfocus="this.removeAttribute('readonly');"><br>
  <input type="submit">
</form></code>```

Body:
What you want is to disable HTML  autocomplete Attribute.

Setting autocomplete="off" here has two effects:

It stops the browser from saving field data for later autocompletion
  on similar forms though heuristics that vary by browser. It stops the
  browser from caching form data in session history. When form data is
  cached in session history, the information filled in by the user will
  be visible after the user has submitted the form and clicked on the
  Back button to go back to the original form page.

Read more on MDN Network

Here's an example how to do it.

<form action="#" autocomplete="on">
  First name:<input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  E-mail: <input type="email" name="email" autocomplete="off"><br>
  <input type="submit">
</form>

If it's on React framework then use as follows:

<input
    id={field.name}
    className="form-control"
    type="text"
    placeholder={field.name}
    autoComplete="off"
    {...fields}/>

Link to react docs

Update

Here's an update to fix some browsers skipping "autocomplete=off" flag.

<form action="#" autocomplete="off">
  First name: <input type="text" name="fname" autocomplete="off" readonly onfocus="this.removeAttribute('readonly');"><br> Last name: <input type="text" name="lname" autocomplete="off" readonly onfocus="this.removeAttribute('readonly');"><br> E-mail:
  <input type="email" name="email" autocomplete="off" readonly onfocus="this.removeAttribute('readonly');"><br>
  <input type="submit">
</form>


问:
Transpile errors with cordova-plugin-file-transfer
I want to use the cordova file transfer plugin. I'm using it through the Ionic-Native transfer module.

The app won't run because there is a transpile error with the file transfer plugin and the file plugin:

```<code>transpile started ...
typescript: plugins/cordova-plugin-file-transfer/types/index.d.ts, line: 9
Cannot find type definition file for 'cordova-plugin-file'.

L8:  * @param server            URL of the server to receive the file, as encoded by encodeURI().
L9:  * @param successCallback   A callback that is passed a FileUploadResult object.
L10: * @param errorCallback     A callback that executes if an error occurs retrieving the FileUploadResult.
</code>```

I installed @types/cordova-plugin-file through npm, but the app won't run because of duplicate identifiers in the two cordova-plugin-file packages:

```<code>transpile started ...
typescript: node_modules/@types/cordova-plugin-file/index.d.ts, line: 376
Duplicate identifier 'PERSISTENT'.

typescript: node_modules/@types/cordova-plugin-file/index.d.ts, line: 377
Duplicate identifier 'TEMPORARY'.

typescript: plugins/cordova-plugin-file/types/index.d.ts, line: 376
Duplicate identifier 'PERSISTENT'.

typescript: plugins/cordova-plugin-file/types/index.d.ts, line: 377
Duplicate identifier 'TEMPORARY'.
</code>```

What is the right approach here?

答:
It seems the "plugin/" folder is cordova plugins for ionic2, which you may not need to perform typescript compilation,

You can always ignore the index.d.ts by specifying the exclude target from tsconfig.json

Body:
I want to use the cordova file transfer plugin. I'm using it through the Ionic-Native transfer module.

The app won't run because there is a transpile error with the file transfer plugin and the file plugin:

transpile started ...
typescript: plugins/cordova-plugin-file-transfer/types/index.d.ts, line: 9
Cannot find type definition file for 'cordova-plugin-file'.

L8:  * @param server            URL of the server to receive the file, as encoded by encodeURI().
L9:  * @param successCallback   A callback that is passed a FileUploadResult object.
L10: * @param errorCallback     A callback that executes if an error occurs retrieving the FileUploadResult.

I installed @types/cordova-plugin-file through npm, but the app won't run because of duplicate identifiers in the two cordova-plugin-file packages:

transpile started ...
typescript: node_modules/@types/cordova-plugin-file/index.d.ts, line: 376
Duplicate identifier 'PERSISTENT'.

typescript: node_modules/@types/cordova-plugin-file/index.d.ts, line: 377
Duplicate identifier 'TEMPORARY'.

typescript: plugins/cordova-plugin-file/types/index.d.ts, line: 376
Duplicate identifier 'PERSISTENT'.

typescript: plugins/cordova-plugin-file/types/index.d.ts, line: 377
Duplicate identifier 'TEMPORARY'.

What is the right approach here?


问:
how to override func with autocompletion

EDIT

Just restart xcode, and everything works. Seems xcode got stuck in something.

ORIGIN

I'm new to swift, and I want to write a custom UICollectionViewCell.
But I found autocompletion just don't work. In objc I can autocomplete initWithFrame: by typing "- initWithF" + TAB, But no matter what I tried in swift it always shows no completion or other stuff.

So what is the key word to override a function in swift? Or does swift broke in xcode 8.3?

答:
You have to add these two functions:</p>

```<code>override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
</code>```

Body:
You have to add these two functions:

override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }


问:
Why does the C# compiler create a new Action instance for every passed delegate?
Consider the following code:

```<code>public static void M() {
    A(V);
    A(V);
    A(V);
}

public static void V() {

}

public static void A(Action x) {
    x();
}
</code>```

This gets compiled behind-the-scenes as:

```<code>public static void M() {
    A(new Action(V));
    A(new Action(V));
    A(new Action(V));
}
</code>```

However, we can write our own simple performance improvement that reduces unnecessary garbage:

```<code>private static readonly Action v = new Action(V);
A(v);
A(v);
A(v);
</code>```

For this very simple case, is there any reason Roslyn couldn't make a similar optimisation?

If the answer is no, what about when the methods are not static but instance members? And what about when there are closed-over variables captured?

答:
There are a number of different components and nuances to your question, so I'll attempt to break them down one and a time.

First, the compiler is performing magic through syntactic sugar.  As you noted,

```<code>public static void M() { A(V); }
</code>```

is the equivalent of

```<code>public static void M() { A(new Action(V)); }
</code>```

but the compiler is saving you the trouble of having to declare the action instance directly.  In either case however, the generated IL needs to perform a series of steps:

```<code>IL_000C:  ldnull
IL_000D:  ldftn       UserQuery.V
IL_0013:  newobj      System.Action..ctor
IL_0018:  call        UserQuery.A
IL_0014:  ldarg.0
IL_0015:  ldarg.0
IL_0016:  ldftn       UserQuery.V
IL_001C:  newobj      System.Action..ctor
IL_0021:  call        UserQuery.A
IL_0027:  ldarg.0
IL_0028:  ldarg.0
IL_0029:  ldftn       UserQuery.V
IL_002F:  newobj      System.Action..ctor
IL_0034:  call        UserQuery.A
</code>```

A native pointer is generated for our V method at instruction IL_000D.  The previous instruction is simply telling us that the method is static, otherwise we'd see instruction IL_000C:  ldarg.0 since our instance method argument would need to be pushed onto the evaluation stack.  However, in either case, the new action instance still needs to be generated at instruction IL_0013:  newobj since we are passing a method pointer (under the hood), not a method instance.  Finally, once we have our pointer and new instance, we can invoke our A method.

However, in your second example, things shake up:

```<code>IL_0001:  ldsfld      UserQuery.v
IL_0006:  call        UserQuery.A
IL_000B:  nop
IL_000C:  ldsfld      UserQuery.v
IL_0011:  call        UserQuery.A
IL_0016:  nop
IL_0017:  ldsfld      UserQuery.v
IL_001C:  call        UserQuery.A
</code>```

Instead of generating pointers or creating new objects, we simply push the value of our static field v onto the evaluation stack in our ldsfld instructions.  Since we have the value, we don't have to perform any additional operations other than call our A method.

Once again, in our second example an additional instruction is generated for instance method declarations, but it doesn't change how the parameter is generated and passed, which is the fundamental underlying reason why Roslyn wouldn't optimize...the compiler is obligated to generate IL that the runtime understands and expects.  Trying to optimize your first case to act like the second case is a fundamentally different set of instructions and it can't be optimized as such.

Body:
Consider the following code:

public static void M() {
    A(V);
    A(V);
    A(V);
}

public static void V() {

}

public static void A(Action x) {
    x();
}

This gets compiled behind-the-scenes as:

public static void M() {
    A(new Action(V));
    A(new Action(V));
    A(new Action(V));
}

However, we can write our own simple performance improvement that reduces unnecessary garbage:

private static readonly Action v = new Action(V);
A(v);
A(v);
A(v);

For this very simple case, is there any reason Roslyn couldn't make a similar optimisation?

If the answer is no, what about when the methods are not static but instance members? And what about when there are closed-over variables captured?

Body:
There are a number of different components and nuances to your question, so I'll attempt to break them down one and a time.

First, the compiler is performing magic through syntactic sugar.  As you noted,

public static void M() { A(V); }

is the equivalent of

public static void M() { A(new Action(V)); }

but the compiler is saving you the trouble of having to declare the action instance directly.  In either case however, the generated IL needs to perform a series of steps:

IL_000C:  ldnull
IL_000D:  ldftn       UserQuery.V
IL_0013:  newobj      System.Action..ctor
IL_0018:  call        UserQuery.A
IL_0014:  ldarg.0
IL_0015:  ldarg.0
IL_0016:  ldftn       UserQuery.V
IL_001C:  newobj      System.Action..ctor
IL_0021:  call        UserQuery.A
IL_0027:  ldarg.0
IL_0028:  ldarg.0
IL_0029:  ldftn       UserQuery.V
IL_002F:  newobj      System.Action..ctor
IL_0034:  call        UserQuery.A

A native pointer is generated for our V method at instruction IL_000D.  The previous instruction is simply telling us that the method is static, otherwise we'd see instruction IL_000C:  ldarg.0 since our instance method argument would need to be pushed onto the evaluation stack.  However, in either case, the new action instance still needs to be generated at instruction IL_0013:  newobj since we are passing a method pointer (under the hood), not a method instance.  Finally, once we have our pointer and new instance, we can invoke our A method.

However, in your second example, things shake up:

IL_0001:  ldsfld      UserQuery.v
IL_0006:  call        UserQuery.A
IL_000B:  nop
IL_000C:  ldsfld      UserQuery.v
IL_0011:  call        UserQuery.A
IL_0016:  nop
IL_0017:  ldsfld      UserQuery.v
IL_001C:  call        UserQuery.A

Instead of generating pointers or creating new objects, we simply push the value of our static field v onto the evaluation stack in our ldsfld instructions.  Since we have the value, we don't have to perform any additional operations other than call our A method.

Once again, in our second example an additional instruction is generated for instance method declarations, but it doesn't change how the parameter is generated and passed, which is the fundamental underlying reason why Roslyn wouldn't optimize...the compiler is obligated to generate IL that the runtime understands and expects.  Trying to optimize your first case to act like the second case is a fundamentally different set of instructions and it can't be optimized as such.


问:
Create a repository with sub-repositories
I want to create a repo that has sub-repositories, to do that I created a sample folder in my workspace:

```<code>$ cd ~/workspace/
$ mkdir samples
$ cd samples
$ pwd
~/workspace/samples
</code>```

This means that the sample folder will be the main repository (something like a container),
for example I would like to have the following structure:

```<code>$ mkdir sample-java
$ mkdir sample-c-plus-plus
$ mkdir sample-csharp
$ ls -l
total 3
drwxr-xr-x  juanca  staff  408 Mar 30 20:04 sample-java
drwxr-xr-x  juanca  staff  408 Mar 30 20:12 sample-c-plus-plus
drwxr-xr-x  juanca  staff  408 Mar 30 20:23 sample-csharp
</code>```

I want a repo for each folder listed above, in my github account, for example:

```<code>|- samples -----------------> github.com/my-user/samples.git
    |- sample-java ---------> github.com/my-user/samples.git/sample-java.git
    |- sample-c-plus-plus --> github.com/my-user/samples.git/sample-c-plus-plus.git
    |- sample-csharp -------> github.com/my-user/samples.git/sample-csharp.git
</code>```

I would like to have control in each sample-* folder and in turn all of them grouped in a main repository.

Is it possible? Or what would be the best approach?

I found something similar with git submodule, but this adds an existing repo, for example:

```<code>$ git submodule add https:// github.com/any-account/any-project.git any-project
</code>```

I do not think this solution works for me. Any idea?

答:
I found something similar with git submodule, but this adds an existing repo.

This is actually the solution.

Each of your sub-repo should be individual repos of their own (ie, directly under  github.com/my-user).

That way, you can declare them as submodule of your main repo

```<code>cd samples
git submodule add github.com/my-user/sample-java.git sample-java
git submodule add github.com/my-user/sample-c-plus-plusgit sample-c-plus-plus
git submodule add github.com/my-user/csharp.git sample-csharp
</code>```

That way:

any git clone --recursive of the repo samples would automatically clone and checkout those sub-repos at their respective SHA1.

any modification done in each repo can be tracked indivisually, added and committed (and pushed) to its own repo.

Body:
I want to create a repo that has sub-repositories, to do that I created a sample folder in my workspace:

$ cd ~/workspace/
$ mkdir samples
$ cd samples
$ pwd
~/workspace/samples

This means that the sample folder will be the main repository (something like a container),
for example I would like to have the following structure:

$ mkdir sample-java
$ mkdir sample-c-plus-plus
$ mkdir sample-csharp
$ ls -l
total 3
drwxr-xr-x  juanca  staff  408 Mar 30 20:04 sample-java
drwxr-xr-x  juanca  staff  408 Mar 30 20:12 sample-c-plus-plus
drwxr-xr-x  juanca  staff  408 Mar 30 20:23 sample-csharp

I want a repo for each folder listed above, in my github account, for example:

|- samples -----------------> github.com/my-user/samples.git
    |- sample-java ---------> github.com/my-user/samples.git/sample-java.git
    |- sample-c-plus-plus --> github.com/my-user/samples.git/sample-c-plus-plus.git
    |- sample-csharp -------> github.com/my-user/samples.git/sample-csharp.git

I would like to have control in each sample-* folder and in turn all of them grouped in a main repository.

Is it possible? Or what would be the best approach?

I found something similar with git submodule, but this adds an existing repo, for example:

$ git submodule add https:// github.com/any-account/any-project.git any-project

I do not think this solution works for me. Any idea?

Body:
I found something similar with git submodule, but this adds an existing repo.

This is actually the solution.

Each of your sub-repo should be individual repos of their own (ie, directly under  github.com/my-user).

That way, you can declare them as submodule of your main repo

cd samples
git submodule add github.com/my-user/sample-java.git sample-java
git submodule add github.com/my-user/sample-c-plus-plusgit sample-c-plus-plus
git submodule add github.com/my-user/csharp.git sample-csharp

That way:

any git clone --recursive of the repo samples would automatically clone and checkout those sub-repos at their respective SHA1.

any modification done in each repo can be tracked indivisually, added and committed (and pushed) to its own repo.


问:
"The operation is not valid for the state of the transaction" error and transaction scope
I am getting the following error when I try to call a stored procedure that contains a SELECT Statement:

The operation is not valid for the state of the transaction

Here is the structure of my calls:

```<code>public void MyAddUpdateMethod()
{

    using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
    {
        using(SQLServer Sql = new SQLServer(this.m_connstring))
        {
            //do my first add update statement

            //do my call to the select statement sp
            bool DoesRecordExist = this.SelectStatementCall(id)
        }
    }
}

public bool SelectStatementCall(System.Guid id)
{
    using(SQLServer Sql = new SQLServer(this.m_connstring)) //breaks on this line
    {
        //create parameters
        //
    }
}
</code>```

Is the problem with me creating another connection to the same database within the transaction?

答:
I also come across same problem, I changed transaction timeout to 15 minutes and it works.
I hope this helps.</p>

```<code>TransactionOptions options = new TransactionOptions();
options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
options.Timeout = new TimeSpan(0, 15, 0);
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required,options))
{
    sp1();
    sp2();
    ...

}
</code>```

OwnerDisplayName: Michael Kniskern

Body:
I am getting the following error when I try to call a stored procedure that contains a SELECT Statement:

The operation is not valid for the state of the transaction

Here is the structure of my calls:

public void MyAddUpdateMethod()
{

    using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
    {
        using(SQLServer Sql = new SQLServer(this.m_connstring))
        {
            //do my first add update statement

            //do my call to the select statement sp
            bool DoesRecordExist = this.SelectStatementCall(id)
        }
    }
}

public bool SelectStatementCall(System.Guid id)
{
    using(SQLServer Sql = new SQLServer(this.m_connstring)) //breaks on this line
    {
        //create parameters
        //
    }
}

Is the problem with me creating another connection to the same database within the transaction?

Body:
I also come across same problem, I changed transaction timeout to 15 minutes and it works.
I hope this helps.

TransactionOptions options = new TransactionOptions();
options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
options.Timeout = new TimeSpan(0, 15, 0);
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required,options))
{
    sp1();
    sp2();
    ...

}

ContentLicense: CC BY-SA 2.5


问:
In Gtk3 C, while connected to "key-release-event" how to avoid initial Return pressed to run the application
Edit: I have found a solution for the simple example below, but it fails for my real application, and generates a critical warning on the example below. Through trial and error, I discovered that inserting gtk_main_quit () at the end of the activate function successfully blocks the initial command line "Return". However, of course, it also generates a critical warning: Gtk-CRITICAL **: gtk_main_quit: assertion 'main_loops != NULL' failed. Another thing that works for the example but I don't want in my application is to put up a "hello" dialog in the activate function which the user has to dismiss.

I am working on a Gtk3 app that listens for the key-release-event, and I would like one of those events to be the "Return" key. The app will normally be started from a .desktop file, but may be started from a terminal too. When started from a terminal, it recognizes the initial "Return"  that the user pressed to execute the app as a key-press. How can I avoid that? Here is a simple example "test_return.c"

```<code>/* gcc `pkg-config --cflags gtk+-3.0` -o test_return test_return.c `pkg-config --libs gtk+-3.0`
 */
#include <gtk/gtk.h>

static gboolean key_event_cb (GtkWidget *widget,
                            GdkEventKey *event,
                                gpointer data)
{
  if (event->keyval == GDK_KEY_Return) {
    GtkWidget *dialog =
      gtk_message_dialog_new (GTK_WINDOW(widget),
          GTK_DIALOG_DESTROY_WITH_PARENT,
          GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE,
          "Return");
    gtk_dialog_run (GTK_DIALOG (dialog));
    gtk_widget_destroy (dialog);
    return TRUE;
  }
  return FALSE; //allow further processing of the keypress if it's not Return
}

static void activate (GtkApplication* app,
                      gpointer        user_data)
{
  GtkWidget *window;

  window = gtk_application_window_new (app);
  gtk_widget_show_all (window);
  g_signal_connect (window, "key-release-event",
                    G_CALLBACK (key_event_cb), NULL); //keyboard events
}

int
main (int    argc,
      char **argv)
{
  GtkApplication *app;
  int status;

  app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
  status = g_application_run (G_APPLICATION (app), 0, NULL);
  g_object_unref (app);

  return status;
}
</code>```

What I want to happen is that it will not pop up a dialog until "Return" is pressed. When run from a terminal, it immediately shows the dialog because it recognizes the "Return" pressed in the terminal to start the app. When run from a .desktop file, it works as expected.

At first, I tried simply defining a gboolean that was TRUE at start, and FALSE after the first Return. That worked from the terminal, but then requred 2 Return key-presses when started from a .desktop file. My app will only be used in Linux (and in fact requires X11). I tried fflush(stdin);, but it doesn't work. I even tried a timer to ignore Returns received in the first hundreth of a second using https://developer.gnome.org/glib/stable/glib-Timers.html, but I get strange behavior.

From the comments, I remembered that I've already tried waiting to connect the signal until the widget is fully drawn. It didn't work. Apparently, the "Return" key press is waiting in a buffer, but I can't figure out how to clear that buffer.

Also from the comments, I remembered that I already tried getchar() but that just waited for a character to be entered, completely ignoring the Return that I was trying to get rid of.

I edited main() replacing argc, argv with 0, NULL in the g_application_run funtion to ignore command line arguments, but that didn't help.

答:
As I was reading through all the GdkEvent functions: https://developer.gnome.org/gdk3/stable/gdk3-Events.html, I eventually realized it might be informative to use gdk_set_show_events (TRUE) so that as the program runs, all the events are listed in the terminal. There were tons of events, but just searching on the word "key" I eventually realized something very important. There is a difference between the Return key event from the command line and all the other Return key events: the one from the command line doesn't have a key-press-event, only a key-release event! So, here's how the solution works for the example shown in my question:

```<code>/* gcc `pkg-config --cflags gtk+-3.0` -o test_return test_return.c `pkg-config --libs gtk+-3.0`
 */
#include <gtk/gtk.h>

// Need to keep track of both key press and key release to distinguish unwanted terminal Return from others.
// The terminal Return that started the app won't have a key press event.
static gboolean key_press_event_cb (GtkWidget *widget,
                            GdkEventKey *event,
                                gpointer data)
{
  gboolean *p_key_pressed = data;
  *p_key_pressed = TRUE;
  return FALSE; //keep processing event
}

static gboolean key_release_event_cb (GtkWidget *widget,
                            GdkEventKey *event,
                                gpointer data)
{
  gboolean *p_key_pressed = data;
  // If there's no key-press before this key-release, then it's from starting the app in a terminal
  // So ignore it.
  if (*p_key_pressed & event->keyval == GDK_KEY_Return) {
    GtkWidget *dialog =
      gtk_message_dialog_new (GTK_WINDOW(widget),
          GTK_DIALOG_DESTROY_WITH_PARENT,
          GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE,
          "time is %d", event->time);
    gtk_dialog_run (GTK_DIALOG (dialog));
    gtk_widget_destroy (dialog);
    return TRUE;
  }
  return FALSE; //allow further processing of the keypress if it's not Return
}

static void activate (GtkApplication* app,
                      gpointer        user_data)
{
  GtkWidget *window;
  // create a pointer to a gboolean to track the key press events
  static gboolean key_pressed = FALSE, *p_key_pressed = &key_pressed;

  window = gtk_application_window_new (app);

  g_signal_connect (window, "key-press-event",
                    G_CALLBACK (key_press_event_cb), p_key_pressed); // p_key_pressed will be the "data" in cb function
  g_signal_connect (window, "key-release-event",
                    G_CALLBACK (key_release_event_cb), p_key_pressed); // p_key_pressed will be the "data" in cb function

  gtk_widget_show_all (window);
}

int
main (int    argc,
      char **argv)
{
  GtkApplication *app;
  int status;

  app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
  status = g_application_run (G_APPLICATION (app), 0, NULL);
  g_object_unref (app);

  return status;
}
</code>```

Body:
Edit: I have found a solution for the simple example below, but it fails for my real application, and generates a critical warning on the example below. Through trial and error, I discovered that inserting gtk_main_quit () at the end of the activate function successfully blocks the initial command line "Return". However, of course, it also generates a critical warning: Gtk-CRITICAL **: gtk_main_quit: assertion 'main_loops != NULL' failed. Another thing that works for the example but I don't want in my application is to put up a "hello" dialog in the activate function which the user has to dismiss.

I am working on a Gtk3 app that listens for the key-release-event, and I would like one of those events to be the "Return" key. The app will normally be started from a .desktop file, but may be started from a terminal too. When started from a terminal, it recognizes the initial "Return"  that the user pressed to execute the app as a key-press. How can I avoid that? Here is a simple example "test_return.c"

/* gcc `pkg-config --cflags gtk+-3.0` -o test_return test_return.c `pkg-config --libs gtk+-3.0`
 */
#include <gtk/gtk.h>

static gboolean key_event_cb (GtkWidget *widget,
                            GdkEventKey *event,
                                gpointer data)
{
  if (event->keyval == GDK_KEY_Return) {
    GtkWidget *dialog =
      gtk_message_dialog_new (GTK_WINDOW(widget),
          GTK_DIALOG_DESTROY_WITH_PARENT,
          GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE,
          "Return");
    gtk_dialog_run (GTK_DIALOG (dialog));
    gtk_widget_destroy (dialog);
    return TRUE;
  }
  return FALSE; //allow further processing of the keypress if it's not Return
}

static void activate (GtkApplication* app,
                      gpointer        user_data)
{
  GtkWidget *window;

  window = gtk_application_window_new (app);
  gtk_widget_show_all (window);
  g_signal_connect (window, "key-release-event",
                    G_CALLBACK (key_event_cb), NULL); //keyboard events
}

int
main (int    argc,
      char **argv)
{
  GtkApplication *app;
  int status;

  app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
  status = g_application_run (G_APPLICATION (app), 0, NULL);
  g_object_unref (app);

  return status;
}

What I want to happen is that it will not pop up a dialog until "Return" is pressed. When run from a terminal, it immediately shows the dialog because it recognizes the "Return" pressed in the terminal to start the app. When run from a .desktop file, it works as expected.

At first, I tried simply defining a gboolean that was TRUE at start, and FALSE after the first Return. That worked from the terminal, but then requred 2 Return key-presses when started from a .desktop file. My app will only be used in Linux (and in fact requires X11). I tried fflush(stdin);, but it doesn't work. I even tried a timer to ignore Returns received in the first hundreth of a second using https://developer.gnome.org/glib/stable/glib-Timers.html, but I get strange behavior.

From the comments, I remembered that I've already tried waiting to connect the signal until the widget is fully drawn. It didn't work. Apparently, the "Return" key press is waiting in a buffer, but I can't figure out how to clear that buffer.

Also from the comments, I remembered that I already tried getchar() but that just waited for a character to be entered, completely ignoring the Return that I was trying to get rid of.

I edited main() replacing argc, argv with 0, NULL in the g_application_run funtion to ignore command line arguments, but that didn't help.

Body:
As I was reading through all the GdkEvent functions: https://developer.gnome.org/gdk3/stable/gdk3-Events.html, I eventually realized it might be informative to use gdk_set_show_events (TRUE) so that as the program runs, all the events are listed in the terminal. There were tons of events, but just searching on the word "key" I eventually realized something very important. There is a difference between the Return key event from the command line and all the other Return key events: the one from the command line doesn't have a key-press-event, only a key-release event! So, here's how the solution works for the example shown in my question:

/* gcc `pkg-config --cflags gtk+-3.0` -o test_return test_return.c `pkg-config --libs gtk+-3.0`
 */
#include <gtk/gtk.h>

// Need to keep track of both key press and key release to distinguish unwanted terminal Return from others.
// The terminal Return that started the app won't have a key press event.
static gboolean key_press_event_cb (GtkWidget *widget,
                            GdkEventKey *event,
                                gpointer data)
{
  gboolean *p_key_pressed = data;
  *p_key_pressed = TRUE;
  return FALSE; //keep processing event
}

static gboolean key_release_event_cb (GtkWidget *widget,
                            GdkEventKey *event,
                                gpointer data)
{
  gboolean *p_key_pressed = data;
  // If there's no key-press before this key-release, then it's from starting the app in a terminal
  // So ignore it.
  if (*p_key_pressed & event->keyval == GDK_KEY_Return) {
    GtkWidget *dialog =
      gtk_message_dialog_new (GTK_WINDOW(widget),
          GTK_DIALOG_DESTROY_WITH_PARENT,
          GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE,
          "time is %d", event->time);
    gtk_dialog_run (GTK_DIALOG (dialog));
    gtk_widget_destroy (dialog);
    return TRUE;
  }
  return FALSE; //allow further processing of the keypress if it's not Return
}

static void activate (GtkApplication* app,
                      gpointer        user_data)
{
  GtkWidget *window;
  // create a pointer to a gboolean to track the key press events
  static gboolean key_pressed = FALSE, *p_key_pressed = &key_pressed;

  window = gtk_application_window_new (app);

  g_signal_connect (window, "key-press-event",
                    G_CALLBACK (key_press_event_cb), p_key_pressed); // p_key_pressed will be the "data" in cb function
  g_signal_connect (window, "key-release-event",
                    G_CALLBACK (key_release_event_cb), p_key_pressed); // p_key_pressed will be the "data" in cb function

  gtk_widget_show_all (window);
}

int
main (int    argc,
      char **argv)
{
  GtkApplication *app;
  int status;

  app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
  status = g_application_run (G_APPLICATION (app), 0, NULL);
  g_object_unref (app);

  return status;
}


问:
CSS3 border-image Repeat Not working in Chrome 56
I have an element set with a border image that is not uniform and needs to repeat on edges. Works perfectly in all browsers except Chrome 56.0.2924.76 but fine in newer and older versions of chrome.

In the version that doesn't work, it does repeat on the edges but not where the slices are defined.

(Sorry, I had to blur some content, client site is not live yet)

https://jsfiddle.net/np1kmsut/1/

.main-content {
  background: url('../images/texture-bg-light.jpg');
  border-style: solid;
  border-width: 69px 74px 24px 74px;
  -moz-border-image: url(http://10poundgorilla.com/-temp/sign-border-mobile.jpg) 69 74 24 74 repeat;
  -webkit-border-image: url(http://10poundgorilla.com/-temp/sign-border-mobile.jpg) 69 74 24 74 repeat;
  -o-border-image: url(http://10poundgorilla.com/-temp/sign-border-mobile.jpg) 69 74 24 74 repeat;
  border-image: url(http://10poundgorilla.com/-temp/sign-border-mobile.jpg) 69 74 24 74 repeat;

  margin: 0 2rem 256px 2rem;
  padding: 3.3rem 0 0 0;
  position: relative;
  text-align: center;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main-content">
<h1>Testing</h1>
</div></code>```

答:
A quick-n-dirty solution you may have already tried would be setting the border-image-repeat property to stretch. Of course it looks...stretched.

Otherwise, the problem has to do with your image's dimensions and their interplay with the border-image slices. Use a square image (I used 250px x 250px) and you should be all set.

Fiddle

I hope this helps!

Body:
I have an element set with a border image that is not uniform and needs to repeat on edges. Works perfectly in all browsers except Chrome 56.0.2924.76 but fine in newer and older versions of chrome.

In the version that doesn't work, it does repeat on the edges but not where the slices are defined.

(Sorry, I had to blur some content, client site is not live yet)

https://jsfiddle.net/np1kmsut/1/

.main-content {
  background: url('../images/texture-bg-light.jpg');
  border-style: solid;
  border-width: 69px 74px 24px 74px;
  -moz-border-image: url(http://10poundgorilla.com/-temp/sign-border-mobile.jpg) 69 74 24 74 repeat;
  -webkit-border-image: url(http://10poundgorilla.com/-temp/sign-border-mobile.jpg) 69 74 24 74 repeat;
  -o-border-image: url(http://10poundgorilla.com/-temp/sign-border-mobile.jpg) 69 74 24 74 repeat;
  border-image: url(http://10poundgorilla.com/-temp/sign-border-mobile.jpg) 69 74 24 74 repeat;

  margin: 0 2rem 256px 2rem;
  padding: 3.3rem 0 0 0;
  position: relative;
  text-align: center;
 }

Testing


问:
node.js script works off command line but not from browser?
I launched and amazon ec2 instance running ubuntu 12.04

I then followed the instructions to install node.js from here http://howtonode.org/how-to-install-nodejs

```<code>sudo apt-get install g++ curl libssl-dev apache2-utils
sudo apt-get install git-core

git clone git://github.com/ry/node.git
cd node
./configure
make
sudo make install
</code>```

I then used the example code to make hello.js

```<code>var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Node.js\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
</code>```

I then ran hello.js

```<code>/var/www$ node hello.js
Server running at http://127.0.0.1:8124/
</code>```

However, when I try to access this from the url, with http://ec2-***.compute-1.amazonaws.com:8124/ I get an error page from my browser.

Any advice on how to get it to show up in the browser?

EDIT
I'm still encountering this problem after changing the above line of code

```<code>}).listen(8124, "127.0.0.1");
</code>```

to this

```<code>}).listen(8124);
</code>```

答: I also had same issue, Uninstalling skype worked for me, You can also search for some setting which force skype to move to some other port.</p>

Body:
I launched and amazon ec2 instance running ubuntu 12.04

I then followed the instructions to install node.js from here http://howtonode.org/how-to-install-nodejs

sudo apt-get install g++ curl libssl-dev apache2-utils
sudo apt-get install git-core

git clone git://github.com/ry/node.git
cd node
./configure
make
sudo make install

I then used the example code to make hello.js

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Node.js\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

I then ran hello.js

/var/www$ node hello.js
Server running at http://127.0.0.1:8124/

However, when I try to access this from the url, with http://ec2-***.compute-1.amazonaws.com:8124/ I get an error page from my browser.

Any advice on how to get it to show up in the browser?

EDIT
I'm still encountering this problem after changing the above line of code

}).listen(8124, "127.0.0.1");

to this

}).listen(8124);


问:
How to integrate Graph Engine with C# application
An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
The type initializer for 'Trinity.Global' threw an exception.</p>

答:
I fixed this to change setting
Tool-Option --   Project and solution-- Web Projects--checked checkbox use the 64 bit version of IIS Express for web site and project
    enter code here

And
able to Trininty Dll integrate with my WebAPI (Odata) application


答:
You need to use ++x in place of x++.  The x++ initially evaluates to 0 (but increments x to 1), and 0 is false, so the action is not taken; nothing is printed for the first line.

When you initialize x to -1, the first line is printed because x++ evaluates to -1 which is true; the second is skipped because x is 0, etc.

You don't need the BEGIN block.  Variables are auto-vivified with zero (or the empty string) as the value.  And in fact you don't need to trigger the printing based on whether x is zero or not; you simply want to always print an incremented value of x.

So, on a Mac (Unix-like) system, I can run:

```<code>$ gawk "-F" ";" '{print $0,$1";"++x}' file.in
file.log;2000 file.log;1
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4
$
</code>```

Translated to VMS conventions, that would be:

```<code>gawk "-F" ";" "{print $0,$1"";""++x}" file.in
</code>```

Title: AWK - error in script with count variable OR error in AWK Implementation / version?

Body:
Awk version: GNU Awk 3.1.1

Platform: OpenVMS 8.4-L1

Awk knowledge: limited

Script (Awk one liner).
NOTE: OpenVMS parameter parsing requires quotes

gawk "-F" ";" "BEGIN {x = 0} ; x++ {print $0,$1"";""x}" in.file > out.file

**in.file**
file.log;2000
file.log;1999
file.log;1998
file.log;1997

**out.file**
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4

I wanted the following instead

file.log;2000 file.log;1
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4

If I change the awk command above to: ...{x = -1}... I get

**out.file**
file.log;2000 file.log;0
file.log;1998 file.log;2
file.log;1997 file.log;3

What I am wondering is

Can someone else using a different platform test this to see if it produces the same output?

Could it be the awk version I am running that is at fault OR is there something wrong with my awk script that I am not understanding

It really seems to me that it should produce a file.log;1999 file.log;1 line but it doesn't. I'm at a loss and need some pointers / awk education

Thanks in advance :-)

Body:
You need to use ++x in place of x++.  The x++ initially evaluates to 0 (but increments x to 1), and 0 is false, so the action is not taken; nothing is printed for the first line.

When you initialize x to -1, the first line is printed because x++ evaluates to -1 which is true; the second is skipped because x is 0, etc.

You don't need the BEGIN block.  Variables are auto-vivified with zero (or the empty string) as the value.  And in fact you don't need to trigger the printing based on whether x is zero or not; you simply want to always print an incremented value of x.

So, on a Mac (Unix-like) system, I can run:

$ gawk "-F" ";" '{print $0,$1";"++x}' file.in
file.log;2000 file.log;1
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4
$

Translated to VMS conventions, that would be:

gawk "-F" ";" "{print $0,$1"";""++x}" file.in


问:
MySQL CONCAT add comma after
I am struggling to get comma after value but this query is adding before value

```<code>ipaddress = CONCAT(IFNULL(ipaddress,''), ',$ipaddress')
</code>```

The field's default value is NULL

Even I have tried this too but result is the same. Adding comma before not after.

```<code>ipaddress = CONCAT(IFNULL(ipaddress,''), ',', '$ipaddress')
</code>```

答:
Use the CONCAT_WS function. It inserts the separator between items, but ignores null items.

```<code>ipaddress = CONCAT_WS(',', ipaddress, '$ipaddress')
</code>```

So if ipaddress is initially null, it will be ignored, so this won't put the separator between it and the added $ipaddress value.

However, the fact that you need to do this suggests that you're putting a comma-separated list into a SQL column. This is very poor design. You should normalize your schema, and move this to a separate table with a separate row for each value, and a foreign key relating back to this table.

Title: MySQL CONCAT add comma after

Body:
I am struggling to get comma after value but this query is adding before value

ipaddress = CONCAT(IFNULL(ipaddress,''), ',$ipaddress')

The field's default value is NULL

Even I have tried this too but result is the same. Adding comma before not after.

ipaddress = CONCAT(IFNULL(ipaddress,''), ',', '$ipaddress')

Body:
Use the CONCAT_WS function. It inserts the separator between items, but ignores null items.

ipaddress = CONCAT_WS(',', ipaddress, '$ipaddress')

So if ipaddress is initially null, it will be ignored, so this won't put the separator between it and the added $ipaddress value.

However, the fact that you need to do this suggests that you're putting a comma-separated list into a SQL column. This is very poor design. You should normalize your schema, and move this to a separate table with a separate row for each value, and a foreign key relating back to this table.


问:
Use MS Access form on a mobile device
I'm going to a robotics competition (FRC) in which we're supposed to "scout" other robots' and see how they perform. My database consists of the number of points they get for each category. I made a form to enter in the data. There are six teams, and I wanted to use six android phones or tablets for data entry.

Is there a way to open the form and enter data in on a mobile device, and then transfer the records to a master computer?

P.S. At the competition we would not have an internet connection, so the only data transfer methods would be USB, Bluetooth, or LAN.

Thanks

EDIT: I figured it out. Instead of using an access form, i'm creating an android app that simply allows you to enter the data in, and export the data as a csv to use in a database. I'll try and make it work.

答: The easiest way to "run" MS Access application on any iOS, Android or WinCE device is using remote desktop. Enterprise solutions like Citrix would be better. You will need a server in local network, which can support the terminal clients and install on each device RDP terminal client or Citrix client. Access application in fact works on the server, mobile device shows the screen and allows to interact with application.</p>

Title: Use MS Access form on a mobile device


问:
Splitting data set into training and testing sets on recommender systems
I have implemented a recommender system based upon matrix factorization techniques. I want to evaluate it.

I want to use 10-fold-cross validation with All-but-one protocol (https://ai2-s2-pdfs.s3.amazonaws.com/0fcc/45600283abca12ea2f422e3fb2575f4c7fc0.pdf).

My data set has the following structure:

```<code>user_id,item_id,rating
1,1,2
1,2,5
1,3,0
2,1,5
...
</code>```

It's confusing for me to think how the data is going to be splitted, because I can't put some triples (user,item,rating) in the testing set. For example, if I select the triple (2,1,5) to the testing set and this is the only rating user 2 has made, there won't be any other information about this user and the trained model won't predict any values for him.

Considering this scenario, how should I do the splitting?

答:
collaborative filtering (matrix factorization) can't have a good recommendation for an unseen user with no feedback. Nevertheless, an evaluation should consider this case and take it into account.

One thing you can do is to report performance for all test users, just test users with some feedback and just unseen users with no feedback.

So I'd say keep the test, train split random but evaluate separately for unseen users.

More info here.

Body:
I have implemented a recommender system based upon matrix factorization techniques. I want to evaluate it.

I want to use 10-fold-cross validation with All-but-one protocol (https://ai2-s2-pdfs.s3.amazonaws.com/0fcc/45600283abca12ea2f422e3fb2575f4c7fc0.pdf).

My data set has the following structure:

user_id,item_id,rating
1,1,2
1,2,5
1,3,0
2,1,5
...

It's confusing for me to think how the data is going to be splitted, because I can't put some triples (user,item,rating) in the testing set. For example, if I select the triple (2,1,5) to the testing set and this is the only rating user 2 has made, there won't be any other information about this user and the trained model won't predict any values for him.

Considering this scenario, how should I do the splitting?


问:
Materialize css select box broken with large number of options
I am using Materialize select box and I have around 50000 options to show. How can I achieve virtual scrolling for select box?
When I am simply adding 50000 options then page is not responsive as there are so many options in DOM at a time.

Any help is appreciated. Thanks.

答:
If you add such number of elements to HTML, yes, it will be very slow. So I think the best would be to change the input field type. You could try:

An autocomplete field, which will show some results after entering few characters

Your custom selector (probably some popup dialog) with a possibility to search for the value user wants. For example if searching for a car model, you would have a vendor select box and a year range. Then you can display a list of matching options to pick.

Add pagination to the list of options. But this is not used often.


问:
Bootstrap place all div in single line
I am trying to place userlist in left side and searchbox and button in right side in same line

```<code><div class="row">
  <div class="col-md-4">
    <div class="user-title">User List-5</div>
  </div>
  <div class="col-md-8">
    <div class="input-group user-search-box col-md-6">
      <input type="text" class="form-control" placeholder="Search" aria-describedby="basic-addon2">
      <span class="input-group-addon input-search-custom-adon" ><i class="fa fa-search" aria-hidden="true"></i></span>
    </div>
    <div class="add-new-user col-md-6">
      <a class="btn  add-new-user" href="#" role="button">ADD NEW USER</a>
    </div>
  </div>
</div>
</code>```

i have tried by using float:left then add button will show first instead of search box
can any one help me

答:
All you need to do is float the two elements next to each other with float: left on the search box, and float: right on the button. If you don't want to use any CSS, you can also use the the built-in Bootstrap helper classes pull-left and pull-right. Simply set pull-left on the search box, and pull-right on the button:

```<code><div class="row">
  <div class="col-md-4">
    <div class="user-title">User List-5</div>
  </div>
  <div class="col-md-8">
    <div class="input-group user-search-box col-md-6 pull-left">
      <input type="text" class="form-control" placeholder="Search" aria-describedby="basic-addon2">
      <span class="input-group-addon input-search-custom-adon" ><i class="fa fa-search" aria-hidden="true"></i></span>
    </div>
    <div class="add-new-user col-md-6 pull-right">
      <a class="btn  add-new-user" href="#" role="button">ADD NEW USER</a>
    </div>
  </div>
</div>
</code>```

I've created a BootPly showing this here.

Hope this helps! :)

Title: Bootstrap place all div in single line

Body:
I am trying to place userlist in left side and searchbox and button in right side in same line

User List-5

      <input type="text" class="form-control" placeholder="Search" aria-describedby="basic-addon2">

      ADD NEW USER

i have tried by using float:left then add button will show first instead of search box
can any one help me

Body:
All you need to do is float the two elements next to each other with float: left on the search box, and float: right on the button. If you don't want to use any CSS, you can also use the the built-in Bootstrap helper classes pull-left and pull-right. Simply set pull-left on the search box, and pull-right on the button:

<div class="row">
  <div class="col-md-4">
    <div class="user-title">User List-5</div>
  </div>
  <div class="col-md-8">
    <div class="input-group user-search-box col-md-6 pull-left">
      <input type="text" class="form-control" placeholder="Search" aria-describedby="basic-addon2">
      <span class="input-group-addon input-search-custom-adon" ><i class="fa fa-search" aria-hidden="true"></i></span>
    </div>
    <div class="add-new-user col-md-6 pull-right">
      <a class="btn  add-new-user" href="#" role="button">ADD NEW USER</a>
    </div>
  </div>
</div>

I've created a BootPly showing this here.

Hope this helps! :)


问:
Importing tcomb lib in Angular 2 / webpack app gives undefined
Importing tcomb gives undefined:

```<code>import t from 'tcomb';
console.log(t); // undefined

// So this won't work
t.assert(t.Number.is(colorString), 'colorString is invalid argument');
</code>```

However I got it working like this, which actually I like more:

```<code>import {assert, Number} from 'tcomb';
assert(Number.is(colorString), 'colorString is invalid argument');
</code>```

Importing all as t returns just the assert() method not the full object

```<code>import * as t from 'tcomb';
</code>```

I'm using a pretty standard setup with webpack-dev-server, angular 2, typescript and HMR. All libs so far load ok. The project is already a few months old.

Any idea on what is happening here? Why t is undefined?

Note: I'm using runtime check even if I have TS types all over the place because some services methods could still receive the wrong arguments at runtime. As a sidenote, tcomb seems fine to me, but just to learn, is there a better option than tcomb?

答:
Have you tried var t = require('tcomb')?
Perhaps something to do with the es6 import statement which is not working?

Body:
Importing tcomb gives undefined:

import t from 'tcomb';
console.log(t); // undefined

// So this won't work
t.assert(t.Number.is(colorString), 'colorString is invalid argument');

However I got it working like this, which actually I like more:

import {assert, Number} from 'tcomb';
assert(Number.is(colorString), 'colorString is invalid argument');

Importing all as t returns just the assert() method not the full object

import * as t from 'tcomb';

I'm using a pretty standard setup with webpack-dev-server, angular 2, typescript and HMR. All libs so far load ok. The project is already a few months old.

Any idea on what is happening here? Why t is undefined?

Note: I'm using runtime check even if I have TS types all over the place because some services methods could still receive the wrong arguments at runtime. As a sidenote, tcomb seems fine to me, but just to learn, is there a better option than tcomb?


问:
Detect large files being included while compiling
I'm using armcc/gcc for a code base that contains large header files (>20MB hardware CSR files). I want to be able to detect any file that includes this large header file, since I'm trying to root-cause my super-slow build.

Is there an option I could use in one of these compilers to warn me about the size of a file (including the size of the headers that it might be including)?

答:
You can put to your large header file:

```<code>#warning This large header is included
</code>```

Then in every translation unit you'll get a compiller (GCC) warning message pointing you to what source file has that header included (directly or indirectly).

Body:
You can put to your large header file:

#warning This large header is included

Then in every translation unit you'll get a compiller (GCC) warning message pointing you to what source file has that header included (directly or indirectly).


问:
System design: whether to normalize the departments or not
I'm working with two consultants in one project. The thing is we reached a point where both of them cannot get into an agreement and each offer a different approach.

The thing is we have a store with four departments and we want to find the best approach for working with all of them in the same database.

Each department sell different products: Cars, Boats, Jetskies and Motorbikes.

When the data is inserted or updated in each department there are some triggers to be fires so different workflows will begin, when adding a new car there are certain requirements that needs to be checked as well as the details of the car that are completely different than a boat. Also, regarding the data there are not many fields there are in common, I would say so far only the brand, color, model and year, everything else is specific for each deparment due to the different products and how they work with them..

Consultant one says:

Create one table for all the departments and use a column to identify what department the row belongs to, this way you will have only one trigger and inside the trigger you will then call the function/mehod you need for each record type.

Reason: you only have one table (with over 200 fields) and one trigger, is easier to maintain. Also if you need to report you just need to query one table and filter based on the record type. If you need to report for all the items you don't need to have multiple joins.

Consultant two says:

Create one table for each deparment and a trigger for each table.

Reason: you will have smaller tables (aprox 50 fields each) and is more flexible and you have it all separated. If you want to report you need to join the tables as you want to include data from different places.

I see the advantages of having everything in one place but if I want to expand or change anything I have the feeling I will bre creating a beast table as the data grows.

On the other side keep it separated look more appealing but will need to setup everything for each different table.

What would you say is the best approach?

答:
I'll say one

These are all Products, It doesn't matter that its a Bike or a Car.  You can control the fields and the object by RecordTypes and Page layouts and that will save you from having 4 Objects, which means potentially 8 new classes(if it follows my pattern it could be up to 20+) + all of the workflow rules and validation rules across the these new objects, it will be very hard to maintain a structure that has 4 objects but are all the same thing.. Tracking Products.

Down the road if you decide to add a new product such as planes, it will be very easy to add a plane to this object and the code will be able to pick up from there if needed.  You will definitely need Record Types to manage each Product.  The trigger code shouldn't be an issue if the consultants are building it properly meaning a trigger should never have any business logic so as long as that is followed all of the code will be maintainable


问:
click on TableViewCell to open profile view of current user
I am using firebase database and have a table view showing name, age, location, and image of user at index path.row. How would I go about showing another view when the cell is clicked to the users profile with more information and photos of the user. here is the code for my tableView.

```<code> override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return userList.count

}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "prefCell", for: indexPath) as! SFPTableViewCell

      let user = userList[indexPath.row]

    cell.name.text = userList[indexPath.row].name
    cell.location.text = userList[indexPath.row].location

    if let imageURL = user.image {

        cell.imageOne.loadImageUsingCacheWithUrlString(urlString: imageURL)
    }
          return cell
}

    }
</code>```

答:
Just used UITableViewDelegate method "didSelectRowAtIndexPath" and send image to other view controller with its indexPath

```<code> override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let sb = UIStoryboard(name: "Main", bundle: nil)
        let detailVC = sb.instantiateViewController(withIdentifier: "ImageVC") as! DetailViewController
        detailVC.strImage  = self.arrImage[indexPath.row]
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
</code>```

In DetailViewController take one variable

```<code>var strImage : String = ""
</code>```

and assgin this variable to UIImagView

```<code> imgView.image = UIImage(named: strImage)
</code>```

Body:
I am using firebase database and have a table view showing name, age, location, and image of user at index path.row. How would I go about showing another view when the cell is clicked to the users profile with more information and photos of the user. here is the code for my tableView.

 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return userList.count

}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "prefCell", for: indexPath) as! SFPTableViewCell

      let user = userList[indexPath.row]

    cell.name.text = userList[indexPath.row].name
    cell.location.text = userList[indexPath.row].location

    if let imageURL = user.image {

        cell.imageOne.loadImageUsingCacheWithUrlString(urlString: imageURL)
    }
          return cell
}

    }

Body:
Just used UITableViewDelegate method "didSelectRowAtIndexPath" and send image to other view controller with its indexPath

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let sb = UIStoryboard(name: "Main", bundle: nil)
        let detailVC = sb.instantiateViewController(withIdentifier: "ImageVC") as! DetailViewController
        detailVC.strImage  = self.arrImage[indexPath.row]
        self.navigationController?.pushViewController(detailVC, animated: true)
    }

In DetailViewController take one variable

var strImage : String = ""

and assgin this variable to UIImagView

 imgView.image = UIImage(named: strImage)


问:
jsRender not rendering values
I've been at this for hours, and I still haven't figured this out.  Any help is greatly appreciated.

I have this template

```<code><script id="TwoLevelsDeepTbodyTemplate" type="text/x-jsrender">
    <tbody class="TwoLevelsDeep">
        {{for #data}}
        <tr class="ClassificationTwoLevelsDeep">
            <td colspan="2">┖ <span class="Type">{{:title}}</span></td>
            <td class="CusClassificationInput">
                <span class="Editable hidden"><input type="text" value="{{:percentageOfBusiness}}" maxlength="3">%</span>
                <span class="CustomerTypeValue">
                  {{if percentageOfBusiness}}
                      {{:percentageOfBusiness}}
                  {{else}}
                      -
                  {{/if}}
                </span>
            </td>
        </tr>
        {{/for}}
    </tbody>
</script>
</code>```

Method which gathers data and fills template:

```<code>function getGrandChildrenTemplate(paryGrandChildren) {
    let jsonObj = [];
    $.each(paryGrandChildren, function (i, gc) {
        let item = {};
        item['title'] = gc.Text;
        item['percentageOfBusiness'] = gc.Data;
        jsonObj.push(item);
    });
    let data = JSON.stringify(jsonObj);
    let tmpl = $.templates('#TwoLevelsDeepTbodyTemplate');
    let html = tmpl.render(data);
    console.log(data);
    console.log(html);
    return html;
};
</code>```

When I check the log, the template looks like

```<code><tbody class="TwoLevelsDeep">
    <tr class="BCClassificationTwoLevelsDeep">
        <td colspan="2">┖ <span class="Type"></span></td>
        <td class="CusClassificationInput">
            <span class="Editable hidden"><input type="text" value="" maxlength="3">%</span>
            <span class="CustomerTypeValue">-</span>
        </td>
    </tr>
</tbody>
</code>```

The stringified JSON looks like:

```<code>[{"title":"Single Family","percentageOfBusiness":""},{"title":"Multi-Family","percentageOfBusiness":""}]
</code>```

Notice there is nothing in the template where the values should be filled.  Also, there's only one TR when there should be 2 in this example.  I'm obviously doing something wrong, but I can't figure out what.  My understanding of the {{for #data}} is that it will (in this example) create a TR for every object and fill in the values based on the keys.  Is this not correct?

答:
2 Changes

Use {{for data}} for iteration
ex

```<code> <script id="TwoLevelsDeepTbodyTemplate" type="text/x-jsrender">
  <tbody class="TwoLevelsDeep">
    {{for data}}
    <tr class="ClassificationTwoLevelsDeep">
      <td colspan="2">┖ <span class="Type">{{:title}}</span></td>
      <td class="CusClassificationInput">
        <span class="Editable hidden"><input type="text" value="{{:percentageOfBusiness}}" maxlength="3">%</span>
        <span class="CustomerTypeValue">
                  {{if percentageOfBusiness}}
                      {{:percentageOfBusiness}}
                  {{else}}
                      -
                  {{/if}}
                </span>
      </td>
    </tr>
    {{/for}}
  </tbody>
</script>
</code>```

No need to stringify the json data

```<code>function getGrandChildrenTemplate(paryGrandChildren) {
  let jsonObj = [];
  $.each(paryGrandChildren, function(i, gc) {
    let item = {};
    item['title'] = gc.Text;
    item['percentageOfBusiness'] = gc.Data;
    jsonObj.push(item);
  });

  let tmpl = $.templates('#TwoLevelsDeepTbodyTemplate');
  let html = tmpl.render({
    data: jsonObj
  });
  console.log(html);
  return html;
};
</code>```

Title: jsRender not rendering values

Body:
I've been at this for hours, and I still haven't figured this out.  Any help is greatly appreciated.

I have this template

Method which gathers data and fills template:

function getGrandChildrenTemplate(paryGrandChildren) {
    let jsonObj = [];
    $.each(paryGrandChildren, function (i, gc) {
        let item = {};
        item['title'] = gc.Text;
        item['percentageOfBusiness'] = gc.Data;
        jsonObj.push(item);
    });
    let data = JSON.stringify(jsonObj);
    let tmpl = $.templates('#TwoLevelsDeepTbodyTemplate');
    let html = tmpl.render(data);
    console.log(data);
    console.log(html);
    return html;
};

When I check the log, the template looks like

        ┖

            <input type="text" value="" maxlength="3">%
            -

The stringified JSON looks like:

[{"title":"Single Family","percentageOfBusiness":""},{"title":"Multi-Family","percentageOfBusiness":""}]

Notice there is nothing in the template where the values should be filled.  Also, there's only one TR when there should be 2 in this example.  I'm obviously doing something wrong, but I can't figure out what.  My understanding of the {{for #data}} is that it will (in this example) create a TR for every object and fill in the values based on the keys.  Is this not correct?

Body:
2 Changes

Use {{for data}} for iteration
ex

 <script id="TwoLevelsDeepTbodyTemplate" type="text/x-jsrender">
  <tbody class="TwoLevelsDeep">
    {{for data}}
    <tr class="ClassificationTwoLevelsDeep">
      <td colspan="2">┖&nbsp;<span class="Type">{{:title}}</span></td>
      <td class="CusClassificationInput">
        <span class="Editable hidden"><input type="text" value="{{:percentageOfBusiness}}" maxlength="3">%</span>
        <span class="CustomerTypeValue">
                  {{if percentageOfBusiness}}
                      {{:percentageOfBusiness}}
                  {{else}}
                      -
                  {{/if}}
                </span>
      </td>
    </tr>
    {{/for}}
  </tbody>
</script>

No need to stringify the json data

function getGrandChildrenTemplate(paryGrandChildren) {
  let jsonObj = [];
  $.each(paryGrandChildren, function(i, gc) {
    let item = {};
    item['title'] = gc.Text;
    item['percentageOfBusiness'] = gc.Data;
    jsonObj.push(item);
  });

  let tmpl = $.templates('#TwoLevelsDeepTbodyTemplate');
  let html = tmpl.render({
    data: jsonObj
  });
  console.log(html);
  return html;
};