问:
SQL - summarize all Product Types from a list of Authorized
I'm trying to figure out how to display the TYPES of orders each client can place with us. We have the following tables CLIENTS, CLIENT_SERVICE_TYPE, SERVICE_TYPES, PRODUCT_TYPE

We have many service types which can be easily associated with Fruits and Vegetables.

CLIENTS - Lists all our clients

   CLIENT_SERVICE_TYPE - lists all of the service types (Apples, Pears, Bananas, Squash, Chicken) they are authorized to place.

   SERVICE_TYPES - lists the hundreds and hundreds of fruits and vegetables we offer (Of which, each client can only order a select few from.

   PRODUCT_TYPE lists the 5 categories we offer (IE Fruits, Vegetables, Spices, Dairy, Meat)

I want to be able to create a summary report that will display certain Clients like this

Company Name | Sales Rep  | Product Types

Company ABC  | Jane Smith | Fruits

Company XYZ  | Joe Aardvark | Vegetables, Fruits

Company 123  | Amy Addams | Meat, Vegetables, Fruits

In the above example, Company ABC has 15 authorized Fruits (Bananas, Apples, Oranges, etc) but its summarized as 1 on one line Fruits.  Company XYZ has the same 15 authorized fruits and 1 carrot.  I want it to show up (order doesn't matter) as  Vegetables, Fruits on the same line.  Company 123 is authorized for only 4 services (Chicken, Bananas, Peas and Squash).  Meat, Vegetables, Fruits

I know this is probably simple to find existing tutorials on, but my terminology is obviously not up to par.  This is as far as I got and as you can probably guess, it's showing up multiple lines for the X amount of service types they are approved for.

```<code>SELECT
    company [Client Name]
    ,salesperson [Sales Rep]
    --,pt.productTypeName [List of approved Product Types]
    FROM CLIENT cl (NOLOCK)
        LEFT JOIN
    CLIENT_SERVICE_TYPE cst (NOLOCK) = cl.client_key = cst.client_key
        LEFT JOIN
    SERVICE_TYPE st (NOLOCK) = cst.service_key = st.service_key
        LEFT JOIN
    PRODUCT_TYPE pt (NOLOCK) = cst.productTypeId = pt.productTypeId
WHERE cl.client_program_id in (1,2,3)
    and status = 160
ORDER BY company
</code>```

答:
Found the answer through trial and error.  Within a SELECT statement, this is how I did it

```<code>SELECT
company as [Company Name]
,salesperson as [Sales Rep]
,(STUFF((SELECT CAST(', ' + productTypeName AS VARCHAR(MAX))
    FROM CLIENT_SERVICE_TYPE cst
        LEFT JOIN
    SERVICE_TYPE st on cst.service_type_key = st.service_type_key
        LEFT JOIN
    PRODUCT_TYPE pt on st.product_type_key = pt.product_type_key
    WHERE c.client_key = cst.client_key
    GROUP BY pt.product_type_name
    FOR XML PATH ('')),1,2, '')) [Product Types]
FROM CLIENT c
</code>```

The end results

Company Name | Sales Rep    | Product Types

Company ABC  | Jane Smith   | Fruits

Company XYZ  | Joe Aardvark | Vegetables, Fruits

Company 123  | Amy Addams   | Meat, Vegetables, Fruits

Body:
I'm trying to figure out how to display the TYPES of orders each client can place with us. We have the following tables CLIENTS, CLIENT_SERVICE_TYPE, SERVICE_TYPES, PRODUCT_TYPE

We have many service types which can be easily associated with Fruits and Vegetables.

CLIENTS - Lists all our clients

   CLIENT_SERVICE_TYPE - lists all of the service types (Apples, Pears, Bananas, Squash, Chicken) they are authorized to place.

   SERVICE_TYPES - lists the hundreds and hundreds of fruits and vegetables we offer (Of which, each client can only order a select few from.

   PRODUCT_TYPE lists the 5 categories we offer (IE Fruits, Vegetables, Spices, Dairy, Meat)

I want to be able to create a summary report that will display certain Clients like this

Company Name | Sales Rep  | Product Types

Company ABC  | Jane Smith | Fruits

Company XYZ  | Joe Aardvark | Vegetables, Fruits

Company 123  | Amy Addams | Meat, Vegetables, Fruits

In the above example, Company ABC has 15 authorized Fruits (Bananas, Apples, Oranges, etc) but its summarized as 1 on one line Fruits.  Company XYZ has the same 15 authorized fruits and 1 carrot.  I want it to show up (order doesn't matter) as  Vegetables, Fruits on the same line.  Company 123 is authorized for only 4 services (Chicken, Bananas, Peas and Squash).  Meat, Vegetables, Fruits

I know this is probably simple to find existing tutorials on, but my terminology is obviously not up to par.  This is as far as I got and as you can probably guess, it's showing up multiple lines for the X amount of service types they are approved for.

SELECT
    company [Client Name]
    ,salesperson [Sales Rep]
    --,pt.productTypeName [List of approved Product Types]
    FROM CLIENT cl (NOLOCK)
        LEFT JOIN
    CLIENT_SERVICE_TYPE cst (NOLOCK) = cl.client_key = cst.client_key
        LEFT JOIN
    SERVICE_TYPE st (NOLOCK) = cst.service_key = st.service_key
        LEFT JOIN
    PRODUCT_TYPE pt (NOLOCK) = cst.productTypeId = pt.productTypeId
WHERE cl.client_program_id in (1,2,3)
    and status = 160
ORDER BY company

Body:
Found the answer through trial and error.  Within a SELECT statement, this is how I did it

SELECT
company as [Company Name]
,salesperson as [Sales Rep]
,(STUFF((SELECT CAST(', ' + productTypeName AS VARCHAR(MAX))
    FROM CLIENT_SERVICE_TYPE cst
        LEFT JOIN
    SERVICE_TYPE st on cst.service_type_key = st.service_type_key
        LEFT JOIN
    PRODUCT_TYPE pt on st.product_type_key = pt.product_type_key
    WHERE c.client_key = cst.client_key
    GROUP BY pt.product_type_name
    FOR XML PATH ('')),1,2, '')) [Product Types]
FROM CLIENT c

The end results

Company Name | Sales Rep    | Product Types

Company ABC  | Jane Smith   | Fruits

Company XYZ  | Joe Aardvark | Vegetables, Fruits

Company 123  | Amy Addams   | Meat, Vegetables, Fruits


来源: stackexchange

问:
"The requested fetchSize is more than the allowed value in Athena" with JDBC driver
I'm trying to pull data from an Athena DB into R using RJDBC as described in detail on AWS's own blog. Alas, the amount of data I'm trying to pull is substantial and so I'm getting the following error message:

```<code>Error in .jcall(rp, "I", "fetch", stride, block) :
  java.sql.SQLException: The requested fetchSize is more than the allowed value in Athena. Please reduce the fetchSize and try again. Refer to the Athena documentation for valid fetchSize values.
</code>```

The Athena documentation doesn't actually give any such fetchSize values but I gather from this github issue that the value should be lower than 1000. I gather from the same github issue that there is no way to pass this fetchSize to RJDBC. So are there other ways of querying Athena that respect this limit?

答:
The basic problem is that dbGetQuery doesn't allow one to specify the fetchSize. As per the RJDBC package author one workaround is to call the two functions that dbGetQuery wraps separately and pass the fetchSize to fetch():

```<code>q <- dbSendQuery(c, ...)
fetch(q, -1, block=999)
</code>```

More generally:

```<code>setMethod("dbGetQuery", signature(conn="JDBCConnection", statement="character"),  def=function(conn, statement, ...) {
  r <- dbSendQuery(conn, statement, ...)
  on.exit(.jcall(r@stat, "V", "close"))
  if (conn@jc %instanceof% "com.amazonaws.athena.jdbc.AthenaConnection") fetch(r, -1, 999) # Athena can only pull 999 rows at a time
  else fetch(r, -1)
})
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to pull data from an Athena DB into R using RJDBC as described in detail on AWS's own blog. Alas, the amount of data I'm trying to pull is substantial and so I'm getting the following error message:

Error in .jcall(rp, "I", "fetch", stride, block) :
  java.sql.SQLException: The requested fetchSize is more than the allowed value in Athena. Please reduce the fetchSize and try again. Refer to the Athena documentation for valid fetchSize values.

The Athena documentation doesn't actually give any such fetchSize values but I gather from this github issue that the value should be lower than 1000. I gather from the same github issue that there is no way to pass this fetchSize to RJDBC. So are there other ways of querying Athena that respect this limit?

Body:
The basic problem is that dbGetQuery doesn't allow one to specify the fetchSize. As per the RJDBC package author one workaround is to call the two functions that dbGetQuery wraps separately and pass the fetchSize to fetch():

q <- dbSendQuery(c, ...)
fetch(q, -1, block=999)

More generally:

setMethod("dbGetQuery", signature(conn="JDBCConnection", statement="character"),  def=function(conn, statement, ...) {
  r <- dbSendQuery(conn, statement, ...)
  on.exit(.jcall(r@stat, "V", "close"))
  if (conn@jc %instanceof% "com.amazonaws.athena.jdbc.AthenaConnection") fetch(r, -1, 999) # Athena can only pull 999 rows at a time
  else fetch(r, -1)
})


问:
Javascript Date Returning NaN undefined NaN
I am pulling modified dates from a SharePoint library and using the below to convert it:

```<code>    function convertSPDate(d) {
    // split apart the date and time
    var xDate = d.split("")[0];
    var xTime = d.split(" ")[1];

    // split apart the hour, minute, & second
    var xTimeParts = xTime.split(":");
    var xHour = xTimeParts[0];
    var xMin = xTimeParts[1];

    // split apart the year, month, & day
    var xDateParts = xDate.split("-");
    var xMonth = xDateParts[1]-1;
    var xDay = xDateParts[2];
    var xYear = xDateParts[0];

    var dDate = new Date(xYear, xMonth, xDay, xHour, xMin);
    return dDate;
}
</code>```

And then formatting it using:

```<code>function getformattedDate(d){
var month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "October", "Nov" , "Dec"];
var getConvertedDate = d;
return formattedDate =  getConvertedDate.getDate() +" "+month[getConvertedDate.getMonth()] +" "+getConvertedDate.getFullYear();
}
</code>```

I'm then trying to display this date on a page for different items using:

```<code>var getDate = getformattedDate(convertSPDate(getFilteredItems[i].modified));
</code>```

However this is just returning NaN undefined NaN - any help at all would be much appreciated!

答:
For what it's worth, if you use moment.js this is a one-liner :

var d = moment("2017-06-06 19:15").format("D MMM YYYY");

jsbin link

Body:
I am pulling modified dates from a SharePoint library and using the below to convert it:

    function convertSPDate(d) {
    // split apart the date and time
    var xDate = d.split("")[0];
    var xTime = d.split(" ")[1];

    // split apart the hour, minute, & second
    var xTimeParts = xTime.split(":");
    var xHour = xTimeParts[0];
    var xMin = xTimeParts[1];

    // split apart the year, month, & day
    var xDateParts = xDate.split("-");
    var xMonth = xDateParts[1]-1;
    var xDay = xDateParts[2];
    var xYear = xDateParts[0];

    var dDate = new Date(xYear, xMonth, xDay, xHour, xMin);
    return dDate;
}

And then formatting it using:

function getformattedDate(d){
var month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "October", "Nov" , "Dec"];
var getConvertedDate = d;
return formattedDate =  getConvertedDate.getDate() +" "+month[getConvertedDate.getMonth()] +" "+getConvertedDate.getFullYear();
}

I'm then trying to display this date on a page for different items using:

var getDate = getformattedDate(convertSPDate(getFilteredItems[i].modified));

However this is just returning NaN undefined NaN - any help at all would be much appreciated!


问:
Take from a list only the element i just clicked and use it
i have a list and when someone clicks on an li element then with $.ajax()  i fetch the specific data it wants.

for ie :

```<code><li id="test1">test 1 </li>
<li id="test2">test 2 </li>
<li id="test3">test 3 </li>
...
<li id="testN">test N </li>
</code>```

So the ajax part is for test 1 :

```<code>$('#test1').click(function() {

 $.ajax({
  url: 'fetch.php',
  type: 'POST',
  data: { temp : 'test1'},
  success: function(data) {
    $('#test1').append(data);
  }
});
</code>```

and the same for 2,3,4...N

But the problem is it comes too much of code..ok its just copy paste but can i do it another way? meaning when i click test1 element jQuery finds out what element i clicked and runs for it...

Sorry my bad english
thanks

答:
Use the change even to only fire when you select an item from the list:</p>

```<code>$('#test1').change(function() {
    $.ajax({
    url: 'fetch.php',
    type: 'POST',
    data: { temp : 'test1'},
    success: function(data) {
        $('#test1').append(data);
    }
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
i have a list and when someone clicks on an li element then with $.ajax()  i fetch the specific data it wants.

for ie :

test 1

test 2

test 3

...

test N

So the ajax part is for test 1 :

$('#test1').click(function() {

 $.ajax({
  url: 'fetch.php',
  type: 'POST',
  data: { temp : 'test1'},
  success: function(data) {
    $('#test1').append(data);
  }
});

and the same for 2,3,4...N

But the problem is it comes too much of code..ok its just copy paste but can i do it another way? meaning when i click test1 element jQuery finds out what element i clicked and runs for it...

Sorry my bad english
thanks

Body:
Use the change even to only fire when you select an item from the list:

$('#test1').change(function() {
    $.ajax({
    url: 'fetch.php',
    type: 'POST',
    data: { temp : 'test1'},
    success: function(data) {
        $('#test1').append(data);
    }
});


问:
Testing A function
I need to write a unit test for a function. I have no idea about testing and the examples I have seen are more maths oriented so I can not understand how to write a test for this funtion. Can Anyone please help me write a unit test for this function:</p>

```<code>public static void CreateUser(
    int userId,
    string name,
    System.DateTime createdAt,
    string createdBy,
    System.DateTime modifiedAt,
    string modifiedBy,
    string address,
    string city,
    string province,
    string country,
    string postcode,
    string phone)
{
    try
    {
        using (UserDbContext _usermain = new UserDbContext())
        {
            User newuser = new User()
            {
                UserId = userId,
                Name = name,
                CreatedAt = createdAt,
                CreatedBy = createdBy,
                ModifiedBy = modifiedBy,
                ModifiedAt = modifiedAt,
                Address = address,
                City = city
            };
            _usermain.Users.Add(newuser);
            _usermain.SaveChanges();
        }
    }
    catch (Exception ex)
    {
        string error = string.Format("Error in Creating User", ex.Message);
        throw new Exception(error, ex);
    }
}
</code>```

答:
Unit tests should be written to validate the behavior of a function.  In your case, your function is taking in input and updating a database.  Writing a unit test will be difficult since databases are very hard to mock.  You essentially would need to figure out a way to mock the UserDbContext, pass inputs to the function, and verify that the database is updated properly.

I would suggest that a unit test is not appropriate for this function.  Its sole purpose is to mutate an external environment that you cannot easily mock.  Some changes that would make it easier to test are:

inject the context instead of creating a new one (so you can pass in a mock).  That's probably more trouble than it's worth.

Making it two functions - one to create a User and one to take the User and insert it into the database. (In that case I would unit test the first method but not the second).  If you already have a unit test for the User constructor then the separation and unit test are not needed.

As a side note, catching any exception and throwing a new generic exception does not add value.  In fact it removes value since you lose or hide the following information:

The original stack trace

The error message

The type of exception.

All of these are buried in the InnerException when you throw a new exception.  Just take out the try/catch block and let the original exception bubble up if you're not going to do anything with it.

Title: Testing A function

Body:
I need to write a unit test for a function. I have no idea about testing and the examples I have seen are more maths oriented so I can not understand how to write a test for this funtion. Can Anyone please help me write a unit test for this function:

public static void CreateUser(
    int userId,
    string name,
    System.DateTime createdAt,
    string createdBy,
    System.DateTime modifiedAt,
    string modifiedBy,
    string address,
    string city,
    string province,
    string country,
    string postcode,
    string phone)
{
    try
    {
        using (UserDbContext _usermain = new UserDbContext())
        {
            User newuser = new User()
            {
                UserId = userId,
                Name = name,
                CreatedAt = createdAt,
                CreatedBy = createdBy,
                ModifiedBy = modifiedBy,
                ModifiedAt = modifiedAt,
                Address = address,
                City = city
            };
            _usermain.Users.Add(newuser);
            _usermain.SaveChanges();
        }
    }
    catch (Exception ex)
    {
        string error = string.Format("Error in Creating User", ex.Message);
        throw new Exception(error, ex);
    }
}


问:
How do I return a string in a Jest mocked component's render method without Flow complaining?
I'm mocking a React component in a Jest test, and flow is complaining:

```<code>[flow] string (This type is incompatible with the expected return type of React$Element)
</code>```

How do I allow for this?  Here's my code:

```<code>jest.mock('../../../../ui-components/lib/Forms/TextField', () => {
  const React = require('react');
  const TextField = class extends React.Component {
      render() {
          return 'TextField'; // Flow complains here
      }
  };
  return TextField;
});
</code>```

EDIT:

For those googling, this is what I did:

```<code>jest.mock('../../../../ui-components/lib/Forms/TextField', () => {
  const React = require('react');
  const TextField = class extends React.Component {
      render() {
          return <div />;
      }
  };
  return TextField;
});
</code>```

I was operating under an incorrect assumption that enzyme's shallow wrapper wouldn't locate the component unless I was returning a string here.  I'll be honest, I don't recall why I thought that, as it seems absurd now.

I've marked the answer to my original question below, as that was correct if I hadn't taken this better approach.  The use of // $FlowFixMe

答:
I'm not sure why you're doing this, but if you're certain about it, you  can add a //$FlowFixMe comment above the line that errors.

//$FlowFixMe Defines a magical comment that suppresses any Flow errors on the following line

Hope this helps.

Body:
I'm mocking a React component in a Jest test, and flow is complaining:

[flow] string (This type is incompatible with the expected return type of React$Element)

How do I allow for this?  Here's my code:

jest.mock('../../../../ui-components/lib/Forms/TextField', () => {
  const React = require('react');
  const TextField = class extends React.Component {
      render() {
          return 'TextField'; // Flow complains here
      }
  };
  return TextField;
});

EDIT:

For those googling, this is what I did:

jest.mock('../../../../ui-components/lib/Forms/TextField', () => {
  const React = require('react');
  const TextField = class extends React.Component {
      render() {
          return
;
      }
  };
  return TextField;
});

I was operating under an incorrect assumption that enzyme's shallow wrapper wouldn't locate the component unless I was returning a string here.  I'll be honest, I don't recall why I thought that, as it seems absurd now.

I've marked the answer to my original question below, as that was correct if I hadn't taken this better approach.  The use of // $FlowFixMe


问:
Combining Two Queries Without the Use of Certain Functions
I have two separate queries:

```<code>SELECT TIME_TO_SEC(SUM(odchodDoch - prichodDoch)) AS cisloDoch,
  SUM(prestavkaDoch) as presDoch,
  operatorDoch
  FROM dochazkaVyroba
    WHERE operatorDoch IN ("x","y","z")
    AND datumDoch BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY operatorDoch;

SELECT SUM(CAS) as cisloVyk,
  JMENO
  FROM produkce
    WHERE JMENO IN ("x","y","z")
    AND DATUM BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY JMENO;
</code>```

And I wish to combine these into a single query.

and separately I get the following results:

```<code>cisloDoch presDoch operatorDoch
 57600      60         x
  0         0          y
 57600      0          z

cisloVyk JMENO
 532       x
  0        y
 780       z
</code>```

What I am looking to do is combine the above queries into one, based on:

produkce.JMENO = dochazkaVyroba.operatorDoch,

so that I get following:

```<code>cisloDoch presDoch operatorDoch  cisloVyk JMENO
 57600      60         x             532    x
  0         0          y               0    y
 57600      0          z              780   z
</code>```

Unfortunately, FULL OUTER JOIN isn't usable in  MySQL.

I also cannot use UNION with ON produkce.JMENO = dochazkaVyroba.operatorDoch.

答:
The brute force way would be to just join the two subqueries:</p>

```<code>SELECT
    t1.cisloDoch,
    t1.presDoch,
    t1.operatorDoch,
    t2.cisloVyk,
    t2.JMENO
FROM
(
    SELECT
        TIME_TO_SEC(SUM(odchodDoch - prichodDoch)) AS cisloDoch,
        SUM(prestavkaDoch) AS presDoch,
        operatorDoch
    FROM dochazkaVyroba
    WHERE operatorDoch IN ("x","y","z") AND
          datumDoch BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY operatorDoch
) t1
INNER JOIN
(
    SELECT SUM(CAS) as cisloVyk, JMENO
    FROM produkce
    WHERE JMENO IN ("x","y","z") AND
          DATUM BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY JMENO
) t2
    ON t1.operatorDoch = t2.JMENO
</code>```

Body:
I have two separate queries:

SELECT TIME_TO_SEC(SUM(odchodDoch - prichodDoch)) AS cisloDoch,
  SUM(prestavkaDoch) as presDoch,
  operatorDoch
  FROM dochazkaVyroba
    WHERE operatorDoch IN ("x","y","z")
    AND datumDoch BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY operatorDoch;

SELECT SUM(CAS) as cisloVyk,
  JMENO
  FROM produkce
    WHERE JMENO IN ("x","y","z")
    AND DATUM BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY JMENO;

And I wish to combine these into a single query.

and separately I get the following results:

cisloDoch presDoch operatorDoch
 57600      60         x
  0         0          y
 57600      0          z

cisloVyk JMENO
 532       x
  0        y
 780       z

What I am looking to do is combine the above queries into one, based on:

produkce.JMENO = dochazkaVyroba.operatorDoch,

so that I get following:

cisloDoch presDoch operatorDoch  cisloVyk JMENO
 57600      60         x             532    x
  0         0          y               0    y
 57600      0          z              780   z

Unfortunately, FULL OUTER JOIN isn't usable in  MySQL.

I also cannot use UNION with ON produkce.JMENO = dochazkaVyroba.operatorDoch.

Body:
The brute force way would be to just join the two subqueries:

SELECT
    t1.cisloDoch,
    t1.presDoch,
    t1.operatorDoch,
    t2.cisloVyk,
    t2.JMENO
FROM
(
    SELECT
        TIME_TO_SEC(SUM(odchodDoch - prichodDoch)) AS cisloDoch,
        SUM(prestavkaDoch) AS presDoch,
        operatorDoch
    FROM dochazkaVyroba
    WHERE operatorDoch IN ("x","y","z") AND
          datumDoch BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY operatorDoch
) t1
INNER JOIN
(
    SELECT SUM(CAS) as cisloVyk, JMENO
    FROM produkce
    WHERE JMENO IN ("x","y","z") AND
          DATUM BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY JMENO
) t2
    ON t1.operatorDoch = t2.JMENO


问:
Google oauth login in codenameone on android devices using native client not working
I'm trying to implement GoogleConnect in a codenameone application.
Everything works ok in the simulator, using the web client, however on the device the authentication process is delegated to the native login which keeps showing a pop-up to select a google account. Once I select an accout, the pop-up disappears briefly and it reappears. And the only way to make it get away is to close the app.

I tried to force GoogleConnect to use the web client but, surprise, Google is not allowing ouath loging from embedded user agents anymore, as they have announced in this post:

https://developers.googleblog.com/2016/08/modernizing-oauth-interactions-in-native-apps.html

"In the coming months, we will no longer allow OAuth requests to Google in embedded browsers known as “web-views".

I'm getting a "useragent_dissalowed" error.

So apparently the only solution to this is to fix the native login.

So coming back to this, it looks like the GoogleConnect instance that is used on my android device is GoogleImpl, and judging by the behaviour, it looks like it goes through the flow implemented in this code fragment:

https://github.com/codenameone/CodenameOne/blob/master/Ports/Android/src/com/codename1/social/GoogleImpl.java#L198-L209

I'm assuming that the "GoogleAuthUtil.getToken" is throwing an "UserRecoverableAuthException" and it keeps retrying, although this is not "recoverable" by any means. Any help ?

Thanks.

答:
I have just applied a patch that should fix this issue.  The fix will be available in the next server update (Friday).

See patch here


问:
C# - Undeclared Prefix in XML
So I am trying to make a standard xml in C# but receive the error, 'xmii' is an undeclared prefix. I have researched the problem but nothing has seemed to work. Any suggestions?

```<code>        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<xmii:Request/>");

        docFrag.InnerXml = "<xmii:Name>" + name + "</xmii:Name>";
        doc.DocumentElement.AppendChild(docFrag);

        docFrag.InnerXml = "<xmii:PWord>" + pword + "</xmii:PWord>";
        doc.DocumentElement.AppendChild(docFrag);
</code>```

Here is an example of what the xml should look like

<xmii:Request>
  <xmii:Name>John</xmii:Name>
  <xmii:PWord>Monkey</xmii:PWord>
</xmii:Request>```

答:
Just to summarize the comments. Credit to @MichaelCoxon with his answer. The code works if this is included </p>

```<code>        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<xmii:Request xmlns:xmii=\"http://my.namespace.com/xmii/namespace\"/>");

        docFrag.InnerXml = "<xmii:Name xmlns:xmii=\"http://my.namespace.com/xmii/namespace\">" + name + "</xmii:Name>";
        doc.DocumentElement.AppendChild(docFrag);

        docFrag.InnerXml = "<xmii:PWord xmlns:xmii=\"http://my.namespace.com/xmii/namespace\">" + pword + "</xmii:PWord>";
        doc.DocumentElement.AppendChild(docFrag);
</code>```

Title: C# - Undeclared Prefix in XML

Body:
So I am trying to make a standard xml in C# but receive the error, 'xmii' is an undeclared prefix. I have researched the problem but nothing has seemed to work. Any suggestions?

        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<xmii:Request/>");

        docFrag.InnerXml = "<xmii:Name>" + name + "</xmii:Name>";
        doc.DocumentElement.AppendChild(docFrag);

        docFrag.InnerXml = "<xmii:PWord>" + pword + "</xmii:PWord>";
        doc.DocumentElement.AppendChild(docFrag);

Here is an example of what the xml should look like

<xmii:Request>
  <xmii:Name>John</xmii:Name>
  <xmii:PWord>Monkey</xmii:PWord>
</xmii:Request>

Body:
Just to summarize the comments. Credit to @MichaelCoxon with his answer. The code works if this is included

        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<xmii:Request xmlns:xmii=\"http://my.namespace.com/xmii/namespace\"/>");

        docFrag.InnerXml = "<xmii:Name xmlns:xmii=\"http://my.namespace.com/xmii/namespace\">" + name + "</xmii:Name>";
        doc.DocumentElement.AppendChild(docFrag);

        docFrag.InnerXml = "<xmii:PWord xmlns:xmii=\"http://my.namespace.com/xmii/namespace\">" + pword + "</xmii:PWord>";
        doc.DocumentElement.AppendChild(docFrag);


问:
How do I format a String in an email so Outlook will print the line breaks?
I'm trying to send an email in Java but when I read the body of the email in Outlook, it's gotten rid of all my linebreaks. I'm putting \n at the ends of the lines but is there something special I need to do other than that? The receivers are always going to be using Outlook.

I found a page on microsoft.com that says there's a 'Remove line breaks' "feature" in Outlook so does this mean there's no solution to get around that other than un-checking that setting?

Thanks

答: I had the same issue, and found a solution. Try this:  %0D%0A to add a line break.

OwnerDisplayName: MattGrommes

LastEditorDisplayName: Chris


问:
Why is sfinae on if constexpr not allowed?
The detection idiom works as follows

```<code>template<typename T, typename = void>
struct has_foo {static constexpr bool value = false;};
template<typename T>
struct has_foo<T, std::void_t<decltype(&T::foo)>> {static constexpr bool value = true;};
template<typename T>
constexpr bool has_foo_v = has_foo<T>::value;
</code>```

And then we can detect the presence of foo in any type T.

```<code>if constexpr(has_foo_v<decltype(var)>)
    var.foo();
</code>```

My problem is, that is quite a lot to type (read: want to smash my keyboard a lot to type), and I wondered if the following is possible

```<code>if constexpr(std::void_t<decltype(&decltype(var)::foo)>(), true)
    var.foo();
</code>```

It is not.

Is there a reason behind this?

More specifically, what trade-offs will have to be made if this were allowed?

答:
Your use of pointer to member function is a bad idea; if foo is overloaded, it spuriously fails (you have a foo, but not just one).  Who really wants "do you have exactly one foo"?  Almost nobody.

Here is a briefer version:

```<code>template<class T>
using dot_foo_r = decltype( std::declval<T>().foo() );

template<class T>
using can_foo = can_apply<dot_foo_r, T>;
</code>```

where

```<code>namespace details {
  template<template<class...>class, class, class...>
  struct can_apply:std::false_type{};
  template<template<class...>class Z, class...Ts>
  struct can_apply<Z, std::void_t<Z<Ts...>>, Ts...>:std::true_type{};
}
template<template<class...>class Z, class...Ts>
using can_apply = details::can_apply<Z, void, Ts...>;
</code>```

Now, writing dot_foo_r is a bit annoying.

With constexpr lambdas we can make it less annoying and do it inline.

```<code>#define RETURNS(...) \
  noexcept(noexcept(__VA_ARGS__)) \
  -> decltype(__VA_ARGS__) \
  { return __VA_ARGS__; }
</code>```

It does need the RETURNS macro, at least until @Barry's submission to [](auto&&f)RETURNS(f()) be equivalent to [](auto&&f)=>f().

We then write can_invoke, which is a constexpr variant of std::is_invocable:

```<code>template<class F>
constexpr auto can_invoke( F&& f ) {
  return [](auto&&...args)->std::is_invocable<F(decltype(args)...)>{
    return {};
  };
}
</code>```

This gives us:

```<code>if constexpr(
  can_invoke([](auto&&var) RETURNS(var.foo()))(var)
) {
  var.foo();
}
</code>```

or using @Barry's proposed C++20 syntax:

```<code>if constexpr(can_invoke(var=>var.foo())(var)) {
  var.foo();
}
</code>```

and we are done.

The trick is that RETURNS macro (or => C++20 feature) lets us do SFINAE on an expression.  The lambda becomes an easy way to carry that expression around as a value.

You could write

```<code>    [](auto&&var) ->decltype(var.foo()) { return var.foo(); }
</code>```

but I think RETURNS is worth it (and I don't like macros).

Body:
The detection idiom works as follows

template<typename T, typename = void>
struct has_foo {static constexpr bool value = false;};
template<typename T>
struct has_foo<T, std::void_t<decltype(&T::foo)>> {static constexpr bool value = true;};
template<typename T>
constexpr bool has_foo_v = has_foo<T>::value;

And then we can detect the presence of foo in any type T.

if constexpr(has_foo_v<decltype(var)>)
    var.foo();

My problem is, that is quite a lot to type (read: want to smash my keyboard a lot to type), and I wondered if the following is possible

if constexpr(std::void_t<decltype(&decltype(var)::foo)>(), true)
    var.foo();

It is not.

Is there a reason behind this?

More specifically, what trade-offs will have to be made if this were allowed?

Body:
Your use of pointer to member function is a bad idea; if foo is overloaded, it spuriously fails (you have a foo, but not just one).  Who really wants "do you have exactly one foo"?  Almost nobody.

Here is a briefer version:

template<class T>
using dot_foo_r = decltype( std::declval<T>().foo() );

template<class T>
using can_foo = can_apply<dot_foo_r, T>;

where

namespace details {
  template<template<class...>class, class, class...>
  struct can_apply:std::false_type{};
  template<template<class...>class Z, class...Ts>
  struct can_apply<Z, std::void_t<Z<Ts...>>, Ts...>:std::true_type{};
}
template<template<class...>class Z, class...Ts>
using can_apply = details::can_apply<Z, void, Ts...>;

Now, writing dot_foo_r is a bit annoying.

With constexpr lambdas we can make it less annoying and do it inline.

#define RETURNS(...) \
  noexcept(noexcept(__VA_ARGS__)) \
  -> decltype(__VA_ARGS__) \
  { return __VA_ARGS__; }

It does need the RETURNS macro, at least until @Barry's submission to [](auto&&f)RETURNS(f()) be equivalent to [](auto&&f)=>f().

We then write can_invoke, which is a constexpr variant of std::is_invocable:

template<class F>
constexpr auto can_invoke( F&& f ) {
  return [](auto&&...args)->std::is_invocable<F(decltype(args)...)>{
    return {};
  };
}

This gives us:

if constexpr(
  can_invoke([](auto&&var) RETURNS(var.foo()))(var)
) {
  var.foo();
}

or using @Barry's proposed C++20 syntax:

if constexpr(can_invoke(var=>var.foo())(var)) {
  var.foo();
}

and we are done.

The trick is that RETURNS macro (or => C++20 feature) lets us do SFINAE on an expression.  The lambda becomes an easy way to carry that expression around as a value.

You could write

    [](auto&&var) ->decltype(var.foo()) { return var.foo(); }

but I think RETURNS is worth it (and I don't like macros).

ContentLicense: CC BY-SA 4.0


问:
Unable to index x-axis of bokeh line chart with timestamps
I have been trying to make a bokeh line chart, however I am running into the issue of indexing the x-axis with a column of time stamps from my pandas data frame. Currently my data frame looks like this:

```<code>           TMAX TMIN  TAVG        DAY   NUM
2007-04-30   65   46  55.5 2007-04-30     1
2007-05-01   75   45  60.0 2007-05-01     2
2007-05-02   66   52  59.0 2007-05-02     3
2007-05-03   65   43  54.0 2007-05-03     4
2007-05-04   61   45  53.0 2007-05-04     5
2007-05-05   65   43  54.0 2007-05-05     6
2007-05-06   77   51  64.0 2007-05-06     7
2007-05-07   89   66  77.5 2007-05-07     8
2007-05-08   91   56  73.5 2007-05-08     9
2007-05-09   83   48  65.5 2007-05-09    10
2007-05-10   68   47  57.5 2007-05-10    11
2007-05-11   65   46  55.5 2007-05-11    12
2007-05-12   63   43  53.0 2007-05-12    13
2007-05-13   65   46  55.5 2007-05-13    14
2007-05-14   71   46  58.5 2007-05-14    15
....
[3592 rows x 5 columns]
</code>```

I want to index the line plot with the values of the "DAY" column, however, I get an error no matter the approach I take. The documentation for line plots says that "x (str or list(str), optional) – specifies variable(s) to use for x axis". My code is as follows:

```<code>xyvalues = np.array([df['TAVG'], df_reg['ry'], df['DAY']])
regr = Line(data=xyvalues, x='DAY', title="Linear Regression of Data", ylabel="Average Daily Temperature", xlabel="Number of Days")
output_file("regression.html")
show(regr)
</code>```

This gives me the error "TypeError: Cannot compare type 'Timestamp' with type 'float64'". I have tried converting it to float, but it doesn't seem to have an effect. Any help would be much appreciated. The df_reg['ry'] is data from a linear regression data frame.

Documentation for line graphs can be found here: http://docs.bokeh.org/en/latest/docs/reference/charts.html#line

答:
Inside Line, you need to pass a pandas data frame to the data argument in order to be able to refer to your variable DAY for the x axis ticks. Here I create a new pandas DataFrame from the other two:

```<code>import pandas as pd
df2 = pd.DataFrame(data=dict(TAVG=df['TAVG'], ry=df_reg['ry'], DAY=df['DAY']))
regr = Line(data=df2, x='DAY',
                 title="Linear Regression of Data",
                 ylabel="Average Daily Temperature",
                 xlabel="Number of Days")
output_file("regression.html")
show(regr)
</code>```

Body:
I have been trying to make a bokeh line chart, however I am running into the issue of indexing the x-axis with a column of time stamps from my pandas data frame. Currently my data frame looks like this:

           TMAX TMIN  TAVG        DAY   NUM
2007-04-30   65   46  55.5 2007-04-30     1
2007-05-01   75   45  60.0 2007-05-01     2
2007-05-02   66   52  59.0 2007-05-02     3
2007-05-03   65   43  54.0 2007-05-03     4
2007-05-04   61   45  53.0 2007-05-04     5
2007-05-05   65   43  54.0 2007-05-05     6
2007-05-06   77   51  64.0 2007-05-06     7
2007-05-07   89   66  77.5 2007-05-07     8
2007-05-08   91   56  73.5 2007-05-08     9
2007-05-09   83   48  65.5 2007-05-09    10
2007-05-10   68   47  57.5 2007-05-10    11
2007-05-11   65   46  55.5 2007-05-11    12
2007-05-12   63   43  53.0 2007-05-12    13
2007-05-13   65   46  55.5 2007-05-13    14
2007-05-14   71   46  58.5 2007-05-14    15
....
[3592 rows x 5 columns]

I want to index the line plot with the values of the "DAY" column, however, I get an error no matter the approach I take. The documentation for line plots says that "x (str or list(str), optional) – specifies variable(s) to use for x axis". My code is as follows:

xyvalues = np.array([df['TAVG'], df_reg['ry'], df['DAY']])
regr = Line(data=xyvalues, x='DAY', title="Linear Regression of Data", ylabel="Average Daily Temperature", xlabel="Number of Days")
output_file("regression.html")
show(regr)

This gives me the error "TypeError: Cannot compare type 'Timestamp' with type 'float64'". I have tried converting it to float, but it doesn't seem to have an effect. Any help would be much appreciated. The df_reg['ry'] is data from a linear regression data frame.

Documentation for line graphs can be found here: http://docs.bokeh.org/en/latest/docs/reference/charts.html#line

Body:
Inside Line, you need to pass a pandas data frame to the data argument in order to be able to refer to your variable DAY for the x axis ticks. Here I create a new pandas DataFrame from the other two:

import pandas as pd
df2 = pd.DataFrame(data=dict(TAVG=df['TAVG'], ry=df_reg['ry'], DAY=df['DAY']))
regr = Line(data=df2, x='DAY',
                 title="Linear Regression of Data",
                 ylabel="Average Daily Temperature",
                 xlabel="Number of Days")
output_file("regression.html")
show(regr)


问:
Problems with variable scope in example swap for powershell
```<code>$global:value1
$global:value2
$global:value3

function initialize {
    $value1 = 100
    $value2 = 500
}

function subtract {
    $value3 = $value1 - $value2
    Write-Host $value3
}

function swap {
    Write-Host Before swap Value1: $value1 "& Value2: "$value2
    $value3 = $value1
    $value1 = $value2
    $value2 = $value3
    Write-Host After swap Value1: $value1 "& Value2: "$value2
}

function run-myscript {
    cls
    initialize
    subtract
    swap
    subtract
}
</code>```

Output:

-400

  Before swap Value1: 100 & Value2:  500

  After swap Value1: 500 & Value2:  100

  -400

Please explain this behaviour why i get both values as -400, i should get once -400 and second time 400

答:
You might read global values that are created outside your function but if you set a value inside a function they will be newly created within the local scope (unless you explicitly refer to the global with $Global:...).

So, if you set $value1 = $value2 within your swap function you have two $value1 values: one local $Local:Value1 and one global: $Global:Value1.

Anyway, it is in general, it is not a good practice to manipulate global variables from within a function. Normally, you should input (pipe or arguments) and output (pipe) the concerned variables.
And if you do so, you will probably see the light and come to the conclusion that a swap 'function' already exists:

```<code>$Value1, $Value2 = $Value2, $Value1
</code>```

Body:
$global:value1
$global:value2
$global:value3

function initialize {
    $value1 = 100
    $value2 = 500
}

function subtract {
    $value3 = $value1 - $value2
    Write-Host $value3
}

function swap {
    Write-Host Before swap Value1: $value1 "& Value2: "$value2
    $value3 = $value1
    $value1 = $value2
    $value2 = $value3
    Write-Host After swap Value1: $value1 "& Value2: "$value2
}

function run-myscript {
    cls
    initialize
    subtract
    swap
    subtract
}

Output:

-400

  Before swap Value1: 100 & Value2:  500

  After swap Value1: 500 & Value2:  100

  -400

Please explain this behaviour why i get both values as -400, i should get once -400 and second time 400

Body:
You might read global values that are created outside your function but if you set a value inside a function they will be newly created within the local scope (unless you explicitly refer to the global with $Global:...).

So, if you set $value1 = $value2 within your swap function you have two $value1 values: one local $Local:Value1 and one global: $Global:Value1.

Anyway, it is in general, it is not a good practice to manipulate global variables from within a function. Normally, you should input (pipe or arguments) and output (pipe) the concerned variables.
And if you do so, you will probably see the light and come to the conclusion that a swap 'function' already exists:

$Value1, $Value2 = $Value2, $Value1


问:
Return integrated function using R
Let's say i have a function defined as the following in R:

```<code>> f <- function(x) 0.5*sin(x)*(x>=0)*(x<=pi)
</code>```

i can do this to integrate it between 0 and pi:

```<code>> Integrate <- function(f,a,b) integrate(Vectorize(f),a,b)$value
> F <- Integrate(f,0,pi)
</code>```

But if i want to evaluate and return some values of F i get this error:

```<code>> F(c(-100,0,1,2,pi,100))
Error in F(c(-100, 0, 1, 2, pi, 100)) :
      function "F" is not found
</code>```

i can understand that this is due to the fact, that my integrate <- function(f,a,b) returns a constant value C which is the result of the integration of f between a and b, but how can i return F as a function to be able to evaluate it's values as a vector and plot it ?

like in this case F should give 0 for any value less than 0 and 1 for any value bigger than pi and be variable between them.

Thanks.

Edit: just to sum it up more clearly: how can i define a function f(x) in [a,b] that will give me f(x) if x is in [a,b], 0 if xb ?

答:
Try wrapping your function call in an sapply and have Integrate return a function.

```<code>Integrate <- function(f, a, b)  function(x) if (x < a) 0 else if (x > b) 1 else integrate(Vectorize(f), a, x)$value
F <- Integrate(f, 0, pi)
sapply(c(-100,0,1,2,pi,100), F)
</code>```

gives

```<code>[1] 0.0000000 0.0000000 0.2298488 0.7080734 1.0000000 1.0000000
</code>```

Title: Return integrated function using R

Body:
Let's say i have a function defined as the following in R:

> f <- function(x) 0.5*sin(x)*(x>=0)*(x<=pi)

i can do this to integrate it between 0 and pi:

> Integrate <- function(f,a,b) integrate(Vectorize(f),a,b)$value
> F <- Integrate(f,0,pi)

But if i want to evaluate and return some values of F i get this error:

> F(c(-100,0,1,2,pi,100))
Error in F(c(-100, 0, 1, 2, pi, 100)) :
      function "F" is not found

i can understand that this is due to the fact, that my integrate <- function(f,a,b) returns a constant value C which is the result of the integration of f between a and b, but how can i return F as a function to be able to evaluate it's values as a vector and plot it ?

like in this case F should give 0 for any value less than 0 and 1 for any value bigger than pi and be variable between them.

Thanks.

Edit: just to sum it up more clearly: how can i define a function f(x) in [a,b] that will give me f(x) if x is in [a,b], 0 if xb ?

Body:
Try wrapping your function call in an sapply and have Integrate return a function.

Integrate <- function(f, a, b)  function(x) if (x < a) 0 else if (x > b) 1 else integrate(Vectorize(f), a, x)$value
F <- Integrate(f, 0, pi)
sapply(c(-100,0,1,2,pi,100), F)

gives

[1] 0.0000000 0.0000000 0.2298488 0.7080734 1.0000000 1.0000000


问:
Check to see if python script is running
I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?

I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.

How can i check (using python) if my script is running?

答:
Came across this old question looking for solution myself.

Use psutil:

```<code>import psutil
import sys
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'your_script.py']:
        sys.exit('Process found: exiting.')

print('Process not found: starting it.')
Popen(['python', 'your_script.py'])
</code>```

Body:
Came across this old question looking for solution myself.

Use psutil:

import psutil
import sys
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'your_script.py']:
        sys.exit('Process found: exiting.')

print('Process not found: starting it.')
Popen(['python', 'your_script.py'])


问:
how do I make triangle collisions with pygame?
I am trying to make a platformer in pygame and I have come across an issue. I can easily make collisions for rectangles and squares but I can't do it for right angle triangles. Is it possible to even do this using pygame? I have thought about just removing one of the corners to do it but I am unaware of how to do this and can't find any useful information anywhere. one person suggested using smaller rectangular collisions to make the triangles collisions but this didn't give the desired effect. the following code was made by someone else but it is basically the same as mine, the only difference is mine has animations etc and I changed some of the numbers in the jumping physics etc </p>

```<code>#! /usr/bin/python

import pygame
from pygame import *

WIN_WIDTH = 800
WIN_HEIGHT = 640
HALF_WIDTH = int(WIN_WIDTH / 2)
HALF_HEIGHT = int(WIN_HEIGHT / 2)

DISPLAY = (WIN_WIDTH, WIN_HEIGHT)
DEPTH = 32
FLAGS = 0
CAMERA_SLACK = 30

def main():
    global cameraX, cameraY
    pygame.init()
    screen = pygame.display.set_mode(DISPLAY, FLAGS, DEPTH)
    pygame.display.set_caption("Use arrows to move!")
    timer = pygame.time.Clock()

    up = down = left = right = running = False
    bg = Surface((32,72))
    bg.convert()
    bg.fill(Color("#000000"))
    entities = pygame.sprite.Group()
    player = Player(32, 32)
    platforms = []

    x = y = 0
    level = [
        "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "P                    PPPPPPPPPPP           P",
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "P    PPPPPPPP                              P",
        "P                                          P",
        "P                          PPPPPPP         P",
        "P                 PPPPPP                   P",
        "P                                          P",
        "P         PPPPPPP                          P",
        "P                                          P",
        "P                     PPPPPP               P",
        "P                                          P",
        "P   PPPPPPPPPPP                            P",
        "P                                          P",
        "P                 PPPPPPPPPPP              P",
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",]
    # build the level
    for row in level:
        for col in row:
            if col == "P":
                p = Platform(x, y)
                platforms.append(p)
                entities.add(p)
            if col == "E":
                e = ExitBlock(x, y)
                platforms.append(e)
                entities.add(e)
            x += 32
        y += 32
        x = 0

    total_level_width  = len(level[0])*32
    total_level_height = len(level)*32
    camera = Camera(complex_camera, total_level_width, total_level_height)
    entities.add(player)

    while 1:
        timer.tick(60)

        for e in pygame.event.get():
            if e.type == QUIT: raise SystemExit, "QUIT"
            if e.type == KEYDOWN and e.key == K_ESCAPE:
                raise SystemExit, "ESCAPE"
            if e.type == KEYDOWN and e.key == K_UP:
                up = True
            if e.type == KEYDOWN and e.key == K_DOWN:
                down = True
            if e.type == KEYDOWN and e.key == K_LEFT:
                left = True
            if e.type == KEYDOWN and e.key == K_RIGHT:
                right = True
            if e.type == KEYDOWN and e.key == K_SPACE:
                running = True

            if e.type == KEYUP and e.key == K_UP:
                up = False
            if e.type == KEYUP and e.key == K_DOWN:
                down = False
            if e.type == KEYUP and e.key == K_RIGHT:
                right = False
            if e.type == KEYUP and e.key == K_LEFT:
                left = False

        # draw background
        for y in range(32):
            for x in range(32):
                screen.blit(bg, (x * 32, y * 32))

        camera.update(player)

        # update player, draw everything else
        player.update(up, down, left, right, running, platforms)
        for e in entities:
            screen.blit(e.image, camera.apply(e))

        pygame.display.update()

class Camera(object):
    def __init__(self, camera_func, width, height):
        self.camera_func = camera_func
        self.state = Rect(0, 0, width, height)

    def apply(self, target):
        return target.rect.move(self.state.topleft)

    def update(self, target):
        self.state = self.camera_func(self.state, target.rect)

def simple_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    return Rect(-l+HALF_WIDTH, -t+HALF_HEIGHT, w, h)

def complex_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    l, t, _, _ = -l+HALF_WIDTH, -t+HALF_HEIGHT, w, h

    l = min(0, l)                           # stop scrolling at the left edge
    l = max(-(camera.width-WIN_WIDTH), l)   # stop scrolling at the right edge
    t = max(-(camera.height-WIN_HEIGHT), t) # stop scrolling at the bottom
    t = min(0, t)                           # stop scrolling at the top
    return Rect(l, t, w, h)

class Entity(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

class Player(Entity):
    def __init__(self, x, y):
        Entity.__init__(self)
        self.xvel = 0
        self.yvel = 0
        self.onGround = False
        self.image = Surface((32,72))
        self.image.fill(Color("#0000FF"))
        self.image.convert()
        self.rect = Rect(x, y, 32, 72)

    def update(self, up, down, left, right, running, platforms):
        if up:
            # only jump if on the ground
            if self.onGround: self.yvel -= 10
        if down:
            pass
        if running:
            self.xvel = 12
        if left:
            self.xvel = -8
        if right:
            self.xvel = 8
        if not self.onGround:
            # only accelerate with gravity if in the air
            self.yvel += 0.3
            # max falling speed
            if self.yvel > 100: self.yvel = 100
        if not(left or right):
            self.xvel = 0
        # increment in x direction
        self.rect.left += self.xvel
        # do x-axis collisions
        self.collide(self.xvel, 0, platforms)
        # increment in y direction
        self.rect.top += self.yvel
        # assuming we're in the air
        self.onGround = False;
        # do y-axis collisions
        self.collide(0, self.yvel, platforms)

    def collide(self, xvel, yvel, platforms):
        for p in platforms:
            if pygame.sprite.collide_rect(self, p):
                if isinstance(p, ExitBlock):
                    pygame.event.post(pygame.event.Event(QUIT))
                if xvel > 0:
                    self.rect.right = p.rect.left
                    print "collide right"
                if xvel < 0:
                    self.rect.left = p.rect.right
                    print "collide left"
                if yvel > 0:
                    self.rect.bottom = p.rect.top
                    self.onGround = True
                    self.yvel = 0
                if yvel < 0:
                    self.rect.top = p.rect.bottom

class Platform(Entity):
    def __init__(self, x, y):
        Entity.__init__(self)
        self.image = Surface((32, 32))
        self.image.convert()
        self.image.fill(Color("#DDDDDD"))
        self.rect = Rect(x, y, 32, 32)

    def update(self):
        pass

class ExitBlock(Platform):
    def __init__(self, x, y):
        Platform.__init__(self, x, y)
        self.image.fill(Color("#0033FF"))

if __name__ == "__main__":
    main()
</code>```

答: It isn't possible to implement triangle collision with the pygame module methods. But search about Pylygon module. </p>

Body:
I am trying to make a platformer in pygame and I have come across an issue. I can easily make collisions for rectangles and squares but I can't do it for right angle triangles. Is it possible to even do this using pygame? I have thought about just removing one of the corners to do it but I am unaware of how to do this and can't find any useful information anywhere. one person suggested using smaller rectangular collisions to make the triangles collisions but this didn't give the desired effect. the following code was made by someone else but it is basically the same as mine, the only difference is mine has animations etc and I changed some of the numbers in the jumping physics etc

#! /usr/bin/python

import pygame
from pygame import *

WIN_WIDTH = 800
WIN_HEIGHT = 640
HALF_WIDTH = int(WIN_WIDTH / 2)
HALF_HEIGHT = int(WIN_HEIGHT / 2)

DISPLAY = (WIN_WIDTH, WIN_HEIGHT)
DEPTH = 32
FLAGS = 0
CAMERA_SLACK = 30

def main():
    global cameraX, cameraY
    pygame.init()
    screen = pygame.display.set_mode(DISPLAY, FLAGS, DEPTH)
    pygame.display.set_caption("Use arrows to move!")
    timer = pygame.time.Clock()

    up = down = left = right = running = False
    bg = Surface((32,72))
    bg.convert()
    bg.fill(Color("#000000"))
    entities = pygame.sprite.Group()
    player = Player(32, 32)
    platforms = []

    x = y = 0
    level = [
        "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "P                    PPPPPPPPPPP           P",
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "P    PPPPPPPP                              P",
        "P                                          P",
        "P                          PPPPPPP         P",
        "P                 PPPPPP                   P",
        "P                                          P",
        "P         PPPPPPP                          P",
        "P                                          P",
        "P                     PPPPPP               P",
        "P                                          P",
        "P   PPPPPPPPPPP                            P",
        "P                                          P",
        "P                 PPPPPPPPPPP              P",
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",]
    # build the level
    for row in level:
        for col in row:
            if col == "P":
                p = Platform(x, y)
                platforms.append(p)
                entities.add(p)
            if col == "E":
                e = ExitBlock(x, y)
                platforms.append(e)
                entities.add(e)
            x += 32
        y += 32
        x = 0

    total_level_width  = len(level[0])*32
    total_level_height = len(level)*32
    camera = Camera(complex_camera, total_level_width, total_level_height)
    entities.add(player)

    while 1:
        timer.tick(60)

        for e in pygame.event.get():
            if e.type == QUIT: raise SystemExit, "QUIT"
            if e.type == KEYDOWN and e.key == K_ESCAPE:
                raise SystemExit, "ESCAPE"
            if e.type == KEYDOWN and e.key == K_UP:
                up = True
            if e.type == KEYDOWN and e.key == K_DOWN:
                down = True
            if e.type == KEYDOWN and e.key == K_LEFT:
                left = True
            if e.type == KEYDOWN and e.key == K_RIGHT:
                right = True
            if e.type == KEYDOWN and e.key == K_SPACE:
                running = True

            if e.type == KEYUP and e.key == K_UP:
                up = False
            if e.type == KEYUP and e.key == K_DOWN:
                down = False
            if e.type == KEYUP and e.key == K_RIGHT:
                right = False
            if e.type == KEYUP and e.key == K_LEFT:
                left = False

        # draw background
        for y in range(32):
            for x in range(32):
                screen.blit(bg, (x * 32, y * 32))

        camera.update(player)

        # update player, draw everything else
        player.update(up, down, left, right, running, platforms)
        for e in entities:
            screen.blit(e.image, camera.apply(e))

        pygame.display.update()

class Camera(object):
    def __init__(self, camera_func, width, height):
        self.camera_func = camera_func
        self.state = Rect(0, 0, width, height)

    def apply(self, target):
        return target.rect.move(self.state.topleft)

    def update(self, target):
        self.state = self.camera_func(self.state, target.rect)

def simple_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    return Rect(-l+HALF_WIDTH, -t+HALF_HEIGHT, w, h)

def complex_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    l, t, _, _ = -l+HALF_WIDTH, -t+HALF_HEIGHT, w, h

    l = min(0, l)                           # stop scrolling at the left edge
    l = max(-(camera.width-WIN_WIDTH), l)   # stop scrolling at the right edge
    t = max(-(camera.height-WIN_HEIGHT), t) # stop scrolling at the bottom
    t = min(0, t)                           # stop scrolling at the top
    return Rect(l, t, w, h)

class Entity(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

class Player(Entity):
    def __init__(self, x, y):
        Entity.__init__(self)
        self.xvel = 0
        self.yvel = 0
        self.onGround = False
        self.image = Surface((32,72))
        self.image.fill(Color("#0000FF"))
        self.image.convert()
        self.rect = Rect(x, y, 32, 72)

    def update(self, up, down, left, right, running, platforms):
        if up:
            # only jump if on the ground
            if self.onGround: self.yvel -= 10
        if down:
            pass
        if running:
            self.xvel = 12
        if left:
            self.xvel = -8
        if right:
            self.xvel = 8
        if not self.onGround:
            # only accelerate with gravity if in the air
            self.yvel += 0.3
            # max falling speed
            if self.yvel > 100: self.yvel = 100
        if not(left or right):
            self.xvel = 0
        # increment in x direction
        self.rect.left += self.xvel
        # do x-axis collisions
        self.collide(self.xvel, 0, platforms)
        # increment in y direction
        self.rect.top += self.yvel
        # assuming we're in the air
        self.onGround = False;
        # do y-axis collisions
        self.collide(0, self.yvel, platforms)

    def collide(self, xvel, yvel, platforms):
        for p in platforms:
            if pygame.sprite.collide_rect(self, p):
                if isinstance(p, ExitBlock):
                    pygame.event.post(pygame.event.Event(QUIT))
                if xvel > 0:
                    self.rect.right = p.rect.left
                    print "collide right"
                if xvel < 0:
                    self.rect.left = p.rect.right
                    print "collide left"
                if yvel > 0:
                    self.rect.bottom = p.rect.top
                    self.onGround = True
                    self.yvel = 0
                if yvel < 0:
                    self.rect.top = p.rect.bottom

class Platform(Entity):
    def __init__(self, x, y):
        Entity.__init__(self)
        self.image = Surface((32, 32))
        self.image.convert()
        self.image.fill(Color("#DDDDDD"))
        self.rect = Rect(x, y, 32, 32)

    def update(self):
        pass

class ExitBlock(Platform):
    def __init__(self, x, y):
        Platform.__init__(self, x, y)
        self.image.fill(Color("#0033FF"))

if __name__ == "__main__":
    main()


问:
One-to-many Using Bridge Table
I'm setting up relationships between models and I'm wondering if there's any harm using a bridge table for a one-to-many relationship?

i.e. These are some of the models

User

Team

Group

Each User may or may-not have a Team or Group. Would it be better to have nullable FK's in the User model for team_id, group_id, or is using bridge tables team_user, group_user acceptable? (There is little chance this will ever be a many-to-many relationship)

Would there be any ill effects in using a bridge table for one-to-many?

答:
A "bridge table" is usually used to model many-to-many. In your case, can a user be in more than one team or group? If so, a bridge table is what you want. If not, I'd go with nullable-FK's.

If you want the bridge table for one-to-many you should use a unique index to ensure you only have "one."

Now nulls themselves are the subject of some religious wars. There are good arguments to avoid them. In this case, I think they're ok - it means 0 (fk is NULL) or 1 (fk points to the team or group the user belongs to.)

Title: One-to-many Using Bridge Table


问:
How to get text I inputted into textView
```<code>-(void)textViewDidChange:(UITextView *)textView{
    self.textView.text=textView.text;
    self.statusString=textView.text;
}
</code>```

In this method ,it returns self.statusString nil or empty description(when initialized statusString it happens), and self.textView.text is nil too.

How to get the text I inputted into textView?

答:
Give the different name to the connected textView .

```<code>IBOutlet UITextView *objTextVIew ;
</code>```

In ViewDidLoad

```<code> objTextVIew.delegate = self
    -(void)textViewDidChange:(UITextView *)textView{
        self.objTextVIew.text=textView.text; // also see that have  you got textView's text
        self.statusString=textView.text;
    }
</code>```

Body:
-(void)textViewDidChange:(UITextView *)textView{
    self.textView.text=textView.text;
    self.statusString=textView.text;
}

In this method ,it returns self.statusString nil or empty description(when initialized statusString it happens), and self.textView.text is nil too.

How to get the text I inputted into textView?

Body:
Give the different name to the connected textView .

IBOutlet UITextView *objTextVIew ;

In ViewDidLoad

 objTextVIew.delegate = self
    -(void)textViewDidChange:(UITextView *)textView{
        self.objTextVIew.text=textView.text; // also see that have  you got textView's text
        self.statusString=textView.text;
    }


问:
Why is my code jumping out of a loop In php
I am writing a project on web scraping using simple HTML DOM parser. I scrape web pages from my database, extract contents and store then in database. The code is working fine with the first URL, but on the remaining URL it just break out of the loop. Below is my code.

```<code>include_once('Connections/elecom_connect.php');
include_once('dom/simple_html_dom.php');

mysqli_select_db($elecom_connect,$database_elecom_connect);
$sql = "SELECT * FROM link_data";
$result_links = array();
$result_cates = '';
$result_subs = '';
$result_names = '';
$num = -1;
$count = 0;

$img = '.image-wrapper img';
$brand = 'h2.title span.brand';
$name = 'h2.title span.name';
$price = 'span.price-box';
$link = 'section.products a.link';

$site = new simple_html_dom();

$query = mysqli_query($elecom_connect,$sql);

if (!$query){
    echo 'Database error: ' .    mysqli_error($elecom_connect);
}

while ($row = mysqli_fetch_array($query)) {
    $result_links[] =  $row;
}

foreach($result_links as $link){
    $var = $link['link'];
    if (!empty($var)) {
        var_dump($var);

        $site->load_file($var);
        if (!empty($site)) {
            $currentImg = $site->find($img);
            $currentBrand = $site->find($brand);
            $currentName = $site->find($name);
            $currentPrice = $site->find($price);
            $currentLink = $site->find($link);

            $rid = $link['id'];
            $rcates = $link['link_category'];
            $rsubs = $link['link_subcategory'];
            $rnames = $link['link_name'];
            if (!empty($currentImg)) {
                foreach($currentImg as $im){
                    $count++;

                    if($count % 2 == 0 && $count < 40){
                        $num++;

                        $cImg = $im->src;
                        $cBrand = "<p>".$currentBrand[$num]->plaintext."</p>";
                        $cName = "<p>".$currentName[$num]->plaintext."</p>";
                        $cPrice = "<p>".$currentPrice[$num]->plaintext."</p>";
                        //$cLink = $currentLink[$num]->href;

                        $content = file_get_contents($cImg);
                        //Store in the filesystem.
                        $save_path = "cachedPages/$rid.$num.jpg";
                        file_put_contents($save_path,$content);

                        $insertSQL = "INSERT INTO item_detail (item_name, item_brand, item_price, item_img, item_cate, item_sub_cate,filter_by) VALUES ('$cName', '$cBrand', '$cPrice','$save_path','$rcates','$rsubs','$rnames')";

                        mysqli_select_db($elecom_connect,$database_elecom_connect);
                        $Result1 = mysqli_query($elecom_connect,$insertSQL) or die(mysqli_error(          $elecom_connect));

                        echo 'Success';

                    }
                }
            }

        }
    }
    $site->clear();
}
</code>```

Here is the error code I get.

Fatal error: Uncaught Error: Call to a member function find() on null in dom/simple_html_dom.php:1113 Stack trace: #0

What should I do.?

答:
This line of code is incorrect:

```<code>$site = new simple_html_dom();
</code>```

You apparently do not need to do this based on the example directory in GitHub https://github.com/samacs/simple_html_dom/tree/master/example

What you want to do is use one of two methods

file_get_html or str_get_html which are loaded when you include the include_once('dom/simple_html_dom.php');.

So you actually want to see

```<code>$site = file_get_html($url); //URL to a site you are parsing ie 'http://www.google.com/'
//OR
$site = str_get_html($str); // String file to some html file
</code>```

Which if you read the code actually creates a $dom_node which has the find method on it.

The reason what you have is strange is because you are creating and object and when you check if(!empty($site)) it returns true because there is an object. However that internal dom_node is not set properly.

When you get to line 1113 of this libs file not yours you have a null dom_node which null->find() will throw the error you are getting.

Body:
I am writing a project on web scraping using simple HTML DOM parser. I scrape web pages from my database, extract contents and store then in database. The code is working fine with the first URL, but on the remaining URL it just break out of the loop. Below is my code.

include_once('Connections/elecom_connect.php');
include_once('dom/simple_html_dom.php');

mysqli_select_db($elecom_connect,$database_elecom_connect);
$sql = "SELECT * FROM link_data";
$result_links = array();
$result_cates = '';
$result_subs = '';
$result_names = '';
$num = -1;
$count = 0;

$img = '.image-wrapper img';
$brand = 'h2.title span.brand';
$name = 'h2.title span.name';
$price = 'span.price-box';
$link = 'section.products a.link';

$site = new simple_html_dom();

$query = mysqli_query($elecom_connect,$sql);

if (!$query){
    echo 'Database error: ' .    mysqli_error($elecom_connect);
}

while ($row = mysqli_fetch_array($query)) {
    $result_links[] =  $row;
}

foreach($result_links as $link){
    $var = $link['link'];
    if (!empty($var)) {
        var_dump($var);

        $site->load_file($var);
        if (!empty($site)) {
            $currentImg = $site->find($img);
            $currentBrand = $site->find($brand);
            $currentName = $site->find($name);
            $currentPrice = $site->find($price);
            $currentLink = $site->find($link);

            $rid = $link['id'];
            $rcates = $link['link_category'];
            $rsubs = $link['link_subcategory'];
            $rnames = $link['link_name'];
            if (!empty($currentImg)) {
                foreach($currentImg as $im){
                    $count++;

                    if($count % 2 == 0 && $count < 40){
                        $num++;

                        $cImg = $im->src;
                        $cBrand = "
".$currentBrand[$num]->plaintext."
";
                        $cName = "
".$currentName[$num]->plaintext."
";
                        $cPrice = "
".$currentPrice[$num]->plaintext."
";
                        //$cLink = $currentLink[$num]->href;

                        $content = file_get_contents($cImg);
                        //Store in the filesystem.
                        $save_path = "cachedPages/$rid.$num.jpg";
                        file_put_contents($save_path,$content);

                        $insertSQL = "INSERT INTO item_detail (item_name, item_brand, item_price, item_img, item_cate, item_sub_cate,filter_by) VALUES ('$cName', '$cBrand', '$cPrice','$save_path','$rcates','$rsubs','$rnames')";

                        mysqli_select_db($elecom_connect,$database_elecom_connect);
                        $Result1 = mysqli_query($elecom_connect,$insertSQL) or die(mysqli_error(          $elecom_connect));

                        echo 'Success';

                    }
                }
            }

        }
    }
    $site->clear();
}

Here is the error code I get.

Fatal error: Uncaught Error: Call to a member function find() on null in dom/simple_html_dom.php:1113 Stack trace: #0

What should I do.?

Body:
This line of code is incorrect:

$site = new simple_html_dom();

You apparently do not need to do this based on the example directory in GitHub https://github.com/samacs/simple_html_dom/tree/master/example

What you want to do is use one of two methods

file_get_html or str_get_html which are loaded when you include the include_once('dom/simple_html_dom.php');.

So you actually want to see

$site = file_get_html($url); //URL to a site you are parsing ie 'http://www.google.com/'
//OR
$site = str_get_html($str); // String file to some html file

Which if you read the code actually creates a $dom_node which has the find method on it.

The reason what you have is strange is because you are creating and object and when you check if(!empty($site)) it returns true because there is an object. However that internal dom_node is not set properly.

When you get to line 1113 of this libs file not yours you have a null dom_node which null->find() will throw the error you are getting.


问:
NaN Cholesky's decomposition in Fortran if I don't use a printing subroutine
I programmed a function to obtain Cholesky's decomposition of a REAL matrix. The problem is that it returns NaN values in some spots of the matrix. Here is the code:

```<code>MODULE funciones2
IMPLICIT NONE
CONTAINS
FUNCTION cholesky(a)
USE ::comprob !Module to test whether or not a matrix is square and symmetric
IMPLICIT NONE
REAL, ALLOCATABLE :: cholesky(:,:),u(:,:)
REAL :: a(:,:),s
INTEGER :: i,j,k,n
LOGICAL :: comp

comp=symmat(a)

IF (comp) THEN
n=size(a,1)
ALLOCATE (u(n,n))
u=0.0
u(1,1)=sqrt(a(1,1))

DO j=2,n,1
    u(1,j)=a(1,j)/u(1,1)
END DO

DO i=2,n,1
    DO k=1,i-1,1
        s=s+(u(k,i)**2)
    END DO
    u(i,i)=sqrt(a(i,i)-s)
    s=0
    DO j=i+1,n,1
        DO k=1,i-1,1
            s=s+u(k,i)*u(k,j)
        END DO
        u(i,j)=(1/u(i,i))*(a(i,j)-s)
        s=0
    END DO
END DO

cholesky=u

ELSE
    print*,"CHOLESKY: The matrix is not symmetric."
ENDIF
ENDFUNCTION
ENDMODULE
</code>```

And the program code is:

```<code>PROGRAM pchol
USE :: funciones2
USE :: dispmodule
IMPLICIT NONE
REAL, ALLOCATABLE :: a(:,:),af(:,:)
CHARACTER(LEN=20) :: na

na='B.txt'

a=loadm(na)
CALL DISP('A =',a,ADVANCE='DOUBLE')

a=matmul(transpose(a),a)
!CALL DISP('ATA =',a,ADVANCE='DOUBLE')

af=cholesky(a)
CALL DISP('Ach ',af,ADVANCE='DOUBLE')

af=transpose(af)
CALL DISP('AchT ',af,ADVANCE='DOUBLE')

ENDPROGRAM
</code>```

"dispmodule" is a module (Jonasson, 2009) for pretty-printing matrices (you can take a look about it here: https://notendur.hi.is/jonasson/greinar/dispmodule-report.pdf ). I discovered that if I use the subroutine DISP in this part:

```<code>a=matmul(transpose(a),a)
CALL DISP('ATA =',a,ADVANCE='DOUBLE')
</code>```

the problem of NaN disappears!(notice that in this last part, there is not "!" before "CALL DISP").

Why is this happening? I am going to use the Cholesky decomposition function for another function, and I can't call DISP all the time to avoid problems. How can I fix this?

Edit:
Here's the numerical result without compiling the program with the DISP subroutine:

```<code>A =3.00000   2.00000  4.00000   5.00000
   2.00000  -3.00000  1.00000  -2.00000
   1.00000   1.00000  2.00000   0.00000

Ach 3.74166  0.26726  4.27618  2.93987
    0.00000      NaN      NaN      NaN
    0.00000  0.00000      NaN      NaN
    0.00000  0.00000  0.00000      NaN

AchT 3.74166  0.00000  0.00000  0.00000
     0.26726      NaN  0.00000  0.00000
     4.27618      NaN      NaN  0.00000
     2.93987      NaN      NaN      NaN
</code>```

Here is the numerical result when I do compile the DISP subroutine:

```<code>A =3.00000   2.00000  4.00000   5.00000
   2.00000  -3.00000  1.00000  -2.00000
   1.00000   1.00000  2.00000   0.00000

ATA =14.0000   1.0000  16.0000  11.0000
      1.0000  14.0000   7.0000  16.0000
     16.0000   7.0000  21.0000  18.0000
     11.0000  16.0000  18.0000  29.0000

Ach 3.74166  0.26726  4.27618   2.93987
    0.00000  3.73210  1.56940   4.07660
    0.00000  0.00000  0.50128  -1.93350
    0.00000  0.00000  0.00000   0.00648

AchT 3.74166  0.00000   0.00000  0.00000
     0.26726  3.73210   0.00000  0.00000
     4.27618  1.56940   0.50128  0.00000
     2.93987  4.07660  -1.93350  0.00648
</code>```

EDIT 2: I assigned new variables to every new computed matrix, but the problem remains.

```<code>PROGRAM pchol
USE :: funciones2
USE :: dispmodule
IMPLICIT NONE
REAL, ALLOCATABLE :: a(:,:),af(:,:),at(:,:),am(:,:),am1(:,:)
CHARACTER(LEN=20) :: na
INTEGER :: m,n

na='B.txt'

a=loadm(na)
!CALL DISP('A =',a,ADVANCE='DOUBLE')

m=size(a,1)
n=size(a,2)

ALLOCATE (at(n,m))
ALLOCATE (am(n,n))
ALLOCATE (af(n,n))

at=transpose(a)
am=matmul(at,a)
am1=am
!CALL DISP('ATA =',am1,ADVANCE='DOUBLE')

af=cholesky(am)
CALL DISP('Ach ',af,ADVANCE='DOUBLE')

af=transpose(af)
CALL DISP('AchT ',af,ADVANCE='DOUBLE')

ENDPROGRAM
</code>```

UPDATE: Minimum compilable example. I took out the subroutine DISP() with its respective module. I also took out the module and function that made the comprobation of the symmetry of the matrix. Moreover, I took out the function that I wrote for reading the matrix from a file (I wrote the same matrix directly on the program) and the function for printing the matrix. The problem gets worse, now there are no numbers, not even the first row as before, all the matrix becomes NaN after the use of cholesky(). The gfortran version is 5.3.0

```<code>PROGRAM pcholstack
IMPLICIT NONE
REAL, ALLOCATABLE :: af(:,:),at(:,:),am(:,:),am1(:,:)
REAL :: a(3,4)
INTEGER :: m,n,i,j

a(1,1)=3
a(2,1)=2
a(3,1)=1
a(1,2)=2
a(2,2)=-3
a(3,2)=1
a(1,3)=4
a(2,3)=1
a(3,3)=2
a(1,4)=5
a(2,4)=-2
a(3,4)=1

m=size(a,1)
n=size(a,2)

do i=1,m,1
    write(*,1017),(a(i,j),j=1,n)
    end do
        1017 format (10f15.2)

write(*,*)

ALLOCATE (at(n,m))
ALLOCATE (am(n,n))
ALLOCATE (af(n,n))

at=transpose(a)
am=matmul(at,a)
am1=am
write(*,*) am1(1,1)
write(*,*)

do i=1,n,1
    write(*,1018),(at(i,j),j=1,m)
    end do
        1018 format (10f15.2)

write(*,*)

do i=1,n,1
    write(*,1019),(am(i,j),j=1,n)
    end do
        1019 format (10f15.2)

write(*,*)

af=cholesky(am)

!af=transpose(af)

do i=1,n,1
    write(*,1016),(af(i,j),j=1,n)
    end do
        1016 format (10f15.2)

CONTAINS

FUNCTION cholesky(a)
IMPLICIT NONE
REAL, ALLOCATABLE :: u(:,:),cholesky(:,:)
REAL :: a(:,:),s
INTEGER :: i,j,k,n

n=size(a,1)
ALLOCATE (u(n,n))
u=0.0
u(1,1)=sqrt(a(1,1))

DO j=2,n,1
    u(1,j)=a(1,j)/u(1,1)
END DO

DO i=2,n,1
    DO k=1,i-1,1
        s=s+(u(k,i)**2)
    END DO
    u(i,i)=sqrt(a(i,i)-s)
    s=0
    DO j=i+1,n,1
        DO k=1,i-1,1
            s=s+u(k,i)*u(k,j)
        END DO
        u(i,j)=(1/u(i,i))*(a(i,j)-s)
        s=0
    END DO
END DO

cholesky=u

ENDFUNCTION

ENDPROGRAM
</code>```

答:
Intel Fortran identified that you are using s incorrectly in Cholesky. The value of s is not defined when you are first using it.

Thus, the result can be anything.

Probably you wanted to set it to 0.

```<code>> ifort cholesky.f90 -g -check -traceback -standard-semantics
> ./a.out
           3.00           2.00           4.00           5.00
           2.00          -3.00           1.00          -2.00
           1.00           1.00           2.00           1.00

 14.00000

           3.00           2.00           1.00
           2.00          -3.00           1.00
           4.00           1.00           2.00
           5.00          -2.00           1.00

          14.00           1.00          16.00          12.00
           1.00          14.00           7.00          17.00
          16.00           7.00          21.00          20.00
          12.00          17.00          20.00          30.00

forrtl: severe (194): Run-Time Check Failure. The variable 'cholesky$S$_1' is being used in 'cholesky.f90(82,9)' without being defined
Image              PC                Routine            Line        Source
a.out              0000000000407DB7  pcholstack_IP_cho          82  cholesky.f90
a.out              0000000000405B47  MAIN__                     54  cholesky.f90
a.out              000000000040261E  Unknown               Unknown  Unknown
libc.so.6          00007F41B73496E5  Unknown               Unknown  Unknown
a.out              0000000000402529  Unknown               Unknown  Unknown
</code>```

The reported code is:

```<code>s = 0  !you probably wanted

DO i=2,n,1
    DO k=1,i-1,1
        s=s+(u(k,i)**2)   !<<<=====
</code>```

Body:
I programmed a function to obtain Cholesky's decomposition of a REAL matrix. The problem is that it returns NaN values in some spots of the matrix. Here is the code:

MODULE funciones2
IMPLICIT NONE
CONTAINS
FUNCTION cholesky(a)
USE ::comprob !Module to test whether or not a matrix is square and symmetric
IMPLICIT NONE
REAL, ALLOCATABLE :: cholesky(:,:),u(:,:)
REAL :: a(:,:),s
INTEGER :: i,j,k,n
LOGICAL :: comp

comp=symmat(a)

IF (comp) THEN
n=size(a,1)
ALLOCATE (u(n,n))
u=0.0
u(1,1)=sqrt(a(1,1))

DO j=2,n,1
    u(1,j)=a(1,j)/u(1,1)
END DO

DO i=2,n,1
    DO k=1,i-1,1
        s=s+(u(k,i)**2)
    END DO
    u(i,i)=sqrt(a(i,i)-s)
    s=0
    DO j=i+1,n,1
        DO k=1,i-1,1
            s=s+u(k,i)*u(k,j)
        END DO
        u(i,j)=(1/u(i,i))*(a(i,j)-s)
        s=0
    END DO
END DO

cholesky=u

ELSE
    print*,"CHOLESKY: The matrix is not symmetric."
ENDIF
ENDFUNCTION
ENDMODULE

And the program code is:

PROGRAM pchol
USE :: funciones2
USE :: dispmodule
IMPLICIT NONE
REAL, ALLOCATABLE :: a(:,:),af(:,:)
CHARACTER(LEN=20) :: na

na='B.txt'

a=loadm(na)
CALL DISP('A =',a,ADVANCE='DOUBLE')

a=matmul(transpose(a),a)
!CALL DISP('ATA =',a,ADVANCE='DOUBLE')

af=cholesky(a)
CALL DISP('Ach ',af,ADVANCE='DOUBLE')

af=transpose(af)
CALL DISP('AchT ',af,ADVANCE='DOUBLE')

ENDPROGRAM

"dispmodule" is a module (Jonasson, 2009) for pretty-printing matrices (you can take a look about it here: https://notendur.hi.is/jonasson/greinar/dispmodule-report.pdf ). I discovered that if I use the subroutine DISP in this part:

a=matmul(transpose(a),a)
CALL DISP('ATA =',a,ADVANCE='DOUBLE')

the problem of NaN disappears!(notice that in this last part, there is not "!" before "CALL DISP").

Why is this happening? I am going to use the Cholesky decomposition function for another function, and I can't call DISP all the time to avoid problems. How can I fix this?

Edit:
Here's the numerical result without compiling the program with the DISP subroutine:

A =3.00000   2.00000  4.00000   5.00000
   2.00000  -3.00000  1.00000  -2.00000
   1.00000   1.00000  2.00000   0.00000

Ach 3.74166  0.26726  4.27618  2.93987
    0.00000      NaN      NaN      NaN
    0.00000  0.00000      NaN      NaN
    0.00000  0.00000  0.00000      NaN

AchT 3.74166  0.00000  0.00000  0.00000
     0.26726      NaN  0.00000  0.00000
     4.27618      NaN      NaN  0.00000
     2.93987      NaN      NaN      NaN

Here is the numerical result when I do compile the DISP subroutine:

A =3.00000   2.00000  4.00000   5.00000
   2.00000  -3.00000  1.00000  -2.00000
   1.00000   1.00000  2.00000   0.00000

ATA =14.0000   1.0000  16.0000  11.0000
      1.0000  14.0000   7.0000  16.0000
     16.0000   7.0000  21.0000  18.0000
     11.0000  16.0000  18.0000  29.0000

Ach 3.74166  0.26726  4.27618   2.93987
    0.00000  3.73210  1.56940   4.07660
    0.00000  0.00000  0.50128  -1.93350
    0.00000  0.00000  0.00000   0.00648

AchT 3.74166  0.00000   0.00000  0.00000
     0.26726  3.73210   0.00000  0.00000
     4.27618  1.56940   0.50128  0.00000
     2.93987  4.07660  -1.93350  0.00648

EDIT 2: I assigned new variables to every new computed matrix, but the problem remains.

PROGRAM pchol
USE :: funciones2
USE :: dispmodule
IMPLICIT NONE
REAL, ALLOCATABLE :: a(:,:),af(:,:),at(:,:),am(:,:),am1(:,:)
CHARACTER(LEN=20) :: na
INTEGER :: m,n

na='B.txt'

a=loadm(na)
!CALL DISP('A =',a,ADVANCE='DOUBLE')

m=size(a,1)
n=size(a,2)

ALLOCATE (at(n,m))
ALLOCATE (am(n,n))
ALLOCATE (af(n,n))

at=transpose(a)
am=matmul(at,a)
am1=am
!CALL DISP('ATA =',am1,ADVANCE='DOUBLE')

af=cholesky(am)
CALL DISP('Ach ',af,ADVANCE='DOUBLE')

af=transpose(af)
CALL DISP('AchT ',af,ADVANCE='DOUBLE')

ENDPROGRAM

UPDATE: Minimum compilable example. I took out the subroutine DISP() with its respective module. I also took out the module and function that made the comprobation of the symmetry of the matrix. Moreover, I took out the function that I wrote for reading the matrix from a file (I wrote the same matrix directly on the program) and the function for printing the matrix. The problem gets worse, now there are no numbers, not even the first row as before, all the matrix becomes NaN after the use of cholesky(). The gfortran version is 5.3.0

PROGRAM pcholstack
IMPLICIT NONE
REAL, ALLOCATABLE :: af(:,:),at(:,:),am(:,:),am1(:,:)
REAL :: a(3,4)
INTEGER :: m,n,i,j

a(1,1)=3
a(2,1)=2
a(3,1)=1
a(1,2)=2
a(2,2)=-3
a(3,2)=1
a(1,3)=4
a(2,3)=1
a(3,3)=2
a(1,4)=5
a(2,4)=-2
a(3,4)=1

m=size(a,1)
n=size(a,2)

do i=1,m,1
    write(*,1017),(a(i,j),j=1,n)
    end do
        1017 format (10f15.2)

write(*,*)

ALLOCATE (at(n,m))
ALLOCATE (am(n,n))
ALLOCATE (af(n,n))

at=transpose(a)
am=matmul(at,a)
am1=am
write(*,*) am1(1,1)
write(*,*)

do i=1,n,1
    write(*,1018),(at(i,j),j=1,m)
    end do
        1018 format (10f15.2)

write(*,*)

do i=1,n,1
    write(*,1019),(am(i,j),j=1,n)
    end do
        1019 format (10f15.2)

write(*,*)

af=cholesky(am)

!af=transpose(af)

do i=1,n,1
    write(*,1016),(af(i,j),j=1,n)
    end do
        1016 format (10f15.2)

CONTAINS

FUNCTION cholesky(a)
IMPLICIT NONE
REAL, ALLOCATABLE :: u(:,:),cholesky(:,:)
REAL :: a(:,:),s
INTEGER :: i,j,k,n

n=size(a,1)
ALLOCATE (u(n,n))
u=0.0
u(1,1)=sqrt(a(1,1))

DO j=2,n,1
    u(1,j)=a(1,j)/u(1,1)
END DO

DO i=2,n,1
    DO k=1,i-1,1
        s=s+(u(k,i)**2)
    END DO
    u(i,i)=sqrt(a(i,i)-s)
    s=0
    DO j=i+1,n,1
        DO k=1,i-1,1
            s=s+u(k,i)*u(k,j)
        END DO
        u(i,j)=(1/u(i,i))*(a(i,j)-s)
        s=0
    END DO
END DO

cholesky=u

ENDFUNCTION

ENDPROGRAM

Body:
Intel Fortran identified that you are using s incorrectly in Cholesky. The value of s is not defined when you are first using it.

Thus, the result can be anything.

Probably you wanted to set it to 0.

> ifort cholesky.f90 -g -check -traceback -standard-semantics
> ./a.out
           3.00           2.00           4.00           5.00
           2.00          -3.00           1.00          -2.00
           1.00           1.00           2.00           1.00

 14.00000

           3.00           2.00           1.00
           2.00          -3.00           1.00
           4.00           1.00           2.00
           5.00          -2.00           1.00

          14.00           1.00          16.00          12.00
           1.00          14.00           7.00          17.00
          16.00           7.00          21.00          20.00
          12.00          17.00          20.00          30.00

forrtl: severe (194): Run-Time Check Failure. The variable 'cholesky$S$_1' is being used in 'cholesky.f90(82,9)' without being defined
Image              PC                Routine            Line        Source
a.out              0000000000407DB7  pcholstack_IP_cho          82  cholesky.f90
a.out              0000000000405B47  MAIN__                     54  cholesky.f90
a.out              000000000040261E  Unknown               Unknown  Unknown
libc.so.6          00007F41B73496E5  Unknown               Unknown  Unknown
a.out              0000000000402529  Unknown               Unknown  Unknown

The reported code is:

s = 0  !you probably wanted

DO i=2,n,1
    DO k=1,i-1,1
        s=s+(u(k,i)**2)   !<<<=====


问:
Formencode ignores if_missing on USPostalCode
I have a problem with FormEncode not acknowledging that a validator has if_missing set. It keeps returning a "Missing Error" error for the field.

I have a Schema that looks like this

```<code>class ABCSchema(Schema):

allow_extra_fields = True
filter_extra_fields = True

primary_surname = validators.UnicodeString(not_empty=True)
mailing_address_1 = validators.UnicodeString(not_empty=True)
mailing_address_2 = validators.UnicodeString()
mailing_city = validators.UnicodeString(not_empty=True)
mailing_state = national.USStateProvince(not_empty=True)
mailing_zip = national.USPostalCode(not_empty=True)
billing_address_is_same_as_mailing = validators.StringBool(if_empty=False, not_empty=False)
billing_address_1 = validators.UnicodeString(if_missing=None)
billing_address_2 = validators.UnicodeString(if_missing=None)
billing_city = validators.UnicodeString(if_missing=None)
billing_state = national.USStateProvince(if_missing=None)
billing_zip = national.USPostalCode(if_empty=None, not_empty=False)
special_instructions = validators.UnicodeString()
</code>```

The validator in question is billing_zip.

The idea is that a user may have the option to flip the billing_address_is_same_as_mailing flag. This will disable the billing address fields which prevents those fields from being submitted.

Upon form submission the request has the following values

```<code>NestedMultiDict([('primary_surname', 'Something'), ('mailing_address_1', '81 turnbull St'), ('mailing_address_2', ''), ('mailing_city', 'Tampa'), ('mailing_state', 'NE'), ('mailing_zip', '98754'), ('billing_address_is_same_as_mailing', 'True'), ('special_instructions', ''), ('submit', 'Submit')])
</code>```

This is validate with the following data and error dicts.

```<code>{'special_instructions': '', 'billing_city': None, 'mailing_city': 'Budd Lake', 'primary_surname': 'Something', 'billing_address_is_same_as_mailing': 'True', 'billing_state': None, 'mailing_address_1': '81 turnbull St', 'billing_zip': None, 'mailing_zip': '07828', 'mailing_state': 'NE', 'billing_address_2': None, 'submit': 'Submit', 'billing_address_1': None, 'mailing_address_2': '8 Locust St'}
{'billing_zip': 'Missing value'}
</code>```

I've tried if_empty, if_missing, and not_empty in various combinations, but I can't seem to get the validator to pass if the billing_zip is missing. However, it doesn't seem to complain about the other billing fields.

What am I missing?

答:
USPostalCode really ignores if_missing option. It can be seen in source code (USPostalCode is implemented as Any compound validator that does not define if_missing unlike All compound validator). Also the next commands demonstrate it:

```<code>>>> validators.Regex(r'^\d+$', not_empty=False, if_missing='').if_missing
''
>>> national.USPostalCode(not_empty=False, if_missing='').if_missing
<class 'formencode.api.NoDefault'>
</code>```

It should be a bug in formencode.

As a possible workaround, if_missing may be defined manually for each validator:

```<code>us_postal_code_validator = national.USPostalCode(if_empty=None, not_empty=False)
us_postal_code_validator.if_missing = ''

class ABCSchema(Schema):
    allow_extra_fields = True
    filter_extra_fields = True
    billing_zip = us_postal_code_validator
</code>```

Or if_key_missing may be defined for the entire schema (but be careful since it will affect all fields in that schema):

```<code>class ABCSchema(Schema):
    if_key_missing = ''
    allow_extra_fields = True
    filter_extra_fields = True
    billing_zip = national.USPostalCode(if_empty=None, not_empty=False)
</code>```

Body:
I have a problem with FormEncode not acknowledging that a validator has if_missing set. It keeps returning a "Missing Error" error for the field.

I have a Schema that looks like this

class ABCSchema(Schema):

allow_extra_fields = True
filter_extra_fields = True

primary_surname = validators.UnicodeString(not_empty=True)
mailing_address_1 = validators.UnicodeString(not_empty=True)
mailing_address_2 = validators.UnicodeString()
mailing_city = validators.UnicodeString(not_empty=True)
mailing_state = national.USStateProvince(not_empty=True)
mailing_zip = national.USPostalCode(not_empty=True)
billing_address_is_same_as_mailing = validators.StringBool(if_empty=False, not_empty=False)
billing_address_1 = validators.UnicodeString(if_missing=None)
billing_address_2 = validators.UnicodeString(if_missing=None)
billing_city = validators.UnicodeString(if_missing=None)
billing_state = national.USStateProvince(if_missing=None)
billing_zip = national.USPostalCode(if_empty=None, not_empty=False)
special_instructions = validators.UnicodeString()

The validator in question is billing_zip.

The idea is that a user may have the option to flip the billing_address_is_same_as_mailing flag. This will disable the billing address fields which prevents those fields from being submitted.

Upon form submission the request has the following values

NestedMultiDict([('primary_surname', 'Something'), ('mailing_address_1', '81 turnbull St'), ('mailing_address_2', ''), ('mailing_city', 'Tampa'), ('mailing_state', 'NE'), ('mailing_zip', '98754'), ('billing_address_is_same_as_mailing', 'True'), ('special_instructions', ''), ('submit', 'Submit')])

This is validate with the following data and error dicts.

{'special_instructions': '', 'billing_city': None, 'mailing_city': 'Budd Lake', 'primary_surname': 'Something', 'billing_address_is_same_as_mailing': 'True', 'billing_state': None, 'mailing_address_1': '81 turnbull St', 'billing_zip': None, 'mailing_zip': '07828', 'mailing_state': 'NE', 'billing_address_2': None, 'submit': 'Submit', 'billing_address_1': None, 'mailing_address_2': '8 Locust St'}
{'billing_zip': 'Missing value'}

I've tried if_empty, if_missing, and not_empty in various combinations, but I can't seem to get the validator to pass if the billing_zip is missing. However, it doesn't seem to complain about the other billing fields.

What am I missing?

Body:
USPostalCode really ignores if_missing option. It can be seen in source code (USPostalCode is implemented as Any compound validator that does not define if_missing unlike All compound validator). Also the next commands demonstrate it:

>>> validators.Regex(r'^\d+$', not_empty=False, if_missing='').if_missing
''
>>> national.USPostalCode(not_empty=False, if_missing='').if_missing
<class 'formencode.api.NoDefault'>

It should be a bug in formencode.

As a possible workaround, if_missing may be defined manually for each validator:

us_postal_code_validator = national.USPostalCode(if_empty=None, not_empty=False)
us_postal_code_validator.if_missing = ''

class ABCSchema(Schema):
    allow_extra_fields = True
    filter_extra_fields = True
    billing_zip = us_postal_code_validator

Or if_key_missing may be defined for the entire schema (but be careful since it will affect all fields in that schema):

class ABCSchema(Schema):
    if_key_missing = ''
    allow_extra_fields = True
    filter_extra_fields = True
    billing_zip = national.USPostalCode(if_empty=None, not_empty=False)


问:
cannot import name linkedin

I am here for the first time like a member and I'm new in python. I want to get a API string from linkedin using 'python-linkedin' package like this:

```<code>from linkedin import linkedin

API_KEY = 'my_key'
API_SECRET = 'my_secret'
RETURN_URL = 'http://127.0.0.1:8000'

authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values())
print authentication.authorization_url  # open this url on your browser
application = linkedin.LinkedInApplication(authentication)
</code>```

I have got this error:

```<code>C:\Python27\python.exe C:/Users/alemcluster.ALEM/PycharmProjects/linkedinapi/linkedin.py
Traceback (most recent call last):
  File "C:/Users/alemcluster.ALEM/PycharmProjects/linkedinapi/linkedin.py", line 1, in <module>
from linkedin import linkedin
  File "C:\Users\alemcluster.ALEM\PycharmProjects\linkedinapi\linkedin.py", line 1, in <module>
from linkedin import linkedin
ImportError: cannot import name linkedin

Process finished with exit code 1
</code>```

I tried to change linkedin to another variable, but does not help. I'm sorry if it is not properly posted. Prior to this, I only looked answers to questions.

答:
I have got similar issue a while back. This is due to because your filename is also same as your library name and python interpreter first looks library in a working directory. And when interpreter checks working directory interpreter founds a same name as library name so interpreter start getting from it which is actually not library. That's why it is giving error.

Simple rename your file and you are good to go.

Hope It Works :)

Title: cannot import name linkedin

Body:
I am here for the first time like a member and I'm new in python. I want to get a API string from linkedin using 'python-linkedin' package like this:

from linkedin import linkedin

API_KEY = 'my_key'
API_SECRET = 'my_secret'
RETURN_URL = 'http://127.0.0.1:8000'

authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values())
print authentication.authorization_url  # open this url on your browser
application = linkedin.LinkedInApplication(authentication)

I have got this error:

C:\Python27\python.exe C:/Users/alemcluster.ALEM/PycharmProjects/linkedinapi/linkedin.py
Traceback (most recent call last):
  File "C:/Users/alemcluster.ALEM/PycharmProjects/linkedinapi/linkedin.py", line 1, in <module>
from linkedin import linkedin
  File "C:\Users\alemcluster.ALEM\PycharmProjects\linkedinapi\linkedin.py", line 1, in <module>
from linkedin import linkedin
ImportError: cannot import name linkedin

Process finished with exit code 1

I tried to change linkedin to another variable, but does not help. I'm sorry if it is not properly posted. Prior to this, I only looked answers to questions.