问:
Send file in memory to API from Node Express
I've an API in Node and Express which is receiving a file from a the client (Postman in development) and I use multer to get the file in memory like this:

```<code>router.post('/api/v1/upload', contrl.upload, contrl.uploadFile);
</code>```

and then in my controller:

```<code>exports upload = multer({ storage: multer.memoryStorage() }).single('file');
</code>```

Now I can access the file with req.file.buffer, but then I want to send this same file to another API.
I'm using request-promise-native so this would be something like this:

```<code>const rp = require('request-promise-native')

exports.uploadFile = (req, res) => {

  const options = {
    method: 'POST',
    uri: `${uri}`,
    form: {
      file: req.file.buffer
    }
  }

  rp(options)
    .then(parsedBody => {
      return res.status(201).send(parsedBody);
    })
    .catch(err => res.status(400).send(err));
}
</code>```

I removed some other params for simplicity, but this is not working, probably because Node doesn´t know how to handle the info inside req.file.buffer.

EDIT. Ok after some tests I tried to make this work with a real file instead of using multer memoryStorage. So I got this:

```<code>exports upload = multer({ dest: 'uploads/' }).single('file');
</code>```

to save the file to disk, and then

```<code>const request = require('request')

exports.uploadFile = (req, res) => {

  const formData = {
    file: fs.createReadStream('uploads/' + req.file.filename)
  }
  const options = {
    url: `${uri}`
    formData
  }

  request.post(options, (err, response, body) => {
    if (err) return res.status(400).send(err);
    return res.status(201).send(response);
  });
}
</code>```

And it works! But then when I change to memoryStorage in multer and I use file: req.file.buffer instead, it does not work.

EDIT2: I also tried to send the file as a stream when in memory, so I tried this

```<code>const bufferStream = new stream.PassThrough();
bufferStream.end(req.file.buffer);
</code>```

and then passing it in the formData with file: bufferStream but also not working.

How can I achieve this?
Thanks

答:
I recently encountered a similar situation，My process:web to node to PHP.I use "multer" and "request" resolve this problem and i don't use real file.</p>

```<code>    const multer  = require('multer')
    const upload = multer();
    const request = require('request');

    router.post('/upload', upload.single('img'),(req,res,next) => {

        let formData = {
            'quality':80,
            //file field need set options 'contentType' and 'filename' for formData
            'file':{
                value:req.file.buffer,
                options:{
                    contentType:req.file.mimetype,
                    filename:req.file.originalname
                }
            }
        }
       request.post({
             url:''/**uploadurl*/,
             formData
       },function(err,response,body){res.send(body)})
    })
</code>```

Body:
I've an API in Node and Express which is receiving a file from a the client (Postman in development) and I use multer to get the file in memory like this:

router.post('/api/v1/upload', contrl.upload, contrl.uploadFile);

and then in my controller:

exports upload = multer({ storage: multer.memoryStorage() }).single('file');

Now I can access the file with req.file.buffer, but then I want to send this same file to another API.
I'm using request-promise-native so this would be something like this:

const rp = require('request-promise-native')

exports.uploadFile = (req, res) => {

  const options = {
    method: 'POST',
    uri: `${uri}`,
    form: {
      file: req.file.buffer
    }
  }

  rp(options)
    .then(parsedBody => {
      return res.status(201).send(parsedBody);
    })
    .catch(err => res.status(400).send(err));
}

I removed some other params for simplicity, but this is not working, probably because Node doesn´t know how to handle the info inside req.file.buffer.

EDIT. Ok after some tests I tried to make this work with a real file instead of using multer memoryStorage. So I got this:

exports upload = multer({ dest: 'uploads/' }).single('file');

to save the file to disk, and then

const request = require('request')

exports.uploadFile = (req, res) => {

  const formData = {
    file: fs.createReadStream('uploads/' + req.file.filename)
  }
  const options = {
    url: `${uri}`
    formData
  }

  request.post(options, (err, response, body) => {
    if (err) return res.status(400).send(err);
    return res.status(201).send(response);
  });
}

And it works! But then when I change to memoryStorage in multer and I use file: req.file.buffer instead, it does not work.

EDIT2: I also tried to send the file as a stream when in memory, so I tried this

const bufferStream = new stream.PassThrough();
bufferStream.end(req.file.buffer);

and then passing it in the formData with file: bufferStream but also not working.

How can I achieve this?
Thanks

Body:
I recently encountered a similar situation，My process:web to node to PHP.I use "multer" and "request" resolve this problem and i don't use real file.

    const multer  = require('multer')
    const upload = multer();
    const request = require('request');

    router.post('/upload', upload.single('img'),(req,res,next) => {

        let formData = {
            'quality':80,
            //file field need set options 'contentType' and 'filename' for formData
            'file':{
                value:req.file.buffer,
                options:{
                    contentType:req.file.mimetype,
                    filename:req.file.originalname
                }
            }
        }
       request.post({
             url:''/**uploadurl*/,
             formData
       },function(err,response,body){res.send(body)})
    })


来源: stackexchange

问:
Comparing files in two directories
this is what i have tried to do so far:

```<code>$fse = Get-ChildItem -Recurse -Path C:\new1 -Filter *.txt

$fso = Get-ChildItem -Path C:\new2 -Filter *.txt | where {$fse.name -eq $_.name}

echo "output : $fso"
</code>```

new1 directory is having files :- hi.txt, hiCopy.txt, hiCopy2.txt

new2 directory is having files :- hi.txt, hiCopy.txt

This is what i am getting :

```<code>PS C:\Users\prshrivastava> $fse = Get-ChildItem -Recurse -Path C:\new1 -Filter *.txt

PS C:\Users\prshrivastava> $fso = Get-ChildItem -Path C:\new2 -Filter *.txt | where {$fse.name -eq $_.name}

PS C:\Users\prshrivastava> echo "output : $fso"
output :
</code>```

I'm trying to list out same files in different directory and then delete the compared directory if same files found with same match

答:
Your problem is that you are trying to compare a collection against a single item (-eq).

```<code>PS C:\> $Fse = Get-ChildItem -Path 'C:\new1' -Filter '*.txt' -Recurse
PS C:\> $Fse.Name

hi.txt
hiCopy.txt
hiCopy2.txt

PS C:\> $Fso = Get-ChildItem -Path 'C:\new2' -Filter '*.txt' -Recurse |
>> Where-Object { $Fse.Name -contains $_.Name }
PS C:\> $Fso

hi.txt
hiCopy.txt
</code>```

RESOURCES

ContentLicense: CC BY-SA 3.0

Title: Comparing files in two directories

Body:
this is what i have tried to do so far:

$fse = Get-ChildItem -Recurse -Path C:\new1 -Filter *.txt

$fso = Get-ChildItem -Path C:\new2 -Filter *.txt | where {$fse.name -eq $_.name}

echo "output : $fso"

new1 directory is having files :- hi.txt, hiCopy.txt, hiCopy2.txt

new2 directory is having files :- hi.txt, hiCopy.txt

This is what i am getting :

PS C:\Users\prshrivastava> $fse = Get-ChildItem -Recurse -Path C:\new1 -Filter *.txt

PS C:\Users\prshrivastava> $fso = Get-ChildItem -Path C:\new2 -Filter *.txt | where {$fse.name -eq $_.name}

PS C:\Users\prshrivastava> echo "output : $fso"
output :

I'm trying to list out same files in different directory and then delete the compared directory if same files found with same match

Body:
Your problem is that you are trying to compare a collection against a single item (-eq).

PS C:\> $Fse = Get-ChildItem -Path 'C:\new1' -Filter '*.txt' -Recurse
PS C:\> $Fse.Name

hi.txt
hiCopy.txt
hiCopy2.txt

PS C:\> $Fso = Get-ChildItem -Path 'C:\new2' -Filter '*.txt' -Recurse |
>> Where-Object { $Fse.Name -contains $_.Name }
PS C:\> $Fso

hi.txt
hiCopy.txt

RESOURCES


问:
How to check disk-usage in specific schema and sum for all schema? pg9+
The documentation about disk-usage have no "fast and simple" clue or information... So is faster to check here.

When I try SELECT pg_relation_filepath(oid), relpages FROM pg_class WHERE relname = 'big' it  is working fine... but "big" is not a "public.big", it is a "othername.big", if there are public also, will be ambiguous.

When I try SELECT pg_relation_filepath(oid), relpages FROM pg_class WHERE relname = 'othername.big' not works.

I need to compare disk-usage of tables and to check (or sum) all schema disk-usage.

答:
To get Schema size :

```<code>SELECT schemaname, pg_size_pretty(t.taille::bigint) AS taille_table, pg_size_pretty(t.taille_totale::bigint) AS taille_totale_table
  FROM (SELECT schemaname,
               sum(pg_relation_size(schemaname || '.' || tablename)) AS taille,
               sum(pg_total_relation_size(schemaname || '.' || tablename)) AS taille_totale
          FROM pg_tables
          WHERE relname_exists(tablename,schemaname)   -- see note
GROUP BY schemaname) as t ORDER BY taille_totale DESC;
</code>```

And for Tables by Schema, you can do this :

```<code>SELECT schemaname, tablename, tablespace, pg_size_pretty(taille) AS taille_table, pg_size_pretty(taille_totale) AS taille_totale_table
  FROM (SELECT *,
               pg_relation_size(schemaname || '.' || tablename) AS taille,
               pg_total_relation_size(schemaname || '.' || tablename) AS taille_totale
          FROM pg_tables) AS tables
          WHERE relname_exists(tablename,schemaname)   -- see note
 ORDER BY taille_totale DESC;
</code>```

NOTE: to avoid "ERROR: relation 'x.y' does not exist", needs to guard  the string before use it, so

use to_regclass(rel_name) in Postgres 9.4+... See https://stackoverflow.com/a/24089729

or use a generic (see "SwissKnife libraries") function for any pg version, as below

```<code>CREATE or replace FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $$
  SELECT EXISTS (
     SELECT 1
     FROM   pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
            regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
     WHERE  CASE
            WHEN COALESCE(x[2],'')>'' THEN   n.nspname = x[1]      AND c.relname = x[2]
            WHEN $2 IS NULL THEN         n.nspname = 'public'  AND c.relname = $1
            ELSE                         n.nspname = $2        AND c.relname = $1
     END
  )
$$ language SQL IMMUTABLE;
</code>```

Body:
To get Schema size :

SELECT schemaname, pg_size_pretty(t.taille::bigint) AS taille_table, pg_size_pretty(t.taille_totale::bigint) AS taille_totale_table
  FROM (SELECT schemaname,
               sum(pg_relation_size(schemaname || '.' || tablename)) AS taille,
               sum(pg_total_relation_size(schemaname || '.' || tablename)) AS taille_totale
          FROM pg_tables
          WHERE relname_exists(tablename,schemaname)   -- see note
GROUP BY schemaname) as t ORDER BY taille_totale DESC;

And for Tables by Schema, you can do this :

SELECT schemaname, tablename, tablespace, pg_size_pretty(taille) AS taille_table, pg_size_pretty(taille_totale) AS taille_totale_table
  FROM (SELECT *,
               pg_relation_size(schemaname || '.' || tablename) AS taille,
               pg_total_relation_size(schemaname || '.' || tablename) AS taille_totale
          FROM pg_tables) AS tables
          WHERE relname_exists(tablename,schemaname)   -- see note
 ORDER BY taille_totale DESC;

NOTE: to avoid "ERROR: relation 'x.y' does not exist", needs to guard  the string before use it, so

use to_regclass(rel_name) in Postgres 9.4+... See https://stackoverflow.com/a/24089729

or use a generic (see "SwissKnife libraries") function for any pg version, as below

CREATE or replace FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $$
  SELECT EXISTS (
     SELECT 1
     FROM   pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
            regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
     WHERE  CASE
            WHEN COALESCE(x[2],'')>'' THEN   n.nspname = x[1]      AND c.relname = x[2]
            WHEN $2 IS NULL THEN         n.nspname = 'public'  AND c.relname = $1
            ELSE                         n.nspname = $2        AND c.relname = $1
     END
  )
$$ language SQL IMMUTABLE;


问:
R Subtracting columns within a list
I'd like to subtract specific columns within a list. I'm still learning how to properly use the apply functions. For example, given

```<code>> b <- list(data.frame(12:16, 3*2:6), data.frame(10:14, 2*1:5))
> b

[[1]]
  X12.16 X3...2.6
1     12        6
2     13        9
3     14       12
4     15       15
5     16       18

[[2]]
  X10.14 X2...1.5
1     10        2
2     11        4
3     12        6
4     13        8
5     14       10
</code>```

I'd like some function x so that I get

```<code>> x(b)

[[1]]
  X12.16 X3...2.6  <newcol>
1     12        6         6
2     13        9         4
3     14       12         2
4     15       15         0
5     16       18        -2

[[2]]
  X10.14 X2...1.5  <newcol>
1     10        2         8
2     11        4         7
3     12        6         6
4     13        8         5
5     14       10         4
</code>```

Thanks in advance.

Title: R Subtracting columns within a list

Body:
I'd like to subtract specific columns within a list. I'm still learning how to properly use the apply functions. For example, given

> b <- list(data.frame(12:16, 3*2:6), data.frame(10:14, 2*1:5))
> b

[[1]]
  X12.16 X3...2.6
1     12        6
2     13        9
3     14       12
4     15       15
5     16       18

[[2]]
  X10.14 X2...1.5
1     10        2
2     11        4
3     12        6
4     13        8
5     14       10

I'd like some function x so that I get

> x(b)

[[1]]
  X12.16 X3...2.6  <newcol>
1     12        6         6
2     13        9         4
3     14       12         2
4     15       15         0
5     16       18        -2

[[2]]
  X10.14 X2...1.5  <newcol>
1     10        2         8
2     11        4         7
3     12        6         6
4     13        8         5
5     14       10         4

Thanks in advance.

Body:
with dplyr:

library(dplyr)
lapply(b, function(x) x %>% mutate(new_col = .[[1]]-.[[2]]))

Result:

[[1]]
  X12.16 X3...2.6 new_col
1     12        6       6
2     13        9       4
3     14       12       2
4     15       15       0
5     16       18      -2

[[2]]
  X10.14 X2...1.5 new_col
1     10        2       8
2     11        4       7
3     12        6       6
4     13        8       5
5     14       10       4


问:
How to convert javascript to HTML
I'm completely new here and this is my first question. I'm scared.

I will be honest, I'm completely new at HTML and javascript, and my doubt is the following: I'm performing an HttpWebRequest in order to get a string with some text in html format. This text contains lots of javascript code, but what I actually need is to get a string containing the interpreted html (this means, what a browser would do when executing that source code after having entered the corresponding URL in the browse bar).

Is there any way to make such a conversion in C#?

答:
Html.Raw() can be,

in ASP.NET MVC Razor view

For example: Html.Raw("
").

Title: How to convert javascript to HTML

Body:
Html.Raw() can be,

in ASP.NET MVC Razor view

For example: Html.Raw("<div>").


问:
TeeChart Different between LineSeries XY value and Cursor value on Series Double Click
I'm using basic TeeChart version arrived with Delphi 10.1.
A double click on a LineSeries toggle the point and the Mark of this series.
I'm also present the cursor value.
However, there is a shift between the two, they are not identical.

```<code>procedure TfrmMain.SeriesDblClick(Sender: TChartSeries; ValueIndex: Integer;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  tmpX1,tmpY1,tmpX2,tmpY2:Double;
begin
  // First values
  tmpX1:=Chart.Axes.Bottom.CalcPosPoint(X);
  tmpY1:=Chart.Axes.Left.CalcPosPoint(Y);

  // The prevous values are not identical to:
  tmpX2:=(Sender as tLineSeries).XValue[ValueIndex];
  tmpY2:=(Sender as tLineSeries).YValue[ValueIndex];
end;
</code>```

How to fix it?

答:
It's not going to be possible to resolve this. Information is lost when you map from the real-valued space to integer screen space, and back again.

CalcPosPoint takes the integer screen coordinate and maps that to the real-valued axis space. On the other hand XValue[] and YValue[] return the original data.

The chart code starts with the real values in XValue[] and YValue[]. These are mapped to integer values. That mapping by necessity rounds to the nearest integer, after the transformation to real axis values. At that point information is lost, that cannot be retrieved.

As a thought experiment, consider two real X values that were very close. Let's suppose that XValue[0] = 0.0 and XValue[1] = 1e-6, for the sake of argument. The X axis ranges from 0 to 1 say. Now, in this scenario, you would need 1e6 pixels on the screen in order for these two points to have different integer coordinates when mapped onto the screen. Your screen doesn't have that many pixels and so these two points, with different real X values, map to the same X coordinate on the screen.

Hopefully this example shows the imposibility of what you are trying to do. Perhaps the best you can achieve is to search the raw coordinates in XValue[] and YValue[] to find the closes to (tmpX1, tmpY1), and report those closest raw coordinate values.

Body:
I'm using basic TeeChart version arrived with Delphi 10.1.
A double click on a LineSeries toggle the point and the Mark of this series.
I'm also present the cursor value.
However, there is a shift between the two, they are not identical.

procedure TfrmMain.SeriesDblClick(Sender: TChartSeries; ValueIndex: Integer;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  tmpX1,tmpY1,tmpX2,tmpY2:Double;
begin
  // First values
  tmpX1:=Chart.Axes.Bottom.CalcPosPoint(X);
  tmpY1:=Chart.Axes.Left.CalcPosPoint(Y);

  // The prevous values are not identical to:
  tmpX2:=(Sender as tLineSeries).XValue[ValueIndex];
  tmpY2:=(Sender as tLineSeries).YValue[ValueIndex];
end;

How to fix it?


问:
PHP Display as long as field is unique
In my MySQL table, there are several rows which share the same "case number". I want to display the case numbers on a page but do not want cases which have multiple rows to be displayed more than once. This is basically the code I am using:

```<code>//select all records
$query="SELECT * FROM cases ";
$rt=mysql_query($query);
echo mysql_error();

while($nt=mysql_fetch_array($rt)){

echo $nt['case'];
echo $nt['date_created'];

}
</code>```

Any ideas?

答:
you need

```<code>SELECT DISTINCT(case_number) FROM cases
</code>```

you might want to use ORDER BY to order the case_number or by any other field you want.

ContentLicense: CC BY-SA 2.5

Title: PHP Display as long as field is unique

Body:
In my MySQL table, there are several rows which share the same "case number". I want to display the case numbers on a page but do not want cases which have multiple rows to be displayed more than once. This is basically the code I am using:

//select all records
$query="SELECT * FROM cases ";
$rt=mysql_query($query);
echo mysql_error();

while($nt=mysql_fetch_array($rt)){

echo $nt['case'];
echo $nt['date_created'];

}

Any ideas?

Body:
you need

SELECT DISTINCT(case_number) FROM cases

you might want to use ORDER BY to order the case_number or by any other field you want.


问:
how to define a Scala function that takes multiple return values
I want to write a generic function that returns both session(Cassandra database) and connection(MySQL) is it possible?

Here is my code:

```<code>def getdb: Session = {
    var cluster = Cluster.builder().addContactPoint("127.0.0.1").build()
    var session: Session = cluster.connect("keyspace")
    if (session.getState != null) {
      currentDB = "cassandra"
      return session
      }
      else{
      //code for mysql connection
      return Connection
      }
}
</code>```

How should I define my function such that get db should return to whichever it is connected.

答: This is impossible as these two Sessions objects are different although they have the same name. You could return a Either but you would then still need different code for handling right VS left. </p>

Body:
I want to write a generic function that returns both session(Cassandra database) and connection(MySQL) is it possible?

Here is my code:

def getdb: Session = {
    var cluster = Cluster.builder().addContactPoint("127.0.0.1").build()
    var session: Session = cluster.connect("keyspace")
    if (session.getState != null) {
      currentDB = "cassandra"
      return session
      }
      else{
      //code for mysql connection
      return Connection
      }
}

How should I define my function such that get db should return to whichever it is connected.


问:
PHP: associate an array with another array both taken from curl
I have the following code that fetches arrays from a cURL.

```<code>$codici_hotel_arr = array();
foreach($data_destin['results'] as $key=>$val) {
    $codici_hotel_arr[] = '"' . $val['hotel_code'] . '"';
    $codici_price_arr[] = '"' . $val['products'][0]['price'] . '"';
}
$codici_definitivi = implode(', ', $codici_hotel_arr);
$codici_prezzi = implode(', ', $codici_price_arr);
</code>```

The code returns these values:

```<code>**$codici_definitivi:**
"1074d0", "19f726", "1072ba", "183444", "1071bf", "112438", "1b326e", "15d8ab", "19d885", "193e61", "10aab2", "107155", "110669", "189b95", "16d78f", "18dd7d"

**$codici_prezzi**
"160.16", "234.32", "256.88", "325.42", "342.22", "353.30", "365.78", "372.84", "395.72", "478.75", "503.36", "543.39", "584.61", "584.61", "597.70", "601.63".
</code>```

I would need to get a $codici_prezzi for each $codici_definitivi.
As a response of a string cURL, both codes are as follows:

1074d0 -> 160.16;

19f726 -> 234.32;

1072ba -> 256.88;

etc...

It's possible?

Thank you

答:
Supposing that the indices of the arrays are aligned, I would do this:

```<code><?php
for($i = 0; $i < count($codici_definitivi); $i++) {
    echo $codici_definitivi[0] . ' -> ' . $codici_prezzi[0];
    // or set up any other mapping you need, e.g. key => value in another array
}
?>
</code>```

Edit: you should place this mapping before the implode statements, otherwise you overwrite the original arrays with strings.

Body:
I have the following code that fetches arrays from a cURL.

$codici_hotel_arr = array();
foreach($data_destin['results'] as $key=>$val) {
    $codici_hotel_arr[] = '"' . $val['hotel_code'] . '"';
    $codici_price_arr[] = '"' . $val['products'][0]['price'] . '"';
}
$codici_definitivi = implode(', ', $codici_hotel_arr);
$codici_prezzi = implode(', ', $codici_price_arr);

The code returns these values:

**$codici_definitivi:**
"1074d0", "19f726", "1072ba", "183444", "1071bf", "112438", "1b326e", "15d8ab", "19d885", "193e61", "10aab2", "107155", "110669", "189b95", "16d78f", "18dd7d"

**$codici_prezzi**
"160.16", "234.32", "256.88", "325.42", "342.22", "353.30", "365.78", "372.84", "395.72", "478.75", "503.36", "543.39", "584.61", "584.61", "597.70", "601.63".

I would need to get a $codici_prezzi for each $codici_definitivi.
As a response of a string cURL, both codes are as follows:

1074d0 -> 160.16;

19f726 -> 234.32;

1072ba -> 256.88;

etc...

It's possible?

Thank you

Body:
Supposing that the indices of the arrays are aligned, I would do this:

<?php
for($i = 0; $i < count($codici_definitivi); $i++) {
    echo $codici_definitivi[0] . ' -> ' . $codici_prezzi[0];
    // or set up any other mapping you need, e.g. key => value in another array
}
?>

Edit: you should place this mapping before the implode statements, otherwise you overwrite the original arrays with strings.


问:
Can I share data between different class instances in Python?
I have a class option, for which I create an instance z.

How can I use the optionbook from instance z in another instance of option, say y?

```<code>class option(object):
    nextIdNum = 0
    def __init__(self):
          self.optionbook = {}
          self.options = []
          self.optioncomb = {}
    def addopttobook(self,optiondescription):
        self.idNum = option.nextIdNum
        if optiondescription in self.optionbook.values() :
            raise ValueError('Duplicate Option')
        self.optionbook["Opt.ID." + str(self.idNum)] = optiondescription
        option.nextIdNum += 1
    def addoptocomb (self,option):
         combID = 0
         if option in self.optionbook.values():
               if option in self.options:
                    raise ValueError('Duplicate Option')
               self.combID = combID
               self.options.append(str(list(self.optionbook.keys())[list(self.optionbook.values()).index(option)]) +":"+ option)
               self.optioncomb["Optcomb.ID." + str(self.combID)] = self.options
               self.combID +=1
         else:
              raise ValueError('Add options to optionbook first')
    def __str__(self):
        return  str(self.optionbook)

    def getOptionbook(self):
        return self.optionbook.copy()

    def getOptioncomb(self):

        return self.optioncomb.copy()

z = option()
z.addopttobook('open the well')

y = option()
y.addoptocomb('open the well')
</code>```

This gives me a ValueError "Add options to optionbook first" , I understand the error, y and z are different instances. I just want to know how to share data between different instances of same class.

答:
You already defined a variable, that 'shares data between different instance': nextIdNum, so you can do the same for optionbook.

```<code>class option(object):
    nextIdNum = 0
    optionbook = {}

    def __init__(self):
          self.options = []
          self.optioncomb = {}
    ...  # rest of your code here

z = option()
z.addopttobook('z opens the well 1')
z.addopttobook('z opens the well 2')

y = option()
z.addopttobook('y opens the well 1')
y.addoptocomb('z opens the well 1')

print(option.optionbook)
print (option.optionbook == z.optionbook == y.optionbook)
</code>```

Returns:

```<code>{'Opt.ID.0': 'z opens the well 1', 'Opt.ID.1': 'z opens the well 2', 'Opt.ID.2': 'y opens the well 1'}
True  # >> The class itself as well as all instances share the same data.
</code>```

Body:
I have a class option, for which I create an instance z.

How can I use the optionbook from instance z in another instance of option, say y?

class option(object):
    nextIdNum = 0
    def __init__(self):
          self.optionbook = {}
          self.options = []
          self.optioncomb = {}
    def addopttobook(self,optiondescription):
        self.idNum = option.nextIdNum
        if optiondescription in self.optionbook.values() :
            raise ValueError('Duplicate Option')
        self.optionbook["Opt.ID." + str(self.idNum)] = optiondescription
        option.nextIdNum += 1
    def addoptocomb (self,option):
         combID = 0
         if option in self.optionbook.values():
               if option in self.options:
                    raise ValueError('Duplicate Option')
               self.combID = combID
               self.options.append(str(list(self.optionbook.keys())[list(self.optionbook.values()).index(option)]) +":"+ option)
               self.optioncomb["Optcomb.ID." + str(self.combID)] = self.options
               self.combID +=1
         else:
              raise ValueError('Add options to optionbook first')
    def __str__(self):
        return  str(self.optionbook)

    def getOptionbook(self):
        return self.optionbook.copy()

    def getOptioncomb(self):

        return self.optioncomb.copy()

z = option()
z.addopttobook('open the well')

y = option()
y.addoptocomb('open the well')

This gives me a ValueError "Add options to optionbook first" , I understand the error, y and z are different instances. I just want to know how to share data between different instances of same class.

Body:
You already defined a variable, that 'shares data between different instance': nextIdNum, so you can do the same for optionbook.

class option(object):
    nextIdNum = 0
    optionbook = {}

    def __init__(self):
          self.options = []
          self.optioncomb = {}
    ...  # rest of your code here

z = option()
z.addopttobook('z opens the well 1')
z.addopttobook('z opens the well 2')

y = option()
z.addopttobook('y opens the well 1')
y.addoptocomb('z opens the well 1')

print(option.optionbook)
print (option.optionbook == z.optionbook == y.optionbook)

Returns:

{'Opt.ID.0': 'z opens the well 1', 'Opt.ID.1': 'z opens the well 2', 'Opt.ID.2': 'y opens the well 1'}
True  # >> The class itself as well as all instances share the same data.


问:
UITableView is not refreshing when scrolling
I have UITableView, with CustomCell. In CustomCell there is UICollectionView with CustomUICollectionViewCell.
Everything is created in the way, according to UICollectionView inside CustomTableCell.
Then, let's say I have 12 rows. On the beginning I can see 6 of them.
In CustomUICollectionViewCell, labels are fine, but when I scroll down, to see other cells, CustomUICollectionViewCells labels are not as expected. They are the same as first 6 rows, which are now scrolled up.

Where should I refresh CustomUICollectionViewCells label after scroll?

Example view:
Before scrolling:

After scrolling:

However when debugging, when assigning data to cell, everything is assigned fine.
All code is in the link as it's also my question.
Seems that it's duplicating rows. I guess that it should be reloaded(?).

Added prepareForReuse method, as advised, but didn't help. Now my CustomCellClass looks:

```<code>@implementation TemperatureTableViewCell

    NSNumberFormatter *decimalStyleFormatter;

- (void)awakeFromNib
{
    [super awakeFromNib];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

    [flowLayout setItemSize:CGSizeMake(50, 50)];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.collectionView = [[CollectionView alloc] initWithFrame: CGRectZero collectionViewLayout:flowLayout];
    [self.collectionView registerClass:[TemperatureItemCollectionViewCell class] forCellWithReuseIdentifier:@"TemperatureItemCollectionCell"];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;

    [self.contentView addSubview:self.collectionView];

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.collection.count;
}

-(void)collectionView:(CollectionView *)collectionView willDisplayCell:(TemperatureItemCollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    TemperatureSensor *temp = self.collection[indexPath.item];
    cell.temperatureValue = temp.temperature.stringValue;
    cell.tempValTempCollViewCell.text = [NSString stringWithFormat:@"%@°C", cell.temperatureValue];
    cell.sensorName.text = temp.sensorName;
    cell.imageTempCollViewCell.image = [TemperatureImageHelper getTemperatureIcon:temp];
     [self.collectionView reloadData];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TemperatureItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TemperatureItemCollectionCell" forIndexPath:indexPath];
    return cell;
}

- (void)setCollectionViewDelegate:(id)dataSourceDelegate indexPath:(NSIndexPath *)indexPath {
    self.collectionView.delegate = dataSourceDelegate;
}

@end
</code>```

And my CustomCollectionViewCell:

```<code>@implementation TemperatureItemCollectionViewCell
-(void)awakeFromNib {
    [super awakeFromNib];

}
-(void)prepareForReuse {
    [super prepareForReuse];

    self.imageTempCollViewCell.image = nil;
    self.tempValTempCollViewCell.text = nil;
    self.sensorName.text = nil;
    self.temperatureValue = nil;

}
@end
</code>```

My TableViewController

```<code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_tempSensorsDictionary == nil)
        return 0;
    else {
        NSArray *allSensorKeys = [_tempSensorsDictionary allKeys];
        return [allSensorKeys count];
    }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(TemperatureTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell setCollectionViewDelegate:self indexPath:indexPath];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {

    NSArray *nodeNumbers = [_tempSensorsDictionary allKeys];
    TemperatureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath: indexPath];
    cell.collection = [_tempSensorsDictionary  objectForKey:nodeNumbers[indexPath.row]];
    //NSArray *nodeNumbers = [_tempSensorsDictionary allKeys];
    if([[UnitNameCache sharedUnitNameCache] getNameForId:nodeNumbers[indexPath.row]] != nil &&
       ![[[UnitNameCache sharedUnitNameCache] getNameForId:nodeNumbers[indexPath.row]] isEqualToString:@""]) {
        NSString *name = [NSString stringWithFormat:@"%@ (%@)", [[UnitNameCache sharedUnitNameCache] getNameForId:nodeNumbers[indexPath.row]], nodeNumbers[indexPath.row]];
        cell.unitNameLabel.text = name;
    } else {
        cell.unitNameLabel.text = nodeNumbers[indexPath.row];
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 85.0;
}
</code>```

答:
Because UITableViewCells are reused for performance, caching can sometimes occur. In your TemperatureTableViewCell class you should override prepareForReuse and reset its properties. In your case you should clear the data you are populating it with. I would also keep prepareForReuse in TemperatureItemCollectionViewCell to avoid anymore issues.

```<code>- (void)prepareForReuse
{
  [super prepareForReuse];

  //Reset properties here.
  self.collection = nil;
  [self.collectionView reloadData];
}
</code>```

Body:
I have UITableView, with CustomCell. In CustomCell there is UICollectionView with CustomUICollectionViewCell.
Everything is created in the way, according to UICollectionView inside CustomTableCell.
Then, let's say I have 12 rows. On the beginning I can see 6 of them.
In CustomUICollectionViewCell, labels are fine, but when I scroll down, to see other cells, CustomUICollectionViewCells labels are not as expected. They are the same as first 6 rows, which are now scrolled up.

Where should I refresh CustomUICollectionViewCells label after scroll?

Example view:
Before scrolling:

After scrolling:

However when debugging, when assigning data to cell, everything is assigned fine.
All code is in the link as it's also my question.
Seems that it's duplicating rows. I guess that it should be reloaded(?).

Added prepareForReuse method, as advised, but didn't help. Now my CustomCellClass looks:

@implementation TemperatureTableViewCell

    NSNumberFormatter *decimalStyleFormatter;

- (void)awakeFromNib
{
    [super awakeFromNib];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

    [flowLayout setItemSize:CGSizeMake(50, 50)];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.collectionView = [[CollectionView alloc] initWithFrame: CGRectZero collectionViewLayout:flowLayout];
    [self.collectionView registerClass:[TemperatureItemCollectionViewCell class] forCellWithReuseIdentifier:@"TemperatureItemCollectionCell"];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;

    [self.contentView addSubview:self.collectionView];

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.collection.count;
}

-(void)collectionView:(CollectionView *)collectionView willDisplayCell:(TemperatureItemCollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    TemperatureSensor *temp = self.collection[indexPath.item];
    cell.temperatureValue = temp.temperature.stringValue;
    cell.tempValTempCollViewCell.text = [NSString stringWithFormat:@"%@°C", cell.temperatureValue];
    cell.sensorName.text = temp.sensorName;
    cell.imageTempCollViewCell.image = [TemperatureImageHelper getTemperatureIcon:temp];
     [self.collectionView reloadData];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TemperatureItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TemperatureItemCollectionCell" forIndexPath:indexPath];
    return cell;
}

- (void)setCollectionViewDelegate:(id)dataSourceDelegate indexPath:(NSIndexPath *)indexPath {
    self.collectionView.delegate = dataSourceDelegate;
}

@end

And my CustomCollectionViewCell:

@implementation TemperatureItemCollectionViewCell
-(void)awakeFromNib {
    [super awakeFromNib];

}
-(void)prepareForReuse {
    [super prepareForReuse];

    self.imageTempCollViewCell.image = nil;
    self.tempValTempCollViewCell.text = nil;
    self.sensorName.text = nil;
    self.temperatureValue = nil;

}
@end

My TableViewController

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_tempSensorsDictionary == nil)
        return 0;
    else {
        NSArray *allSensorKeys = [_tempSensorsDictionary allKeys];
        return [allSensorKeys count];
    }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(TemperatureTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell setCollectionViewDelegate:self indexPath:indexPath];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {

    NSArray *nodeNumbers = [_tempSensorsDictionary allKeys];
    TemperatureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath: indexPath];
    cell.collection = [_tempSensorsDictionary  objectForKey:nodeNumbers[indexPath.row]];
    //NSArray *nodeNumbers = [_tempSensorsDictionary allKeys];
    if([[UnitNameCache sharedUnitNameCache] getNameForId:nodeNumbers[indexPath.row]] != nil &&
       ![[[UnitNameCache sharedUnitNameCache] getNameForId:nodeNumbers[indexPath.row]] isEqualToString:@""]) {
        NSString *name = [NSString stringWithFormat:@"%@ (%@)", [[UnitNameCache sharedUnitNameCache] getNameForId:nodeNumbers[indexPath.row]], nodeNumbers[indexPath.row]];
        cell.unitNameLabel.text = name;
    } else {
        cell.unitNameLabel.text = nodeNumbers[indexPath.row];
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 85.0;
}

Body:
Because UITableViewCells are reused for performance, caching can sometimes occur. In your TemperatureTableViewCell class you should override prepareForReuse and reset its properties. In your case you should clear the data you are populating it with. I would also keep prepareForReuse in TemperatureItemCollectionViewCell to avoid anymore issues.

- (void)prepareForReuse
{
  [super prepareForReuse];

  //Reset properties here.
  self.collection = nil;
  [self.collectionView reloadData];
}


问:
How to prevent Browser returning default value of int when input is an int parameter in the URL?
```<code>  public IActionResult Info(int id)
            {
                return Content(id + "");
            }
</code>```

Whenever I input Jan/Info/2 the browser returns me the value 0. Why is this and how can I fix this? I'm using MVC core 1.1. UrlParameter.Optional is also not present in Visual Studio for some reason it's not accessible.

```<code>app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "Naam",
                    template: "{controller=Jan}/{action}/{voornaam}");
                routes.MapRoute(
                     name: "Info",
                     template: "{controller=Jan}/{action}/{id}");

            }

 public IActionResult Naam(string voornaam)
        {

            return Content(voornaam);
        }
</code>```

答:
Because you already have another route registration which is matching the exact pattern. As per that registration, it will read the value and assign to the voornaam parameter.

So this should work

```<code>public IActionResult Info(int voornaam)
{
    return Content(voornaam + "");
}
</code>```

Since you have unique names for your action method, you do not need to specify the custom routes for each action method. The default route registration will work fine.

```<code>app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "defaultroutes",
        template: "{controller}/{action=Index}/{id?}",
        defaults: new { controller = "jan" });
});
</code>```

Assuming your controller looks like this

```<code>public class JanController : Controller
{
    public IActionResult Info(int id)
    {
        return Content(id + " : id");
    }
    public IActionResult Naam(string voornaam)
    {
        return Content(voornaam+ ": param value");
    }
}
</code>```

When you access yourSite/jan/info/123, The Info method will handle that and when you request yourSite/jan/Naam?voornaam=shyju ,the Naam method will handle that.

If you want to support url structure like yourSite/jan/Naam/shyju instead of the explicit querystring, you can specify a route pattern on that action method with attribute routing

```<code>public class JanController : Controller
{
    public IActionResult Info(int id)
    {
        return Content(id + " id");
    }
    [Route("[controller]/[action]/{voornaam}")]
    public IActionResult Naam(string voornaam)
    {
        return Content(voornaam + " : param value");
    }
}
</code>```

Now when you request yourSite/jan/Naam/shyju, The Naam method will be called and the string "shyju" will be available in the voornaam parameter

Body:
  public IActionResult Info(int id)
            {
                return Content(id + "");
            }

Whenever I input Jan/Info/2 the browser returns me the value 0. Why is this and how can I fix this? I'm using MVC core 1.1. UrlParameter.Optional is also not present in Visual Studio for some reason it's not accessible.

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "Naam",
                    template: "{controller=Jan}/{action}/{voornaam}");
                routes.MapRoute(
                     name: "Info",
                     template: "{controller=Jan}/{action}/{id}");

            }

 public IActionResult Naam(string voornaam)
        {

            return Content(voornaam);
        }

Body:
Because you already have another route registration which is matching the exact pattern. As per that registration, it will read the value and assign to the voornaam parameter.

So this should work

public IActionResult Info(int voornaam)
{
    return Content(voornaam + "");
}

Since you have unique names for your action method, you do not need to specify the custom routes for each action method. The default route registration will work fine.

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "defaultroutes",
        template: "{controller}/{action=Index}/{id?}",
        defaults: new { controller = "jan" });
});

Assuming your controller looks like this

public class JanController : Controller
{
    public IActionResult Info(int id)
    {
        return Content(id + " : id");
    }
    public IActionResult Naam(string voornaam)
    {
        return Content(voornaam+ ": param value");
    }
}

When you access yourSite/jan/info/123, The Info method will handle that and when you request yourSite/jan/Naam?voornaam=shyju ,the Naam method will handle that.

If you want to support url structure like yourSite/jan/Naam/shyju instead of the explicit querystring, you can specify a route pattern on that action method with attribute routing

public class JanController : Controller
{
    public IActionResult Info(int id)
    {
        return Content(id + " id");
    }
    [Route("[controller]/[action]/{voornaam}")]
    public IActionResult Naam(string voornaam)
    {
        return Content(voornaam + " : param value");
    }
}

Now when you request yourSite/jan/Naam/shyju, The Naam method will be called and the string "shyju" will be available in the voornaam parameter


问:
Google App script extracting data from website
So I am writing a script which look at review done on google+ pages
and updates a google spreadsheet.

I have found out that the line in the html which holds this value is

```<code><span class="A7a">103</span>
</code>```

I just need to make it possible for me to extract from the page with just knowing the URL and that html code.

答:
I agree with the previous answer but there are some omissions</p>

```<code>var response = UrlFetchApp.fetch(url);
var str = response.getContentText();
var balise = '<span class="A7a">'
var cut = str.substring(str.indexOf( balise ), response.length);
var value = cut.substring(balise.length, cut.indexOf("</span>"));
</code>```

Body:
So I am writing a script which look at review done on google+ pages
and updates a google spreadsheet.

I have found out that the line in the html which holds this value is

103

I just need to make it possible for me to extract from the page with just knowing the URL and that html code.

Body:
I agree with the previous answer but there are some omissions

var response = UrlFetchApp.fetch(url);
var str = response.getContentText();
var balise = '<span class="A7a">'
var cut = str.substring(str.indexOf( balise ), response.length);
var value = cut.substring(balise.length, cut.indexOf("</span>"));


问:
Using WebMatrix.Data in Visual Studio with the facebook helpers
I installed the facebook helper package in my Visual Studio 2010 MVC project. Using it currently breaks my site because it can't find the classes it uses from the WebMatrix.Data and WebMatrix.WebData libraries. I can use them in my cs files, but from the facebook.cshtml file they appear to be inaccessible.

Has anybody encountered this? I know this all beta but still.

Thanx
Rinze

答:
Copy the dll files to your site bin folder, which are in

C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies

on my pc


问:
Access Google Search API from outside GAE
I would like to use The Search API, provided by Google for indexing our data and then search on it. The problem is that our application does not go inside GAE. I find way how to use datastore outside GAE, but cannot find how to use Search API outside GAE. The question is: is it really possible to use it from application outside GAE?

PS: we use java.

答:
Nope, the Search API is not even available in the GAE's flexible environment. From Search:

The Search service is currently unavailable outside of the standard
  environment. You can host any full-text search database such as
  ElasticSearch on Google Compute Engine and access it from both
  the standard and flexible environments.


问:
frequency count on considering four columns in r
currently i am trying to count frequency of set of sequence of data frame.

```<code>A  B
1  a
1  b
1  c
2  a
2  b
2  c
</code>```

i have this data frame and i would like to count frequency of "B" of another data frame looking like this

```<code>C  D
1  a
1  a
1  b
1  b
2  b
2  c
2  c
</code>```

As you can see the number of rows is different so datatable(counts) does not work. i would like to it to look like this after frequency count is done

```<code>a  b  freq
1  a   2
1  b   2
1  c   0
2  a   0
2  b   1
2  c   2
</code>```

As you can see it makes counts of all the frequency even the 0 as the on some groups there is no data on it.

thanks for anyone that helps!

答:
By using merge and aggregate

```<code>df2$freq = 1
df = merge(df1,aggregate(freq~.,df2,length),by.x = c('A','B'),by.y = c('C','D'),all.x = T)
df[is.na(df)] = 0
df
  A B freq
1 1 a    2
2 1 b    2
3 1 c    0
4 2 a    0
5 2 b    1
6 2 c    2
</code>```

More Info

```<code>aggregate(freq~.,df2,length)
  C D freq
1 1 a    2
2 1 b    2
3 2 b    1
4 2 c    2
</code>```

Data Input

```<code>df1
  A B
1 1 a
2 1 b
3 1 c
4 2 a
5 2 b
6 2 c

df2
  C D
1 1 a
2 1 a
3 1 b
4 1 b
5 2 b
6 2 c
7 2 c
</code>```

Body:
currently i am trying to count frequency of set of sequence of data frame.

A  B
1  a
1  b
1  c
2  a
2  b
2  c

i have this data frame and i would like to count frequency of "B" of another data frame looking like this

C  D
1  a
1  a
1  b
1  b
2  b
2  c
2  c

As you can see the number of rows is different so datatable(counts) does not work. i would like to it to look like this after frequency count is done

a  b  freq
1  a   2
1  b   2
1  c   0
2  a   0
2  b   1
2  c   2

As you can see it makes counts of all the frequency even the 0 as the on some groups there is no data on it.

thanks for anyone that helps!

Body:
By using merge and aggregate

df2$freq = 1
df = merge(df1,aggregate(freq~.,df2,length),by.x = c('A','B'),by.y = c('C','D'),all.x = T)
df[is.na(df)] = 0
df
  A B freq
1 1 a    2
2 1 b    2
3 1 c    0
4 2 a    0
5 2 b    1
6 2 c    2

More Info

aggregate(freq~.,df2,length)
  C D freq
1 1 a    2
2 1 b    2
3 2 b    1
4 2 c    2

Data Input

df1
  A B
1 1 a
2 1 b
3 1 c
4 2 a
5 2 b
6 2 c

df2
  C D
1 1 a
2 1 a
3 1 b
4 1 b
5 2 b
6 2 c
7 2 c


问:
Convert int 20171116101856 to yyyymmddhhmmss format to be used in datediff function
So I have this table that has date columns in int type.

```<code>last_run_date | last_run_time
   20171116   | 100234
</code>```

Im trying to convert this two values into a datetime to be used in datediff statement.

this is my statement

```<code>SELECT 1
FROM V_Jobs_All_Servers vjas
WHERE JobName='DailyReports_xxxx' and Step_Name='xxxx'
and DATEDIFF(hour, Convert(varchar,STUFF(STUFF(STUFF(STUFF(STUFF(cast(
Convert(varchar(100),vjas.last_run_date) +  Convert(varchar(100),vjas.last_run_time) as varchar)
,5,0,'-'),8,0,'-'),11,0,' '),14,0,':'),17,0,':')), Getdate()) <3
</code>```

This works but only when the last_run_time value is in two digits hour format
101216, but whenever its one digit hour 91316 it fails with the following error,

```<code>The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
</code>```

I am on SQL Server 2005

答:
```<code>DECLARE @temp TABLE (last_run_date int, last_run_time int)
INSERT INTO @temp VALUES (20171116, 100234)

SELECT convert(datetime,CAST(last_run_date as varchar))
             + Convert(time, Dateadd(SECOND, Right(last_run_time,2)/1
                                           ,Dateadd(MINUTE, Right(last_run_time,4)/100
                                                          ,Dateadd(hour, Right(last_run_time,6)/10000
                                                                       ,'1900-01-01'
                                                                  )
                                                    )
                                     )
                      ) [DateConverted]
  FROM @temp
</code>```

Produces Output:

```<code>DateConverted
2017-11-16 10:02:34.000
</code>```

You can see how this works by doing each part individually.

```<code>SELECT Dateadd(hour, Right(last_run_time,6)/10000
                   ,'1900-01-01')
FROM @temp
</code>```

Gives the hours position.

```<code>SELECT Dateadd(MINUTE, Right(last_run_time,4)/100
                     ,Dateadd(hour, Right(last_run_time,6)/10000
                     ,'1900-01-01'))
FROM @temp
</code>```

Gives the hours plus minutes position.

Etc.

Body:
So I have this table that has date columns in int type.

last_run_date | last_run_time
   20171116   | 100234

Im trying to convert this two values into a datetime to be used in datediff statement.

this is my statement

SELECT 1
FROM V_Jobs_All_Servers vjas
WHERE JobName='DailyReports_xxxx' and Step_Name='xxxx'
and DATEDIFF(hour, Convert(varchar,STUFF(STUFF(STUFF(STUFF(STUFF(cast(
Convert(varchar(100),vjas.last_run_date) +  Convert(varchar(100),vjas.last_run_time) as varchar)
,5,0,'-'),8,0,'-'),11,0,' '),14,0,':'),17,0,':')), Getdate()) <3

This works but only when the last_run_time value is in two digits hour format
101216, but whenever its one digit hour 91316 it fails with the following error,

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.

I am on SQL Server 2005

Body:
DECLARE @temp TABLE (last_run_date int, last_run_time int)
INSERT INTO @temp VALUES (20171116, 100234)

SELECT convert(datetime,CAST(last_run_date as varchar))
             + Convert(time, Dateadd(SECOND, Right(last_run_time,2)/1
                                           ,Dateadd(MINUTE, Right(last_run_time,4)/100
                                                          ,Dateadd(hour, Right(last_run_time,6)/10000
                                                                       ,'1900-01-01'
                                                                  )
                                                    )
                                     )
                      ) [DateConverted]
  FROM @temp

Produces Output:

DateConverted
2017-11-16 10:02:34.000

You can see how this works by doing each part individually.

SELECT Dateadd(hour, Right(last_run_time,6)/10000
                   ,'1900-01-01')
FROM @temp

Gives the hours position.

SELECT Dateadd(MINUTE, Right(last_run_time,4)/100
                     ,Dateadd(hour, Right(last_run_time,6)/10000
                     ,'1900-01-01'))
FROM @temp

Gives the hours plus minutes position.

Etc.


问:
typescript w/ angular loading bloburl into img not working
I'm having problems converting a svg blob to a png via canvas.

Here my code:

```<code>const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const data = (new XMLSerializer()).serializeToString(svg);
const svgBlob = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
console.log(svgBlob, canvas);
const img = new Image();
const url = URL.createObjectURL(svgBlob);

img.onload = (() => function () {
      console.log('inside onload');
      ctx.canvas.width = size;
      ctx.canvas.height = size;
      ctx.drawImage(img, 0, 0);
      URL.revokeObjectURL(url);
      const imgURI = canvas
        .toDataURL('image/png')
        .replace('image/png', 'image/octet-stream');

      DownloadModalComponent.triggerDownload(imgURI);
});
img.src = url;
console.log(img.complete,  img.currentSrc);
</code>```

This worked previously with plain javascript (well some jquery).

The console is outputting for img.complete false and currentSrc is empty.

In the network tab I can see that the local svg url is fetched.

答:
let svgSource = "yourSVGcodehere"; // string of your <svg></svg>
let data = "data:image/svg+xml," + encodeURIComponent(svgSource);
let ctx = my2dcanvas.getContext("2d"); // my2dcanvas is your canvas element
let img = new Image();
img.onload = function() {
        ctx.drawImage(img, 0, 0);
        my2dcanvas.toBlob(function(blob) {
        doSomethingWithBlob(blob) // funciton processing the blob
        // clear canvas context:
        ctx.clearRect(0, 0, 320, 320)
    }, 'image/png');
};
img.src = data;```

This is a prod working snippet. Let me know if helps

ContentLicense: CC BY-SA 4.0

Body:
I'm having problems converting a svg blob to a png via canvas.

Here my code:

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const data = (new XMLSerializer()).serializeToString(svg);
const svgBlob = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
console.log(svgBlob, canvas);
const img = new Image();
const url = URL.createObjectURL(svgBlob);

img.onload = (() => function () {
      console.log('inside onload');
      ctx.canvas.width = size;
      ctx.canvas.height = size;
      ctx.drawImage(img, 0, 0);
      URL.revokeObjectURL(url);
      const imgURI = canvas
        .toDataURL('image/png')
        .replace('image/png', 'image/octet-stream');

      DownloadModalComponent.triggerDownload(imgURI);
});
img.src = url;
console.log(img.complete,  img.currentSrc);

This worked previously with plain javascript (well some jquery).

The console is outputting for img.complete false and currentSrc is empty.

In the network tab I can see that the local svg url is fetched.

Body:
let svgSource = "yourSVGcodehere"; // string of your <svg></svg>
let data = "data:image/svg+xml," + encodeURIComponent(svgSource);
let ctx = my2dcanvas.getContext("2d"); // my2dcanvas is your canvas element
let img = new Image();
img.onload = function() {
        ctx.drawImage(img, 0, 0);
        my2dcanvas.toBlob(function(blob) {
        doSomethingWithBlob(blob) // funciton processing the blob
        // clear canvas context:
        ctx.clearRect(0, 0, 320, 320)
    }, 'image/png');
};
img.src = data;

This is a prod working snippet. Let me know if helps


问:
Does SQL Server transform text in any way when performing a BULK INSERT?
I'm trying to use a BULK INSERT statement to populate a large (17-million-row) table in SQL Server from a text file.  One column, of type nchar(17) has a UNIQUE constraint on it.  I've checked (using some Python code) that the file contains no duplicates, but when I execute the query I get this error message from SQL Server:

Cannot insert duplicate key row in object 'dbo.tbl_Name' with unique index 'IX_tbl_Name'.

Could Server be transforming the text in some way as it executes BULK INSERT?  Do SQL Server databases forbid any punctuation marks in nchar columns, or require that any be escaped?  Is there any way I can find out which row is causing the trouble?  Should I switch to some other method for inserting the data?

答: Your collation settings on the column could be causing data to be seen as duplicate, whereas your code may see it as unique.  Things like accents and capitals can cause issues under certain collation settings.</p>

OwnerDisplayName: Tommy Herbert

OwnerDisplayName: ck

LastEditorDisplayName: ck


问:
How to check Mac OS X version at runtime
I am using below code to check OS X version at runtime.

```<code>if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_10)
{
    /* On a 10.10.x or earlier system */
}
</code>```

But this condition return false on 10.10.4 OS X. I am using Xcode 6.3.2.

According to AppKit Release Notes for OS X v10.11, It should work.

```<code>if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9) {
  /* On a 10.9.x or earlier system */
} else if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_10) {
  /* On a 10.10 - 10.10.x system */
} else {
  /* 10.11 or later system */
}
</code>```

答:
Since Xcode 9.0, you can use code below.
Reference to Apple documentation.

Swift

```<code>if #available(macOS 10.13, *) {
      // macOS 10.13 or later code path
} else {
      // code for earlier than 10.13
}
</code>```

Objective-C

```<code>if (@available(macOS 10.13, *)) {
      // macOS 10.13 or later code path
} else {
      // code for earlier than 10.13
}
</code>```

Body:
I am using below code to check OS X version at runtime.

if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_10)
{
    /* On a 10.10.x or earlier system */
}

But this condition return false on 10.10.4 OS X. I am using Xcode 6.3.2.

According to AppKit Release Notes for OS X v10.11, It should work.

if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9) {
  /* On a 10.9.x or earlier system */
} else if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_10) {
  /* On a 10.10 - 10.10.x system */
} else {
  /* 10.11 or later system */
}

Body:
Since Xcode 9.0, you can use code below.
Reference to Apple documentation.

Swift

if #available(macOS 10.13, *) {
      // macOS 10.13 or later code path
} else {
      // code for earlier than 10.13
}

Objective-C

if (@available(macOS 10.13, *)) {
      // macOS 10.13 or later code path
} else {
      // code for earlier than 10.13
}


问:
Dragging SCNNode in ARKit Using SceneKit
I have a simple SCNNode in ARKit and I am trying to drag it wherever I moved my finger on the phone. Here is my code. </p>

```<code> @objc func pan(recognizer :UIGestureRecognizer) {

        guard let currentFrame = self.sceneView.session.currentFrame else {
            return
        }

        var translation = matrix_identity_float4x4
        translation.columns.3.z = -1.5

        let sceneView = recognizer.view as! ARSCNView
        let touchLocation = recognizer.location(in: sceneView)

        let hitTestResult = sceneView.hitTest(touchLocation, options: [:])

        if !hitTestResult.isEmpty {

            print("hit result")

            guard let hitResult = hitTestResult.first else {
                return
            }

            let node = hitResult.node

            node.simdTransform = matrix_multiply(currentFrame.camera.transform, translation)
        }
    }
</code>```

<p>The problem is that the drag is very slow and not smooth. </p>

答:
I handle translation with PanGesture like this. The division by 700 is to smooth and adjust speed of movement, I reached to that value by trial or error, you may want to experiment with it

@objc func onTranslate(_ sender: UIPanGestureRecognizer) {
    let position = sender.location(in: scnView)
    let state = sender.state

    if (state == .failed || state == .cancelled) {
        return
    }

    if (state == .began) {
        // Check it's on a virtual object
        if let objectNode = virtualObject(at: position) {
            // virtualObject(at searches for root node if it's a subnode
            targetNode = objectNode
            latestTranslatePos = position
        }

    }
    else if let _ = targetNode {

        // Translate virtual object
        let deltaX = Float(position.x - latestTranslatePos!.x)/700
        let deltaY = Float(position.y - latestTranslatePos!.y)/700

        targetNode!.localTranslate(by: SCNVector3Make(deltaX, 0.0, deltaY))

        latestTranslatePos = position

        if (state == .ended) {
            targetNode = nil
        }
    }
}
```

Body:
I have a simple SCNNode in ARKit and I am trying to drag it wherever I moved my finger on the phone. Here is my code.

 @objc func pan(recognizer :UIGestureRecognizer) {

        guard let currentFrame = self.sceneView.session.currentFrame else {
            return
        }

        var translation = matrix_identity_float4x4
        translation.columns.3.z = -1.5

        let sceneView = recognizer.view as! ARSCNView
        let touchLocation = recognizer.location(in: sceneView)

        let hitTestResult = sceneView.hitTest(touchLocation, options: [:])

        if !hitTestResult.isEmpty {

            print("hit result")

            guard let hitResult = hitTestResult.first else {
                return
            }

            let node = hitResult.node

            node.simdTransform = matrix_multiply(currentFrame.camera.transform, translation)
        }
    }

The problem is that the drag is very slow and not smooth.


问:
How can I merge overlapping strings in python?
I have some strings,

```<code>['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV']
</code>```

These strings partially overlap each other. If you manually overlapped them you would get:

```<code>SGALWDVPSPV
</code>```

I want a way to go from the list of overlapping strings to the final compressed string in python.  I feel like this must be a problem that someone has solved already and am trying to avoid reinventing the wheel.  The methods I can imagine now are either brute force or involve getting more complicated by using biopython and sequence aligners than I would like.  I have some simple short strings and just want to properly merge them in a simple way.

Does anyone have any advice on a nice way to do this in python?  Thanks!

答:
To determine the overlap of two strings a and b, you can check if any prefix of b is a suffix of a. You can then use that check in a simple loop, aggregating the result and slicing the next string in the list according to the overlap.

```<code>lst = ['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV']

def overlap(a, b):
    return max(i for i in range(len(b)+1) if a.endswith(b[:i]))

res = lst[0]
for s in lst[1:]:
    o = overlap(res, s)
    res += s[o:]
print(res) # SGALWDVPSPV
</code>```

Or using reduce:

```<code>from functools import reduce # Python 3
print(reduce(lambda a, b: a + b[overlap(a,b):], lst))
</code>```

This is probably not super-efficient, with complexity of about O(n k), with n being the number of strings in the list and k the average length per string. You can make it a bit more efficient by only testing whether the last char of the presumed overlap of b is the last character of a, thus reducing the amount of string slicing and function calls in the generator expression:

```<code>def overlap(a, b):
    return max(i for i in range(len(b)) if b[i-1] == a[-1] and a.endswith(b[:i]))
</code>```

Body:
I have some strings,

['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV']

These strings partially overlap each other. If you manually overlapped them you would get:

SGALWDVPSPV

I want a way to go from the list of overlapping strings to the final compressed string in python.  I feel like this must be a problem that someone has solved already and am trying to avoid reinventing the wheel.  The methods I can imagine now are either brute force or involve getting more complicated by using biopython and sequence aligners than I would like.  I have some simple short strings and just want to properly merge them in a simple way.

Does anyone have any advice on a nice way to do this in python?  Thanks!

Body:
To determine the overlap of two strings a and b, you can check if any prefix of b is a suffix of a. You can then use that check in a simple loop, aggregating the result and slicing the next string in the list according to the overlap.

lst = ['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV']

def overlap(a, b):
    return max(i for i in range(len(b)+1) if a.endswith(b[:i]))

res = lst[0]
for s in lst[1:]:
    o = overlap(res, s)
    res += s[o:]
print(res) # SGALWDVPSPV

Or using reduce:

from functools import reduce # Python 3
print(reduce(lambda a, b: a + b[overlap(a,b):], lst))

This is probably not super-efficient, with complexity of about O(n k), with n being the number of strings in the list and k the average length per string. You can make it a bit more efficient by only testing whether the last char of the presumed overlap of b is the last character of a, thus reducing the amount of string slicing and function calls in the generator expression:

def overlap(a, b):
    return max(i for i in range(len(b)) if b[i-1] == a[-1] and a.endswith(b[:i]))


问:
Regex to match comma separated values?
I am looking for a regular expression which accepts comma separated values(no space) of both string and numbers(especially mobile numbers, 10 digits) for client side validation.

I have gone through regexlib.com but i couldn't find good one.

UPDATE

Input patterns:

```<code>9655770780,college,8095145098,schoolmates
</code>```

Its a just a input field, users can enter group name of mobile numbers or just the numbers.

Any suggestions!

答:
Try this pattern. This will verify if a text is a comma separated</p>

```<code>([a-zA-Z0-9]+,)+
</code>```

Title: Regex to match comma separated values?

Body:
I am looking for a regular expression which accepts comma separated values(no space) of both string and numbers(especially mobile numbers, 10 digits) for client side validation.

I have gone through regexlib.com but i couldn't find good one.

UPDATE

Input patterns:

9655770780,college,8095145098,schoolmates

Its a just a input field, users can enter group name of mobile numbers or just the numbers.

Any suggestions!

Body:
Try this pattern. This will verify if a text is a comma separated

([a-zA-Z0-9]+,)+


问:
Is there a way to stop Google Analytics counting development work as hits?
I have added the JavaScript that I need to the bottom of my pages so that I can make use of Google Analytics. Only problem is that I am sure that it is counting all my development work as hits. Seeing as I probably see some of those pages a hundred times a day it will really skew my readings. Is there a way to turn it off from a particular IP address or is this something that should be built into my build process so it only gets added when I build for deployment?</p>

答:
Use a custom metric to filter all this traffic.

When you init GA in your app, set a custom flag to track developres:

```<code>// In your header, after the GA code is injected
if( <your_code_to_check_if_is_dev> ) {
  ga('set', 'is_developer', 1 );
}
</code>```

Then add a filter in your GA Account to remove these results.

Admin > Account > All Filters > Add Filter > User Defined

Body:
Use a custom metric to filter all this traffic.

When you init GA in your app, set a custom flag to track developres:

// In your header, after the GA code is injected
if( <your_code_to_check_if_is_dev> ) {
  ga('set', 'is_developer', 1 );
}

Then add a filter in your GA Account to remove these results.

Admin > Account > All Filters > Add Filter > User Defined


问:
issue to show highlighted text or when any of the table rows are blank
I am using jsPDF API to export the data to the PDF when user click on export button. I am facing issues when the PDF is generated when there is a highlighted text, or there are no values in any of the table rows. The highlighted text color is not been shown in the generated PDF and if the table contains any blank values the table is not shown correctly in the generated PDF.

Please find the online demo https://plnkr.co/edit/GfXDGHWNHh2Mb89In7zK?p=preview

Demo :

 var app = angular.module("app", []);

 app.controller("myController", ["$scope",
   function($scope) {

   $scope.export = function() {

        // var pdf = new jsPDF('landscape');
       var pdf = new jsPDF('p','pt','a4');
        var pdfName = 'test.pdf';

        //var options = {pagesplit: true,'width': 550};
           var options = {
              pagesplit: true,'width': 500
          };

        var $divs = $('.myDivClass')
        var totalDiv = $divs.length -1;
        var currentRecursion=0;

        function recursiveAddHtmlAndSave(currentRecursion, totalRecursions){
            //Once we have done all the divs save the pdf
            if(currentRecursion==totalRecursions){
                pdf.save(pdfName);
            }else{
                currentRecursion++;
                pdf.addPage();
                pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                    recursiveAddHtmlAndSave(currentRecursion, totalRecursions)
                });
            }
        }

        pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
            recursiveAddHtmlAndSave(currentRecursion, totalDiv);
        });
    }
   }
 ]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html ng-app="app">

<head>
<link data-require="bootstrap-css@3.2.0" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
    <link rel="stylesheet" href="style.css" />

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.33/vfs_fonts.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
   <script src="split_text_to_size.js"></script>
<script src="script.js"></script>
</head>

<body>
  <div ng-controller="myController">
        <button ng-click="export()">Export</button>

   <div class="myDivClass" style="background-color:white">
The identity of the longest word in English depends upon the definition of what constitutes a word in the English language, as well as how length should be compared. In addition to words derived naturally from the language's roots (without any known intentional invention), English allows new words to be formed by coinage and construction; place names may be considered words; technical terms may be arbitrarily long. Length may be understood in terms of orthography and number of written letters, or (less commonly)
      <font color="red">This is red texttttt</font>
    <p><span style='background-color: rgb(255, 255, 0);'>text hightlighted with yellow color</span></p><p><span style='background-color: rgb(255, 0, 0);'>asdjasdjasdsjadhjsahdjasdh
     red color</span></p><p><span style='background-color: rgb(255, 0, 0);'><b>asdasdasdasdsaas -- bold and red colorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
    rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr</b></span></p>
<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
     <p><span style="background-color: rgb(255, 255, 0);"><b>Below are the options with bullets</b></span></p><ul><li><span style="background-color: rgb(255, 255, 0);"><b>option1</b></span></li><li><span style="background-color: rgb(255, 255, 0);"><b>option2</b></span></li></ul><p><b style="background-color: rgb(231, 99, 99);">Below are options with numbers</b></p><ol><li><b style="background-color: rgb(231, 99, 99);">option1</b></li><li><b style="background-color: rgb(231, 99, 99);">option2</b></li></ol>

<p><br></p><table class="table table-bordered"><tbody><tr><td>133</td><td><br></td><td><br></td></tr><tr><td><br></td><td>666</td><td><br></td></tr></tbody></table><p><br></p>

  </div></div>
</body>

</html></code>```

I am sure there should be some CSS/js hacks to resolve this issues. Any inputs are helpful.

答:
Well it is not the best solution , but you can convert your entire document into an image and then print the image in the page ,or you can use their new method addHTML but they don't generate a very good

Approach one :

```<code>  $scope.export = function() {

        // var pdf = new jsPDF('landscape');
       var pdf = new jsPDF('p','pt','a4');
        var pdfName = 'test.pdf';

        //var options = {pagesplit: true,'width': 550};
           var options = {
              pagesplit: true,'width': 500
          };

        var $divs = $('.myDivClass')
        var totalDiv = $divs.length -1;
        var currentRecursion=0;

        function recursiveAddHtmlAndSave(currentRecursion, totalRecursions){
            //Once we have done all the divs save the pdf
            if(currentRecursion==totalRecursions){
                pdf.save(pdfName);
            }else{
                currentRecursion++;
                pdf.addPage();
                pdf.addHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                    recursiveAddHtmlAndSave(currentRecursion, totalRecursions)
                });
            }
        }

        pdf.addHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
            recursiveAddHtmlAndSave(currentRecursion, totalDiv);
        });
    }
</code>```

Approach 2 :
where printDiv is the div in which you have to wrap your whole html content

```<code>  var app = angular.module("app", []);

         app.controller("myController", ["$scope",
             function($scope) {

                 $scope.export = function() {
                     html2canvas(document.getElementById("printDiv"), {
                         onrendered: function(canvas) {
                            var imgData = canvas.toDataURL('image/png');
                             console.log('Report Image URL: ' + imgData);
                             var doc = new jsPDF('l', 'mm', [canvas.width, canvas.height]); //210mm wide and 297mm high
                             doc.addImage(imgData, 'PNG', 0, 0, canvas.width, canvas.height);
                             doc.save('sample.pdf');
                         }
                     });
                 }
             }
         ]);
</code>```

Body:
I am using jsPDF API to export the data to the PDF when user click on export button. I am facing issues when the PDF is generated when there is a highlighted text, or there are no values in any of the table rows. The highlighted text color is not been shown in the generated PDF and if the table contains any blank values the table is not shown correctly in the generated PDF.

Please find the online demo https://plnkr.co/edit/GfXDGHWNHh2Mb89In7zK?p=preview

Demo :

 var app = angular.module("app", []);

 app.controller("myController", ["$scope",
   function($scope) {

   $scope.export = function() {

        // var pdf = new jsPDF('landscape');
       var pdf = new jsPDF('p','pt','a4');
        var pdfName = 'test.pdf';

        //var options = {pagesplit: true,'width': 550};
           var options = {
              pagesplit: true,'width': 500
          };

        var $divs = $('.myDivClass')
        var totalDiv = $divs.length -1;
        var currentRecursion=0;

        function recursiveAddHtmlAndSave(currentRecursion, totalRecursions){
            //Once we have done all the divs save the pdf
            if(currentRecursion==totalRecursions){
                pdf.save(pdfName);
            }else{
                currentRecursion++;
                pdf.addPage();
                pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                    recursiveAddHtmlAndSave(currentRecursion, totalRecursions)
                });
            }
        }

        pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
            recursiveAddHtmlAndSave(currentRecursion, totalDiv);
        });
    }
   }
 ]);

<!doctype html>

<link data-require="bootstrap-css@3.2.0" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
    <link rel="stylesheet" href="style.css" />

        <button ng-click="export()">Export</button>

The identity of the longest word in English depends upon the definition of what constitutes a word in the English language, as well as how length should be compared. In addition to words derived naturally from the language's roots (without any known intentional invention), English allows new words to be formed by coinage and construction; place names may be considered words; technical terms may be arbitrarily long. Length may be understood in terms of orthography and number of written letters, or (less commonly)
      This is red texttttt

text hightlighted with yellow color

asdjasdjasdsjadhjsahdjasdh
     red color

asdasdasdasdsaas -- bold and red colorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
    rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr

Coffee

Tea

Milk

Below are the options with bullets

option1

option2

Below are options with numbers

option1

option2

133

	666

I am sure there should be some CSS/js hacks to resolve this issues. Any inputs are helpful.

Body:
Well it is not the best solution , but you can convert your entire document into an image and then print the image in the page ,or you can use their new method addHTML but they don't generate a very good

Approach one :

  $scope.export = function() {

        // var pdf = new jsPDF('landscape');
       var pdf = new jsPDF('p','pt','a4');
        var pdfName = 'test.pdf';

        //var options = {pagesplit: true,'width': 550};
           var options = {
              pagesplit: true,'width': 500
          };

        var $divs = $('.myDivClass')
        var totalDiv = $divs.length -1;
        var currentRecursion=0;

        function recursiveAddHtmlAndSave(currentRecursion, totalRecursions){
            //Once we have done all the divs save the pdf
            if(currentRecursion==totalRecursions){
                pdf.save(pdfName);
            }else{
                currentRecursion++;
                pdf.addPage();
                pdf.addHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                    recursiveAddHtmlAndSave(currentRecursion, totalRecursions)
                });
            }
        }

        pdf.addHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
            recursiveAddHtmlAndSave(currentRecursion, totalDiv);
        });
    }

Approach 2 :
where printDiv is the div in which you have to wrap your whole html content

  var app = angular.module("app", []);

         app.controller("myController", ["$scope",
             function($scope) {

                 $scope.export = function() {
                     html2canvas(document.getElementById("printDiv"), {
                         onrendered: function(canvas) {
                            var imgData = canvas.toDataURL('image/png');
                             console.log('Report Image URL: ' + imgData);
                             var doc = new jsPDF('l', 'mm', [canvas.width, canvas.height]); //210mm wide and 297mm high
                             doc.addImage(imgData, 'PNG', 0, 0, canvas.width, canvas.height);
                             doc.save('sample.pdf');
                         }
                     });
                 }
             }
         ]);


问:
How to display images in a row with IPython display?
If I execute the following command:

```<code>for file in files:
    display(Image(filename=os.path.join(folder,file)))
</code>```

I get a list of images in a column:

How to put them in a row (horizontally)?

答:
This is an improvement to AkiRoss's answer. This gives more flexiblility on how you display and avoids repeating the function for every row by displaying in a grid format.

```<code>import matplotlib.pyplot as plt

def grid_display(list_of_images, list_of_titles=[], no_of_columns=2, figsize=(10,10)):

    fig = plt.figure(figsize=figsize)
    column = 0
    for i in range(len(list_of_images)):
        column += 1
        #  check for end of column and create a new figure
        if column == no_of_columns+1:
            fig = plt.figure(figsize=figsize)
            column = 1
        fig.add_subplot(1, no_of_columns, column)
        plt.imshow(list_of_images[i])
        plt.axis('off')
        if len(list_of_titles) >= len(list_of_images):
            plt.title(list_of_titles[i])
</code>```

Parameters:

list_of_images - a list containing all images you want to display.

list_of_titles - a list containing all titles of image in the same order.

no_of_columns - number of columns in the grid.

figsize - the size of each row to prevent squashing. (horizontal_size, vertical_size).

Example:

```<code>import cv2
import matplotlib.pyplot as plt

img = cv2.imread("files/tiger_monkey.jpg")
grey_img = cv2.imread("files/tiger_monkey_grey.png")

img_b, img_g, img_r = cv2.split(img)
grey_img_b, grey_img_g, grey_img_r = cv2.split(grey_img)

combi_one = cv2.merge((img_b, grey_img_g, img_r))
combi_two = cv2.merge((grey_img_b, grey_img_g, img_r))
combi_three = cv2.merge((img_b, img_g, grey_img_r))
combi_four = cv2.merge((grey_img_b, img_g, img_r))
combi_five = cv2.merge((grey_img_b, img_g, grey_img_r))
combi_six = cv2.merge((img_b, grey_img_g, grey_img_r))

titles = ["combi_one",
          "combi_two",
          "combi_three",
          "combi_four",
          "combi_five",
          "combi_six"]
images = [combi_one,
          combi_two,
          combi_three,
          combi_four,
          combi_five,
          combi_six]

images = [cv2.cvtColor(image, cv2.COLOR_BGR2RGB) for image in images]
grid_display(images, titles, 3, (10,10))
</code>```

Original images:

img

grey_img

Body:
If I execute the following command:

for file in files:
    display(Image(filename=os.path.join(folder,file)))

I get a list of images in a column:

How to put them in a row (horizontally)?

Body:
This is an improvement to AkiRoss's answer. This gives more flexiblility on how you display and avoids repeating the function for every row by displaying in a grid format.

import matplotlib.pyplot as plt

def grid_display(list_of_images, list_of_titles=[], no_of_columns=2, figsize=(10,10)):

    fig = plt.figure(figsize=figsize)
    column = 0
    for i in range(len(list_of_images)):
        column += 1
        #  check for end of column and create a new figure
        if column == no_of_columns+1:
            fig = plt.figure(figsize=figsize)
            column = 1
        fig.add_subplot(1, no_of_columns, column)
        plt.imshow(list_of_images[i])
        plt.axis('off')
        if len(list_of_titles) >= len(list_of_images):
            plt.title(list_of_titles[i])

Parameters:

list_of_images - a list containing all images you want to display.

list_of_titles - a list containing all titles of image in the same order.

no_of_columns - number of columns in the grid.

figsize - the size of each row to prevent squashing. (horizontal_size, vertical_size).

Example:

import cv2
import matplotlib.pyplot as plt

img = cv2.imread("files/tiger_monkey.jpg")
grey_img = cv2.imread("files/tiger_monkey_grey.png")

img_b, img_g, img_r = cv2.split(img)
grey_img_b, grey_img_g, grey_img_r = cv2.split(grey_img)

combi_one = cv2.merge((img_b, grey_img_g, img_r))
combi_two = cv2.merge((grey_img_b, grey_img_g, img_r))
combi_three = cv2.merge((img_b, img_g, grey_img_r))
combi_four = cv2.merge((grey_img_b, img_g, img_r))
combi_five = cv2.merge((grey_img_b, img_g, grey_img_r))
combi_six = cv2.merge((img_b, grey_img_g, grey_img_r))

titles = ["combi_one",
          "combi_two",
          "combi_three",
          "combi_four",
          "combi_five",
          "combi_six"]
images = [combi_one,
          combi_two,
          combi_three,
          combi_four,
          combi_five,
          combi_six]

images = [cv2.cvtColor(image, cv2.COLOR_BGR2RGB) for image in images]
grid_display(images, titles, 3, (10,10))

Original images:

img

grey_img


问:
Sending JSON through amqp-publish from bash
I have a shell script that sends text messages through amqp-publish to a Java Spring RabbitMQ server.

```<code>amqp-publish -u amqp://guest:guest@127.0.0.1/%2f -r "queue.udrive.ustorage" -e "directExchangeUdrive" -b "$msg"
</code>```

So I want to send a JSON message and I did like this but I got errors...

```<code>amqp-publish -u amqp://guest:guest@127.0.0.1/%2f -r "queue.udrive.ustorage" -e "directExchangeUdrive" -p -C application/json "$msg"
Usage: amqp-publish [-?] [-u|--url=amqp://...] [-s|--server=hostname] [--port=port] [--vhost=vhost] [--username=username]
        [--password=password] [--ssl] [--cacert=cacert.pem] [--key=key.pem] [--cert=cert.pem] [-e|--exchange=exchange]
        [-r|--routing-key=routing key] [-p|--persistent] [-C|--content-type=content type] [-t|--reply-to=reply to]
        [-l|--line-buffered] [-E|--content-encoding=content encoding] [-b|--body=body] [-?|--help] [--usage] [OPTIONS]...
</code>```

答:
add -b parameter before "$msg"

amqp-publish -u amqp://guest:guest@127.0.0.1/%2f -r "queue.udrive.ustorage" -e "directExchangeUdrive" -p -C application/json -b "$msg"

Body:
I have a shell script that sends text messages through amqp-publish to a Java Spring RabbitMQ server.

amqp-publish -u amqp://guest:guest@127.0.0.1/%2f -r "queue.udrive.ustorage" -e "directExchangeUdrive" -b "$msg"

So I want to send a JSON message and I did like this but I got errors...

amqp-publish -u amqp://guest:guest@127.0.0.1/%2f -r "queue.udrive.ustorage" -e "directExchangeUdrive" -p -C application/json "$msg"
Usage: amqp-publish [-?] [-u|--url=amqp://...] [-s|--server=hostname] [--port=port] [--vhost=vhost] [--username=username]
        [--password=password] [--ssl] [--cacert=cacert.pem] [--key=key.pem] [--cert=cert.pem] [-e|--exchange=exchange]
        [-r|--routing-key=routing key] [-p|--persistent] [-C|--content-type=content type] [-t|--reply-to=reply to]
        [-l|--line-buffered] [-E|--content-encoding=content encoding] [-b|--body=body] [-?|--help] [--usage] [OPTIONS]...


问:
Fallback Value at Object Declaration
Ok so I could not find anything about this. I hope it's not the most basic question ever.

In Typescript, suppose I want to create an instance of an object and make one parameter dependant on whether or not another object has got a parameter.

Example:

```<code>bigNote : BigNote = {
    title: 'Heads up!',
    message: 'I like notes!',
    color: 'red'
};
</code>```

This is my first object. My second object would be:

```<code>smallNote: SmallNote = {
    title: bigNote.title,
    message: bigNote.message
};
</code>```

Now my question: bigNote may not have a title - if it doesn't - smallNote is supposed to get a replacement (some string), however if it does, I want it to be the bigNote.title.

I know how to do this with a subsequent if-clause but I wonder if this is possible to achieve in the initial declaration already?

(Hope this question isn't too confusing.)

答:
Just use the logical OR operator. It evaluates to its second argument if its first is falsey:

```<code>title: bigNote.title || someString,
</code>```

Where someString is the title you want to default to.

This is basically what you'd be doing with an if statement, but is instead a nice, inline expression.

Title: Fallback Value at Object Declaration

Body:
Ok so I could not find anything about this. I hope it's not the most basic question ever.

In Typescript, suppose I want to create an instance of an object and make one parameter dependant on whether or not another object has got a parameter.

Example:

bigNote : BigNote = {
    title: 'Heads up!',
    message: 'I like notes!',
    color: 'red'
};

This is my first object. My second object would be:

smallNote: SmallNote = {
    title: bigNote.title,
    message: bigNote.message
};

Now my question: bigNote may not have a title - if it doesn't - smallNote is supposed to get a replacement (some string), however if it does, I want it to be the bigNote.title.

I know how to do this with a subsequent if-clause but I wonder if this is possible to achieve in the initial declaration already?

(Hope this question isn't too confusing.)

Body:
Just use the logical OR operator. It evaluates to its second argument if its first is falsey:

title: bigNote.title || someString,

Where someString is the title you want to default to.

This is basically what you'd be doing with an if statement, but is instead a nice, inline expression.


问:
How to add [ngClass] to dynamically created element in Angular?
I have an Nokia map addon, which needs me to create markers on the map by using document.createElement('div').
I want to bind this new div to ngClass, is there possibility of doing this in Angular?

if you know the terminology of what I am trying to explain over-here, that would be a great help, since I did this kind of stuff on Vue and React without problem, I just can't explain to google(or anyone for that matter) what is it that I want to do.

答:
Yes your can achieve this in the following way

let's say you've created a div like

```<code>var div = '<div ng-class="yourClassName">Any text here or whatever</div>';
</code>```

Now you'll have to make dynamic compilation for this element to bind it with controller scope like

```<code>  var newDiv= $compile(div)($scope);
</code>```

Now you can append them with any DOM element. For example

```<code>$('.anyOtherDivClass').append(newDiv)
</code>```

This will allow all of the events like ng-click etc to trigger for your dynamically created elements.

Ps. Don't forget to inject $compile service in your controller.

Hope this helps

Body:
Yes your can achieve this in the following way

let's say you've created a div like

var div = '<div ng-class="yourClassName">Any text here or whatever</div>';

Now you'll have to make dynamic compilation for this element to bind it with controller scope like

  var newDiv= $compile(div)($scope);

Now you can append them with any DOM element. For example

$('.anyOtherDivClass').append(newDiv)

This will allow all of the events like ng-click etc to trigger for your dynamically created elements.

Ps. Don't forget to inject $compile service in your controller.

Hope this helps