问:
Stored Procedure OUT parameter always returning NULL
My stored procedure returns the expected value, but the OUT parameter is not returning anything. Printing the value of the out parameter just before the procedure exits, the parameter's value is set and looks great. So why is my test code not getting any value back?</p>

```<code>USE MyDB
GO
EXECUTE sp_addmessage
   @msgnum   = 51001,
   @severity = 16,
   @msgtext  = N'Resource NOT Available',
   @lang     = 'us_english',
   @replace  = REPLACE
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetNewFileNumber]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetNewFileNumber]
GO

CREATE PROCEDURE dbo.GetNewFileNumber
   (
      @NextFileNum  nvarchar(11) = NULL output
   )
AS
BEGIN

    set transaction isolation level serializable
    begin transaction

    declare @LockResult int;
    declare @CurrentDate date;
    declare @FileNumberDate date;
    declare @FileNumber int;

    execute @LockResult = sp_getapplock
        @Resource    = 'GetNewFileNumber_TRANSACTION',
        @LockMode    = 'Exclusive',
        @LockTimeout = 0
    if @LockResult <> 0
    begin
        rollback transaction
        raiserror ( 51001, 16, 1 )
        return
    end

        set @CurrentDate = CONVERT (date, GETUTCDATE());

    select @FileNumberDate = filedate,
        @FileNumber = fileCount from  dbo._globalCounters;
    if @FileNumberDate != @CurrentDate
    begin
        set @FileNumberDate = @CurrentDate;
        set @FileNumber = 0;
    end

    set @FileNumber = @FileNumber + 1;
    update dbo._globalCounters
        set fileDate = @FileNumberDate, fileCount = @FileNumber;

    set @NextFileNum = convert(nvarchar(6), @FileNumberDate, 12) +
        '-' +
        RIGHT('00'+convert(nvarchar(2), @FileNumber),2);

    execute sp_releaseapplock 'GetNewFileNumber_TRANSACTION'

    commit transaction
    print 'filenum:' + @NextFileNum
    return @FileNumber;
END

GO

--Test the procedure
DECLARE @return_value int
DECLARE @out_value nvarchar(11)
EXEC    @return_value = [dbo].[GetNewFileNumber] @out_value
SELECT  'Return Value' = @return_value, 'Out Value' = @out_value -- Out value always     returns null?!
GO
</code>```

答:
I had the same problem. It turned out that one of my input NVARCHAR parameters was NULL. When added to the output parameter NVARCHAR, it set the whole parameter to NULL.
Bizarrely.
Check your input parameters if adding them to an NVARCHAR output parameter.
I spent quite a while on this!</p>

Body:
My stored procedure returns the expected value, but the OUT parameter is not returning anything. Printing the value of the out parameter just before the procedure exits, the parameter's value is set and looks great. So why is my test code not getting any value back?

USE MyDB
GO
EXECUTE sp_addmessage
   @msgnum   = 51001,
   @severity = 16,
   @msgtext  = N'Resource NOT Available',
   @lang     = 'us_english',
   @replace  = REPLACE
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetNewFileNumber]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetNewFileNumber]
GO

CREATE PROCEDURE dbo.GetNewFileNumber
   (
      @NextFileNum  nvarchar(11) = NULL output
   )
AS
BEGIN

    set transaction isolation level serializable
    begin transaction

    declare @LockResult int;
    declare @CurrentDate date;
    declare @FileNumberDate date;
    declare @FileNumber int;

    execute @LockResult = sp_getapplock
        @Resource    = 'GetNewFileNumber_TRANSACTION',
        @LockMode    = 'Exclusive',
        @LockTimeout = 0
    if @LockResult <> 0
    begin
        rollback transaction
        raiserror ( 51001, 16, 1 )
        return
    end

        set @CurrentDate = CONVERT (date, GETUTCDATE());

    select @FileNumberDate = filedate,
        @FileNumber = fileCount from  dbo._globalCounters;
    if @FileNumberDate != @CurrentDate
    begin
        set @FileNumberDate = @CurrentDate;
        set @FileNumber = 0;
    end

    set @FileNumber = @FileNumber + 1;
    update dbo._globalCounters
        set fileDate = @FileNumberDate, fileCount = @FileNumber;

    set @NextFileNum = convert(nvarchar(6), @FileNumberDate, 12) +
        '-' +
        RIGHT('00'+convert(nvarchar(2), @FileNumber),2);

    execute sp_releaseapplock 'GetNewFileNumber_TRANSACTION'

    commit transaction
    print 'filenum:' + @NextFileNum
    return @FileNumber;
END

GO

--Test the procedure
DECLARE @return_value int
DECLARE @out_value nvarchar(11)
EXEC    @return_value = [dbo].[GetNewFileNumber] @out_value
SELECT  'Return Value' = @return_value, 'Out Value' = @out_value -- Out value always     returns null?!
GO


来源: stackexchange

问:
javascript click change child div elements
So I have a
 and when you click it becomes wider until you click it again and shrinks. I also have images inside it that when clicked will fill the new space, my problem is I want all but first one to be hidden until it becomes wider.

https://jsfiddle.net/4ayy4amk/

```<code>document.getElementById("logo").onclick = function () {
    ( this.style.width == '45px' || this.style.width == '' )
    ? this.style.width = '241px'
    : this.style.width = '45px';
};
</code>```

答: You just needed to set overflow:hidden on the #logo.  See this.

ContentLicense: CC BY-SA 3.0

Body:
So I have a
 and when you click it becomes wider until you click it again and shrinks. I also have images inside it that when clicked will fill the new space, my problem is I want all but first one to be hidden until it becomes wider.

https://jsfiddle.net/4ayy4amk/

document.getElementById("logo").onclick = function () {
    ( this.style.width == '45px' || this.style.width == '' )
    ? this.style.width = '241px'
    : this.style.width = '45px';
};


问:
How to get two <div> floating below each other
I want to ask how can I move floated  below another so both of them are floating on the same side but they're below each other. Thanks.</p>

答:
```<code>div {
 clear: right;
}
</code>```

Here's a demo:

http://codepen.io/paulcredmond/pen/BWvPNK

ContentLicense: CC BY-SA 4.0

Body:
div {
 clear: right;
}

Here's a demo:

http://codepen.io/paulcredmond/pen/BWvPNK


问:
MySql Fulltext Search not correct with short words
After many tries and many searches i came to the following query:

```<code>SELECT id,
       title,
       description,
       MATCH(title,description,tags) AGAINST ('$search' IN NATURAL LANGUAGE MODE) AS score
FROM pages
</code>```

I use this query to search inside a large amounts of pages which contain music lessons. It works quite wel. Pages get a score based on how good they match to the query.

Except when the users search for something like "C Chord" or "Am Chord" the first part is ignored. If i search for "A chord" or "E chord" the page called "C chord" is always on top.

So.. Part 1 of my question is: how can i fix that?

Then part 2. Is it possible to give the column "Title" a bigger importance for the score then "Description"?

答:
Question

This has been discussed on SO quite a few times: MySQL's built-in fulltext parser is designed for searching for words, not for single characters and comes with default minimum word length setting of 3 (innodb) or 4 (myisam) These settings mean that no words shorter than 3 or 4 characters get indexed and therefore will not be found by a fulltext search. You may lower the minimum character length limit to 1 and rebuild the index, but it will slow the searching down, since the indexes will be bigger.

Question

It is possible, but you need to search on the title field separately and bump up the relevancy score results from the title field.

You can use union to get a combined list with sum() to sum the score up for any record:

```<code>SELECT p.id, any_value(title), any_value(description), any_value(tags), sum(t.score) as sum_score
FROM
    (SELECT id, (MATCH(title) AGAINST ('$search' IN NATURAL LANGUAGE MODE)) *2 AS score
     FROM pages
     UNION ALL
     SELECT id, MATCH(description,tags) AGAINST ('$search' IN NATURAL LANGUAGE MODE) AS score
     FROM pages) t
INNER JOIN pages p on t.id=p.id
GROUP BY p.id
ORDER BY sum(t.score) DESC
</code>```

You need to adjust the fulltext indexes to be able to do the separate searches.

Body:
After many tries and many searches i came to the following query:

SELECT id,
       title,
       description,
       MATCH(title,description,tags) AGAINST ('$search' IN NATURAL LANGUAGE MODE) AS score
FROM pages

I use this query to search inside a large amounts of pages which contain music lessons. It works quite wel. Pages get a score based on how good they match to the query.

Except when the users search for something like "C Chord" or "Am Chord" the first part is ignored. If i search for "A chord" or "E chord" the page called "C chord" is always on top.

So.. Part 1 of my question is: how can i fix that?

Then part 2. Is it possible to give the column "Title" a bigger importance for the score then "Description"?

Body:
Question

This has been discussed on SO quite a few times: MySQL's built-in fulltext parser is designed for searching for words, not for single characters and comes with default minimum word length setting of 3 (innodb) or 4 (myisam) These settings mean that no words shorter than 3 or 4 characters get indexed and therefore will not be found by a fulltext search. You may lower the minimum character length limit to 1 and rebuild the index, but it will slow the searching down, since the indexes will be bigger.

Question

It is possible, but you need to search on the title field separately and bump up the relevancy score results from the title field.

You can use union to get a combined list with sum() to sum the score up for any record:

SELECT p.id, any_value(title), any_value(description), any_value(tags), sum(t.score) as sum_score
FROM
    (SELECT id, (MATCH(title) AGAINST ('$search' IN NATURAL LANGUAGE MODE)) *2 AS score
     FROM pages
     UNION ALL
     SELECT id, MATCH(description,tags) AGAINST ('$search' IN NATURAL LANGUAGE MODE) AS score
     FROM pages) t
INNER JOIN pages p on t.id=p.id
GROUP BY p.id
ORDER BY sum(t.score) DESC

You need to adjust the fulltext indexes to be able to do the separate searches.


问:
R scripts crontab error about Oracle
I am newer but I real get a question : I have one R script to put in crontab and get one error,but I can run the scripts in commandline.the error is :

Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared object '/usr/lib64/RRO-8.0.1/R-3.1.2/lib64/R/library/ROracle/libs/ROracle.so':
  libclntsh.so.10.1: cannot open shared object file: No such file or directory
Loading required package: plyr
Loading required package: lubridate

Attaching package: 'lubridate'

The following object is masked from 'package:plyr':

    here

Loading required package: mailR
Error: Couldn't find driver Oracle. Looked in:
* global namespace
* in package called Oracle
* in package called ROracle```

some tips will be very thanks

答: i was facing the same error while running in crontab as all env variables are not correctly set when run through crontab. You can either define variables ORACLE_HOME,LD_LIBRARY_PATH,PATH in the crontab before r script or simply use shell wrapper to call the r script. By default all env variables are read and set properly in shell and you can call the r scipt from there.</p>

Title: R scripts crontab error about Oracle

Body:
I am newer but I real get a question : I have one R script to put in crontab and get one error,but I can run the scripts in commandline.the error is :

Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared object '/usr/lib64/RRO-8.0.1/R-3.1.2/lib64/R/library/ROracle/libs/ROracle.so':
  libclntsh.so.10.1: cannot open shared object file: No such file or directory
Loading required package: plyr
Loading required package: lubridate

Attaching package: 'lubridate'

The following object is masked from 'package:plyr':

    here

Loading required package: mailR
Error: Couldn't find driver Oracle. Looked in:
* global namespace
* in package called Oracle
* in package called ROracle

some tips will be very thanks


问:
How can I construct a string to be read as unicode?
I am trying to convert a 4-digit binary string into a hexadecimal digit (0-f), then combine several of these digits into a single Unicode string, that is then printed as a single ASCII character. This requires me to have "\" at the start of each Unicode character, but attempting to add the hexadecimal digits to "\" returns a "SyntaxError: EOL while scanning string literal.

Adding them instead to "\\" avoids the error, but the now formed Unicode string is printed as "\XXX" rather than as a single character.

print "\x3f" returns ?
print "\x3f" returns \x3f

Is there a way to dynamically construct Unicode strings by appending to a string?

Body:
It's not easy to understand what your input and outout should look like, but those function should help you achieve your goal :

>>> "1010"
'1010'
>>> int("1010",2)
10
>>> hex(int("1010",2))
'0xa'
>>> hex(int("1010",2))[2:]
'a'
>>> hex1 = hex(int("1010",2))[2:]
>>> hex2 = hex(int("0101",2))[2:]
>>> hex1+hex2
'a5'
>>> int(hex1+hex2,16)
165
>>> int("1010"+"0101",2)
165
>>> unichr(int(hex1+hex2,16))
u'\xa5'


问:
where is homestead.yaml if i install homestead via vagrant box add?
According to https://laravel.com/docs/5.4/homestead I can install Laravel Homestead by doing vagrant box add laravel/homestead. Installing by cloning the git repo is another way but it's not the only way listed nor is it even the first method listed.

Anyway, the next section of the documentation is Configuring Homestead. It talks about homestead.yaml a lot but idk where that file lives. Maybe there are additional steps in the install process that https://laravel.com/docs/5.4/homestead neglects to mention?

答:
no its not one or the other, but the 2 steps are necessary

install the vagrant box running vagrant box add laravel/homestead

install homestead from cloning the git repo

```<code>$ cd ~
$ git clone https://github.com/laravel/homestead.git Homestead
$ cd Homestead
$ bash init.sh
</code>```

Review the Homestead configuration

open the Homestead.yaml file and check all the configuration

boot the VM once you have configured your homestead file

```<code>$ vagrant up
</code>```

Body:
no its not one or the other, but the 2 steps are necessary

install the vagrant box running vagrant box add laravel/homestead

install homestead from cloning the git repo

$ cd ~
$ git clone https://github.com/laravel/homestead.git Homestead
$ cd Homestead
$ bash init.sh

Review the Homestead configuration

open the Homestead.yaml file and check all the configuration

boot the VM once you have configured your homestead file

$ vagrant up


问:
C++ - Splitting Filename and File Extension
Ok, first of all I don't want to use Boost, or any external libraries. I just want to use the C++ Standard Library. I can easily split strings with a given delimiter with my split() function:

```<code>void split(std::string &string, std::vector<std::string> &tokens, const char &delim) {
    std::string ea;
    std::stringstream stream(string);
    while(getline(stream, ea, delim))
        tokens.push_back(ea);
}
</code>```

I do this on filenames. But there's a problem. There are files that have extensions like: tar.gz, tar.bz2, etc. Also there are some filenames that have extra dots. Some.file.name.tar.gz. I wish to separate Some.file.name and tar.gz Note: The number of dots in a filename isn't constant.

I also tried PathFindExtension but no luck. Is this possible? If so, please enlighten me. Thank you.

Edit: I'm very sorry about not specifying the OS. It's Windows.

答:
There's nothing in the C++ standard library -- that is, it's not in the Standard --, but every operating system I know of provides this functionality in a variety of ways.

In Windows you can use _splitpath(), and in Linux you can use dirname() & basename()

ContentLicense: CC BY-SA 2.5

Body:
Ok, first of all I don't want to use Boost, or any external libraries. I just want to use the C++ Standard Library. I can easily split strings with a given delimiter with my split() function:

void split(std::string &string, std::vector<std::string> &tokens, const char &delim) {
    std::string ea;
    std::stringstream stream(string);
    while(getline(stream, ea, delim))
        tokens.push_back(ea);
}

I do this on filenames. But there's a problem. There are files that have extensions like: tar.gz, tar.bz2, etc. Also there are some filenames that have extra dots. Some.file.name.tar.gz. I wish to separate Some.file.name and tar.gz Note: The number of dots in a filename isn't constant.

I also tried PathFindExtension but no luck. Is this possible? If so, please enlighten me. Thank you.

Edit: I'm very sorry about not specifying the OS. It's Windows.


问:
How do I split file removals into a separate changeset in git
I have a massive git changeset on a local branch. It contains file additions, file modifications and file deletions.

How do I split the file deletions into a separate subsequent changeset? (To make the additions and modifications easier to review.)

(In case it matters, this is git-cinnabar, not plain git.)

答:
Assuming that all your changes are currently unstaged, you can use the powerful ls-files utility:

```<code>git ls-files --deleted | xargs git add
</code>```

Note this assumes that cinnabar doesn't mask this git feature, and that you are using a bash-like shell.

Body:
Assuming that all your changes are currently unstaged, you can use the powerful ls-files utility:

git ls-files --deleted | xargs git add

Note this assumes that cinnabar doesn't mask this git feature, and that you are using a bash-like shell.


问:
SQL Server continue series of inserts from Select statements despite errors(?)
I have a large file of SQL statements that are lined up as follows:

```<code> INSERT INTO [table here]
    SELECT [columns]
    FROM OPENROWSET(xlsx tab 1)

INSERT INTO [table here]
    SELECT [columns]
    FROM OPENROWSET(xlsx tab 2)

... etc etc...
</code>```

The problem is that sometimes XLSX tab #2 (or 22) does not exist and may cause an error and the entire series of statements fails.

Is there a way to get each statement to execute as though they were their own query or ignore the error and continue?

Thanks!

答:
Thinking you want something along these lines.</p>

```<code>begin try
    INSERT INTO [table here]
        SELECT [columns]
        FROM OPENROWSET(xlsx tab 1)
end try
begin catch
    select 'Tab1 errored'
end catch

begin try
    INSERT INTO [table here]
        SELECT [columns]
        FROM OPENROWSET(xlsx tab 2)
end try
begin catch
    select 'Tab2 errored'
end catch
</code>```

Body:
I have a large file of SQL statements that are lined up as follows:

 INSERT INTO [table here]
    SELECT [columns]
    FROM OPENROWSET(xlsx tab 1)

INSERT INTO [table here]
    SELECT [columns]
    FROM OPENROWSET(xlsx tab 2)

... etc etc...

The problem is that sometimes XLSX tab #2 (or 22) does not exist and may cause an error and the entire series of statements fails.

Is there a way to get each statement to execute as though they were their own query or ignore the error and continue?

Thanks!

Body:
Thinking you want something along these lines.

begin try
    INSERT INTO [table here]
        SELECT [columns]
        FROM OPENROWSET(xlsx tab 1)
end try
begin catch
    select 'Tab1 errored'
end catch

begin try
    INSERT INTO [table here]
        SELECT [columns]
        FROM OPENROWSET(xlsx tab 2)
end try
begin catch
    select 'Tab2 errored'
end catch


问:
HTML inside XML CDATA being converted with < and > brackets
I have some sample XML:

```<code><sample><![CDATA[Line 1<br />Line 2<br />Line 3<br />]]></sample>
</code>```

I'm using ASP to output this XML using a stylesheet like so:

```<code>Set xmlHttp = Server.CreateObject("Microsoft.XMLHTTP")
xmlHttp.open "GET", URLxml, false
xmlHttp.send()

Set xslHttp = Server.CreateObject("Microsoft.XMLHTTP")
xslHttp.open "GET", xXsl, false
xslHttp.send()

Set xmlDoc = Server.CreateObject("MICROSOFT.XMLDOM")
Set xslDoc = Server.CreateObject("MICROSOFT.XMLDOM")
xmlDoc.async = false
xslDoc.async = false
xmlDoc.Load xmlHttp.responseXML
xslDoc.Load xslHttp.responseXML

Response.Write xmlDoc.transformNode(xslDoc)
</code>```

However, once this is getting written, the HTML output is showing up as:

```<code>Line 1<br />Line 2<br />Line 3
</code>```

I can see that ASP is converting the brackets in the code, but I'm not sure why.  Any thoughts?

答:
I have some sample XML:

```<code><sample><![CDATA[Line 1<br />Line 2<br />Line 3<br />]]></sample>
</code>```

This is a sample element with a text node child.

Suppose you apply an identity transform. Then the result will be:

```<code><sample>Line 1<br />Line 2<br />Line 3<br /></sample>
</code>```

Why? Because text nodes and attribute values have the special character &, < and > escape as character entities.

EDIT: Of course, you could use DOE... But, besides that it's an optional feature, the result will be a text node no matter what (without the encode character entities). You will need other parser fase (this may be useful when output and encode HTML fragment to a (X)HTML document like in feeds, with the risk of malformed output...).

This stylesheet:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="sample">
        <p>
            <xsl:value-of select="." disable-output-escaping="yes"/>
        </p>
    </xsl:template>
</xsl:stylesheet>
</code>```

Output:

```<code><p>Line 1<br />Line 2<br />Line 3<br /></p>
</code>```

Render as (actual markup):

Line 1
Line 2
Line 3

Body:
I have some sample XML:

<sample><![CDATA[Line 1
Line 2
Line 3
]]></sample>

I'm using ASP to output this XML using a stylesheet like so:

Set xmlHttp = Server.CreateObject("Microsoft.XMLHTTP")
xmlHttp.open "GET", URLxml, false
xmlHttp.send()

Set xslHttp = Server.CreateObject("Microsoft.XMLHTTP")
xslHttp.open "GET", xXsl, false
xslHttp.send()

Set xmlDoc = Server.CreateObject("MICROSOFT.XMLDOM")
Set xslDoc = Server.CreateObject("MICROSOFT.XMLDOM")
xmlDoc.async = false
xslDoc.async = false
xmlDoc.Load xmlHttp.responseXML
xslDoc.Load xslHttp.responseXML

Response.Write xmlDoc.transformNode(xslDoc)

However, once this is getting written, the HTML output is showing up as:

Line 1
Line 2
Line 3

I can see that ASP is converting the brackets in the code, but I'm not sure why.  Any thoughts?

Body:
I have some sample XML:

<sample><![CDATA[Line 1<br />Line 2<br />Line 3<br />]]></sample>

This is a sample element with a text node child.

Suppose you apply an identity transform. Then the result will be:

<sample>Line 1&lt;br /&gt;Line 2&lt;br /&gt;Line 3&lt;br /&gt;</sample>

Why? Because text nodes and attribute values have the special character &, < and > escape as character entities.

EDIT: Of course, you could use DOE... But, besides that it's an optional feature, the result will be a text node no matter what (without the encode character entities). You will need other parser fase (this may be useful when output and encode HTML fragment to a (X)HTML document like in feeds, with the risk of malformed output...).

This stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="sample">
        <p>
            <xsl:value-of select="." disable-output-escaping="yes"/>
        </p>
    </xsl:template>
</xsl:stylesheet>

Output:

<p>Line 1<br />Line 2<br />Line 3<br /></p>

Render as (actual markup):

Line 1
Line 2
Line 3


问:
Author value does not display when not provided
I am trying to create a java program where I have a superclass ReadingMaterial and many different sub classes namely Newspaper, Manga, Novel and TextBook. Now, Readingmaterial has 3 data members and each of the other classes have 2 different data members each.

I am trying to display the String that I am creating like  for example:

```<code>allMat.add(new Newspaper("NewYork_Times"));
</code>```

I want the  "NewYork_Times" and the date, the author to be displayed
can  anyone tell me what I am doing  wrongly?

ps: I am new in JAVA programming

Newspaper class

```<code>public class Newspaper
        extends ReadingMaterial {

    private String title = "BHCC_Newspaper";

    //public Newspaper(){}
    public Newspaper(String title) {
        this.title = title;
    }

    public Newspaper(String title, String author, boolean readingMaterial) {
        super(author, readingMaterial);
        this.title = title;
    }

    //getter
    public String getTitle() {
        return title;
    }

    // setter
    public void setTitle(String title) {
        this.title = title;
    }

    public void displayReadingMaterials() {
        System.out.println(getTitle() + "\n Microsoft recruited 15 students from a community college.\n");
    }
}
</code>```

this is the superclass

```<code>public class ReadingMaterial implements Comparable {

    private String author = "Lydie";
    private boolean readingMaterial;
    private java.util.Date dateCreated;

    // no-arg constructor
    public ReadingMaterial() {
        dateCreated = new java.util.Date();
    }
    // arg constructor

    public ReadingMaterial(String author, boolean readingMaterial) {
        dateCreated = new java.util.Date();
        this.author = author;
        this.readingMaterial = readingMaterial;
    }
    // getters

    public String getAuthor() {
        return author;
    }

    public java.util.Date getDateCreated() {
        return dateCreated;
    }

    public boolean getReadingMaterial() {
        return readingMaterial;
    }
    // setters

    public void setAuthor(String author) {
        this.author = author;
    }

    public void setReadingMaterial(boolean readingMaterial) {
        this.readingMaterial = readingMaterial;
    }

    public void displayReadingMaterials() {
        System.out.println("Written on " + getDateCreated() + " by " + getAuthor()
                + " on all ReadingMaterial: " + getReadingMaterial());
    }

//Comparator for sorting the list
     public static  Comparator <ReadingMaterial> testCompare = new Comparator <ReadingMaterial>(){

             public int compare(ReadingMaterial readMat1, ReadingMaterial readMat2){

             return (int) (readMat1.getAuthor().compareTo(readMat2.getAuthor()));
             }
     };
    @Override
    public String toString() {
        return "Written on " + dateCreated + " by " + author
                + " on all ReadingMaterial: " + readingMaterial;
    }

    @Override
    public int compareTo(Object t) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}
</code>```

and this is the main

```<code>package readingmaterial;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.Collections;

public class ReadingFactory {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // create and initialize a newspaper, a manga, a textbook and a novel

        List<ReadingMaterial> allMat = new ArrayList<ReadingMaterial>();
        allMat.add(new Newspaper("NewYork_Times"));
        allMat.add(new Manga("Naruto"));
        allMat.add(new TextBook("Bible"));
        allMat.add(new Novel("Argonauts"));
        //Iterator<ReadingMaterial> readMat = all.iterator();

        System.out.println("ArrayList elements after sorting in ascending order : ");

       Collections.sort(allMat, ReadingMaterial.testCompare);

       for(ReadingMaterial str: allMat){
            System.out.println(str);

        //ReadingMaterial[] allMat={newspaper,manga,textbook,novel};
        //for(int i=0;i<4;i++){
          //   allMat[i].displayReadingMaterials();
        // }
    }
    // this method show the polymorphic call and display any reading material

}
</code>```

答:
The problem is that when you are doing new Newspaper("NewYork_Times") you are using the default super constructor, with no args, which means author is not set.

therefore, you are getting null pointer on your comparator (getAuthor returns null):

```<code>readMat1.getAuthor().compareTo(readMat2.getAuthor())
</code>```

You should:

1. add null check to your comparator

2. if you count on author for comparing, you can't allow it to be null. either don't have constructor without it, or set a default value (like you do with the date)

Body:
I am trying to create a java program where I have a superclass ReadingMaterial and many different sub classes namely Newspaper, Manga, Novel and TextBook. Now, Readingmaterial has 3 data members and each of the other classes have 2 different data members each.

I am trying to display the String that I am creating like  for example:

allMat.add(new Newspaper("NewYork_Times"));

I want the  "NewYork_Times" and the date, the author to be displayed
can  anyone tell me what I am doing  wrongly?

ps: I am new in JAVA programming

Newspaper class

public class Newspaper
        extends ReadingMaterial {

    private String title = "BHCC_Newspaper";

    //public Newspaper(){}
    public Newspaper(String title) {
        this.title = title;
    }

    public Newspaper(String title, String author, boolean readingMaterial) {
        super(author, readingMaterial);
        this.title = title;
    }

    //getter
    public String getTitle() {
        return title;
    }

    // setter
    public void setTitle(String title) {
        this.title = title;
    }

    public void displayReadingMaterials() {
        System.out.println(getTitle() + "\n Microsoft recruited 15 students from a community college.\n");
    }
}

this is the superclass

public class ReadingMaterial implements Comparable {

    private String author = "Lydie";
    private boolean readingMaterial;
    private java.util.Date dateCreated;

    // no-arg constructor
    public ReadingMaterial() {
        dateCreated = new java.util.Date();
    }
    // arg constructor

    public ReadingMaterial(String author, boolean readingMaterial) {
        dateCreated = new java.util.Date();
        this.author = author;
        this.readingMaterial = readingMaterial;
    }
    // getters

    public String getAuthor() {
        return author;
    }

    public java.util.Date getDateCreated() {
        return dateCreated;
    }

    public boolean getReadingMaterial() {
        return readingMaterial;
    }
    // setters

    public void setAuthor(String author) {
        this.author = author;
    }

    public void setReadingMaterial(boolean readingMaterial) {
        this.readingMaterial = readingMaterial;
    }

    public void displayReadingMaterials() {
        System.out.println("Written on " + getDateCreated() + " by " + getAuthor()
                + " on all ReadingMaterial: " + getReadingMaterial());
    }

//Comparator for sorting the list
     public static  Comparator <ReadingMaterial> testCompare = new Comparator <ReadingMaterial>(){

             public int compare(ReadingMaterial readMat1, ReadingMaterial readMat2){

             return (int) (readMat1.getAuthor().compareTo(readMat2.getAuthor()));
             }
     };
    @Override
    public String toString() {
        return "Written on " + dateCreated + " by " + author
                + " on all ReadingMaterial: " + readingMaterial;
    }

    @Override
    public int compareTo(Object t) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

and this is the main

package readingmaterial;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.Collections;

public class ReadingFactory {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // create and initialize a newspaper, a manga, a textbook and a novel

        List<ReadingMaterial> allMat = new ArrayList<ReadingMaterial>();
        allMat.add(new Newspaper("NewYork_Times"));
        allMat.add(new Manga("Naruto"));
        allMat.add(new TextBook("Bible"));
        allMat.add(new Novel("Argonauts"));
        //Iterator<ReadingMaterial> readMat = all.iterator();

        System.out.println("ArrayList elements after sorting in ascending order : ");

       Collections.sort(allMat, ReadingMaterial.testCompare);

       for(ReadingMaterial str: allMat){
            System.out.println(str);

        //ReadingMaterial[] allMat={newspaper,manga,textbook,novel};
        //for(int i=0;i<4;i++){
          //   allMat[i].displayReadingMaterials();
        // }
    }
    // this method show the polymorphic call and display any reading material

}

Body:
The problem is that when you are doing new Newspaper("NewYork_Times") you are using the default super constructor, with no args, which means author is not set.

therefore, you are getting null pointer on your comparator (getAuthor returns null):

readMat1.getAuthor().compareTo(readMat2.getAuthor())

You should:

1. add null check to your comparator

2. if you count on author for comparing, you can't allow it to be null. either don't have constructor without it, or set a default value (like you do with the date)


问:
Get the updated html content of asp:Literal or div in server side when modified by jquery
I currently have an series of html code that pass to the literal asp control.

```<code>Labelhighlight.Text = <strong>foo sample</strong>;
</code>```

On my View here are my controls used

```<code><div id="highlightedtext" class="well" runat="server">
  <asp:Literal ID="Labelhighlight" runat="server" Mode="PassThrough">
  </asp:Literal>
  </asp:Label>
</div>
</code>```

then on my client side I wrapped a string using jquery that results to

```<code><div id="highlightedtext" class="well">
  <string>foo <span id='test'>sample</span> </strong>
</div>
</code>```

then on my server side I should get the updated html content on button click
here's the code behind:

```<code>protected void btnSave_Click(object sender, EventArgs e)
{
  var test = RenderControl(Labelhighlight);
}

public string RenderControl(System.Web.UI.Control ctrl)
{
  StringBuilder sb = new StringBuilder();
  StringWriter tw = new StringWriter(sb);
  HtmlTextWriter hw = new HtmlTextWriter(tw);

  ctrl.RenderControl(hw);
  return sb.ToString();
}
</code>```

I only  get the previous html string which is foo sample. I also tried getting the html content of div but the following error occur: Cannot get inner content of because the contents are not literal.

答:
I found a way to save the content to a hidden div without using runat="server" then get the content in my server side using request form, code as follows:

```<code><input type="hidden" id="div_content" name="div_content" />
</code>```

then on my jquery

```<code>   function SaveToHidden() {

                     var content = document.getElementById("highlightedtext").innerHTML;

                     document.getElementById("div_content").value = content;
                 };
    </script>
</code>```

Body:
I currently have an series of html code that pass to the literal asp control.

Labelhighlight.Text = foo sample;

On my View here are my controls used

  <asp:Literal ID="Labelhighlight" runat="server" Mode="PassThrough">
  </asp:Literal>
  </asp:Label>

then on my client side I wrapped a string using jquery that results to

  <string>foo sample

then on my server side I should get the updated html content on button click
here's the code behind:

protected void btnSave_Click(object sender, EventArgs e)
{
  var test = RenderControl(Labelhighlight);
}

public string RenderControl(System.Web.UI.Control ctrl)
{
  StringBuilder sb = new StringBuilder();
  StringWriter tw = new StringWriter(sb);
  HtmlTextWriter hw = new HtmlTextWriter(tw);

  ctrl.RenderControl(hw);
  return sb.ToString();
}

I only  get the previous html string which is foo sample. I also tried getting the html content of div but the following error occur: Cannot get inner content of because the contents are not literal.

Body:
I found a way to save the content to a hidden div without using runat="server" then get the content in my server side using request form, code as follows:

<input type="hidden" id="div_content" name="div_content" />

then on my jquery

   function SaveToHidden() {

                     var content = document.getElementById("highlightedtext").innerHTML;

                     document.getElementById("div_content").value = content;
                 };
    </script>


问:
Bash Parameter expansion
I am trying to write bash-script with user input. Script gets user input and build find command with data from input(Use parameter if they aren't empty). I was reading about bash expansion from  here and i did something like :

```<code> eval find $USERPATH "${USERNAME:+'-name' \"\$USERNAME\"}" "${USERSIZE:+'-size' \"\$USERSIZE\"}" "${USERDATA:+'-mmin' \"\$USERDATA\"}"
</code>```

It's work great, but i want to search by content, so i need add

```<code>-exec fgrep -l $USERCONTENT {} \;;
</code>```

but i can't. I was trying something like this

```<code> "${USERCONTENT:+'-exec fgrep -l' \"\$USERCONTENT {}\;;'\"}"
</code>```

but it doesn't work. I don't know how i can do this in good way.

答:
It is far simpler to collect the arguments in an array.</p>

```<code>find_args=( "$USERPATH" )
[[ -n "$USERNAME" ]] && find_args+=(-name "$USERNAME")
[[ -n "$USERSIZE" ]] && find_args+=(-size "$USERSIZE")
[[ -n "$USERDATA" ]] && find_args+=(-mmin "$USERDATA")
[[ -n "$USERCONTENT" ]] && find_args+=(-exec fgrep -l "$USERCONTENT" {} \;)
find "${find_args[@]}"
</code>```

Title: Bash Parameter expansion

Body:
I am trying to write bash-script with user input. Script gets user input and build find command with data from input(Use parameter if they aren't empty). I was reading about bash expansion from  here and i did something like :

 eval find $USERPATH "${USERNAME:+'-name' \"\$USERNAME\"}" "${USERSIZE:+'-size' \"\$USERSIZE\"}" "${USERDATA:+'-mmin' \"\$USERDATA\"}"

It's work great, but i want to search by content, so i need add

-exec fgrep -l $USERCONTENT {} \;;

but i can't. I was trying something like this

 "${USERCONTENT:+'-exec fgrep -l' \"\$USERCONTENT {}\;;'\"}"

but it doesn't work. I don't know how i can do this in good way.

Body:
It is far simpler to collect the arguments in an array.

find_args=( "$USERPATH" )
[[ -n "$USERNAME" ]] && find_args+=(-name "$USERNAME")
[[ -n "$USERSIZE" ]] && find_args+=(-size "$USERSIZE")
[[ -n "$USERDATA" ]] && find_args+=(-mmin "$USERDATA")
[[ -n "$USERCONTENT" ]] && find_args+=(-exec fgrep -l "$USERCONTENT" {} \;)
find "${find_args[@]}"


问:
Lookup shell variables by name, indirectly
Let's say I have a variable's name stored in another variable:

```<code>myvar=123
varname=myvar
</code>```

Now, I'd like to get 123 by just using $varname variable.
Is there a direct way for that? I found no such bash builtin for lookup by name, so came up with this:

```<code>function var { v="\$$1"; eval "echo "$v; }
</code>```

so

```<code>var $varname  # gives 123
</code>```

Which doesn't look too bad in the end, but I'm wondering if I missed something more obvious.

答:
```<code># bmuSetIndirectVar()
# TO DOUBLE CHECK THIS COMMENT AND DEMO
# This function is an helper to read indirect variables.
# i.e. get the content of a variable whose name is saved
# within an other variable. Like:
# MYDIR="/tmp"
# WHICHDIR="MYDIR"
#       bmuSetIndirectVar "WHICHDIR" "$MYDIR"
#
bmuSetIndirectVar(){
    tmpVarName=$1
    locVarName=$1
    extVarName=$2
    #echo "debug Ind Input >$1< >$2<"
    eval tmpVarName=\$$extVarName
    #echo "debug Ind Output >$tmpVarName< >$extVarName<"
    export $locVarName="${tmpVarName}"
}
</code>```

I am currently using this little function. I am not fully happy with it, and I have seen different solutions on the web (if I could recall I would write them here), but it seems to work. Within these few lines there is already some redundancy and extra data but it was helpful for debugging.

If you want to see it in place, i.e. where I am using it, check:
https://github.com/mariotti/bmu/blob/master/bin/backmeup.shellfunctions.sh

Of course it is not the best solution, but made me going on with the work, in
the hope I can replace it with something a bit more general soon.

Body:
Let's say I have a variable's name stored in another variable:

myvar=123
varname=myvar

Now, I'd like to get 123 by just using $varname variable.
Is there a direct way for that? I found no such bash builtin for lookup by name, so came up with this:

function var { v="\$$1"; eval "echo "$v; }

so

var $varname  # gives 123

Which doesn't look too bad in the end, but I'm wondering if I missed something more obvious.

Body:
# bmuSetIndirectVar()
# TO DOUBLE CHECK THIS COMMENT AND DEMO
# This function is an helper to read indirect variables.
# i.e. get the content of a variable whose name is saved
# within an other variable. Like:
# MYDIR="/tmp"
# WHICHDIR="MYDIR"
#       bmuSetIndirectVar "WHICHDIR" "$MYDIR"
#
bmuSetIndirectVar(){
    tmpVarName=$1
    locVarName=$1
    extVarName=$2
    #echo "debug Ind Input >$1< >$2<"
    eval tmpVarName=\$$extVarName
    #echo "debug Ind Output >$tmpVarName< >$extVarName<"
    export $locVarName="${tmpVarName}"
}

I am currently using this little function. I am not fully happy with it, and I have seen different solutions on the web (if I could recall I would write them here), but it seems to work. Within these few lines there is already some redundancy and extra data but it was helpful for debugging.

If you want to see it in place, i.e. where I am using it, check:
https://github.com/mariotti/bmu/blob/master/bin/backmeup.shellfunctions.sh

Of course it is not the best solution, but made me going on with the work, in
the hope I can replace it with something a bit more general soon.


问:
How to tell clang to put debug symbol into executable binaries?
My compile command  is in macOS Sierra is

```<code>clang -std=c11 -g -Wall -Werror -fsanitize=address -file.c -o file
</code>```

after it compiles, it also generates an extra file.dSYM file which included all debug symbols. However, when I use WSL or other *nix system it will not generate such file, debug symbols were embedded into executable binaries.
So I just wondering is there a way to do the same in macOS with clang.

答:
When you compile a program in one pass, clang actually runs dsymutil for you, which is responsible for creating the .dSYM file. Thus, the solution to your problem is to compile and link separately, in which case clang won't automatically call dsymutil.

Check this SO question for more details!

Body:
My compile command  is in macOS Sierra is

clang -std=c11 -g -Wall -Werror -fsanitize=address -file.c -o file

after it compiles, it also generates an extra file.dSYM file which included all debug symbols. However, when I use WSL or other *nix system it will not generate such file, debug symbols were embedded into executable binaries.
So I just wondering is there a way to do the same in macOS with clang.


问:
ImageSnapshot for larger images in flex limit on size
I'm loading and displaying a large image say 6000 x 6000 px using an image tag. I wanted to take a snapshot of the image. But the maximum limit I get is 2880 px dimensions using Flex 4, flash player 10. Didn't the limit of FP 10 increased to 4096 px? Then why am I getting 2880? Is there a way to increase that size. Or any other method you suggest in doing so?

Thanks.

答:
Do note the method signature:
public static function captureImage(source:*, dpi:Number=0, encoder:IImageEncoder=null, scaleLimited:Boolean=true):ImageSnapshot

So, have you tried:
mySnapshot:ImageSnapshot = ImageSnapshot.captureImage(mySource, 200, mx.graphics.codec.JPEGEncoder, false);

Note the last parameter == false, to disable scaleLimited...


问:
Updating a field based on other fields being changed
If I have several fields containing a currency value and a total field, how do I keep the total up-to-date when any value is changed?

I know that I can use events like ActiveChanged or Changed against individual controls but this becomes laborious when you have a lot of fields and also creates a lot of identical methods which seems inefficient to me.

I know that I can also use a button but this requires more input from the user. I'd like it to be somewhat automated so that the total can be observed as values are entered, or at least when switching to the next field.

Currently it's going to be a lot of code like below.

```<code>private void field1_Changed(object sender, System.EventArgs e)
        {
            calculate();
        }

private void field2_Changed(object sender, System.EventArgs e)
        {
            calculate();
        }
</code>```

答:
If exactly same code needs to be executed then you can create only one event handler and point all them to same event handler

Go to form.designer.cs and change event handlers. For very basic example, 2 text box pointing to same event handlers

```<code>this.textBox1.TextChanged += new System.EventHandler(this.ValueChanged);

this.textBox2.TextChanged += new System.EventHandler(this.ValueChanged);
</code>```

In form.cs

```<code>private void ValueChanged(object sender, EventArgs e)
{
            this.label1.Text = (int.Parse(this.textBox2.Text)
                               + int.Parse(this.textBox1.Text))
                               .ToString();
 }
</code>```

Body:
If I have several fields containing a currency value and a total field, how do I keep the total up-to-date when any value is changed?

I know that I can use events like ActiveChanged or Changed against individual controls but this becomes laborious when you have a lot of fields and also creates a lot of identical methods which seems inefficient to me.

I know that I can also use a button but this requires more input from the user. I'd like it to be somewhat automated so that the total can be observed as values are entered, or at least when switching to the next field.

Currently it's going to be a lot of code like below.

private void field1_Changed(object sender, System.EventArgs e)
        {
            calculate();
        }

private void field2_Changed(object sender, System.EventArgs e)
        {
            calculate();
        }

Body:
If exactly same code needs to be executed then you can create only one event handler and point all them to same event handler

Go to form.designer.cs and change event handlers. For very basic example, 2 text box pointing to same event handlers

this.textBox1.TextChanged += new System.EventHandler(this.ValueChanged);

this.textBox2.TextChanged += new System.EventHandler(this.ValueChanged);

In form.cs

private void ValueChanged(object sender, EventArgs e)
{
            this.label1.Text = (int.Parse(this.textBox2.Text)
                               + int.Parse(this.textBox1.Text))
                               .ToString();
 }


问:
Subsetting list-elements based on conditional
I have the following dataframe

```<code>mydf<- data.frame(c(1,1,3,4,5,6),
                  c(1,1,3,10,20,30),
                  c(1,10,20,20,15,10))
colnames(mydf)<-c( "ID1","ID2", "ID3")
</code>```

Let's count how many instances of mydf$ID1 and mydf$ID2 we have where they appear twice

```<code>tmp<-plyr::ddply(mydf,c("ID1","ID2"),nrow)
tmp<-tmp[tmp$V1==2,]
</code>```

This has the following output (there's two identical instances)

```<code>  ID1 ID2 V1
1   1   1  2
</code>```

Now I want to extract the remaining fields, i.e. ID3, of these two instances:

```<code>asd<-mydf[ (mydf$ID1 %in% tmp$ID1) & (mydf$ID1 %in% tmp$ID2), ]
</code>```

This gives me the following

```<code>  ID1 ID2 ID3
1   1   1   1
2   1   1  10
</code>```

This is exactly as desired and what I wanted, so all good.

However, my real data set doesn't only contain 3 vectors like mydf, but 300. And each vector is not just 6 elements long, but +50.000

When I run the above method on my data, then I get instances of entries that occur not only 2 times, but also 1, 3, 4 and so on. So that means something is wrong.

Is it because the above method cannot be scaled up to large data? Or is it because the method I outlined above is inherently wrong?

Unfortunately, due to the large size of my data, I cannot post it here.

UPDATE: Having a list with 3 vectors was just chosen as an example. In reality my data has many vectors, but I still want to group them based on duplicates of two vectors. An example:

```<code>library(dplyr)

mydf<- data.frame(c(1,  1, 3, 4, 5, 6,0),
                  c(22,22, 3,10,20,30,0),
                  c(2, 10,20,20,15,10,0),
                  c(3, 10,20,20,15,10,0),
                  c(4, 10,20,20,15,10,15),
                  c(5, 99,98,98,97,99,97))
colnames(mydf)<-c( "ID1","ID2", "ID3", "ID4", "ID5", "ID6")

(mydf %>% group_by(ID5, ID6) %>% filter(n()==2))
</code>```

As desired, this produces

```<code>    ID1   ID2   ID3   ID4   ID5   ID6
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     1    22    10    10    10    99
2     3     3    20    20    20    98
3     4    10    20    20    20    98
4     5    20    15    15    15    97
5     6    30    10    10    10    99
6     0     0     0     0    15    97
</code>```

答:
A base R solution is to use ave to calculate the duplicate counts, extract the counts, and subset according to which ones are pairwise duplicates.

```<code>mydf[ave(mydf$ID3, mydf$ID1, mydf$ID2, FUN=length) == 2, ]
  ID1 ID2 ID3
1   1   1   1
2   1   1  10
</code>```

To extend the grouping to many variables, you can replace the explicit listing of ID1 and ID2 with the output of Reduce and interaction like this:

```<code>mydf[ave(mydf$ID3, Reduce(interaction, mydf[-3]), FUN=length) == 2, ]
  ID1 ID2 ID3
1   1   1   1
2   1   1  10
</code>```

Here, Reduce(interaction, mydf[-3]) constructs a factor variable that is the interaction of ID1 and ID2. This will happily take as many vectors as you provide.

Body:
I have the following dataframe

mydf<- data.frame(c(1,1,3,4,5,6),
                  c(1,1,3,10,20,30),
                  c(1,10,20,20,15,10))
colnames(mydf)<-c( "ID1","ID2", "ID3")

Let's count how many instances of mydf$ID1 and mydf$ID2 we have where they appear twice

tmp<-plyr::ddply(mydf,c("ID1","ID2"),nrow)
tmp<-tmp[tmp$V1==2,]

This has the following output (there's two identical instances)

  ID1 ID2 V1
1   1   1  2

Now I want to extract the remaining fields, i.e. ID3, of these two instances:

asd<-mydf[ (mydf$ID1 %in% tmp$ID1) & (mydf$ID1 %in% tmp$ID2), ]

This gives me the following

  ID1 ID2 ID3
1   1   1   1
2   1   1  10

This is exactly as desired and what I wanted, so all good.

However, my real data set doesn't only contain 3 vectors like mydf, but 300. And each vector is not just 6 elements long, but +50.000

When I run the above method on my data, then I get instances of entries that occur not only 2 times, but also 1, 3, 4 and so on. So that means something is wrong.

Is it because the above method cannot be scaled up to large data? Or is it because the method I outlined above is inherently wrong?

Unfortunately, due to the large size of my data, I cannot post it here.

UPDATE: Having a list with 3 vectors was just chosen as an example. In reality my data has many vectors, but I still want to group them based on duplicates of two vectors. An example:

library(dplyr)

mydf<- data.frame(c(1,  1, 3, 4, 5, 6,0),
                  c(22,22, 3,10,20,30,0),
                  c(2, 10,20,20,15,10,0),
                  c(3, 10,20,20,15,10,0),
                  c(4, 10,20,20,15,10,15),
                  c(5, 99,98,98,97,99,97))
colnames(mydf)<-c( "ID1","ID2", "ID3", "ID4", "ID5", "ID6")

(mydf %>% group_by(ID5, ID6) %>% filter(n()==2))

As desired, this produces

    ID1   ID2   ID3   ID4   ID5   ID6
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     1    22    10    10    10    99
2     3     3    20    20    20    98
3     4    10    20    20    20    98
4     5    20    15    15    15    97
5     6    30    10    10    10    99
6     0     0     0     0    15    97

Body:
A base R solution is to use ave to calculate the duplicate counts, extract the counts, and subset according to which ones are pairwise duplicates.

mydf[ave(mydf$ID3, mydf$ID1, mydf$ID2, FUN=length) == 2, ]
  ID1 ID2 ID3
1   1   1   1
2   1   1  10

To extend the grouping to many variables, you can replace the explicit listing of ID1 and ID2 with the output of Reduce and interaction like this:

mydf[ave(mydf$ID3, Reduce(interaction, mydf[-3]), FUN=length) == 2, ]
  ID1 ID2 ID3
1   1   1   1
2   1   1  10

Here, Reduce(interaction, mydf[-3]) constructs a factor variable that is the interaction of ID1 and ID2. This will happily take as many vectors as you provide.


问:
Schema.org for ranking of compared web sites for which an account is needed
I have a website providing a ranking (based on reviews) of other websites that require a membership to access them (ex. Online tool requiring a monthly membership).

I have 2 question related to this:

Should I use the Product or WebSite entity? At the moment I opted for Product since it has the price attribute and so on.

How can I describe my ranking of website? I'm looking for a kind of ordered list of products (or websites if I have to change that).

答:
With the offers property, you can directly offer the WebSite (or WebApplication, which might be more appropriate in your case). No need for Product.

For the ranking, you have several options:

With the review property you can specify a Review, which can have the reviewRating property to specify a Rating. This allows you to provide specific scores (e.g., in the form of "1.27", "1.28", "2.04" …).

If the rank is the average rating from all reviews, you can use the aggregateRating property to specify an AggregateRating.

With an ItemList you could specify for each entry a ListItem with the position property. This allows you to (implicitly) provide a ranking (i.e., in the form of "1", "2", "3", …).

You could also use both ways (Rating/AggregateRating and ItemList).

Make sure to apply the review/aggregateRating on the correct item: on the Offer if you are ranking the offers, on the WebApplication if you are ranking the apps.


问:
Difference between subset and filter from dplyr
It seems to me that subset and filter (from dplyr) are having the same result.
But my question is: is there at some point a potential difference, for ex. speed, data sizes it can handle etc? Are there occasions that it is better to use one or the other?

Example:

```<code>library(dplyr)

df1<-subset(airquality, Temp>80 & Month > 5)
df2<-filter(airquality, Temp>80 & Month > 5)

summary(df1$Ozone)
# Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's
# 9.00   39.00   64.00   64.51   84.00  168.00      14

summary(df2$Ozone)
# Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's
# 9.00   39.00   64.00   64.51   84.00  168.00      14
</code>```

Body:
It seems to me that subset and filter (from dplyr) are having the same result.
But my question is: is there at some point a potential difference, for ex. speed, data sizes it can handle etc? Are there occasions that it is better to use one or the other?

Example:

library(dplyr)

df1<-subset(airquality, Temp>80 & Month > 5)
df2<-filter(airquality, Temp>80 & Month > 5)

summary(df1$Ozone)
# Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's
# 9.00   39.00   64.00   64.51   84.00  168.00      14

summary(df2$Ozone)
# Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's
# 9.00   39.00   64.00   64.51   84.00  168.00      14

Body:
One additional difference not yet mentioned is that filter discards rownames, while subset doesn't:

filter(mtcars, gear == 5)

  mpg    cyl   disp      hp  drat wt    qsec  vs am   gear carb
1 26.0   4     120.3     91  4.43 2.140 16.7  0  1    5    2
2 30.4   4     95.1      113 3.77 1.513 16.9  1  1    5    2
3 15.8   4     351.0     264 4.22 3.170 14.5  0  1    5    4
4 19.7   4     145.0     175 3.62 2.770 15.5  0  1    5    6
5 15.0   4     301.0     335 3.54 3.570 14.6  0  1    5    8

subset(mtcars, gear == 5)
               mpg    cyl   disp      hp  drat wt    qsec vs  am   gear carb
Porsche 914-2  26.0   4     120.3     91  4.43 2.140 16.7  0  1    5    2
Lotus Europa   30.4   4     95.1      113 3.77 1.513 16.9  1  1    5    2
Ford Pantera L 15.8   4     351.0     264 4.22 3.170 14.5  0  1    5    4
Ferrari Dino   19.7   4     145.0     175 3.62 2.770 15.5  0  1    5    6
Maserati Bora  15.0   4     301.0     335 3.54 3.570 14.6  0  1    5    8


问:
Why this error when I try to create workspaces in ROS?
Whenever I try to create a workspace:

```<code>~/catkin_ws$ catkin_make
</code>```

It shows like this:

```<code>ImportError: "from catkin_pkg.package import parse_package" failed: No module named 'catkin_pkg'
Make sure that you have installed "catkin_pkg", it is up to date and on the PYTHONPATH.
CMake Error at /opt/ros/kinetic/share/catkin/cmake/safe_execute_process.cmake:11 (message):
  execute_process(/home/usuario/miniconda3/bin/python
  "/opt/ros/kinetic/share/catkin/cmake/parse_package_xml.py"
  "/opt/ros/kinetic/share/catkin/cmake/../package.xml"
  "/home/usuario/catkin_ws/build/catkin/catkin_generated/version/package.cmake")
  returned error code 1
Call Stack (most recent call first):
  /opt/ros/kinetic/share/catkin/cmake/catkin_package_xml.cmake:63 (safe_execute_process)
  /opt/ros/kinetic/share/catkin/cmake/all.cmake:151 (_catkin_package_xml)
  /opt/ros/kinetic/share/catkin/cmake/catkinConfig.cmake:20 (include)
  CMakeLists.txt:52 (find_package)

-- Configuring incomplete, errors occurred!
See also "/home/usuario/catkin_ws/build/CMakeFiles/CMakeOutput.log".
See also "/home/usuario/catkin_ws/build/CMakeFiles/CMakeError.log".
Invoking "cmake" failed
</code>```

It seems like there is a problem with catkin_pkg but I dont find the solution

答:
I just installed ROS on Ubuntu 16.04, had the same issue, and fixed it. The location for catkin_pkg is likely not on your PYTHONPATH and needs to be added.

From the error output:

Make sure that you have installed "catkin_pkg", it is up to date and on the PYTHONPATH.

Try locating catkin_pkg and check your PYTHONPATH. catkin_pkg wasn't on my PYTHONPATH (likely due to other program installs), so I added it and ran catkin_make again, this time successfully.

```<code>~/catkin_ws$ locate catkin_pkg
/usr/lib/python2.7/dist-packages/catkin_pkg

~/catkin_ws$ echo $PYTHONPATH
/opt/ros/kinetic/lib/python2.7/dist-packages
</code>```

To append the catkin_pkg dir to PYTHONPATH (for this session):

```<code>~/catkin_ws$ export PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/dist-packages
</code>```

For permanency I appended the catkin_pkg dir to PYTHONPATH in my .bashrc (you might want to backup your .bashrc file first, e.g. cp -p ~/.bashrc ~/.bashrc-ros-catkin.bak).

To do this, edit your ~/.bashrc file (you might need to use sudo to edit this file) and add the following two lines to the end of the file:

```<code># manually added for ROS catkin_make workspace setup
export PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/dist-packages
</code>```

Save the file and run source to update your session:

```<code>~/catkin_ws$ source ~/.bashrc
</code>```

Check your PYTHONPATH again:

```<code>~/catkin_ws$ echo $PYTHONPATH
/opt/ros/kinetic/lib/python2.7/dist-packages:/usr/lib/python2.7/dist-packages
</code>```

Obviously the location of your catkin_pkg files might be different to mine, so use that path instead when appending to $PYTHONPATH above.

Now try running catkin_make again. If you get the same error, paste the output of your catkin_pkg location and PYTHONPATH here.

Cheers,
sb

Body:
Whenever I try to create a workspace:

~/catkin_ws$ catkin_make

It shows like this:

ImportError: "from catkin_pkg.package import parse_package" failed: No module named 'catkin_pkg'
Make sure that you have installed "catkin_pkg", it is up to date and on the PYTHONPATH.
CMake Error at /opt/ros/kinetic/share/catkin/cmake/safe_execute_process.cmake:11 (message):
  execute_process(/home/usuario/miniconda3/bin/python
  "/opt/ros/kinetic/share/catkin/cmake/parse_package_xml.py"
  "/opt/ros/kinetic/share/catkin/cmake/../package.xml"
  "/home/usuario/catkin_ws/build/catkin/catkin_generated/version/package.cmake")
  returned error code 1
Call Stack (most recent call first):
  /opt/ros/kinetic/share/catkin/cmake/catkin_package_xml.cmake:63 (safe_execute_process)
  /opt/ros/kinetic/share/catkin/cmake/all.cmake:151 (_catkin_package_xml)
  /opt/ros/kinetic/share/catkin/cmake/catkinConfig.cmake:20 (include)
  CMakeLists.txt:52 (find_package)

-- Configuring incomplete, errors occurred!
See also "/home/usuario/catkin_ws/build/CMakeFiles/CMakeOutput.log".
See also "/home/usuario/catkin_ws/build/CMakeFiles/CMakeError.log".
Invoking "cmake" failed

It seems like there is a problem with catkin_pkg but I dont find the solution

Body:
I just installed ROS on Ubuntu 16.04, had the same issue, and fixed it. The location for catkin_pkg is likely not on your PYTHONPATH and needs to be added.

From the error output:

Make sure that you have installed "catkin_pkg", it is up to date and on the PYTHONPATH.

Try locating catkin_pkg and check your PYTHONPATH. catkin_pkg wasn't on my PYTHONPATH (likely due to other program installs), so I added it and ran catkin_make again, this time successfully.

~/catkin_ws$ locate catkin_pkg
/usr/lib/python2.7/dist-packages/catkin_pkg

~/catkin_ws$ echo $PYTHONPATH
/opt/ros/kinetic/lib/python2.7/dist-packages

To append the catkin_pkg dir to PYTHONPATH (for this session):

~/catkin_ws$ export PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/dist-packages

For permanency I appended the catkin_pkg dir to PYTHONPATH in my .bashrc (you might want to backup your .bashrc file first, e.g. cp -p ~/.bashrc ~/.bashrc-ros-catkin.bak).

To do this, edit your ~/.bashrc file (you might need to use sudo to edit this file) and add the following two lines to the end of the file:

# manually added for ROS catkin_make workspace setup
export PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/dist-packages

Save the file and run source to update your session:

~/catkin_ws$ source ~/.bashrc

Check your PYTHONPATH again:

~/catkin_ws$ echo $PYTHONPATH
/opt/ros/kinetic/lib/python2.7/dist-packages:/usr/lib/python2.7/dist-packages

Obviously the location of your catkin_pkg files might be different to mine, so use that path instead when appending to $PYTHONPATH above.

Now try running catkin_make again. If you get the same error, paste the output of your catkin_pkg location and PYTHONPATH here.

Cheers,
sb


问:
JavaScript Best Practices: How to implement long-lived apps (one-page web apps)?
Are there any best practices for implementing a long-lived JavaScript app, i.e. a web app that consists of a single page and loads other pages into the content area via AJAX? (Gmail is a good example of this.)

I already read about pro and cons, SEO, performance, etc. (http://stackoverflow.com/questions/1499129/one-page-only-javascript-applications), I'm interested in patterns how to implement this.

I'd like to avoid large frameworks (e.g. Cappuccino, Echo2, SproutCore, Claypool).

How would I manage dynamically loading content while maintaining the #link portion of the URL (for bookmarking)?

Don't get me wrong, I have an idea how to implement this myself, but this problem must have been solved before.

Are there articles on this? Maybe a tiny JavaScript library?

Thanks!
Mark

答: I found JQuery Address http://www.asual.com/jquery/address/ extremely easy to set up. $.address.change() let's you know whenever something was clicked (works with back and forth as well) and you just parse self.location.hash and build your app from there. It seems lighweight enough as well, if you can handle using JQuery.


问:
How to display SPECIFIC laravel validation error in view, not all of them
The problem I am having is I have multiple validation rules on my date of birth field.

```<code>        @if($errors->has('dob'))
            <span id="helpBlock" class="help-block error">
                @foreach($errors->get('dob') as $message)
                    {{ $message }}
                @endforeach
            </span>
            <script>$('#dob').addClass('formError');</script>
        @endif
</code>```

This will print out ALL of the errors.

I only want to print out the 'required' validation rule if it gets triggered, I am handleing the other validation in the front end.

答:
Remove the foreach and do</p>

```<code>{{ $errors->first('dob') }}
</code>```

Body:
The problem I am having is I have multiple validation rules on my date of birth field.

        @if($errors->has('dob'))

                @foreach($errors->get('dob') as $message)
                    {{ $message }}
                @endforeach

        @endif

This will print out ALL of the errors.

I only want to print out the 'required' validation rule if it gets triggered, I am handleing the other validation in the front end.

Body:
Remove the foreach and do

{{ $errors->first('dob') }}


问:
Process delimited text with xslt 1.0
I need to to process a delimited text with xslt that looks like:

```<code>abc@mail;#6896;#def@mail;#7467;#hij@mail
</code>```

The output should be a mailto: link with all addresses and I need to throw away the numbers between them. I am working on Sharepoint, so can only use XSLT 1.0

Edit:
I found this question from about 7 years ago, that is almost the same:
"Regular expression"-style replace in XSLT 1.0
In my case, it doing exactly the opposite: keeping the numbers and throwing out the mail addresses. Can someone help me how to modify the code in the address?
update: as a workaround, I added the delimiter as prefix to my text, and the template works perfect.

答:
This specifically looks for numbers rather than skipping every other item.</p>

```<code>    <xsl:template name="ExtractNumbers">
    <xsl:param name="strInputString"/>

    <xsl:variable name="strCurrent" select="substring-before($strInputString, ';#')" />
    <xsl:variable name="strRemaining" select="substring-after($strInputString, ';#')" />

    <xsl:if test="$strCurrent != ''">
        <xsl:if test="string(number($strCurrent)) != 'NaN'">
            <xsl:value-of select="$strCurrent" />

            <xsl:if test="contains($strRemaining, ';#')">
                <xsl:text>, </xsl:text>
            </xsl:if>
        </xsl:if>

        <xsl:call-template name="ExtractNumbers">
            <xsl:with-param name="strInputString" select="$strRemaining"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>
</code>```

Title: Process delimited text with xslt 1.0

Body:
I need to to process a delimited text with xslt that looks like:

abc@mail;#6896;#def@mail;#7467;#hij@mail

The output should be a mailto: link with all addresses and I need to throw away the numbers between them. I am working on Sharepoint, so can only use XSLT 1.0

Edit:
I found this question from about 7 years ago, that is almost the same:
"Regular expression"-style replace in XSLT 1.0
In my case, it doing exactly the opposite: keeping the numbers and throwing out the mail addresses. Can someone help me how to modify the code in the address?
update: as a workaround, I added the delimiter as prefix to my text, and the template works perfect.

Body:
This specifically looks for numbers rather than skipping every other item.

    <xsl:template name="ExtractNumbers">
    <xsl:param name="strInputString"/>

    <xsl:variable name="strCurrent" select="substring-before($strInputString, ';#')" />
    <xsl:variable name="strRemaining" select="substring-after($strInputString, ';#')" />

    <xsl:if test="$strCurrent != ''">
        <xsl:if test="string(number($strCurrent)) != 'NaN'">
            <xsl:value-of select="$strCurrent" />

            <xsl:if test="contains($strRemaining, ';#')">
                <xsl:text>, </xsl:text>
            </xsl:if>
        </xsl:if>

        <xsl:call-template name="ExtractNumbers">
            <xsl:with-param name="strInputString" select="$strRemaining"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>


问:
Postgresql Text Fields get '' when they are nulls
I have a table called art_movimientos

```<code>CREATE TABLE public.art_movimientos
(
  cmovimiento bigint NOT NULL DEFAULT nextval('art_movimientos_cmovimiento_seq'::regclass),
  tipo character varying(3) NOT NULL, -- Tipos de Valores:...
  fecha_mov timestamp without time zone NOT NULL,
  documento integer NOT NULL,
  control integer,
  fecha_doc timestamp without time zone NOT NULL,
  corden integer NOT NULL DEFAULT 0,
  calmacen integer NOT NULL,
  calmacen2 integer,
  status character varying(13) NOT NULL DEFAULT 'PENDIENTE'::bpchar, -- PENDIENTE...
  donado integer NOT NULL DEFAULT 0,
  monto_mov numeric(11,2) NOT NULL DEFAULT 0.00,
  monto_desc numeric(11,2) NOT NULL DEFAULT 0.00,
  monto_total numeric(11,2) NOT NULL DEFAULT 0.00,
  observacion text,
  casiento integer,
  crea_user character varying(25),
  crea_date timestamp without time zone,
  mod_user character varying(25),
  mod_date timestamp without time zone,
  cproveedor integer NOT NULL DEFAULT 0,
  CONSTRAINT pk_cmovimiento_art_movimientos PRIMARY KEY (cmovimiento)
  USING INDEX TABLESPACE sistema_index,
  CONSTRAINT fk_calmacen_art_movimientos FOREIGN KEY (calmacen)
      REFERENCES public.almacen (calmacen) MATCH SIMPLE
      ON UPDATE RESTRICT ON DELETE RESTRICT,
  CONSTRAINT ck_donado_art_movimientos CHECK (donado = ANY (ARRAY[0, 1])),
  CONSTRAINT ck_monto_total_art_movimientos CHECK (monto_total > 0::numeric AND monto_total >= monto_mov),
  CONSTRAINT ck_status_art_movimientos CHECK (status::text = ANY (ARRAY['PENDIENTE'::character varying, 'PROCESADO'::character varying, 'APROBADO'::character varying, 'CONTABILIZADO'::character varying]::text[])),
  CONSTRAINT ck_tipo_art_movimientos CHECK (tipo::text = ANY (ARRAY['AJE'::character varying, 'AJS'::character varying, 'SI'::character varying, 'CSM'::character varying, 'COI'::character varying, 'COM'::character varying, 'DEV'::character varying, 'TRF'::character varying]::text[]))
)
WITH (
  OIDS=FALSE
);
</code>```

The Controller get the data and it convert in array to pass to the class:

```<code>...
$_obs =$_POST['observacion']<>'' ? strtoupper($_POST['observacion']) : $_POST['observacion'];
....
array_push($values, $_obs);
...
$mov_dat = $mov->new_mov($values);
</code>```

The DB Class have the function, it call another function and return the result:

```<code>    public function new_mov($array){
            return $mov = $this->db->procedure("insert_art_mov",$array);
        }
...
public function procedure($procedure=false,$rows=false){
        $response=array();
        if($procedure==false){
            $response="Query is Empty!";
        }else{
            $sql = "SELECT ".$procedure."(";
            for ($i=1; $i<=count($rows); $i++){
                $sql .= "$".$i.",";
            }
            $sql = substr($sql,0,-1);
            $sql .= ")";
            //echo $sql;
            $res = pg_prepare($this->linkid, "my_query", $sql);
            $res = @pg_execute($this->linkid, "my_query", $rows);
            if($res){
                while($consF=pg_fetch_assoc($res))
                    array_push($response,$consF[$procedure]);
            }else{
                array_push($response,"ERROR");
                array_push($response,$this->validateOperation());
            }
            $sql = sprintf('DEALLOCATE "%s"',pg_escape_string("my_query"));
             if(!pg_query($sql)) {
                die("Can't query '$sql': " . pg_last_error());
             }
            return $response;
        }
    }
</code>```

Then i execute the Procedure in the DB:

```<code>CREATE OR REPLACE FUNCTION public.insert_art_mov(...IN _observacion text,..)
INSERT INTO art_movimientos(tipo,fecha_mov,documento,control,fecha_doc,corden,cproveedor,calmacen,status,donado,monto_mov,monto_desc,monto_total,observacion,crea_user)
            VALUES(_tipo,NOW(),_documento,_control,_fecha_doc,_corden,_cprov,_calmacen,'PENDIENTE',_donado,MONTO_MOV,_monto_desc,MONTO_TOT,_observacion,_crea_user) RETURNING cmovimiento INTO new_cmov;
</code>```

But in the table in observacion i see '' (simple cuotes) and i wanna know why?

答:
You will get those single quotes because you do not check for empty strings. What I would recommend and I do this as well is that for every string field pass it to a function to return either data or NULL.

DICLAIMER: Half answer but mostly a guide :)

For the backend, you can try the below function when there is a string that needs to be added:

```<code>function chech_string ($str) {
    return (0 != strlen($str)) ? $str : NULL;
}
</code>```

Or you create your sql string as follow

```<code>$sql = "INSERT INTO table(col1, col2) VALUES (';

if (0 != strlen($str1))
    $sql .= "'$str1'";
else
    $sql .= "NULL";

if (0 != strlen($str2))
    $sql .= "'$str2'";
else
    $sql .= "NULL";

    $sql .= ')';
</code>```

At the end your string would look like

```<code>$sql = "INSERT INTO table(col1, col2) VALUES ('STR1', 'STR2')";
OR
$sql = "INSERT INTO table(col1, col2) VALUES ('STR1', NULL)";
</code>```

So you can use this mething to create you procedure as well

For the front end:

```<code><input type="text" value="<?php echo (0 != strlen($col_val)) ? $col_val : '' ?>"/>
</code>```

that will give you the result you need in the front end

Body:
I have a table called art_movimientos

CREATE TABLE public.art_movimientos
(
  cmovimiento bigint NOT NULL DEFAULT nextval('art_movimientos_cmovimiento_seq'::regclass),
  tipo character varying(3) NOT NULL, -- Tipos de Valores:...
  fecha_mov timestamp without time zone NOT NULL,
  documento integer NOT NULL,
  control integer,
  fecha_doc timestamp without time zone NOT NULL,
  corden integer NOT NULL DEFAULT 0,
  calmacen integer NOT NULL,
  calmacen2 integer,
  status character varying(13) NOT NULL DEFAULT 'PENDIENTE'::bpchar, -- PENDIENTE...
  donado integer NOT NULL DEFAULT 0,
  monto_mov numeric(11,2) NOT NULL DEFAULT 0.00,
  monto_desc numeric(11,2) NOT NULL DEFAULT 0.00,
  monto_total numeric(11,2) NOT NULL DEFAULT 0.00,
  observacion text,
  casiento integer,
  crea_user character varying(25),
  crea_date timestamp without time zone,
  mod_user character varying(25),
  mod_date timestamp without time zone,
  cproveedor integer NOT NULL DEFAULT 0,
  CONSTRAINT pk_cmovimiento_art_movimientos PRIMARY KEY (cmovimiento)
  USING INDEX TABLESPACE sistema_index,
  CONSTRAINT fk_calmacen_art_movimientos FOREIGN KEY (calmacen)
      REFERENCES public.almacen (calmacen) MATCH SIMPLE
      ON UPDATE RESTRICT ON DELETE RESTRICT,
  CONSTRAINT ck_donado_art_movimientos CHECK (donado = ANY (ARRAY[0, 1])),
  CONSTRAINT ck_monto_total_art_movimientos CHECK (monto_total > 0::numeric AND monto_total >= monto_mov),
  CONSTRAINT ck_status_art_movimientos CHECK (status::text = ANY (ARRAY['PENDIENTE'::character varying, 'PROCESADO'::character varying, 'APROBADO'::character varying, 'CONTABILIZADO'::character varying]::text[])),
  CONSTRAINT ck_tipo_art_movimientos CHECK (tipo::text = ANY (ARRAY['AJE'::character varying, 'AJS'::character varying, 'SI'::character varying, 'CSM'::character varying, 'COI'::character varying, 'COM'::character varying, 'DEV'::character varying, 'TRF'::character varying]::text[]))
)
WITH (
  OIDS=FALSE
);

The Controller get the data and it convert in array to pass to the class:

...
$_obs =$_POST['observacion']<>'' ? strtoupper($_POST['observacion']) : $_POST['observacion'];
....
array_push($values, $_obs);
...
$mov_dat = $mov->new_mov($values);

The DB Class have the function, it call another function and return the result:

    public function new_mov($array){
            return $mov = $this->db->procedure("insert_art_mov",$array);
        }
...
public function procedure($procedure=false,$rows=false){
        $response=array();
        if($procedure==false){
            $response="Query is Empty!";
        }else{
            $sql = "SELECT ".$procedure."(";
            for ($i=1; $i<=count($rows); $i++){
                $sql .= "$".$i.",";
            }
            $sql = substr($sql,0,-1);
            $sql .= ")";
            //echo $sql;
            $res = pg_prepare($this->linkid, "my_query", $sql);
            $res = @pg_execute($this->linkid, "my_query", $rows);
            if($res){
                while($consF=pg_fetch_assoc($res))
                    array_push($response,$consF[$procedure]);
            }else{
                array_push($response,"ERROR");
                array_push($response,$this->validateOperation());
            }
            $sql = sprintf('DEALLOCATE "%s"',pg_escape_string("my_query"));
             if(!pg_query($sql)) {
                die("Can't query '$sql': " . pg_last_error());
             }
            return $response;
        }
    }

Then i execute the Procedure in the DB:

CREATE OR REPLACE FUNCTION public.insert_art_mov(...IN _observacion text,..)
INSERT INTO art_movimientos(tipo,fecha_mov,documento,control,fecha_doc,corden,cproveedor,calmacen,status,donado,monto_mov,monto_desc,monto_total,observacion,crea_user)
            VALUES(_tipo,NOW(),_documento,_control,_fecha_doc,_corden,_cprov,_calmacen,'PENDIENTE',_donado,MONTO_MOV,_monto_desc,MONTO_TOT,_observacion,_crea_user) RETURNING cmovimiento INTO new_cmov;

But in the table in observacion i see '' (simple cuotes) and i wanna know why?

Body:
You will get those single quotes because you do not check for empty strings. What I would recommend and I do this as well is that for every string field pass it to a function to return either data or NULL.

DICLAIMER: Half answer but mostly a guide :)

For the backend, you can try the below function when there is a string that needs to be added:

function chech_string ($str) {
    return (0 != strlen($str)) ? $str : NULL;
}

Or you create your sql string as follow

$sql = "INSERT INTO table(col1, col2) VALUES (';

if (0 != strlen($str1))
    $sql .= "'$str1'";
else
    $sql .= "NULL";

if (0 != strlen($str2))
    $sql .= "'$str2'";
else
    $sql .= "NULL";

    $sql .= ')';

At the end your string would look like

$sql = "INSERT INTO table(col1, col2) VALUES ('STR1', 'STR2')";
OR
$sql = "INSERT INTO table(col1, col2) VALUES ('STR1', NULL)";

So you can use this mething to create you procedure as well

For the front end:

<input type="text" value="<?php echo (0 != strlen($col_val)) ? $col_val : '' ?>"/>

that will give you the result you need in the front end


问:
Google cloud storage options for small blobs
We have about 10 millions of small files - blobs, most of them around 1-2kB, some around 100kB and a very few above 1MB, total size 50GB. They have unique integer id - key from MySQL database. They will be always accessed by the key, never searched. Access time for one blob should be to 50ms. But we want to archive them occasionally, or do some bulk deletes or updates. I need to choose the proper storage option in the Google Cloud:

Storage - natural choice for blobs. But cannot do well archive and restore large number of objects - no bulk download/upload operations.

Datastore - is suitable as a blob store? But has limit 1MB per entity.

CloudSQL - is suitable as blob store?

BigTable - too expensive :-)

Custom file server - NFS, Gluster, ...

Custom NoSQL? Also an option, but we would prefer hosted Google solution.

Other?

答:
You are going to be slightly limited on Google Cloud Platform options based on your requirements.

The ideal approach would be to use data store but yes they have size limitations for entities. CloudSQL is an option however it is really designed for transactions and therefore comes with a larger cost of running it.

I would therefore say - you would need to either use CloudSQL or have your own storage setup on an instance until they look to increase limits.


问:
How to make a masonry layout grid in bootstrap 3?
I am using boostrap to make a masonry layout. But I am having a problem. As you can see in my code, I have 5 divs. I want Div 4 and 5 to move up(check the attached image) but I have no idea how to do it. I can do it with margin-top but it will break the responsive layout. So, what's the possible solution for this? I am a newbie, it will be a great help. Thanks in advance.

```<code><html>
<head>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">
    <style>
        .div1{
            border: 2px solid;
        }
        .div2{
            border: 2px solid;
        }
        .div3{
            border: 2px solid;
            height: 100px;
        }
        .div4{
            border: 2px solid;
        }
        .div5{
            border: 2px solid;
            height: 40px;
        }
    </style>
</head>
<body>
    <div class="col-md-12">
        <div class="col-md-4 div1">Div1</div>
        <div class="col-md-4 div2">Div2</div>
        <div class="col-md-4 div3">Div3</div>
        <div class="col-md-8 div4">Div4</div>
        <div class="col-md-8 div5">Div5</div>
    </div>
<!-- Loading minified js. jQuery and Bootstrap -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>
</html>
</code>```

The current layout is:

But I want it like this:

答:
you can do it this way:

// external js: masonry.pkgd.js

$('.grid').masonry({
  itemSelector: '.grid-item',
  columnWidth: '.grid-sizer',
  percentPosition: true
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">
  <style>
    .div1{
            border: 2px solid;
          height: 40px;
        }
        .div2{
            border: 2px solid;
          height: 40px;
        }
        .div3{
            border: 2px solid;
            height: 100px;
        }
        .div4{
            border: 2px solid;
          height: 40px;
        }
        .div5{
            border: 2px solid;
            height: 40px;
        }
  </style>
</head>

<body>
  <div class="col-md-12">
    <div class="container-fluid">
      <!-- add extra container element for Masonry -->
      <div class="grid">
        <div class="grid-sizer col-xs-4"></div>
        <div class="grid-item col-xs-4 div1"></div>
        <div class="grid-item col-xs-4 div2"></div>
        <div class="grid-item col-xs-4 div3"></div>
        <div class="grid-item col-xs-8 div4"></div>
        <div class="grid-item col-xs-8 div5"></div>
      </div>
    </div>
  </div>

  <!-- Loading minified js. jQuery and Bootstrap -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="http://masonry.desandro.com/masonry.pkgd.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>

</html></code>```

Body:
I am using boostrap to make a masonry layout. But I am having a problem. As you can see in my code, I have 5 divs. I want Div 4 and 5 to move up(check the attached image) but I have no idea how to do it. I can do it with margin-top but it will break the responsive layout. So, what's the possible solution for this? I am a newbie, it will be a great help. Thanks in advance.

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">

Div1

Div2

Div3

Div4

Div5

The current layout is:

But I want it like this:

Body:
you can do it this way:

// external js: masonry.pkgd.js

$('.grid').masonry({
  itemSelector: '.grid-item',
  columnWidth: '.grid-sizer',
  percentPosition: true
});

<html>

<head>
  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">
  <style>
    .div1{
            border: 2px solid;
          height: 40px;
        }
        .div2{
            border: 2px solid;
          height: 40px;
        }
        .div3{
            border: 2px solid;
            height: 100px;
        }
        .div4{
            border: 2px solid;
          height: 40px;
        }
        .div5{
            border: 2px solid;
            height: 40px;
        }
  </style>
</head>

<body>
  <div class="col-md-12">
    <div class="container-fluid">
      <!-- add extra container element for Masonry -->
      <div class="grid">
        <div class="grid-sizer col-xs-4"></div>
        <div class="grid-item col-xs-4 div1"></div>
        <div class="grid-item col-xs-4 div2"></div>
        <div class="grid-item col-xs-4 div3"></div>
        <div class="grid-item col-xs-8 div4"></div>
        <div class="grid-item col-xs-8 div5"></div>
      </div>
    </div>
  </div>

  <!-- Loading minified js. jQuery and Bootstrap -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="http://masonry.desandro.com/masonry.pkgd.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>

</html>


问:
Split a file name and only take one part for use
I have a $value such as 22214-HAV.jpg or 22214 HAV.jpg (notice no dash)

I want to run a quick function to pull only the number from filename.

答:
You can use explode for this </p>

```<code>   //for '-'
            list($reqval)=explode('-', $value);
    //for space
            list($reqval)=explode(' ', $value);

        echo $reqval
</code>```

Body:
You can use explode for this

   //for '-'
            list($reqval)=explode('-', $value);
    //for space
            list($reqval)=explode(' ', $value);

        echo $reqval


问:
error writing file on remote server in WCF
I'm creating a WCF (C#, VS2010) for my silverlight app, I'm trying to create a file on my remote server (where WCF exists), but I get an unknown error, I just get "Server not found" error in WCF function complete exception message, I use following codes to create a file on my remote server (I use a VDS, so I think I don't have permission problems, I use remote desktop on my server)

```<code>            using (StreamWriter outfile =
            new StreamWriter("mytest.htm"))
            {
                outfile.Write(body);
            }
</code>```

what is going wrong here? is it possible that I have permission problems? I run my WCF on local system and it creates file successfully, but there is no luck when it is uploaded to remote server

should I use Server.MapPath for giving address of my file?

答:
Please use this:</p>

```<code>        System.Net.FileWebRequest request = (System.Net.FileWebRequest)System.Net.FileWebRequest.CreateDefault(new Uri("\\\\remotelocation\\MyText.txt"));
        request.Method = "POST";

        Stream requestStream = request.GetRequestStream();
        byte [] fileContents = Encoding.UTF8.GetBytes("test_content");
        requestStream.Write(fileContents, 0, fileContents.Length);

        requestStream.Close();
</code>```

Body:
I'm creating a WCF (C#, VS2010) for my silverlight app, I'm trying to create a file on my remote server (where WCF exists), but I get an unknown error, I just get "Server not found" error in WCF function complete exception message, I use following codes to create a file on my remote server (I use a VDS, so I think I don't have permission problems, I use remote desktop on my server)

            using (StreamWriter outfile =
            new StreamWriter("mytest.htm"))
            {
                outfile.Write(body);
            }

what is going wrong here? is it possible that I have permission problems? I run my WCF on local system and it creates file successfully, but there is no luck when it is uploaded to remote server

should I use Server.MapPath for giving address of my file?

Body:
Please use this:

        System.Net.FileWebRequest request = (System.Net.FileWebRequest)System.Net.FileWebRequest.CreateDefault(new Uri("\\\\remotelocation\\MyText.txt"));
        request.Method = "POST";

        Stream requestStream = request.GetRequestStream();
        byte [] fileContents = Encoding.UTF8.GetBytes("test_content");
        requestStream.Write(fileContents, 0, fileContents.Length);

        requestStream.Close();


问:
Mocking an abstract method, but not the class constructor
I have a scenario where I have an abstract class similar to the below. I want to mock out the RandomNumberGenerator instance that is supplied via the constructor and I want to write a unit test to test the logic in the doSomethingRandomLotsOfTimes method.

Is there a way I can do this with mockito/another framework?

```<code>public abstract class MyClass {

    private final RandomNumberGenerator randomNumberGenerator;

    public MyClass(RandomNumberGenerator randomNumberGenerator) {
        this.randomNumberGenerator = randomNumberGenerator;
    }

    public abstract void doSomething(int x);

    public void doSomethingRandomLotsOfTimes() {
        for(int i=0; i<10; i++) {
            int r = randomNumberGenerator.next();
            doSomething(r);
        }
    }
}
</code>```

My Test

```<code>@Test
public void testItDoesSomething10Times() {
    // Given
    when(randomNumberGenerator.next()).thenReturn(0);
    MyClass myClass = ...

    // When
    myClass.doSomethingRandomLotsOfTimes();

    // Then
    // Assert Something
}
</code>```

答:
Your class is much more readily implemented via composition:

```<code>public final class MyClass {

    private final RandomNumberGenerator randomNumberGenerator;
    private final IntConsumer somethingDoer;

    public MyClass(
            RandomNumberGenerator randomNumberGenerator,
            IntConsumer somethingDoer) {
        this.randomNumberGenerator = randomNumberGenerator;
        this.somethingDoer = somethingDoer;
    }

    public void doSomethingRandomLotsOfTimes() {
        for(int i=0; i<10; i++) {
            int r = randomNumberGenerator.next();
            somethingDoer.consume(r);
        }
    }
}
</code>```

Now, you can write a unit test to assert that MyClass works, and it calls the somethingDoer the expected number of times; and you can write unit tests to assert that your IntConsumers work.

But you don't have to worry about things like:

The fragile base class problem.

Careless/malicious implementations of MyClass invoking doSomethingRandomLotsOfTimes() from doSomething() (well, maybe you do, it's just a lot harder...)

"Designing and documenting for inheritance"

etc.

Body:
I have a scenario where I have an abstract class similar to the below. I want to mock out the RandomNumberGenerator instance that is supplied via the constructor and I want to write a unit test to test the logic in the doSomethingRandomLotsOfTimes method.

Is there a way I can do this with mockito/another framework?

public abstract class MyClass {

    private final RandomNumberGenerator randomNumberGenerator;

    public MyClass(RandomNumberGenerator randomNumberGenerator) {
        this.randomNumberGenerator = randomNumberGenerator;
    }

    public abstract void doSomething(int x);

    public void doSomethingRandomLotsOfTimes() {
        for(int i=0; i<10; i++) {
            int r = randomNumberGenerator.next();
            doSomething(r);
        }
    }
}

My Test

@Test
public void testItDoesSomething10Times() {
    // Given
    when(randomNumberGenerator.next()).thenReturn(0);
    MyClass myClass = ...

    // When
    myClass.doSomethingRandomLotsOfTimes();

    // Then
    // Assert Something
}

Body:
Your class is much more readily implemented via composition:

public final class MyClass {

    private final RandomNumberGenerator randomNumberGenerator;
    private final IntConsumer somethingDoer;

    public MyClass(
            RandomNumberGenerator randomNumberGenerator,
            IntConsumer somethingDoer) {
        this.randomNumberGenerator = randomNumberGenerator;
        this.somethingDoer = somethingDoer;
    }

    public void doSomethingRandomLotsOfTimes() {
        for(int i=0; i<10; i++) {
            int r = randomNumberGenerator.next();
            somethingDoer.consume(r);
        }
    }
}

Now, you can write a unit test to assert that MyClass works, and it calls the somethingDoer the expected number of times; and you can write unit tests to assert that your IntConsumers work.

But you don't have to worry about things like:

The fragile base class problem.

Careless/malicious implementations of MyClass invoking doSomethingRandomLotsOfTimes() from doSomething() (well, maybe you do, it's just a lot harder...)

"Designing and documenting for inheritance"

etc.


问:
How can I construct a string to be read as unicode?
I am trying to convert a 4-digit binary string into a hexadecimal digit (0-f), then combine several of these digits into a single Unicode string, that is then printed as a single ASCII character. This requires me to have "\" at the start of each Unicode character, but attempting to add the hexadecimal digits to "\" returns a "SyntaxError: EOL while scanning string literal.

Adding them instead to "\\" avoids the error, but the now formed Unicode string is printed as "\XXX" rather than as a single character.

print "\x3f" returns ?
print "\x3f" returns \x3f

Is there a way to dynamically construct Unicode strings by appending to a string?

Body:
Without input and output examples, here's what I could come up with:

# Get our input from somewhere
binaries = [
    "0101", "0100", "0110", "1000", "0110", "0101", "0111", "0010",
    "0110", "0101", "0010", "0000", "0110", "1001", "0111", "0011",
    "0010", "0000", "0110", "1110", "0110", "1111", "0010", "0000",
    "0110", "0011", "0110", "1111", "0111", "0111", "0010", "0000",
    "0110", "1100", "0110", "0101", "0111", "0110", "0110", "0101",
    "0110", "1100"
]

# Convert the binary strings to numbers so we can do math
inters = []
for b in binaries:
    if type(b) is str :
        inters += [ int(b, 2) ]
    else:
        inters += [ b ]

i = 0
outstr = u''
while i < len(inters):
    # "add" the two together using bitwise or to get the
    # ordinal value of the character you're looking for
    b = inters[i] << 4
    b |= inters[i + 1]
    # Make sure the value of b is a valid ASCII character
    if b > 0 and b < 255:
        # append the character that matches value "b"
        outstr += u"{!s}".format(chr(b))
    else:
        # Add a "?" in the case of an illegal character value
        outstr += u"?"
    # increment our counter
    i += 2

print( outstr )
# u'There is no cow level'

Revision

After jsbueno's comments, I think I see what OP is trying to do.  Dealing with multi-byte unicode seems to be tough.  Let's throw a multi-byte character into our string:

sample_string = u'\xa1There is no \xa2\u014fw level!'

# nibbles = [i for s in [[y[0:4], y[4:]] for y in ['{:08b}'.format(x) for x in map(ord, list(sample_string.encode('utf-8')))]] for i in s]

nibbles = [
    '1100', '0010', '1010', '0001', '0101', '0100', '0110', '1000',
    '0110', '0101', '0111', '0010', '0110', '0101', '0010', '0000',
    '0110', '1001', '0111', '0011', '0010', '0000', '0110', '1110',
    '0110', '1111', '0010', '0000', '1100', '0010', '1010', '0010',
    '1100', '0101', '1000', '1111', '0111', '0111', '0010', '0000',
    '0110', '1100', '0110', '0101', '0111', '0110', '0110', '0101',
    '0110', '1100', '0010', '0001'
]

# Make the list of nibbles (4 bits) into a list of bytes (8 bits)
bytelist = [ x[0] + x[1] for x in zip(nibbles[0::2], nibbles[1::2])]

# Make sure the bytelist is half the size of the nibble list:
len(nibbles) == len(bytelist) * 2
# True

# Change each byte in the bytelist into UTF-8 hex codes
hexlist = ['0x{:02x}'.format(int(y, 2)) for y in bytelist]

# create a list of integers from hex string values
intlist = [int(x, 0) for x in hexlist]

# Print it out!
print(''.join(chr(x) for x in intlist))

# Or, you can convert it into unicode:
unistr = unicode(''.join(chr(x) for x in intlist), 'utf-8')
print(unistr)

All this can be compressed to the following:

def decodeNibbles(nibbles):
    if len(nibbles) % 2 != 0:
        raise ValueError('Uneven number of nibbles given')
    unistr = ''.join(
            chr(int('{:s}'.format(y), 2))
            for y in [ x[0] + x[1] for x in zip(nibbles[0::2], nibbles[1::2])]
        )
    return unistr

nibbles = [
    '1100', '0010', '1010', '0001', '0101', '0100', '0110', '1000',
    '0110', '0101', '0111', '0010', '0110', '0101', '0010', '0000',
    '0110', '1001', '0111', '0011', '0010', '0000', '0110', '1110',
    '0110', '1111', '0010', '0000', '1100', '0010', '1010', '0010',
    '1100', '0101', '1000', '1111', '0111', '0111', '0010', '0000',
    '0110', '1100', '0110', '0101', '0111', '0110', '0110', '0101',
    '0110', '1100', '0010', '0001'
]

decodedString = decodeNibbles(nibbles)
print(decodedString)
# ¡There is no ¢ŏw level!