答:
Regarding the error, the reason is that there isn’t the obj/Docker/publish folder or file. (check the answer of Leonid)

The docker-compose.ci.build.yml file is for building the project and the docker-compose.yml file is used for running the project, so you need to build the project through docker-compose.ci.build.yml file with Dokcer-compose task, then build/run image with docker-compose.yml file with Docker-compose task.

There is a thread about docker-compose.ci.build.yml, docker-compose.yml and Dockerfile: Asp.net core with linux docker container

Update:

Refer to these steps to deploy project to Azure:

Create a new build definition

Add Docker Compose task (Docker Compose File: **/docker-compose.ci.build.yml; Action: Run a Docker Compose command; Command:run ci-build)

Add Copy Files task (Source Folder: $(System.DefaultWorkingDirectory)/[your project path]/obj/Docker/publish; Contents: **; Target Folder: $(Build.ArtifactStagingDirectory))

Add Publish Build Artifacts task (Path to publish: $(Build.ArtifactStagingDirectory))

Create a new release definitioin

Add Azure App Service Deploy task (Package or folder: $(System.DefaultWorkingDirectory)/[artifact build definition name]/[artifact name]; Uncheck Publish using Web Deploy option)

Title: Docker compose VSTS task failder

Body:
I'working on Asp.Bet Core 2 app with MSSQL on Linux. I would like to configure CI and CD to Azure.
I defined docker-compose task in Visual Studio Team Services, but I'm getting an error.

2017-11-09T20:24:09.4725450Z ##[section]Starting: Create images
2017-11-09T20:24:09.4801610Z ==============================================================================
2017-11-09T20:24:09.4817660Z Task         : Docker Compose
2017-11-09T20:24:09.4835680Z Description  : Build, push or run multi-container Docker applications. Task can be used with Docker or Azure Container registry.
2017-11-09T20:24:09.4852370Z Version      : 0.4.7
2017-11-09T20:24:09.4867100Z Author       : Microsoft Corporation
2017-11-09T20:24:09.4881820Z Help         : [More Information](https://go.microsoft.com/fwlink/?linkid=848006)
2017-11-09T20:24:09.4897520Z ==============================================================================
2017-11-09T20:24:10.5040990Z [command]/usr/local/bin/docker-compose -f /opt/vsts/work/1/s/docker-compose.yml -f /opt/vsts/work/1/s/docker-compose.ci.build.yml -f /home/vsts/agent/.docker-compose.1510259050468.yml -p Travelingowe build
2017-11-09T20:24:10.8628630Z db uses an image, skipping
2017-11-09T20:24:10.8646610Z Building api
2017-11-09T20:24:10.9373040Z Step 1/7 : FROM microsoft/aspnetcore:2.0
2017-11-09T20:24:12.0041790Z 2.0: Pulling from microsoft/aspnetcore
2017-11-09T20:25:03.6328690Z Digest: sha256:e36cb8d1edcd1bfd7aea0412349482a9c1a601089d76d1a294067f5f7f1098a9
2017-11-09T20:25:03.6497680Z Status: Downloaded newer image for microsoft/aspnetcore:2.0
2017-11-09T20:25:03.6524910Z  ---> e0e49def2506
2017-11-09T20:25:03.6551560Z Step 2/7 : MAINTAINER Maciej Skuratowski <maciejskuratowski@gmail.com>
2017-11-09T20:25:03.7496070Z  ---> Running in e7667861d293
2017-11-09T20:25:03.9222120Z  ---> 24ba03484562
2017-11-09T20:25:03.9436840Z Removing intermediate container e7667861d293
2017-11-09T20:25:03.9458600Z Step 3/7 : ARG source
2017-11-09T20:25:04.0562980Z  ---> Running in 7b57f9fc515f
2017-11-09T20:25:04.2292420Z  ---> 4d07188edf18
2017-11-09T20:25:04.2503550Z Removing intermediate container 7b57f9fc515f
2017-11-09T20:25:04.2581270Z Step 4/7 : WORKDIR /app
2017-11-09T20:25:04.5347440Z  ---> 4546b8dc771f
2017-11-09T20:25:04.5527690Z Removing intermediate container 0a595d10e668
2017-11-09T20:25:04.5558170Z Step 5/7 : EXPOSE 80
2017-11-09T20:25:04.6765650Z  ---> Running in aa273cc9ca2c
2017-11-09T20:25:04.8330020Z  ---> 6dd874db617e
2017-11-09T20:25:04.8619290Z Removing intermediate container aa273cc9ca2c
2017-11-09T20:25:04.8650100Z Step 6/7 : COPY ${source:-obj/Docker/publish} .
2017-11-09T20:25:04.8686070Z Service 'api' failed to build: COPY failed: stat /var/lib/docker/tmp/docker-builder211771018/obj/Docker/publish: no such file or directory
2017-11-09T20:25:04.9064960Z ##[error]db uses an image, skipping
2017-11-09T20:25:04.9127660Z ##[error]Building api
2017-11-09T20:25:04.9175860Z ##[error]Service 'api' failed to build: COPY failed: stat /var/lib/docker/tmp/docker-builder211771018/obj/Docker/publish: no such file or directory
2017-11-09T20:25:04.9258880Z ##[error]/usr/local/bin/docker-compose failed with return code: 1
2017-11-09T20:25:04.9325830Z ##[section]Finishing: Create images

Here's my docker-compose:

version: '3'

services:
  api:
    image: api
    container_name: api
    build:
      context: ./Api
      dockerfile: Dockerfile
    ports:
      - "8000:80"
    depends_on:
      - db
  db:
    image: "microsoft/mssql-server-linux"
    container_name: mssql
    environment:
        SA_PASSWORD: "testtest3030!"
        ACCEPT_EULA: "Y"
        MSSQL_PID: "Developer"
    ports:
      - "127.0.0.1:8001:1433"

and docker-compose.ci.build.yml file:

version: '3'

services:

      ci-build:
        image: microsoft/aspnetcore-build:1.0-1.1
        volumes:
          - .:/src
        working_dir: /src
        command: /bin/bash -c "dotnet restore ./Travelingowe.sln && dotnet publish ./Travelingowe.sln -c Release -o ./obj/Docker/publish"

Also I attached my VSTS docker-compose taks:

Do you have any idea for I'm doing wrong?


来源: stackexchange

问:
convert list of lists with time strings to seconds and find count times between
I have a list of lists with time strings in them (this format "17:04:20"). I want to iterate through the list and count the times with a gap of 5 minutes or greater.

```<code>Eg. [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]
</code>```

In this case the gap would be from 17:08:54 + 5 minutes until 17:50:33.

I've been trying to do this by replacing the : in  the time strings and then turning the value into seconds and putting them sorted into a list of lists. Then I wanted to go through the list and if the next value is more than 300 seconds record this value.

Im having trouble even changing the strings to second can anyone help ?

答:
This code will give the location, time and delay. You can easily count the number of occurences using len().

```<code>import datetime

event_times = [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]
threshold = 5*60

delayed = []
dt_prev_et = None
for i, ets in enumerate(event_times):
    for j, et in enumerate(ets):
        dt_et = datetime.datetime.strptime(et, "%H:%M:%S")
        if dt_prev_et is None:
            dt_prev_et = dt_et
            continue

        delay = (dt_et - dt_prev_et).seconds
        if delay > threshold:
            delayed.append((i, j, et, delay))

        dt_prev_et = dt_et

print(delayed)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a list of lists with time strings in them (this format "17:04:20"). I want to iterate through the list and count the times with a gap of 5 minutes or greater.

Eg. [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]

In this case the gap would be from 17:08:54 + 5 minutes until 17:50:33.

I've been trying to do this by replacing the : in  the time strings and then turning the value into seconds and putting them sorted into a list of lists. Then I wanted to go through the list and if the next value is more than 300 seconds record this value.

Im having trouble even changing the strings to second can anyone help ?

Body:
This code will give the location, time and delay. You can easily count the number of occurences using len().

import datetime

event_times = [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]
threshold = 5*60

delayed = []
dt_prev_et = None
for i, ets in enumerate(event_times):
    for j, et in enumerate(ets):
        dt_et = datetime.datetime.strptime(et, "%H:%M:%S")
        if dt_prev_et is None:
            dt_prev_et = dt_et
            continue

        delay = (dt_et - dt_prev_et).seconds
        if delay > threshold:
            delayed.append((i, j, et, delay))

        dt_prev_et = dt_et

print(delayed)


问:
Gradle build error, Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug' in pom.xml
Hello people i get the following error when iam trying to run my android app:

Gradle build error, Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'
  com.android.build.api.transform.TransformException:com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META/INF/maven/com.squareup.okio/okio/pom.xml

These are my both gradle files:

```<code>  // Top-level build file where you can add configuration options common to
  all sub-projects/modules.

buildscript {
repositories {
    jcenter()

}
dependencies {
    classpath 'com.android.tools.build:gradle:2.1.0'
    classpath 'com.google.gms:google-services:3.1.0'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
 repositories {
    jcenter()
    apply plugin: 'maven'
    maven { url 'https://maven.google.com' }
    maven {url 'https://maven.fabric.io/public'}
 }
 }

task clean(type: Delete) {
   delete rootProject.buildDir
}
</code>```

And this is the other one:

```<code> apply plugin: 'com.android.application'
 android {
  compileSdkVersion 26
  buildToolsVersion "26.0.2"

  defaultConfig {
     applicationId "com.dp.liveupdatestatus"
     minSdkVersion 18
     targetSdkVersion 26
     versionCode 1
     versionName "1.0"
  }
  buildTypes {
     release {
         minifyEnabled false
         proguardFiles getDefaultProguardFile('proguard-android.txt'),
         'proguard-rules.pro'
    }
  }
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'

compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:design:26.1.0'
compile 'com.android.support:recyclerview-v7:26.1.0'
// This is needed for firebase UI
compile 'com.android.support:support-v4:26.1.0'
compile 'com.android.support:customtabs:26.1.0'
compile 'com.android.support:cardview-v7:26.1.0'

compile 'com.google.firebase:firebase-core:11.4.2'
compile 'com.google.firebase:firebase-database:11.4.2'
compile 'com.google.firebase:firebase-storage:11.4.2'
compile 'com.google.firebase:firebase-crash:11.4.2'
compile 'com.google.firebase:firebase-auth:11.4.2'
compile 'com.google.firebase:firebase-messaging:11.4.2'
compile 'com.firebaseui:firebase-ui:3.1.0'
compile 'com.squareup.picasso:picasso:2.5.2'
}
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'
</code>```

Please help!

答:
```<code>android {
......
packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/dependencies.txt'
    exclude 'META-INF/LGPL2.1'
}
}
</code>```

<p>add this to exclude the META inf files </p>

Body:
Hello people i get the following error when iam trying to run my android app:

Gradle build error, Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'
  com.android.build.api.transform.TransformException:com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META/INF/maven/com.squareup.okio/okio/pom.xml

These are my both gradle files:

  // Top-level build file where you can add configuration options common to
  all sub-projects/modules.

buildscript {
repositories {
    jcenter()

}
dependencies {
    classpath 'com.android.tools.build:gradle:2.1.0'
    classpath 'com.google.gms:google-services:3.1.0'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
 repositories {
    jcenter()
    apply plugin: 'maven'
    maven { url 'https://maven.google.com' }
    maven {url 'https://maven.fabric.io/public'}
 }
 }

task clean(type: Delete) {
   delete rootProject.buildDir
}

And this is the other one:

 apply plugin: 'com.android.application'
 android {
  compileSdkVersion 26
  buildToolsVersion "26.0.2"

  defaultConfig {
     applicationId "com.dp.liveupdatestatus"
     minSdkVersion 18
     targetSdkVersion 26
     versionCode 1
     versionName "1.0"
  }
  buildTypes {
     release {
         minifyEnabled false
         proguardFiles getDefaultProguardFile('proguard-android.txt'),
         'proguard-rules.pro'
    }
  }
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'

compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:design:26.1.0'
compile 'com.android.support:recyclerview-v7:26.1.0'
// This is needed for firebase UI
compile 'com.android.support:support-v4:26.1.0'
compile 'com.android.support:customtabs:26.1.0'
compile 'com.android.support:cardview-v7:26.1.0'

compile 'com.google.firebase:firebase-core:11.4.2'
compile 'com.google.firebase:firebase-database:11.4.2'
compile 'com.google.firebase:firebase-storage:11.4.2'
compile 'com.google.firebase:firebase-crash:11.4.2'
compile 'com.google.firebase:firebase-auth:11.4.2'
compile 'com.google.firebase:firebase-messaging:11.4.2'
compile 'com.firebaseui:firebase-ui:3.1.0'
compile 'com.squareup.picasso:picasso:2.5.2'
}
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'

Please help!

Body:
android {
......
packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/dependencies.txt'
    exclude 'META-INF/LGPL2.1'
}
}

add this to exclude the META inf files


问:
How to perform a numerical Laplace and inverse Laplace transforms in Matlab for a discrete input signal?
I want to evaluate the Laplace transform of a discrete stochastic signal I sample from a communication device.

As a simple test case I am trying to use the ilaplace to get the original signal, but I am not sure if my approach is plausible.

```<code>x = sym('x','real');
y = sym('y','real');
t=linspace(0,1000,1000);
f=sin(t);
s = x+i*y;
F_s=sum(f.*exp(-s*t));
ilaplace(F_s)
</code>```

The above might seem silly, though in my real problem I am trying to estimate the medium Green's function which is of the formilaplace(2*F_s/(-s*F_s +f(0))).

I have also tried to use a signal symbolic variable s and it gives me a train of deltas which I am not sure it's correct and what is the error estimation.

```<code>syms s;
F_s = symfun(sum(sin(t).*exp(-s*t)), s);
ilaplace(F_s)
</code>```

答:
Try increasing the number of elements in t to more accurately sample the sine function, or smoothing the signal before calculations. Another problem you face is that the inverse Laplace transform expects a function to be defined for s>0, i.e. up to infinity. You truncate your signal at t=1000, thus the Laplace transform is not going to infinity either.

Judging the documentation of ilaplace it tries to transform each individual term in your array F_s. This has a sum of a thousand entries of some constant times some exponential of the form exp(-s*t), whose inverse transform is a delta pulse, see this Wikipedia page, second entry of the table. Hence, your inverse transform of F_s is a series of a thousand delta pulses, which will presumably be exactly the thousand input points you generated with your sin(t), up to some numerical error which emerged in the forward and backward Laplace transform.

Finally: MATLAB expects, as stated in the documentation, a single symbolic variable s. You made s consist of two symbolic variables. Whilst mathematically correct, MATLAB only takes the first symbolic variable to be the transform variable, thus you get an answer with delta pulses multiplied by some exp(1i*y) function. Using the following code, you at least get rid of that problem (but obviously keep the summation of delta pulses):

```<code>t=linspace(0,1000,1000);
f=sin(t);
syms s
F_s=sum(f.*exp(-s*t));
ilaplace(F_s)
</code>```

Body:
I want to evaluate the Laplace transform of a discrete stochastic signal I sample from a communication device.

As a simple test case I am trying to use the ilaplace to get the original signal, but I am not sure if my approach is plausible.

x = sym('x','real');
y = sym('y','real');
t=linspace(0,1000,1000);
f=sin(t);
s = x+i*y;
F_s=sum(f.*exp(-s*t));
ilaplace(F_s)

The above might seem silly, though in my real problem I am trying to estimate the medium Green's function which is of the formilaplace(2*F_s/(-s*F_s +f(0))).

I have also tried to use a signal symbolic variable s and it gives me a train of deltas which I am not sure it's correct and what is the error estimation.

syms s;
F_s = symfun(sum(sin(t).*exp(-s*t)), s);
ilaplace(F_s)

Body:
Try increasing the number of elements in t to more accurately sample the sine function, or smoothing the signal before calculations. Another problem you face is that the inverse Laplace transform expects a function to be defined for s>0, i.e. up to infinity. You truncate your signal at t=1000, thus the Laplace transform is not going to infinity either.

Judging the documentation of ilaplace it tries to transform each individual term in your array F_s. This has a sum of a thousand entries of some constant times some exponential of the form exp(-s*t), whose inverse transform is a delta pulse, see this Wikipedia page, second entry of the table. Hence, your inverse transform of F_s is a series of a thousand delta pulses, which will presumably be exactly the thousand input points you generated with your sin(t), up to some numerical error which emerged in the forward and backward Laplace transform.

Finally: MATLAB expects, as stated in the documentation, a single symbolic variable s. You made s consist of two symbolic variables. Whilst mathematically correct, MATLAB only takes the first symbolic variable to be the transform variable, thus you get an answer with delta pulses multiplied by some exp(1i*y) function. Using the following code, you at least get rid of that problem (but obviously keep the summation of delta pulses):

t=linspace(0,1000,1000);
f=sin(t);
syms s
F_s=sum(f.*exp(-s*t));
ilaplace(F_s)


问:
Grails 3 JSON Views custom rendering one-to-many associations
Okay I have tried everything I know to custom render a one-to-many association with JSON views and failed miserably.

Here's what part of my ticket domain looks like (All good here) ...

```<code>class TttTicket {

    String title
    String number
    String description
    TttUser assignee
    String priority
    String status
    TttUser creator

    Date dateCreated
    Date lastUpdated

    static mappedBy = [subscribers : 'none', creator:'none']

    static belongsTo = [project:TttProject, creator:TttUser]
    static hasMany = [subscribers: TttUser]

... blar blar
}
</code>```

Here's my associated gson rendering template...

```<code>import ttt_api_server.TttTicket

model {
    TttTicket tttTicket
}

json g.render(tttTicket, [excludes:['creator','subscribers','project']]){
    creator {
        id tttTicket.creator.id
        name tttTicket.creator.name
        email tttTicket.creator.email
    }

    project{
        id tttTicket.project.id
        name tttTicket.project.name
    }
}
</code>```

... which is working nicely so far. I want to now restricted the output of the properties for each of the subscribers.

How do I rotate over these? For example...

```<code>import ttt_api_server.TttTicket

model {
    TttTicket tttTicket
}

json g.render(tttTicket, [excludes:['creator','subscribers','project']]){
    creator {
        id tttTicket.creator.id
        name tttTicket.creator.name
        email tttTicket.creator.email
    }
    subscibers g.render(){
        tttTicket.subscribers.each {sub ->
            return {
                name sub.name
            }
        }
    }
    project{
        id tttTicket.project.id
        name tttTicket.project.name
    }
}
</code>```

This does not seem to be documented anywhere. I would like to controller the JSON out put of each subscriber at this level. Not at the domain level as I may need to change the property output depending on my JSON requirements.

Please help :-(

答:
If I understand this correctly, when you do a REST call on ticket, you wanted the domain object that is inside the hasMany relationship to show a specified properties (in this case its subscribers). But when you call directly on the subscribers, you wanted all the properties.

You can create a map first and then render the objects based on the map created (have a look at this).
In your case:

```<code>import ttt_api_server.TttTicket

model {
    TttTicket tttTicket
}

json g.render(tttTicket, [excludes:['creator','subscribers','project']]){
    creator {
        id tttTicket.creator.id
        name tttTicket.creator.name
        email tttTicket.creator.email
    }

    def s = tttTicket.subsribers.collect {
        [
            id: it.id,
            name: it.name
        ]
    }

    subscribers s //this part is doing the rendering

    project{
        id tttTicket.project.id
        name tttTicket.project.name
    }
}
</code>```

Body:
Okay I have tried everything I know to custom render a one-to-many association with JSON views and failed miserably.

Here's what part of my ticket domain looks like (All good here) ...

class TttTicket {

    String title
    String number
    String description
    TttUser assignee
    String priority
    String status
    TttUser creator

    Date dateCreated
    Date lastUpdated

    static mappedBy = [subscribers : 'none', creator:'none']

    static belongsTo = [project:TttProject, creator:TttUser]
    static hasMany = [subscribers: TttUser]

... blar blar
}

Here's my associated gson rendering template...

import ttt_api_server.TttTicket

model {
    TttTicket tttTicket
}

json g.render(tttTicket, [excludes:['creator','subscribers','project']]){
    creator {
        id tttTicket.creator.id
        name tttTicket.creator.name
        email tttTicket.creator.email
    }

    project{
        id tttTicket.project.id
        name tttTicket.project.name
    }
}

... which is working nicely so far. I want to now restricted the output of the properties for each of the subscribers.

How do I rotate over these? For example...

import ttt_api_server.TttTicket

model {
    TttTicket tttTicket
}

json g.render(tttTicket, [excludes:['creator','subscribers','project']]){
    creator {
        id tttTicket.creator.id
        name tttTicket.creator.name
        email tttTicket.creator.email
    }
    subscibers g.render(){
        tttTicket.subscribers.each {sub ->
            return {
                name sub.name
            }
        }
    }
    project{
        id tttTicket.project.id
        name tttTicket.project.name
    }
}

This does not seem to be documented anywhere. I would like to controller the JSON out put of each subscriber at this level. Not at the domain level as I may need to change the property output depending on my JSON requirements.

Please help :-(

Body:
If I understand this correctly, when you do a REST call on ticket, you wanted the domain object that is inside the hasMany relationship to show a specified properties (in this case its subscribers). But when you call directly on the subscribers, you wanted all the properties.

You can create a map first and then render the objects based on the map created (have a look at this).
In your case:

import ttt_api_server.TttTicket

model {
    TttTicket tttTicket
}

json g.render(tttTicket, [excludes:['creator','subscribers','project']]){
    creator {
        id tttTicket.creator.id
        name tttTicket.creator.name
        email tttTicket.creator.email
    }

    def s = tttTicket.subsribers.collect {
        [
            id: it.id,
            name: it.name
        ]
    }

    subscribers s //this part is doing the rendering

    project{
        id tttTicket.project.id
        name tttTicket.project.name
    }
}


问:
How do I receive both json and binary data in a post to my webapi controller?
I have a class I created called Event. My Event class contains a list of Documents. Document is another class I've created. Each Document class contains a class called DocumentData which has a property called FileData of type byte[].

So it looks like this:

myEventObj.Documents[0].DocumentData.FileData

Right now my controller that accepts new or updated Events only accepts json data, which is fine for everything in my Event class except for FileData.

I have another controller which accepts file uploads. The problem is, there's no easy way for me to link the binary file data accepted by my second controller and pair it with the FileData property of an Event sent to my first controller. How do I combine them so there's only one call to my web service to save both an Event along with any file data?

Here's my Post and Put functions of my Event controller:

```<code>[HttpPost]
public IHttpActionResult Post(Event coreEvent) {
    coreEvent.PrepareToPersist();
    _unitOfWork.Events.Add(coreEvent);
    _unitOfWork.Complete();
    return Created("api/events/" + coreEvent.EventId, coreEvent);
}

[HttpPut]
public IHttpActionResult Put(Event coreEvent) {
    coreEvent.PrepareToPersist();
    _unitOfWork.Events.Update(coreEvent);
    _unitOfWork.Complete();
    return Ok(coreEvent);
}
</code>```

Here's the Post function for my controller that handles file uploads:

```<code>[HttpPost]
public async Task<IHttpActionResult> Post() {
    if (!Request.Content.IsMimeMultipartContent()) {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    var provider = new MultipartMemoryStreamProvider();

    try {
        await Request.Content.ReadAsMultipartAsync(provider);

        foreach (var file in provider.Contents) {
            string filename = file.Headers.ContentDisposition.FileName.Trim('\"');
            byte[] buffer = await file.ReadAsByteArrayAsync();
        }
        return Ok();
    }
    catch (System.Exception e) {
        return InternalServerError(e);
    }
}
</code>```

How do I put these together?

答:
Well usually I prefer it in two methods to support multi ajax upload files, so the second method will support uploading files by Ajax and will return a unique key for the uploaded file, after you saving it somewhere on the server and adding a record for it in the database ( ex: attachments table),

and when you call the first method for posing event , your object myEventObj.Documents[0].DocumentData.FileData will contains the returned key from the second method, so probably your object will be, myEventObj.Documents as List of string (files keys)

Thanks

Body:
I have a class I created called Event. My Event class contains a list of Documents. Document is another class I've created. Each Document class contains a class called DocumentData which has a property called FileData of type byte[].

So it looks like this:

myEventObj.Documents[0].DocumentData.FileData

Right now my controller that accepts new or updated Events only accepts json data, which is fine for everything in my Event class except for FileData.

I have another controller which accepts file uploads. The problem is, there's no easy way for me to link the binary file data accepted by my second controller and pair it with the FileData property of an Event sent to my first controller. How do I combine them so there's only one call to my web service to save both an Event along with any file data?

Here's my Post and Put functions of my Event controller:

[HttpPost]
public IHttpActionResult Post(Event coreEvent) {
    coreEvent.PrepareToPersist();
    _unitOfWork.Events.Add(coreEvent);
    _unitOfWork.Complete();
    return Created("api/events/" + coreEvent.EventId, coreEvent);
}

[HttpPut]
public IHttpActionResult Put(Event coreEvent) {
    coreEvent.PrepareToPersist();
    _unitOfWork.Events.Update(coreEvent);
    _unitOfWork.Complete();
    return Ok(coreEvent);
}

Here's the Post function for my controller that handles file uploads:

[HttpPost]
public async Task<IHttpActionResult> Post() {
    if (!Request.Content.IsMimeMultipartContent()) {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    var provider = new MultipartMemoryStreamProvider();

    try {
        await Request.Content.ReadAsMultipartAsync(provider);

        foreach (var file in provider.Contents) {
            string filename = file.Headers.ContentDisposition.FileName.Trim('\"');
            byte[] buffer = await file.ReadAsByteArrayAsync();
        }
        return Ok();
    }
    catch (System.Exception e) {
        return InternalServerError(e);
    }
}

How do I put these together?


问:
Where does cookies get stored by office word add-in on mac
i have stored the data in cookies by office task pane word add-in. to store the data in cookies i have used the following function.

```<code>   function setCookie(cname, cvalue, exdays)
        {
            var d = new Date();
            d.setTime(d.getTime() + (exdays*24*60*60*1000));
            var expires = "expires="+d.toUTCString();
            document.cookie = cname + "=" + cvalue + "; " + expires;
        }
</code>```

This function stores the data. But when i'm trying to clear the cookies it doen't get cleared. I have cleared the history and delete the cookies of safari browser, i have cleared the cache and cookies at location ~/Library/caches and ~/Library/cookies but still cookies are not cleared. If anyone know the exact location where the cookies get stored, please let me know.

Thanks in advance.

答: You can try to clear Internet explorer cookies as it use this browser internally.</p>

Body:
i have stored the data in cookies by office task pane word add-in. to store the data in cookies i have used the following function.

   function setCookie(cname, cvalue, exdays)
        {
            var d = new Date();
            d.setTime(d.getTime() + (exdays*24*60*60*1000));
            var expires = "expires="+d.toUTCString();
            document.cookie = cname + "=" + cvalue + "; " + expires;
        }

This function stores the data. But when i'm trying to clear the cookies it doen't get cleared. I have cleared the history and delete the cookies of safari browser, i have cleared the cache and cookies at location ~/Library/caches and ~/Library/cookies but still cookies are not cleared. If anyone know the exact location where the cookies get stored, please let me know.

Thanks in advance.


问:
My Java program stopped sending emails using my gmail Account
I searched several related posts here and in other places, but none of them solved my problem. I have a program that sends emails to a set of people using "javamail API". It worked fine once. Today I needed again, but I cannot send any email... My sendEmail method is the following:

```<code>public void sendEmail(String userName, String password, String toAddress,
       String subject, String message, String[] attachFiles)
       throws AddressException, MessagingException {

     // sets SMTP properties
    Properties properties = new Properties();
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", "587");
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.user", userName);
    properties.put("mail.password", password);

    // creates a new session with an authenticator
    Authenticator auth = new SMTPAuthenticator(userName, password);
    Session session = Session.getInstance(properties, auth);

    // creates a new e-mail message
    MimeMessage msg = new MimeMessage(session);

    try {
        msg.setFrom(new InternetAddress(userName, "My name"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    InternetAddress[] toAddresses = {new InternetAddress(toAddress)};
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    msg.setSubject(subject);
    msg.setSentDate(new Date());

    // creates message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(message, "text/html");

    // creates multi-part
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // adds attachments
    if (attachFiles != null && attachFiles.length > 0) {
        for (String filePath : attachFiles) {
            addAttachment(multipart, filePath);
        }
    }

    // sets the multi-part as e-mail's content
    msg.setContent(multipart);

    // sends the e-mail
    Transport.send(msg);

}
</code>```

So, now the attempt to call this method I got the following error
(I'm using jdk 1.7.0_21):

```<code>Sending email Failed...

javax.mail.MessagingException: Could not convert socket to TLS;
  nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1907)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:666)
    at javax.mail.Service.connect(Service.java:367)
    at javax.mail.Service.connect(Service.java:226)
    at javax.mail.Service.connect(Service.java:175)
    at javax.mail.Transport.send0(Transport.java:253)
    at javax.mail.Transport.send(Transport.java:124)
    at EmailSender.sendEmail(EmailSender.java:86)
    at CFP_LaWasp_EmailSender.sendCFPLaWasp(CFP_LaWasp_EmailSender.java:178)
    at CFP_LaWasp_EmailSender.main(CFP_LaWasp_EmailSender.java:220)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1886)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:528)
    at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:465)
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1902)
    ... 9 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
    at sun.security.validator.Validator.validate(Validator.java:260)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323)
    ... 19 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
    ... 25 more
</code>```

I don't know how to solve this issue, since it used to work before... Also, I don't know if my Gmail has something to do with this (if it blocked this access...)

I appreciate any help.

答:
I had this problem with java 8. After updating this property problem solved

properties.put("mail.smtp.ssl.trust", "smtp.gmail.com")

if used spring boot in application.property

spring.mail.properties.mail.smtp.ssl.trust = smtp.gmail.com

Body:
I searched several related posts here and in other places, but none of them solved my problem. I have a program that sends emails to a set of people using "javamail API". It worked fine once. Today I needed again, but I cannot send any email... My sendEmail method is the following:

public void sendEmail(String userName, String password, String toAddress,
       String subject, String message, String[] attachFiles)
       throws AddressException, MessagingException {

     // sets SMTP properties
    Properties properties = new Properties();
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", "587");
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.user", userName);
    properties.put("mail.password", password);

    // creates a new session with an authenticator
    Authenticator auth = new SMTPAuthenticator(userName, password);
    Session session = Session.getInstance(properties, auth);

    // creates a new e-mail message
    MimeMessage msg = new MimeMessage(session);

    try {
        msg.setFrom(new InternetAddress(userName, "My name"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    InternetAddress[] toAddresses = {new InternetAddress(toAddress)};
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    msg.setSubject(subject);
    msg.setSentDate(new Date());

    // creates message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(message, "text/html");

    // creates multi-part
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // adds attachments
    if (attachFiles != null && attachFiles.length > 0) {
        for (String filePath : attachFiles) {
            addAttachment(multipart, filePath);
        }
    }

    // sets the multi-part as e-mail's content
    msg.setContent(multipart);

    // sends the e-mail
    Transport.send(msg);

}

So, now the attempt to call this method I got the following error
(I'm using jdk 1.7.0_21):

Sending email Failed...

javax.mail.MessagingException: Could not convert socket to TLS;
  nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1907)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:666)
    at javax.mail.Service.connect(Service.java:367)
    at javax.mail.Service.connect(Service.java:226)
    at javax.mail.Service.connect(Service.java:175)
    at javax.mail.Transport.send0(Transport.java:253)
    at javax.mail.Transport.send(Transport.java:124)
    at EmailSender.sendEmail(EmailSender.java:86)
    at CFP_LaWasp_EmailSender.sendCFPLaWasp(CFP_LaWasp_EmailSender.java:178)
    at CFP_LaWasp_EmailSender.main(CFP_LaWasp_EmailSender.java:220)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1886)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:528)
    at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:465)
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1902)
    ... 9 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
    at sun.security.validator.Validator.validate(Validator.java:260)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323)
    ... 19 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
    ... 25 more

I don't know how to solve this issue, since it used to work before... Also, I don't know if my Gmail has something to do with this (if it blocked this access...)

I appreciate any help.


问:
Make view round after autolayout
I have a tableview with custom cells which are built from storyboard with an identifier using AutoLayout.

One of the subviews needs to be round (layer.cornerRadius = width/2), it is a square in the beginning.

I have tried in layoutSubviews() but it seems to be called before AutoLayout changes its size... same thing for didMoveToSuperview()

Where is the proper function to update things like this to my subviews after AutoLayout has changed their sizes?

```<code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell_small") as! Cell
    ...
    return cell
}

// In Cell

override func layoutSubviews() {
    rankLabel.layer.cornerRadius = rankLabel.bounds.width/2
    rankLabel.layer.masksToBounds = true
}

override func didMoveToSuperview() {
    rankLabel.layer.cornerRadius = rankLabel.bounds.width/2
    rankLabel.layer.masksToBounds = true
}
</code>```

Result:

答:
I had the same issue with my imageview so i resolved it by sub-classing UIImageView.

```<code>@interface MyImageView : UIImageView

@end
</code>```

```<code>@implementation MyImageView

-(void)layoutSubviews
{
    [super layoutSubviews];
    self.layer.cornerRadius = self.bounds.size.width / 2.0;
}
@end
</code>```

Title: Make view round after autolayout

Body:
I have a tableview with custom cells which are built from storyboard with an identifier using AutoLayout.

One of the subviews needs to be round (layer.cornerRadius = width/2), it is a square in the beginning.

I have tried in layoutSubviews() but it seems to be called before AutoLayout changes its size... same thing for didMoveToSuperview()

Where is the proper function to update things like this to my subviews after AutoLayout has changed their sizes?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell_small") as! Cell
    ...
    return cell
}

// In Cell

override func layoutSubviews() {
    rankLabel.layer.cornerRadius = rankLabel.bounds.width/2
    rankLabel.layer.masksToBounds = true
}

override func didMoveToSuperview() {
    rankLabel.layer.cornerRadius = rankLabel.bounds.width/2
    rankLabel.layer.masksToBounds = true
}

Result:

Body:
I had the same issue with my imageview so i resolved it by sub-classing UIImageView.

@interface MyImageView : UIImageView

@end

@implementation MyImageView

-(void)layoutSubviews
{
    [super layoutSubviews];
    self.layer.cornerRadius = self.bounds.size.width / 2.0;
}
@end


问:
How to run my python script on docker?
I am trying to run my python script on docker. I tried different ways to do it but not able to run it on docker. My python script is given below:

```<code>import os

print ('hello')
</code>```

I have already installed docker on my mac. But i want to know how i can make images and then push it to docker after that i wanna pull and run my script on docker itself.

答:
Alright, first create a specific project directory for your docker image. For example:

```<code>mkdir /home/pi/Desktop/teasr/capturing
</code>```

Copy your dockerfile and script in there and change the current context to this directory.

```<code>cp /home/pi/Desktop/teasr/capturing.py /home/pi/Desktop/teasr/dockerfile /home/pi/Desktop/teasr/capturing/

cd /home/pi/Desktop/teasr/capturing
</code>```

This is for best practice, as the first thing the docker-engine does on build, is read the whole current context.

Next we'll take a look at your dockerfile. It should look something like this now:

```<code>FROM python:latest

WORKDIR /usr/local/bin

COPY capturing.py .

CMD ["capturing.py", "-OPTIONAL_FLAG"]
</code>```

The next thing you need to do is build it with a smart name. Using dots is generally discouraged.

```<code>docker build -t pulkit/capturing:1.0 .
</code>```

Next thing is to just run the image like you've done.

```<code>docker run -ti --name capturing pulkit/capturing:1.0
</code>```

The script now get executed inside the container and will probably exit upon completion.

Edit after finding the problem that created the following error:

```<code>standard_init_linux.go:195: exec user process caused "exec format error"
</code>```

There's a different architecture beneath raspberry pi's (ARM instead of x86_64), which COULD'VE BEEN the problem, but wasn't. If that would've been the problem, a switch of the parent image to FROM armhf/python would've been enough.

Source

BUT! The error kept occurring.

So the solution to this problem is a simple missing Sha-Bang on top of the python script. The first line in the script needs to be #!/usr/bin/env python and that should solve the problem.

Source

Title: How to run my python script on docker?

Body:
I am trying to run my python script on docker. I tried different ways to do it but not able to run it on docker. My python script is given below:

import os

print ('hello')

I have already installed docker on my mac. But i want to know how i can make images and then push it to docker after that i wanna pull and run my script on docker itself.

Body:
Alright, first create a specific project directory for your docker image. For example:

mkdir /home/pi/Desktop/teasr/capturing

Copy your dockerfile and script in there and change the current context to this directory.

cp /home/pi/Desktop/teasr/capturing.py /home/pi/Desktop/teasr/dockerfile /home/pi/Desktop/teasr/capturing/

cd /home/pi/Desktop/teasr/capturing

This is for best practice, as the first thing the docker-engine does on build, is read the whole current context.

Next we'll take a look at your dockerfile. It should look something like this now:

FROM python:latest

WORKDIR /usr/local/bin

COPY capturing.py .

CMD ["capturing.py", "-OPTIONAL_FLAG"]

The next thing you need to do is build it with a smart name. Using dots is generally discouraged.

docker build -t pulkit/capturing:1.0 .

Next thing is to just run the image like you've done.

docker run -ti --name capturing pulkit/capturing:1.0

The script now get executed inside the container and will probably exit upon completion.

Edit after finding the problem that created the following error:

standard_init_linux.go:195: exec user process caused "exec format error"

There's a different architecture beneath raspberry pi's (ARM instead of x86_64), which COULD'VE BEEN the problem, but wasn't. If that would've been the problem, a switch of the parent image to FROM armhf/python would've been enough.

Source

BUT! The error kept occurring.

So the solution to this problem is a simple missing Sha-Bang on top of the python script. The first line in the script needs to be #!/usr/bin/env python and that should solve the problem.

Source

ContentLicense: CC BY-SA 4.0


问:
Efficient way to define new variables by iterating a dictionary (Julia)
Consider a dictionary d in Julia which contains a thousand of keys. Each key is a symbol and each value is an array. I can access to the value associated with the symbol :S1 and assign it to the variable k1 via

k1 = d[:S1]

Now assume I want to define the new variables k2, k3, k4, ..., k10 by repeating the same procedure for the special keys :S1 ... :S10 (not for all the keys in the dictionary). What is the most efficient way to do it? I have the impression this can be solved using metaprogramming but not sure about that.

答:
The easy way is to use Parameters.jl.

```<code>using Parameters
d = Dict{Symbol,Any}(:a=>5.0,:b=>2,:c=>"Hi!")
@unpack a, c = d
a == 5.0 #true
c == "Hi!" #true
</code>```

BTW, this doesn't use eval.

Body:
The easy way is to use Parameters.jl.

using Parameters
d = Dict{Symbol,Any}(:a=>5.0,:b=>2,:c=>"Hi!")
@unpack a, c = d
a == 5.0 #true
c == "Hi!" #true

BTW, this doesn't use eval.