问:
Join a CTE to a main query
How to I join a CTE to a main query?

(ps: Thank you again - this community is brilliant)

```<code> With tempCTE1locws ([1stchargeableweights], movementref, lastdate)
as
(Select
SUM(c.[Chargeable Weight]) AS [1stchargeableweights],
mm.MovementRef [movementref],
MAX (ts.systemstamp) [lastdate]

FROM      dbo.whsConsignment wc
INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
inner join dbo.movMovement mm on mm.MovementID = m.MovementID
INNER JOIN dbo.whsHeader wh ON wh.WhsHeaderID = wc.whsHeaderID
AND wc.whsHeaderID = wh.WhsHeaderID
AND wc.StatusCode = 'NL'
AND c.[Service Type] = 'F'
AND ts.SlackNoSlack = 'slack'
or ts.slacknoslack like 'slack - tripped%'
WHERE wh.ArrDepDate BETWEEN @StartDate AND @EndDate
GROUP by mm.MovementRef),
</code>```

I would like to join this CTE to dbo.movmovement on movementref. However, writing it like

```<code>From dbo.movmovement m
Inner join dbo.tempCTE1locws locws on locws.movementref = m.movementref
</code>```

doesn't work at all.

答:
So there's an excellent SO answer on this topic that you should go through.
Multiple CTE in single query

Quoting from accepted answer

Use the key word WITH once at the top and if any of your Common Table
  Expressions (CTE) are recursive (rCTE) you have to add the keyword
  RECURSIVE at the top also, even if not all CTEs are recursive:

```<code>WITH RECURSIVE
  cte1 AS (...)  -- can still be non-recursive
, cte2 AS (SELECT ...
           UNION ALL
           SELECT ...)  -- recursive term
, cte3 AS (...)

SELECT ... FROM cte3 WHERE ...
</code>```

This is the reason why you need , in CTE definition.

Your error is coming up because you have a typo.

Incorrect syntax near 'tempCTE1locwns'. that is the error I am getting

See the extra n in CTE name; it should be tempCTE1locwns and not tempCTE1locwns

Title: Join a CTE to a main query

Body:
How to I join a CTE to a main query?

(ps: Thank you again - this community is brilliant)

 With tempCTE1locws ([1stchargeableweights], movementref, lastdate)
as
(Select
SUM(c.[Chargeable Weight]) AS [1stchargeableweights],
mm.MovementRef [movementref],
MAX (ts.systemstamp) [lastdate]

FROM      dbo.whsConsignment wc
INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
inner join dbo.movMovement mm on mm.MovementID = m.MovementID
INNER JOIN dbo.whsHeader wh ON wh.WhsHeaderID = wc.whsHeaderID
AND wc.whsHeaderID = wh.WhsHeaderID
AND wc.StatusCode = 'NL'
AND c.[Service Type] = 'F'
AND ts.SlackNoSlack = 'slack'
or ts.slacknoslack like 'slack - tripped%'
WHERE wh.ArrDepDate BETWEEN @StartDate AND @EndDate
GROUP by mm.MovementRef),

I would like to join this CTE to dbo.movmovement on movementref. However, writing it like

From dbo.movmovement m
Inner join dbo.tempCTE1locws locws on locws.movementref = m.movementref

doesn't work at all.

Body:
So there's an excellent SO answer on this topic that you should go through.
Multiple CTE in single query

Quoting from accepted answer

Use the key word WITH once at the top and if any of your Common Table
  Expressions (CTE) are recursive (rCTE) you have to add the keyword
  RECURSIVE at the top also, even if not all CTEs are recursive:

WITH RECURSIVE
  cte1 AS (...)  -- can still be non-recursive
, cte2 AS (SELECT ...
           UNION ALL
           SELECT ...)  -- recursive term
, cte3 AS (...)

SELECT ... FROM cte3 WHERE ...

This is the reason why you need , in CTE definition.

Your error is coming up because you have a typo.

Incorrect syntax near 'tempCTE1locwns'. that is the error I am getting

See the extra n in CTE name; it should be tempCTE1locwns and not tempCTE1locwns


来源: stackexchange

问:
Quickly processing a string
I have an input string which I will use to build an output string. The output string is much the same as the input string but has some slight changes along the way, depending on if we hit a certain characters in the input. The code looks like this

```<code>outputTree(std::ostream& o, const char* input) {
    size_t len = strlen(input);
    int indent = 0;
    string output;

    for(size_t i = 0; i < input_len; i++) {
        if(input[i] == '(') {
            indent++;
            output.append(1,'\n');
            for(int j = 0; j < indent; j++) {
                output.append("    ");
            }
        }
        if(input[i] == ')') {
            output.append(1,'\n');
            for(int j = 0; j < indent; j++) {
                output.append("    ");
            }
            indent--;
        }
        output.append(1,input[i]);
    }
    o << output << endl;
}
</code>```

While this works, doing it character by character is pretty slow. Can anyone recommend some better approaches to this (pref with standard features, ie no boost)?

答:
I am not sure what "pretty slow" means and how much improvement you expect. The algorithm you have is an efficient O(N) algorithm. The only thing you can do is trying to optimise individual operations, but then again I am not sure what kind of optimisations is the compiler doing.

One thing you could do is get rid of the inner loops that write the indentation string as many times is needed by the level of indentation (your indent variable). So instead of writing a newline and then execute the for loop, you can perform just one append that has the newline concatenated with the right amount of indentation. If you can set a limit to the depth of your indentation (say 10 levels deep) you can then create an array that has all 10 different indentation strings (all strings starting with a newline).

Another thing you can try is to use std::string::find to find the occurrences of '(' and ')' and do string copies up to these markers, instead of copying character by character.

Finally, note that your code might not behave as you want it, if the input is not as expected. Notice what will happen if you first encounter a ')' without having a corresponding '('.

ContentLicense: CC BY-SA 3.0

Title: Quickly processing a string

Body:
I have an input string which I will use to build an output string. The output string is much the same as the input string but has some slight changes along the way, depending on if we hit a certain characters in the input. The code looks like this

outputTree(std::ostream& o, const char* input) {
    size_t len = strlen(input);
    int indent = 0;
    string output;

    for(size_t i = 0; i < input_len; i++) {
        if(input[i] == '(') {
            indent++;
            output.append(1,'\n');
            for(int j = 0; j < indent; j++) {
                output.append("    ");
            }
        }
        if(input[i] == ')') {
            output.append(1,'\n');
            for(int j = 0; j < indent; j++) {
                output.append("    ");
            }
            indent--;
        }
        output.append(1,input[i]);
    }
    o << output << endl;
}

While this works, doing it character by character is pretty slow. Can anyone recommend some better approaches to this (pref with standard features, ie no boost)?


问:
Using jq to update objects within a JSON document if the value corresponding to a given key starts with a specified string
I have the given JSON and want to change the id value of all elements, which starts with test in the name element:

```<code>{
    "other-value": "some-id",
    "values": [
        {
            "name": "test-2017-12-01",
            "id": "1"

        },
        {
            "name": "othert",
            "id": "2"
        }

    ]
}
</code>```

The following jq commands works jqplay

```<code>jq (.values[] | select(.name == "test-afs").id) |= "NEWID"
</code>```

But when I try it with startswith it stops working, what am I missing? jqplay

```<code>(.values[] | select(.name | startswith("test")).id) |= "NEWID"
</code>```

jq: error (at :14): Invalid path expression near attempt to access element "id" of {"name":"test-afs","id":"id"}
  exit status 5

答:
You can also use map, like this:

```<code>jq '(.values)|=(map((if .name|startswith("test") then .id="NEWID"  else . end)))' file
</code>```

Output:

```<code>{
  "other-value": "some-id",
  "values": [
    {
      "name": "test-2017-12-01",
      "id": "NEWID"
    },
    {
      "name": "othert",
      "id": "2"
    }
  ]
}
</code>```

Body:
I have the given JSON and want to change the id value of all elements, which starts with test in the name element:

{
    "other-value": "some-id",
    "values": [
        {
            "name": "test-2017-12-01",
            "id": "1"

        },
        {
            "name": "othert",
            "id": "2"
        }

    ]
}

The following jq commands works jqplay

jq (.values[] | select(.name == "test-afs").id) |= "NEWID"

But when I try it with startswith it stops working, what am I missing? jqplay

(.values[] | select(.name | startswith("test")).id) |= "NEWID"

jq: error (at :14): Invalid path expression near attempt to access element "id" of {"name":"test-afs","id":"id"}
  exit status 5

Body:
You can also use map, like this:

jq '(.values)|=(map((if .name|startswith("test") then .id="NEWID"  else . end)))' file

Output:

{
  "other-value": "some-id",
  "values": [
    {
      "name": "test-2017-12-01",
      "id": "NEWID"
    },
    {
      "name": "othert",
      "id": "2"
    }
  ]
}


问:
CSS/HTML5: How to adjust div tag height equal to browser window's current height?
I want the height of my div tag exactly equal to the height of the browser's window. So if you resize the browser the  should adjust automatically.
So what should I set my height equal to in CSS.

I have tried

```<code>.class {
  height: 100%;
}
</code>```

Doesn't work.

em, rem, vh, wh apparently only work with the font.

If I however, hard-code the body tag to some amount of pixels, then the percentage works for the children tags but this is not dynamic.

What I want: Just as I am viewing this stack page in my browser. I wish when I resize the browser I still get the same amount of page viewership, only resized for the new size (responsive).

Thanks.

答:
Solution 1

You can try height :100vh to achieve this. Check below snippet:

body{
  margin: 0;
}
.windowHeight{
  height: 100vh;
  display: block;
  background: #000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="windowHeight">

</div></code>```

Solution 2

Another way to do this by jQuery. Check below snippet:

$('.windowHeight').css('height', $(window).height());```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
  margin:0;
}
.windowHeight{
  background:#000;
}</code>```

```

Body:
I want the height of my div tag exactly equal to the height of the browser's window. So if you resize the browser the  should adjust automatically.
So what should I set my height equal to in CSS.

I have tried

.class {
  height: 100%;
}

Doesn't work.

em, rem, vh, wh apparently only work with the font.

If I however, hard-code the body tag to some amount of pixels, then the percentage works for the children tags but this is not dynamic.

What I want: Just as I am viewing this stack page in my browser. I wish when I resize the browser I still get the same amount of page viewership, only resized for the new size (responsive).

Thanks.

Body:
Solution 1

You can try height :100vh to achieve this. Check below snippet:

body{
  margin: 0;
}
.windowHeight{
  height: 100vh;
  display: block;
  background: #000;
}

<div class="windowHeight">

</div>

Solution 2

Another way to do this by jQuery. Check below snippet:

$('.windowHeight').css('height', $(window).height());

body{
  margin:0;
}
.windowHeight{
  background:#000;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="windowHeight"></div>


问:
Split a column into separate columns using regex
I have got a single column that includes the information as follows:

```<code>1 x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo
2 x=oljhh88999\ty=lop9876666
3 x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid
</code>```

So, none of the id types has a certain number of occurences in a line.
They are all separated by tab.
I am searching for a way to obtain the IDs for each line as separate columns and have found tstrsplit within data.table but cannot figure out how I can use it with multiple split arguments. Any ideas?

Edit: The expected format is:

```<code>     x1          x2        y1    y2                          z1                  z2
1  abc1000000   NA pqr2000000    NA         olk78fgzu_zuii8999_ikooo            NA
2  oljhh88999   NA lop9876666    NA                               NA            NA
3  frdt876544   NA ztr6u76532   uzrt899963  wertttts_765342_ioooosww  zuuuee_66554422_88uuiiid
</code>```

Note that the id's do not include 'id' in their names. So I updated the example accordingly. The id's may appear a number of times in each line. The format given above is just an example to make the question clearer. In reality, the X type of IDs for example, can have 20 occurences in one line. The number of columns for X will be then the maximum number of appearance of this particular type of ID in a line given the whole dataset. The data is pretty large. We are talking about some 30m lines.

答:
New answer to the updated question

The OP has now specified the expected result and also has updated the sample data set. So, the answer has to be updated accordingly.

The approach below uses data.table as in Jaap's answer but differs as follows

tstrsplit() is only called once to split up all columns,

melt() is used to melt multiple columns resulting in two value columns, one for the ids, one for the pay load values,

for each row, the occurence of each id is numbered consecutively,

the final dcast() is used to rename the columns appropriately.

The code below should work with an arbitrary number of id-value-pairs in each row as it has been requested by the OP:

```<code>library(data.table)   # CRAN version 1.10.4 used
# split input data at "=" and "\t"
splitted <- DT[, tstrsplit(V1, "=|\t")]
# odd numbered columns contain the ids
cols_odd  <- names(splitted)[c(TRUE, FALSE)] # or: seq(1L, ncol(splitted), by = 2L)
# even numbered columns contain the pay load values
cols_even <- names(splitted)[c(FALSE, TRUE)] # or: seq(2L, ncol(splitted), by = 2L)
# add row number before melting, melt multiple columns, remove NA
molten <- melt(splitted[, rn := .I],
               measure.vars = list(cols_odd, cols_even),
               value.name = c("id", "value"), na.rm = TRUE)
# in each row, number the occurences of each id consecutively
molten[, var.count := rowid(id), rn]
# final reshape from long to wide,
# create column names from id and id count per row
# remove rn because no longer needed
dcast(molten, rn ~ id + var.count, sep = "")[, rn := NULL][]
</code>```

results in

```<code>           x1         y1         y2                       z1                        z2
1: abc1000000 pqr2000000         NA olk78fgzu_zuii8999_ikooo                        NA
2: oljhh88999 lop9876666         NA                       NA                        NA
3: frdt876544 ztr6u76532 uzrt899963 wertttts_765342_ioooosww tzuuuee_66554422_88uuiiid
</code>```

In contrast to above result, the result expected by the OP includes an empty x2 column. In case this is really intended by the OP, the missing rows need to be added before  the final dcast(). This is achieved by joining a data.table containing all possible combinations of row numbers, ids and id counts per row as follows:

```<code>   dcast(molten[CJ(rn, id, var.count, unique = TRUE),
             on = .(rn = V1, id = V2, var.count = V3)],
      rn ~ id + var.count, sep = "")[, rn := NULL][]
</code>```

which yields

```<code>           x1 x2         y1         y2                       z1                        z2
1: abc1000000 NA pqr2000000         NA olk78fgzu_zuii8999_ikooo                        NA
2: oljhh88999 NA lop9876666         NA                       NA                        NA
3: frdt876544 NA ztr6u76532 uzrt899963 wertttts_765342_ioooosww tzuuuee_66554422_88uuiiid
</code>```

Data

```<code>library(data.table)
DT <- fread('"x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo"
  "x=oljhh88999\ty=lop9876666"
  "x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid"',
  header=FALSE)
</code>```

Answer to the original question

As the question is entitled Split a column into separate columns using regex and the OP explicitely is asking for ideas on how to use tstrsplit with multiple split arguments all answers focused on splitting the columns.

However, if the OP is only interested to obtain the IDs for each line as separate columns there is a simple solution available:

```<code>stringr::str_extract_all(DT$V1, "\\wid\\d", simplify = TRUE)
#     [,1]   [,2]   [,3]   [,4]   [,5]
#[1,] "xid1" "yid2" "zid3" ""     ""
#[2,] "xid4" "yid5" ""     ""     ""
#[3,] "xid6" "yid7" "yid8" "zid8" "zid9"
</code>```

or in data.table context:

```<code>DT[, data.table(stringr::str_extract_all(V1, "\\wid\\d", simplify = TRUE))]
#     V1   V2   V3   V4   V5
#1: xid1 yid2 zid3
#2: xid4 yid5
#3: xid6 yid7 yid8 zid8 zid9
</code>```

Note that in the third line an ID zid8 has been found which is missing in all other answers. The other answers are looking to split the strings at \t (tab character). It might be that there is a \ missing in row three of the given data set, so the section reads tzid8= instead of \tzid8=.

Data

As provided in the question (including the potential error).

```<code>DT <- fread('"xid1=abc1000000\tyid2=pqr2000000\tzid3=olk78fgzu_zuii8999_ikooo"
"xid4=oljhh88999\tyid5=lop9876666"
"xid6=frdt876544\tyid7=ztr6u76532\tyid8=uzrt899963tzid8=wertttts_765342_ioooosww\tzid9=tzuuuee_66554422_88uuiiid"',
header=FALSE)
</code>```

Body:
I have got a single column that includes the information as follows:

1 x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo
2 x=oljhh88999\ty=lop9876666
3 x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid

So, none of the id types has a certain number of occurences in a line.
They are all separated by tab.
I am searching for a way to obtain the IDs for each line as separate columns and have found tstrsplit within data.table but cannot figure out how I can use it with multiple split arguments. Any ideas?

Edit: The expected format is:

     x1          x2        y1    y2                          z1                  z2
1  abc1000000   NA pqr2000000    NA         olk78fgzu_zuii8999_ikooo            NA
2  oljhh88999   NA lop9876666    NA                               NA            NA
3  frdt876544   NA ztr6u76532   uzrt899963  wertttts_765342_ioooosww  zuuuee_66554422_88uuiiid

Note that the id's do not include 'id' in their names. So I updated the example accordingly. The id's may appear a number of times in each line. The format given above is just an example to make the question clearer. In reality, the X type of IDs for example, can have 20 occurences in one line. The number of columns for X will be then the maximum number of appearance of this particular type of ID in a line given the whole dataset. The data is pretty large. We are talking about some 30m lines.

Body:
New answer to the updated question

The OP has now specified the expected result and also has updated the sample data set. So, the answer has to be updated accordingly.

The approach below uses data.table as in Jaap's answer but differs as follows

tstrsplit() is only called once to split up all columns,

melt() is used to melt multiple columns resulting in two value columns, one for the ids, one for the pay load values,

for each row, the occurence of each id is numbered consecutively,

the final dcast() is used to rename the columns appropriately.

The code below should work with an arbitrary number of id-value-pairs in each row as it has been requested by the OP:

library(data.table)   # CRAN version 1.10.4 used
# split input data at "=" and "\t"
splitted <- DT[, tstrsplit(V1, "=|\t")]
# odd numbered columns contain the ids
cols_odd  <- names(splitted)[c(TRUE, FALSE)] # or: seq(1L, ncol(splitted), by = 2L)
# even numbered columns contain the pay load values
cols_even <- names(splitted)[c(FALSE, TRUE)] # or: seq(2L, ncol(splitted), by = 2L)
# add row number before melting, melt multiple columns, remove NA
molten <- melt(splitted[, rn := .I],
               measure.vars = list(cols_odd, cols_even),
               value.name = c("id", "value"), na.rm = TRUE)
# in each row, number the occurences of each id consecutively
molten[, var.count := rowid(id), rn]
# final reshape from long to wide,
# create column names from id and id count per row
# remove rn because no longer needed
dcast(molten, rn ~ id + var.count, sep = "")[, rn := NULL][]

results in

           x1         y1         y2                       z1                        z2
1: abc1000000 pqr2000000         NA olk78fgzu_zuii8999_ikooo                        NA
2: oljhh88999 lop9876666         NA                       NA                        NA
3: frdt876544 ztr6u76532 uzrt899963 wertttts_765342_ioooosww tzuuuee_66554422_88uuiiid

In contrast to above result, the result expected by the OP includes an empty x2 column. In case this is really intended by the OP, the missing rows need to be added before  the final dcast(). This is achieved by joining a data.table containing all possible combinations of row numbers, ids and id counts per row as follows:

   dcast(molten[CJ(rn, id, var.count, unique = TRUE),
             on = .(rn = V1, id = V2, var.count = V3)],
      rn ~ id + var.count, sep = "")[, rn := NULL][]

which yields

           x1 x2         y1         y2                       z1                        z2
1: abc1000000 NA pqr2000000         NA olk78fgzu_zuii8999_ikooo                        NA
2: oljhh88999 NA lop9876666         NA                       NA                        NA
3: frdt876544 NA ztr6u76532 uzrt899963 wertttts_765342_ioooosww tzuuuee_66554422_88uuiiid

Data

library(data.table)
DT <- fread('"x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo"
  "x=oljhh88999\ty=lop9876666"
  "x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid"',
  header=FALSE)

Answer to the original question

As the question is entitled Split a column into separate columns using regex and the OP explicitely is asking for ideas on how to use tstrsplit with multiple split arguments all answers focused on splitting the columns.

However, if the OP is only interested to obtain the IDs for each line as separate columns there is a simple solution available:

stringr::str_extract_all(DT$V1, "\\wid\\d", simplify = TRUE)
#     [,1]   [,2]   [,3]   [,4]   [,5]
#[1,] "xid1" "yid2" "zid3" ""     ""
#[2,] "xid4" "yid5" ""     ""     ""
#[3,] "xid6" "yid7" "yid8" "zid8" "zid9"

or in data.table context:

DT[, data.table(stringr::str_extract_all(V1, "\\wid\\d", simplify = TRUE))]
#     V1   V2   V3   V4   V5
#1: xid1 yid2 zid3
#2: xid4 yid5
#3: xid6 yid7 yid8 zid8 zid9

Note that in the third line an ID zid8 has been found which is missing in all other answers. The other answers are looking to split the strings at \t (tab character). It might be that there is a \ missing in row three of the given data set, so the section reads tzid8= instead of \tzid8=.

Data

As provided in the question (including the potential error).

DT <- fread('"xid1=abc1000000\tyid2=pqr2000000\tzid3=olk78fgzu_zuii8999_ikooo"
"xid4=oljhh88999\tyid5=lop9876666"
"xid6=frdt876544\tyid7=ztr6u76532\tyid8=uzrt899963tzid8=wertttts_765342_ioooosww\tzid9=tzuuuee_66554422_88uuiiid"',
header=FALSE)


问:
How to get a List of Base class objects, from x number of child classes lists?
For the sake of explanation I made an example

```<code>public class Base {
    public string Name { get; set; }
    public string Surname { get; set; }

    public Base(string name, string surname) {
        Name = name;
        Surname = surname;
    }
}

public class Student : Base {

    public int StudentID { get; set; }

    public Student(string name, string surname, int studentID)
                          : base(name, surname) {
        Name = name;
        Surname = surname;
        StudentID = studentID;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, ID is {2}",
                              Name, Surname, StudentID);
    }
}

public class Teacher : Base {

    public string TeachingSubject { get; set; }

    public Teacher(string name, string surname, string teachingSubject)
                          : base(name, surname) {
        Name = name;
        Surname = surname;
        TeachingSubject = teachingSubject;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, TeachingSubject is {2}",
                              Name, Surname, TeachingSubject);
    }
}
</code>```

In my case, there are 4 child classes, but 2 is enough to keep it simple and still hit the point. Keep in mind that Student and Teacher classes contain their own property, so each object from the Base list should be different, according to the derived class properties.

Somewhere in the project I need to have a Method that returns List of Base objects

```<code>List<Base> GetAllLists() {

    return allLists; //Lets name the return list of Base objects like this
}
</code>```

So I need to put lists of objects from derived classes to a Base class List and use it somewhere.

I already did something like this

```<code>List<Base> GetAllLists() {

    var allLists = new List<Base>();

    var studentList = new StudentService().GetList();  //Service class that populates the list of students from a csv file
    foreach (var item in studentList) {
        allLists.Add(new Student(item.Name, item.Surname, item.StudentID));
    }
    var teacherList = new TeacherService().GetList();  //Service class that populates the list of teachers from a csv file
    foreach (var item in teacherList) {
        allLists.Add(new Teacher(item.Name, item.Surname, item.TeachingSubject));
    }

    return allLists;
}
</code>```

I got a comment:

there's no need to iterate all of the lists and instantiate a new
  object of each entity, since all of them inherit from the same base
  class

So how to achieve this in some other way?

答:
You don't need to write Name = name; Surname = surname; since you already have : base(name, surname)

Regarding to the shadow/deep copy in AddRange(), you can also implement ICloneable or add a copy constructor. Example:

Class definations:

```<code>public class Base {
    public string Name { get; set; }
    public string Surname { get; set; }

    public Base(string name, string surname) {
        Name = name;
        Surname = surname;
    }
}

public class Student : Base, ICloneable {  // ICloneable

    public int StudentID { get; set; }

    public Student(string name, string surname, int studentID) : base(name, surname) {
        //Name = name;
        //Surname = surname;
        StudentID = studentID;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, ID is {2}", Name, Surname, StudentID);
    }

    public object Clone() {
        return MemberwiseClone();
    }
}

public class Teacher : Base {  // Copy constructor

    public string TeachingSubject { get; set; }

    public Teacher(string name, string surname, string teachingSubject) : base(name, surname) {
        //Name = name;
        //Surname = surname;
        TeachingSubject = teachingSubject;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, TeachingSubject is {2}", Name, Surname, TeachingSubject);
    }

    public Teacher(Teacher obj) : base(obj.Name, obj.Surname) {
        TeachingSubject = obj.TeachingSubject;
    }
}
</code>```

Sample usage:

```<code>// AddRange()
List<Student> stud = new List<Student>(2);
stud.Add(new Student("s1", "ss1", 1));
stud.Add(new Student("s2", "ss2", 2));
List<Teacher> teac = new List<Teacher>(2);
teac.Add(new Teacher("t1", "ts1", "subject1"));
teac.Add(new Teacher("t2", "ts2", "subject2"));

List<Base> bas = new List<Base>(4);
bas.AddRange(stud);
bas.AddRange(teac);
Debug.Print($"{Environment.NewLine}AddRange():");
Debug.Print($"Base List:{Environment.NewLine}{bas[0]}{Environment.NewLine}{bas[1]}{Environment.NewLine}{bas[2]}{Environment.NewLine}{bas[3]}");

stud[0] = new Student("s3_changed", "ss3_changed", 3);
stud[1].Name = "s4_changed";
stud[1].Surname = "ss4_changed";
stud[1].StudentID = 4;
bas[2].Name = "b3_changed";
bas[2].Surname = "bs3_changed";
((Teacher)bas[2]).TeachingSubject = "bsub3_changed";
bas[3] = new Teacher("t4_changed", "ts4_changed", "tsbu4_changed");
Debug.Print($"{Environment.NewLine}After Change:");
Debug.Print($"Student List:{Environment.NewLine}{stud[0]}{Environment.NewLine}{stud[1]}");
Debug.Print($"Teacher List:{Environment.NewLine}{teac[0]}{Environment.NewLine}{teac[1]}");
Debug.Print($"Base List:{Environment.NewLine}{bas[0]}{Environment.NewLine}{bas[1]}{Environment.NewLine}{bas[2]}{Environment.NewLine}{bas[3]}");

// Concat()
List<Student> stud2 = new List<Student>(2);
stud2.Add(new Student("s1", "ss1", 1));
stud2.Add(new Student("s2", "ss2", 2));
List<Teacher> teac2 = new List<Teacher>(2);
teac2.Add(new Teacher("t1", "ts1", "subject1"));
teac2.Add(new Teacher("t2", "ts2", "subject2"));

List<Base> bas2 = new List<Base>();
bas2 = bas2.Concat(stud2).Concat(teac2).ToList();
Debug.Print($"{Environment.NewLine}Concat:");
Debug.Print($"Base List:{Environment.NewLine}{bas2[0]}{Environment.NewLine}{bas2[1]}{Environment.NewLine}{bas2[2]}{Environment.NewLine}{bas2[3]}");

stud2[0] = new Student("s3_changed", "ss3_changed", 3);
stud2[1].Name = "s4_changed";
stud2[1].Surname = "ss4_changed";
stud2[1].StudentID = 4;
bas2[2].Name = "b3_changed";
bas2[2].Surname = "bs3_changed";
((Teacher)bas2[2]).TeachingSubject = "bsub3_changed";
bas2[3] = new Teacher("t4_changed", "ts4_changed", "tsbu4_changed");
Debug.Print($"{Environment.NewLine}After Change:");
Debug.Print($"Student List:{Environment.NewLine}{stud2[0]}{Environment.NewLine}{stud2[1]}");
Debug.Print($"Teacher List:{Environment.NewLine}{teac2[0]}{Environment.NewLine}{teac2[1]}");
Debug.Print($"Base List:{Environment.NewLine}{bas2[0]}{Environment.NewLine}{bas2[1]}{Environment.NewLine}{bas2[2]}{Environment.NewLine}{bas2[3]}");

// AddRange() clone
List<Student> stud3 = new List<Student>(2);
stud3.Add(new Student("s1", "ss1", 1));
stud3.Add(new Student("s2", "ss2", 2));
List<Teacher> teac3 = new List<Teacher>(2);
teac3.Add(new Teacher("t1", "ts1", "subject1"));
teac3.Add(new Teacher("t2", "ts2", "subject2"));

List<Base> bas3 = new List<Base>(4);
bas3.AddRange(stud3.Select(x => (Student)x.Clone()).ToList());  // Clone
bas3.AddRange(teac3.Select(x => new Teacher(x)).ToList());  // Copy c'tor
Debug.Print($"{Environment.NewLine}AddRange() clone:");
Debug.Print($"Base List:{Environment.NewLine}{bas3[0]}{Environment.NewLine}{bas3[1]}{Environment.NewLine}{bas3[2]}{Environment.NewLine}{bas3[3]}");

stud3[0] = new Student("s3_changed", "ss3_changed", 3);
stud3[1].Name = "s4_changed";
stud3[1].Surname = "ss4_changed";
stud3[1].StudentID = 4;
bas3[2].Name = "b3_changed";
bas3[2].Surname = "bs3_changed";
((Teacher)bas3[2]).TeachingSubject = "bsub3_changed";
bas3[3] = new Teacher("t4_changed", "ts4_changed", "tsbu4_changed");
Debug.Print($"{Environment.NewLine}After Change:");
Debug.Print($"Student List:{Environment.NewLine}{stud3[0]}{Environment.NewLine}{stud3[1]}");
Debug.Print($"Teacher List:{Environment.NewLine}{teac3[0]}{Environment.NewLine}{teac3[1]}");
Debug.Print($"Base List:{Environment.NewLine}{bas3[0]}{Environment.NewLine}{bas3[1]}{Environment.NewLine}{bas3[2]}{Environment.NewLine}{bas3[3]}");
</code>```

Output:

```<code>AddRange():
Base List:
Name is s1, surname is ss1, ID is 1
Name is s2, surname is ss2, ID is 2
Name is t1, surname is ts1, TeachingSubject is subject1
Name is t2, surname is ts2, TeachingSubject is subject2

After Change:
Student List:
Name is s3_changed, surname is ss3_changed, ID is 3
Name is s4_changed, surname is ss4_changed, ID is 4
Teacher List:
Name is b3_changed, surname is bs3_changed, TeachingSubject is bsub3_changed
Name is t2, surname is ts2, TeachingSubject is subject2
Base List:
Name is s1, surname is ss1, ID is 1
Name is s4_changed, surname is ss4_changed, ID is 4
Name is b3_changed, surname is bs3_changed, TeachingSubject is bsub3_changed
Name is t4_changed, surname is ts4_changed, TeachingSubject is tsbu4_changed

Concat:
Base List:
Name is s1, surname is ss1, ID is 1
Name is s2, surname is ss2, ID is 2
Name is t1, surname is ts1, TeachingSubject is subject1
Name is t2, surname is ts2, TeachingSubject is subject2

After Change:
Student List:
Name is s3_changed, surname is ss3_changed, ID is 3
Name is s4_changed, surname is ss4_changed, ID is 4
Teacher List:
Name is b3_changed, surname is bs3_changed, TeachingSubject is bsub3_changed
Name is t2, surname is ts2, TeachingSubject is subject2
Base List:
Name is s1, surname is ss1, ID is 1
Name is s4_changed, surname is ss4_changed, ID is 4
Name is b3_changed, surname is bs3_changed, TeachingSubject is bsub3_changed
Name is t4_changed, surname is ts4_changed, TeachingSubject is tsbu4_changed

AddRange() clone:
Base List:
Name is s1, surname is ss1, ID is 1
Name is s2, surname is ss2, ID is 2
Name is t1, surname is ts1, TeachingSubject is subject1
Name is t2, surname is ts2, TeachingSubject is subject2

After Change:
Student List:
Name is s3_changed, surname is ss3_changed, ID is 3
Name is s4_changed, surname is ss4_changed, ID is 4
Teacher List:
Name is t1, surname is ts1, TeachingSubject is subject1
Name is t2, surname is ts2, TeachingSubject is subject2
Base List:
Name is s1, surname is ss1, ID is 1
Name is s2, surname is ss2, ID is 2
Name is b3_changed, surname is bs3_changed, TeachingSubject is bsub3_changed
Name is t4_changed, surname is ts4_changed, TeachingSubject is tsbu4_changed
</code>```

Body:
For the sake of explanation I made an example

public class Base {
    public string Name { get; set; }
    public string Surname { get; set; }

    public Base(string name, string surname) {
        Name = name;
        Surname = surname;
    }
}

public class Student : Base {

    public int StudentID { get; set; }

    public Student(string name, string surname, int studentID)
                          : base(name, surname) {
        Name = name;
        Surname = surname;
        StudentID = studentID;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, ID is {2}",
                              Name, Surname, StudentID);
    }
}

public class Teacher : Base {

    public string TeachingSubject { get; set; }

    public Teacher(string name, string surname, string teachingSubject)
                          : base(name, surname) {
        Name = name;
        Surname = surname;
        TeachingSubject = teachingSubject;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, TeachingSubject is {2}",
                              Name, Surname, TeachingSubject);
    }
}

In my case, there are 4 child classes, but 2 is enough to keep it simple and still hit the point. Keep in mind that Student and Teacher classes contain their own property, so each object from the Base list should be different, according to the derived class properties.

Somewhere in the project I need to have a Method that returns List of Base objects

List<Base> GetAllLists() {

    return allLists; //Lets name the return list of Base objects like this
}

So I need to put lists of objects from derived classes to a Base class List and use it somewhere.

I already did something like this

List<Base> GetAllLists() {

    var allLists = new List<Base>();

    var studentList = new StudentService().GetList();  //Service class that populates the list of students from a csv file
    foreach (var item in studentList) {
        allLists.Add(new Student(item.Name, item.Surname, item.StudentID));
    }
    var teacherList = new TeacherService().GetList();  //Service class that populates the list of teachers from a csv file
    foreach (var item in teacherList) {
        allLists.Add(new Teacher(item.Name, item.Surname, item.TeachingSubject));
    }

    return allLists;
}

I got a comment:

there's no need to iterate all of the lists and instantiate a new
  object of each entity, since all of them inherit from the same base
  class

So how to achieve this in some other way?

Body:
You don't need to write Name = name; Surname = surname; since you already have : base(name, surname)

Regarding to the shadow/deep copy in AddRange(), you can also implement ICloneable or add a copy constructor. Example:

Class definations:

public class Base {
    public string Name { get; set; }
    public string Surname { get; set; }

    public Base(string name, string surname) {
        Name = name;
        Surname = surname;
    }
}

public class Student : Base, ICloneable {  // ICloneable

    public int StudentID { get; set; }

    public Student(string name, string surname, int studentID) : base(name, surname) {
        //Name = name;
        //Surname = surname;
        StudentID = studentID;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, ID is {2}", Name, Surname, StudentID);
    }

    public object Clone() {
        return MemberwiseClone();
    }
}

public class Teacher : Base {  // Copy constructor

    public string TeachingSubject { get; set; }

    public Teacher(string name, string surname, string teachingSubject) : base(name, surname) {
        //Name = name;
        //Surname = surname;
        TeachingSubject = teachingSubject;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, TeachingSubject is {2}", Name, Surname, TeachingSubject);
    }

    public Teacher(Teacher obj) : base(obj.Name, obj.Surname) {
        TeachingSubject = obj.TeachingSubject;
    }
}

Sample usage:

// AddRange()
List<Student> stud = new List<Student>(2);
stud.Add(new Student("s1", "ss1", 1));
stud.Add(new Student("s2", "ss2", 2));
List<Teacher> teac = new List<Teacher>(2);
teac.Add(new Teacher("t1", "ts1", "subject1"));
teac.Add(new Teacher("t2", "ts2", "subject2"));

List<Base> bas = new List<Base>(4);
bas.AddRange(stud);
bas.AddRange(teac);
Debug.Print($"{Environment.NewLine}AddRange():");
Debug.Print($"Base List:{Environment.NewLine}{bas[0]}{Environment.NewLine}{bas[1]}{Environment.NewLine}{bas[2]}{Environment.NewLine}{bas[3]}");

stud[0] = new Student("s3_changed", "ss3_changed", 3);
stud[1].Name = "s4_changed";
stud[1].Surname = "ss4_changed";
stud[1].StudentID = 4;
bas[2].Name = "b3_changed";
bas[2].Surname = "bs3_changed";
((Teacher)bas[2]).TeachingSubject = "bsub3_changed";
bas[3] = new Teacher("t4_changed", "ts4_changed", "tsbu4_changed");
Debug.Print($"{Environment.NewLine}After Change:");
Debug.Print($"Student List:{Environment.NewLine}{stud[0]}{Environment.NewLine}{stud[1]}");
Debug.Print($"Teacher List:{Environment.NewLine}{teac[0]}{Environment.NewLine}{teac[1]}");
Debug.Print($"Base List:{Environment.NewLine}{bas[0]}{Environment.NewLine}{bas[1]}{Environment.NewLine}{bas[2]}{Environment.NewLine}{bas[3]}");

// Concat()
List<Student> stud2 = new List<Student>(2);
stud2.Add(new Student("s1", "ss1", 1));
stud2.Add(new Student("s2", "ss2", 2));
List<Teacher> teac2 = new List<Teacher>(2);
teac2.Add(new Teacher("t1", "ts1", "subject1"));
teac2.Add(new Teacher("t2", "ts2", "subject2"));

List<Base> bas2 = new List<Base>();
bas2 = bas2.Concat(stud2).Concat(teac2).ToList();
Debug.Print($"{Environment.NewLine}Concat:");
Debug.Print($"Base List:{Environment.NewLine}{bas2[0]}{Environment.NewLine}{bas2[1]}{Environment.NewLine}{bas2[2]}{Environment.NewLine}{bas2[3]}");

stud2[0] = new Student("s3_changed", "ss3_changed", 3);
stud2[1].Name = "s4_changed";
stud2[1].Surname = "ss4_changed";
stud2[1].StudentID = 4;
bas2[2].Name = "b3_changed";
bas2[2].Surname = "bs3_changed";
((Teacher)bas2[2]).TeachingSubject = "bsub3_changed";
bas2[3] = new Teacher("t4_changed", "ts4_changed", "tsbu4_changed");
Debug.Print($"{Environment.NewLine}After Change:");
Debug.Print($"Student List:{Environment.NewLine}{stud2[0]}{Environment.NewLine}{stud2[1]}");
Debug.Print($"Teacher List:{Environment.NewLine}{teac2[0]}{Environment.NewLine}{teac2[1]}");
Debug.Print($"Base List:{Environment.NewLine}{bas2[0]}{Environment.NewLine}{bas2[1]}{Environment.NewLine}{bas2[2]}{Environment.NewLine}{bas2[3]}");

// AddRange() clone
List<Student> stud3 = new List<Student>(2);
stud3.Add(new Student("s1", "ss1", 1));
stud3.Add(new Student("s2", "ss2", 2));
List<Teacher> teac3 = new List<Teacher>(2);
teac3.Add(new Teacher("t1", "ts1", "subject1"));
teac3.Add(new Teacher("t2", "ts2", "subject2"));

List<Base> bas3 = new List<Base>(4);
bas3.AddRange(stud3.Select(x => (Student)x.Clone()).ToList());  // Clone
bas3.AddRange(teac3.Select(x => new Teacher(x)).ToList());  // Copy c'tor
Debug.Print($"{Environment.NewLine}AddRange() clone:");
Debug.Print($"Base List:{Environment.NewLine}{bas3[0]}{Environment.NewLine}{bas3[1]}{Environment.NewLine}{bas3[2]}{Environment.NewLine}{bas3[3]}");

stud3[0] = new Student("s3_changed", "ss3_changed", 3);
stud3[1].Name = "s4_changed";
stud3[1].Surname = "ss4_changed";
stud3[1].StudentID = 4;
bas3[2].Name = "b3_changed";
bas3[2].Surname = "bs3_changed";
((Teacher)bas3[2]).TeachingSubject = "bsub3_changed";
bas3[3] = new Teacher("t4_changed", "ts4_changed", "tsbu4_changed");
Debug.Print($"{Environment.NewLine}After Change:");
Debug.Print($"Student List:{Environment.NewLine}{stud3[0]}{Environment.NewLine}{stud3[1]}");
Debug.Print($"Teacher List:{Environment.NewLine}{teac3[0]}{Environment.NewLine}{teac3[1]}");
Debug.Print($"Base List:{Environment.NewLine}{bas3[0]}{Environment.NewLine}{bas3[1]}{Environment.NewLine}{bas3[2]}{Environment.NewLine}{bas3[3]}");

Output:

AddRange():
Base List:
Name is s1, surname is ss1, ID is 1
Name is s2, surname is ss2, ID is 2
Name is t1, surname is ts1, TeachingSubject is subject1
Name is t2, surname is ts2, TeachingSubject is subject2

After Change:
Student List:
Name is s3_changed, surname is ss3_changed, ID is 3
Name is s4_changed, surname is ss4_changed, ID is 4
Teacher List:
Name is b3_changed, surname is bs3_changed, TeachingSubject is bsub3_changed
Name is t2, surname is ts2, TeachingSubject is subject2
Base List:
Name is s1, surname is ss1, ID is 1
Name is s4_changed, surname is ss4_changed, ID is 4
Name is b3_changed, surname is bs3_changed, TeachingSubject is bsub3_changed
Name is t4_changed, surname is ts4_changed, TeachingSubject is tsbu4_changed

Concat:
Base List:
Name is s1, surname is ss1, ID is 1
Name is s2, surname is ss2, ID is 2
Name is t1, surname is ts1, TeachingSubject is subject1
Name is t2, surname is ts2, TeachingSubject is subject2

After Change:
Student List:
Name is s3_changed, surname is ss3_changed, ID is 3
Name is s4_changed, surname is ss4_changed, ID is 4
Teacher List:
Name is b3_changed, surname is bs3_changed, TeachingSubject is bsub3_changed
Name is t2, surname is ts2, TeachingSubject is subject2
Base List:
Name is s1, surname is ss1, ID is 1
Name is s4_changed, surname is ss4_changed, ID is 4
Name is b3_changed, surname is bs3_changed, TeachingSubject is bsub3_changed
Name is t4_changed, surname is ts4_changed, TeachingSubject is tsbu4_changed

AddRange() clone:
Base List:
Name is s1, surname is ss1, ID is 1
Name is s2, surname is ss2, ID is 2
Name is t1, surname is ts1, TeachingSubject is subject1
Name is t2, surname is ts2, TeachingSubject is subject2

After Change:
Student List:
Name is s3_changed, surname is ss3_changed, ID is 3
Name is s4_changed, surname is ss4_changed, ID is 4
Teacher List:
Name is t1, surname is ts1, TeachingSubject is subject1
Name is t2, surname is ts2, TeachingSubject is subject2
Base List:
Name is s1, surname is ss1, ID is 1
Name is s2, surname is ss2, ID is 2
Name is b3_changed, surname is bs3_changed, TeachingSubject is bsub3_changed
Name is t4_changed, surname is ts4_changed, TeachingSubject is tsbu4_changed


问:
Android : BufferedReader InputStreamReader returning old value
In my android application am reading text file which is in server.
Am using below method.

```<code>private String getUrlContents(String UrlOfFile)
{
    StringBuilder content = new StringBuilder();

    try
    {
        URL url = new URL(UrlOfFile);
        URLConnection urlConnection = url.openConnection();
        BufferedReader bufferedReader = new BufferedReader(new
        InputStreamReader(urlConnection.getInputStream()));

        String line;

        while ((line = bufferedReader.readLine()) != null)
        {
            content.append(line + "\n");
        }
        bufferedReader.close();
    }
    catch(Exception e)
    {
      Log.d(TAG,"Exception    >>>"+Log.getStackTraceString(e));
    }
    return content.toString();
}
</code>```

But I am getting previous value of text file. When I once do clear data of app its able to get actual value.

Please help me to solve this issue.

答:
My problem was due to returning of cached response.
Issue solved by urlConnection.setUseCaches(false);

Thanks to all responds,

How to prevent Android from returning a cached response to my HTTP Request?

Adding header for HttpURLConnection

Body:
In my android application am reading text file which is in server.
Am using below method.

private String getUrlContents(String UrlOfFile)
{
    StringBuilder content = new StringBuilder();

    try
    {
        URL url = new URL(UrlOfFile);
        URLConnection urlConnection = url.openConnection();
        BufferedReader bufferedReader = new BufferedReader(new
        InputStreamReader(urlConnection.getInputStream()));

        String line;

        while ((line = bufferedReader.readLine()) != null)
        {
            content.append(line + "\n");
        }
        bufferedReader.close();
    }
    catch(Exception e)
    {
      Log.d(TAG,"Exception    >>>"+Log.getStackTraceString(e));
    }
    return content.toString();
}

But I am getting previous value of text file. When I once do clear data of app its able to get actual value.

Please help me to solve this issue.


问:
MVC architecture control flow
I am a bit confused how the three components - Model, View, Controller - interact with each other in MVC architecture. Sometimes I feel I know how MVC works and sometimes I feel I don't know its inner working properly.

What I know about MVC architecture is -

User requests are intercepted by Controller whether it is a URL

request or any event raised by the user on the page.

Then controller processes the user input and talks to the Model.

Model prepares data and sends back to the Controller.

Finally, controller hands over data back to the view and is displayed to the user.

Here in my opinion, View never talks to the Model directly. The interaction between the View and Model will be handled by the Controller only.

So far so good!

But when I see diagrams like below then I get confused. In the below diagram, the left arrow shows that View component can also interact with the Model component.

Also in this code-project article, it is written that "A model is accessible by both controller and view" and "a view can use model to display data".

So kindly clarify whether a model is accessible only by the controller or by both the controller and the view. And if second one is also correct then in what situation this is possible. I work on ASP.NET MVC Framework and here any interaction is done through a controller object. I have never encountered a situation where a view directly talks to the model object.

答:
In Case If the view is Strongly typed with any models then we can say

View=> models

In Case if view is not strongly typed with models then we can say

controller=>Models=> Views

Title: MVC architecture control flow


问:
How to separate a collection into different "buckets"
I have a collection of C# objects. Each object has, for data members, a string which is a guid, an index which is an int, and a string which is a document name. Here is what a typical collection looks like:

```<code>"guid1","c:\temp\doc1.docx",1
"guid1","c:\temp\doc2.docx",2
"guid1","c:\temp\doc3.docx",3
"guid1","c:\temp\doc4.docx",4
"guid2","c:\temp\doc5.docx",5
"guid1","c:\temp\doc6.docx",6
"guid1","c:\temp\doc7.docx",7

I need to end up breaking the collection into individual collections like this:

"guid1","c:\temp\doc1.docx",1
"guid1","c:\temp\doc2.docx",2
"guid1","c:\temp\doc3.docx",3
"guid1","c:\temp\doc4.docx",4

"guid2","c:\temp\doc5.docx",5

"guid1","c:\temp\doc6.docx",6
"guid1","c:\temp\doc7.docx",7
</code>```

These individual collections will then be fed into another function for processing. Trying to figure out the best way to do this.

答:
I did this with linq and no external variables

```<code>    var list = new []{
        new {Id = "guid1", Path = @"c:\temp\doc1.docx", Index = 1},
        new {Id = "guid1", Path = @"c:\temp\doc2.docx", Index = 2},
        new {Id = "guid1", Path = @"c:\temp\doc3.docx", Index = 3},
        new {Id = "guid1", Path = @"c:\temp\doc4.docx", Index = 4},
        new {Id = "guid2", Path = @"c:\temp\doc5.docx", Index = 5},
        new {Id = "guid1", Path = @"c:\temp\doc6.docx", Index = 6},
        new {Id = "guid1", Path = @"c:\temp\doc7.docx", Index = 7}
    };

    var batchSize = 3;

    var batched = list.GroupBy(x => x.Id)
                    .Select(x => x.GroupBy(p => p.Index/batchSize)
                                    .ToArray());

    string json = JsonConvert.SerializeObject(batched);

    Console.WriteLine(json);
</code>```

The json serialization is just for printing to the screen the output, which would be:

```<code>[
   [
      [
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc1.docx",
            "Index":1
         },
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc2.docx",
            "Index":2
         }
      ],
      [
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc3.docx",
            "Index":3
         },
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc4.docx",
            "Index":4
         }
      ],
      [
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc6.docx",
            "Index":6
         },
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc7.docx",
            "Index":7
         }
      ]
   ],
   [
      [
         {
            "Id":"guid2",
            "Path":"c:\\temp\\doc5.docx",
            "Index":5
         }
      ]
   ]
]
</code>```

Body:
I have a collection of C# objects. Each object has, for data members, a string which is a guid, an index which is an int, and a string which is a document name. Here is what a typical collection looks like:

"guid1","c:\temp\doc1.docx",1
"guid1","c:\temp\doc2.docx",2
"guid1","c:\temp\doc3.docx",3
"guid1","c:\temp\doc4.docx",4
"guid2","c:\temp\doc5.docx",5
"guid1","c:\temp\doc6.docx",6
"guid1","c:\temp\doc7.docx",7

I need to end up breaking the collection into individual collections like this:

"guid1","c:\temp\doc1.docx",1
"guid1","c:\temp\doc2.docx",2
"guid1","c:\temp\doc3.docx",3
"guid1","c:\temp\doc4.docx",4

"guid2","c:\temp\doc5.docx",5

"guid1","c:\temp\doc6.docx",6
"guid1","c:\temp\doc7.docx",7

These individual collections will then be fed into another function for processing. Trying to figure out the best way to do this.

Body:
I did this with linq and no external variables

    var list = new []{
        new {Id = "guid1", Path = @"c:\temp\doc1.docx", Index = 1},
        new {Id = "guid1", Path = @"c:\temp\doc2.docx", Index = 2},
        new {Id = "guid1", Path = @"c:\temp\doc3.docx", Index = 3},
        new {Id = "guid1", Path = @"c:\temp\doc4.docx", Index = 4},
        new {Id = "guid2", Path = @"c:\temp\doc5.docx", Index = 5},
        new {Id = "guid1", Path = @"c:\temp\doc6.docx", Index = 6},
        new {Id = "guid1", Path = @"c:\temp\doc7.docx", Index = 7}
    };

    var batchSize = 3;

    var batched = list.GroupBy(x => x.Id)
                    .Select(x => x.GroupBy(p => p.Index/batchSize)
                                    .ToArray());

    string json = JsonConvert.SerializeObject(batched);

    Console.WriteLine(json);

The json serialization is just for printing to the screen the output, which would be:

[
   [
      [
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc1.docx",
            "Index":1
         },
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc2.docx",
            "Index":2
         }
      ],
      [
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc3.docx",
            "Index":3
         },
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc4.docx",
            "Index":4
         }
      ],
      [
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc6.docx",
            "Index":6
         },
         {
            "Id":"guid1",
            "Path":"c:\\temp\\doc7.docx",
            "Index":7
         }
      ]
   ],
   [
      [
         {
            "Id":"guid2",
            "Path":"c:\\temp\\doc5.docx",
            "Index":5
         }
      ]
   ]
]


问:
Pass array to where in Codeigniter Active Record
I have a table in my database with adminId and clientId

There might be 20 records with the adminId of the logged in user and I'm trying to pull a list of clients.

I am wondering if there is a way i can say something like:

```<code>$this->db->where('id', '20 || 15 || 22 || 46 || 86');
</code>```

I'm trying to do this with dynamic data (you never know how many clients Id's you'll need to pull). Any ideas?

答:
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate,

```<code>$this->db->where_in()
ex :  $this->db->where_in('id', array('1','2','3'));
</code>```

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR if appropriate

```<code>$this->db->or_where_in()
ex :  $this->db->where_in('id', array('1','2','3'));
</code>```

Body:
I have a table in my database with adminId and clientId

There might be 20 records with the adminId of the logged in user and I'm trying to pull a list of clients.

I am wondering if there is a way i can say something like:

$this->db->where('id', '20 || 15 || 22 || 46 || 86');

I'm trying to do this with dynamic data (you never know how many clients Id's you'll need to pull). Any ideas?

Body:
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate,

$this->db->where_in()
ex :  $this->db->where_in('id', array('1','2','3'));

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR if appropriate

$this->db->or_where_in()
ex :  $this->db->where_in('id', array('1','2','3'));


问:
How to save DataFrame directly to Hive?
Is it possible to save DataFrame in spark directly to Hive?

I have tried with converting DataFrame to Rdd and then saving as a text file and then loading in hive. But I am wondering if I can directly save dataframe to hive

答:
Saving to Hive is just a matter of using write() method of your SQLContext:

```<code>df.write.saveAsTable(tableName)
</code>```

See https://spark.apache.org/docs/2.1.0/api/java/org/apache/spark/sql/DataFrameWriter.html#saveAsTable(java.lang.String)

From Spark 2.2: use DataSet instead DataFrame.

ContentLicense: CC BY-SA 4.0

Title: How to save DataFrame directly to Hive?

Body:
Saving to Hive is just a matter of using write() method of your SQLContext:

df.write.saveAsTable(tableName)

See https://spark.apache.org/docs/2.1.0/api/java/org/apache/spark/sql/DataFrameWriter.html#saveAsTable(java.lang.String)

From Spark 2.2: use DataSet instead DataFrame.


问:
SFTP file transfer using Apache Commons Vfs2
I am using Apache Commons VFS2 to upload a file to server. Below is the code for the same. I have all the credentials right. The code printed "File uploaded successfully" String as well. But, I could not find the file on server when i cross checked it. Is there anything i am missing here in the code ?

I have all the Jars required (Apache Commons VFS jars, JSH jar)

```<code>public static void main(String[] args) {

    SendMyFiles sendMyFiles = new SendMyFiles();

    sendMyFiles.startFTP("C:/useragent.log");

}

public boolean startFTP(String fileToFTP) {

    props = new Properties();
    StandardFileSystemManager manager = new StandardFileSystemManager();

    try {

        // props.load(new FileInputStream("properties/" +
        // propertiesFilename));
        String serverAddress = "10.111.111.11";
        String userId = "username";
        String password = "password";
        String remoteDirectory = "local/home/client/files/";

        // check if the file exists
        String filepath = fileToFTP;
        File file = new File(filepath);
        if (!file.exists())
            throw new RuntimeException("Error. Local file not found");

        // Initializes the file manager
        manager.init();

        // Setup our SFTP configuration
        FileSystemOptions opts = new FileSystemOptions();
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
        SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
        SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

        // Create the SFTP URI using the host name, userid, password, remote
        // path and file name
        String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + remoteDirectory;

        // Create local file object
        FileObject localFile = manager.resolveFile(file.getAbsolutePath());

        // Create remote file object
        FileObject remoteFile = manager.resolveFile(sftpUri, opts);

        // Copy local file to sftp server
        remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
        System.out.println("File upload successful");

    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    } finally {
        manager.close();
    }

    return true;
}
</code>```

答:
I'd assume that the sftpUri should be a path to the destination file, not directory:

```<code>String sftpUri =
    "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + remoteDirectory + "/" +
    file.getName();
</code>```

Body:
I am using Apache Commons VFS2 to upload a file to server. Below is the code for the same. I have all the credentials right. The code printed "File uploaded successfully" String as well. But, I could not find the file on server when i cross checked it. Is there anything i am missing here in the code ?

I have all the Jars required (Apache Commons VFS jars, JSH jar)

public static void main(String[] args) {

    SendMyFiles sendMyFiles = new SendMyFiles();

    sendMyFiles.startFTP("C:/useragent.log");

}

public boolean startFTP(String fileToFTP) {

    props = new Properties();
    StandardFileSystemManager manager = new StandardFileSystemManager();

    try {

        // props.load(new FileInputStream("properties/" +
        // propertiesFilename));
        String serverAddress = "10.111.111.11";
        String userId = "username";
        String password = "password";
        String remoteDirectory = "local/home/client/files/";

        // check if the file exists
        String filepath = fileToFTP;
        File file = new File(filepath);
        if (!file.exists())
            throw new RuntimeException("Error. Local file not found");

        // Initializes the file manager
        manager.init();

        // Setup our SFTP configuration
        FileSystemOptions opts = new FileSystemOptions();
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
        SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
        SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

        // Create the SFTP URI using the host name, userid, password, remote
        // path and file name
        String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + remoteDirectory;

        // Create local file object
        FileObject localFile = manager.resolveFile(file.getAbsolutePath());

        // Create remote file object
        FileObject remoteFile = manager.resolveFile(sftpUri, opts);

        // Copy local file to sftp server
        remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
        System.out.println("File upload successful");

    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    } finally {
        manager.close();
    }

    return true;
}

Body:
I'd assume that the sftpUri should be a path to the destination file, not directory:

String sftpUri =
    "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + remoteDirectory + "/" +
    file.getName();


问:
Shopify webhook failing to return a successful response
I have created shopify app in which I have used webhooks for checkout/update. Webhook is working fine but I am getting this error message.

Your webhook for checkouts/update
  at https://www.smsblitz.io/smsblitz/abondoned?shop=smsblitz.myshopify.com&user=iman%5Egemconsultinginc.org is
  failing to return a successful response.This webhook has been
  attempted 23 times. If your webhook continues to fail, it will be
  removed and your application will not receive any more notifications.

Please help me to solve this issue.

Thanks

答:
Initially I had the same problems. Following things could be taken care for getting out of the above issue.

Do not wait till you process the data in the notification. Soon after you get the webhook data, send back a 200 ok status code and then go further processing.

Make sure there is no white space before php tag or there is no echo statement available before you send the 200 status code to shopify because that will end up with error - header already sent.

Do not sleep with a timer as shopify wait for a 5 second time window and expect your 200 status code in between that time span.

You can save your processed data/id in a database. Shopify sends a webhook notification around 19(they say but sometimes more in real) times. So, you can try with first check with your database that the webhook notification is already processed by you or not. If processed send a 200 OK immediately.

Webhooks created through API are more reliable than the one created manually through the Shopify admin. (Though shopify claims they treat them same.)


问:
JSF / Primefaces Link to Filesystem
I have a WebApplication, where I have to provide direct access to a mounted network drive on the client side (e.g. \\server\zentrale mapped to drive Z:\).

I tried following, but nothing works:

```<code><a target="_blank" href="file:///server/zentrale/username/data">user files</a>
<h:outputlink target="_blank" value="file:///server/zentrale/username/data">user files</a>

<a target="_blank" href="file:///Z:/username/data">user files</a>
<h:outputlink target="_blank" value="file:///Z:/username/data">user files</a>
</code>```

I also added <disable-cross-context>false</disable-cross-context> in my jboss-web.xml - without success.

@BalusC mentioned in JSF 2 and a link to file system  to create a new webapp context.
So, how can I do this using WildFly 10 and Primefaces 6.1 ?

In an older version of our WebApplication we used the IE View plugin for Firefox, but this was last updated in 2013! Because we have to support other browser like Chrome and IE, we don't want to be dependent on some browser plugins!

答:
In https://developer.jboss.org/thread/227893 I found a hint, how to get access to the local filesystem on the server side.

standalone.xml

```<code><subsystem xmlns="urn:jboss:domain:undertow:3.0">
    <buffer-cache name="default"/>
    <server name="default-server">
        <http-listener name="default" socket-binding="http" redirect-socket="https"/>
            <host name="default-host" alias="localhost">
                <location name="/" handler="welcome-content"/>
                <location name="documents" handler="document-handler"/>
                <filter-ref name="server-header"/>
                <filter-ref name="x-powered-by-header"/>
            </host>
    </server>
    <handlers>
        <file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
        <file name="document-handler" directory-listing="true" path="\\server\Zentrale\docments"/>
    </handlers>
</subsystem>
</code>```

To achieve this using jboss-cli.sh use the following commands:

```<code>/subsystem=undertow/server=default-server/host=default-host/location=documents:add(handler=document-handler)
/subsystem=undertow/configuration=handler/file=document-handler:add(path=\\\\server\\Zentrale\\documents, directory-listing=true)
</code>```

A click on each link in page.xhtml opens a new tab in the browser where I can navigate in the server's file system - even on shared folders!

page.xhtml

```<code><a href="/documents/projects/project_4711/" target="_blank">Project 4711</a>
<h:outputLink value="/documents/projects/project_4711/" target="_blank">Project 4711</h:outputLink>
</code>```

This is the solution for my problem, but yes - it does not allow me to navigate on the clients local filesystem!

Title: JSF / Primefaces Link to Filesystem

Body:
I have a WebApplication, where I have to provide direct access to a mounted network drive on the client side (e.g. \\server\zentrale mapped to drive Z:\).

I tried following, but nothing works:

user files
<h:outputlink target="_blank" value="file:///server/zentrale/username/data">user files

user files
<h:outputlink target="_blank" value="file:///Z:/username/data">user files

I also added <disable-cross-context>false</disable-cross-context> in my jboss-web.xml - without success.

@BalusC mentioned in JSF 2 and a link to file system  to create a new webapp context.
So, how can I do this using WildFly 10 and Primefaces 6.1 ?

In an older version of our WebApplication we used the IE View plugin for Firefox, but this was last updated in 2013! Because we have to support other browser like Chrome and IE, we don't want to be dependent on some browser plugins!

Body:
In https://developer.jboss.org/thread/227893 I found a hint, how to get access to the local filesystem on the server side.

standalone.xml

<subsystem xmlns="urn:jboss:domain:undertow:3.0">
    <buffer-cache name="default"/>
    <server name="default-server">
        <http-listener name="default" socket-binding="http" redirect-socket="https"/>
            <host name="default-host" alias="localhost">
                <location name="/" handler="welcome-content"/>
                <location name="documents" handler="document-handler"/>
                <filter-ref name="server-header"/>
                <filter-ref name="x-powered-by-header"/>
            </host>
    </server>
    <handlers>
        <file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
        <file name="document-handler" directory-listing="true" path="\\server\Zentrale\docments"/>
    </handlers>
</subsystem>

To achieve this using jboss-cli.sh use the following commands:

/subsystem=undertow/server=default-server/host=default-host/location=documents:add(handler=document-handler)
/subsystem=undertow/configuration=handler/file=document-handler:add(path=\\\\server\\Zentrale\\documents, directory-listing=true)

A click on each link in page.xhtml opens a new tab in the browser where I can navigate in the server's file system - even on shared folders!

page.xhtml

<a href="/documents/projects/project_4711/" target="_blank">Project 4711</a>
<h:outputLink value="/documents/projects/project_4711/" target="_blank">Project 4711</h:outputLink>

This is the solution for my problem, but yes - it does not allow me to navigate on the clients local filesystem!


问:
some classes from maven dependency cannot be referenced
I added org.joda.time dependency through maven, and I can reference for example Seconds class from org.joda.time package but I can't DateTime or others. What can cause this behavior? I can browse joda-time-2.9.9.jar in Maven Dependencies and all classes are there.

As you see Seconds class is imported as expected but DateTimeField is not recognized.

答: Problem was in corrupted jars. After i deleted joda.time folder from local maven repo and did Maven->Update it started to work.</p>


问:
How to identify if the error/warning is created with swiftlint rules
I am working on CI/CD setup for my xcode project. For code analysis i am using swiftlint. It is working fine and i am able to see all the errors and warnings in my xcode along with the description. I have also written the run script such that swiftlint only shows the errors and warnings during code analysis and not during build/run.

My issue is, after i integrate the bot with my Xcode server i am not able to identify whether the errors/warnings are generated due to swiftlint rules or by xcode.

Is it possible to identify if the error is due to swiftlint and not generated by xcode itself?

答:
It's easy. [The blue part below is NOT from swiftlint, and the rest below it IS.]

It says "Shell Script Invocation Warning"

At the end of the message it gives you the rule that has been triggered inside parentheses

```<code>(function_body_length)
</code>```

I just look for the messages ending in parens.

Body:
It's easy. [The blue part below is NOT from swiftlint, and the rest below it IS.]

It says "Shell Script Invocation Warning"

At the end of the message it gives you the rule that has been triggered inside parentheses

(function_body_length)

I just look for the messages ending in parens.


问:
codeigniter session destroy two different application
For example i am using two admin panel.Once I destroy all session value through one admin panel, another one admin session value also will destroyed . I am using unset and session_destroy for both admin panel. Is this any way to prevent one another

答:
NOTE: Do not use session_destroy(), it destroys all data registered to a session.
So better to use unset(), it unset a given variable passed to the function. Also avoid the same session variable names.


问:
Monitor /var/log/messages file for specific keyword
we need to monitor /var/log/messages for a specific keyword "Critical"

We need to monitor the same every minute and the moment it appears in messages file it should send an email.

It should only send the latest entry in messages files.

There is no specific time when it can generate the keyword

Can you please provide any idea for the same

Thank You in advance

答:
Try to use below command to monitor /var/log/messages/ with specific keyword.

#  tail -f /var/log/messages | grep "critical"


问:
Is $this->session->userdata and $this->session->has_userdata same when use for authenticate in CodeIgniter?
I used use following code to authenticate in CodeIgniter.

```<code>if(empty($this->session->userdata('user_id'))){
        redirect(base_url());
}
</code>```

After reading the documentation again I found the Codeigniter has another function for it.

```<code>if(!($this->session->has_userdata('user_id'))){
            redirect(base_url());
}
</code>```

If both codes are same or my code has security issues?

答:
Both are different functions & both of them have their own usage.

The second is better option to use because it checks whether the user_data has user_id key or not & thus runs on less code (but it is a legacy function you should use isset($_SESSION[$key]) instead of it).

the first one :-

```<code>if(empty($this->session->userdata('user_id'))){
    redirect(base_url());
}
</code>```

It access the value of user_id key in userdata array in session array.

And the second one :-

```<code>if(!($this->session->has_userdata('user_id'))){
        redirect(base_url());
}
</code>```

It checks whether the user_id key exists or not.

NOTE:

has_userdata($key) is a legacy method kept only for backwards compatibility with older applications. It is just an alias for isset($_SESSION[$key]) - please use that instead.

It returns TRUE if the specified key exists, FALSE if not

Body:
I used use following code to authenticate in CodeIgniter.

if(empty($this->session->userdata('user_id'))){
        redirect(base_url());
}

After reading the documentation again I found the Codeigniter has another function for it.

if(!($this->session->has_userdata('user_id'))){
            redirect(base_url());
}

If both codes are same or my code has security issues?

Body:
Both are different functions & both of them have their own usage.

The second is better option to use because it checks whether the user_data has user_id key or not & thus runs on less code (but it is a legacy function you should use isset($_SESSION[$key]) instead of it).

the first one :-

if(empty($this->session->userdata('user_id'))){
    redirect(base_url());
}

It access the value of user_id key in userdata array in session array.

And the second one :-

if(!($this->session->has_userdata('user_id'))){
        redirect(base_url());
}

It checks whether the user_id key exists or not.

NOTE:

has_userdata($key) is a legacy method kept only for backwards compatibility with older applications. It is just an alias for isset($_SESSION[$key]) - please use that instead.

It returns TRUE if the specified key exists, FALSE if not


问:
XML file or database in this particular case (file updated frequently)
I have a list of URL and I should loop over them every minute or so and save the last successful access time into an XML file or database. Obviously, the URL and some short description will be saved in file as well.

I'm wondering whether XML files are reliable enough or I'm better with a database? If I must go with the database option, which one?

Please advise. Thanks.

答:
I would also use a XML (or JSON) file storage. A simple way to build wrapper classes for a XML file is the XML Schema Binding Generator Wizard in Delphi Professional, or the Data Binding Wizard (in Enterprise / Architect). You only need to provide an example XML or a W3C XSD file. The wizard will create DOM based classes and binding code.

Tutorials:

Delphi XML Binding Wizard Tutorial

Delphi Programming Tutorial #39 - XML Data Binding

ContentLicense: CC BY-SA 2.5


问:
How do you submit a job to Spark from code?
I've spun up a single-node standalone Spark cluster and confirmed my build works with ./bin/run-example SparkPi 10. Then I wrote a really simple test project in scala;

```<code>import org.apache.spark.{SparkConf, SparkContext}

object Main {
  def main(args: Array[String]): Unit = {
    val sparkConf = new SparkConf()
    val sc = new SparkContext("spark://UbuntuVM:7077", "Simple Application")

    val count = sc.parallelize(1 to 100).map{i =>
      val x = Math.random()
      val y = Math.random()
      if (x*x + y*y < 1) 1 else 0
    }.reduce(_ + _)
    println("Pi is roughly " + 4.0 * count / 100)
  }
}
</code>```

I'm running this from inside my IDE (IntelliJ). It connects to the cluster successfully, and I see it submit jobs, but they all throw an error;

```<code>INFO TaskSetManager: Lost task 1.3 in stage 0.0 (TID 7) on executor 192.168.1.233: java.lang.ClassNotFoundException (Main$$anonfun$1) [duplicate 7]
</code>```

If I understand spark correctly, this is because the cluster can't find the code. So how do I feed the code to spark? I'm not running HDFS or anything in this test, but it's all on one box, so I would have expected SparkContext to pass the current directory to spark, but it apparently does not.

Can anyone point me at the right way to set this up?

答:
Here is the Class.

https://spark.apache.org/docs/1.4.0/api/java/org/apache/spark/launcher/package-summary.html

```<code>    import org.apache.spark.launcher.SparkLauncher;

   public class MyLauncher {
     public static void main(String[] args) throws Exception {
       Process spark = new SparkLauncher()
         .setAppResource("/my/app.jar")
         .setMainClass("my.spark.app.Main")
         .setMaster("local")
         .setConf(SparkLauncher.DRIVER_MEMORY, "2g")
         .launch();
       spark.waitFor();
     }
   }
</code>```

Body:
I've spun up a single-node standalone Spark cluster and confirmed my build works with ./bin/run-example SparkPi 10. Then I wrote a really simple test project in scala;

import org.apache.spark.{SparkConf, SparkContext}

object Main {
  def main(args: Array[String]): Unit = {
    val sparkConf = new SparkConf()
    val sc = new SparkContext("spark://UbuntuVM:7077", "Simple Application")

    val count = sc.parallelize(1 to 100).map{i =>
      val x = Math.random()
      val y = Math.random()
      if (x*x + y*y < 1) 1 else 0
    }.reduce(_ + _)
    println("Pi is roughly " + 4.0 * count / 100)
  }
}

I'm running this from inside my IDE (IntelliJ). It connects to the cluster successfully, and I see it submit jobs, but they all throw an error;

INFO TaskSetManager: Lost task 1.3 in stage 0.0 (TID 7) on executor 192.168.1.233: java.lang.ClassNotFoundException (Main$$anonfun$1) [duplicate 7]

If I understand spark correctly, this is because the cluster can't find the code. So how do I feed the code to spark? I'm not running HDFS or anything in this test, but it's all on one box, so I would have expected SparkContext to pass the current directory to spark, but it apparently does not.

Can anyone point me at the right way to set this up?

Body:
Here is the Class.

https://spark.apache.org/docs/1.4.0/api/java/org/apache/spark/launcher/package-summary.html

    import org.apache.spark.launcher.SparkLauncher;

   public class MyLauncher {
     public static void main(String[] args) throws Exception {
       Process spark = new SparkLauncher()
         .setAppResource("/my/app.jar")
         .setMainClass("my.spark.app.Main")
         .setMaster("local")
         .setConf(SparkLauncher.DRIVER_MEMORY, "2g")
         .launch();
       spark.waitFor();
     }
   }


问:
Enable Cache On Azure CDN
I am setting up Azure CDN, and having trouble setting the Cache-Control header.

I used Cloudberry Explorer to setup a sync between my server folders and the CDN.  This is working well.   All my files were copied to the CDN with no problem.

Under Tools > Http Headers > Edit Http Header I set the value for Cache-Control to be: public,max-age=604800

However, this does not appear to be having any effect (according to both Fiddler and Page Speed).

Any tips on setting the Cache-Control header for the Azure CDN would be GREATLY appreciated.

答:
I had this issue myself and needed to update the Cache-Control header on thousands of files. To prevent caching issues in sites, I re-deploy these files with every release to a new path.

I was able to patch together some different suggestions online and ultimately landed on the following solution, which I currently use for deploying one of my production apps.

You need two files, and the script assumes they're in the same directory on your computer:

A text file with a listing of the files in the container (see example below)

The PowerShell script

The Text File (file-list.txt)

The file should be in the example format below with the full file path as deployed to the CDN container. Note this uses forward slashes, and should not include the container name since it will be included in the script. The name of this text file will be included in the PowerShell script below.

```<code>v12/app/app.js
v12/app/app.min.js
v12/app/app.min.js.map
v12/app/account/signup.js
v12/app/account/signup.min.js
... (and so on)
</code>```

The Script (cdn-cache-control.ps1)

The full script is below. You'll need to replace the constants like STORAGE_ACCOUNT_NAME, STORAGE_KEY, and you may need to update the path to the Azure SDK DLL if you have a different version. There are also 2 possible implementations of $blobClient; I repurposed some of this code from a source online, and the un-commented one works for me.

The key difference between what I have here and what you'll find online is the inclusion of $blob.FetchAttributes(). Without explicitly calling this method, a majority of the blob properties like Content-Type, Last Modified Date, and others will be loaded into memory as empty/default values, then when $blob.SetProperties() is called these empty values will blow away the existing ones in the CDN, causing files to load without a Content-Type among other things.

```<code>Add-Type -Path "C:\Program Files\Microsoft SDKs\Azure\.NET SDK\v2.9\bin\Microsoft.WindowsAzure.StorageClient.dll"

$accountName = "STORAGE_ACCOUNT_NAME"
$accountKey = "STORAGE_KEY"
$blobContainerName = "STORAGE_CONTAINER_NAME"

$storageCredentials = New-Object Microsoft.WindowsAzure.StorageCredentialsAccountAndKey -ArgumentList $accountName,$accountKey
$storageAccount = New-Object Microsoft.WindowsAzure.CloudStorageAccount -ArgumentList $storageCredentials,$true
#$blobClient = $storageAccount.CreateCloudBlobClient()
$blobClient = [Microsoft.WindowsAzure.StorageClient.CloudStorageAccountStorageClientExtensions]::CreateCloudBlobClient($storageAccount)

$cacheControlValue = "max-age=31556926"

echo "Setting cache control: $cacheControlValue"

Get-Content "file-list.txt" | foreach {
    $blobName = "$blobContainerName/$_".Trim()
    $blob = $blobClient.GetBlobReference($blobName)
    $blob.FetchAttributes()
    $blob.Properties.CacheControl = $cacheControlValue
    $blob.SetProperties()
    echo $blobName
}
</code>```

It was tricky to find information about mass-setting the Cache-Control header but I've run this script for multiple production releases with great success. I've verified the configuration of the header as well, and routinely run Google's PageSpeed Insights against my site to verify.

Title: Enable Cache On Azure CDN

Body:
I had this issue myself and needed to update the Cache-Control header on thousands of files. To prevent caching issues in sites, I re-deploy these files with every release to a new path.

I was able to patch together some different suggestions online and ultimately landed on the following solution, which I currently use for deploying one of my production apps.

You need two files, and the script assumes they're in the same directory on your computer:

A text file with a listing of the files in the container (see example below)

The PowerShell script

The Text File (file-list.txt)

The file should be in the example format below with the full file path as deployed to the CDN container. Note this uses forward slashes, and should not include the container name since it will be included in the script. The name of this text file will be included in the PowerShell script below.

v12/app/app.js
v12/app/app.min.js
v12/app/app.min.js.map
v12/app/account/signup.js
v12/app/account/signup.min.js
... (and so on)

The Script (cdn-cache-control.ps1)

The full script is below. You'll need to replace the constants like STORAGE_ACCOUNT_NAME, STORAGE_KEY, and you may need to update the path to the Azure SDK DLL if you have a different version. There are also 2 possible implementations of $blobClient; I repurposed some of this code from a source online, and the un-commented one works for me.

The key difference between what I have here and what you'll find online is the inclusion of $blob.FetchAttributes(). Without explicitly calling this method, a majority of the blob properties like Content-Type, Last Modified Date, and others will be loaded into memory as empty/default values, then when $blob.SetProperties() is called these empty values will blow away the existing ones in the CDN, causing files to load without a Content-Type among other things.

Add-Type -Path "C:\Program Files\Microsoft SDKs\Azure\.NET SDK\v2.9\bin\Microsoft.WindowsAzure.StorageClient.dll"

$accountName = "STORAGE_ACCOUNT_NAME"
$accountKey = "STORAGE_KEY"
$blobContainerName = "STORAGE_CONTAINER_NAME"

$storageCredentials = New-Object Microsoft.WindowsAzure.StorageCredentialsAccountAndKey -ArgumentList $accountName,$accountKey
$storageAccount = New-Object Microsoft.WindowsAzure.CloudStorageAccount -ArgumentList $storageCredentials,$true
#$blobClient = $storageAccount.CreateCloudBlobClient()
$blobClient = [Microsoft.WindowsAzure.StorageClient.CloudStorageAccountStorageClientExtensions]::CreateCloudBlobClient($storageAccount)

$cacheControlValue = "max-age=31556926"

echo "Setting cache control: $cacheControlValue"

Get-Content "file-list.txt" | foreach {
    $blobName = "$blobContainerName/$_".Trim()
    $blob = $blobClient.GetBlobReference($blobName)
    $blob.FetchAttributes()
    $blob.Properties.CacheControl = $cacheControlValue
    $blob.SetProperties()
    echo $blobName
}

It was tricky to find information about mass-setting the Cache-Control header but I've run this script for multiple production releases with great success. I've verified the configuration of the header as well, and routinely run Google's PageSpeed Insights against my site to verify.


问:
How to access different components using props
I'm trying to access state from my Login.jsx component but I'm currently working in the UI.jsx component that is displayed once you are logged in.

My logout button in my Login component should be rendered when your state is set to logged in, but I don't want to render it from Login.jsx. I want to render it from UI.jsx.

The button is displayed once I'm not mounting any components but UI takes over as soon as I load it and it won't show up. All my states are in Login but there should be a way to access it from UI, right?

答:
I am not sure I understand your situation, but you can access to component methods via ref. For example, if your UI component declares its Login as follows:

```<code><Login/>
</code>```

you could do this:

```<code><Login ref={(r)=>this.login=r}/>
</code>```

Then you have access from UI's methods to Login's methods using this.login.method().

By the way, wouldn't it be better to store login state in UI component, and update it using a handler?

```<code><Login handler={(ok)=>this.setState({loggedIn: ok})} />
</code>```

and then inside Login component method that checks login:

```<code>doLogin () {
  const ok = //check login
  this.props.handler(ok);
}
</code>```

Body:
I am not sure I understand your situation, but you can access to component methods via ref. For example, if your UI component declares its Login as follows:

<Login/>

you could do this:

<Login ref={(r)=>this.login=r}/>

Then you have access from UI's methods to Login's methods using this.login.method().

By the way, wouldn't it be better to store login state in UI component, and update it using a handler?

<Login handler={(ok)=>this.setState({loggedIn: ok})} />

and then inside Login component method that checks login:

doLogin () {
  const ok = //check login
  this.props.handler(ok);
}


问:
Onclick html attribute invoking encapsulated function
How can you call an encapsulated jQuery function using html attribute onclick="myFunction()"?

HTML

<input type="submit" onclick="processForm()">

Script

```<code>(function($) {

    function processForm() {
        alert('You rang?');
    }

})(jQuery);
</code>```

答:
You can't. You can change the scope in which you apply your onclick, though :

HTML

```<code><input type="submit">
</code>```

JS

```<code>(function($) {

    $('input[type="submit"]').click(function(){
      processForm();
    });

    function processForm() {
        alert('You rang?');
    }

})(jQuery);
</code>```

Body:
How can you call an encapsulated jQuery function using html attribute onclick="myFunction()"?

HTML

<input type="submit" onclick="processForm()">

Script

(function($) {

    function processForm() {
        alert('You rang?');
    }

})(jQuery);

Body:
You can't. You can change the scope in which you apply your onclick, though :

HTML

<input type="submit">

JS

(function($) {

    $('input[type="submit"]').click(function(){
      processForm();
    });

    function processForm() {
        alert('You rang?');
    }

})(jQuery);


问:
online database for C# window application
I'm going to develop a POS system for medium scale company
and the requirement for me is to make all data on time for all of their branches
while in my mind, move the server from local to web would solve this problem
but, i never done any online server for window application
may i know what is the best option for use as secure database ?
such as SQL can handle this well ?
i tried to google but all of the result return is not what i want
may i know what will you do when you facing this problem ?
my knowledge on coding is just VB and CS
also SQL for database
i would like to learn new if there is better option
i hope it is impossible to access by anonymous and it is store secure at back-end only</p>

答:
Typically you don't move the server off of the site premises.

The problem is that they will go completely down in the event your remote server is inaccessible.  Things that can cause this are internet service interruption (pretty common), remote server overloaded (common enough), basically anything that can stop the traffic between the store location and your remove server will bring them to their knees.  The first time this happens they'll scream.  The second time and they'll want your head due to the lost sales.

Instead, leave a sql server at each location.  Set up a master sql server somewhere.  Then set up a VPN connection between the stores and this central office.  Finally, have the store sql boxes do merge replication with the central office.  Incidentally, don't use the built in replication, but an off the shelf product which specializes in replicating sql server.  The built in one can be difficult to learn.

In the event their internet connection goes dark the individual stores will still be able to function.  It will also remain performant as all of the desktop app traffic is purely to the local sql box.

Solving replication errors is much easier than dealing with a flaky ISP.


答:
You need to have the event and the function in the same scope.</p>

```<code> <input type="submit" class="inputTarget">

(function($) {
            $(".inputTarget").on("click",function(){
              processForm();
            });

            function processForm() {
                alert('You rang?');
            }

})(jQuery);
</code>```

Title: Onclick html attribute invoking encapsulated function

Body:
You need to have the event and the function in the same scope.

 <input type="submit" class="inputTarget">

(function($) {
            $(".inputTarget").on("click",function(){
              processForm();
            });

            function processForm() {
                alert('You rang?');
            }

})(jQuery);


问:
Test if a variable is read-only
To test if a variable is read-only, there are the following ugly hacks:

```<code># True if readonly
readonly -p | egrep "declare -[:lower:]+ ${var}="

# False if readonly
temp="$var"; eval $var=x 2>/dev/null && eval $var=\$temp
</code>```

Is there a more elegant solution?

答:
Using a subshell seems to work. Both with local and exported variables.

```<code>$ foo=123
$ bar=456

$ readonly foo

$ echo $foo $bar
123 456

$ (unset foo 2> /dev/null) || echo "Read only"
Read only

$ (unset bar 2> /dev/null) || echo "Read only"
$

$ echo $foo $bar
123 456           # Still intact :-)
</code>```

The important thing is that even is that the subshell salvages your RW ($bar in this case) from being unset in your current shell.

Tested with bash and ksh.

Title: Test if a variable is read-only

Body:
To test if a variable is read-only, there are the following ugly hacks:

# True if readonly
readonly -p | egrep "declare -[:lower:]+ ${var}="

# False if readonly
temp="$var"; eval $var=x 2>/dev/null && eval $var=\$temp

Is there a more elegant solution?

Body:
Using a subshell seems to work. Both with local and exported variables.

$ foo=123
$ bar=456

$ readonly foo

$ echo $foo $bar
123 456

$ (unset foo 2> /dev/null) || echo "Read only"
Read only

$ (unset bar 2> /dev/null) || echo "Read only"
$

$ echo $foo $bar
123 456           # Still intact :-)

The important thing is that even is that the subshell salvages your RW ($bar in this case) from being unset in your current shell.

Tested with bash and ksh.


问:
subtract two columns then add some value and insert in third column using trigger in oracle
i am using oracle 10 g i have been told to do this task using trigger i have come up with this

```<code>|`create trigger total
on inventory
after insert or update
for each row
begin set
:new.total=:new.stockin - :new.stockout +20;
end;`|
</code>```

error missing before,after
i want total = stockin -stockout + 20

table inventory

```<code>|stcokin |               |stockout |                | total|
 |-------|               |---------|                |------|
|2|                        |5|                         | 23|
</code>```

答:
You should assign using :=

You should edit the new values before updating or inserting. After update is ment to (for example) update other tables

I think your trigger name was causing problems too.

so:

```<code>CREATE OR REPLACE TRIGGER trg_total BEFORE INSERT OR UPDATE ON inventory
FOR EACH ROW
BEGIN
    :NEW.total := :NEW.stockin - :NEW.stockout + 20;
END;
</code>```

Body:
i am using oracle 10 g i have been told to do this task using trigger i have come up with this

|`create trigger total
on inventory
after insert or update
for each row
begin set
:new.total=:new.stockin - :new.stockout +20;
end;`|

error missing before,after
i want total = stockin -stockout + 20

table inventory

|stcokin |               |stockout |                | total|
 |-------|               |---------|                |------|
|2|                        |5|                         | 23|

Body:
You should assign using :=

You should edit the new values before updating or inserting. After update is ment to (for example) update other tables

I think your trigger name was causing problems too.

so:

CREATE OR REPLACE TRIGGER trg_total BEFORE INSERT OR UPDATE ON inventory
FOR EACH ROW
BEGIN
    :NEW.total := :NEW.stockin - :NEW.stockout + 20;
END;