问:
How to use AWS S3 in WinForm project - CSharp
I'm been reading multiples articles about the usage of the AWS S3 in Visual Studio. But all of those are focused on Web implementation.

Has anyone had the need to implement AWS S3 in WinForms - C#?

答:
I implemented a class in C# that interact basically with AWS S3 without having too much configuration.

** I'm using the MS Framework 4.5 **

First of all, remember to use the NuGet Package and install the AWS references (In VS >> Menu >> Tools >> NuGet Package Manager >> Manage NuGet Package Manager for Solution):

AWSSDK - Amazon Simple Storage Service

AWSSDK - Core Runtime

...implemented this class, for my need I only required the access key, secret key, region and the bucket (Exists more methods, but I only required copy, read and delete).

Note: It's not required additional configuration in the app.config file or install/create a profile in the USER folder...

```<code>public class clsAwsS3
{
    string accessKey { get; set; }
    string secretKey { get; set; }
    string bucket { get; set; }
    RegionEndpoint region { get; set; }
    IAmazonS3 client;

    public clsAwsS3(string strBucket, string strAccessKey, string strSecretKey, RegionEndpoint region)
    {
        this.bucket = strBucket;
        this.accessKey = strAccessKey;
        this.secretKey = strSecretKey;
        this.region = region;
        login();
    }

    private void login()
    {
        client = new AmazonS3Client(accessKey, secretKey, region);
    }

    public List<string> getItems(string strPrefix = "")
    {
        List<string> lstResult = new List<string>();
        ListObjectsV2Request listRequest;

        if (strPrefix == "")
            listRequest = new ListObjectsV2Request
            {
                BucketName = bucket
            };
        else
            listRequest = new ListObjectsV2Request
            {
                BucketName = bucket,
                Prefix = strPrefix
            };

        ListObjectsV2Response listResponse;

        do
        {
            listResponse = client.ListObjectsV2(listRequest);

            foreach (S3Object awsObject in listResponse.S3Objects)
                lstResult.Add(awsObject.Key);

            listRequest.ContinuationToken = listResponse.NextContinuationToken;
        } while (listResponse.IsTruncated);

        return lstResult;
    }

    public string downloadItem(string strItemKey, string strDestination)
    {
        GetObjectRequest request = new GetObjectRequest
        {
            BucketName = bucket,
            Key = strItemKey
        };

        using (GetObjectResponse response = client.GetObject(request))
        {
            response.WriteResponseStreamToFile(strDestination);
        }

        return strDestination;
    }

    public void copyItem(string strItemKeySource, string strItemKeyDestination)
    {
        CopyObjectRequest copyRequest = new CopyObjectRequest
        {
            SourceBucket = bucket,
            SourceKey = strItemKeySource,
            DestinationBucket = bucket,
            DestinationKey = strItemKeyDestination
        };

        CopyObjectResponse copyResponse = client.CopyObject(copyRequest);

        if (copyResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
            throw new Exception("Item has an error");
    }

    public void deleteItem(string strItemKey)
    {
        DeleteObjectRequest deleteObject = new DeleteObjectRequest
        {
            BucketName = bucket,
            Key = strItemKey
        };

        DeleteObjectResponse deleteResponse = client.DeleteObject(deleteObject);
    }
}
</code>```

Hope this helps to someone else.

Body:
I implemented a class in C# that interact basically with AWS S3 without having too much configuration.

** I'm using the MS Framework 4.5 **

First of all, remember to use the NuGet Package and install the AWS references (In VS >> Menu >> Tools >> NuGet Package Manager >> Manage NuGet Package Manager for Solution):

AWSSDK - Amazon Simple Storage Service

AWSSDK - Core Runtime

...implemented this class, for my need I only required the access key, secret key, region and the bucket (Exists more methods, but I only required copy, read and delete).

Note: It's not required additional configuration in the app.config file or install/create a profile in the USER folder...

public class clsAwsS3
{
    string accessKey { get; set; }
    string secretKey { get; set; }
    string bucket { get; set; }
    RegionEndpoint region { get; set; }
    IAmazonS3 client;

    public clsAwsS3(string strBucket, string strAccessKey, string strSecretKey, RegionEndpoint region)
    {
        this.bucket = strBucket;
        this.accessKey = strAccessKey;
        this.secretKey = strSecretKey;
        this.region = region;
        login();
    }

    private void login()
    {
        client = new AmazonS3Client(accessKey, secretKey, region);
    }

    public List<string> getItems(string strPrefix = "")
    {
        List<string> lstResult = new List<string>();
        ListObjectsV2Request listRequest;

        if (strPrefix == "")
            listRequest = new ListObjectsV2Request
            {
                BucketName = bucket
            };
        else
            listRequest = new ListObjectsV2Request
            {
                BucketName = bucket,
                Prefix = strPrefix
            };

        ListObjectsV2Response listResponse;

        do
        {
            listResponse = client.ListObjectsV2(listRequest);

            foreach (S3Object awsObject in listResponse.S3Objects)
                lstResult.Add(awsObject.Key);

            listRequest.ContinuationToken = listResponse.NextContinuationToken;
        } while (listResponse.IsTruncated);

        return lstResult;
    }

    public string downloadItem(string strItemKey, string strDestination)
    {
        GetObjectRequest request = new GetObjectRequest
        {
            BucketName = bucket,
            Key = strItemKey
        };

        using (GetObjectResponse response = client.GetObject(request))
        {
            response.WriteResponseStreamToFile(strDestination);
        }

        return strDestination;
    }

    public void copyItem(string strItemKeySource, string strItemKeyDestination)
    {
        CopyObjectRequest copyRequest = new CopyObjectRequest
        {
            SourceBucket = bucket,
            SourceKey = strItemKeySource,
            DestinationBucket = bucket,
            DestinationKey = strItemKeyDestination
        };

        CopyObjectResponse copyResponse = client.CopyObject(copyRequest);

        if (copyResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
            throw new Exception("Item has an error");
    }

    public void deleteItem(string strItemKey)
    {
        DeleteObjectRequest deleteObject = new DeleteObjectRequest
        {
            BucketName = bucket,
            Key = strItemKey
        };

        DeleteObjectResponse deleteResponse = client.DeleteObject(deleteObject);
    }
}

Hope this helps to someone else.


来源: stackexchange

问:
How to fix refreshPreferences Message in Xcode 9
add this line code to my class

```<code>let myLayer = CALayer()
myLayer.contents = self.makeTrySwiftLogoImage().CGImage

var transform = CATransform3DIdentity
transform.m34 = 1.0 / -500
transform = CATransform3DRotate(transform, 45.0f * M_PI / 180.0, 0, 1, 0)
myLayer.transform = transform
</code>```

and get this message to my console

2017-09-22 18:00:53.354890+0330 SibDiet[973:944502] refreshPreferences: HangTracerEnabled: 0
2017-09-22 18:00:53.355974+0330 SibDiet[973:944502] refreshPreferences: HangTracerDuration: 500
2017-09-22 18:00:53.356014+0330 SibDiet[973:944502] refreshPreferences: ActivationLoggingEnabled: 0 ActivationLoggingTaskedOffByDA:0

and don't run my application, remove this 6 line and run again but receive this message again, remove Xcode and install again but no fix

答:
I managed to fix it on High Sierra(10.13.1) XCode 9.1 and with iOS 11.0.3 by defining OS_ACTIVITY_MODE as disable by going in XCode via

Product > Scheme > Edit Scheme > Arguments > Environment Variables

add OS_ACTIVITY_MODE disable
schema editor (fragment)

Note: NSLog may not work after doing this.

Similar issue is reported in the question:

refreshPreferences HangTracerEnabled / HangTracerDuration messages in iOS 11 + Xcode 9

ContentLicense: CC BY-SA 3.0

Body:
add this line code to my class

let myLayer = CALayer()
myLayer.contents = self.makeTrySwiftLogoImage().CGImage

var transform = CATransform3DIdentity
transform.m34 = 1.0 / -500
transform = CATransform3DRotate(transform, 45.0f * M_PI / 180.0, 0, 1, 0)
myLayer.transform = transform

and get this message to my console

2017-09-22 18:00:53.354890+0330 SibDiet[973:944502] refreshPreferences: HangTracerEnabled: 0
2017-09-22 18:00:53.355974+0330 SibDiet[973:944502] refreshPreferences: HangTracerDuration: 500
2017-09-22 18:00:53.356014+0330 SibDiet[973:944502] refreshPreferences: ActivationLoggingEnabled: 0 ActivationLoggingTaskedOffByDA:0

and don't run my application, remove this 6 line and run again but receive this message again, remove Xcode and install again but no fix


问:
Getting 100% height not starting from the top?
http://www.xs4all.nl/~peterned/examples/csslayout1.html

The tutorial above is essentially what I want with a white column that extends to the bottom of the browser. In the tutorial it actually begins at the very top, with the header being a different shade of grey covering the white.

My case, the header would have to match the textured background. So, what I want is to have the container begin below the header. I don't know if it is possible because right now my header pushes the container down.

答:
http://andrew.x10.mx/adam/

html -

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>for adam</title>
    <link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div id="header">

    </div>
    <div id="container">
        <br class="push"></br>
        <div id="content">
            <h1>Hi</h1>
        </div>
    </div>
</body>
</html>
</code>```

css -

```<code>html,body  {
    height: 100%;
    margin: 0;
    padding: 0;
    text-align: center;
}

 #header {
    position: absolute;
    z-index: 2;
    top: 0px;
    left: 0px;
    width:100%;
    height: 49px;
    background: #fff url("bg.png") repeat-x top left;
    padding: 0;
    }

.push {
    width: 860px;
    height: 49px;
    margin: 0;
    }

#container {
    background: #ff0;
    height:auto !important;
    height:100%;
    position:relative;
    width: 860px;
    text-align: left;
    margin: 0 auto;
    min-height:100%;
    z-index:1;
    }

#content { padding: 10px; }
</code>```

Only tested it in Firefox, though. :)

Updated: feel free to validate. :)
Updated v2: Had a problem when adding content inside the container. Fixed now, but had to do some more complex-ish stuff.

ContentLicense: CC BY-SA 2.5

Body:
http://andrew.x10.mx/adam/

html -

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>for adam</title>
    <link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div id="header">

    </div>
    <div id="container">
        <br class="push"></br>
        <div id="content">
            <h1>Hi</h1>
        </div>
    </div>
</body>
</html>

css -

html,body  {
    height: 100%;
    margin: 0;
    padding: 0;
    text-align: center;
}

 #header {
    position: absolute;
    z-index: 2;
    top: 0px;
    left: 0px;
    width:100%;
    height: 49px;
    background: #fff url("bg.png") repeat-x top left;
    padding: 0;
    }

.push {
    width: 860px;
    height: 49px;
    margin: 0;
    }

#container {
    background: #ff0;
    height:auto !important;
    height:100%;
    position:relative;
    width: 860px;
    text-align: left;
    margin: 0 auto;
    min-height:100%;
    z-index:1;
    }

#content { padding: 10px; }

Only tested it in Firefox, though. :)

Updated: feel free to validate. :)
Updated v2: Had a problem when adding content inside the container. Fixed now, but had to do some more complex-ish stuff.


问:
How to get Sql Temp Table Join with column values that are not in table, replaced by 0
I have 5 temp tables that I want to combine into a new temp table via the month_year column and the prod_id. Where the columns are not prod_id or month_year and values are not available, I want that column's value(e.g. job_amt or received_qty) to be 0.

```<code>#tmp_spoilt_good_job_amt
month_year  job_amt     spoil   good    prod_id
07-2017         40      10        20    2
08-2017         827     0         210   3
09-2017         27      1         27    2
09-2017         732     22        345   3
10-2017         50      0         6     2
10-2017         1130    55        50    3
11-2017         300     0         0     4

#tmp_received_qty
month_year  received_qty    prod_id
 08-2017    32                 2
 08-2017    2500               3
 09-2017    2200               2
 11-2017    2500               4

#tmp_purchase_qty
month_year  purchase_qty    prod_id
 09-2017    11                 2

#tmp_opening_balance
month_year  opening_balance   prod_id
08-2017              32         2
08-2017             2500        3
09-2017               22        2
09-2017             2300        3
10-2017             2163        2
10-2017             2023        3
11-2017             2500        4

#tmp_closing_balance
month_year  closing_balance     prod_id
08-2017         2300                3
08-2017         32                  2
09-2017         2213                2
09-2017         1998                3
10-2017         1687                3
10-2017         2163                2
11-2017         2400                4
</code>```

I tried some inner joins but the values were repeating or some were not reflecting. what query could I use to get these combined?

I am looking for the following output:

答:
So, this kind of relation ships have very week performance, first of all it is better to change the tables structure and all other thing that related to fill data in you database.

Any way, this query created for your current needs with current data structure, also if you work on this query or divided it in to some views maybe you can improve performance:

```<code>SELECT CASE WHEN ISNULL(srpo.month_year , '-1') <> '-1' THEN srpo.month_year
            WHEN ISNULL(c.month_year , '-1') <> '-1' THEN c.month_year
       END AS month_year,
       CASE WHEN ISNULL(srpo.prod_id, -1) <> -1 THEN srpo.prod_id
            WHEN ISNULL (c.prod_id, -1) <> -1 THEN c.prod_id
       END AS prod_id,
       CASE WHEN ISNULL(c.closing_balance, -1) = -1 THEN 0 else c.closing_balance END AS closing_balance,
       srpo.job_amt,srpo.spoil,srpo.good ,srpo.received_qty,srpo.purchase_qty, srpo.opening_balance
FROM   #tmp_closing_balance AS c FULL OUTER JOIN

(SELECT CASE WHEN ISNULL(srp.month_year , '-1') <> '-1' THEN srp.month_year
            WHEN ISNULL(o.month_year , '-1') <> '-1' THEN o.month_year
       END AS month_year,
       CASE WHEN ISNULL(srp.prod_id, -1) <> -1 THEN srp.prod_id
            WHEN ISNULL (o.prod_id, -1) <> -1 THEN o.prod_id
       END AS prod_id,
       CASE WHEN ISNULL(o.opening_balance, -1) = -1 THEN 0 else o.opening_balance END AS opening_balance,
       srp.job_amt,srp.spoil,srp.good ,srp.received_qty,srp.purchase_qty
FROM   #tmp_opening_balance AS o FULL OUTER JOIN

(SELECT CASE WHEN ISNULL(sr.month_year , '-1') <> '-1' THEN sr.month_year
            WHEN ISNULL(p.month_year , '-1') <> '-1' THEN p.month_year
       END AS month_year,
       CASE WHEN ISNULL(sr.prod_id, -1) <> -1 THEN sr.prod_id
            WHEN ISNULL (p.prod_id, -1) <> -1 THEN p.prod_id
       END AS prod_id,
       CASE WHEN ISNULL(p.purchase_qty, -1) = -1 THEN 0 else p.purchase_qty END AS purchase_qty,
       sr.job_amt,sr.spoil,sr.good ,sr.received_qty
FROM #tmp_purchase_qty AS p FULL OUTER JOIN
     (SELECT CASE WHEN ISNULL(s.month_year , '-1') <> '-1' THEN s.month_year
            WHEN ISNULL(r.month_year , '-1') <> '-1' THEN r.month_year
       END AS month_year,
       CASE WHEN ISNULL(s.prod_id, -1) <> -1 THEN s.prod_id
            WHEN ISNULL (r.prod_id, -1) <> -1 THEN r.prod_id
       END AS prod_id,
       CASE WHEN ISNULL(s.job_amt, -1) = -1 THEN 0 else s.job_amt END AS job_amt,
       CASE WHEN ISNULL(s.spoil, -1) = -1 THEN 0 else s.spoil END AS spoil,
       CASE WHEN ISNULL(s.good, -1) = -1 THEN 0 else s.good END AS good,
       CASE WHEN ISNULL(r.received_qty, -1) = -1 THEN 0 else r.received_qty END AS received_qty
FROM #tmp_spoilt_good_job_amt AS s FULL OUTER JOIN
     #tmp_received_qty AS r ON s.prod_id = r.prod_id AND
                              LTRIM(rtrim(s.month_year)) = LTRIM(rtrim(r.month_year))) AS sr ON
     sr.prod_id = p.prod_id AND LTRIM(rtrim(sr.month_year)) = LTRIM(rtrim(p.month_year)) ) AS srp ON
     srp.prod_id = o.prod_id AND LTRIM(rtrim(srp.month_year)) = LTRIM(rtrim(o.month_year))) AS srpo ON
     srpo.prod_id = c.prod_id AND LTRIM(rtrim(srpo.month_year)) = LTRIM(rtrim(c.month_year))
</code>```

I use FULL OUTER JOIN for all part of query because you mentioned that, may be all tables have possible values for keys columns(month_year and prod_id).

Body:
I have 5 temp tables that I want to combine into a new temp table via the month_year column and the prod_id. Where the columns are not prod_id or month_year and values are not available, I want that column's value(e.g. job_amt or received_qty) to be 0.

#tmp_spoilt_good_job_amt
month_year  job_amt     spoil   good    prod_id
07-2017         40      10        20    2
08-2017         827     0         210   3
09-2017         27      1         27    2
09-2017         732     22        345   3
10-2017         50      0         6     2
10-2017         1130    55        50    3
11-2017         300     0         0     4

#tmp_received_qty
month_year  received_qty    prod_id
 08-2017    32                 2
 08-2017    2500               3
 09-2017    2200               2
 11-2017    2500               4

#tmp_purchase_qty
month_year  purchase_qty    prod_id
 09-2017    11                 2

#tmp_opening_balance
month_year  opening_balance   prod_id
08-2017              32         2
08-2017             2500        3
09-2017               22        2
09-2017             2300        3
10-2017             2163        2
10-2017             2023        3
11-2017             2500        4

#tmp_closing_balance
month_year  closing_balance     prod_id
08-2017         2300                3
08-2017         32                  2
09-2017         2213                2
09-2017         1998                3
10-2017         1687                3
10-2017         2163                2
11-2017         2400                4

I tried some inner joins but the values were repeating or some were not reflecting. what query could I use to get these combined?

I am looking for the following output:

Body:
So, this kind of relation ships have very week performance, first of all it is better to change the tables structure and all other thing that related to fill data in you database.

Any way, this query created for your current needs with current data structure, also if you work on this query or divided it in to some views maybe you can improve performance:

SELECT CASE WHEN ISNULL(srpo.month_year , '-1') <> '-1' THEN srpo.month_year
            WHEN ISNULL(c.month_year , '-1') <> '-1' THEN c.month_year
       END AS month_year,
       CASE WHEN ISNULL(srpo.prod_id, -1) <> -1 THEN srpo.prod_id
            WHEN ISNULL (c.prod_id, -1) <> -1 THEN c.prod_id
       END AS prod_id,
       CASE WHEN ISNULL(c.closing_balance, -1) = -1 THEN 0 else c.closing_balance END AS closing_balance,
       srpo.job_amt,srpo.spoil,srpo.good ,srpo.received_qty,srpo.purchase_qty, srpo.opening_balance
FROM   #tmp_closing_balance AS c FULL OUTER JOIN

(SELECT CASE WHEN ISNULL(srp.month_year , '-1') <> '-1' THEN srp.month_year
            WHEN ISNULL(o.month_year , '-1') <> '-1' THEN o.month_year
       END AS month_year,
       CASE WHEN ISNULL(srp.prod_id, -1) <> -1 THEN srp.prod_id
            WHEN ISNULL (o.prod_id, -1) <> -1 THEN o.prod_id
       END AS prod_id,
       CASE WHEN ISNULL(o.opening_balance, -1) = -1 THEN 0 else o.opening_balance END AS opening_balance,
       srp.job_amt,srp.spoil,srp.good ,srp.received_qty,srp.purchase_qty
FROM   #tmp_opening_balance AS o FULL OUTER JOIN

(SELECT CASE WHEN ISNULL(sr.month_year , '-1') <> '-1' THEN sr.month_year
            WHEN ISNULL(p.month_year , '-1') <> '-1' THEN p.month_year
       END AS month_year,
       CASE WHEN ISNULL(sr.prod_id, -1) <> -1 THEN sr.prod_id
            WHEN ISNULL (p.prod_id, -1) <> -1 THEN p.prod_id
       END AS prod_id,
       CASE WHEN ISNULL(p.purchase_qty, -1) = -1 THEN 0 else p.purchase_qty END AS purchase_qty,
       sr.job_amt,sr.spoil,sr.good ,sr.received_qty
FROM #tmp_purchase_qty AS p FULL OUTER JOIN
     (SELECT CASE WHEN ISNULL(s.month_year , '-1') <> '-1' THEN s.month_year
            WHEN ISNULL(r.month_year , '-1') <> '-1' THEN r.month_year
       END AS month_year,
       CASE WHEN ISNULL(s.prod_id, -1) <> -1 THEN s.prod_id
            WHEN ISNULL (r.prod_id, -1) <> -1 THEN r.prod_id
       END AS prod_id,
       CASE WHEN ISNULL(s.job_amt, -1) = -1 THEN 0 else s.job_amt END AS job_amt,
       CASE WHEN ISNULL(s.spoil, -1) = -1 THEN 0 else s.spoil END AS spoil,
       CASE WHEN ISNULL(s.good, -1) = -1 THEN 0 else s.good END AS good,
       CASE WHEN ISNULL(r.received_qty, -1) = -1 THEN 0 else r.received_qty END AS received_qty
FROM #tmp_spoilt_good_job_amt AS s FULL OUTER JOIN
     #tmp_received_qty AS r ON s.prod_id = r.prod_id AND
                              LTRIM(rtrim(s.month_year)) = LTRIM(rtrim(r.month_year))) AS sr ON
     sr.prod_id = p.prod_id AND LTRIM(rtrim(sr.month_year)) = LTRIM(rtrim(p.month_year)) ) AS srp ON
     srp.prod_id = o.prod_id AND LTRIM(rtrim(srp.month_year)) = LTRIM(rtrim(o.month_year))) AS srpo ON
     srpo.prod_id = c.prod_id AND LTRIM(rtrim(srpo.month_year)) = LTRIM(rtrim(c.month_year))

I use FULL OUTER JOIN for all part of query because you mentioned that, may be all tables have possible values for keys columns(month_year and prod_id).


问:
Reusing the same reducer & epic for multiple Ajax calls like an api factory?
is using the same reducer to update different parts of state an anti pattern?

Like my data reducer has a GET_DATA_DONE action, updates state.data and then in another instance you use fetch something else and call GET_DATA_DONE to update state.somethingElse?

Or would you do something like GET_SOMETHING_DATA_DONE & so on.. multiple diff actions doing the same thing? (Hardly DRY)

reducers.js

```<code>export const reducer = (state, action) => {
  switch (action.type) {
    case actions.GET_DATA_REQUESTED:
      return { ...state, isLoading: true };
    case actions.GET_DATA_DONE:
      return { ...state, isLoading: false, data: action.payload };
    case actions.GET_DATA_FAILED:
      return { ...state, isLoading: false, isError: true }
    default:
      return state;
  }
};
</code>```

actions.js

```<code>export function getDataRequested() {
  return {
    type: 'GET_DATA_REQUESTED'
  };
}

export function getDataDone(data) {
  return {
    type: 'GET_DATA_DONE',
    payload: data
  };
}

export function getDataFailed(error) {
  return {
    type: 'GET_DATA_FAILED',
    payload: error
  };
};

export function getDataEpic(action$) {
  return action$.ofType(GET_DATA_REQUESTED)
    .mergeMap(action =>
      ajax.getJSON(action.url)
        .map(response => getDataDone(response))
        .catch(error => getDataFailed(error))
    );
}
</code>```

What't the best way to structure the app such that , getDataEpic acts like a api factory and the data returned from getDataDone(response) can be passed to another reducer to update a part of state based on the action, for example a cities action using getDataDone reducer dispatches another action which updates state.cities with the response?

Edit: I've made an app with rx-observable & redux calling 3 different api's but I ended up with a lot of duplicate code and just not happy with the solution, so i want to build a properly architectured app

Hope I was clear enough.

Thanks a lot!

答:
I don't think it's an anti-pattern if deals with state of it's own children, but if used too much, it could certainly get you in trouble. Having it modify totally unrelated state is a definite anti-pattern. According to the docs the first line hits the nail on the head.

For any meaningful application, putting all your update logic into a single reducer function is quickly going to become unmaintainable.

We're not talking about 'all our data' but we are talking about all the data from a single API call.

It's not too complicated in regards to setting a loading flag but in a real world app would get significantly more complicated for a reducer that is both setting a loading flag, error flag and 'data'. And that is assuming we even know what the data being requested is.

In your example, if the intention is to create an API factory through reducers, we have to assume an API could return any number of different data structures, right now it could be a string or an int but what if it's a deeply nested Object? How would you access this data and differentiate it between another piece of data?

Let's say we have an app with this data structure for just the errors:

```<code>{
  "errors": {
    "byId": {
      "1": {
        "code": 500,
        "message": "There was an internal server error"
      },
      "2": {
        "code": 400,
        "message": "There was another error."
      },
      "3": {
        "code": 999,
        "message": "Wow! weird error."
      },
    },
    "all": ["1", "2", "3"]
  }
}
</code>```

I might have a byId reducer that returns a computed key with another reducer as the value.

```<code>byId = (state={}, action) => {
  if (action.type === 'ADD_ERROR') {
    ...state,
    [action.id]:error_reducer(state[action.id], action)
  } else {
    return state
  }
}
</code>```

error_reducer might look like

```<code>errorReducer = (state={}, action) => {
  if (action.type === 'ADD_ERROR') {
    code: action.code,
    message: action.message
  } else {
    return state
  }
}
</code>```

I think it makes more sense to have errorReducer handle both code and message because we know that they are both mutually inclusive pieces of data where as each error is mutually exclusive (different ids) and so require their own reducer.

Another major advantage of this when dealing with real-world applications is that when the data is separated one action can update state across MANY different areas of our app. When reducers handle multiple pieces of state these pieces of tied state become harder to update.

There are many different patterns you can employ with your reducers and none of them are wrong however I have found this pattern to work very well for me and i've used it successfully in a quite complex production app.

Having said all that, one possible approach for your AJAX function is to write a generic action that accepts an object that contains your dispatches.

By using a library like redux-thunk you can execute multiple dispatches to update different parts of your state with different pieces of data. I won't explain redux-thunk here as I think it's beyond the scope of the question.

an example object might look like this:

```<code>{
  getDataRequested: function () {
    return {
      type: 'GET_DATA_REQUESTED'
    };
  },
  getDataFailed: function (error) {
    return {
      type: 'GET_DATA_FAILED',
      payload: error
    };
  },
  getDataDone: function (data) {
    return {
      type: 'GET_DATA_DONE',
      payload: data
    };
  }
}
</code>```

then you can pass this object of callbacks to your main AJAX function along with your API endpoint, REST request type etc.

I hope this helps.

Body:
is using the same reducer to update different parts of state an anti pattern?

Like my data reducer has a GET_DATA_DONE action, updates state.data and then in another instance you use fetch something else and call GET_DATA_DONE to update state.somethingElse?

Or would you do something like GET_SOMETHING_DATA_DONE & so on.. multiple diff actions doing the same thing? (Hardly DRY)

reducers.js

export const reducer = (state, action) => {
  switch (action.type) {
    case actions.GET_DATA_REQUESTED:
      return { ...state, isLoading: true };
    case actions.GET_DATA_DONE:
      return { ...state, isLoading: false, data: action.payload };
    case actions.GET_DATA_FAILED:
      return { ...state, isLoading: false, isError: true }
    default:
      return state;
  }
};

actions.js

export function getDataRequested() {
  return {
    type: 'GET_DATA_REQUESTED'
  };
}

export function getDataDone(data) {
  return {
    type: 'GET_DATA_DONE',
    payload: data
  };
}

export function getDataFailed(error) {
  return {
    type: 'GET_DATA_FAILED',
    payload: error
  };
};

export function getDataEpic(action$) {
  return action$.ofType(GET_DATA_REQUESTED)
    .mergeMap(action =>
      ajax.getJSON(action.url)
        .map(response => getDataDone(response))
        .catch(error => getDataFailed(error))
    );
}

What't the best way to structure the app such that , getDataEpic acts like a api factory and the data returned from getDataDone(response) can be passed to another reducer to update a part of state based on the action, for example a cities action using getDataDone reducer dispatches another action which updates state.cities with the response?

Edit: I've made an app with rx-observable & redux calling 3 different api's but I ended up with a lot of duplicate code and just not happy with the solution, so i want to build a properly architectured app

Hope I was clear enough.

Thanks a lot!

Body:
I don't think it's an anti-pattern if deals with state of it's own children, but if used too much, it could certainly get you in trouble. Having it modify totally unrelated state is a definite anti-pattern. According to the docs the first line hits the nail on the head.

For any meaningful application, putting all your update logic into a single reducer function is quickly going to become unmaintainable.

We're not talking about 'all our data' but we are talking about all the data from a single API call.

It's not too complicated in regards to setting a loading flag but in a real world app would get significantly more complicated for a reducer that is both setting a loading flag, error flag and 'data'. And that is assuming we even know what the data being requested is.

In your example, if the intention is to create an API factory through reducers, we have to assume an API could return any number of different data structures, right now it could be a string or an int but what if it's a deeply nested Object? How would you access this data and differentiate it between another piece of data?

Let's say we have an app with this data structure for just the errors:

{
  "errors": {
    "byId": {
      "1": {
        "code": 500,
        "message": "There was an internal server error"
      },
      "2": {
        "code": 400,
        "message": "There was another error."
      },
      "3": {
        "code": 999,
        "message": "Wow! weird error."
      },
    },
    "all": ["1", "2", "3"]
  }
}

I might have a byId reducer that returns a computed key with another reducer as the value.

byId = (state={}, action) => {
  if (action.type === 'ADD_ERROR') {
    ...state,
    [action.id]:error_reducer(state[action.id], action)
  } else {
    return state
  }
}

error_reducer might look like

errorReducer = (state={}, action) => {
  if (action.type === 'ADD_ERROR') {
    code: action.code,
    message: action.message
  } else {
    return state
  }
}

I think it makes more sense to have errorReducer handle both code and message because we know that they are both mutually inclusive pieces of data where as each error is mutually exclusive (different ids) and so require their own reducer.

Another major advantage of this when dealing with real-world applications is that when the data is separated one action can update state across MANY different areas of our app. When reducers handle multiple pieces of state these pieces of tied state become harder to update.

There are many different patterns you can employ with your reducers and none of them are wrong however I have found this pattern to work very well for me and i've used it successfully in a quite complex production app.

Having said all that, one possible approach for your AJAX function is to write a generic action that accepts an object that contains your dispatches.

By using a library like redux-thunk you can execute multiple dispatches to update different parts of your state with different pieces of data. I won't explain redux-thunk here as I think it's beyond the scope of the question.

an example object might look like this:

{
  getDataRequested: function () {
    return {
      type: 'GET_DATA_REQUESTED'
    };
  },
  getDataFailed: function (error) {
    return {
      type: 'GET_DATA_FAILED',
      payload: error
    };
  },
  getDataDone: function (data) {
    return {
      type: 'GET_DATA_DONE',
      payload: data
    };
  }
}

then you can pass this object of callbacks to your main AJAX function along with your API endpoint, REST request type etc.

I hope this helps.


问:
Make multiple random number of copies of rows in a dataframe
I have a dataframe in r with 100 rows of unique first and last name and address.  I also have columns for weather 1 and weather 2.  I want to make a random number of copies between 50 and 100 for each row.   How would I do that?

df$fname df$lname  df$street df$town df%state df$weather1  df$weather2

答:
This is probably not the easiest way to do this, but...

What I've done here is for each for of the data set select just that row and make 1-3 (sub 50-100) copies of that row, and finally stack all the results together.

library(dplyr)
library(purrr)

df <- tibble(foo = 1:3, bar = letters[1:3])

map_dfr(seq_len(nrow(df)), ~{
  df %>%
    slice(.x) %>%
    sample_n(size = sample(1:3, 1), replace = TRUE)
})

#> # A tibble: 7 x 2
#>     foo   bar
#>   <int> <chr>
#> 1     1     a
#> 2     1     a
#> 3     1     a
#> 4     2     b
#> 5     2     b
#> 6     3     c
#> 7     3     c
```


问:
IdentityServer4 - How to store refresh token into database using mysql.data?
I'm new at IdentityServer4. I read I need to implement an IPersistedGrantStore to store refresh tokens into a table like PersistedGrants in my database.

IdentityServer logs is the following when my native app ask for a new access token: "refresh_token" grant with value: "{value}" not found in store.

That's because I'm using in-memory version of the persisted grant store. So I need to store refresh token in a PersistedGrant table.

Therefore
in my startup.cs I added the following line:

```<code>builder.Services.AddScoped<IPersistedGrantStore, PersistedGrantStore>();
</code>```

and IPersistedGrantStore.cs is

```<code>public interface IPersistedGrantStore
{
    Task StoreAsync(CustomPersistedGrant grant);

    Task<CustomPersistedGrant> GetAsync(string key);

    Task<IEnumerable<CustomPersistedGrant>> GetAllAsync(string subjectId);
}
</code>```

So I have a CustomPersistedGrant.cs class

```<code>public class CustomPersistedGrant
{
    public string Key { get; set; }

    public string Type { get; set; }

    public string SubjectId { get; set; }

    public string ClientId { get; set; }

    public DateTime CreationTime { get; set; }

    public DateTime? Expiration { get; set; }

    public string Data { get; set; }
}
</code>```

and now I have to write the code for my PersistedGrantStore.cs class.
But the question is: once I have write code for PersistedGrantStore.cs class where I call PersistedGrantStore.cs class? In Identity.Server Account/AccountController? I didn't find any example about it without use EntityFramework, because I don't want to use Entity Framework.

Thanks.

答:
The key will be to implement IPersistedGrantStore using whatever backend you like, then to tell IdentityServer to use that implementation by registering the implementation in the dependency injection system.

For example, if you call your implementation PersistedGrantStore, then you could register the implementation like this:

services.AddTransient<IPersistedGrantStore, PersistedGrantStore>();

You can see that essentially this is all that the EntityFramework implementation does, once you take away all the EntityFramework stuff.

Later when IdentityServer wants to persist a grant, it will get your implementation and call the appropriate method.  So you don't have to do anything, other than inject your implementation into IdentityServer so it can do whats needed.

Body:
I'm new at IdentityServer4. I read I need to implement an IPersistedGrantStore to store refresh tokens into a table like PersistedGrants in my database.

IdentityServer logs is the following when my native app ask for a new access token: "refresh_token" grant with value: "{value}" not found in store.

That's because I'm using in-memory version of the persisted grant store. So I need to store refresh token in a PersistedGrant table.

Therefore
in my startup.cs I added the following line:

builder.Services.AddScoped<IPersistedGrantStore, PersistedGrantStore>();

and IPersistedGrantStore.cs is

public interface IPersistedGrantStore
{
    Task StoreAsync(CustomPersistedGrant grant);

    Task<CustomPersistedGrant> GetAsync(string key);

    Task<IEnumerable<CustomPersistedGrant>> GetAllAsync(string subjectId);
}

So I have a CustomPersistedGrant.cs class

public class CustomPersistedGrant
{
    public string Key { get; set; }

    public string Type { get; set; }

    public string SubjectId { get; set; }

    public string ClientId { get; set; }

    public DateTime CreationTime { get; set; }

    public DateTime? Expiration { get; set; }

    public string Data { get; set; }
}

and now I have to write the code for my PersistedGrantStore.cs class.
But the question is: once I have write code for PersistedGrantStore.cs class where I call PersistedGrantStore.cs class? In Identity.Server Account/AccountController? I didn't find any example about it without use EntityFramework, because I don't want to use Entity Framework.

Thanks.


问:
How to resolve "Uncaught TypeError: Failed to construct 'Comment': Please use the 'new' operat....." with respect to React JS?
I have a home.jsp where within body

```<code><body>
    <script type="text/babel" src="../resources/scripts/example.js"></script>
     <a href="javascript:Comment();">News</a>
</body>
</code>```

In a separate example.js, I have the following

```<code>alert("I am coming here ... BEEP");

var Comment = React.createClass({
      loadCommentsFromServer: function() {
        $.ajax({
          url: this.props.url,
          dataType: 'json',
          cache: false,
          success: function(data) {
            this.setState({data: data});
          }.bind(this),
          error: function(xhr, status, err) {
            console.error(this.props.url, status, err.toString());
          }.bind(this)
        });
      },
      getInitialState: function() {
        return {data: []};
      },
      componentDidMount: function() {
        this.loadCommentsFromServer();
        setInterval(this.loadCommentsFromServer, this.props.pollInterval);
      },
      render: function() {
        return (
          <div className="comment">
            <Comment data={this.state.data} />
            <span dangerouslySetInnerHTML={{__html: data}} />
          </div>
        );
      }
    });

    ReactDOM.render(
      <Comment url="/workingUrl" pollInterval={2000} />,
      document.getElementById('content')
    );
</code>```

I am getting the following error in Chrome console.

```<code>Uncaught TypeError: Failed to construct 'Comment': Please use the 'new'
operator, this DOM object constructor cannot be called as a function.
</code>```

I have added React js tags in home.jsp file.

How to fix this? Please help me.

答:
Maybe this will help someone who had the same issue as me...I simply forgot to import the component I was trying to render:</p>
```<code>import { Comment } from './comment'
</code>```

Body:
I have a home.jsp where within body

     News

In a separate example.js, I have the following

alert("I am coming here ... BEEP");

var Comment = React.createClass({
      loadCommentsFromServer: function() {
        $.ajax({
          url: this.props.url,
          dataType: 'json',
          cache: false,
          success: function(data) {
            this.setState({data: data});
          }.bind(this),
          error: function(xhr, status, err) {
            console.error(this.props.url, status, err.toString());
          }.bind(this)
        });
      },
      getInitialState: function() {
        return {data: []};
      },
      componentDidMount: function() {
        this.loadCommentsFromServer();
        setInterval(this.loadCommentsFromServer, this.props.pollInterval);
      },
      render: function() {
        return (

            <Comment data={this.state.data} />

        );
      }
    });

    ReactDOM.render(
      <Comment url="/workingUrl" pollInterval={2000} />,
      document.getElementById('content')
    );

I am getting the following error in Chrome console.

Uncaught TypeError: Failed to construct 'Comment': Please use the 'new'
operator, this DOM object constructor cannot be called as a function.

I have added React js tags in home.jsp file.

How to fix this? Please help me.

Body:
Maybe this will help someone who had the same issue as me...I simply forgot to import the component I was trying to render:

import { Comment } from './comment'

ContentLicense: CC BY-SA 4.0


问:
Azure importing data SQL
I've been trying to sort through Microsoft's extensive documentation, but, cannot find the answer I'm looking for, hence, posting it here for the experts!

I have a table in a database in MS SQL Server 2016, that I read/write to using MS SSMMS. I would like to export this single table into my Azure storage account for further analysis in the MS Data Science Virtual Machine, but cannot find a way to do this. Any suggestions?

Thanks.

答:
You can also use tools built into the MS Data Science Virtual Machine (DSVM) to first export from SQL Server to CSV. BCP (command line) is one tool.

If you want a graphic tool, use SSMS and use the "import and export" option to save result of your query to CSV file. Then you can copy the CSV file to a Azure storage account using Azcopy (command line) or Azure Storage explorer (graphical) also available on the DSVM. Hope this helps.

Title: Azure importing data SQL


问:
react-data-grid headerRenderer Sorting
How is sorting and filtering implemented when using a custom header cell in the react-data-grid?

```<code>{
  key: "myColumn1",
  name: "My Column Name",
  headerRenderer: this.renderHeader,
  sortable: true,
  filterable: true
},
{
  key: "myColumn2",
  name: "My Other Column Name",
  sortable: true,
  filterable: true
}
  ...

renderHeader(props){
  return  (<extra-stuff>
    {props.column.name}
  </extra-stuff>)
}
</code>```

I have myColumn2 sorting fine but nothing happens with the custom header: myColumn1.  What do I need to do in renderHeader(){} to get sorting (and filtering, but mainly sorting) working?

答:
Instead of trying to call a function in headerRenderer, put a component instead:</p>

```<code>{
  key: "myColumn1",
  name: "My Column Name",
  headerRenderer: <renderHeader value={this.renderHeader()} />,
  sortable: true,
  filterable: true
},
</code>```

Title: react-data-grid headerRenderer Sorting

Body:
How is sorting and filtering implemented when using a custom header cell in the react-data-grid?

{
  key: "myColumn1",
  name: "My Column Name",
  headerRenderer: this.renderHeader,
  sortable: true,
  filterable: true
},
{
  key: "myColumn2",
  name: "My Other Column Name",
  sortable: true,
  filterable: true
}
  ...

renderHeader(props){
  return  (<extra-stuff>
    {props.column.name}
  </extra-stuff>)
}

I have myColumn2 sorting fine but nothing happens with the custom header: myColumn1.  What do I need to do in renderHeader(){} to get sorting (and filtering, but mainly sorting) working?

Body:
Instead of trying to call a function in headerRenderer, put a component instead:

{
  key: "myColumn1",
  name: "My Column Name",
  headerRenderer: <renderHeader value={this.renderHeader()} />,
  sortable: true,
  filterable: true
},


问:
This code is in an infinite loop and was wondering how to fix it
```<code>for(num <= num2; num++;)
{
    for (i = 1; i <= num; i++)

        if(num % i == 0)

        prime++;
    cout << "There are "<< prime <<" prime numbers in the given range." << endl;
}
</code>```

It seems to me that this should be right or I'm just overlooking some small detail. But when I output it keeps going.

答:
This is wrong. For loop has 3 statements.

```<code>1) initialization. We can leave this blank if not required.
2) Condition
3) modification of variables.
</code>```

your outer loop is missing first statement. So num <= num2 is getting treated as first statement.

It should be

```<code>for(;num <= num2; num++)
</code>```

Body:
for(num <= num2; num++;)
{
    for (i = 1; i <= num; i++)

        if(num % i == 0)

        prime++;
    cout << "There are "<< prime <<" prime numbers in the given range." << endl;
}

It seems to me that this should be right or I'm just overlooking some small detail. But when I output it keeps going.

Body:
This is wrong. For loop has 3 statements.

1) initialization. We can leave this blank if not required.
2) Condition
3) modification of variables.

your outer loop is missing first statement. So num <= num2 is getting treated as first statement.

It should be

for(;num <= num2; num++)


答: for(num <= num2; num++;) this is the problem for(init; condition; increment) but your condition is num++ now.

Title: This code is in an infinite loop and was wondering how to fix it


问:
userscript is blocking itself when loaded on more than one tab
I have this problem with greasemonkey 3.17 on FF56 as well as in tampermonkey on Vivaldi, and I cannot find anything about this problem via google.

Example script:

```<code>// ==UserScript==
// @name        stackoverflow.com
// @namespace   siod87gbnwf87rnsfdkn
// @include     https://stackoverflow.com/*
// @version     1
// ==/UserScript==

alert(1);
alert(2);
</code>```

As you can see it's super simple and should give one message box, and after clicking OK the second one. This basically works fine, but now for the problem:

Go to stackoverflow.com

Use middle mouse button two open a question in a new tab twice directly after another, so that the second tab opens while the other still loads

What happens is, that both tabs will show popupbox "1" as expected, but when you click OK on the box from the first tab the script will pause until you click OK on the popupbox in the second tab. After you clicked OK twice on the second tab, then the alert on the first tab will trigger.

Why do the scripts not run independently from each other? This has nothing to do with alert, I had this problem with a more complicated script, but for showing my problem, alert works the same.

答:
Why do the scripts not run independently from each other?

They are run "independently" in the sense that they do not share the global space. However, blocking calls such as alert are handled by the browser itself, and the ordering is not specified in the ECMAScript specification.

One "solution" would be to not use blocking calls such as alert. Instead, if you need to print out values, use console.log or console.info.

Body:
I have this problem with greasemonkey 3.17 on FF56 as well as in tampermonkey on Vivaldi, and I cannot find anything about this problem via google.

Example script:

// ==UserScript==
// @name        stackoverflow.com
// @namespace   siod87gbnwf87rnsfdkn
// @include     https://stackoverflow.com/*
// @version     1
// ==/UserScript==

alert(1);
alert(2);

As you can see it's super simple and should give one message box, and after clicking OK the second one. This basically works fine, but now for the problem:

Go to stackoverflow.com

Use middle mouse button two open a question in a new tab twice directly after another, so that the second tab opens while the other still loads

What happens is, that both tabs will show popupbox "1" as expected, but when you click OK on the box from the first tab the script will pause until you click OK on the popupbox in the second tab. After you clicked OK twice on the second tab, then the alert on the first tab will trigger.

Why do the scripts not run independently from each other? This has nothing to do with alert, I had this problem with a more complicated script, but for showing my problem, alert works the same.


问:
How can I mix decorators with the @contextmanager decorator?
Here is the code I'm working with:

```<code>from contextlib import contextmanager
from functools import wraps
class with_report_status(object):

    def __init__(self, message):
        self.message = message

    def __call__(self, f):
        @wraps(f)
        def wrapper(_self, *a, **kw):
            try:
                return f(_self, *a, **kw)
            except:
                log.exception("Handling exception in reporting operation")
                if not (hasattr(_self, 'report_status') and _self.report_status):
                    _self.report_status = self.message
                raise

        return wrapper

class MyClass(object):

    @contextmanager
    @with_report_status('unable to create export workspace')
    def make_workspace(self):
        temp_dir = tempfile.mkdtemp()
        log.debug("Creating working directory in %s", temp_dir)
        self.workspace = temp_dir
        yield self.workspace
        log.debug("Cleaning up working directory in %s", temp_dir)
        shutil.rmtree(temp_dir)

    @with_report_status('working on step 1')
    def step_one(self):
        # do something that isn't a context manager
</code>```

The problem is, @with_report_status does not yield, as expected by @contextmanager. However, I can't wrap it the other way around either, because @contextmanager returns a generator object (i think!) instead of the value itself.

How can I make @contextmanager play nice with decorators?

答:
That is kind of a weird question: @contextmanager returns a context manager, not a generator. But for some reason you want to treat that context manager like a function? That's not something you can make work, they have nothing in common.

I think what you want is a MyClass.make_workspace that is context manager and also has a report_status field in case of exceptions. For that you need to write a context manager yourself that sets this field in it's __exit__ method, @contextmanager can't help you here.

You can subclass contextlib.GeneratorContextManager to avoid most of the work. It's not documented, so use the source, Luke.

Body:
Here is the code I'm working with:

from contextlib import contextmanager
from functools import wraps
class with_report_status(object):

    def __init__(self, message):
        self.message = message

    def __call__(self, f):
        @wraps(f)
        def wrapper(_self, *a, **kw):
            try:
                return f(_self, *a, **kw)
            except:
                log.exception("Handling exception in reporting operation")
                if not (hasattr(_self, 'report_status') and _self.report_status):
                    _self.report_status = self.message
                raise

        return wrapper

class MyClass(object):

    @contextmanager
    @with_report_status('unable to create export workspace')
    def make_workspace(self):
        temp_dir = tempfile.mkdtemp()
        log.debug("Creating working directory in %s", temp_dir)
        self.workspace = temp_dir
        yield self.workspace
        log.debug("Cleaning up working directory in %s", temp_dir)
        shutil.rmtree(temp_dir)

    @with_report_status('working on step 1')
    def step_one(self):
        # do something that isn't a context manager

The problem is, @with_report_status does not yield, as expected by @contextmanager. However, I can't wrap it the other way around either, because @contextmanager returns a generator object (i think!) instead of the value itself.

How can I make @contextmanager play nice with decorators?


问:
Exporting A PHP Different Dynamic Tables to EXCEL/SPREADSHEET horizontally
I am using the php2excel I found at https://github.com/rainabba/jquery-table2excel

Here is the output image

THIS IS THE OUTPUT THAT I WANT

```<code><script type="text/javascript" src="dist/jquery.table2excel.min.js"></script>

          <script>
                          function printReports() {
                              $(".center").table2excel({
                                exclude: ".noExl",
                                name: "Excel Document Name",
                                filename: "Term_Grades" + new Date().toISOString().replace(/[\-\:\.]/g, ""),
                                fileext: ".xlsx",
                                exclude_img: true,
                                exclude_links: true,
                                exclude_inputs: true
                              });
                            };
                          </script>
</code>```

Download

```<code>                              <table border='0' class="table" style="border-color: white;float:left; width:18%">
                                <thead >
                                  <!-- <th>#</th> -->
                                  <th style= "background-color: #008066; color: white; height:60px; width: 28px; font-size:12px">No</th>
                                  <th style= "background-color: #008066; color: white; height:60px; width: 115px; font-size:12px">Lastname</th>
                                  <th style= "background-color: #008066; color: white; height:60px; width: 42px; font-size:12px">SN</th>
                                  <th style= "background-color: #008066; color: white; height:60px; width: 100px; font-size:12px">COY</th>
                                </thead>
                                <tbody>

                                  <tr>
                                    <td>1</td>
                                    <td>2</td>
                                    <td>3</td>
                                    <td>4</td>
                                  <tr>
                                  <tr>
                                    <td>5</td>
                                    <td>6</td>
                                    <td>7</td>
                                    <td>8</td>
                                  <tr>

                                </tbody>
                              </table>

                              <table border='0' class="table" style="border-color: white;float:left; width:18%">
                                <thead >
                                  <!-- <th>#</th> -->
                                  <th style= "background-color: #008066; color: white; height:60px; width: 28px; font-size:12px">Another No</th>
                                  <th style= "background-color: #008066; color: white; height:60px; width: 115px; font-size:12px">Another Lastname</th>
                                  <th style= "background-color: #008066; color: white; height:60px; width: 42px; font-size:12px">Another SN</th>
                                  <th style= "background-color: #008066; color: white; height:60px; width: 100px; font-size:12px">Another COY</th>
                                </thead>
                                <tbody>

                                  <tr>
                                    <td>Another 1</td>
                                    <td>Another 2</td>
                                    <td>Another 3</td>
                                    <td>Another 4</td>
                                  <tr>
                                  <tr>
                                    <td>Another 5</td>
                                    <td>Another 6</td>
                                    <td>Another 7</td>
                                    <td>Another 8</td>
                                  <tr>

                                </tbody>
                              </table>

                              <table border='0' class="table" style="border-color: white;float:left; width:18%">
                                <thead >
                                  <!-- <th>#</th> -->
                                  <th style= "background-color: #008066; color: white; height:60px; width: 28px; font-size:12px">Some No</th>
                                  <th style= "background-color: #008066; color: white; height:60px; width: 115px; font-size:12px">Some Lastname</th>
                                  <th style= "background-color: #008066; color: white; height:60px; width: 42px; font-size:12px">Some SN</th>
                                  <th style= "background-color: #008066; color: white; height:60px; width: 100px; font-size:12px">Some COY</th>
                                </thead>
                                <tbody>

                                  <tr>
                                    <td>Some 1</td>
                                    <td>Some 2</td>
                                    <td>Some 3</td>
                                    <td>Some 4</td>
                                  <tr>

                                  <tr>
                                    <td>Some 5</td>
                                    <td>Some 6</td>
                                    <td>Some 7</td>
                                    <td>Some 8</td>
                                  <tr>

                                </tbody>
                              </table>

                          </div>
</code>```

The output of excel file when i export it is that the 2 tables are in the bottom instead of having side by side to each other. I cannot join 3 tables into 1 due to other instances so. The code above is just a dummy table

答: How to make 3 html tables show exactly in excel file side by side. Currently the output is that the 3 tables are in the end of each other.  the code is above and the output is shown in the picture</p>

Body:
I am using the php2excel I found at https://github.com/rainabba/jquery-table2excel

Here is the output image

THIS IS THE OUTPUT THAT I WANT

Download

                                  No
                                  Lastname
                                  SN
                                  COY

                                    1
                                    2
                                    3
                                    4

                                    5
                                    6
                                    7
                                    8

                                  Another No
                                  Another Lastname
                                  Another SN
                                  Another COY

                                    Another 1
                                    Another 2
                                    Another 3
                                    Another 4

                                    Another 5
                                    Another 6
                                    Another 7
                                    Another 8

                                  Some No
                                  Some Lastname
                                  Some SN
                                  Some COY

                                    Some 1
                                    Some 2
                                    Some 3
                                    Some 4

                                    Some 5
                                    Some 6
                                    Some 7
                                    Some 8

The output of excel file when i export it is that the 2 tables are in the bottom instead of having side by side to each other. I cannot join 3 tables into 1 due to other instances so. The code above is just a dummy table


问:
Do html and php use the same css file?
for example: you created a website and in that website you want to create a login page using php. Do you use the css file that you design your website with, to design login page?</p>

答:
You can use a single CSS page to style your whole website if you want to . You will just have to make sure you load in every html file that you load in the browser.

I would suggest splitting this up css file into parts if you expect your application to grow bigger.

Title: Do html and php use the same css file?


问:
"Unexpected token {" when using npx babel-node
Here is my script test.js:

```<code>import 'jsdom-global/register';
import 'canvas';
console.log('done');
</code>```

And here is my package.json:

```<code>{
  "name": "test-jsdom",
  "description": "Test",
  "version": "0.1.0",
  "author": "anthony@me.com",
  "dependencies": {
    "canvas": "^1.6.7"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-stage-0": "^6.24.1",
    "jsdom": "^11.3.0",
    "jsdom-global": "^3.0.2"
  }
}
</code>```

When I run npx babel-node test.js, I encountered this error

```<code>/Users/antkong/test/node_modules/jsdom/lib/api.js:10
const { URL } = require("whatwg-url");
      ^

SyntaxError: Unexpected token {
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Module._extensions..js (module.js:416:10)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/antkong/test/node_modules/babel-register/lib/node.js:152:7)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at globalJsdom (/Users/antkong/test/node_modules/jsdom-global/index.js:28:15)
    at Object.<anonymous> (/Users/antkong/test/node_modules/jsdom-global/register.js:1:19)
</code>```

And it is my .babelrc file

```<code>{
 "presets": ["env", "stage-0"]
}
</code>```

It seems to me babel-node cannot handle es6 syntax in the dependent js file. I expect babel-node to be able to load and compile all dependency on the fly. How can I fix this problem?

Version info:

```<code>$ node --version
v4.8.6
$ npm --version
2.15.11
</code>```

答:
Should use more up to date version of node.

I use nvm to switch  node to  version 8.7.0 and the issue is fixed.

Body:
Here is my script test.js:

import 'jsdom-global/register';
import 'canvas';
console.log('done');

And here is my package.json:

{
  "name": "test-jsdom",
  "description": "Test",
  "version": "0.1.0",
  "author": "anthony@me.com",
  "dependencies": {
    "canvas": "^1.6.7"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-stage-0": "^6.24.1",
    "jsdom": "^11.3.0",
    "jsdom-global": "^3.0.2"
  }
}

When I run npx babel-node test.js, I encountered this error

/Users/antkong/test/node_modules/jsdom/lib/api.js:10
const { URL } = require("whatwg-url");
      ^

SyntaxError: Unexpected token {
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Module._extensions..js (module.js:416:10)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/antkong/test/node_modules/babel-register/lib/node.js:152:7)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at globalJsdom (/Users/antkong/test/node_modules/jsdom-global/index.js:28:15)
    at Object.<anonymous> (/Users/antkong/test/node_modules/jsdom-global/register.js:1:19)

And it is my .babelrc file

{
 "presets": ["env", "stage-0"]
}

It seems to me babel-node cannot handle es6 syntax in the dependent js file. I expect babel-node to be able to load and compile all dependency on the fly. How can I fix this problem?

Version info:

$ node --version
v4.8.6
$ npm --version
2.15.11


答:
You have a semi-colon after num++ on the first line.
Should be for(;num <= num2; num++)


答:
Using iris and baseR:

```<code>#example data
iris2 <- iris[1:100, ]
#replicate rows at random
iris2[rep(1:100, times = sample(50:100, 100, replace = TRUE)), ]
</code>```

Each row of iris2 will be replicated between 50-100 times at random

Title: Make multiple random number of copies of rows in a dataframe

Body:
I have a dataframe in r with 100 rows of unique first and last name and address.  I also have columns for weather 1 and weather 2.  I want to make a random number of copies between 50 and 100 for each row.   How would I do that?

df$fname df$lname  df$street df$town df%state df$weather1  df$weather2

Body:
Using iris and baseR:

#example data
iris2 <- iris[1:100, ]
#replicate rows at random
iris2[rep(1:100, times = sample(50:100, 100, replace = TRUE)), ]

Each row of iris2 will be replicated between 50-100 times at random


问:
Python account system
I'm trying to practice because I'm doing Not Examined Assessment in school and I'm stuck with my code, it doesn't work as intended because it doesn't matter whatever I write in accnick it says that the username is correct :/ </p>

```<code> acc = input("Do you have an existing account? y/n ")
if acc == "y":
    accnick= input("Enter your username. ")
    while accnick in open("file.txt").read():
        print("Correct username.")
        accpass= input("Enter your password. ")
        if len(accpass) == 0:
            accpass = input("Try again. ")
        while accpass in open("file.txt").read():
            print("Correct password. ")
            break

    else:
        accnick = input("Wrong username, try again. ")

elif acc == "n":
    name = input("Enter your name. ")
    while len(name) == 0:
        name = input("You haven't entered anything, try again. ")
    age = int(input("Enter your age. "))
    age = str(age)
    while len(age) == 0:
        age = input("Enter your age again. ")
    password = input("Enter your password. ")
    nick = name[:3]
    nickname = nick+str(age)
    file=open("file.txt","w+") #w+ is to write to a file and create a file if it doesnt exist yet
    file.write(name+' '+str(age)+' '+nickname+' '+' '+password)
    file=open("file.txt","r")
    kurwa=file.read()
    print(kurwa)
    name = input("Enter your name. ") ###
    if 'Test Test' in open('file.txt').read():
        print("Someone with that name already exists. ")
</code>```

答:
In your code it will jumpback to print("Correct username.") after a correct username was typed in. So you are stuck in a endless loop. Your break should be part of the while loop. Further I changed the second while to if.

Try this:

```<code>acc = input("Do you have an existing account? y/n")
if acc == "y":
    accnick= input("Enter your username. ")
    while accnick in open("file.txt").read():
        print("Correct username.")
        accpass= input("Enter your password. ")
        if len(accpass) == 0:
            accpass = input("Try again. ")
        if accpass in open("file.txt").read():
            print("Correct password. ")
        break
</code>```

Title: Python account system

Body:
I'm trying to practice because I'm doing Not Examined Assessment in school and I'm stuck with my code, it doesn't work as intended because it doesn't matter whatever I write in accnick it says that the username is correct :/

 acc = input("Do you have an existing account? y/n ")
if acc == "y":
    accnick= input("Enter your username. ")
    while accnick in open("file.txt").read():
        print("Correct username.")
        accpass= input("Enter your password. ")
        if len(accpass) == 0:
            accpass = input("Try again. ")
        while accpass in open("file.txt").read():
            print("Correct password. ")
            break

    else:
        accnick = input("Wrong username, try again. ")

elif acc == "n":
    name = input("Enter your name. ")
    while len(name) == 0:
        name = input("You haven't entered anything, try again. ")
    age = int(input("Enter your age. "))
    age = str(age)
    while len(age) == 0:
        age = input("Enter your age again. ")
    password = input("Enter your password. ")
    nick = name[:3]
    nickname = nick+str(age)
    file=open("file.txt","w+") #w+ is to write to a file and create a file if it doesnt exist yet
    file.write(name+' '+str(age)+' '+nickname+' '+' '+password)
    file=open("file.txt","r")
    kurwa=file.read()
    print(kurwa)
    name = input("Enter your name. ") ###
    if 'Test Test' in open('file.txt').read():
        print("Someone with that name already exists. ")

Body:
In your code it will jumpback to print("Correct username.") after a correct username was typed in. So you are stuck in a endless loop. Your break should be part of the while loop. Further I changed the second while to if.

Try this:

acc = input("Do you have an existing account? y/n")
if acc == "y":
    accnick= input("Enter your username. ")
    while accnick in open("file.txt").read():
        print("Correct username.")
        accpass= input("Enter your password. ")
        if len(accpass) == 0:
            accpass = input("Try again. ")
        if accpass in open("file.txt").read():
            print("Correct password. ")
        break


问:
Dereference works with ptr->operator*() but not with *ptr
I'm creating an iterator for a list class.  The iterator has a dereference operator:

```<code>    T& operator*() const {
        return this->currentNode->data;
    }
</code>```

While trying to use the iterator:

```<code>for( ; list->begin() != list->end; (*list_iter).operator++())
{
    cout << list_iter << endl;
    cout << list_iter->operator*() << endl;
    //cout << *list_iter << endl;  //not working
}
</code>```

The commented line says "invalid operand to binary experssion ostream and MyList::iterator".  Likewise, if I change from (*list_iter).operator++() to list_iter++ or (*list_iter)++, I get a similar error.

What I think is happening is something like this:

```<code>int num1 = 3;
int *num2 = new int;
*num2 = 3;
</code>```

In this case, num1 is == *num2...  *num2 is functionally similar to num1 (both are integers), though num2 is a pointer to an integer, the *num2 makes it an integer.

So in:

```<code>MyList list1();
MyList *list2 = new MyList();
</code>```

In this case, should I expect "*list2" to be similar to list1 in the same way that "*num2" is similar to num1?  Is num2 going to call a dereferencer, or try to turn a MyList into a MyList?

Really struggling with what's going on under the hood here.  Thanks!

答:
Your loop is completely wrong.

The begin() iterator is not being saved to list_iter, it is being compared directly to the end() iterator.  So the loop will run forever if the list is not empty.

(*list_iter).operator++() dereferences the iterator to access its data, then calls operator++ on that data, not on the iterator itself.

cout << list_iter is not defined for iterators.  You need to dereference the iterator so you can output the data being referenced: cout << *list_iter.

cout << list_iter->operator*() dereferences the iterator to access its data, then calls operator* on that data, not on the iterator itself.

Your loop should look more like this instead:

```<code>for(list_iter = list->begin(); list_iter != list->end(); ++list_iter)
{
    cout << *list_iter << endl;
}
</code>```

Or, in C++11, you can use a range-for loop instead and let it handle the iterator for you:

```<code>for(auto &data : *list)
{
    cout << data << endl;
}
</code>```

Body:
I'm creating an iterator for a list class.  The iterator has a dereference operator:

    T& operator*() const {
        return this->currentNode->data;
    }

While trying to use the iterator:

for( ; list->begin() != list->end; (*list_iter).operator++())
{
    cout << list_iter << endl;
    cout << list_iter->operator*() << endl;
    //cout << *list_iter << endl;  //not working
}

The commented line says "invalid operand to binary experssion ostream and MyList::iterator".  Likewise, if I change from (*list_iter).operator++() to list_iter++ or (*list_iter)++, I get a similar error.

What I think is happening is something like this:

int num1 = 3;
int *num2 = new int;
*num2 = 3;

In this case, num1 is == *num2...  *num2 is functionally similar to num1 (both are integers), though num2 is a pointer to an integer, the *num2 makes it an integer.

So in:

MyList list1();
MyList *list2 = new MyList();

In this case, should I expect "*list2" to be similar to list1 in the same way that "*num2" is similar to num1?  Is num2 going to call a dereferencer, or try to turn a MyList into a MyList?

Really struggling with what's going on under the hood here.  Thanks!

Body:
Your loop is completely wrong.

The begin() iterator is not being saved to list_iter, it is being compared directly to the end() iterator.  So the loop will run forever if the list is not empty.

(*list_iter).operator++() dereferences the iterator to access its data, then calls operator++ on that data, not on the iterator itself.

cout << list_iter is not defined for iterators.  You need to dereference the iterator so you can output the data being referenced: cout << *list_iter.

cout << list_iter->operator*() dereferences the iterator to access its data, then calls operator* on that data, not on the iterator itself.

Your loop should look more like this instead:

for(list_iter = list->begin(); list_iter != list->end(); ++list_iter)
{
    cout << *list_iter << endl;
}

Or, in C++11, you can use a range-for loop instead and let it handle the iterator for you:

for(auto &data : *list)
{
    cout << data << endl;
}


问:
Dataframe and read_csv function - Python
I'm using the pandas library to make a simple program.

First of all I have a .csv file called small.csv, which contains the following structure.

```<code>1,4.0,?,?,none,?
2,2.0,3.0,?,none,38
2,2.5,2.5,?,tc,39
</code>```

On my main function I have the following code:

```<code>def main():
    # my code here
    fname = "/home/sergio/PycharmProjects/practica2/small.csv"
    sep = ","
    vars = ["x1", "x2", "x3", "x4", "x5", "x6"]
    na_values = ["?", "none"]
    prefix = "col_"

    df = da.load_data(fname, delimiter=sep, nan=na_values,
                      header=False, pref=prefix)
    print df
</code>```

The explanation of the main function is the following, depending on the parameters that I pass to the load_data function, you will have to load the data from my .csv file in one way or another.

These are the possible arguments and the function that they develop:

inputFile: The name of the csv file that contains the data.

delimiter: The character that delimits the data. By default the function must use the comma character (",").

nan: A list of Strings that will be treated as missing values. Any occurrence in the input file of one of the strings in this list will be interpreted as  NaN . The default value will be None.

header:  A Boolean flag that will indicate if the file contains a header ( True ) or if not ( False ). By default it must be  True .

varNames: A list of * Strings * that will be used as variable names only in the case where header  is valid  False . The default value will be None .

pref: A string that will be used as a prefix for the names of the variables only in the case where header  is valid  False and the list has not been defined * varNames . For example, if pref = "x", the names of the variables will be "x0", "x1", "x2", etc. The default value will be "var_".

My load_data function:

```<code>def load_data(inputFile, delimiter=",", nan=None, header=True,
              varNames=None, pref="var_"):

    data = DataFrame()

    if header == False:
        if not varNames:
            print "header=false and varNames not defined"
            data = pd.read_csv(inputFile, sep=delimiter, na_values=nan,  prefix=pref, header=None)
            listaNum = list(range(len(data.columns)))
            data.columns = listaNum
        else: # varNames defined
            data = pd.read_csv(inputFile, sep=delimiter, na_values=nan,  prefix=pref)
    else:
        return data
</code>```

This function is responsible for displaying the data based on the parameters we have entered, varying the output depending on the case

One of the cases that I have to evaluate is the following.

if header = False and the variable varsNames, which indicates the name of the column is not passed to that function (Null), I have to assign a numerical value from 0 to the number of columns that have, that is, 0 1 2 ... up to max columns.

Also in this case I would have to add the prefix that we passed to that number that defines the column, in this case it would be "col_".

The result woulb be the following one:

```<code>  col_0 col_1   col_2   col_3   col_4   col_5
0   1   4.0      NaN    NaN      NaN    NaN
1   2   2.0      3.0    NaN      NaN    38.0
2   2   2.5      2.5    NaN       tc    39.0
</code>```

Here is my problem, in the case I have commented that we have to add a prefix to each of the numeric columns, with the variable prefix, I could do it by hand, that is, to each of the elements of my column list, add the string "col_".

However I think it is wrong, since I do not use the "prefix" option that can be passed through the read_csv function, I have tried it nevertheless and it does not do it correctly.

This is my result, and as you can see although I pass the prefix argument to read_csv function, it ignores it.

```<code>   0    1    2   3    4     5
0  1  4.0  NaN NaN  NaN   NaN
1  2  2.0  3.0 NaN  NaN  38.0
2  2  2.5  2.5 NaN   tc  39.0
</code>```

In addition another one of the doubts, is that since I am calculating the numerical value that I have to assign to the columns, I do it modifying the dataframe that already has been generated and I believe that it is not the most optimal form to realize it.

答:
This works well for me on v0.21.

```<code>import io

text = \
'''1,4.0,?,?,none,?
2,2.0,3.0,?,none,38
2,2.5,2.5,?,tc,39'''

buf = io.StringIO(text)

df = pd.read_csv(buf, na_values=['?', 'none'], header=None, prefix='col_')
df

col_0  col_1  col_2  col_3 col_4  col_5
0      1    4.0    NaN    NaN   NaN    NaN
1      2    2.0    3.0    NaN   NaN   38.0
2      2    2.5    2.5    NaN    tc   39.0
</code>```

Another trick (if this still doesn't work) would be to use add_prefix:

```<code>df

   0    1    2   3    4     5
0  1  4.0  NaN NaN  NaN   NaN
1  2  2.0  3.0 NaN  NaN  38.0
2  2  2.5  2.5 NaN   tc  39.0

df = df.add_prefix('col_')
df

   col_0  col_1  col_2  col_3 col_4  col_5
0      1    4.0    NaN    NaN   NaN    NaN
1      2    2.0    3.0    NaN   NaN   38.0
2      2    2.5    2.5    NaN    tc   39.0
</code>```

Body:
I'm using the pandas library to make a simple program.

First of all I have a .csv file called small.csv, which contains the following structure.

1,4.0,?,?,none,?
2,2.0,3.0,?,none,38
2,2.5,2.5,?,tc,39

On my main function I have the following code:

def main():
    # my code here
    fname = "/home/sergio/PycharmProjects/practica2/small.csv"
    sep = ","
    vars = ["x1", "x2", "x3", "x4", "x5", "x6"]
    na_values = ["?", "none"]
    prefix = "col_"

    df = da.load_data(fname, delimiter=sep, nan=na_values,
                      header=False, pref=prefix)
    print df

The explanation of the main function is the following, depending on the parameters that I pass to the load_data function, you will have to load the data from my .csv file in one way or another.

These are the possible arguments and the function that they develop:

inputFile: The name of the csv file that contains the data.

delimiter: The character that delimits the data. By default the function must use the comma character (",").

nan: A list of Strings that will be treated as missing values. Any occurrence in the input file of one of the strings in this list will be interpreted as  NaN . The default value will be None.

header:  A Boolean flag that will indicate if the file contains a header ( True ) or if not ( False ). By default it must be  True .

varNames: A list of * Strings * that will be used as variable names only in the case where header  is valid  False . The default value will be None .

pref: A string that will be used as a prefix for the names of the variables only in the case where header  is valid  False and the list has not been defined * varNames . For example, if pref = "x", the names of the variables will be "x0", "x1", "x2", etc. The default value will be "var_".

My load_data function:

def load_data(inputFile, delimiter=",", nan=None, header=True,
              varNames=None, pref="var_"):

    data = DataFrame()

    if header == False:
        if not varNames:
            print "header=false and varNames not defined"
            data = pd.read_csv(inputFile, sep=delimiter, na_values=nan,  prefix=pref, header=None)
            listaNum = list(range(len(data.columns)))
            data.columns = listaNum
        else: # varNames defined
            data = pd.read_csv(inputFile, sep=delimiter, na_values=nan,  prefix=pref)
    else:
        return data

This function is responsible for displaying the data based on the parameters we have entered, varying the output depending on the case

One of the cases that I have to evaluate is the following.

if header = False and the variable varsNames, which indicates the name of the column is not passed to that function (Null), I have to assign a numerical value from 0 to the number of columns that have, that is, 0 1 2 ... up to max columns.

Also in this case I would have to add the prefix that we passed to that number that defines the column, in this case it would be "col_".

The result woulb be the following one:

  col_0 col_1   col_2   col_3   col_4   col_5
0   1   4.0      NaN    NaN      NaN    NaN
1   2   2.0      3.0    NaN      NaN    38.0
2   2   2.5      2.5    NaN       tc    39.0

Here is my problem, in the case I have commented that we have to add a prefix to each of the numeric columns, with the variable prefix, I could do it by hand, that is, to each of the elements of my column list, add the string "col_".

However I think it is wrong, since I do not use the "prefix" option that can be passed through the read_csv function, I have tried it nevertheless and it does not do it correctly.

This is my result, and as you can see although I pass the prefix argument to read_csv function, it ignores it.

   0    1    2   3    4     5
0  1  4.0  NaN NaN  NaN   NaN
1  2  2.0  3.0 NaN  NaN  38.0
2  2  2.5  2.5 NaN   tc  39.0

In addition another one of the doubts, is that since I am calculating the numerical value that I have to assign to the columns, I do it modifying the dataframe that already has been generated and I believe that it is not the most optimal form to realize it.

Body:
This works well for me on v0.21.

import io

text = \
'''1,4.0,?,?,none,?
2,2.0,3.0,?,none,38
2,2.5,2.5,?,tc,39'''

buf = io.StringIO(text)

df = pd.read_csv(buf, na_values=['?', 'none'], header=None, prefix='col_')
df

col_0  col_1  col_2  col_3 col_4  col_5
0      1    4.0    NaN    NaN   NaN    NaN
1      2    2.0    3.0    NaN   NaN   38.0
2      2    2.5    2.5    NaN    tc   39.0

Another trick (if this still doesn't work) would be to use add_prefix:

df

   0    1    2   3    4     5
0  1  4.0  NaN NaN  NaN   NaN
1  2  2.0  3.0 NaN  NaN  38.0
2  2  2.5  2.5 NaN   tc  39.0

df = df.add_prefix('col_')
df

   col_0  col_1  col_2  col_3 col_4  col_5
0      1    4.0    NaN    NaN   NaN    NaN
1      2    2.0    3.0    NaN   NaN   38.0
2      2    2.5    2.5    NaN    tc   39.0


问:
Crawl data on the app store
Does anyone know how AppShopper.com crawl the data on the Apple's app store?
Do we have to simulate a browser using automated testing like Watir? Is this the only way to collect the data (e.g., download statistics, price)?</p>

答: If you right click on any link or icon in iTunes, it will give you the URL it uses to download the data it displays for that next iTunes page.  The format of the HTML data changes in undocumented ways periodically.  If you use wget or curl to download data from these URLs, you may also have to imitate the iTunes user agent and national store front name, which you can get by monitoring the iTunes traffic with something like wire shark.</p>

Title: Crawl data on the app store


问:
Save fileds changes with ajax in laravel
I want to change some parts of my data from index page without loading edit page with Ajax.
For example my reviews has status where value is 0 or 1 and also comment section. I want to change these values from my index page.

All the code i have is simply my index method only, where i load my list

```<code>public function index()
    {
      $ratings = Rating::orderby('id', 'desc')->paginate(10);
      return view('admin.ratings.index', compact('ratings'));
    }
</code>```

I need help to make my index page as a form with Ajax in order to edit from there but not to use my Update method because I'll need it for my edit.blade.php (maybe add another method in my controller?)

Thanks.

答:
First of all you need a controller that updates the post status. As discussed it totally up to you want you want to do.

My suggestion is to create a new controller called UpdatePostStatusController and then have update method that takes post id and the status either 1 or 0 and update it.

Your index file should have javascript that gets triggred everytime you change the status like so

checkbox html

```<code><input type="checkbox" data-uuid="{{ $post->id }}" class="update" @if($post->status) checked @endif/>
</code>```

Now your ajax should

```<code> $('.update').change(function() {

  data = {'status' : this.checked }
  post_id =  $(this).data('uuid');

//do your ajax post request here here
}
</code>```

Body:
I want to change some parts of my data from index page without loading edit page with Ajax.
For example my reviews has status where value is 0 or 1 and also comment section. I want to change these values from my index page.

All the code i have is simply my index method only, where i load my list

public function index()
    {
      $ratings = Rating::orderby('id', 'desc')->paginate(10);
      return view('admin.ratings.index', compact('ratings'));
    }

I need help to make my index page as a form with Ajax in order to edit from there but not to use my Update method because I'll need it for my edit.blade.php (maybe add another method in my controller?)

Thanks.

Body:
First of all you need a controller that updates the post status. As discussed it totally up to you want you want to do.

My suggestion is to create a new controller called UpdatePostStatusController and then have update method that takes post id and the status either 1 or 0 and update it.

Your index file should have javascript that gets triggred everytime you change the status like so

checkbox html

<input type="checkbox" data-uuid="{{ $post->id }}" class="update" @if($post->status) checked @endif/>

Now your ajax should

 $('.update').change(function() {

  data = {'status' : this.checked }
  post_id =  $(this).data('uuid');

//do your ajax post request here here
}


问:
SQL Server - import XML fields from multiple levels
I'm wanting to select the XML hierarchy value for Chart Name into the first column for all Filter values under that Chart.

I've used the method below but ChartName returns a NULL.  I suspect I will need to do a subquery

```<code>DECLARE @input XML =
'<Report>
    <DataSets>
    </DataSets>
    <ReportSections>
      <ReportSection>
        <ReportItems>
          <Chart Name="Hub1">
            <Filters>
                <Filter>
                  <Expression>Fields!Hub.Value</Expression>
                  <Operator>Like</Operator>
                  <Values>
                    <Value>Central</Value>
                  </Values>
                </Filter>
                <Filter>
                    <Expression>Fields!ADP_Hrs.Value</Expression>
                    <Operator>NotEqual</Operator>
                    <Values>
                      <Value DataType="Float">0</Value>
                    </Values>
                </Filter>
                <Filter>
                    <Expression>Fields!TL.Value</Expression>
                    <Operator>Equal</Operator>
                    <Values>
                      <Value DataType="Integer">1</Value>
                    </Values>
                </Filter>
            </Filters>
          </Chart>
        </ReportItems>
      </ReportSection>
    </ReportSections>
</Report>'

SELECT
    [Tbl].[Col].value('Chart [4]', 'varchar(50)') as ChartName,
    [Tbl].[Col].value('Expression [1]', 'varchar(50)') as Expression,
    [Tbl].[Col].value(' Operator [1]', 'varchar(50)') as 'Operator',
    [Tbl].[Col].value(' Values [1]', 'varchar(50)') as 'Value'
FROM
    @input.nodes('Report/ReportSections/ReportSection/ReportItems/Chart/Filters/Filter') as [Tbl]([Col])
</code>```

Expected output:

```<code>ChartName  Expression              Operator    Value
------------------------------------------------------
Hub1       Fields!Hub.Value        Like        Central
Hub1       Fields!ADP_Hrs.Value    NotEqual    0
Hub1       Fields!TL.Value         Equal       1
</code>```

答:
Yet another option

Example

```<code>Select ChartName    = lvl1.n.value('@Name'        ,'varchar(50)')
      ,Expression   = lvl2.n.value('Expression[1]','varchar(50)')
      ,Operator     = lvl2.n.value('Operator[1]'  ,'varchar(50)')
      ,Value        = lvl2.n.value('Values[1]'    ,'varchar(50)')
 From  @input.nodes('Report/ReportSections/ReportSection/ReportItems/*') lvl1(n)
 Cross Apply lvl1.n.nodes('Filters/Filter') lvl2(n)
</code>```

Returns

```<code>ChartName   Expression              Operator    Value
Hub1        Fields!Hub.Value        Like        Central
Hub1        Fields!ADP_Hrs.Value    NotEqual    0
Hub1        Fields!TL.Value         Equal       1
</code>```

Body:
I'm wanting to select the XML hierarchy value for Chart Name into the first column for all Filter values under that Chart.

I've used the method below but ChartName returns a NULL.  I suspect I will need to do a subquery

DECLARE @input XML =
'<Report>
    <DataSets>
    </DataSets>
    <ReportSections>
      <ReportSection>
        <ReportItems>
          <Chart Name="Hub1">
            <Filters>
                <Filter>
                  <Expression>Fields!Hub.Value</Expression>
                  <Operator>Like</Operator>
                  <Values>
                    <Value>Central</Value>
                  </Values>
                </Filter>
                <Filter>
                    <Expression>Fields!ADP_Hrs.Value</Expression>
                    <Operator>NotEqual</Operator>
                    <Values>
                      <Value DataType="Float">0</Value>
                    </Values>
                </Filter>
                <Filter>
                    <Expression>Fields!TL.Value</Expression>
                    <Operator>Equal</Operator>
                    <Values>
                      <Value DataType="Integer">1</Value>
                    </Values>
                </Filter>
            </Filters>
          </Chart>
        </ReportItems>
      </ReportSection>
    </ReportSections>
</Report>'

SELECT
    [Tbl].[Col].value('Chart [4]', 'varchar(50)') as ChartName,
    [Tbl].[Col].value('Expression [1]', 'varchar(50)') as Expression,
    [Tbl].[Col].value(' Operator [1]', 'varchar(50)') as 'Operator',
    [Tbl].[Col].value(' Values [1]', 'varchar(50)') as 'Value'
FROM
    @input.nodes('Report/ReportSections/ReportSection/ReportItems/Chart/Filters/Filter') as [Tbl]([Col])

Expected output:

ChartName  Expression              Operator    Value
------------------------------------------------------
Hub1       Fields!Hub.Value        Like        Central
Hub1       Fields!ADP_Hrs.Value    NotEqual    0
Hub1       Fields!TL.Value         Equal       1

Body:
Yet another option

Example

Select ChartName    = lvl1.n.value('@Name'        ,'varchar(50)')
      ,Expression   = lvl2.n.value('Expression[1]','varchar(50)')
      ,Operator     = lvl2.n.value('Operator[1]'  ,'varchar(50)')
      ,Value        = lvl2.n.value('Values[1]'    ,'varchar(50)')
 From  @input.nodes('Report/ReportSections/ReportSection/ReportItems/*') lvl1(n)
 Cross Apply lvl1.n.nodes('Filters/Filter') lvl2(n)

Returns

ChartName   Expression              Operator    Value
Hub1        Fields!Hub.Value        Like        Central
Hub1        Fields!ADP_Hrs.Value    NotEqual    0
Hub1        Fields!TL.Value         Equal       1


问:
Connecting Biopac MP36 to Simi Motion
I need to synchronize the biopac MP36 with the Simi Motion so that when we start / stop the recording of a device the other one does the same.

I know that there are an input trigger and an analogic output on the biopac and I thought that the signal for the Simi could be a light but I don't know how to create the global circuit of synchronization. And I thought that may be I need to use Matlab or LabVIEW to do this..

Can someone help me?

答:
According to the MP36 manual:

A trigger device may be connected to the “Trigger” port on the back
  panel.

There's more information on pages 3-4 on how to connect several MP36 together.

According to Simi Motion's site, for digital equipment:

The majority of equipment can however be synchronised with a hardware
  trigger, and the data can then be imported into Simi Motion.

However, if you are using a camera, maybe you will have to use a light to have a visual indication and then align your data with that marker (similar to the use of a clapperboard to sink image and audio on films) - check your product manual.

As the MP36 allows for a 5V analogue trigger, you should be able to use that line to feed a small light bulb, so when you press the trigger for the MP36 you get a visual indicator on the video.

The use of software (Labview or Matlab) is sometimes limited to the communication speed with each device and how well it can actually communicate with both at the "same time".

In my experience using labview to trigger several devices I normally prefer to use it to configure every device to expect a trigger and then use a single analogue signal to trigger them all externally (or a common *TRG signal through a GPIB net, for instance).

Title: Connecting Biopac MP36 to Simi Motion


问:
How can I lookup a Java enum from its String value?
I would like to lookup an enum from its string value (or possibly any other value). I've tried the following code but it doesn't allow static in initialisers. Is there a simple way?</p>

```<code>public enum Verbosity {

    BRIEF, NORMAL, FULL;

    private static Map<String, Verbosity> stringMap = new HashMap<String, Verbosity>();

    private Verbosity() {
        stringMap.put(this.toString(), this);
    }

    public static Verbosity getVerbosity(String key) {
        return stringMap.get(key);
    }
};
</code>```

答:
In case it helps others, the option I prefer, which is not listed here, uses Guava's Maps functionality:

```<code>public enum Vebosity {
    BRIEF("BRIEF"),
    NORMAL("NORMAL"),
    FULL("FULL");

    private String value;
    private Verbosity(final String value) {
        this.value = value;
    }

    public String getValue() {
        return this.value;
    }

    private static ImmutableMap<String, Verbosity> reverseLookup =
            Maps.uniqueIndex(Arrays.asList(Verbosity.values()), Verbosity::getValue);

    public static Verbosity fromString(final String id) {
        return reverseLookup.getOrDefault(id, NORMAL);
    }
}
</code>```

With the default you can use null, you can throw IllegalArgumentException or your fromString could return an Optional, whatever behavior you prefer.

Body:
I would like to lookup an enum from its string value (or possibly any other value). I've tried the following code but it doesn't allow static in initialisers. Is there a simple way?

public enum Verbosity {

    BRIEF, NORMAL, FULL;

    private static Map<String, Verbosity> stringMap = new HashMap<String, Verbosity>();

    private Verbosity() {
        stringMap.put(this.toString(), this);
    }

    public static Verbosity getVerbosity(String key) {
        return stringMap.get(key);
    }
};

Body:
In case it helps others, the option I prefer, which is not listed here, uses Guava's Maps functionality:

public enum Vebosity {
    BRIEF("BRIEF"),
    NORMAL("NORMAL"),
    FULL("FULL");

    private String value;
    private Verbosity(final String value) {
        this.value = value;
    }

    public String getValue() {
        return this.value;
    }

    private static ImmutableMap<String, Verbosity> reverseLookup =
            Maps.uniqueIndex(Arrays.asList(Verbosity.values()), Verbosity::getValue);

    public static Verbosity fromString(final String id) {
        return reverseLookup.getOrDefault(id, NORMAL);
    }
}

With the default you can use null, you can throw IllegalArgumentException or your fromString could return an Optional, whatever behavior you prefer.