问:
MatTableDataSource Cannot read property 'data' of undefined in Angular 7
I am trying to implement MatTableDataSource in Angular 7, I am following Angular Material guideline, but it seems it doesn't work and I am getting `

Cannot read property 'data' of undefined

`. When printing in console, the data is bound and the results are shown, but it is not bound to my table.

HTML

```<code><div class="mat-elevation-z8 full-width-table" *ngIf="brList">
<table class="full-width-table" mat-table [dataSource]="brList" matSort aria-label="Elements">
  <!-- Id Column -->
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>Id</th>
    <td mat-cell *matCellDef="let row">{{row.id}}</td>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
    <td mat-cell *matCellDef="let row">{{row.name}}</td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

<mat-paginator #paginator
    [length]="dataSource.data.length"
    [pageIndex]="0"
    [pageSize]="10"
    [pageSizeOptions]="[10, 15, 20, 25]">
</mat-paginator>
</div>
</code>```

Model

```<code>export interface Br {
    id: number;
    name: string;
}
</code>```

Component

```<code>export class ListBComponent implements OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  brList: MatTableDataSource<Br> = new MatTableDataSource<Br>();
  displayedColumns = ['id', 'name'];
  constructor(private mm: BrService){

  }
  ngOnInit() {
    this.mm.getMM().subscribe(
      result =>
      {
         this.brList.data = result;
         this.brList.paginator = this.paginator;
         this.brList.sort = this.sort;
         console.log(this.brList); //prints the data correctly
      })
  }
</code>```

答:
The error is here:

```<code><mat-paginator #paginator
    [length]="dataSource.data.length"
    [pageIndex]="0"
    [pageSize]="10"
    [pageSizeOptions]="[10, 15, 20, 25]">
</mat-paginator>
</code>```

I think instead of dataSource.data.length you mean brList.data.length.

Body:
I am trying to implement MatTableDataSource in Angular 7, I am following Angular Material guideline, but it seems it doesn't work and I am getting `

Cannot read property 'data' of undefined

`. When printing in console, the data is bound and the results are shown, but it is not bound to my table.

HTML

  <ng-container matColumnDef="id">
    Id
    {{row.id}}
  </ng-container>

  <ng-container matColumnDef="name">
    Name
    {{row.name}}
  </ng-container>

<mat-paginator #paginator
    [length]="dataSource.data.length"
    [pageIndex]="0"
    [pageSize]="10"
    [pageSizeOptions]="[10, 15, 20, 25]">
</mat-paginator>

Model

export interface Br {
    id: number;
    name: string;
}

Component

export class ListBComponent implements OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  brList: MatTableDataSource
 = new MatTableDataSource
();
  displayedColumns = ['id', 'name'];
  constructor(private mm: BrService){

  }
  ngOnInit() {
    this.mm.getMM().subscribe(
      result =>
      {
         this.brList.data = result;
         this.brList.paginator = this.paginator;
         this.brList.sort = this.sort;
         console.log(this.brList); //prints the data correctly
      })
  }

Body:
The error is here:

<mat-paginator #paginator
    [length]="dataSource.data.length"
    [pageIndex]="0"
    [pageSize]="10"
    [pageSizeOptions]="[10, 15, 20, 25]">
</mat-paginator>

I think instead of dataSource.data.length you mean brList.data.length.


来源: stackexchange

问:
CORS issue posting domain A to domain B
I am getting a CORS issue only on axios.

In this html page, I am using a traditional form to post from domain A to domain B.

The form submit works correctly.
The ajax post request works correctly.
The axios post returns me to a CORS .

Access to XMLHttpRequest at 'https://domainB/post.php' from origin 'http://domain A.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

```<code><html>
<head>
    <title>Registration Form</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://npmcdn.com/axios/dist/axios.min.js"></script>
<body>

    <h2>Registration Form</h2>

    <form action="https://domainB.com/post.php" method="POST">

        Last name:

        <input type="text" name="username">

        <input type="hidden" name="form_submitted" value="1" />

        <input type="submit" value="Submit">

    </form>

    <script>
        $(document).ready(function(){
    $.post("https://domainB.com/post.php",
    {
      username: "Donald Duck",
      city: "Duckburg"
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
});
    </script>
    <script>

(function() {

axios.post('https://domainB.com/post.php', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

})();

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

my post.php

```<code><?php
echo 'post working';
var_dump( $_POST);
 $_POST['username'];
?>
</code>```

答: There was a configuration with the server. I did not do anything on my side and insisted with hosting company. They were able to fix it.</p>

ContentLicense: CC BY-SA 4.0

Title: CORS issue posting domain A to domain B

Body:
I am getting a CORS issue only on axios.

In this html page, I am using a traditional form to post from domain A to domain B.

The form submit works correctly.
The ajax post request works correctly.
The axios post returns me to a CORS .

Access to XMLHttpRequest at 'https://domainB/post.php' from origin 'http://domain A.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

    <title>Registration Form</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Registration Form

    <form action="https://domainB.com/post.php" method="POST">

        Last name:

        <input type="text" name="username">

        <input type="hidden" name="form_submitted" value="1" />

        <input type="submit" value="Submit">

    </form>

my post.php

<?php
echo 'post working';
var_dump( $_POST);
 $_POST['username'];
?>


问:
How to execute Metrics2 plugin from command line?
Is it possible to run Metrics Plugin from Command Line.

I am not interested in Ant Task. What I am looking for is to run this from a shell script passing the file name as a parameter and to get the output metrics on stdout

Is it possible to do so.

答: I don't believe you can.  Metrics2 is designed to work in an Eclipse environment, and is highly dependent on Eclipse functionality.  All output goes to a table in Eclipse.  Metrics2 is open source, so you may be able to contribute something useful there.</p>

ContentLicense: CC BY-SA 3.0


问:
Does the min value of the xAxes have to be within the dataset
I'm trying to add the ability to change a 'date' range for my chart, and I've added a button callback that changes the min value of the xAxes and then calls chart.update(), but the chart doesn't change.

I've tried manually entering a number, and unless it's a value in the data given for the table it won't update the graph.

```<code>this.analysisChart = new Chart(context, {
            // The type of chart we want to create
            type: 'line',

            // The data for our dataset
            data: {
                labels: calculations.rollingTimestamps,
                datasets: [
                {
                    label: 'Cycle Times',
                    data: calculations.rollingCycleTimesXY,
                    borderColor: 'rgb(0,255,0,1)',
                    backgroundColor: 'rgb(0,255,0,0.5)',
                    type: 'scatter',
                    showLine: false,
                    labels: calculations.rollingAliases
                },
                {
                    label: 'Rolling μ',
                    borderColor: 'rgb(255, 99, 132, 1)',
                    backgroundColor: 'rgb(255, 99, 132, 0.5)',
                    data: calculations.rollingAverage,
                    fill: false,
                    pointRadius: 0
                },
                {
                    label: 'Overall μ',
                    data: calculations.overallAverageArr,
                    fill: false,
                    borderColor: 'rgb(0,0,0,1)',
                    backgroundColor: 'rgb(0,0,0,0.5)',
                    pointRadius: 0,
                    showLine: true
                },
                {
                    label: 'μ + σ',
                    data: calculations.rollingMaxStandardDeviation,
                    fill: 4,
                    backgroundColor: 'rgb(50,50,255,0.35)',
                    borderColor: 'rgb(50,50,255,0)',
                    pointRadius: 0,
                    showLine: true
                },
                {
                    label: 'μ - σ',
                    data: calculations.rollingMinStandardDeviation,
                    fill: 3,
                    backgroundColor: 'rgb(50,50,255,0.35)',
                    borderColor: 'rgb(50,50,255,0)',
                    pointRadius: 0,
                    showLine: true
                },
                {
                    label: 'μ + 2 * σ',
                    data: calculations.rollingMaxSecondStandardDeviation,
                    fill: 3,
                    backgroundColor: 'rgb(50,50,255,0.3)',
                    borderColor: 'rgb(50,50,255,0)',
                    pointRadius: 0,
                    showLine: true
                },
                {
                    label: 'μ - 2 * σ',
                    data: calculations.rollingMinSecondStandardDeviation,
                    fill: 4,
                    backgroundColor: 'rgb(50,50,255,0.3)',
                    borderColor: 'rgb(50,50,255,0)',
                    pointRadius: 0,
                    showLine: true
                }
                ]
            },

            // Configuration options go here
            options: {
                layout: {
                    padding: {
                        left: 20,
                        right: 20,
                        top: 0,
                        bottom: 0
                    }
                },
                tooltips: {
                    mode: 'index',
                    intersect: false,
                    callbacks: {
                        label: function(tooltipItem, data) {
                            var label = data.datasets[tooltipItem.datasetIndex].label || '';

                            if (label) {
                                label += ': ';
                            }
                            label += Math.round(tooltipItem.yLabel * 10) / 10;
                            return label + " days";
                        }
                    }
                },
                hover: {
                    mode: 'index',
                    intersect: false
                },
                scales: {
                    yAxes: [{
                        ticks: {
                            min: 0,
                            type: 'linear',
                            callback: function(label, index, labels) {
                                return label + " days";
                            }
                        }
                    }],
                    xAxes: [{
                        ticks: {
                            type: 'linear',
                            min: 0,
                            callback: function(label, index, labels) {
                                return new Date(label).toDateString();
                            }
                        }
                    }]
                },
                title: {
                    display: true,
                    text: 'Cycle Times'
                }
            }
        });
</code>```

What I'd like to do is give an arbitrary number and have it perform a greater than check across the data for determining what to cut off rather than doing a find and then cutting anything off that is after that index in the array.

How can I do this?

答:
As a solution, I just wrote a function to iterate through the array and find the first value that is greater than or equal to the value I wanted and then set the min of the xAxes to that value. Not very ideal, but hey at least it works.

I couldn't find anything in the documentation about callbacks for the min value.

Body:
I'm trying to add the ability to change a 'date' range for my chart, and I've added a button callback that changes the min value of the xAxes and then calls chart.update(), but the chart doesn't change.

I've tried manually entering a number, and unless it's a value in the data given for the table it won't update the graph.

this.analysisChart = new Chart(context, {
            // The type of chart we want to create
            type: 'line',

            // The data for our dataset
            data: {
                labels: calculations.rollingTimestamps,
                datasets: [
                {
                    label: 'Cycle Times',
                    data: calculations.rollingCycleTimesXY,
                    borderColor: 'rgb(0,255,0,1)',
                    backgroundColor: 'rgb(0,255,0,0.5)',
                    type: 'scatter',
                    showLine: false,
                    labels: calculations.rollingAliases
                },
                {
                    label: 'Rolling μ',
                    borderColor: 'rgb(255, 99, 132, 1)',
                    backgroundColor: 'rgb(255, 99, 132, 0.5)',
                    data: calculations.rollingAverage,
                    fill: false,
                    pointRadius: 0
                },
                {
                    label: 'Overall μ',
                    data: calculations.overallAverageArr,
                    fill: false,
                    borderColor: 'rgb(0,0,0,1)',
                    backgroundColor: 'rgb(0,0,0,0.5)',
                    pointRadius: 0,
                    showLine: true
                },
                {
                    label: 'μ + σ',
                    data: calculations.rollingMaxStandardDeviation,
                    fill: 4,
                    backgroundColor: 'rgb(50,50,255,0.35)',
                    borderColor: 'rgb(50,50,255,0)',
                    pointRadius: 0,
                    showLine: true
                },
                {
                    label: 'μ - σ',
                    data: calculations.rollingMinStandardDeviation,
                    fill: 3,
                    backgroundColor: 'rgb(50,50,255,0.35)',
                    borderColor: 'rgb(50,50,255,0)',
                    pointRadius: 0,
                    showLine: true
                },
                {
                    label: 'μ + 2 * σ',
                    data: calculations.rollingMaxSecondStandardDeviation,
                    fill: 3,
                    backgroundColor: 'rgb(50,50,255,0.3)',
                    borderColor: 'rgb(50,50,255,0)',
                    pointRadius: 0,
                    showLine: true
                },
                {
                    label: 'μ - 2 * σ',
                    data: calculations.rollingMinSecondStandardDeviation,
                    fill: 4,
                    backgroundColor: 'rgb(50,50,255,0.3)',
                    borderColor: 'rgb(50,50,255,0)',
                    pointRadius: 0,
                    showLine: true
                }
                ]
            },

            // Configuration options go here
            options: {
                layout: {
                    padding: {
                        left: 20,
                        right: 20,
                        top: 0,
                        bottom: 0
                    }
                },
                tooltips: {
                    mode: 'index',
                    intersect: false,
                    callbacks: {
                        label: function(tooltipItem, data) {
                            var label = data.datasets[tooltipItem.datasetIndex].label || '';

                            if (label) {
                                label += ': ';
                            }
                            label += Math.round(tooltipItem.yLabel * 10) / 10;
                            return label + " days";
                        }
                    }
                },
                hover: {
                    mode: 'index',
                    intersect: false
                },
                scales: {
                    yAxes: [{
                        ticks: {
                            min: 0,
                            type: 'linear',
                            callback: function(label, index, labels) {
                                return label + " days";
                            }
                        }
                    }],
                    xAxes: [{
                        ticks: {
                            type: 'linear',
                            min: 0,
                            callback: function(label, index, labels) {
                                return new Date(label).toDateString();
                            }
                        }
                    }]
                },
                title: {
                    display: true,
                    text: 'Cycle Times'
                }
            }
        });

What I'd like to do is give an arbitrary number and have it perform a greater than check across the data for determining what to cut off rather than doing a find and then cutting anything off that is after that index in the array.

How can I do this?


问:
Vimeo full width
I'm trying to have a vimeo video shown full width in web page.

This is how it looks now:

As you can see the black is full width but not the video. It should be full width, no controls shown, play automatic and play in a loop.

My code looks like this now:

```<code><iframe src="https://player.vimeo.com/video/208176323?autoplay=1&loop=1&background=1" width="100%" height="500px" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</code>```

The client has vimeo plus but not vimeo pro. Can someone help me with this.

UPDATE:

I've changed my code to this:

```<code><style>
    .embed-container {
        position: relative;
        padding-bottom: 56.25%;
        height: 0; overflow: hidden;
        max-width: 100%; height: auto;
    }
    .embed-container iframe, .embed-container object, .embed-container embed {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }
</style>

<div class='embed-container'><iframe src='https://player.vimeo.com/video/208791851?autoplay=1&loop=1&background=1' frameborder='0' webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></div>
</code>```

But I still have black border on bottom and top.

I've created a jsfiddle where you can also see this: https://jsfiddle.net/07fkfwz3/ . And the video that you can see here doesn't have any borders.

答:
This worked for me:

```<code><style>
  .embed-container {
    position: relative;
    padding-bottom: 56.25%;
    height: 0;
    overflow: hidden;
    max-width: 100%;
  }

  .embed-container iframe,
  .embed-container object,
  .embed-container embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
</style>
<div class='embed-container'><iframe src='https://player.vimeo.com/video/157467640?background=1' frameborder='0' webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></div>
</code>```

Source: https://forum.webflow.com/t/setting-vimeo-video-to-full-width-of-div/25499/2

Title: Vimeo full width

Body:
I'm trying to have a vimeo video shown full width in web page.

This is how it looks now:

As you can see the black is full width but not the video. It should be full width, no controls shown, play automatic and play in a loop.

My code looks like this now:

The client has vimeo plus but not vimeo pro. Can someone help me with this.

UPDATE:

I've changed my code to this:

But I still have black border on bottom and top.

I've created a jsfiddle where you can also see this: https://jsfiddle.net/07fkfwz3/ . And the video that you can see here doesn't have any borders.

Body:
This worked for me:

<style>
  .embed-container {
    position: relative;
    padding-bottom: 56.25%;
    height: 0;
    overflow: hidden;
    max-width: 100%;
  }

  .embed-container iframe,
  .embed-container object,
  .embed-container embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
</style>
<div class='embed-container'><iframe src='https://player.vimeo.com/video/157467640?background=1' frameborder='0' webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></div>

Source: https://forum.webflow.com/t/setting-vimeo-video-to-full-width-of-div/25499/2


问:
Can I generate a payment URL with Stripe Checkout?
I'd like to create a URL that I can share in my newsletter that sends people directly to a Stripe Checkout form to make a small (fixed amount) payment.

With the new Stripe Checkout I can generate the HTML Code to build a button that I can include in a website. I'd like to avoid sending people to a website where they have to click that button, but send them straight to the payment form based on the parameters in a URL. Is this possible?

答:
Edit: This is now possible with the launch of Payment Links! Check it out here: Stripe Payment Links

This is unfortunately not possible. Stripe.js generates a unique redirect page for each redirectToCheckout call using your publishable key. This ensures that the page is unique to each customer so it can be tracked easier.

You can't really get around sending your customers to a website as even legacy Checkout requires the use of JavaScript to generate the payment form.


问:
Run application in the background
I'm trying to start the GroomDroid web server in Android but when it starts, a black window is shown.

I'd like to start this app in the background without that screen being shown.

I'm starting this app in the following way:

```<code>Intent webServer = new Intent();
webServer.setClassName("net.allory.groom","net.allory.groom.GroomDroid");
startActivity(webServer);
</code>```

I also tried with startService(webServer); but it doesn't seem to work.

Can anybody help me with that ?

答:
You should move your background logic to a service, and when it's running create an ongoing notification.

Selecting that notification should start your activity (ui), and the service can communicate its data to it using a Handler.

Also, if you specify the launchMode of your activity to singleTask:

```<code><activity android:name=".activity.YourActivity"
    android:launchMode="singleTask"
    android:alwaysRetainTaskState="true"
    android:clearTaskOnLaunch="false"
    android:finishOnTaskLaunch="false">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>
</code>```

and on application start check if your service is already running (say you've already started the application, and now press its icon again), you'll be able to start the very same task, instead of relaunching your service and/or showing nothing.

This explanation might be not too clear, let me know if you need more details :)

ContentLicense: CC BY-SA 2.5

Title: Run application in the background

Body:
I'm trying to start the GroomDroid web server in Android but when it starts, a black window is shown.

I'd like to start this app in the background without that screen being shown.

I'm starting this app in the following way:

Intent webServer = new Intent();
webServer.setClassName("net.allory.groom","net.allory.groom.GroomDroid");
startActivity(webServer);

I also tried with startService(webServer); but it doesn't seem to work.

Can anybody help me with that ?

Body:
You should move your background logic to a service, and when it's running create an ongoing notification.

Selecting that notification should start your activity (ui), and the service can communicate its data to it using a Handler.

Also, if you specify the launchMode of your activity to singleTask:

<activity android:name=".activity.YourActivity"
    android:launchMode="singleTask"
    android:alwaysRetainTaskState="true"
    android:clearTaskOnLaunch="false"
    android:finishOnTaskLaunch="false">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

and on application start check if your service is already running (say you've already started the application, and now press its icon again), you'll be able to start the very same task, instead of relaunching your service and/or showing nothing.

This explanation might be not too clear, let me know if you need more details :)


问:
What is the difference between Connection and Proxy-connection in HTTP header?
What is the difference between Connection and Proxy-Connection in HTTP header?

Is the Proxy-Connection field added by the proxy? Or the client and server?  What will the proxy, client or server do after receiving a header with these two fields with value keep-alive and close respectively?

答:
Quoted from https://www.rfc-editor.org/rfc/rfc7230#appendix-A.1.2

In HTTP/1.0, each connection is established by the client prior to
the request and closed by the server after sending the response.
However, some implementations implement the explicitly negotiated
("Keep-Alive") version of persistent connections described in Section
19.7.1 of [RFC2068].

Some clients and servers might wish to be compatible with these
previous approaches to persistent connections, by explicitly
negotiating for them with a "Connection: keep-alive" request header
field. However, some experimental implementations of HTTP/1.0
persistent connections are faulty; for example, if an HTTP/1.0 proxy
server doesn't understand Connection, it will erroneously forward
that header field to the next inbound server, which would result in a
hung connection.

One attempted solution was the introduction of a Proxy-Connection
header field, targeted specifically at proxies. In practice, this
was also unworkable, because proxies are often deployed in multiple
layers, bringing about the same problem discussed above.

As a result, clients are encouraged not to send the Proxy-Connection
header field in any requests.

Clients are also encouraged to consider the use of Connection:
keep-alive in requests carefully; while they can enable persistent
connections with HTTP/1.0 servers, clients using them will need to
monitor the connection for "hung" requests (which indicate that the
client ought stop sending the header field), and this mechanism ought
not be used by clients at all when a proxy is being used.


问:
Adding User to Group using Graph API B2C
I am using Azure AD B2C to create users.
After a user is created I would like to add them to a Group

Using Postman I have made the following request (with access token in the header). Note: I have managed to successfully create a group using the Api.

POST
https://graph.windows.net/{azure-tenant}/groups/{group-objectId/members/$ref?api-version=1.6

With Body:

```<code>{
    "@odata.id": "https://graph.windows.net/{azure-tenant}/directoryObjects/{user-objectId}"
}
</code>```

Which is what the documentation specifies. No matter the body that is sent I get the following error

```<code>{
    "odata.error": {
        "code": "Request_BadRequest",
        "message": {
            "lang": "en",
            "value": "The request URI is not valid. Since the segment 'members' refers to a collection, this must be the last segment in the request URI. All intermediate segments must refer to a single resource."
        },
        "requestId": "48cf65f3-20ba-411e-8121-f7ea54252f3a",
        "date": "2019-05-27T06:09:25"
    }
}
</code>```

I tried removing the /$ref

POST
https://graph.windows.net/{azure-tenant}/groups/{group-objectId/members?api-version=1.6

Body:

```<code>{
    "@odata.id": "https://graph.windows.net/{azure-tenant}/directoryObjects/{user-objectId}"
}
</code>```

as well as

```<code>{
    "@odata.id": "https://graph.windows.net/{azure-tenant}/users/{user-objectId}"
}
</code>```

Now the error that gets returned now is:

```<code>{
    "odata.error": {
        "code": "Request_BadRequest",
        "message": {
            "lang": "en",
            "value": "Unsupported resource type 'DirectoryObject' for operation 'Create'."
        },
        "requestId": "2c36cc6d-383c-44f8-8609-2ac3e3efc862",
        "date": "2019-05-27T06:15:26"
    }
}
</code>```

The documentation that I have been using https://learn.microsoft.com/en-us/graph/api/group-post-members?view=graph-rest-1.0&tabs=javascript

答:
You are using graph.windows.net endpoint, so you should refer to azure ad graph api.

```<code>POST https://graph.windows.net/myorganization/groups/b4bda672-1fba-4711-8fb1-5383c40b2c14/$links/members?api-version=1.6

{
  "url": "https://graph.windows.net/myorganization/directoryObjects/3eb6055a-baeb-44d4-a1ea-2fee86d8891b"
}
</code>```

The document you referred to is microsoft graph api. The endpoint should be https://graph.microsoft.com.

You can use Microsoft Graph explorer to call these apis.

Body:
I am using Azure AD B2C to create users.
After a user is created I would like to add them to a Group

Using Postman I have made the following request (with access token in the header). Note: I have managed to successfully create a group using the Api.

POST
https://graph.windows.net/{azure-tenant}/groups/{group-objectId/members/$ref?api-version=1.6

With Body:

{
    "@odata.id": "https://graph.windows.net/{azure-tenant}/directoryObjects/{user-objectId}"
}

Which is what the documentation specifies. No matter the body that is sent I get the following error

{
    "odata.error": {
        "code": "Request_BadRequest",
        "message": {
            "lang": "en",
            "value": "The request URI is not valid. Since the segment 'members' refers to a collection, this must be the last segment in the request URI. All intermediate segments must refer to a single resource."
        },
        "requestId": "48cf65f3-20ba-411e-8121-f7ea54252f3a",
        "date": "2019-05-27T06:09:25"
    }
}

I tried removing the /$ref

POST
https://graph.windows.net/{azure-tenant}/groups/{group-objectId/members?api-version=1.6

Body:

{
    "@odata.id": "https://graph.windows.net/{azure-tenant}/directoryObjects/{user-objectId}"
}

as well as

{
    "@odata.id": "https://graph.windows.net/{azure-tenant}/users/{user-objectId}"
}

Now the error that gets returned now is:

{
    "odata.error": {
        "code": "Request_BadRequest",
        "message": {
            "lang": "en",
            "value": "Unsupported resource type 'DirectoryObject' for operation 'Create'."
        },
        "requestId": "2c36cc6d-383c-44f8-8609-2ac3e3efc862",
        "date": "2019-05-27T06:15:26"
    }
}

The documentation that I have been using https://learn.microsoft.com/en-us/graph/api/group-post-members?view=graph-rest-1.0&tabs=javascript

Body:
You are using graph.windows.net endpoint, so you should refer to azure ad graph api.

POST https://graph.windows.net/myorganization/groups/b4bda672-1fba-4711-8fb1-5383c40b2c14/$links/members?api-version=1.6

{
  "url": "https://graph.windows.net/myorganization/directoryObjects/3eb6055a-baeb-44d4-a1ea-2fee86d8891b"
}

The document you referred to is microsoft graph api. The endpoint should be https://graph.microsoft.com.

You can use Microsoft Graph explorer to call these apis.


问:
Performance issue with Promises, setTimeout, async/await on Edge
Is there anything inherently wrong with the following mixed use of asnyc/await, promise, and setInterval? It's working as desired, but the performance is terrible on Edge. My test case runs in about 3.5 sec in Chrome, but takes over 2 min in Edge. Note that this is a method from a TypeScript class.

```<code>public async exportPdf(sourceGraph: IGraph, filters: EntityFilter) {
        if (sourceGraph) {
            ...snip....
            for (let verticalPageIndex = 0; verticalPageIndex < pagesHighWithMargins; verticalPageIndex++) {
                for (let horizontalPageIndex = 0; horizontalPageIndex < pagesWideWithMargins; horizontalPageIndex++) {
                    // run with setTimeout so we can process other events between pages and prevent locking up the browser
                    await new Promise(resolve => setTimeout(resolve, 0)).then(async () => {
                        ...snip...
                        const svgElement = await exporter.exportSvgAsync(exportComponent) as SVGElement;
                         ....snip - expensive code to convert SVG to PDF page...
                    });
                }
            }

            return jsPdf.output('datauristring');
        } else {
            return new Promise((_, reject) => {
                reject(new Error('graph argument is null'));
            });
        }
    }
</code>```

Obviously I'm a newbie with JS and TS, but I've been around long enough to know that mixing 3 different techniques for managing async operations is probably wrong. :-)

答:
I'm closing out this question because I've isolated my primary issue -- performance when using the Edge browser -- to a library I'm using to convert SVG to PDF and not my use of promises, setTimeout, or async/await, but any further insight on the additional findings below is appreciated!

@Bergi's suggestions are much appreciated, but I'm probably still be missing something. If I don't include the lines after await new Promise(...) inside the then(), my loops complete before I've generated the content of my PDF pages, which causes the next steps -- exporting the complete PDF content as a string and saving to disk -- to fail. I need this loop to complete synchronously so I get all the PDF content in the correct order. The only reason I'm using new Promise(resolve => setTimeout(resolve, 0)) is to slightly improve the browser's responsiveness during the loop, which is working pretty much as shown in the original post.

I did removed the async from the then's callback and switched to a synchronous version of the exportSvg function and it's working well. Simply awaiting the call to exporter.exportSvgAsync without enclosing it in a await new Promise(resolve => setTimeout(resolve, 0)).then(...) did not allow the browser to be responsive at all inside the loop though.

Body:
Is there anything inherently wrong with the following mixed use of asnyc/await, promise, and setInterval? It's working as desired, but the performance is terrible on Edge. My test case runs in about 3.5 sec in Chrome, but takes over 2 min in Edge. Note that this is a method from a TypeScript class.

public async exportPdf(sourceGraph: IGraph, filters: EntityFilter) {
        if (sourceGraph) {
            ...snip....
            for (let verticalPageIndex = 0; verticalPageIndex < pagesHighWithMargins; verticalPageIndex++) {
                for (let horizontalPageIndex = 0; horizontalPageIndex < pagesWideWithMargins; horizontalPageIndex++) {
                    // run with setTimeout so we can process other events between pages and prevent locking up the browser
                    await new Promise(resolve => setTimeout(resolve, 0)).then(async () => {
                        ...snip...
                        const svgElement = await exporter.exportSvgAsync(exportComponent) as SVGElement;
                         ....snip - expensive code to convert SVG to PDF page...
                    });
                }
            }

            return jsPdf.output('datauristring');
        } else {
            return new Promise((_, reject) => {
                reject(new Error('graph argument is null'));
            });
        }
    }

Obviously I'm a newbie with JS and TS, but I've been around long enough to know that mixing 3 different techniques for managing async operations is probably wrong. :-)


问:
Imacros add a part to the URL
I'm trying to make a Imacro script to download multiple photos from Unsplash because I have a project and it's time consuming to download one by one.

So far, I've managed to make the following code. But it skips many images.

VERSION BUILD=8970419 RECORDER=FX
TAB T=1

ONDOWNLOAD FOLDER=* FILE=+_{{!NOW:yyyymmdd_hhnnss}} WAIT=YES
TAG POS={{!LOOP}} TYPE=A ATTR=HREF:https://unsplash.com/photos/*/download?force=true```
</div>
</div>
</p>

<p>Then I found out that the problem is Unsplash doesn't have <code>download?force=true</code> for all images.</p>

<p>Now, what I want is, let it add + <code>download?force=true</code> part after the URL automatically.</p>

<p>To clarify more, this is what I want.</p>

```https://unsplash.com/photos/*/ + download?force=true
```

Thanks in advance.

答:
This should be good enough, I would think:

```<code>TAG POS={{!LOOP}} TYPE=A ATTR=HREF:https://unsplash.com/photos/*/*
</code>```

Only keep the parts that are always there and replace the parts that might be changing or might not be there with *, like you were already doing in /photos/*/....

Title: Imacros add a part to the URL

Body:
I'm trying to make a Imacro script to download multiple photos from Unsplash because I have a project and it's time consuming to download one by one.

So far, I've managed to make the following code. But it skips many images.

VERSION BUILD=8970419 RECORDER=FX
TAB T=1

ONDOWNLOAD FOLDER=* FILE=+_{{!NOW:yyyymmdd_hhnnss}} WAIT=YES
TAG POS={{!LOOP}} TYPE=A ATTR=HREF:https://unsplash.com/photos/*/download?force=true

Then I found out that the problem is Unsplash doesn't have download?force=true for all images.

Now, what I want is, let it add + download?force=true part after the URL automatically.

To clarify more, this is what I want.

https://unsplash.com/photos/*/ + download?force=true

Thanks in advance.

Body:
This should be good enough, I would think:

TAG POS={{!LOOP}} TYPE=A ATTR=HREF:https://unsplash.com/photos/*/*

Only keep the parts that are always there and replace the parts that might be changing or might not be there with *, like you were already doing in /photos/*/....


问:
Keikai: how to check if filter is enabled
I am trying to import an Excel file that has filter into Keikai Spreadsheet for further integration. I need to know programmatically if the filter in the sheet is enabled or not, and its range. What is the right API to use? Can someone give me an example?</p>

答:
You can call

```<code>spreadsheet.getWorksheet().isAutoFilterEnabled();
spreadsheet.getWorksheet().getAutoFilterRange();
</code>```

Please refer to https://keikai.io/javadoc/latest/io/keikai/client/api/Worksheet.html

Body:
You can call

spreadsheet.getWorksheet().isAutoFilterEnabled();
spreadsheet.getWorksheet().getAutoFilterRange();

Please refer to https://keikai.io/javadoc/latest/io/keikai/client/api/Worksheet.html


问:
is there an explicit interface declaration for abstract methods?
i have a (quite easy) problem and it seems I can't find out how to do it. I would appreciate some help.

I have two classes which are something like this:

```<code>public class FileParameters { ... }

public abstract class File {
    ...
    public abstract FileParameters Params { get; }
}
</code>```

From both classes I have a derived special version:

```<code>public class SpecialFileParameters { ... }

public abstract class SpecialFile {
    ...
    private SpecialFileParameters params;
    public override FileParameters Params { get { return params; } }
}
</code>```

When I want to use the SpecialFileParameters I have to cast them first, e.g:

```<code>((SpecialFileParameters)SpecialFileObject.Parameters).DoSomething();
</code>```

which is quite obnoxious. What I would like to have is basically the same syntax as with interfaces

```<code>public abstract class SpecialFile {
    ...
    private SpecialFileParameters params;
    private override FileParameters File.Params { get { return params; } }
    public new SpecialFileParameters Params { get { return params; } }
}
</code>```

But like this i get an compiler error: 'File' in explicit interface declaration is not an interface. Is there some other way to do this?

Some further information:

I cannot change the base classes, only my special classes

I actually need 2 special derived classes, one is written in C#, the other in C++/CLI. If the "trick" to makes it work is different between C# and C++ CLI please let me know.

Thanks for your help (and patience I guess ^^),

答:
No, there's no syntax in C# for marking an explicit abstract override method (as distinct from another method with the same signature), and since you can't have two matching signatures declared in the same level you can't do quite what you want.

Since you've ruled out changing the base class, the only suggestion I have is to add an artificial extra level:

```<code>public abstract class File {
    public abstract FileParameters Params { get; }
}
public abstract class FileIntermediate : File
{
    public override FileParameters Params {get { return ParamsImpl; }}
    protected abstract FileParameters ParamsImpl { get; }
}
public class SpecialFile : FileIntermediate
{
    public new SpecialFileParameters Params { get { return null; } }// TODO
    protected override FileParameters ParamsImpl {get { return Params; }}
}
</code>```

Body:
i have a (quite easy) problem and it seems I can't find out how to do it. I would appreciate some help.

I have two classes which are something like this:

public class FileParameters { ... }

public abstract class File {
    ...
    public abstract FileParameters Params { get; }
}

From both classes I have a derived special version:

public class SpecialFileParameters { ... }

public abstract class SpecialFile {
    ...
    private SpecialFileParameters params;
    public override FileParameters Params { get { return params; } }
}

When I want to use the SpecialFileParameters I have to cast them first, e.g:

((SpecialFileParameters)SpecialFileObject.Parameters).DoSomething();

which is quite obnoxious. What I would like to have is basically the same syntax as with interfaces

public abstract class SpecialFile {
    ...
    private SpecialFileParameters params;
    private override FileParameters File.Params { get { return params; } }
    public new SpecialFileParameters Params { get { return params; } }
}

But like this i get an compiler error: 'File' in explicit interface declaration is not an interface. Is there some other way to do this?

Some further information:

I cannot change the base classes, only my special classes

I actually need 2 special derived classes, one is written in C#, the other in C++/CLI. If the "trick" to makes it work is different between C# and C++ CLI please let me know.

Thanks for your help (and patience I guess ^^),

Body:
No, there's no syntax in C# for marking an explicit abstract override method (as distinct from another method with the same signature), and since you can't have two matching signatures declared in the same level you can't do quite what you want.

Since you've ruled out changing the base class, the only suggestion I have is to add an artificial extra level:

public abstract class File {
    public abstract FileParameters Params { get; }
}
public abstract class FileIntermediate : File
{
    public override FileParameters Params {get { return ParamsImpl; }}
    protected abstract FileParameters ParamsImpl { get; }
}
public class SpecialFile : FileIntermediate
{
    public new SpecialFileParameters Params { get { return null; } }// TODO
    protected override FileParameters ParamsImpl {get { return Params; }}
}


问:
How to struct yaml file in parent child order?
I want to form a struct using golang via yaml file but I find it difficult to figure out to do it.

```<code>api:
  local:
    host: localhost
    port: 8085
  develop:
    host:
    port:
  production:
    host:
    port:
rest-api:
  local:
    host: localhost
    port: 8085
  develop:
    host:
    port:
  production:
    host:
    port:
</code>```

this is the format in my yaml file

the expected code of this is i want to create a dynamic api url in local, develop and production format like api : local = host+port, same to develop and production to dynamically configure it easily and set up

Would appreciate your help in golang struct and also for your help.

答:
This online resource will get you halfway there:

https://mengzhuo.github.io/yaml-to-go/

Pasting your yaml yields this:

```<code>type AutoGenerated struct {
    API struct {
        Local struct {
            Host string `yaml:"host"`
            Port int    `yaml:"port"`
        } `yaml:"local"`
        Develop struct {
            Host interface{} `yaml:"host"`
            Port interface{} `yaml:"port"`
        } `yaml:"develop"`
        Production struct {
            Host interface{} `yaml:"host"`
            Port interface{} `yaml:"port"`
        } `yaml:"production"`
    } `yaml:"api"`
    RestAPI struct {
        Local struct {
            Host string `yaml:"host"`
            Port int    `yaml:"port"`
        } `yaml:"local"`
        Develop struct {
            Host interface{} `yaml:"host"`
            Port interface{} `yaml:"port"`
        } `yaml:"develop"`
        Production struct {
            Host interface{} `yaml:"host"`
            Port interface{} `yaml:"port"`
        } `yaml:"production"`
    } `yaml:"rest-api"`
}
</code>```

There's obvious sub-type duplicates. So it can be trimmed.

First pass:

```<code>type Address struct {
    Host string `yaml:"host"`
    Port int    `yaml:"port"`
}

type MyConfig struct {
    API struct {
        Local      Address `yaml:"local"`
        Develop    Address `yaml:"develop"`
        Production Address `yaml:"production"`
    } `yaml:"api"`
    RestAPI struct {
        Local      Address `yaml:"local"`
        Develop    Address `yaml:"develop"`
        Production Address `yaml:"production"`
    } `yaml:"rest-api"`
}
</code>```

Second (and final) pass:

```<code>type Address struct {
    Host string `yaml:"host"`
    Port int    `yaml:"port"`
}

type Deployment struct {
    Local      Address `yaml:"local"`
    Develop    Address `yaml:"develop"`
    Production Address `yaml:"production"`
}

type MyConfig struct {
    API     Deployment `yaml:"api"`
    RestAPI Deployment `yaml:"rest-api"`
}
</code>```

Body:
I want to form a struct using golang via yaml file but I find it difficult to figure out to do it.

api:
  local:
    host: localhost
    port: 8085
  develop:
    host:
    port:
  production:
    host:
    port:
rest-api:
  local:
    host: localhost
    port: 8085
  develop:
    host:
    port:
  production:
    host:
    port:

this is the format in my yaml file

the expected code of this is i want to create a dynamic api url in local, develop and production format like api : local = host+port, same to develop and production to dynamically configure it easily and set up

Would appreciate your help in golang struct and also for your help.

Body:
This online resource will get you halfway there:

https://mengzhuo.github.io/yaml-to-go/

Pasting your yaml yields this:

type AutoGenerated struct {
    API struct {
        Local struct {
            Host string `yaml:"host"`
            Port int    `yaml:"port"`
        } `yaml:"local"`
        Develop struct {
            Host interface{} `yaml:"host"`
            Port interface{} `yaml:"port"`
        } `yaml:"develop"`
        Production struct {
            Host interface{} `yaml:"host"`
            Port interface{} `yaml:"port"`
        } `yaml:"production"`
    } `yaml:"api"`
    RestAPI struct {
        Local struct {
            Host string `yaml:"host"`
            Port int    `yaml:"port"`
        } `yaml:"local"`
        Develop struct {
            Host interface{} `yaml:"host"`
            Port interface{} `yaml:"port"`
        } `yaml:"develop"`
        Production struct {
            Host interface{} `yaml:"host"`
            Port interface{} `yaml:"port"`
        } `yaml:"production"`
    } `yaml:"rest-api"`
}

There's obvious sub-type duplicates. So it can be trimmed.

First pass:

type Address struct {
    Host string `yaml:"host"`
    Port int    `yaml:"port"`
}

type MyConfig struct {
    API struct {
        Local      Address `yaml:"local"`
        Develop    Address `yaml:"develop"`
        Production Address `yaml:"production"`
    } `yaml:"api"`
    RestAPI struct {
        Local      Address `yaml:"local"`
        Develop    Address `yaml:"develop"`
        Production Address `yaml:"production"`
    } `yaml:"rest-api"`
}

Second (and final) pass:

type Address struct {
    Host string `yaml:"host"`
    Port int    `yaml:"port"`
}

type Deployment struct {
    Local      Address `yaml:"local"`
    Develop    Address `yaml:"develop"`
    Production Address `yaml:"production"`
}

type MyConfig struct {
    API     Deployment `yaml:"api"`
    RestAPI Deployment `yaml:"rest-api"`
}


问:
Viewing DOM source using Chrome Developer Tools
I am unable to figure out how I can view the DOM source for the table at following web page, using Chrome Developer Tools:

https://www.nseindia.com/corporates/corporateHome.html?id=eqFinResults

I am interested in scraping the entries from the table (i.e. the table with column names Symbol, Company, .... , XBRL Filename, Status).

I tried various options, including:

View page Source

View Frame Source

Highlighting a row in the table and selecting Inspect

Highlighting the entire page (Ctrl+A) and selecting Inspect

I would like to be able to see the HTML code corresponding to:

a particular row in the table

the entire table

答: Right-click > Inspect works fine for me.


问:
How to make exact CSS3 Linear gradient like it's in the image?
For example this is gradient which I want to make in CSS3

I can use 1 px image cut and repeat in x axis as we were doing before. But now if I want to make same exact gradient using CSS3.

I know many free CSS3 Gradient Generator , Maker available on Internet. My questions is Which Generator is most preferred and how to make needed gradients with that.

Edit after Alex's answer : more Gradients

答:
Linear gradient should work fine :</p>

```<code>background: -webkit-gradient(linear, left top, left bottom, from(#ccc), to(#343434));
background: -moz-linear-gradient(top,  #ccc,  #343434);
</code>```

Body:
Linear gradient should work fine :

background: -webkit-gradient(linear, left top, left bottom, from(#ccc), to(#343434));
background: -moz-linear-gradient(top,  #ccc,  #343434);


问:
CommonCrawl: How to find a specific web page?
I am using CommonCrawl to restore pages I should have achieved but have not.

In my understanding, the Common Crawl Index offers access to all URLs stored by Common Crawl. Thus, it should give me an answer if the URL is achieved.

A simple script downloads all indices from the available crawls:

```<code>./cdx-index-client.py -p 4 -c CC-MAIN-2016-18 *.thesun.co.uk --fl url -d CC-MAIN-2016-18
./cdx-index-client.py -p 4 -c CC-MAIN-2016-07 *.thesun.co.uk --fl url -d CC-MAIN-2016-07
... and so on
</code>```

Afterwards I have 112mb of data and simply grep:

```<code>grep "50569" * -r
grep "Locals-tell-of-terror-shock" * -r
</code>```

The pages are not there. Am I missing something? The page were published in 2006 and removed in June 2016. So I assume that CommonCrawl should have achieved them?

Update: Thanks to Sebastian, two links are left...
Two URLs are:

http://www.thesun.co.uk/sol/homepage/news/50569/Locals-tell-of-terror-shock.html

http://www.thesun.co.uk/sol/homepage/news/54032/Sir-Ians-raid-apology.html

They even proposed a "URL Search Tool" which answers with a 502 - Bad Gateway...

答:
AFAIK pages are crawled once and only once, so the pages you're looking for could be in any of the archives.

I wrote a small software that can be used to search all archives at once (here's also a demonstration showing how to do this). So in your case I searched all archives (2008 to 2019) and typed your URLs on the common crawl editor, and found these results for your first URL (couldn't find the second so I guess is not in the database?):

```<code>                           FileName                              Offset    Length
 ------------------------------------------------------------- ---------- --------
  parse-output/segment/1346876860877/1346943319237_751.arc.gz    7374762    12162
  crawl-002/2009/11/21/8/1258808591287_8.arc.gz                 87621562    20028
  crawl-002/2010/01/07/5/1262876334932_5.arc.gz                 80863242    20075
</code>```

Not sure why there're three results. I guess they do re-scan some URLs.

Of if you open any of these URLs on the application I linked you should be able to see the pages in a browser (this is a custom scheme that that includes the filename, offset and length in order to load HTML from the common crawl database):

```<code>crawl://page.common/parse-output/segment/1346876860877/1346943319237_751.arc.gz?o=7374762&l=12162&u=http%3A%2F%2Fwww.thesun.co.uk%2Fsol%2Fhomepage%2Fnews%2F50569%2FLocals-tell-of-terror-shock.html
crawl://page.common/crawl-002/2009/11/21/8/1258808591287_8.arc.gz?o=87621562&l=20028&u=http%3A%2F%2Fwww.thesun.co.uk%2Fsol%2Fhomepage%2Fnews%2F50569%2FLocals-tell-of-terror-shock.html
crawl://page.common/crawl-002/2010/01/07/5/1262876334932_5.arc.gz?o=80863242&l=20075&u=http%3A%2F%2Fwww.thesun.co.uk%2Fsol%2Fhomepage%2Fnews%2F50569%2FLocals-tell-of-terror-shock.html
</code>```

Body:
I am using CommonCrawl to restore pages I should have achieved but have not.

In my understanding, the Common Crawl Index offers access to all URLs stored by Common Crawl. Thus, it should give me an answer if the URL is achieved.

A simple script downloads all indices from the available crawls:

./cdx-index-client.py -p 4 -c CC-MAIN-2016-18 *.thesun.co.uk --fl url -d CC-MAIN-2016-18
./cdx-index-client.py -p 4 -c CC-MAIN-2016-07 *.thesun.co.uk --fl url -d CC-MAIN-2016-07
... and so on

Afterwards I have 112mb of data and simply grep:

grep "50569" * -r
grep "Locals-tell-of-terror-shock" * -r

The pages are not there. Am I missing something? The page were published in 2006 and removed in June 2016. So I assume that CommonCrawl should have achieved them?

Update: Thanks to Sebastian, two links are left...
Two URLs are:

http://www.thesun.co.uk/sol/homepage/news/50569/Locals-tell-of-terror-shock.html

http://www.thesun.co.uk/sol/homepage/news/54032/Sir-Ians-raid-apology.html

They even proposed a "URL Search Tool" which answers with a 502 - Bad Gateway...

Body:
AFAIK pages are crawled once and only once, so the pages you're looking for could be in any of the archives.

I wrote a small software that can be used to search all archives at once (here's also a demonstration showing how to do this). So in your case I searched all archives (2008 to 2019) and typed your URLs on the common crawl editor, and found these results for your first URL (couldn't find the second so I guess is not in the database?):

                           FileName                              Offset    Length
 ------------------------------------------------------------- ---------- --------
  parse-output/segment/1346876860877/1346943319237_751.arc.gz    7374762    12162
  crawl-002/2009/11/21/8/1258808591287_8.arc.gz                 87621562    20028
  crawl-002/2010/01/07/5/1262876334932_5.arc.gz                 80863242    20075

Not sure why there're three results. I guess they do re-scan some URLs.

Of if you open any of these URLs on the application I linked you should be able to see the pages in a browser (this is a custom scheme that that includes the filename, offset and length in order to load HTML from the common crawl database):

crawl://page.common/parse-output/segment/1346876860877/1346943319237_751.arc.gz?o=7374762&l=12162&u=http%3A%2F%2Fwww.thesun.co.uk%2Fsol%2Fhomepage%2Fnews%2F50569%2FLocals-tell-of-terror-shock.html
crawl://page.common/crawl-002/2009/11/21/8/1258808591287_8.arc.gz?o=87621562&l=20028&u=http%3A%2F%2Fwww.thesun.co.uk%2Fsol%2Fhomepage%2Fnews%2F50569%2FLocals-tell-of-terror-shock.html
crawl://page.common/crawl-002/2010/01/07/5/1262876334932_5.arc.gz?o=80863242&l=20075&u=http%3A%2F%2Fwww.thesun.co.uk%2Fsol%2Fhomepage%2Fnews%2F50569%2FLocals-tell-of-terror-shock.html


问:
How to attach excel files to Gmail using Python 3.7?
I created a function in python 3.7 to create draft emails with attached spreadsheets for all the clients.
The code creates that draft email correctly and attaches the files (.xlsx) but these files can no more be opened on gmail. Not sure if this is specific to the encoding that I am using.
(The files can be opened successfully on my desktop computer)

Below is the code:

```<code>def CreateMessageWithAttachment(sender, to, cc, subject, message_text, file_dir, filename):
    """Create email messages with attachment, for sending to partners"""
    message = MIMEMultipart('alternative')
    message['to'] = to
    message['from'] = sender
    message['cc'] = cc
    message['subject'] = subject
    msg = MIMEText(message_text, 'html')
    message.attach(msg)
    path = os.path.join(file_dir, filename)
    content_type, encoding = mimetypes.guess_type(path)
    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'

    main_type, sub_type = content_type.split('/', 1)
    #    main_type, sub_type = 'gzip', None
    fp = open(path, 'rb')
    msg = MIMEBase(main_type, sub_type)
    msg.set_payload(fp.read())
    fp.close()
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)
    raw = base64.urlsafe_b64encode(message.as_bytes())
    raw = raw.decode()
    return {'raw': raw}
    #return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
</code>```

I am assuming, the encoding of the files is what corrupting the spreadsheets attached. Any help would be appreciated.

答:
Try changing these two lines:

```<code>msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())
</code>```

To just this:

```<code>msg = MIMEApplication(fp.read(), sub_type)
</code>```

Body:
I created a function in python 3.7 to create draft emails with attached spreadsheets for all the clients.
The code creates that draft email correctly and attaches the files (.xlsx) but these files can no more be opened on gmail. Not sure if this is specific to the encoding that I am using.
(The files can be opened successfully on my desktop computer)

Below is the code:

def CreateMessageWithAttachment(sender, to, cc, subject, message_text, file_dir, filename):
    """Create email messages with attachment, for sending to partners"""
    message = MIMEMultipart('alternative')
    message['to'] = to
    message['from'] = sender
    message['cc'] = cc
    message['subject'] = subject
    msg = MIMEText(message_text, 'html')
    message.attach(msg)
    path = os.path.join(file_dir, filename)
    content_type, encoding = mimetypes.guess_type(path)
    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'

    main_type, sub_type = content_type.split('/', 1)
    #    main_type, sub_type = 'gzip', None
    fp = open(path, 'rb')
    msg = MIMEBase(main_type, sub_type)
    msg.set_payload(fp.read())
    fp.close()
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)
    raw = base64.urlsafe_b64encode(message.as_bytes())
    raw = raw.decode()
    return {'raw': raw}
    #return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}

I am assuming, the encoding of the files is what corrupting the spreadsheets attached. Any help would be appreciated.

Body:
Try changing these two lines:

msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())

To just this:

msg = MIMEApplication(fp.read(), sub_type)


问:
Firebase authentication, firebase is not defined
Im trying to make a login page to my firebase project, but always when i send the params to the functions its returns "Firebase is not defined . Here's my code:

```<code><button id="login" onclick="signIn()"><Login</button>
</code>```

The function signIn() only change the href to http://localhost:5000/signin/:email/:password

then i have this

```<code>const functions = require('firebase-functions');
const adm = require('firebase-admin');
const express = require('express');
const signin = require('./modules/signin');
const firebase = require("firebase");

// // Create and Deploy Your First Cloud Functions
adm.initializeApp(
    functions.config().adm
);

const app = express();

app.get('/signin/:email/:password', (request, response) => {
    exports.signin = signin(request.params.email, request.params.password);
});

exports.app = functions.https.onRequest(app);
</code>```

and my function is only

```<code>function signin (email, password) {
firebase.auth().signInWithEmailAndPassword(email, password).then(function(user) {
    // user signed in
    console.log ("Usuário logado com sucesso!");
    return True;
    }).catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;

        if (errorCode === 'auth/wrong-password') {
            // alert('Wrong password.');
            return false;
        } else {
            alert(errorCode+": "+errorMessage);
            return false;
        }
    });

}

module.exports = signin;
</code>```

im trying to use the index.js on functions folder as a type of "controller" to call functions on backend, but im having trouble to solve this simple problem.

答: You can't use the Firebase client SDK in Cloud Functions.  Cloud Functions is considered backend code, and doesn't run on the browser.  If you want to sign in the user, you have to use the SDK in your browser code, not backend code.</p>

Body:
Im trying to make a login page to my firebase project, but always when i send the params to the functions its returns "Firebase is not defined . Here's my code:

<button id="login" onclick="signIn()"><Login</button>

The function signIn() only change the href to http://localhost:5000/signin/:email/:password

then i have this

const functions = require('firebase-functions');
const adm = require('firebase-admin');
const express = require('express');
const signin = require('./modules/signin');
const firebase = require("firebase");

// // Create and Deploy Your First Cloud Functions
adm.initializeApp(
    functions.config().adm
);

const app = express();

app.get('/signin/:email/:password', (request, response) => {
    exports.signin = signin(request.params.email, request.params.password);
});

exports.app = functions.https.onRequest(app);

and my function is only

function signin (email, password) {
firebase.auth().signInWithEmailAndPassword(email, password).then(function(user) {
    // user signed in
    console.log ("Usuário logado com sucesso!");
    return True;
    }).catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;

        if (errorCode === 'auth/wrong-password') {
            // alert('Wrong password.');
            return false;
        } else {
            alert(errorCode+": "+errorMessage);
            return false;
        }
    });

}

module.exports = signin;

im trying to use the index.js on functions folder as a type of "controller" to call functions on backend, but im having trouble to solve this simple problem.


问:
private and public field in Django REST Framework
I want to have a list of public and private recipes, hiding all private recipes unless it's owner's. I created a manager for this:

```<code>class RecipeManager(models.Manager):

    def public_recipes(self, *args, **kwargs):
        return super(RecipeManager, self).filter(private=False)

    def private_recipes(self, *args, **kwargs):
        user = kwargs.pop('user')
        return super(RecipeManager, self).filter(private=True, user=user)

class Recipe(models.Model):
    name = models.CharField(max_length=100)
    recipe = models.CharField(max_length=200)
    private = models.BooleanField(default=False)
</code>```

views.py:

```<code>class RecipeViewSet(viewsets.ModelViewSet):
    queryset = Recipe.objects.all()
    serializer_class = RecipeSerializer
    permission_classes = (AllowAny,)
</code>```

serializers.py:

```<code>class RecipeSerializer(serializers.ModelSerializer):

    class Meta:
        model = Recipe
        fields = ('id', 'name', 'recipe', 'total_ingredients')
        depth = 1

</code>```

So, where can I use the methods public_recipes, private_recipes or is there a better solution for this?

答:
Firstly, you may want to set your custom manager as the default manager of your Recipe model, like so:

```<code>class RecipeManager(models.Manager):

    def public_recipes(self, *args, **kwargs):
        return super(RecipeManager, self).filter(private=False)

    def private_recipes(self, *args, **kwargs):
        user = kwargs.pop('user')
        return super(RecipeManager, self).filter(private=True, user=user)

class Recipe(models.Model):
    name = models.CharField(max_length=100)
    recipe = models.CharField(max_length=200)
    private = models.BooleanField(default=False)

    objects = RecipeManager()  # Make this manager the default manager
</code>```

You may override the get_queryset() method on your view to merge the private and public recipes for a user:

```<code>class RecipeViewSet(viewsets.ModelViewSet):
    queryset = Recipe.objects.all()
    serializer_class = RecipeSerializer
    permission_classes = (AllowAny,)

    def get_queryset(self):
        if self.request.user:
            private_recipes = Recipe.objects.private_recipes(user=self.request.user)
        else:
            private_recipes = Recipe.objects.none()

        public_recipes = Recipe.objects.public_recipes()

        final_recipes_list = private_recipes | public_recipes # Shorthand to merge two querysets
        return final_recipes_list
</code>```

I would actually recommend considering having different ViewSet's for public and private recipes, i.e.

```<code>class PublicRecipeViewSet(viewsets.ModelViewSet):
    queryset = Recipe.objects.public_recipes()

class PrivateRecipeViewSet(viewsets.ModelViewSet):
    queryset = Recipe.objects.filter(private=True)

    def get_queryset(self):
        if not self.request.user:
            raise AuthenticationFailed()

        queryset = super().get_queryset()
        return queryset.filter(user=self.request.user)
</code>```

Body:
I want to have a list of public and private recipes, hiding all private recipes unless it's owner's. I created a manager for this:

class RecipeManager(models.Manager):

    def public_recipes(self, *args, **kwargs):
        return super(RecipeManager, self).filter(private=False)

    def private_recipes(self, *args, **kwargs):
        user = kwargs.pop('user')
        return super(RecipeManager, self).filter(private=True, user=user)

class Recipe(models.Model):
    name = models.CharField(max_length=100)
    recipe = models.CharField(max_length=200)
    private = models.BooleanField(default=False)

views.py:

class RecipeViewSet(viewsets.ModelViewSet):
    queryset = Recipe.objects.all()
    serializer_class = RecipeSerializer
    permission_classes = (AllowAny,)

serializers.py:

class RecipeSerializer(serializers.ModelSerializer):

    class Meta:
        model = Recipe
        fields = ('id', 'name', 'recipe', 'total_ingredients')
        depth = 1

So, where can I use the methods public_recipes, private_recipes or is there a better solution for this?

Body:
Firstly, you may want to set your custom manager as the default manager of your Recipe model, like so:

class RecipeManager(models.Manager):

    def public_recipes(self, *args, **kwargs):
        return super(RecipeManager, self).filter(private=False)

    def private_recipes(self, *args, **kwargs):
        user = kwargs.pop('user')
        return super(RecipeManager, self).filter(private=True, user=user)

class Recipe(models.Model):
    name = models.CharField(max_length=100)
    recipe = models.CharField(max_length=200)
    private = models.BooleanField(default=False)

    objects = RecipeManager()  # Make this manager the default manager

You may override the get_queryset() method on your view to merge the private and public recipes for a user:

class RecipeViewSet(viewsets.ModelViewSet):
    queryset = Recipe.objects.all()
    serializer_class = RecipeSerializer
    permission_classes = (AllowAny,)

    def get_queryset(self):
        if self.request.user:
            private_recipes = Recipe.objects.private_recipes(user=self.request.user)
        else:
            private_recipes = Recipe.objects.none()

        public_recipes = Recipe.objects.public_recipes()

        final_recipes_list = private_recipes | public_recipes # Shorthand to merge two querysets
        return final_recipes_list

I would actually recommend considering having different ViewSet's for public and private recipes, i.e.

class PublicRecipeViewSet(viewsets.ModelViewSet):
    queryset = Recipe.objects.public_recipes()

class PrivateRecipeViewSet(viewsets.ModelViewSet):
    queryset = Recipe.objects.filter(private=True)

    def get_queryset(self):
        if not self.request.user:
            raise AuthenticationFailed()

        queryset = super().get_queryset()
        return queryset.filter(user=self.request.user)


问:
Indeterminate progress indicator not animating
The progress indicator does not start animating even if I use queues or sleep.

I have a function that reads contents of a directory and for each mp3 file it gets the file tags. Also, I read posts about progress indicator but nothing helped me so far.

```<code>{
    progressIndicator.startAnimation(self)
    sleep(2)
        if let item = self.outlineView.item(atRow: self.outlineView.selectedRow)  {
             self.arrMp3File.removeAll()
            do {
                let xx = (item as! DirectoryItem).url
                let b = self.getSubDir(path: xx.path)
                print(xx.path)
                for bb in b {
                    self.getTagsFromFile(file: xx.path+"/"+bb)
                }
            }
            self.arrMp3File.sort(by: {
                $0.file < $1.file
            })
            self.loadTagsFromButton.isEnabled = true
            self.tableView.reloadData()
            }
    self.progressIndicator.stopAnimation(self)
}
</code>```

I would like to show the animation, so the user knows the app is not frozen. If I remove stopAnimation it starts animating after the files are shown on the tableview.

I added that sleep just to check the animation.

答:
I solved it.</p>

```<code>{
    if let item = self.outlineView.item(atRow: self.outlineView.selectedRow)  {
        self.arrMp3File.removeAll()
        do {
            let xx = (item as! DirectoryItem).url
            let b = self.getSubDir(path: xx.path)
            DispatchQueue.global(qos: .background).async { [weak self] in
                DispatchQueue.main.async {
                    self?.progressIndicator.isHidden = false
                    self?.progressIndicator.startAnimation(self)
                }
                for bb in b {
                    self?.getTagsFromFile(file: xx.path+"/"+bb)
                }
                DispatchQueue.main.async {
                    self?.arrMp3File.sort(by: {
                        $0.file < $1.file
                    })
                    self?.tableView.reloadData()
                    self?.loadTagsFromButton.isEnabled = true
                    self?.progressIndicator.stopAnimation(self)
                    self?.progressIndicator.isHidden = true
                }
            }
        }
    }

}
</code>```

Body:
The progress indicator does not start animating even if I use queues or sleep.

I have a function that reads contents of a directory and for each mp3 file it gets the file tags. Also, I read posts about progress indicator but nothing helped me so far.

{
    progressIndicator.startAnimation(self)
    sleep(2)
        if let item = self.outlineView.item(atRow: self.outlineView.selectedRow)  {
             self.arrMp3File.removeAll()
            do {
                let xx = (item as! DirectoryItem).url
                let b = self.getSubDir(path: xx.path)
                print(xx.path)
                for bb in b {
                    self.getTagsFromFile(file: xx.path+"/"+bb)
                }
            }
            self.arrMp3File.sort(by: {
                $0.file < $1.file
            })
            self.loadTagsFromButton.isEnabled = true
            self.tableView.reloadData()
            }
    self.progressIndicator.stopAnimation(self)
}

I would like to show the animation, so the user knows the app is not frozen. If I remove stopAnimation it starts animating after the files are shown on the tableview.

I added that sleep just to check the animation.

Body:
I solved it.

{
    if let item = self.outlineView.item(atRow: self.outlineView.selectedRow)  {
        self.arrMp3File.removeAll()
        do {
            let xx = (item as! DirectoryItem).url
            let b = self.getSubDir(path: xx.path)
            DispatchQueue.global(qos: .background).async { [weak self] in
                DispatchQueue.main.async {
                    self?.progressIndicator.isHidden = false
                    self?.progressIndicator.startAnimation(self)
                }
                for bb in b {
                    self?.getTagsFromFile(file: xx.path+"/"+bb)
                }
                DispatchQueue.main.async {
                    self?.arrMp3File.sort(by: {
                        $0.file < $1.file
                    })
                    self?.tableView.reloadData()
                    self?.loadTagsFromButton.isEnabled = true
                    self?.progressIndicator.stopAnimation(self)
                    self?.progressIndicator.isHidden = true
                }
            }
        }
    }

}


问:
How to run a python tkinter app without appearing in unity panel or alt-tab
I am working on a countdown timer for Ubuntu using Python and tkinter.

I have created most of the parts and now I want my app to be able run without appearing in Unity panel or Alt-Tab switching sequence. Is there any way to do this?

And also I'd like to whether it is possible to create a moveable window without the title bar. I tried root.overrideredirect(1).

But with it I am unable to move the window.

Here's the code for my program.

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

import tkinter as tk
from tkinter import ttk
from tkinter import TOP,LEFT
import time
import datetime
import sys

class Countdown(ttk.Frame):

    def __init__(self,parent=None, endDate=None):
        ttk.Frame.__init__(self,parent)
        self.style = ttk.Style()
        self.style.theme_use("clam")
        self.pack()
        endDate = endDate.split("/")
        self.endTime = datetime.datetime(int(endDate[2]),int(endDate[1]),int(endDate[0]))
        self.setWidgets()
        self.initWidgets()

    def setWidgets(self):
        self.dLbl = ttk.Label(self,text="0",font="Ubuntu 14 bold")
        self.dLbl.pack(padx=10,pady=10,side=LEFT)
        self.hLbl = ttk.Label(self,text="0",font="Ubuntu 14 bold")
        self.hLbl.pack(padx=10,pady=10,side=LEFT)
        self.mLbl = ttk.Label(self,text="0",font="Ubuntu 14 bold")
        self.mLbl.pack(padx=10,pady=10,side=LEFT)

    def getTimeDelta(self):
        self.curDate = datetime.datetime.now()
        self.diff = self.endTime - self.curDate

        self.tSec = self.diff.total_seconds()
        self.days = self.diff.days
        h = int(((self.tSec) - self.days*24*60*60)/3600)
        self.hours = h if h>0 else 0
        m = int(((self.tSec) - (self.hours*60*60+self.days*24*60*60))/60)
        self.minutes = m if m>0 else 0
        self.sec = int(self.tSec - self.minutes*60)
        return [self.days,self.hours,self.minutes+1]

    def initWidgets(self):
        def set():
            dhm = self.getTimeDelta()
            self.dLbl["text"]=str(dhm[0])+" Days"
            self.hLbl["text"]=str(dhm[1])+" Hours"
            self.mLbl["text"]=str(dhm[2])+" Mins"
            self.after(1000,set)
        set()

root = tk.Tk()
root.title(sys.argv[1])
app = Countdown(root, sys.argv[2])
app.mainloop()
</code>```

答:
Make your own titlebar, like so:

```<code>import sys
import tkinter as tk
import tkinter.ttk as ttk
root = tk.Tk() #create the window
titlebar = tk.Label(root,height=2, bg='cyan', fg='navyblue', text=sys.argv[0]) #create the titlebar
resizable = ttk.Sizegrip(root) #make the window resizable
titlebar.pack(fill='both') # display the titlebar
root.overrideredirect(1) #make the window run without appearing in alt tab
#root.withdraw()
#root.deiconify()
root.geometry('200x200') #set the window size to 200x200
resizable.pack(fill='y',side='right')
def ontitlebarclicked(event):
    global lastposition
    lastposition=[event.x,event.y]

def ontitlebardragged(event):
    global lastposition
    windowposition=[int(i) for i in root.geometry().split('+')[1:]] # get the window position
    diffposition=[event.x-lastposition[0],event.y-lastposition[1]]
    widthheight=root.geometry().split('+')[0]
    root.geometry(widthheight+'+'+str(windowposition[0]+diffposition[0])+'+'+str(windowposition[1]+diffposition[1]))

titlebar.bind('<Button-1>',ontitlebarclicked)
titlebar.bind('<Button1-Motion>',ontitlebardragged)
titlebar.focus_force()

</code>```

Body:
I am working on a countdown timer for Ubuntu using Python and tkinter.

I have created most of the parts and now I want my app to be able run without appearing in Unity panel or Alt-Tab switching sequence. Is there any way to do this?

And also I'd like to whether it is possible to create a moveable window without the title bar. I tried root.overrideredirect(1).

But with it I am unable to move the window.

Here's the code for my program.

#!/usr/bin/python3

import tkinter as tk
from tkinter import ttk
from tkinter import TOP,LEFT
import time
import datetime
import sys

class Countdown(ttk.Frame):

    def __init__(self,parent=None, endDate=None):
        ttk.Frame.__init__(self,parent)
        self.style = ttk.Style()
        self.style.theme_use("clam")
        self.pack()
        endDate = endDate.split("/")
        self.endTime = datetime.datetime(int(endDate[2]),int(endDate[1]),int(endDate[0]))
        self.setWidgets()
        self.initWidgets()

    def setWidgets(self):
        self.dLbl = ttk.Label(self,text="0",font="Ubuntu 14 bold")
        self.dLbl.pack(padx=10,pady=10,side=LEFT)
        self.hLbl = ttk.Label(self,text="0",font="Ubuntu 14 bold")
        self.hLbl.pack(padx=10,pady=10,side=LEFT)
        self.mLbl = ttk.Label(self,text="0",font="Ubuntu 14 bold")
        self.mLbl.pack(padx=10,pady=10,side=LEFT)

    def getTimeDelta(self):
        self.curDate = datetime.datetime.now()
        self.diff = self.endTime - self.curDate

        self.tSec = self.diff.total_seconds()
        self.days = self.diff.days
        h = int(((self.tSec) - self.days*24*60*60)/3600)
        self.hours = h if h>0 else 0
        m = int(((self.tSec) - (self.hours*60*60+self.days*24*60*60))/60)
        self.minutes = m if m>0 else 0
        self.sec = int(self.tSec - self.minutes*60)
        return [self.days,self.hours,self.minutes+1]

    def initWidgets(self):
        def set():
            dhm = self.getTimeDelta()
            self.dLbl["text"]=str(dhm[0])+" Days"
            self.hLbl["text"]=str(dhm[1])+" Hours"
            self.mLbl["text"]=str(dhm[2])+" Mins"
            self.after(1000,set)
        set()

root = tk.Tk()
root.title(sys.argv[1])
app = Countdown(root, sys.argv[2])
app.mainloop()

Body:
Make your own titlebar, like so:

import sys
import tkinter as tk
import tkinter.ttk as ttk
root = tk.Tk() #create the window
titlebar = tk.Label(root,height=2, bg='cyan', fg='navyblue', text=sys.argv[0]) #create the titlebar
resizable = ttk.Sizegrip(root) #make the window resizable
titlebar.pack(fill='both') # display the titlebar
root.overrideredirect(1) #make the window run without appearing in alt tab
#root.withdraw()
#root.deiconify()
root.geometry('200x200') #set the window size to 200x200
resizable.pack(fill='y',side='right')
def ontitlebarclicked(event):
    global lastposition
    lastposition=[event.x,event.y]

def ontitlebardragged(event):
    global lastposition
    windowposition=[int(i) for i in root.geometry().split('+')[1:]] # get the window position
    diffposition=[event.x-lastposition[0],event.y-lastposition[1]]
    widthheight=root.geometry().split('+')[0]
    root.geometry(widthheight+'+'+str(windowposition[0]+diffposition[0])+'+'+str(windowposition[1]+diffposition[1]))

titlebar.bind('<Button-1>',ontitlebarclicked)
titlebar.bind('<Button1-Motion>',ontitlebardragged)
titlebar.focus_force()


问:
Copy last line in python file and modify it before adding a new line
I would like to check for a string "rele" in a python text file and if string is not present then copy the last line of the file and then modify it as below to add as a new entry.

Example:
Actual File: Where "rele" is not present

```<code>"123456",1,0,"mher",0,"N",01Jan1986 00:00,130:00,
"123456",1,1,"ermt",0,"N",01Jan1986 00:00,100:00,
"123456",1,2,"irbt",0,"N",01Jan1986 00:00,120:00,
</code>```

Expected Output:

```<code>"123456",1,0,"mher",0,"N",01Jan1986 00:00,130:00,
"123456",1,1,"ermt",0,"N",01Jan1986 00:00,0:00,
"123456",1,2,"irbt",0,"N",01Jan1986 00:00,0:00,
"123456",1,3,"rele",0,"0000",01Jan1986 00:00,0:00,
</code>```

Last entry of the file is similar to its previous except few changes to it's 3,4 and 6 columns.

My code:

```<code>  fp = open(srcEtab.txt, 'w')
  for line in lines:
      if 'rele' in line:
         foundRelOrPickup = True
  if not foundRelOrPickup:
     fp1 = open ( 'srcEtab.txt',"w" )
     lineList = fp1.readlines()
     new_line = lineList[len(lineList)-1]
     fp1.write(new_line)
  fp.close()
  fp1.close()
</code>```

答:
```<code>with open(yourFile) as f:
        lines =  f.readlines()
        if not any(map(lambda line: "rele" in line,lines)):
                last_line_words = lines[-1].split(',')
                last_line_words[2] = len(lines)
                last_line_words[3] = '"rele"'
                last_line_words[5] = '"0000"'
                lines.append(",".join([str(i) for i in last_line_words]))

        with open(otherFile, "w") as f1:
                for line in lines:
                        f1.write(line)
</code>```

Body:
I would like to check for a string "rele" in a python text file and if string is not present then copy the last line of the file and then modify it as below to add as a new entry.

Example:
Actual File: Where "rele" is not present

"123456",1,0,"mher",0,"N",01Jan1986 00:00,130:00,
"123456",1,1,"ermt",0,"N",01Jan1986 00:00,100:00,
"123456",1,2,"irbt",0,"N",01Jan1986 00:00,120:00,

Expected Output:

"123456",1,0,"mher",0,"N",01Jan1986 00:00,130:00,
"123456",1,1,"ermt",0,"N",01Jan1986 00:00,0:00,
"123456",1,2,"irbt",0,"N",01Jan1986 00:00,0:00,
"123456",1,3,"rele",0,"0000",01Jan1986 00:00,0:00,

Last entry of the file is similar to its previous except few changes to it's 3,4 and 6 columns.

My code:

  fp = open(srcEtab.txt, 'w')
  for line in lines:
      if 'rele' in line:
         foundRelOrPickup = True
  if not foundRelOrPickup:
     fp1 = open ( 'srcEtab.txt',"w" )
     lineList = fp1.readlines()
     new_line = lineList[len(lineList)-1]
     fp1.write(new_line)
  fp.close()
  fp1.close()


问:
When finding the prime factors of a number some numbers work but others dont
When testing numbers some work for example 48, but others don't. I'm not sure what the best way to approach finding all the factors of a number.

Prime Factorization

```<code>def find_primes(n):
    factors = []
    i = 2
    if n == 0:
        return 0
    if n == 1:
        return 1
    if n >= 2:
        while n % i == 0:
            next_n = n / i
            factors.append(i)
            n = next_n
            if n % i != 0:
                i += 1
                continue
            elif i == n:
                break
    if len(factors) == 0:
        return "{} is a prime number.\n".format(initial_n)
    else:
        return "The prime factors of {} are: {}\n".format(initial_n, factors)

n = int(input("Enter a number to find all the Prime Factors:"))
initial_n = n
print('\n')
print(find_primes(n))
</code>```

I am expecting to get a list of all the factors of a number.

答:
```<code>def find_primes(n):
    factors = []
    i = 2
    if n == 0:
        return 0
    if n == 1:
        return 1
    while i <= n:
        if n % i == 0:
            factors.append(i)
            n /= i
        else:
            i += 1
    if len(factors) == 0:
        return "{} is a prime number.\n".format(initial_n)
    else:
        return "The prime factors of {} are: {}\n".format(initial_n, factors)

n = int(input("Enter a number to find all the Prime Factors:"))
initial_n = n
print('\n')
print(find_primes(n))
</code>```

Body:
When testing numbers some work for example 48, but others don't. I'm not sure what the best way to approach finding all the factors of a number.

Prime Factorization

def find_primes(n):
    factors = []
    i = 2
    if n == 0:
        return 0
    if n == 1:
        return 1
    if n >= 2:
        while n % i == 0:
            next_n = n / i
            factors.append(i)
            n = next_n
            if n % i != 0:
                i += 1
                continue
            elif i == n:
                break
    if len(factors) == 0:
        return "{} is a prime number.\n".format(initial_n)
    else:
        return "The prime factors of {} are: {}\n".format(initial_n, factors)

n = int(input("Enter a number to find all the Prime Factors:"))
initial_n = n
print('\n')
print(find_primes(n))

I am expecting to get a list of all the factors of a number.


问:
Why does AWSCognitoCredentialsProvider.getIdentityId().continueWith(block:) not run its block?
I am trying to get the Identity ID of an AWSCognitoCredentialsProvider but the block doesn't run.

Why does it not run, and what should I check out to investigate this problem? Or what is the solution?

    override func viewDidLoad() {
        super.viewDidLoad()

        //setup service config
        let serviceConfiguration: AWSServiceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: nil)

        //create a pool
        let configuration: AWSCognitoIdentityUserPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: "***", clientSecret: "***", poolId: "us-east-1_***")

        AWSCognitoIdentityUserPool.register(with: serviceConfiguration, userPoolConfiguration: configuration, forKey: "***")
        pool = AWSCognitoIdentityUserPool(forKey: "***")

        pool.delegate = self

        self.user = self.pool.currentUser()
        print("user=", self.user as Any)
        print("user.isSignedIn=", user.isSignedIn)

        let credentialsProvider: AWSCognitoCredentialsProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: "us-east-1:***", identityProviderManager: self.pool)
        let defaultServiceConfiguration: AWSServiceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialsProvider)
        AWSServiceManager.default()!.defaultServiceConfiguration = defaultServiceConfiguration

        let taskNSString: AWSTask<NSString> = credentialsProvider.getIdentityId()
        print("taskNSString.result=", taskNSString.result as Any)

        // Retrieve your Amazon Cognito ID
        credentialsProvider.getIdentityId().continueWith(block: {
            (task) -> AnyObject? in
            if (task.error != nil) {
                print("Error: " + task.error!.localizedDescription)
            }
            else {
                // the task result will contain the identity id
                let cognitoId = task.result!
                print("Cognito id: \(cognitoId)")
            }
            return task;
        })

    }

    extension ViewController: AWSCognitoIdentityPasswordAuthentication {

        public func getDetails(_ authenticationInput: AWSCognitoIdentityPasswordAuthenticationInput, passwordAuthenticationCompletionSource: AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails>) {
            print("getDetails(_:authenticationInput:passwordAuthenticationCompletionSource:)")
            self.passwordAuthenticationCompletion = passwordAuthenticationCompletionSource
            DispatchQueue.main.async {
                if (self.userNameText == nil) {
                    self.userNameText = authenticationInput.lastKnownUsername
                    print("userNameText=", self.userNameText as Any)
                }

            }
        }

        func didCompleteStepWithError(_ error: Error?) {

            print("didCompleteStepWithError\n", error as Any)

        }

    }

    extension ViewController: AWSCognitoIdentityInteractiveAuthenticationDelegate {

        func startPasswordAuthentication() -> AWSCognitoIdentityPasswordAuthentication {
            print("startPasswordAuthentication")
            return self
        }

    }
```

<p>Here are the print results in the debug window:</p>

```user= Optional(<AWSCognitoIdentityUser: 0x600002644ab0>)
user.isSignedIn= false
startPasswordAuthentication
getDetails(_:authenticationInput:passwordAuthenticationCompletionSource:)
taskNSString.result= nil
startPasswordAuthentication
getDetails(_:authenticationInput:passwordAuthenticationCompletionSource:)
userNameText= Optional("***")
```

答:
Since you are returning a task(named Task A) inside your continueWith:, the block won't be executed until task(Task A) has completed.

AWSTask documentation
RETURN: A task that will be completed after block has run. If block returns a AWSTask, then the task returned from this method will not be completed until that task is completed.

TL:DR Try returning nil in your continueWith:

Body:
I am trying to get the Identity ID of an AWSCognitoCredentialsProvider but the block doesn't run.

Why does it not run, and what should I check out to investigate this problem? Or what is the solution?

    override func viewDidLoad() {
        super.viewDidLoad()

        //setup service config
        let serviceConfiguration: AWSServiceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: nil)

        //create a pool
        let configuration: AWSCognitoIdentityUserPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: "***", clientSecret: "***", poolId: "us-east-1_***")

        AWSCognitoIdentityUserPool.register(with: serviceConfiguration, userPoolConfiguration: configuration, forKey: "***")
        pool = AWSCognitoIdentityUserPool(forKey: "***")

        pool.delegate = self

        self.user = self.pool.currentUser()
        print("user=", self.user as Any)
        print("user.isSignedIn=", user.isSignedIn)

        let credentialsProvider: AWSCognitoCredentialsProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: "us-east-1:***", identityProviderManager: self.pool)
        let defaultServiceConfiguration: AWSServiceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialsProvider)
        AWSServiceManager.default()!.defaultServiceConfiguration = defaultServiceConfiguration

        let taskNSString: AWSTask<NSString> = credentialsProvider.getIdentityId()
        print("taskNSString.result=", taskNSString.result as Any)

        // Retrieve your Amazon Cognito ID
        credentialsProvider.getIdentityId().continueWith(block: {
            (task) -> AnyObject? in
            if (task.error != nil) {
                print("Error: " + task.error!.localizedDescription)
            }
            else {
                // the task result will contain the identity id
                let cognitoId = task.result!
                print("Cognito id: \(cognitoId)")
            }
            return task;
        })

    }

    extension ViewController: AWSCognitoIdentityPasswordAuthentication {

        public func getDetails(_ authenticationInput: AWSCognitoIdentityPasswordAuthenticationInput, passwordAuthenticationCompletionSource: AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails>) {
            print("getDetails(_:authenticationInput:passwordAuthenticationCompletionSource:)")
            self.passwordAuthenticationCompletion = passwordAuthenticationCompletionSource
            DispatchQueue.main.async {
                if (self.userNameText == nil) {
                    self.userNameText = authenticationInput.lastKnownUsername
                    print("userNameText=", self.userNameText as Any)
                }

            }
        }

        func didCompleteStepWithError(_ error: Error?) {

            print("didCompleteStepWithError\n", error as Any)

        }

    }

    extension ViewController: AWSCognitoIdentityInteractiveAuthenticationDelegate {

        func startPasswordAuthentication() -> AWSCognitoIdentityPasswordAuthentication {
            print("startPasswordAuthentication")
            return self
        }

    }

Here are the print results in the debug window:

user= Optional(<AWSCognitoIdentityUser: 0x600002644ab0>)
user.isSignedIn= false
startPasswordAuthentication
getDetails(_:authenticationInput:passwordAuthenticationCompletionSource:)
taskNSString.result= nil
startPasswordAuthentication
getDetails(_:authenticationInput:passwordAuthenticationCompletionSource:)
userNameText= Optional("***")


问:
Smoke test approach for AWS Lambda
I have many AWS Lambda using Java 8. We are using Blue/Green deployment for all Lambda which is having Smoke/Live aliases. We are using Jenkins to deploy aws lambda with below steps

Check out: which is to checkout lambda source from git.

Build & Unit test with Junit .

Code Coverages with Jacoco

Deploy it using Smoke alias.

Now we want to perform Smoke Test for the lambda against Smoke alias

If smoke test cases passes, we will promote Smoke alias to Live alias.

For the step 5, could you please advice if we have approaches to perform "smoke test" for a lambda?

I would think we need to actually execute the lambda itself (not junit) but if so actual business rules ran and then it can generate many things output to targets such as dynamodb and s3 ...

So share best practices you have for your real project. Thanks.

I'm thinking should I add a special param which will be passed through Smoke tests and then the lambda itself has a logic to deal with that param.

答:
I have struggled with this concept as well.

Assuming you are externalizing your configurations (e.g. DynamoDB tables, S3 locations, etc) via something like environment variables or SSM Parameters:  ideally you would have your "smoke" or staging versions of the Lambda point to smoke test (i.e. non-production) resources.

One problem with using aliases is you can not have different environment variables for different aliases.

With that in mind, the typical approach for smoke/integration testing lambdas is to abandon using aliases deploy the staging resources as different/separate functions from your production resources.

This can be done more easily if you have a SAM/Cloudformation template that can deploy your lambdas and their dependencies so you can easily setup development, smoketest and production stacks.  You will want to create a parameter for a prefix/suffix that you can give the resources to differentiate the different deployments.

When you are satisfied with your smoke testing results, you simply deploy the tested version of the lambda code to your production lambdas.

Title: Smoke test approach for AWS Lambda


问:
Dictionaries and keys
this is the question:

create a dictionary with values such as

```<code>(1: a, 2:b , 3:c 4:d)
</code>```

Write a Python script to add a key to a dictionary.
Write a Python script to sort (ascending and descending) a dictionary by value.
Write a Python script to check if a given key already exists in a dictionary

```<code>dictionary = {
    "a":1,
    "b":2,
    "c":3,
    "d":4,
    "e":5,
    "f":6,
    "g":7,
    "h":8,
    "i":9,
    "j":10
    }
print (dictionary)
def is_key_present(x):
    if x in d:
        print ("key is present in the dictionary.")
    else:
        print ("key is not present in the dictionary.")
</code>```

答:
First Question:

```<code>import operator
dictionary = {
    "a": 3,
    "b": 2,
    "c": 1,
    "d": 4,
    "e": 5,
    "f": 6,
    "g": 7,
    "h": 8,
    "i": 9,
    "j": 10
}

sorted_asc = sorted(dictionary.items(), key=operator.itemgetter(1))
print(sorted_asc)
</code>```

Second Question:

```<code>def key_in(key, dic):
    rett = False
    if key in dic:
        rett = True
    return rett
</code>```

Title: Dictionaries and keys

Body:
this is the question:

create a dictionary with values such as

(1: a, 2:b , 3:c 4:d)

Write a Python script to add a key to a dictionary.
Write a Python script to sort (ascending and descending) a dictionary by value.
Write a Python script to check if a given key already exists in a dictionary

dictionary = {
    "a":1,
    "b":2,
    "c":3,
    "d":4,
    "e":5,
    "f":6,
    "g":7,
    "h":8,
    "i":9,
    "j":10
    }
print (dictionary)
def is_key_present(x):
    if x in d:
        print ("key is present in the dictionary.")
    else:
        print ("key is not present in the dictionary.")

Body:
First Question:

import operator
dictionary = {
    "a": 3,
    "b": 2,
    "c": 1,
    "d": 4,
    "e": 5,
    "f": 6,
    "g": 7,
    "h": 8,
    "i": 9,
    "j": 10
}

sorted_asc = sorted(dictionary.items(), key=operator.itemgetter(1))
print(sorted_asc)

Second Question:

def key_in(key, dic):
    rett = False
    if key in dic:
        rett = True
    return rett