问:
Configure pretty url iis 7.5
I want to use pretty url on my application. I'm using Yii 1.1 (Php framework) and IIS 7.5

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>

<directoryBrowse enabled="false" />

    <rewrite>
        <rules>
        <rule name="Hide Yii Index" stopProcessing="true">
            <match url="." ignoreCase="false" />
            <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
            </conditions>
                <action type="Rewrite" url="index.php" appendQueryString="true" />
        </rule>
        </rules>
    </rewrite>

</system.webServer>
</configuration>
</code>```

I have configure my IIS rewrite rule like this. But isn't work. Someone knows why?

答:
Try</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <configSections>
        <sectionGroup name="system.webServer">
            <sectionGroup name="rewrite">
                <section name="rewriteMaps" overrideModeDefault="Allow" />
                <section name="rules" overrideModeDefault="Allow" />
            </sectionGroup>
        </sectionGroup>
    </configSections>

    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Imported Rule 1" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php" />
                </rule>
            </rules>
        </rewrite>

    </system.webServer>
</configuration>
</code>```

Title: Configure pretty url iis 7.5

Body:
I want to use pretty url on my application. I'm using Yii 1.1 (Php framework) and IIS 7.5

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>

<directoryBrowse enabled="false" />

    <rewrite>
        <rules>
        <rule name="Hide Yii Index" stopProcessing="true">
            <match url="." ignoreCase="false" />
            <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
            </conditions>
                <action type="Rewrite" url="index.php" appendQueryString="true" />
        </rule>
        </rules>
    </rewrite>

</system.webServer>
</configuration>

I have configure my IIS rewrite rule like this. But isn't work. Someone knows why?

Body:
Try

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <configSections>
        <sectionGroup name="system.webServer">
            <sectionGroup name="rewrite">
                <section name="rewriteMaps" overrideModeDefault="Allow" />
                <section name="rules" overrideModeDefault="Allow" />
            </sectionGroup>
        </sectionGroup>
    </configSections>

    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Imported Rule 1" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php" />
                </rule>
            </rules>
        </rewrite>

    </system.webServer>
</configuration>


来源: stackexchange

问:
Facebook OAuth "The domain of this URL isn't included in the app's domain"
Let me first start with saying I've searched for an answer to this question for quite some time...

I'm trying to setup Facebook OAuth to work with my application that is being developed locally on my machine.  Everything was working perfect with Facebook authorization UNTIL I moved from using localhost to another domain name (still local to my machine.)  Now I'm getting the following error.

Can't Load URL: The domain of this URL isn't included in the app's
domains. To be able to load this URL, add all domains and subdomains
of your app to the App Domains field in your app settings.

My hosts file contains 127.0.0.1   domain.dev  (works perfect)

My redirect in my app (using Socialite) is http://domain.dev/auth/facebook/callback

In my Facebook App Settings...

my App Domain is domain.dev

my Site URL is http://domain.dev/

my Valid OAuth redirect URIs is
http://domain.dev/auth/facebook/callback

The URL at the time of the error message is..

https://www.facebook.com/v2.5/dialog/oauth?client_id=XXXXXXXXXXXXXXX&redirect_uri=http%3A%2F%2Fdomain.dev%2Fauth%2Ffacebook%2Fcallback&scope=email&response_type=code&state=0ztcKhmWwFLtj72TWE8uOKTcf65JmePtG95MZLDD

I'm at a loss of what the problem is...

Screen Shot 1

Screen Shot 2

答: This option should be enabled in portal:

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Static class to use in many activity?
I making a static class so I can access it in different activity..
I need to pass 1 data to another activity, but I don't know to make it properly.
I tried to use put extra things, but it is for passing data to next activity (not global (maybe)).

this is my class..

```<code>static class AuthorizedUserIdClass
{
    private static Guid _authorizedUserId;

    static Guid AuthorizedUserId
    {
        get { return _authorizedUserId; }
        set { _authorizedUserId = value; }
    }
    static AuthorizedUserIdClass()
    {
        AuthorizedUserId = _authorizedUserId;
    }

}
</code>```

is it right?
then, how to use it in activity? and how to call the filled data in another activity?

Thanks in advance :)

答:
you can use directly where ever want in your activity or fragment like this</p>

```<code> Guid value = AuthorizedUserIdClass._authorizedUserId;
</code>```

Title: Static class to use in many activity?

Body:
I making a static class so I can access it in different activity..
I need to pass 1 data to another activity, but I don't know to make it properly.
I tried to use put extra things, but it is for passing data to next activity (not global (maybe)).

this is my class..

static class AuthorizedUserIdClass
{
    private static Guid _authorizedUserId;

    static Guid AuthorizedUserId
    {
        get { return _authorizedUserId; }
        set { _authorizedUserId = value; }
    }
    static AuthorizedUserIdClass()
    {
        AuthorizedUserId = _authorizedUserId;
    }

}

is it right?
then, how to use it in activity? and how to call the filled data in another activity?

Thanks in advance :)

Body:
you can use directly where ever want in your activity or fragment like this

 Guid value = AuthorizedUserIdClass._authorizedUserId;


问:
Xcode 8 Table View Cells to Different Views
I am having trouble with linking view controllers to table view cells. Basically I have 4 cells in my Table View, and I want each cell to present a separate view controller when clicked.

Here are my swift codes:

```<code>import UIKit

var orchard = ["Dog", "Cat", "Bird", "Fish"]
var myIndex = 0

class AnimalList: UITableViewController {

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return orchard.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = orchard[indexPath.row]

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        myIndex = indexPath.row
        performSegue(withIdentifier: "segue", sender: self)
    }
}
</code>```

Here is my storyboard, as you can see I have 4 view controllers that I want to connect to the 4 table view cells.
storyboard

PS: My table view controller has already been embedded inside a navigation controller.

How do I do that? Thank you!

答:
Give a segue for the four ViewControllers and name it as vc1Segue, vc2Segue, vc3Segue, vc3Segue

And change your didSelectRowAt method like below

```<code>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    myIndex = indexPath.row
    switch myIndex {
          case 0:
             performSegue(withIdentifier: "vc1Segue", sender: self)
          case 1:
             performSegue(withIdentifier: "vc2Segue", sender: self)
          case 2:
             performSegue(withIdentifier: "vc3Segue", sender: self)
          case 3:
             performSegue(withIdentifier: "vc4Segue", sender: self)
        default:
            print("Index greater than vcs")
        }
}
</code>```

Body:
I am having trouble with linking view controllers to table view cells. Basically I have 4 cells in my Table View, and I want each cell to present a separate view controller when clicked.

Here are my swift codes:

import UIKit

var orchard = ["Dog", "Cat", "Bird", "Fish"]
var myIndex = 0

class AnimalList: UITableViewController {

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return orchard.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = orchard[indexPath.row]

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        myIndex = indexPath.row
        performSegue(withIdentifier: "segue", sender: self)
    }
}

Here is my storyboard, as you can see I have 4 view controllers that I want to connect to the 4 table view cells.
storyboard

PS: My table view controller has already been embedded inside a navigation controller.

How do I do that? Thank you!

Body:
Give a segue for the four ViewControllers and name it as vc1Segue, vc2Segue, vc3Segue, vc3Segue

And change your didSelectRowAt method like below

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    myIndex = indexPath.row
    switch myIndex {
          case 0:
             performSegue(withIdentifier: "vc1Segue", sender: self)
          case 1:
             performSegue(withIdentifier: "vc2Segue", sender: self)
          case 2:
             performSegue(withIdentifier: "vc3Segue", sender: self)
          case 3:
             performSegue(withIdentifier: "vc4Segue", sender: self)
        default:
            print("Index greater than vcs")
        }
}


问:
Verilog strange simulation results post synthesis
I am facing a strange problem. The code is for a simple ALU. Only code of interest is pasted here:

```<code>   always @(posedge clk or posedge rst)
   begin
        if (rst == 1) begin
           mul_valid_shr = 3'b000;
        end else begin
            if (op_mul_i == 1) begin
                mul_valid_shr = 3'b111;
            end else begin
                mul_valid_shr <= mul_valid_shr << 1;
            end
        end
   end
</code>```

And outside the always block:

```<code>assign mul_valid = mul_valid_shr[2];
</code>```

The POST SYNTHESIS FUNCTIONAL SIMULATION with my test bench has following results:

The reset is already low, why is the sim not working for the first time but working fine for 2nd and third time? If I trigger the op_mul_i before 100ns mark, even if rst is low, even the mul_result stops working on the first time.

Any guesses are welcome.

UPDATE: FULL CODE HERE: https://www.edaplayground.com/x/28Hx

答:
Verilog has has the concepts of nondeterminism and race condtions. Below are exert from various version of Verilog and SystemVerilog explaining the concepts:

IEEE Std 1364-1995 § 5.4.2 Nondeterminism

IEEE Std 1364-2001 § 5.4.2 Nondeterminism

IEEE Std 1800-2012 § 4.8 Nondeterminism

One source of nondeterminism is the fact that active events can be taken off the queue and processed in any order. Another source of nondeterminism is that statements without time-control constructs in behavioral blocks do not have to be executed as one event. Time control statements are the # expression and @ expression constructs (see 9.7 [9.4 for IEEE1800]). At any time while evaluating a behavioral statement, the simulator may suspend execution and place the partially completed event as a pending active event on the event queue. The effect of this is to allow the interleaving of process execution. Note that the order of interleaved execution is nondeterministic and not under control of the user.

IEEE Std 1364-1995 § 5.5 Race conditions

IEEE Std 1364-2001 § 5.5 Race conditions

IEEE Std 1800-2012 § 4.8 Race conditions

Because the execution of expression evaluation and net update events may be intermingled, race conditions are possible:

```<code>assign p = q;
initial begin
  q = 1;
  #1 q = 0;
  $display(p);
end</code>```

The simulator is correct in displaying either a 1 or a 0. The assignment of 0 to q enables an update event for p. The simulator may either continue and execute the $display task or execute the update for p, followed by the $display task.

In short this means an always block that triggers on clk can be evaluated before or after op_mul_i is updated even though clk and op_mul_i are changed in the same time-step. This nondeterministic and race condition behaviors are intentional; allowing the language a way to mimic the same behavior that can happen with critical paths on FPGA and silicon.

Regardless the solution and best practice is to have an offset (time or scheduler region) between the clock and input stimulus. You can use a time offset such at the ± 1 on the first # delay; like I suggest in my comment. Or assign the input stimulus with non-blocking assignments (<=); which will always be updated after the clock and anything dependent on the clock. (This is why flops should be assigned with non-blocking). Which route you take is up to you or your team lead to decide.

Body:
I am facing a strange problem. The code is for a simple ALU. Only code of interest is pasted here:

   always @(posedge clk or posedge rst)
   begin
        if (rst == 1) begin
           mul_valid_shr = 3'b000;
        end else begin
            if (op_mul_i == 1) begin
                mul_valid_shr = 3'b111;
            end else begin
                mul_valid_shr <= mul_valid_shr << 1;
            end
        end
   end

And outside the always block:

assign mul_valid = mul_valid_shr[2];

The POST SYNTHESIS FUNCTIONAL SIMULATION with my test bench has following results:

The reset is already low, why is the sim not working for the first time but working fine for 2nd and third time? If I trigger the op_mul_i before 100ns mark, even if rst is low, even the mul_result stops working on the first time.

Any guesses are welcome.

UPDATE: FULL CODE HERE: https://www.edaplayground.com/x/28Hx

Body:
Verilog has has the concepts of nondeterminism and race condtions. Below are exert from various version of Verilog and SystemVerilog explaining the concepts:

IEEE Std 1364-1995 § 5.4.2 Nondeterminism

IEEE Std 1364-2001 § 5.4.2 Nondeterminism

IEEE Std 1800-2012 § 4.8 Nondeterminism

One source of nondeterminism is the fact that active events can be taken off the queue and processed in any order. Another source of nondeterminism is that statements without time-control constructs in behavioral blocks do not have to be executed as one event. Time control statements are the # expression and @ expression constructs (see 9.7 [9.4 for IEEE1800]). At any time while evaluating a behavioral statement, the simulator may suspend execution and place the partially completed event as a pending active event on the event queue. The effect of this is to allow the interleaving of process execution. Note that the order of interleaved execution is nondeterministic and not under control of the user.

IEEE Std 1364-1995 § 5.5 Race conditions

IEEE Std 1364-2001 § 5.5 Race conditions

IEEE Std 1800-2012 § 4.8 Race conditions

Because the execution of expression evaluation and net update events may be intermingled, race conditions are possible:

assign p = q;
initial begin
  q = 1;
  #1 q = 0;
  $display(p);
end

The simulator is correct in displaying either a 1 or a 0. The assignment of 0 to q enables an update event for p. The simulator may either continue and execute the $display task or execute the update for p, followed by the $display task.

In short this means an always block that triggers on clk can be evaluated before or after op_mul_i is updated even though clk and op_mul_i are changed in the same time-step. This nondeterministic and race condition behaviors are intentional; allowing the language a way to mimic the same behavior that can happen with critical paths on FPGA and silicon.

Regardless the solution and best practice is to have an offset (time or scheduler region) between the clock and input stimulus. You can use a time offset such at the ± 1 on the first # delay; like I suggest in my comment. Or assign the input stimulus with non-blocking assignments (<=); which will always be updated after the clock and anything dependent on the clock. (This is why flops should be assigned with non-blocking). Which route you take is up to you or your team lead to decide.


答:
As far as I understood your case I think you want to save some global data and want to access in different activities.

So what I will suggest is to use the Application class. As it is said that

The Application class in Android is the base class within an Android app that contains all other components such as activities and services. The Application class, or any subclass of the Application class, is instantiated before any other class when the process for your application/package is created.

Read more here and this is the best Question on SO that match your case to save the data.

Please try this and if you find any other problem then let me know

Title: Static class to use in many activity?


问:
Cross join on a group based on the condition in SQL Server
I have Item and Exam tables -

My desire result -

I tried a lot but I am unable to join Exam table to Item table based on Code group.

Is it possible to cross join or any other join for these two tables to get the desire result?

答:
This should produce what you need. I am using UNION to combine CROSS JOIN and item table and then group by to ensure NULLs are removed.      </p>

```<code>SELECT code, max(item) as item, exam
FROM
(SELECT distinct i.code, null as item, e.exam FROM exam e cross join item i
union all
SELECT code, item, exam
FROM item) u
group by code, exam
order by code, exam
</code>```

Body:
This should produce what you need. I am using UNION to combine CROSS JOIN and item table and then group by to ensure NULLs are removed.

SELECT code, max(item) as item, exam
FROM
(SELECT distinct i.code, null as item, e.exam FROM exam e cross join item i
union all
SELECT code, item, exam
FROM item) u
group by code, exam
order by code, exam


答:
To pass data between activities you can use the Intent. Just try

```<code>intent.putExtra(key, value);
</code>```

That way you can pass that to another activity.

Besides that you can use preferences. User preferences is another way to save "global" variables and stuff, is also better than a static class.

You can check how to use those in detail in developer.android.com
But if you MUST use a static class to call this variables you can just call the class directly. Like, for instance, your class is called Util, then you can just call

```<code>Util.publicmethod();
int c = Util.publicIntVariable
</code>```

Title: Static class to use in many activity?

Body:
To pass data between activities you can use the Intent. Just try

intent.putExtra(key, value);

That way you can pass that to another activity.

Besides that you can use preferences. User preferences is another way to save "global" variables and stuff, is also better than a static class.

You can check how to use those in detail in developer.android.com
But if you MUST use a static class to call this variables you can just call the class directly. Like, for instance, your class is called Util, then you can just call

Util.publicmethod();
int c = Util.publicIntVariable


问:
SAS table string length (limit)
I am creating a SAS table in which one of the fields has to holds a huge string.

Following is my table (TABLE name = MKPLOGS4):

```<code>OBS    RNID        DESCTEXT
       ---------   -----------
1       123         This is some text which is part of the record. I want this to appear
2       123         concatenated kinda like concat_group() from MYSQL but for some reason
3       123         SAS does not have such functionality. Now I am having trouble with
4       123         String concatenation.
5       124         Hi there old friend of mine, hope you are enjoying the weather
6       124         Are you sure this is not your jacket, okay then. Will give charity.
.       .           .
.       .           .
.       .           .
</code>```

and I have to get a Table similar to this (table name = MKPLOGSA):

```<code>OBS    RNID        DESCTEXT
       ---------   -----------
1       123         This is some text which is part of the record. I want this to appear concatenated kinda like concat_group() from MYSQL but for some reason SAS does not have such functionality. Now I am having trouble with String concatenation.
2       124         Hi, there old friend of mine, hope you are enjoying the weather Are you sure this is not your jacket, okay then. Will give charity.
.       .           .
.       .           .
.       .           .
</code>```

So, after trying unsuccessfully with SQL, I came up with the following SAS code (please note I am very new at SAS):

```<code>DATA MKPLOGSA (DROP = DTEMP DTEXT);
  SET MKPLOGS4;
  BY RNID;

  RETAIN DTEXT;

  IF FIRST.RNID THEN
  DO;
  DTEXT = DESCTEXT;
  DELETE;
  END;
  ELSE IF LAST.RNID THEN
  DO;
    DTEMP = CATX(' ',DTEXT,DESCTEXT);
    DESCTEXT = DTEMP;
  END;
  ELSE
  DO;
    DTEMP = CATX(' ',DTEXT,DESCTEXT);
    DTEXT = DTEMP;

  DELETE;
  END;
</code>```

The SAS log is producing this warning message:

```<code>WARNING: IN A CALL TO THE CATX FUNCTION, THE BUFFER ALLOCATED
FOR THE RESULT WAS NOT LONG ENOUGH TO CONTAIN THE CONCATENATION
OF ALL THE ARGUMENTS. THE CORRECT RESULT WOULD CONTAIN 229 CHARACTERS,
BUT THE ACTUAL RESULT MAY EITHER BE TRUNCATED TO 200 CHARACTER(S) OR
BE COMPLETELY BLANK, DEPENDING ON THE CALLING ENVIRONMENT. THE
FOLLOWING NOTE INDICATES THE LEFT-MOST ARGUMENT THAT CAUSED TRUNCATION.
</code>```

Followed by the message (for the SAS data step I posted here):

```<code>NOTE: ARGUMENT 3 TO FUNCTION CATX AT LINE 100 COLUMN 15 IS INVALID.
</code>```

Please note that in my sample data table (MKPLOGS4), each line of string for the field DESCTEXT can be upto 116 characters and there is no limit as to how many lines of description text/recordID.

The output I am getting has only the last line of description:

```<code>OBS   RNID   DESCTEXT
      ----   --------
1     123    String concatenation.
2     124    Are you sure this is not your jacket, okay then. Will give charity.
.     .      .
.     .      .
.     .      .
</code>```

I have the following questions:

. is there something wrong with my code?
. is there a limit to SAS string concatenation? Can I override this? If yes, please provide code.

If you have a suggestion, I would really appreciate if you can post your version of code. This is not school work/homework.

答:
Thanks guys, I was able to solve this problem by using PROC TRANSPOSE and then using concatenation. Here is the code:</p>

```<code>/*
  THIS TRANSPOSE STEP TAKES THE MKPLOGS4 TABLE AND
  CREATES A NEW TEMPORARY TABLE CALLED MKPLOGSA. SINCE
  THE DESCRIPTION TEXT IS STORED IN MULTIPLE LINES (OBSERVATIONS)
  IN THE ITEXT FILE, IN ORDER TO COMBINE THEM TO A SINGLE ROW,
  WE USE TRANSPOSE. HOWEVER, AFTER THIS STEP, THE DESCRIPTION TEXT
  SPREAD OVER MULTIPLE LINES ALTHOUGH ON SAME ROW (OBSERVATION)
  ARE STILL SEPARATED INTO MULTIPLE COLUMNS (ON THE SAME ROW)
  ALL PREFIXED IN THIS CASE BY 'DESCTEXT'. WE DROP THE AUTO-CREATED
  COLUMN _NAME_
*/
PROC TRANSPOSE DATA = MKPLOGS4 OUT = MKPLOGSA (DROP = _NAME_)
    PREFIX = DESCTEXT;
    VAR DESCTEXT;
    BY PLOG;
RUN;

/*
  THIS DATA STEP CREATES A NEW TABLE CALLED MKPLOGSB WHICH
  TAKES ALL THE SEPARATED DESCRIPTION TEXT COLUMNS AND
  CONCATENATES THEM INTO A SINGLE COLUMN - LONG_DESCRIPTION.
*/
DATA MKPLOGSB (DROP = DESCTEXT:);
    SET MKPLOGSA;
    /* CONCATENATED DESC. TEXT SET TO MAX. 27000 CHARS. */
    LENGTH LONG_DESCRIPTION $27000;

    LONG_DESCRIPTION = CATX(' ',OF DESCTEXT:);
RUN;
</code>```

ContentLicense: CC BY-SA 2.5

Title: SAS table string length (limit)

Body:
I am creating a SAS table in which one of the fields has to holds a huge string.

Following is my table (TABLE name = MKPLOGS4):

OBS    RNID        DESCTEXT
       ---------   -----------
1       123         This is some text which is part of the record. I want this to appear
2       123         concatenated kinda like concat_group() from MYSQL but for some reason
3       123         SAS does not have such functionality. Now I am having trouble with
4       123         String concatenation.
5       124         Hi there old friend of mine, hope you are enjoying the weather
6       124         Are you sure this is not your jacket, okay then. Will give charity.
.       .           .
.       .           .
.       .           .

and I have to get a Table similar to this (table name = MKPLOGSA):

OBS    RNID        DESCTEXT
       ---------   -----------
1       123         This is some text which is part of the record. I want this to appear concatenated kinda like concat_group() from MYSQL but for some reason SAS does not have such functionality. Now I am having trouble with String concatenation.
2       124         Hi, there old friend of mine, hope you are enjoying the weather Are you sure this is not your jacket, okay then. Will give charity.
.       .           .
.       .           .
.       .           .

So, after trying unsuccessfully with SQL, I came up with the following SAS code (please note I am very new at SAS):

DATA MKPLOGSA (DROP = DTEMP DTEXT);
  SET MKPLOGS4;
  BY RNID;

  RETAIN DTEXT;

  IF FIRST.RNID THEN
  DO;
  DTEXT = DESCTEXT;
  DELETE;
  END;
  ELSE IF LAST.RNID THEN
  DO;
    DTEMP = CATX(' ',DTEXT,DESCTEXT);
    DESCTEXT = DTEMP;
  END;
  ELSE
  DO;
    DTEMP = CATX(' ',DTEXT,DESCTEXT);
    DTEXT = DTEMP;

  DELETE;
  END;

The SAS log is producing this warning message:

WARNING: IN A CALL TO THE CATX FUNCTION, THE BUFFER ALLOCATED
FOR THE RESULT WAS NOT LONG ENOUGH TO CONTAIN THE CONCATENATION
OF ALL THE ARGUMENTS. THE CORRECT RESULT WOULD CONTAIN 229 CHARACTERS,
BUT THE ACTUAL RESULT MAY EITHER BE TRUNCATED TO 200 CHARACTER(S) OR
BE COMPLETELY BLANK, DEPENDING ON THE CALLING ENVIRONMENT. THE
FOLLOWING NOTE INDICATES THE LEFT-MOST ARGUMENT THAT CAUSED TRUNCATION.

Followed by the message (for the SAS data step I posted here):

NOTE: ARGUMENT 3 TO FUNCTION CATX AT LINE 100 COLUMN 15 IS INVALID.

Please note that in my sample data table (MKPLOGS4), each line of string for the field DESCTEXT can be upto 116 characters and there is no limit as to how many lines of description text/recordID.

The output I am getting has only the last line of description:

OBS   RNID   DESCTEXT
      ----   --------
1     123    String concatenation.
2     124    Are you sure this is not your jacket, okay then. Will give charity.
.     .      .
.     .      .
.     .      .

I have the following questions:

. is there something wrong with my code?
. is there a limit to SAS string concatenation? Can I override this? If yes, please provide code.

If you have a suggestion, I would really appreciate if you can post your version of code. This is not school work/homework.

Body:
Thanks guys, I was able to solve this problem by using PROC TRANSPOSE and then using concatenation. Here is the code:

/*
  THIS TRANSPOSE STEP TAKES THE MKPLOGS4 TABLE AND
  CREATES A NEW TEMPORARY TABLE CALLED MKPLOGSA. SINCE
  THE DESCRIPTION TEXT IS STORED IN MULTIPLE LINES (OBSERVATIONS)
  IN THE ITEXT FILE, IN ORDER TO COMBINE THEM TO A SINGLE ROW,
  WE USE TRANSPOSE. HOWEVER, AFTER THIS STEP, THE DESCRIPTION TEXT
  SPREAD OVER MULTIPLE LINES ALTHOUGH ON SAME ROW (OBSERVATION)
  ARE STILL SEPARATED INTO MULTIPLE COLUMNS (ON THE SAME ROW)
  ALL PREFIXED IN THIS CASE BY 'DESCTEXT'. WE DROP THE AUTO-CREATED
  COLUMN _NAME_
*/
PROC TRANSPOSE DATA = MKPLOGS4 OUT = MKPLOGSA (DROP = _NAME_)
    PREFIX = DESCTEXT;
    VAR DESCTEXT;
    BY PLOG;
RUN;

/*
  THIS DATA STEP CREATES A NEW TABLE CALLED MKPLOGSB WHICH
  TAKES ALL THE SEPARATED DESCRIPTION TEXT COLUMNS AND
  CONCATENATES THEM INTO A SINGLE COLUMN - LONG_DESCRIPTION.
*/
DATA MKPLOGSB (DROP = DESCTEXT:);
    SET MKPLOGSA;
    /* CONCATENATED DESC. TEXT SET TO MAX. 27000 CHARS. */
    LENGTH LONG_DESCRIPTION $27000;

    LONG_DESCRIPTION = CATX(' ',OF DESCTEXT:);
RUN;


问:
How to obtain the wifi security type
I am trying to figure out of it is possible to obtain the security type of the network that the device is connected to (WEP/WPA). I know it is possible to get the SSID but I am having no luck getting the security type. Any help?</p>

答: For macOS you can use coreWLAN and then get the info you want from CWSecurity. But coreWLAN is not available for iOS and SystemConfiguration cannot give you that info.</p>

Title: How to obtain the wifi security type


问:
JavaScript numbers to Words
I'm trying to convert numbers into english words, for example 1234 would become: "one thousand two hundred thirty four".

My Tactic goes like this:

Separate the digits to three and put them on Array (finlOutPut), from right to left.

Convert each group (each cell in the finlOutPut array) of three digits to a word (this what the triConvert function does). If all the three digits are zero convert them to "dontAddBigSuffix"

From Right to left, add thousand, million, billion, etc. If the finlOutPut cell equals "dontAddBigSufix" (because it was only zeroes), don't add the word and set the cell to " " (nothing).

It seems to work pretty well, but I've got some problems with numbers like 190000009, converted to: "one hundred ninety million". Somehow it "forgets" the last numbers when there are a few zeros.

What did I do wrong? Where is the bug? Why does it not work perfectly?

function update(){
    var bigNumArry = new Array('', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion');

    var output = '';
    var numString =   document.getElementById('number').value;
    var finlOutPut = new Array();

    if (numString == '0') {
        document.getElementById('container').innerHTML = 'Zero';
        return;
    }

    if (numString == 0) {
        document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
        return;
    }

    var i = numString.length;
    i = i - 1;

    //cut the number to grups of three digits and add them to the Arry
    while (numString.length > 3) {
        var triDig = new Array(3);
        triDig[2] = numString.charAt(numString.length - 1);
        triDig[1] = numString.charAt(numString.length - 2);
        triDig[0] = numString.charAt(numString.length - 3);

        var varToAdd = triDig[0] + triDig[1] + triDig[2];
        finlOutPut.push(varToAdd);
        i--;
        numString = numString.substring(0, numString.length - 3);
    }
    finlOutPut.push(numString);
    finlOutPut.reverse();

    //conver each grup of three digits to english word
    //if all digits are zero the triConvert
    //function return the string "dontAddBigSufix"
    for (j = 0; j < finlOutPut.length; j++) {
        finlOutPut[j] = triConvert(parseInt(finlOutPut[j]));
    }

    var bigScalCntr = 0; //this int mark the million billion trillion... Arry

    for (b = finlOutPut.length - 1; b >= 0; b--) {
        if (finlOutPut[b] != "dontAddBigSufix") {
            finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr] + ' , ';
            bigScalCntr++;
        }
        else {
            //replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
            finlOutPut[b] = ' ';
            bigScalCntr++; //advance the counter
        }
    }

        //convert The output Arry to , more printable string
        for(n = 0; n<finlOutPut.length; n++){
            output +=finlOutPut[n];
        }

    document.getElementById('container').innerHTML = output;//print the output
}

//simple function to convert from numbers to words from 1 to 999
function triConvert(num){
    var ones = new Array('', ' one', ' two', ' three', ' four', ' five', ' six', ' seven', ' eight', ' nine', ' ten', ' eleven', ' twelve', ' thirteen', ' fourteen', ' fifteen', ' sixteen', ' seventeen', ' eighteen', ' nineteen');
    var tens = new Array('', '', ' twenty', ' thirty', ' forty', ' fifty', ' sixty', ' seventy', ' eighty', ' ninety');
    var hundred = ' hundred';
    var output = '';
    var numString = num.toString();

    if (num == 0) {
        return 'dontAddBigSufix';
    }
    //the case of 10, 11, 12 ,13, .... 19
    if (num < 20) {
        output = ones[num];
        return output;
    }

    //100 and more
    if (numString.length == 3) {
        output = ones[parseInt(numString.charAt(0))] + hundred;
        output += tens[parseInt(numString.charAt(1))];
        output += ones[parseInt(numString.charAt(2))];
        return output;
    }

    output += tens[parseInt(numString.charAt(0))];
    output += ones[parseInt(numString.charAt(1))];

    return output;
}   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text"
    id="number"
    size="70"
    onkeyup="update();"
    /*this code prevent non numeric letters*/
    onkeydown="return (event.ctrlKey || event.altKey
                    || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
                    || (95<event.keyCode && event.keyCode<106)
                    || (event.keyCode==8) || (event.keyCode==9)
                    || (event.keyCode>34 && event.keyCode<40)
                    || (event.keyCode==46) )"/>
                    <br/>
<div id="container">Here The Numbers Printed</div></code>```

答:
```<code><script src="http://www.ittutorials.in/js/demo/numtoword.js" type="text/javascript"></script>
    HTML - Convert numbers to words using JavaScript</h1>
<input id="Text1" type="text" onkeypress="return onlyNumbers(this.value);" onkeyup="NumToWord(this.value,'divDisplayWords');"
    maxlength="9" style="background-color: #efefef; border: 2px solid #CCCCC; font-size: large" />
<br />
<br />
<div id="divDisplayWords" style="font-size: 13; color: Teal; font-family: Arial;">
</div>
</code>```

Title: JavaScript numbers to Words

Body:
I'm trying to convert numbers into english words, for example 1234 would become: "one thousand two hundred thirty four".

My Tactic goes like this:

Separate the digits to three and put them on Array (finlOutPut), from right to left.

Convert each group (each cell in the finlOutPut array) of three digits to a word (this what the triConvert function does). If all the three digits are zero convert them to "dontAddBigSuffix"

From Right to left, add thousand, million, billion, etc. If the finlOutPut cell equals "dontAddBigSufix" (because it was only zeroes), don't add the word and set the cell to " " (nothing).

It seems to work pretty well, but I've got some problems with numbers like 190000009, converted to: "one hundred ninety million". Somehow it "forgets" the last numbers when there are a few zeros.

What did I do wrong? Where is the bug? Why does it not work perfectly?

function update(){
    var bigNumArry = new Array('', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion');

    var output = '';
    var numString =   document.getElementById('number').value;
    var finlOutPut = new Array();

    if (numString == '0') {
        document.getElementById('container').innerHTML = 'Zero';
        return;
    }

    if (numString == 0) {
        document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
        return;
    }

    var i = numString.length;
    i = i - 1;

    //cut the number to grups of three digits and add them to the Arry
    while (numString.length > 3) {
        var triDig = new Array(3);
        triDig[2] = numString.charAt(numString.length - 1);
        triDig[1] = numString.charAt(numString.length - 2);
        triDig[0] = numString.charAt(numString.length - 3);

        var varToAdd = triDig[0] + triDig[1] + triDig[2];
        finlOutPut.push(varToAdd);
        i--;
        numString = numString.substring(0, numString.length - 3);
    }
    finlOutPut.push(numString);
    finlOutPut.reverse();

    //conver each grup of three digits to english word
    //if all digits are zero the triConvert
    //function return the string "dontAddBigSufix"
    for (j = 0; j < finlOutPut.length; j++) {
        finlOutPut[j] = triConvert(parseInt(finlOutPut[j]));
    }

    var bigScalCntr = 0; //this int mark the million billion trillion... Arry

    for (b = finlOutPut.length - 1; b >= 0; b--) {
        if (finlOutPut[b] != "dontAddBigSufix") {
            finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr] + ' , ';
            bigScalCntr++;
        }
        else {
            //replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
            finlOutPut[b] = ' ';
            bigScalCntr++; //advance the counter
        }
    }

        //convert The output Arry to , more printable string
        for(n = 0; n<finlOutPut.length; n++){
            output +=finlOutPut[n];
        }

    document.getElementById('container').innerHTML = output;//print the output
}

//simple function to convert from numbers to words from 1 to 999
function triConvert(num){
    var ones = new Array('', ' one', ' two', ' three', ' four', ' five', ' six', ' seven', ' eight', ' nine', ' ten', ' eleven', ' twelve', ' thirteen', ' fourteen', ' fifteen', ' sixteen', ' seventeen', ' eighteen', ' nineteen');
    var tens = new Array('', '', ' twenty', ' thirty', ' forty', ' fifty', ' sixty', ' seventy', ' eighty', ' ninety');
    var hundred = ' hundred';
    var output = '';
    var numString = num.toString();

    if (num == 0) {
        return 'dontAddBigSufix';
    }
    //the case of 10, 11, 12 ,13, .... 19
    if (num < 20) {
        output = ones[num];
        return output;
    }

    //100 and more
    if (numString.length == 3) {
        output = ones[parseInt(numString.charAt(0))] + hundred;
        output += tens[parseInt(numString.charAt(1))];
        output += ones[parseInt(numString.charAt(2))];
        return output;
    }

    output += tens[parseInt(numString.charAt(0))];
    output += ones[parseInt(numString.charAt(1))];

    return output;
}

<input type="text"
    id="number"
    size="70"
    onkeyup="update();"
    /*this code prevent non numeric letters*/
    onkeydown="return (event.ctrlKey || event.altKey
                    || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
                    || (95<event.keyCode && event.keyCode<106)
                    || (event.keyCode==8) || (event.keyCode==9)
                    || (event.keyCode>34 && event.keyCode<40)
                    || (event.keyCode==46) )"/>

Here The Numbers Printed


问:
setState when this got changed
For some reason I used jquery in my react's componentDidMount, but can't use this.setState, because this has been changed by jquery method, I set this to somewhere else, I can accept thisComponent.props.something but why setState failed?

```<code>componentDidMount() {
    const thisComponent = this //jquery changed `this`, thus set `this` set to somewhere else

    $('#container').on('scroll', function() {

        console.log(thisComponent.props.something) //work

        thisComponent.setState({ // not working
            myTestingState: true
        })
    })
}
</code>```

There's no error, I tried print out {this.state.myTestingState.toString()} in my render method, it's just not been set.

答:
You can try this</p>

```<code>componentDidMount() {
    $('#container').on('scroll',() => {
       this.setState({
          myTestingState: true
       })
    })
}
</code>```

Title: setState when this got changed

Body:
For some reason I used jquery in my react's componentDidMount, but can't use this.setState, because this has been changed by jquery method, I set this to somewhere else, I can accept thisComponent.props.something but why setState failed?

componentDidMount() {
    const thisComponent = this //jquery changed `this`, thus set `this` set to somewhere else

    $('#container').on('scroll', function() {

        console.log(thisComponent.props.something) //work

        thisComponent.setState({ // not working
            myTestingState: true
        })
    })
}

There's no error, I tried print out {this.state.myTestingState.toString()} in my render method, it's just not been set.

Body:
You can try this

componentDidMount() {
    $('#container').on('scroll',() => {
       this.setState({
          myTestingState: true
       })
    })
}


问:
How can I see what has changed in a file before committing to git?
I've noticed that while working on one or two tickets, if I step away, I'm not sure what I worked on, what changed, etcetera.

Is there a way to see the changes made for a given file before git add and then git commit?

答:
```<code>git diff <path>/filename
</code>```

path can your be complete system path till the file or

if you are in the project you paste the modified file path also

for Modified files with path use :git status

Body:
git diff <path>/filename

path can your be complete system path till the file or

if you are in the project you paste the modified file path also

for Modified files with path use :git status


问:
SQL Count no result if condition is 0
Hi my code is right about showing the right result wherein count in another table with same value of column

My Database:

Clientgroup table

```<code>id | clientgroup_name | clientgroup_color
10   Business Customer  green
11   Super VIP          red
12   Ultimate VIP       pink
</code>```

Client List Table:

```<code>id | name   | group_id
1    John      10
2    Mark      10
3    Paul      12
4    Nico      12
</code>```

My code:

```<code>SELECT Count(*) as Count,clientgroup_table.clientgroup_name,clientgroup_table.clientgroup_color FROM clientgroup_table, client_list WHERE client_list.group_id = clientgroup_table.id GROUP BY clientgroup_table.clientgroup_name
</code>```

My result:

```<code>Count | clientgroup_name | clientgroup_color
2       Business Customer   green
2       Ultimate VIP        pink
</code>```

My desired result:

```<code>Count | clientgroup_name | clientgroup_color
2       Business Customer   green
2       Ultimate VIP        pink
0       SUPER VIP           red
</code>```

I want to show 0 even there's no row equal to it

Is it possible?

thanks

答:
Your current query has two problems which are giving you the wrong output.  First, you are using an implicit inner join which is discarding records from the client group table which do not match.  Instead, you should be using a LEFT JOIN.  Second, you are counting with COUNT(*) which will give a false count of one for records on the left which do not match anything on the right.  Instead, use COUNT(some column from the right).

```<code>SELECT
    COUNT(t2.group_id) AS Count,   -- returns 0 if t2.group_id is NULL
    t1.clientgroup_name,
    t1.clientgroup_color
FROM clientgroup_table t1
LEFT JOIN client_list t2
    ON t2.group_id = t1.id
GROUP BY
    t1.clientgroup_name,
    t1.clientgroup_color
ORDER BY
    Count DESC,
    t1.clientgroup_name;
</code>```

Demo here:

Rextester

Title: SQL Count no result if condition is 0

Body:
Hi my code is right about showing the right result wherein count in another table with same value of column

My Database:

Clientgroup table

id | clientgroup_name | clientgroup_color
10   Business Customer  green
11   Super VIP          red
12   Ultimate VIP       pink

Client List Table:

id | name   | group_id
1    John      10
2    Mark      10
3    Paul      12
4    Nico      12

My code:

SELECT Count(*) as Count,clientgroup_table.clientgroup_name,clientgroup_table.clientgroup_color FROM clientgroup_table, client_list WHERE client_list.group_id = clientgroup_table.id GROUP BY clientgroup_table.clientgroup_name

My result:

Count | clientgroup_name | clientgroup_color
2       Business Customer   green
2       Ultimate VIP        pink

My desired result:

Count | clientgroup_name | clientgroup_color
2       Business Customer   green
2       Ultimate VIP        pink
0       SUPER VIP           red

I want to show 0 even there's no row equal to it

Is it possible?

thanks

Body:
Your current query has two problems which are giving you the wrong output.  First, you are using an implicit inner join which is discarding records from the client group table which do not match.  Instead, you should be using a LEFT JOIN.  Second, you are counting with COUNT(*) which will give a false count of one for records on the left which do not match anything on the right.  Instead, use COUNT(some column from the right).

SELECT
    COUNT(t2.group_id) AS Count,   -- returns 0 if t2.group_id is NULL
    t1.clientgroup_name,
    t1.clientgroup_color
FROM clientgroup_table t1
LEFT JOIN client_list t2
    ON t2.group_id = t1.id
GROUP BY
    t1.clientgroup_name,
    t1.clientgroup_color
ORDER BY
    Count DESC,
    t1.clientgroup_name;

Demo here:

Rextester


答:
You can use the left join operation to do this to include the other rows that don't have any client.
Try this query:</p>

```<code>SELECT
  Count(*) as Count,
  clientgroup_table.clientgroup_name,
  clientgroup_table.clientgroup_color
FROM clientgroup_table left join client_list
  on client_list.group_id = clientgroup_table.id
GROUP BY clientgroup_table.clientgroup_name;
</code>```

Title: SQL Count no result if condition is 0

Body:
You can use the left join operation to do this to include the other rows that don't have any client.
Try this query:

SELECT
  Count(*) as Count,
  clientgroup_table.clientgroup_name,
  clientgroup_table.clientgroup_color
FROM clientgroup_table left join client_list
  on client_list.group_id = clientgroup_table.id
GROUP BY clientgroup_table.clientgroup_name;


问:
Can't Display an image from google drive on a dialog or sidebar using google apps script
I have a script that I'm working on to learn more about the structure of Google Docs. It displays a lot of the structure I'm trying learn about in a sidebar.  But I've been trying to display an image that is in this Google Doc that my script is contained in but it seems that no matter what I try I can't display the image thats already in Google Docs.  So I uploaded another version of it to Google Drive and tried using Google Links as described in several StackOverFlow references but they just don't seem to be working.  The only thing that seems to work reliably is to upload it to my website and use the url from that. Here's the snippet that's giving me the problems.

```<code>var br = '<br />';
var images=DocumentApp.getActiveDocument().getBody().getImages();
  if(images)
  {
    s+=br + '<strong>Body Images</strong>' + br + '<strong>Number of Images: </strong> ' + images.length;
    for(var i=0;i<images.length;i++)
    {
      s+=br + '<img src="http://myWebsite.com/GmailSignature.png" width="100"/>'; //This is the only thing I can get to work
      s+=br + '<img src="https://drive.google.com/open?id=0Bx2ds1-xxxxxxxxxxxxxxxxxxxx" width="100"/>';//There's several references on StackOverFlow.com that say this should work
      s+=br + '<img src="https://drive.google.com/uc?id=0Bx2ds1-xxxxxxxxxxxxxxxxxxxx&export=download" width="100" />';
    }
  }else{s+=br + '<strong>No Images in this Body element.</strong>';}
</code>```

He's what my sidebar looks like with this code:

The link from my website works.  The link from Google Drive does not.  I just added that image to one of my google sites and took that url and that works as well.  One of stackoverflow references suggest this <img src='https://drive.google.com/uc?id=" + imageId +'"' but what appears to be working for me is to turn that into this: '.

Currently the only solution I have is to insert the image onto one of my google sites(old style).  Save the page and get the url with developer and that works every time.  I'm hoping there is or atleast will be in the future a simpler method.  In this situation, it would be preferable to be able to use the image directly out of the Google Docs Document.

答:
Using images from Google Drive in Dialog and Sidebars

I think my problem was that I wasn't always using the id from the shareable link and possibly I may have not always set it up to be publicly accessible. I just did this little example and they all work just fine and they include some ways that I had problems getting to work in the past.

```<code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <img src="https://drive.google.com/uc?id=ShareableLinkID&export=download" width="200" />
    <img src="http://drive.google.com/uc?export=view&id=ShareableLinkID" width="200" />
    <img src="https://drive.google.com/uc?id=ShareableLinkID" width="200" />

  </body>
</html>
</code>```

Body:
I have a script that I'm working on to learn more about the structure of Google Docs. It displays a lot of the structure I'm trying learn about in a sidebar.  But I've been trying to display an image that is in this Google Doc that my script is contained in but it seems that no matter what I try I can't display the image thats already in Google Docs.  So I uploaded another version of it to Google Drive and tried using Google Links as described in several StackOverFlow references but they just don't seem to be working.  The only thing that seems to work reliably is to upload it to my website and use the url from that. Here's the snippet that's giving me the problems.

var br = '
';
var images=DocumentApp.getActiveDocument().getBody().getImages();
  if(images)
  {
    s+=br + 'Body Images' + br + 'Number of Images:  ' + images.length;
    for(var i=0;i<images.length;i++)
    {
      s+=br + ''; //This is the only thing I can get to work
      s+=br + '';//There's several references on StackOverFlow.com that say this should work
      s+=br + '';
    }
  }else{s+=br + 'No Images in this Body element.';}

He's what my sidebar looks like with this code:

The link from my website works.  The link from Google Drive does not.  I just added that image to one of my google sites and took that url and that works as well.  One of stackoverflow references suggest this <img src='https://drive.google.com/uc?id=" + imageId +'"' but what appears to be working for me is to turn that into this: '.

Currently the only solution I have is to insert the image onto one of my google sites(old style).  Save the page and get the url with developer and that works every time.  I'm hoping there is or atleast will be in the future a simpler method.  In this situation, it would be preferable to be able to use the image directly out of the Google Docs Document.

Body:
Using images from Google Drive in Dialog and Sidebars

I think my problem was that I wasn't always using the id from the shareable link and possibly I may have not always set it up to be publicly accessible. I just did this little example and they all work just fine and they include some ways that I had problems getting to work in the past.

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <img src="https://drive.google.com/uc?id=ShareableLinkID&export=download" width="200" />
    <img src="http://drive.google.com/uc?export=view&id=ShareableLinkID" width="200" />
    <img src="https://drive.google.com/uc?id=ShareableLinkID" width="200" />

  </body>
</html>


问:
Angular 4 template error: 'anonymous' does not contain such a member
Angular 4 written in Typescript 2.3.4

component.ts

```<code>/**
 * Info that drives the tabs in the template. Array is filled
 * in ngOnInit() once data is received from the server
 */
public tabs:Array<{
  title:string,
  description:string,
  data:Array<{name:string}>
}>=[];
</code>```

component.html

```<code><section *ngFor="let t of tabs">
  ...
  <div *ngFor="let i of t.data">{{i.name}}</div>
                                  ^^^^^^
</section>
</code>```

Compiler error

Angular: Identifier 'name' is not defined. <anonymous> does not contain such a member

At first I thought this was linked to my other issue but this is different because there is no ambiguity in the shape of the tabs model: the component clearly shows that name is a property of each member of the data array, itself a property of each member of tabs array.

What's going on here?

答:
Try adding the Safe Navigation Operator (?) in the binding, which allows you to navigate an object path in situations where the path may or may not be initially valid.</p>

```<code>  <div *ngFor="let i of t.data">{{i?.name}}</div>
</code>```

Body:
Angular 4 written in Typescript 2.3.4

component.ts

/**
 * Info that drives the tabs in the template. Array is filled
 * in ngOnInit() once data is received from the server
 */
public tabs:Array<{
  title:string,
  description:string,
  data:Array<{name:string}>
}>=[];

component.html

  ...

{{i.name}}

                                  ^^^^^^

Compiler error

Angular: Identifier 'name' is not defined. <anonymous> does not contain such a member

At first I thought this was linked to my other issue but this is different because there is no ambiguity in the shape of the tabs model: the component clearly shows that name is a property of each member of the data array, itself a property of each member of tabs array.

What's going on here?

Body:
Try adding the Safe Navigation Operator (?) in the binding, which allows you to navigate an object path in situations where the path may or may not be initially valid.

  <div *ngFor="let i of t.data">{{i?.name}}</div>


问:
Laravel: Compare two dates against today with Eloquent
So I have events table which has start date and end date.

What I want to do is a comparison between today and start date + end date so if today is between start and end, return that collection which will be displayed on page, if it isn't ignore that event.

Problem is that when I retrieve an event I cannot access it as it is return that it doesn't exist in the collection, but it does after view is returned.

Here's my controller:

```<code>public function show($id)
{
    $today = date("Y-m-d");
    $today_dt = new DateTime($today);
    $event = Event::with('businesses')
        ->get();
    $test = $event->startdate;
    $test2 = $event->enddate;
    //something like if $today is not less that start date and not higher than end date, return that collection?
    dd($test);
    return view('events.showEvent', compact('event'));
}
</code>```

答:
in Model

```<code>public function scopeOfToday($query){
    $today = \Carbon\Carbon::today()->format('Y-m-d');
    return $query->whereRaw("? BETWEEN startdate and enddate",$today);
}
</code>```

in Controller

```<code>public function show($id)
{
    $event = Event::ofToday()->with('businesses')->get();

    $test = $event->startdate;
    $test2 = $event->enddate;
    //something like if $today is not less that start date and not higher than end date, return that collection?
    dd($test);
    return view('events.showEvent', compact('event'));
}
</code>```

Body:
So I have events table which has start date and end date.

What I want to do is a comparison between today and start date + end date so if today is between start and end, return that collection which will be displayed on page, if it isn't ignore that event.

Problem is that when I retrieve an event I cannot access it as it is return that it doesn't exist in the collection, but it does after view is returned.

Here's my controller:

public function show($id)
{
    $today = date("Y-m-d");
    $today_dt = new DateTime($today);
    $event = Event::with('businesses')
        ->get();
    $test = $event->startdate;
    $test2 = $event->enddate;
    //something like if $today is not less that start date and not higher than end date, return that collection?
    dd($test);
    return view('events.showEvent', compact('event'));
}

Body:
in Model

public function scopeOfToday($query){
    $today = \Carbon\Carbon::today()->format('Y-m-d');
    return $query->whereRaw("? BETWEEN startdate and enddate",$today);
}

in Controller

public function show($id)
{
    $event = Event::ofToday()->with('businesses')->get();

    $test = $event->startdate;
    $test2 = $event->enddate;
    //something like if $today is not less that start date and not higher than end date, return that collection?
    dd($test);
    return view('events.showEvent', compact('event'));
}


问:
How to crosstab this table with pandas?
I have this data and i want to cross-tabulate between the GDP level (above average vs. below average) vs. Level of alcohol consumption (above average vs. below average). and find the correlation.

data

I'm trying this but is not what i want.

```<code>pd.crosstab(df['GDP'],df['Recorded_Consupmtion'], margins=True)
</code>```

答:
IIUC:

```<code>df['GDP_Avg'] = np.where(df.GDP < df.GDP.mean(),'Below Average','Above Average')

df['RC_Avg'] = np.where(df.Recorded_Consupmtion < df.Recorded_Consupmtion.mean(),'Below Average','Above Average')

pd.crosstab(df['GDP_Avg'],df['RC_Avg'], margins=True)
</code>```

Output:

```<code>RC_Avg         Above Average  Below Average  All
GDP_Avg
Above Average              5              0    5
Below Average              1              3    4
All                        6              3    9
</code>```

Title: How to crosstab this table with pandas?

Body:
I have this data and i want to cross-tabulate between the GDP level (above average vs. below average) vs. Level of alcohol consumption (above average vs. below average). and find the correlation.

data

I'm trying this but is not what i want.

pd.crosstab(df['GDP'],df['Recorded_Consupmtion'], margins=True)

Body:
IIUC:

df['GDP_Avg'] = np.where(df.GDP < df.GDP.mean(),'Below Average','Above Average')

df['RC_Avg'] = np.where(df.Recorded_Consupmtion < df.Recorded_Consupmtion.mean(),'Below Average','Above Average')

pd.crosstab(df['GDP_Avg'],df['RC_Avg'], margins=True)

Output:

RC_Avg         Above Average  Below Average  All
GDP_Avg
Above Average              5              0    5
Below Average              1              3    4
All                        6              3    9


问:
How to use Qt 5 datetime data to query Sqlite3 using Python3 and PyQt5
I have a Qt form with two QDateTimeEdit controls.  I want to use these dates and times in the WHERE clause of a sqlite3 SELECT statement when the user presses the SEARCH button.  But I can’t figure out how to extract the date and time components from the QDateTime object in order to construct the julian dates that Sqlite needs.

I have spent many hours reading and rereading the Qt C++ class reference documentation that the PyQt5 Reference Guide links to and trying different things, including trying to do various conversion using QVariant but all to no avail.  Seems to me that the QString QDateTime::toString(const QString &format)const method is what I need to use but PyQt5 bindings don’t seem to include QString or the toString method?  I came across a post that seemed to confirm that this method is what I need but it was referring to PyQt4.  Is it possible that support for this method was dropped in the PyQt5 release?

答:
According to the documentation:

The date and time functions use a subset of IS0-8601 date and time
  formats. The date() function returns the date in this format:
  YYYY-MM-DD. The time() function returns the time as HH:MM:SS. The
  datetime() function returns "YYYY-MM-DD HH:MM:SS". The julianday()
  function returns the Julian day - the number of days since noon in
  Greenwich on November 24, 4714 B.C. (Proleptic Gregorian calendar).
  The strftime() routine returns the date formatted according to the
  format string specified as the first argument. The format string
  supports the most common substitutions found in the strftime()
  function from the standard C library plus two new substitutions, %f
  and %J. The following is a complete list of valid strftime()
  substitutions:

The time data type must have the format YYYY-MM-DD HH:MM:SS, In Qt (and therefore in PyQt) we can get it using the toString function:

```<code>QDateTime.toString("yyyy-MM-dd hh:mm:ss")
</code>```

Example:

```<code>from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtSql import *
import sys

def createConnection():
    db = QSqlDatabase.addDatabase('QSQLITE')
    db.setDatabaseName('memory')
    if not db.open():
        QMessageBox.critical(None, qApp.tr("Cannot open database"),
                             qApp.tr("Unable to establish a database connection.\n"
                                     "This example needs SQLite support. Please read "
                                     "the Qt SQL driver documentation for information "
                                     "how to build it.\n\n"
                                     "Click Cancel to exit."),
                             QMessageBox.Cancel)
        return False

    query = QSqlQuery()
    query.exec_("create table test(id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, dt DATETIME default current_timestamp)")

    query.exec_("insert into test (dt) values('2007-01-01 10:00:00')")
    query.exec_("insert into test (dt) values('2008-01-01 10:00:00')")
    query.exec_("insert into test (dt) values('2009-01-01 10:00:00')")
    query.exec_("insert into test (dt) values('2010-01-01 10:00:00')")
    return True

class Widget(QWidget):
    def __init__(self, change_cursor=True, parent=None):
        QWidget.__init__(self, parent=parent)
        layout = QHBoxLayout(self)
        self.fromDateTE = QDateTimeEdit()
        self.toDateTE = QDateTimeEdit()
        layout.addWidget(self.fromDateTE)
        layout.addWidget(self.toDateTE)
        btn = QPushButton("Select")
        layout.addWidget(btn)
        btn.clicked.connect(self.onClick)

    def onClick(self):
        _from = self.fromDateTE.dateTime().toString("yyyy-MM-dd hh:mm:ss")
        _to = self.toDateTE.dateTime().toString("yyyy-MM-dd hh:mm:ss")
        sql = "SELECT * from test WHERE dt BETWEEN datetime('{}') AND datetime('{}')".format(_from, _to)
        query = QSqlQuery(sql)
        while query.next():
            print(query.value(1))

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)

    if not createConnection():
        sys.exit(1)
    w = Widget()
    w.show()
    sys.exit(app.exec_())
</code>```

If we place the dates as shown in the following figure we get the result shown below.

Screenshot:

Output:

```<code>2008-01-01 10:00:00
</code>```

Body:
According to the documentation:

The date and time functions use a subset of IS0-8601 date and time
  formats. The date() function returns the date in this format:
  YYYY-MM-DD. The time() function returns the time as HH:MM:SS. The
  datetime() function returns "YYYY-MM-DD HH:MM:SS". The julianday()
  function returns the Julian day - the number of days since noon in
  Greenwich on November 24, 4714 B.C. (Proleptic Gregorian calendar).
  The strftime() routine returns the date formatted according to the
  format string specified as the first argument. The format string
  supports the most common substitutions found in the strftime()
  function from the standard C library plus two new substitutions, %f
  and %J. The following is a complete list of valid strftime()
  substitutions:

The time data type must have the format YYYY-MM-DD HH:MM:SS, In Qt (and therefore in PyQt) we can get it using the toString function:

QDateTime.toString("yyyy-MM-dd hh:mm:ss")

Example:

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtSql import *
import sys

def createConnection():
    db = QSqlDatabase.addDatabase('QSQLITE')
    db.setDatabaseName('memory')
    if not db.open():
        QMessageBox.critical(None, qApp.tr("Cannot open database"),
                             qApp.tr("Unable to establish a database connection.\n"
                                     "This example needs SQLite support. Please read "
                                     "the Qt SQL driver documentation for information "
                                     "how to build it.\n\n"
                                     "Click Cancel to exit."),
                             QMessageBox.Cancel)
        return False

    query = QSqlQuery()
    query.exec_("create table test(id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, dt DATETIME default current_timestamp)")

    query.exec_("insert into test (dt) values('2007-01-01 10:00:00')")
    query.exec_("insert into test (dt) values('2008-01-01 10:00:00')")
    query.exec_("insert into test (dt) values('2009-01-01 10:00:00')")
    query.exec_("insert into test (dt) values('2010-01-01 10:00:00')")
    return True

class Widget(QWidget):
    def __init__(self, change_cursor=True, parent=None):
        QWidget.__init__(self, parent=parent)
        layout = QHBoxLayout(self)
        self.fromDateTE = QDateTimeEdit()
        self.toDateTE = QDateTimeEdit()
        layout.addWidget(self.fromDateTE)
        layout.addWidget(self.toDateTE)
        btn = QPushButton("Select")
        layout.addWidget(btn)
        btn.clicked.connect(self.onClick)

    def onClick(self):
        _from = self.fromDateTE.dateTime().toString("yyyy-MM-dd hh:mm:ss")
        _to = self.toDateTE.dateTime().toString("yyyy-MM-dd hh:mm:ss")
        sql = "SELECT * from test WHERE dt BETWEEN datetime('{}') AND datetime('{}')".format(_from, _to)
        query = QSqlQuery(sql)
        while query.next():
            print(query.value(1))

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)

    if not createConnection():
        sys.exit(1)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

If we place the dates as shown in the following figure we get the result shown below.

Screenshot:

Output:

2008-01-01 10:00:00


问:
Matter.js Collision Not Detecting
I'm trying to practice using matter.js to create top down levels Bomberman style.

Right now I want to get my circle, which is controlled by arrow keys to move and bump into static squares but it is just going through them. Did I set it up incorrectly? I have been coding for three months, so I might be quite slow sorry!

```<code>var Engine = Matter.Engine,
    World = Matter.World,
    Bodies = Matter.Bodies;

var engine = Engine.create();
var world = engine.world;

var player;
var rocks = [];
var cols = 7;
var rows = 7;

function setup() {
    createCanvas(750, 750);
    Engine.run(engine);

    player = new Player(300, 300, 25);

    var spacing = width / cols;
    for (var j = 0; j < rows; j++) {
        for (var i = 0; i < cols; i++) {
            var r = new Rocks(i * spacing, j * spacing);
            rocks.push(r);
        }
    }
}

function draw() {
    background(51);
    Engine.update(engine);
    for (var i = 0; i < rocks.length; i++) {
        rocks[i].show();
    }
    player.show();
    player.move();
}

function Player(x, y, r) {
    this.body = Bodies.circle(x, y, r);
    this.r = r;
    World.add(world, this.body);

    this.show = function () {
        ellipse(x, y, this.r * 2);
    }

    this.move = function () {
        if (keyIsDown(RIGHT_ARROW))
            x += 10;
        if (keyIsDown(LEFT_ARROW))
            x -= 10;
        if (keyIsDown(UP_ARROW))
            y -= 10;
        if (keyIsDown(DOWN_ARROW))
            y += 10;
        x = constrain(x, this.r, height - this.r);
        y = constrain(y, this.r, width - this.r);
    }
}

function Rocks(x, y, w, h, options) {
    var options = {
        isStatic: true
    }
    this.body = Bodies.rectangle(x, y, h, w, options);
    this.w = w;
    this.h = h;
    this.size = player.r * 2;
    World.add(world, this.body);

    this.show = function () {
        rect(x, y, this.size, this.size);
    }
}
</code>```

答:
I think the problem is that you player is not drawn in the same position that the physics engine thinks its at.

in your Player function after the initialization of x and y the rest all need to be this.body.position.x and this.body.position.y.  Otherwise you're changing where the picture is drawn at but not where the player actually is.

I'm not entirely sure what all you want me to point out besides that but also I think you want to disable gravity with engine.world.gravity.y = 0 and I was trying to fix the constrain function because as I tested it it wasn't working, I wasn't able to fix it but I'd recommend just making static boundary objects for the walls and just don't draw them.

Also matter.js processes the locations of objects from their centers.  When drawing the objects you either have to take that into consideration or switch the mode to ellipseMode(CENTER);, 'rectMode(CENTER);` .. etc.

I hope this helps

Title: Matter.js Collision Not Detecting

Body:
I'm trying to practice using matter.js to create top down levels Bomberman style.

Right now I want to get my circle, which is controlled by arrow keys to move and bump into static squares but it is just going through them. Did I set it up incorrectly? I have been coding for three months, so I might be quite slow sorry!

var Engine = Matter.Engine,
    World = Matter.World,
    Bodies = Matter.Bodies;

var engine = Engine.create();
var world = engine.world;

var player;
var rocks = [];
var cols = 7;
var rows = 7;

function setup() {
    createCanvas(750, 750);
    Engine.run(engine);

    player = new Player(300, 300, 25);

    var spacing = width / cols;
    for (var j = 0; j < rows; j++) {
        for (var i = 0; i < cols; i++) {
            var r = new Rocks(i * spacing, j * spacing);
            rocks.push(r);
        }
    }
}

function draw() {
    background(51);
    Engine.update(engine);
    for (var i = 0; i < rocks.length; i++) {
        rocks[i].show();
    }
    player.show();
    player.move();
}

function Player(x, y, r) {
    this.body = Bodies.circle(x, y, r);
    this.r = r;
    World.add(world, this.body);

    this.show = function () {
        ellipse(x, y, this.r * 2);
    }

    this.move = function () {
        if (keyIsDown(RIGHT_ARROW))
            x += 10;
        if (keyIsDown(LEFT_ARROW))
            x -= 10;
        if (keyIsDown(UP_ARROW))
            y -= 10;
        if (keyIsDown(DOWN_ARROW))
            y += 10;
        x = constrain(x, this.r, height - this.r);
        y = constrain(y, this.r, width - this.r);
    }
}

function Rocks(x, y, w, h, options) {
    var options = {
        isStatic: true
    }
    this.body = Bodies.rectangle(x, y, h, w, options);
    this.w = w;
    this.h = h;
    this.size = player.r * 2;
    World.add(world, this.body);

    this.show = function () {
        rect(x, y, this.size, this.size);
    }
}


问:
Sort files according to creation date?
First Problem is solved. Files is perfectly arrange.

```<code>for (int i = 0; i < allFiles.GetSize(); i++)
{
    box1.AddString(allFiles[i]);
}

vector<file> files;

vector<tstring> vec;
vec.insert(vec.begin(), &allFiles[0], &allFiles[allFiles.GetSize() - 1] + 1);

transform(vec.begin(), vec.end(),back_inserter(files),[](wstring const &fname)
{
    WIN32_FIND_DATA d;
    HANDLE h = FindFirstFile(fname.c_str(), &d);
    FindClose(h);
    return d;
}

);

sort(files.begin(), files.end());
CStringArray sortFiles;
files.insert(files.begin(), &sortFiles[0], &sortFiles[sortFiles.GetSize() - 1] + 1);
</code>```

Now The problem is how i save sort files in CStringArray. Last Statement show the error see the comments?

答:
Simple way to sort file based on creation date or last write date is store the files in to a map where Key is the date and value is the file name. Map will sort it for you.. my code example as below..</p>

```<code>BOOL GetLastWriteTime(FILETIME ftWrite, LPWSTR lpszString, DWORD dwSize)
{
     DWORD dwRet;
     SYSTEMTIME st, stLocal;
    // Convert the last-write time to local time.
    FileTimeToSystemTime(&ftWrite, &st);
    SystemTimeToTzSpecificLocalTime(NULL, &st, &stLocal);

    // Build a string showing the date and time.
    dwRet = StringCchPrintf(lpszString, dwSize,
        TEXT("%02d%02d%d%02d%02d%02d%04d"),
        stLocal.wMonth, stLocal.wDay, stLocal.wYear,
        stLocal.wHour, stLocal.wMinute, stLocal.wSecond, stLocal.wMilliseconds);

    if( S_OK == dwRet )
        return TRUE;
    else return FALSE;
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::map<wstring, wstring> first;

     wstring directory = L"D:\\SourceCode\\FilesTemp\\*";
     std::wstring name;
     WCHAR szBuf[MAX_PATH];
     WIN32_FIND_DATA d;
     HANDLE hFindFile   = FindFirstFile ( directory.c_str(), &d );

     if (hFindFile == INVALID_HANDLE_VALUE)
    {
        DWORD dwLastError = ::GetLastError();

        if( dwLastError != ERROR_NO_MORE_FILES &&
            dwLastError != ERROR_FILE_NOT_FOUND)
        {
            return FALSE;
        }

        // No files found
        return TRUE;
    }
     do
     {
         if( d.cFileName[0] &&  _tcscmp( d.cFileName, _T( "." )) != 0 &&_tcscmp( d.cFileName, _T( ".." )) != 0 )
         {
             name = d.cFileName;
             if(GetLastWriteTime( d.ftLastWriteTime, szBuf, MAX_PATH ))
             {
                _tprintf(TEXT("Last write time is: %s\n"), szBuf);
                first[szBuf] = name;
             }
         }
     }while (FindNextFile ( hFindFile, &d ));

    return 0;
}
</code>```

Title: Sort files according to creation date?

Body:
First Problem is solved. Files is perfectly arrange.

for (int i = 0; i < allFiles.GetSize(); i++)
{
    box1.AddString(allFiles[i]);
}

vector<file> files;

vector<tstring> vec;
vec.insert(vec.begin(), &allFiles[0], &allFiles[allFiles.GetSize() - 1] + 1);

transform(vec.begin(), vec.end(),back_inserter(files),[](wstring const &fname)
{
    WIN32_FIND_DATA d;
    HANDLE h = FindFirstFile(fname.c_str(), &d);
    FindClose(h);
    return d;
}

);

sort(files.begin(), files.end());
CStringArray sortFiles;
files.insert(files.begin(), &sortFiles[0], &sortFiles[sortFiles.GetSize() - 1] + 1);

Now The problem is how i save sort files in CStringArray. Last Statement show the error see the comments?

Body:
Simple way to sort file based on creation date or last write date is store the files in to a map where Key is the date and value is the file name. Map will sort it for you.. my code example as below..

BOOL GetLastWriteTime(FILETIME ftWrite, LPWSTR lpszString, DWORD dwSize)
{
     DWORD dwRet;
     SYSTEMTIME st, stLocal;
    // Convert the last-write time to local time.
    FileTimeToSystemTime(&ftWrite, &st);
    SystemTimeToTzSpecificLocalTime(NULL, &st, &stLocal);

    // Build a string showing the date and time.
    dwRet = StringCchPrintf(lpszString, dwSize,
        TEXT("%02d%02d%d%02d%02d%02d%04d"),
        stLocal.wMonth, stLocal.wDay, stLocal.wYear,
        stLocal.wHour, stLocal.wMinute, stLocal.wSecond, stLocal.wMilliseconds);

    if( S_OK == dwRet )
        return TRUE;
    else return FALSE;
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::map<wstring, wstring> first;

     wstring directory = L"D:\\SourceCode\\FilesTemp\\*";
     std::wstring name;
     WCHAR szBuf[MAX_PATH];
     WIN32_FIND_DATA d;
     HANDLE hFindFile   = FindFirstFile ( directory.c_str(), &d );

     if (hFindFile == INVALID_HANDLE_VALUE)
    {
        DWORD dwLastError = ::GetLastError();

        if( dwLastError != ERROR_NO_MORE_FILES &&
            dwLastError != ERROR_FILE_NOT_FOUND)
        {
            return FALSE;
        }

        // No files found
        return TRUE;
    }
     do
     {
         if( d.cFileName[0] &&  _tcscmp( d.cFileName, _T( "." )) != 0 &&_tcscmp( d.cFileName, _T( ".." )) != 0 )
         {
             name = d.cFileName;
             if(GetLastWriteTime( d.ftLastWriteTime, szBuf, MAX_PATH ))
             {
                _tprintf(TEXT("Last write time is: %s\n"), szBuf);
                first[szBuf] = name;
             }
         }
     }while (FindNextFile ( hFindFile, &d ));

    return 0;
}


问:
Java Hibernate + spring-data: Cascading Childs not working when Parent is persistent
I have a Parent-Child relashionship and my issue starts when I try to add a new Child through an update on the Parent.

When my Parent is transient, everything works fine

```<code>    CreditCard cc = new CreditCard("1234");

    //User
    User u1 = new User("KILLER");
    u1.addCreditCard(cc); // bi-directional happens here inside.

    // An autowired Spring Data repository that implements CrudRepository
    userRepository.save(u1);

    Assert.assertEquals(1, u1.getCreditCardCollection().size());
    Assert.assertNotNull
    (
            u1.getCreditCardCollection()
            .stream()
            .findFirst()
            .get()
            .getIdCreditCard()
    );
</code>```

The test above is succesfully performed and an ID is generated for cc object.

But when I do:

```<code>    User u2 = new User("Foo Bar McLoud"); // u2 is transient

    userRepository.save(u2); // Now u2 is persistent

    u2 = userRepository.findOne(u2.getIdLogin());// just to be sure I´m working with a persistent object ;)

    CreditCard ccNew = new CreditCard("77777");

    u2.addCreditCard(ccNew );// bidirectional happens here inside

    userRepository.save(u2); // should insert a new credit card right???

    Assert.assertEquals("User should have 1 credit card.",
            1, u2.getCreditCardCollection().size()); // PASS

    Set<CreditCard> ccs = u2.getCreditCardCollection();
    for (CreditCard cc : ccs) {
        Assert.assertNotNull("CreditCard ID is null", cc.getIdCreditCard()); // FAIL: id is not generated. The database entry was not set. Added credit card is still transient...
    }
</code>```

So, in my second Test, my ccNew is still transient after an update on its parent.

Why is it still transient??

Child configuration:

```<code>@JoinColumn(name = "id_user")
@ManyToOne(optional = false)
private User user;
</code>```

Parent configuration:

```<code>@OneToMany(mappedBy = "user")
@org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.ALL)
private Set<CreditCard> creditCardCollection = new HashSet<>();
</code>```

Already tried on Parent:

```<code>    @OneToMany(mappedBy = "user",cascade=javax.persistence.CascadeType.ALL)
    private Set<CreditCard> creditCardCollection = new HashSet<>();
</code>```

答:
you test work inside one transaction ,in this you work with (u2.getCreditCardCollection()) with values from object not with entity (save is not executed yet):

Assert.assertEquals("User should have 2 credit cards.",
                  1, u2.getCreditCardCollection().size());

when you iterate over u2.getCreditCardCollection() and check id , they are null as insert and id generation comes only in commit stage or flush/clear context.

You need call saveAndFlush() instead of just save().

```<code>    u2 = userRepository.findOne(u2.getIdLogin());

    CreditCard ccNew = new CreditCard("77777");

    u2.addCreditCard(ccNew );// bidirectional happens here inside

    userRepository.saveAndFlush(u2);

    Assert.assertEquals("User should have 2 credit cards.",
            1, u2.getCreditCardCollection().size()); // PASS

    Set<CreditCard> ccs = u2.getCreditCardCollection();
    for (CreditCard cc : ccs) {
        Assert.assertNotNull("CreditCard ID is null", cc.getIdCreditCard());
    }
</code>```

from api ;

void flush() Flushes all pending changes to the database.

 S saveAndFlush(S entity)
  Saves an entity and flushes changes instantly

Body:
I have a Parent-Child relashionship and my issue starts when I try to add a new Child through an update on the Parent.

When my Parent is transient, everything works fine

    CreditCard cc = new CreditCard("1234");

    //User
    User u1 = new User("KILLER");
    u1.addCreditCard(cc); // bi-directional happens here inside.

    // An autowired Spring Data repository that implements CrudRepository
    userRepository.save(u1);

    Assert.assertEquals(1, u1.getCreditCardCollection().size());
    Assert.assertNotNull
    (
            u1.getCreditCardCollection()
            .stream()
            .findFirst()
            .get()
            .getIdCreditCard()
    );

The test above is succesfully performed and an ID is generated for cc object.

But when I do:

    User u2 = new User("Foo Bar McLoud"); // u2 is transient

    userRepository.save(u2); // Now u2 is persistent

    u2 = userRepository.findOne(u2.getIdLogin());// just to be sure I´m working with a persistent object ;)

    CreditCard ccNew = new CreditCard("77777");

    u2.addCreditCard(ccNew );// bidirectional happens here inside

    userRepository.save(u2); // should insert a new credit card right???

    Assert.assertEquals("User should have 1 credit card.",
            1, u2.getCreditCardCollection().size()); // PASS

    Set<CreditCard> ccs = u2.getCreditCardCollection();
    for (CreditCard cc : ccs) {
        Assert.assertNotNull("CreditCard ID is null", cc.getIdCreditCard()); // FAIL: id is not generated. The database entry was not set. Added credit card is still transient...
    }

So, in my second Test, my ccNew is still transient after an update on its parent.

Why is it still transient??

Child configuration:

@JoinColumn(name = "id_user")
@ManyToOne(optional = false)
private User user;

Parent configuration:

@OneToMany(mappedBy = "user")
@org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.ALL)
private Set<CreditCard> creditCardCollection = new HashSet<>();

Already tried on Parent:

    @OneToMany(mappedBy = "user",cascade=javax.persistence.CascadeType.ALL)
    private Set<CreditCard> creditCardCollection = new HashSet<>();

Body:
you test work inside one transaction ,in this you work with (u2.getCreditCardCollection()) with values from object not with entity (save is not executed yet):

Assert.assertEquals("User should have 2 credit cards.",
                  1, u2.getCreditCardCollection().size());

when you iterate over u2.getCreditCardCollection() and check id , they are null as insert and id generation comes only in commit stage or flush/clear context.

You need call saveAndFlush() instead of just save().

    u2 = userRepository.findOne(u2.getIdLogin());

    CreditCard ccNew = new CreditCard("77777");

    u2.addCreditCard(ccNew );// bidirectional happens here inside

    userRepository.saveAndFlush(u2);

    Assert.assertEquals("User should have 2 credit cards.",
            1, u2.getCreditCardCollection().size()); // PASS

    Set<CreditCard> ccs = u2.getCreditCardCollection();
    for (CreditCard cc : ccs) {
        Assert.assertNotNull("CreditCard ID is null", cc.getIdCreditCard());
    }

from api ;

void flush() Flushes all pending changes to the database.

 S saveAndFlush(S entity)
  Saves an entity and flushes changes instantly


问:
spring boot : The import org.springframework.jdbc.core.JdbcTemplate cannot be resolved
I am having a hard time with one of my test programs which I am trying to write using springboot. When I try to import the JdbcTemplate class in the DAO layer I get an error : The import org.springframework.jdbc.core.JdbcTemplate cannot be resolved

I am not sure what I am missing, I have checked the dependency and they look fine to me. Below is my pom.xml

```<code>    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.vittles</groupId>
    <artifactId>FoodFood</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>FoodFood</name>
    <url>http://maven.apache.org</url>

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Attached is the error which I get in my java file

Also attach is the list of jar imports .
Can some one please let me know what I am doing wrong.

答:
delete the folder ‘spring-jdbc’ from the maven repository:

%your_path%.m2\repository\org\springframework\spring-jdbc

open Eclipse -> right click on your project -> Maven -> Update project...

P.S. pom.xml should contain the jdbc dependency:

```<code><dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
</code>```

Body:
I am having a hard time with one of my test programs which I am trying to write using springboot. When I try to import the JdbcTemplate class in the DAO layer I get an error : The import org.springframework.jdbc.core.JdbcTemplate cannot be resolved

I am not sure what I am missing, I have checked the dependency and they look fine to me. Below is my pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.vittles</groupId>
    <artifactId>FoodFood</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>FoodFood</name>
    <url>http://maven.apache.org</url>

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Attached is the error which I get in my java file

Also attach is the list of jar imports .
Can some one please let me know what I am doing wrong.

Body:
delete the folder ‘spring-jdbc’ from the maven repository:

%your_path%.m2\repository\org\springframework\spring-jdbc

open Eclipse -> right click on your project -> Maven -> Update project...

P.S. pom.xml should contain the jdbc dependency:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>


问:
Rabbitmq , connect to remote host
I want to connect to rabbitmq remotely, my code is

```<code> public class ReceiveLogsDirect {

      private static final String EXCHANGE_NAME = "direct_logs";

      public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
          factory.setUsername("guest");
          factory.setPassword("guest");
          factory.setVirtualHost("/");
          factory.setHost("192.168.23.214");
          factory.setPort(5672);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        String queueName = channel.queueDeclare().getQueue();

          channel.queueBind(queueName, EXCHANGE_NAME, "user_one");

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        Consumer consumer = new DefaultConsumer(channel) {
          @Override
          public void handleDelivery(String consumerTag, Envelope envelope,
                                     AMQP.BasicProperties properties, byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + message + "'");
          }
        };
        channel.basicConsume(queueName, true, consumer);
      }
    }
</code>```

192.168.23.214 its the local ipv4 address of PC with rabbitmq, but i have the following error

```<code>Exception in thread "main" com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:349)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:63)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:99)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:911)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:870)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:828)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:979)
at tutorial5.ReceiveLogsDirect.main(ReceiveLogsDirect.java:21)
</code>```

My rabbitmq.config contein one line: [{loopback_users, []}].
Any suggestions?

答: Finally, i changed my config to [{rabbit, [{loopback_users, []}]}].

Title: Rabbitmq , connect to remote host

Body:
I want to connect to rabbitmq remotely, my code is

 public class ReceiveLogsDirect {

      private static final String EXCHANGE_NAME = "direct_logs";

      public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
          factory.setUsername("guest");
          factory.setPassword("guest");
          factory.setVirtualHost("/");
          factory.setHost("192.168.23.214");
          factory.setPort(5672);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        String queueName = channel.queueDeclare().getQueue();

          channel.queueBind(queueName, EXCHANGE_NAME, "user_one");

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        Consumer consumer = new DefaultConsumer(channel) {
          @Override
          public void handleDelivery(String consumerTag, Envelope envelope,
                                     AMQP.BasicProperties properties, byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + message + "'");
          }
        };
        channel.basicConsume(queueName, true, consumer);
      }
    }

192.168.23.214 its the local ipv4 address of PC with rabbitmq, but i have the following error

Exception in thread "main" com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:349)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:63)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:99)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:911)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:870)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:828)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:979)
at tutorial5.ReceiveLogsDirect.main(ReceiveLogsDirect.java:21)

My rabbitmq.config contein one line: [{loopback_users, []}].
Any suggestions?


问:
Is it possible to run GAE tests in Hudson?
I have a suite of App Engine tests that are called using nose. When I run them from a terminal, every test completes successfully and all reports, like coverage, are generated.

However, if I try to call the same command from Hudson, I get the following failure from coverage:

```<code>nose.failure.Failure.runTest (from Failure)

Parent module 'coverage' not loaded
-------------------- >> begin captured logging << --------------------
root: INFO: zipimporter('/home/wraith/dev/projects/myapp/lib/python2.5/site-packages/NoseGAE-0.1.7-py2.5.egg', '')
root: WARNING: Could not read datastore data from /tmp/nosegae.datastore
root: WARNING: Could not initialize images API; you are likely missing the Python "PIL" module. ImportError: No module named Image
root: INFO: zipimporter('/home/wraith/dev/projects/myapp/lib/python2.5/site-packages/gaetestbed-0.12dev_r30-py2.5.egg', '')
root: INFO: zipimporter('/home/wraith/dev/projects/myapp/lib/python2.5/site-packages/WebTest-1.2.1-py2.5.egg', '')
root: INFO: zipimporter('/home/wraith/dev/projects/myapp/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '')
root: INFO: zipimporter('/home/wraith/dev/projects/myapp/lib/python2.5/site-packages/WebOb-0.9.8-py2.5.egg', '')
root: INFO: zipimporter('/home/wraith/dev/projects/myapp/lib/python2.5/site-packages/PyYAML-3.09-py2.5-linux-x86_64.egg', '')
root: DEBUG: Could not import "strop": Disallowed C-extension or built-in module
--------------------- >> end captured logging << ---------------------
</code>```

However, if I remove the call to coverage, my tests still fail.

I've succesfully run Python projects with Hudson. Is there a GAE nuance that's tripping me up?

答:
Compare the environments when you run it manually to when you run it using hudson.

I suspect that the initialization happens within the .profile file. That is not called when Hudson spawns a shell. So either you put this initialization into the environment initialization or you call the .profile file manually within the effected build steps.

Body:
I have a suite of App Engine tests that are called using nose. When I run them from a terminal, every test completes successfully and all reports, like coverage, are generated.

However, if I try to call the same command from Hudson, I get the following failure from coverage:

nose.failure.Failure.runTest (from Failure)

Parent module 'coverage' not loaded
-------------------- >> begin captured logging << --------------------
root: INFO: zipimporter('/home/wraith/dev/projects/myapp/lib/python2.5/site-packages/NoseGAE-0.1.7-py2.5.egg', '')
root: WARNING: Could not read datastore data from /tmp/nosegae.datastore
root: WARNING: Could not initialize images API; you are likely missing the Python "PIL" module. ImportError: No module named Image
root: INFO: zipimporter('/home/wraith/dev/projects/myapp/lib/python2.5/site-packages/gaetestbed-0.12dev_r30-py2.5.egg', '')
root: INFO: zipimporter('/home/wraith/dev/projects/myapp/lib/python2.5/site-packages/WebTest-1.2.1-py2.5.egg', '')
root: INFO: zipimporter('/home/wraith/dev/projects/myapp/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '')
root: INFO: zipimporter('/home/wraith/dev/projects/myapp/lib/python2.5/site-packages/WebOb-0.9.8-py2.5.egg', '')
root: INFO: zipimporter('/home/wraith/dev/projects/myapp/lib/python2.5/site-packages/PyYAML-3.09-py2.5-linux-x86_64.egg', '')
root: DEBUG: Could not import "strop": Disallowed C-extension or built-in module
--------------------- >> end captured logging << ---------------------

However, if I remove the call to coverage, my tests still fail.

I've succesfully run Python projects with Hudson. Is there a GAE nuance that's tripping me up?


问:
Use of With Clause in SQL Server
How does with clause work in SQL Server? Does it really give me some performance boost or does it just help to make more readable scripts?

When it is right to use it? What should you know about with clause before you start to use it?

Here's an example of what I'm talking about:

http://www.dotnetspider.com/resources/33984-Use-With-Clause-Sql-Server.aspx

答:
with is a keyword in SQL which just stores the temporary result in a temporary table. Example:

```<code>with a(--here a is the temporary table)
(id)(--id acts as colomn for table a )
 as(select colomn_name from table_name )

select * from a
</code>```

Title: Use of With Clause in SQL Server

Body:
with is a keyword in SQL which just stores the temporary result in a temporary table. Example:

with a(--here a is the temporary table)
(id)(--id acts as colomn for table a )
 as(select colomn_name from table_name )

select * from a


问:
Can I use GitLab with centralize git repository server
My scenario is I have centralized Git repository server is running which is used by developers and they push their codes from local to centralize Git server.

Because GitLab has more features visualization,management like github so I am planing to use it with existing setup.

Is it possible to implement GitLab with git-server and keep up-to-date, every push over git-server will reflact on gitlab too ?

答:
You could add GitLab CE on your Git server, pointing it to your existing bare repo.

That way, you would push to the same server, and still benefit from GitLab features.

If you intend to mirror your git server pushes to gitlab.com, then you would need post-receive hooks on your bare repo in order to push them to their equivalent repos declared on gitlab.com.