问:
DocuSign PHP API Creating Envelope from Template then add Document
we are attempting our first DocuSign API Project and have hit a snag.  We're using PHP API for DocuSign, and we are attempting to create an envelope from a template that has static documents inside it, then add one other custom-generated document, then send the envelope.  But we can't figure out how to make it work.

We originally tried creating the envelope, apply the template, then add the static document, then upload/sending the envelope, which only sends the template.  Then, after research, tried creating the envelope, apply the template, upload the envelope, add the static document then sending, which only sent the static pages too.

Here's our current code we're using:

    public function send($signer_name,$signer_email, $cc_name, $cc_email, $template_id,$email_subject, $extrapdf = null) {
        $this->checkToken();
        $sign_here = new \DocuSign\eSign\Model\SignHere([
        'anchor_string' => '/sn1/', 'anchor_units' =>  'pixels',
        'anchor_y_offset' => '10', 'anchor_x_offset' => '20']);

        //create roles for signers

        $templateRole = new DocuSign\eSign\Model\TemplateRole();
        $templateRole->setEmail($signer_email);
        $templateRole->setName($signer_name);
        $templateRole->setRoleName('Signer 1');
        $templateRole->setTabs(new \DocuSign\eSign\Model\Tabs(['sign_here_tabs' => [$sign_here]]));

        $templateRole2 = new DocuSign\eSign\Model\TemplateRole();
        $templateRole2->setEmail($cc_email);
        $templateRole2->setName($cc_name);
        $templateRole2->setRoleName('Signer 2');
        $templateRole2->setTabs(new \DocuSign\eSign\Model\Tabs(['sign_here_tabs' => [$sign_here]]));

        //create envelope definition
        $envelop_definition = new DocuSign\eSign\Model\EnvelopeDefinition();
        //set template to be used on envelope
        $envelop_definition->setTemplateId($template_id);
        //set email subject on envelope
        $envelop_definition->setEmailSubject($email_subject);
        //apply template roles from above to envelope
        $envelop_definition->setTemplateRoles(array($templateRole, $templateRole2));
        //create new instance of envelope API
        $envelopeApi = new DocuSign\eSign\Api\EnvelopesApi(self::$apiClient);
        //go ahead and create the envelope at DocuSign
        $results = $envelopeApi->createEnvelope(self::$accountID, $envelop_definition);
        //get the created envelope Envelope ID
        $envelopeId = $results['envelope_id'];

        //create another envelope definition.
        $envelop_definition = new DocuSign\eSign\Model\EnvelopeDefinition();
        //see if we have an additional PDF to add to the envelope created above.
        if ($extrapdf != null) {
            //if so, base64 encode it.
            $extrapdf64 = base64_encode($extrapdf);
            //create a new document
            $document = new DocuSign\eSign\Model\Document();
            $document->setDocumentBase64($extrapdf64);
            $document->setName("HomeownershipCounseling.pdf");
            $document->setDocumentId("1");
            $document->setFileExtension("PDF");
            //attach document to envelope definition.
            $envelop_definition->setDocuments([$document]);
            //update the envelope definition to sent to get DocuSign to actually send the envelope.
            $envelop_definition->setStatus('sent');
            //apply changes to the original envelope above.
            $results = $envelopeApi->update(self::$accountID, $envelopeId, $envelop_definition);
        }
        return $results;
    }
```

The envelope does send, but it only sends the static document that was in the template.  We're expecting the static document in the template AND the dynamically generated PDF to both be in the DocuSign Envelope.

Thanks!

答:
Got this figured out... posting here in case anyone is ever interested.  Thank you!

  public function send($signer_name,$signer_email, $cc_name, $cc_email, $template_id,$email_subject, $extrapdf = null) {
        $this->checkToken();

        //create roles for signers

        $signer1 = new \DocuSign\eSign\Model\Signer([
            'email' => $signer_email, 'name' => $signer_name,
            'role_name' => "Signer 1", 'recipient_id' => "1"
        ]);

        $signer2 = new \DocuSign\eSign\Model\Signer([
            'email' => $cc_email, 'name' => $cc_name,
            'role_name' => "Signer 2", 'recipient_id' => "2"

        ]);

        $recipients_server_template = new \DocuSign\eSign\Model\Recipients([
            'signers' => [$signer1,$signer2]]);

        //create composite template
        $comp_template1 = new \DocuSign\eSign\Model\CompositeTemplate([
            'composite_template_id' => "1",
            'server_templates' => [
                new \DocuSign\eSign\Model\ServerTemplate([
                    'sequence' => "1", 'template_id' => $template_id])
            ],
            # Add the roles via an inlineTemplate
            'inline_templates' => [
                new \DocuSign\eSign\Model\InlineTemplate([
                    'sequence' => "1",
                    'recipients' => $recipients_server_template])
            ]

        ]);

        //create new document to be added
        $doc1_b64 = base64_encode($extrapdf);
        $doc1 = new DocuSign\eSign\Model\Document([
            'document_base64' => $doc1_b64,
            'name' => 'HomeownershipCounseling', # can be different from
                                                 # actual file name
            'file_extension' => 'pdf', 'document_id' =>'1']);

        $comp_template2 = new DocuSign\eSign\Model\CompositeTemplate([
            'composite_template_id' => "2",
            # Add the recipients via an inlineTemplate
            'inline_templates' => [
                new \DocuSign\eSign\Model\InlineTemplate([
                    'sequence' => "2"])
            ],
            'document' => $doc1]);

        //create envelope definition
        $envelop_definition = new DocuSign\eSign\Model\EnvelopeDefinition();
        //set email subject on envelope
        $envelop_definition->setEmailSubject($email_subject);
        $envelop_definition->setCompositeTemplates(array($comp_template1, $comp_template2));
        $envelop_definition->setStatus('sent');
        //create new instance of envelope API
        $envelopeApi = new DocuSign\eSign\Api\EnvelopesApi(self::$apiClient);
        //go ahead and create the envelope at DocuSign
        $results = $envelopeApi->createEnvelope(self::$accountID, $envelop_definition);
        //get the created envelope Envelope ID
        $envelopeId = $results['envelope_id'];

        return $results;
    }

```

Body:
we are attempting our first DocuSign API Project and have hit a snag.  We're using PHP API for DocuSign, and we are attempting to create an envelope from a template that has static documents inside it, then add one other custom-generated document, then send the envelope.  But we can't figure out how to make it work.

We originally tried creating the envelope, apply the template, then add the static document, then upload/sending the envelope, which only sends the template.  Then, after research, tried creating the envelope, apply the template, upload the envelope, add the static document then sending, which only sent the static pages too.

Here's our current code we're using:

    public function send($signer_name,$signer_email, $cc_name, $cc_email, $template_id,$email_subject, $extrapdf = null) {
        $this->checkToken();
        $sign_here = new \DocuSign\eSign\Model\SignHere([
        'anchor_string' => '/sn1/', 'anchor_units' =>  'pixels',
        'anchor_y_offset' => '10', 'anchor_x_offset' => '20']);

        //create roles for signers

        $templateRole = new DocuSign\eSign\Model\TemplateRole();
        $templateRole->setEmail($signer_email);
        $templateRole->setName($signer_name);
        $templateRole->setRoleName('Signer 1');
        $templateRole->setTabs(new \DocuSign\eSign\Model\Tabs(['sign_here_tabs' => [$sign_here]]));

        $templateRole2 = new DocuSign\eSign\Model\TemplateRole();
        $templateRole2->setEmail($cc_email);
        $templateRole2->setName($cc_name);
        $templateRole2->setRoleName('Signer 2');
        $templateRole2->setTabs(new \DocuSign\eSign\Model\Tabs(['sign_here_tabs' => [$sign_here]]));

        //create envelope definition
        $envelop_definition = new DocuSign\eSign\Model\EnvelopeDefinition();
        //set template to be used on envelope
        $envelop_definition->setTemplateId($template_id);
        //set email subject on envelope
        $envelop_definition->setEmailSubject($email_subject);
        //apply template roles from above to envelope
        $envelop_definition->setTemplateRoles(array($templateRole, $templateRole2));
        //create new instance of envelope API
        $envelopeApi = new DocuSign\eSign\Api\EnvelopesApi(self::$apiClient);
        //go ahead and create the envelope at DocuSign
        $results = $envelopeApi->createEnvelope(self::$accountID, $envelop_definition);
        //get the created envelope Envelope ID
        $envelopeId = $results['envelope_id'];

        //create another envelope definition.
        $envelop_definition = new DocuSign\eSign\Model\EnvelopeDefinition();
        //see if we have an additional PDF to add to the envelope created above.
        if ($extrapdf != null) {
            //if so, base64 encode it.
            $extrapdf64 = base64_encode($extrapdf);
            //create a new document
            $document = new DocuSign\eSign\Model\Document();
            $document->setDocumentBase64($extrapdf64);
            $document->setName("HomeownershipCounseling.pdf");
            $document->setDocumentId("1");
            $document->setFileExtension("PDF");
            //attach document to envelope definition.
            $envelop_definition->setDocuments([$document]);
            //update the envelope definition to sent to get DocuSign to actually send the envelope.
            $envelop_definition->setStatus('sent');
            //apply changes to the original envelope above.
            $results = $envelopeApi->update(self::$accountID, $envelopeId, $envelop_definition);
        }
        return $results;
    }

The envelope does send, but it only sends the static document that was in the template.  We're expecting the static document in the template AND the dynamically generated PDF to both be in the DocuSign Envelope.

Thanks!


来源: stackexchange

问:
Whats is the meaning of "rel" in the optional elements such as collectionResourceRel in RepositoryRestResource annotation?
Can you please help me understand the meaning of "rel" mentioned optional element of RepositoryRestResource annotation's collectionResourceRel?
I have gone through Java Docs here.

Below is what is written in the documentation.

collectionResourceRel The rel value to use when generating links to
  the collection resource.

答:
In a HATEOAS API, rel "describes how the current context (source) is related to the target resource"

https://restfulapi.net/hateoas/

ContentLicense: CC BY-SA 4.0


问:
How to create a custom EditText layout?
I want to create an EditText like  the Image below.

This is what I want to achieve

This is my code (in the xml file of the layout):

<EditText
            android:id="@+id/newThoughtThoughtText"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp"
            android:background="@drawable/lines"
            android:gravity="top"
            android:hint="@string/thought_first_text"
            android:inputType="textMultiLine"
            android:maxLines="15"
            android:textColor="@color/color_gray"   />
```

<p>I have created a custom drawable layout file. But this only enables me to have one line at the end, and I need several lines inside the EditText.
How can I do this?</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">
            <stroke
            android:width="1dp"
            android:color="@color/color_gray" />
        </shape>
    </item>
</layer-list>
</code>```

Thanks in advance!

答:
To achieve this you have to make changes in your drawable class which you have created.

```<code><inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetLeft="-2dp"
    android:insetRight="-2dp"
    android:insetTop="-2dp">

    <shape android:shape="rectangle" >
        <stroke
            android:width="1dp"
            android:color="#000000" />
        <solid android:color="@color/md_grey_200" />
    </shape>

</inset>
</code>```

This will give you border bottom and you can change color according to your requirement.
If you don't want to give border to the each EditText you can add one View after each EditText like this.

```<code>                    <View
                    style="@style/MenuDivider"
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:layout_marginEnd="5dp"
                    android:layout_marginStart="5dp"
                    android:layout_marginTop="15dp"
                    android:background="@color/black"/>
</code>```

You can change the view height according and background to you.
Hope this will help you.

Title: How to create a custom EditText layout?

Body:
I want to create an EditText like  the Image below.

This is what I want to achieve

This is my code (in the xml file of the layout):

<EditText
            android:id="@+id/newThoughtThoughtText"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp"
            android:background="@drawable/lines"
            android:gravity="top"
            android:hint="@string/thought_first_text"
            android:inputType="textMultiLine"
            android:maxLines="15"
            android:textColor="@color/color_gray"   />

I have created a custom drawable layout file. But this only enables me to have one line at the end, and I need several lines inside the EditText.
How can I do this?

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">
            <stroke
            android:width="1dp"
            android:color="@color/color_gray" />
        </shape>
    </item>
</layer-list>

Thanks in advance!

Body:
To achieve this you have to make changes in your drawable class which you have created.

<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetLeft="-2dp"
    android:insetRight="-2dp"
    android:insetTop="-2dp">

    <shape android:shape="rectangle" >
        <stroke
            android:width="1dp"
            android:color="#000000" />
        <solid android:color="@color/md_grey_200" />
    </shape>

</inset>

This will give you border bottom and you can change color according to your requirement.
If you don't want to give border to the each EditText you can add one View after each EditText like this.

                    <View
                    style="@style/MenuDivider"
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:layout_marginEnd="5dp"
                    android:layout_marginStart="5dp"
                    android:layout_marginTop="15dp"
                    android:background="@color/black"/>

You can change the view height according and background to you.
Hope this will help you.


问:
Need to distinguish like icon from unliked icon
I need to click like icon but after checking the condition, if this is already liked or not. So i need two different locator paths to differentiate between the two. The only thing different is the classes but the class name has spcae in between and the protractor cannot locate the space class name, even after adding dots for space.

My protractor code and html structure is in the picture:

答:
It's not clear what you're trying to achieve. If you update your post showing html of liked icon and not liked icon and what your script is doing i can give you a solution.

If your element is .

There are three ways to locate such elements using CSS.

$heart = $('i[class="fa fa-heart liked"]');

$heart = $('.fa.fa-heart.liked"]');

$heart = $('i[class*="fa-heart"][class*="liked"]'); // contains partially

Also you have an option using xpath

Body:
It's not clear what you're trying to achieve. If you update your post showing html of liked icon and not liked icon and what your script is doing i can give you a solution.

If your element is <i class="fa fa-heart liked">.

There are three ways to locate such elements using CSS.

$heart = $('i[class="fa fa-heart liked"]');

$heart = $('.fa.fa-heart.liked"]');

$heart = $('i[class*="fa-heart"][class*="liked"]'); // contains partially

Also you have an option using xpath


问:
combine 2 observables
I am using firestore as database and use angularfire2 to retrieve data from it.
I have a collection of comments, in which each comment stores a user id. I want to get the user info such as user displayName and photoURL, and then combine it with the original comments stream to result in a stream consists of both comment info and user info. My attempt to combine the comments and users stream as follows:

```<code>const comments$ = this.afs.collection(`comments`).valueChanges();
const users$ = this.afs.collection(`comments`).valueChanges().pipe(
  switchMap((comments) => {
    return comments.map(comment => this.afs.doc(`users/${comment.uid}`).valueChanges());
  })
);
const combine = zip(comments$, users$, (comments, users) => {
  return {...comments, ...users };
});
</code>```

The above code failed to achieve what I want. Essentially it reads the user id from each of the comment, and then use this user id to find the related user info, and combines them together as a resulting stream. The comments$ observable works properly. The users$ observable didn't work. Also, I am not sure if zip is a proper use in this case.

答:
I think you are searching more for a combineLatest instead of a zip. Since every time one stream emits you need to recalculate your output stream.

The merge function seems not good too, If I have understood well, you have to join every comment with its user, for that, you can simply do:

```<code>comments.map((comment) => {
      return {
          ...comment,
          user: users.find(user => user.id === comment.user_id)}
   })
</code>```

Here is a simple code snippet where both streams are joined this way, having as a final result an array of comments with its user information:

function mockUsers$() {
  return rxjs.of([
  {id: '1', name: 'user1'},
  {id: '2', name: 'user2'},
  {id: '3', name: 'user3'}
]);
}

function mockComments$() {
  return rxjs.of([
  {id: '1', user_id: '1', comment: 'user1 comment 1'},
  {id: '2', user_id: '1', comment: 'user1 comment 2'},
  {id: '3', user_id: '1', comment: 'user1 comment 3'},
  {id: '4', user_id: '2', comment: 'user2 comment'},
  {id: '5', user_id: '3', comment: 'user3 comment 1'},
  {id: '6', user_id: '3', comment: 'user3 comment 2'}]);
}

const comments$ = mockComments$();
const users$ = mockUsers$()

rxjs.combineLatest(users$, comments$, (users, comments) => comments.map((comment) => {
      return {
          ...comment,
          user: {...users.find(user => user.id === comment.user_id)}}
   })
).subscribe((data) => console.log('Comments with user info: ', data));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js"></script></code>```

Hope this helps!

Title: combine 2 observables

Body:
I am using firestore as database and use angularfire2 to retrieve data from it.
I have a collection of comments, in which each comment stores a user id. I want to get the user info such as user displayName and photoURL, and then combine it with the original comments stream to result in a stream consists of both comment info and user info. My attempt to combine the comments and users stream as follows:

const comments$ = this.afs.collection(`comments`).valueChanges();
const users$ = this.afs.collection(`comments`).valueChanges().pipe(
  switchMap((comments) => {
    return comments.map(comment => this.afs.doc(`users/${comment.uid}`).valueChanges());
  })
);
const combine = zip(comments$, users$, (comments, users) => {
  return {...comments, ...users };
});

The above code failed to achieve what I want. Essentially it reads the user id from each of the comment, and then use this user id to find the related user info, and combines them together as a resulting stream. The comments$ observable works properly. The users$ observable didn't work. Also, I am not sure if zip is a proper use in this case.

Body:
I think you are searching more for a combineLatest instead of a zip. Since every time one stream emits you need to recalculate your output stream.

The merge function seems not good too, If I have understood well, you have to join every comment with its user, for that, you can simply do:

comments.map((comment) => {
      return {
          ...comment,
          user: users.find(user => user.id === comment.user_id)}
   })

Here is a simple code snippet where both streams are joined this way, having as a final result an array of comments with its user information:

function mockUsers$() {
  return rxjs.of([
  {id: '1', name: 'user1'},
  {id: '2', name: 'user2'},
  {id: '3', name: 'user3'}
]);
}

function mockComments$() {
  return rxjs.of([
  {id: '1', user_id: '1', comment: 'user1 comment 1'},
  {id: '2', user_id: '1', comment: 'user1 comment 2'},
  {id: '3', user_id: '1', comment: 'user1 comment 3'},
  {id: '4', user_id: '2', comment: 'user2 comment'},
  {id: '5', user_id: '3', comment: 'user3 comment 1'},
  {id: '6', user_id: '3', comment: 'user3 comment 2'}]);
}

const comments$ = mockComments$();
const users$ = mockUsers$()

rxjs.combineLatest(users$, comments$, (users, comments) => comments.map((comment) => {
      return {
          ...comment,
          user: {...users.find(user => user.id === comment.user_id)}}
   })
).subscribe((data) => console.log('Comments with user info: ', data));

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js"></script>

Hope this helps!


问:
SQLITE sum of alias column
I am sure this question has been asked several times, but it seems I can't fix it myself. I want to get the sum of Profit as sumProfit as well the sum of ST as sumST, how exactly should I write the query?</p>

```<code>SELECT C.Match_ID, M.Match_Date, T1.TeamName as HomeTeam,
T2.TeamName as AwayTeam, L.League_MyName, S.Season_Year, M.algo,
Round((tp.Home*100),3) as TOP,
case when Round((tp.Home*100),3)=0 then 0
else Round(1/(tp.Home),3) end as TOd,
LW.Home as LW,
case when Pr.Home=0 then 0.0 else Round((tp2.Home*100),3) end as TV,
Pr.Home as BOd,
case when Pr.Home=0 then 0.0 else Round((1/Pr.Home)*100,3) end as BOP,
case when Pr.Home=0 then 0.0 when Pr.Home<2 then 100.0 else Round(100.0/(Pr.Home-1),2) end as ST,
case when Pr.Home =0 then 0.0 when LW.Home = 'W' then Round((case when Pr.Home<2 then 100.0 else Round(100.0/(Pr.Home-1),2) end) * (Pr.Home-1),2)
when LW.Home = 'DNB' then 0.0 else -(case when Pr.Home<2 then 100.0 else Round(100.0/(Pr.Home-1),2) end) end as Profit
FROM Matches as M
inner join (select Home, Match_ID from Computations where Computation_Type_ID = 1) as tp on tp.Match_ID = C.Match_ID
inner join (select Home, Match_ID from Computations where Computation_Type_ID = 2) as tp2 on tp2.Match_ID = C.Match_ID
inner join Computations as C on C.Match_ID = M.Match_ID
inner join Leagues as L on L.Real_League_ID = M.Real_League_ID
inner join Season as S on S.Season_ID = M.Season_ID
inner join Teams as T1 on T1.Team_ID = M.Home_TeamID
inner join Teams as T2 on T2.Team_ID = M.Away_TeamID
inner join LostWon as LW on LW.Match_ID=C.Match_ID
inner join Prices as Pr on Pr.Match_ID=C.Match_ID
where M.Real_League_ID=44
group by C.Match_ID
</code>```

答:
Just make this one as inner query and remove group at very bottom of your inner query

```<code>SELECT Match_ID, SUM(Profit) as SUMPROFIT, SUM(ST) SUMST FROM (
SELECT C.Match_ID, M.Match_Date, T1.TeamName as HomeTeam,
    T2.TeamName as AwayTeam, L.League_MyName, S.Season_Year, M.algo,
    Round((tp.Home*100),3) as TOP,
    case when Round((tp.Home*100),3)=0 then 0
    else Round(1/(tp.Home),3) end as TOd,
    LW.Home as LW,
    case when Pr.Home=0 then 0.0 else Round((tp2.Home*100),3) end as TV,
    Pr.Home as BOd,
    case when Pr.Home=0 then 0.0 else Round((1/Pr.Home)*100,3) end as BOP,
    case when Pr.Home=0 then 0.0 when Pr.Home<2 then 100.0 else Round(100.0/(Pr.Home-1),2) end as ST,
    case when Pr.Home =0 then 0.0 when LW.Home = 'W' then Round((case when Pr.Home<2 then 100.0 else Round(100.0/(Pr.Home-1),2) end) * (Pr.Home-1),2)
    when LW.Home = 'DNB' then 0.0 else -(case when Pr.Home<2 then 100.0 else Round(100.0/(Pr.Home-1),2) end) end as Profit
    FROM Matches as M
    inner join (select Home, Match_ID from Computations where Computation_Type_ID = 1) as tp on tp.Match_ID = C.Match_ID
    inner join (select Home, Match_ID from Computations where Computation_Type_ID = 2) as tp2 on tp2.Match_ID = C.Match_ID
    inner join Computations as C on C.Match_ID = M.Match_ID
    inner join Leagues as L on L.Real_League_ID = M.Real_League_ID
    inner join Season as S on S.Season_ID = M.Season_ID
    inner join Teams as T1 on T1.Team_ID = M.Home_TeamID
    inner join Teams as T2 on T2.Team_ID = M.Away_TeamID
    inner join LostWon as LW on LW.Match_ID=C.Match_ID
    inner join Prices as Pr on Pr.Match_ID=C.Match_ID
    where M.Real_League_ID=44)
GROUP BY Match_ID
</code>```

If you want to see more columns you can add aliases in outer query but dont forget to add them also group by.

Title: SQLITE sum of alias column

Body:
I am sure this question has been asked several times, but it seems I can't fix it myself. I want to get the sum of Profit as sumProfit as well the sum of ST as sumST, how exactly should I write the query?

SELECT C.Match_ID, M.Match_Date, T1.TeamName as HomeTeam,
T2.TeamName as AwayTeam, L.League_MyName, S.Season_Year, M.algo,
Round((tp.Home*100),3) as TOP,
case when Round((tp.Home*100),3)=0 then 0
else Round(1/(tp.Home),3) end as TOd,
LW.Home as LW,
case when Pr.Home=0 then 0.0 else Round((tp2.Home*100),3) end as TV,
Pr.Home as BOd,
case when Pr.Home=0 then 0.0 else Round((1/Pr.Home)*100,3) end as BOP,
case when Pr.Home=0 then 0.0 when Pr.Home<2 then 100.0 else Round(100.0/(Pr.Home-1),2) end as ST,
case when Pr.Home =0 then 0.0 when LW.Home = 'W' then Round((case when Pr.Home<2 then 100.0 else Round(100.0/(Pr.Home-1),2) end) * (Pr.Home-1),2)
when LW.Home = 'DNB' then 0.0 else -(case when Pr.Home<2 then 100.0 else Round(100.0/(Pr.Home-1),2) end) end as Profit
FROM Matches as M
inner join (select Home, Match_ID from Computations where Computation_Type_ID = 1) as tp on tp.Match_ID = C.Match_ID
inner join (select Home, Match_ID from Computations where Computation_Type_ID = 2) as tp2 on tp2.Match_ID = C.Match_ID
inner join Computations as C on C.Match_ID = M.Match_ID
inner join Leagues as L on L.Real_League_ID = M.Real_League_ID
inner join Season as S on S.Season_ID = M.Season_ID
inner join Teams as T1 on T1.Team_ID = M.Home_TeamID
inner join Teams as T2 on T2.Team_ID = M.Away_TeamID
inner join LostWon as LW on LW.Match_ID=C.Match_ID
inner join Prices as Pr on Pr.Match_ID=C.Match_ID
where M.Real_League_ID=44
group by C.Match_ID

Body:
Just make this one as inner query and remove group at very bottom of your inner query

SELECT Match_ID, SUM(Profit) as SUMPROFIT, SUM(ST) SUMST FROM (
SELECT C.Match_ID, M.Match_Date, T1.TeamName as HomeTeam,
    T2.TeamName as AwayTeam, L.League_MyName, S.Season_Year, M.algo,
    Round((tp.Home*100),3) as TOP,
    case when Round((tp.Home*100),3)=0 then 0
    else Round(1/(tp.Home),3) end as TOd,
    LW.Home as LW,
    case when Pr.Home=0 then 0.0 else Round((tp2.Home*100),3) end as TV,
    Pr.Home as BOd,
    case when Pr.Home=0 then 0.0 else Round((1/Pr.Home)*100,3) end as BOP,
    case when Pr.Home=0 then 0.0 when Pr.Home<2 then 100.0 else Round(100.0/(Pr.Home-1),2) end as ST,
    case when Pr.Home =0 then 0.0 when LW.Home = 'W' then Round((case when Pr.Home<2 then 100.0 else Round(100.0/(Pr.Home-1),2) end) * (Pr.Home-1),2)
    when LW.Home = 'DNB' then 0.0 else -(case when Pr.Home<2 then 100.0 else Round(100.0/(Pr.Home-1),2) end) end as Profit
    FROM Matches as M
    inner join (select Home, Match_ID from Computations where Computation_Type_ID = 1) as tp on tp.Match_ID = C.Match_ID
    inner join (select Home, Match_ID from Computations where Computation_Type_ID = 2) as tp2 on tp2.Match_ID = C.Match_ID
    inner join Computations as C on C.Match_ID = M.Match_ID
    inner join Leagues as L on L.Real_League_ID = M.Real_League_ID
    inner join Season as S on S.Season_ID = M.Season_ID
    inner join Teams as T1 on T1.Team_ID = M.Home_TeamID
    inner join Teams as T2 on T2.Team_ID = M.Away_TeamID
    inner join LostWon as LW on LW.Match_ID=C.Match_ID
    inner join Prices as Pr on Pr.Match_ID=C.Match_ID
    where M.Real_League_ID=44)
GROUP BY Match_ID

If you want to see more columns you can add aliases in outer query but dont forget to add them also group by.


问:
Issues with Swing timers
I have 3 timers running on my application which takes care of different action. Timer 1 will deals with automatic logout of the application, timer 2 deals with updating a table, timer 3 deals with updating the color of swing buttons. First timer uses the calculation based on the variables and its values, second and third timers works out of MYSQL queries.

Now when i run this application on an average performance machine the application is not moving .I need to wait for few seconds to a normal click to happen or a window to open. Is it something to do with the timers ? If yes do I have any alternative suggestions to get rid of this timer problem?

答: That should not be related to the Swing timers, that is something else in your code. You need to debug the application to see what is causing the delay.  </p>

ContentLicense: CC BY-SA 3.0

Title: Issues with Swing timers


问:
Issue with hasManyThrough relationship
I created four models: Item, ItemOption, ItemSize, ItemColor. My intention is to create an online shop, I want to have an  online shop, say I create an article shirt, then I can add many variables (options) of that same shirt, particulary colors, sizes... each option with it's own stock. I set these models with a hasManyThrough relationship but then I get this error:

```<code>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'item_colors.item_option_id' in 'on clause' (SQL: select `item_colors`.*, `item_options`.`item_id` as `laravel_through_key` from `item_colors` inner join `item_options` on `item_options`.`id` = `item_colors`.`item_option_id` where `item_options`.`item_id` in (1))
</code>```

These are my migrations:

```<code>Schema::create('item_options', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('item_id')->index()->nullable();
            $table->foreign('item_id')->references('id')->on('items')->nullable();
            $table->unsignedInteger('item_size_id')->index()->nullable();
            $table->foreign('item_size_id')->references('id')->on('item_sizes')->nullable();
            $table->unsignedInteger('item_color_id')->index()->nullable();
            $table->foreign('item_color_id')->references('id')->on('item_colors')->nullable();
            $table->timestamps();
        });

Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('image')->nullable();
            $table->string('title');
            $table->decimal('finalPrice', 5,2);
            $table->text('body');
            $table->timestamps();
        });

Schema::create('item_colors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('colorCode');
            $table->timestamps();
        });

Schema::create('item_sizes', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });
</code>```

And my models:

```<code>class Item extends Model
{

    protected $table = 'items';

    public function options()
    {
        return $this->hasMany(ItemOption::class);
    }

    public function sizes()
    {
        return $this->hasManyThrough(ItemSize::class, ItemOption::class);
    }

    public function colors()
    {
        return $this->hasManyThrough(ItemColor::class, ItemOption::class);
    }

}

class ItemOption extends Model
{

    protected $fillable = ['item_id', 'item_color_id', 'item_size_id', 'stock'];

    public function color()
    {
        return $this->belongsTo(ItemColor::class);
    }

    public function size()
    {
        return $this->belongsTo(ItemSize::class);
    }

}
</code>```

答:
Wow, it is my code from previous question. It wasn't correct at 100%.

You should inverse some params in relation methods:

```<code>public function sizes()
{
    return $this->hasManyThrough(ItemSize::class, ItemOption::class, 'item_id', 'id', 'id', 'item_size_id');
}

public function colors()
{
    return $this->hasManyThrough(ItemColor::class, ItemOption::class, 'item_id', 'id', 'id', 'item_color_id');
}
</code>```

Title: Issue with hasManyThrough relationship

Body:
I created four models: Item, ItemOption, ItemSize, ItemColor. My intention is to create an online shop, I want to have an  online shop, say I create an article shirt, then I can add many variables (options) of that same shirt, particulary colors, sizes... each option with it's own stock. I set these models with a hasManyThrough relationship but then I get this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'item_colors.item_option_id' in 'on clause' (SQL: select `item_colors`.*, `item_options`.`item_id` as `laravel_through_key` from `item_colors` inner join `item_options` on `item_options`.`id` = `item_colors`.`item_option_id` where `item_options`.`item_id` in (1))

These are my migrations:

Schema::create('item_options', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('item_id')->index()->nullable();
            $table->foreign('item_id')->references('id')->on('items')->nullable();
            $table->unsignedInteger('item_size_id')->index()->nullable();
            $table->foreign('item_size_id')->references('id')->on('item_sizes')->nullable();
            $table->unsignedInteger('item_color_id')->index()->nullable();
            $table->foreign('item_color_id')->references('id')->on('item_colors')->nullable();
            $table->timestamps();
        });

Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('image')->nullable();
            $table->string('title');
            $table->decimal('finalPrice', 5,2);
            $table->text('body');
            $table->timestamps();
        });

Schema::create('item_colors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('colorCode');
            $table->timestamps();
        });

Schema::create('item_sizes', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });

And my models:

class Item extends Model
{

    protected $table = 'items';

    public function options()
    {
        return $this->hasMany(ItemOption::class);
    }

    public function sizes()
    {
        return $this->hasManyThrough(ItemSize::class, ItemOption::class);
    }

    public function colors()
    {
        return $this->hasManyThrough(ItemColor::class, ItemOption::class);
    }

}

class ItemOption extends Model
{

    protected $fillable = ['item_id', 'item_color_id', 'item_size_id', 'stock'];

    public function color()
    {
        return $this->belongsTo(ItemColor::class);
    }

    public function size()
    {
        return $this->belongsTo(ItemSize::class);
    }

}

Body:
Wow, it is my code from previous question. It wasn't correct at 100%.

You should inverse some params in relation methods:

public function sizes()
{
    return $this->hasManyThrough(ItemSize::class, ItemOption::class, 'item_id', 'id', 'id', 'item_size_id');
}

public function colors()
{
    return $this->hasManyThrough(ItemColor::class, ItemOption::class, 'item_id', 'id', 'id', 'item_color_id');
}


问:
Need help converting a Neo4j Cypher script to Gremlin
I can't figure out how to rewrite my Cypher script in Gremlin.

First we used the .Net Neo4j client to connect to our Neo4j database and run Cypher queries on it. Then we decided to add an abstraction layer and connect to a Gremlin server instead (which, for now, hosts the same Neo4j database). So now I need to translate our queries from Cypher to Gremlin and I am finding it rather difficult.

Here's one of them:

```<code>MATCH (pc:ProductCategory)-[:HasRootCategory]->(r:RootCategory)
WHERE NOT (:ProductCategory)-[]->(pc)
AND pc.Id = r.RootId
RETURN pc;
</code>```

One of my failed attempts:
g.V().match(as("pc").out("HasRootCategory").as("r"),as("pc").in().has('label', 'ProductCategory').count().is(0))).select("pc", "r").where("pc.Id", eq("r.RootId")).select("pc")

I found an example on stackoverflow using this 'match(as' construct, but it must be depracated or something, because I'm getting an error. Also, not sure how to compare properties with different names on nodes with different labels (I'm sure the 'where' is wrong...)

Any help would be appreciated.

答:
The following traversal should be equivalent:

```<code>g.V().hasLabel("ProductCategory").as("pc").
  not(__.in().hasLabel("ProductCategory")).
  out("HasRootCategory").as("r").
  where("pc", eq("r")).
    by("Id").
    by("RootId").
  select("pc")
</code>```

Since you don't really need the r label, the query can be tweaked a bit:

```<code>g.V().hasLabel("ProductCategory").as("pc").
  not(__.in().hasLabel("ProductCategory")).
  filter(out("HasRootCategory").
         where(eq("pc")).
           by("Id").
           by("RootId"))
</code>```

Last thing to mention: If a ProductCategory vertex can be connected to another ProductCategory vertex by only one (or more) specific edge label, that can lead nowhere else, it would be better to do:

```<code>g.V().hasLabel("ProductCategory").as("pc").
  not(inE("KnownLabelBetweenCategories")).
  filter(out("HasRootCategory").
         where(eq("pc")).
           by("Id").
           by("RootId"))
</code>```

On a different note, match() is not deprecated. I guess you tried to run your traversal in Groovy and it just failed because you didn't use __.as() (as, among others, is a reserved keyword in Groovy).

Body:
I can't figure out how to rewrite my Cypher script in Gremlin.

First we used the .Net Neo4j client to connect to our Neo4j database and run Cypher queries on it. Then we decided to add an abstraction layer and connect to a Gremlin server instead (which, for now, hosts the same Neo4j database). So now I need to translate our queries from Cypher to Gremlin and I am finding it rather difficult.

Here's one of them:

MATCH (pc:ProductCategory)-[:HasRootCategory]->(r:RootCategory)
WHERE NOT (:ProductCategory)-[]->(pc)
AND pc.Id = r.RootId
RETURN pc;

One of my failed attempts:
g.V().match(as("pc").out("HasRootCategory").as("r"),as("pc").in().has('label', 'ProductCategory').count().is(0))).select("pc", "r").where("pc.Id", eq("r.RootId")).select("pc")

I found an example on stackoverflow using this 'match(as' construct, but it must be depracated or something, because I'm getting an error. Also, not sure how to compare properties with different names on nodes with different labels (I'm sure the 'where' is wrong...)

Any help would be appreciated.

Body:
The following traversal should be equivalent:

g.V().hasLabel("ProductCategory").as("pc").
  not(__.in().hasLabel("ProductCategory")).
  out("HasRootCategory").as("r").
  where("pc", eq("r")).
    by("Id").
    by("RootId").
  select("pc")

Since you don't really need the r label, the query can be tweaked a bit:

g.V().hasLabel("ProductCategory").as("pc").
  not(__.in().hasLabel("ProductCategory")).
  filter(out("HasRootCategory").
         where(eq("pc")).
           by("Id").
           by("RootId"))

Last thing to mention: If a ProductCategory vertex can be connected to another ProductCategory vertex by only one (or more) specific edge label, that can lead nowhere else, it would be better to do:

g.V().hasLabel("ProductCategory").as("pc").
  not(inE("KnownLabelBetweenCategories")).
  filter(out("HasRootCategory").
         where(eq("pc")).
           by("Id").
           by("RootId"))

On a different note, match() is not deprecated. I guess you tried to run your traversal in Groovy and it just failed because you didn't use __.as() (as, among others, is a reserved keyword in Groovy).


问:
Forms Recognizer Preview - can't load sample documents
I'm trying to use the Forms Recognizer preview, and after much trial and error, I finally got the documents to be read via the SAS URL. But, even with the sample documents that are provided in the Quick Start[1], I get the following response:

```<code>{
    "modelId": "d7ba79e3-38bc-4913-bb11-82656cb08adc",
    "trainingDocuments": [
        {
            "documentName": "Invoice_1.pdf",
            "pages": 1,
            "errors": [
                "Page 1: Document is either invalid or exceeds the page/size limits."
            ],
            "status": "failure"
        },
        {
            "documentName": "Invoice_2.pdf",
            "pages": 1,
            "errors": [
                "Page 1: Document is either invalid or exceeds the page/size limits."
            ],
            "status": "failure"
        },
        {
            "documentName": "Invoice_3.pdf",
            "pages": 1,
            "errors": [
                "Page 1: Document is either invalid or exceeds the page/size limits."
            ],
            "status": "failure"
        },
        {
            "documentName": "Invoice_4.pdf",
            "pages": 1,
            "errors": [
                "Page 1: Document is either invalid or exceeds the page/size limits."
            ],
            "status": "failure"
        },
        {
            "documentName": "Invoice_5.pdf",
            "pages": 1,
            "errors": [
                "Page 1: Document is either invalid or exceeds the page/size limits."
            ],
            "status": "failure"
        }
    ],
    "errors": [
        {
            "errorMessage": "Unable to fit model. No documents clustered."
        }
    ]
}
</code>```

Is there something special that needs to happen on the BLOB storage side for these documents to be available?

I was getting this error message even on basic forms of our own, that fit well within the size constraints.

Update:
I think this is down to some problem in how I'm generating the SAS URL (of which the documentation is not clear at all). I have a storage account (SA), with a single container (C), containing all the PDF files within that.

Within the Azure Portal, I'm selecting the SA blade, then selecting Shared access signature, taking all the default selections, and then selecting Generate SAS and connection string. I tried taking the Blob service SAS URL value directly and passing that in the source field, but that gives the error:

```<code>{
    "error": {
        "code": "2024",
        "innerError": {
            "requestId": "77e73ba0-cbfe-4046-9730-beff8ec38be5"
        },
        "message": "Unable to list blobs on the Azure Blob storage account."
    }
}
</code>```

I had to add &comp=list&restype=container to the source, and then the files are correctly listed, but with the errors above. Obviously something needs to be added to the SAS URL outside of what the Azure Potral generates, and what I added was only part of that.

I miss being able to send the document contents itself in a REST payload to train a model. :-(

[1] - https://github.com/Azure-Samples/cognitive-services-REST-api-samples/blob/master/curl/form-recognizer/sample_data.zip

答:
How did you call the service? With a cURL command? Also, make sure your PDF files are directly in the Azure Blob container for which you got the shared access signature (no subfolders). The cURL command below worked for me:

curl -X POST "https://Endpoint/formrecognizer/v1.0-preview/custom/train" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: Subscription Key" --data-ascii "{ \"source\": \"SAS URL\"}"

Finally, make sure you are able to open the PDF files (i.e., check that they are not invalid).

Body:
I'm trying to use the Forms Recognizer preview, and after much trial and error, I finally got the documents to be read via the SAS URL. But, even with the sample documents that are provided in the Quick Start[1], I get the following response:

{
    "modelId": "d7ba79e3-38bc-4913-bb11-82656cb08adc",
    "trainingDocuments": [
        {
            "documentName": "Invoice_1.pdf",
            "pages": 1,
            "errors": [
                "Page 1: Document is either invalid or exceeds the page/size limits."
            ],
            "status": "failure"
        },
        {
            "documentName": "Invoice_2.pdf",
            "pages": 1,
            "errors": [
                "Page 1: Document is either invalid or exceeds the page/size limits."
            ],
            "status": "failure"
        },
        {
            "documentName": "Invoice_3.pdf",
            "pages": 1,
            "errors": [
                "Page 1: Document is either invalid or exceeds the page/size limits."
            ],
            "status": "failure"
        },
        {
            "documentName": "Invoice_4.pdf",
            "pages": 1,
            "errors": [
                "Page 1: Document is either invalid or exceeds the page/size limits."
            ],
            "status": "failure"
        },
        {
            "documentName": "Invoice_5.pdf",
            "pages": 1,
            "errors": [
                "Page 1: Document is either invalid or exceeds the page/size limits."
            ],
            "status": "failure"
        }
    ],
    "errors": [
        {
            "errorMessage": "Unable to fit model. No documents clustered."
        }
    ]
}

Is there something special that needs to happen on the BLOB storage side for these documents to be available?

I was getting this error message even on basic forms of our own, that fit well within the size constraints.

Update:
I think this is down to some problem in how I'm generating the SAS URL (of which the documentation is not clear at all). I have a storage account (SA), with a single container (C), containing all the PDF files within that.

Within the Azure Portal, I'm selecting the SA blade, then selecting Shared access signature, taking all the default selections, and then selecting Generate SAS and connection string. I tried taking the Blob service SAS URL value directly and passing that in the source field, but that gives the error:

{
    "error": {
        "code": "2024",
        "innerError": {
            "requestId": "77e73ba0-cbfe-4046-9730-beff8ec38be5"
        },
        "message": "Unable to list blobs on the Azure Blob storage account."
    }
}

I had to add &comp=list&restype=container to the source, and then the files are correctly listed, but with the errors above. Obviously something needs to be added to the SAS URL outside of what the Azure Potral generates, and what I added was only part of that.

I miss being able to send the document contents itself in a REST payload to train a model. :-(

[1] - https://github.com/Azure-Samples/cognitive-services-REST-api-samples/blob/master/curl/form-recognizer/sample_data.zip


问:
How to choose a fuzzy matching algorithm?
I need to know the criteria which made fuzzy algo different from each other between those 3 :

Levenshtein distance Algorithm

Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is the minimum number of single-character edits (i.e. insertions, deletions or substitutions) required to change one word into the other.

Damerau–Levenshtein distance

Damerau–Levenshtein distance is a distance (string metric) between two strings, i.e., finite sequence of symbols, given by counting the minimum number of operations needed to transform one string into the other, where an operation is defined as an insertion, deletion, or substitution of a single character, or a transposition of two adjacent characters.

Bitap algorithm with modifications by Wu and Manber

Bitmap algorithm is an approximate string matching algorithm. The algorithm tells whether a given text contains a substring which is "approximately equal" to a given pattern, where approximate equality is defined in terms of Levenshtein distance — if the substring and pattern are within a given distance k of each other, then the algorithm considers them equal.

My document is a table with name of companies, some companies are twice or three time because of misspelling. In this particular case, how to group the companies by matching them ? Which algorithm to chose and why ? In the file I have 100k lines and it is growing.

答:
If you are on Google Sheets, try using Flookup. You say that your list has over 100K rows so that might prove a bit of a challenge depending on Google's (timed) execution limits but I still encourage you to give it a try.
One function you might be interested in is:

```<code>FLOOKUP(lookupValue, tableArray, lookupCol, indexNum, [threshold], [rank])
</code>```

Full Disclosure: I created Flookup for Google sheets

Body:
If you are on Google Sheets, try using Flookup. You say that your list has over 100K rows so that might prove a bit of a challenge depending on Google's (timed) execution limits but I still encourage you to give it a try.
One function you might be interested in is:

FLOOKUP(lookupValue, tableArray, lookupCol, indexNum, [threshold], [rank])

Full Disclosure: I created Flookup for Google sheets


问:
Reading an Excel file in PHP
I'm trying to read an Excel file (Office 2003). There is an Excel file that needs to be uploaded and its contents parsed.

Via Google, I can only find answers to these related (and insufficient topics): generating Excel files, reading Excel XML files, reading Excel CSV files, or incomplete abandoned projects. I own Office 2003 so if I need any files from there, they are available. It's installed on my box but isn't and can't be installed on my shared host.

Edit: so far all answers point to PHP-ExcelReader and/or this additional article about how to use it.

答: I use PHP-ExcelReader to read xls files, and works great. </p>

OwnerDisplayName: Dinah

Title: Reading an Excel file in PHP

LastEditorDisplayName: Dinah

OwnerDisplayName: Luis Melgratti

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Luis Melgratti


问:
Wordpress messing with my db calls on the wordpress pages?
Hey, hows it going everyone? I am having database conflicts I was wanting some help with.

Basically, I have a header that pulls in a random database field. Nothing special. It is in my header in my template and works just fine on non WordPress pages.

```<code>$sql = "SELECT * FROM headerslogans ORDER BY RAND() LIMIT 1";
    $result = mysql_query($sql);
    while ($myrow = mysql_fetch_array($result)) {
    echo $myrow['slogan'];
};
</code>```

I am using the same database, same user name, same password, etc. However, I get this error where the echo should be....

```<code>Warning: mysql_query() [function.mysql-query]: Access denied for user 'nobody'@'localhost' (using password: NO) in <dir name>
</code>```

So obviously the wordpress connection is "overwriting" the other (wordpress works flawlessly). BUT, I was also confused as to why it doesn't work, although it is connecting to the same database with same username and password.

Can anybody help me out on this?

UPDATE: Posted connection code

$x = mysql_connect($server,$dbuser,$dbpass,true) or die(mysql_error());
mysql_select_db($dbname,$x);

答:
As you said, the connection is getting overwritten, is the database selection also getting over written? It's probable that actually mysql_select_db() is the thing screwing you over. Fix it by setting you your original connection as a variable, and referencing it in the offending mysql_* functions, eg:

```<code>$dbcnct = mysql_connect(...);
mysql_select_db('...', $dbcnct);
mysql_query('...', $dbcnct);
</code>```

This shouldn't affect your current setup either.

Body:
Hey, hows it going everyone? I am having database conflicts I was wanting some help with.

Basically, I have a header that pulls in a random database field. Nothing special. It is in my header in my template and works just fine on non WordPress pages.

$sql = "SELECT * FROM headerslogans ORDER BY RAND() LIMIT 1";
    $result = mysql_query($sql);
    while ($myrow = mysql_fetch_array($result)) {
    echo $myrow['slogan'];
};

I am using the same database, same user name, same password, etc. However, I get this error where the echo should be....

Warning: mysql_query() [function.mysql-query]: Access denied for user 'nobody'@'localhost' (using password: NO) in <dir name>

So obviously the wordpress connection is "overwriting" the other (wordpress works flawlessly). BUT, I was also confused as to why it doesn't work, although it is connecting to the same database with same username and password.

Can anybody help me out on this?

UPDATE: Posted connection code

$x = mysql_connect($server,$dbuser,$dbpass,true) or die(mysql_error());
mysql_select_db($dbname,$x);

Body:
As you said, the connection is getting overwritten, is the database selection also getting over written? It's probable that actually mysql_select_db() is the thing screwing you over. Fix it by setting you your original connection as a variable, and referencing it in the offending mysql_* functions, eg:

$dbcnct = mysql_connect(...);
mysql_select_db('...', $dbcnct);
mysql_query('...', $dbcnct);

This shouldn't affect your current setup either.


问:
Azure Function App inconsistently triggering
In a zip-deployed function app that is triggered off of an event hub, the app inconsistently triggers (only seems to trigger when debugging the app int he Azure Portal and ~15 minutes afterwards).</p>

```<code>resource "azurerm_function_app" "helloworld" {
  name                      = "helloworld-func"
  location                  = "${azurerm_resource_group.helloworld.location}"
  resource_group_name       = "${azurerm_resource_group.helloworld.name}"
  app_service_plan_id       = "${azurerm_app_service_plan.helloworld.id}"
  storage_connection_string = "${azurerm_storage_account.helloworld.primary_connection_string}"
  version                   = "~2"

  app_settings {
    # key must match bindings.connection in functionapp/eventHubsMessages/function.json and must include EntityPath
    # bindings.eventHubName in functionapp/eventHubMessages/function.json is purposelly kept empty to avoid overriding the EntityPath in connection string
    # see https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs#output---configuration
    LOGSEVENTHUBCONNECTIONSTRING = "${azurerm_eventhub_authorization_rule.helloworld.primary_connection_string}"

    # TODO figure out how to use Azure AD and RBAC to allow the Function App access to the storage blob without a time-based token
    WEBSITE_USE_ZIP              = "${azurerm_storage_blob.helloworld.url}${data.azurerm_storage_account_sas.helloworld.sas}"
    HASH                         = "${data.archive_file.helloworld.output_base64sha256}"
    WEBSITE_NODE_DEFAULT_VERSION = "10.14.1"
  }
}
</code>```

答:
This is a long, known outstanding issue that is caused by function triggers not being sync (see https://github.com/Azure/Azure-Functions/issues/210)

add this local-exec provisioner in terraform that use the azure cli to syncfunctiontriggers works well

```<code>  # required to sync the function trigger (event hub trigger); without, function app will trigger inconsistently
  provisioner "local-exec" {
    command = "az resource invoke-action --resource-group ${azurerm_resource_group.datadog_logs.name} --action syncfunctiontriggers --name ${azurerm_function_app.datadog_logs.name} --resource-type Microsoft.Web/sites"
  }
</code>```

Body:
In a zip-deployed function app that is triggered off of an event hub, the app inconsistently triggers (only seems to trigger when debugging the app int he Azure Portal and ~15 minutes afterwards).

resource "azurerm_function_app" "helloworld" {
  name                      = "helloworld-func"
  location                  = "${azurerm_resource_group.helloworld.location}"
  resource_group_name       = "${azurerm_resource_group.helloworld.name}"
  app_service_plan_id       = "${azurerm_app_service_plan.helloworld.id}"
  storage_connection_string = "${azurerm_storage_account.helloworld.primary_connection_string}"
  version                   = "~2"

  app_settings {
    # key must match bindings.connection in functionapp/eventHubsMessages/function.json and must include EntityPath
    # bindings.eventHubName in functionapp/eventHubMessages/function.json is purposelly kept empty to avoid overriding the EntityPath in connection string
    # see https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs#output---configuration
    LOGSEVENTHUBCONNECTIONSTRING = "${azurerm_eventhub_authorization_rule.helloworld.primary_connection_string}"

    # TODO figure out how to use Azure AD and RBAC to allow the Function App access to the storage blob without a time-based token
    WEBSITE_USE_ZIP              = "${azurerm_storage_blob.helloworld.url}${data.azurerm_storage_account_sas.helloworld.sas}"
    HASH                         = "${data.archive_file.helloworld.output_base64sha256}"
    WEBSITE_NODE_DEFAULT_VERSION = "10.14.1"
  }
}

Body:
This is a long, known outstanding issue that is caused by function triggers not being sync (see https://github.com/Azure/Azure-Functions/issues/210)

add this local-exec provisioner in terraform that use the azure cli to syncfunctiontriggers works well

  # required to sync the function trigger (event hub trigger); without, function app will trigger inconsistently
  provisioner "local-exec" {
    command = "az resource invoke-action --resource-group ${azurerm_resource_group.datadog_logs.name} --action syncfunctiontriggers --name ${azurerm_function_app.datadog_logs.name} --resource-type Microsoft.Web/sites"
  }


问:
what query to use in this situation- sqlServer
I haves 2 tables:

Info:

Score:

What query can i use to get this result?
( The months and years column show the score of the guys in June-2019

答:
You could do something like this</p>

```<code>SELECT
    Info.id
    , Info.Name
    , Info.age
    , DATEDIFF(MONTH, CAST(score.date AS datetime), GETDATE()) AS Moths
    , DATEDIFF(YEAR, CAST(score.date AS datetime), GETDATE()) AS Years
FROM
    Info
    INNER JOIN Score
    ON Info.id = Score.ID
</code>```

Body:
You could do something like this

SELECT
    Info.id
    , Info.Name
    , Info.age
    , DATEDIFF(MONTH, CAST(score.date AS datetime), GETDATE()) AS Moths
    , DATEDIFF(YEAR, CAST(score.date AS datetime), GETDATE()) AS Years
FROM
    Info
    INNER JOIN Score
    ON Info.id = Score.ID


问:
Excel VBA changing time/day format on columns
I am having to change the Day/Time format for over 9000 provider records. I am new at vba and am not sure what way to go about it, since there are over 100 varieties of provider office hours.

I thought about using a button that would create a new column that would populate the correct information, but I am not sure that is the right path. I thought about doing If statements but I know that would be over 100 If statements due to the variety of office hours.

The current day/time format the is generated in Excel is:

```<code>M 8:30 AM-5:30 PM
T 8:30 AM-5:30 PM
W 8:30 AM-5:30 PM
R 8:30 AM-5:30 PM
F 8:30 AM-5:30 PM
</code>```

I need to turn that into M-F 8:30 AM-5:30 PM

Here is another example

```<code>M 7:30 AM-11:00 PM
T 7:30 AM-11:00 PM
W 7:30 AM-11:00 PM
R 7:30 AM-11:00 PM
F 7:30 AM-11:00 PM
S 8:00 AM-9:00 PM
</code>```

Desired end result:

```<code>M-F 7:30 AM - 11:00 PM; SA 8:00 AM - 9:00 PM
</code>```

答:
In case an Excel solution might work for you, maybe you can adapt this your needs:

NOTE: For this formula to work:

Your data must start at row 2 or lower, but not on row 1 in any case or formula won't work properly.

Data must be sorted like the one you posted (all same times grouped together, or it won't work)

And the formula:    =IF(IF(TRIM(MID(A2;3;99))=TRIM(MID(A1;3;99));"";ROW())="";"";LEFT(INDEX($A:$A;IF(TRIM(MID(A2;3;99))=TRIM(MID(A1;3;99));"";ROW()));1)&"-"&LEFT(INDEX($A:$A;IF(TRIM(MID(A2;3;99))=TRIM(MID(A1;3;99));"";ROW())+COUNTIFS($A$2:$A$12;"*"&TRIM(MID(A2;3;99))&"*")-1);1)&" "&TRIM(MID(A2;3;99)))

As you may noticed in the image, last result does not fit your needs (you posted SA 8:00 AM - 9:00 PM and my formula gets S-S 8:00 AM-9:00 PM because, to be honest, I have no idea where that A comes from.

Because the complexity of the formula, I've uploaded the file to my Gdrive, and in the file you'll find 2 sheets: one with the formula in just 1 cell, and one with the formula in several columns, emulatin a step by step resolution, in case you might be interested in checking the idea behind it.

https://drive.google.com/open?id=1pmrpPqMWwtFtdzt3-lQoK5npd_JeQs0m

Try to adapt it to your needs.

Body:
I am having to change the Day/Time format for over 9000 provider records. I am new at vba and am not sure what way to go about it, since there are over 100 varieties of provider office hours.

I thought about using a button that would create a new column that would populate the correct information, but I am not sure that is the right path. I thought about doing If statements but I know that would be over 100 If statements due to the variety of office hours.

The current day/time format the is generated in Excel is:

M 8:30 AM-5:30 PM
T 8:30 AM-5:30 PM
W 8:30 AM-5:30 PM
R 8:30 AM-5:30 PM
F 8:30 AM-5:30 PM

I need to turn that into M-F 8:30 AM-5:30 PM

Here is another example

M 7:30 AM-11:00 PM
T 7:30 AM-11:00 PM
W 7:30 AM-11:00 PM
R 7:30 AM-11:00 PM
F 7:30 AM-11:00 PM
S 8:00 AM-9:00 PM

Desired end result:

M-F 7:30 AM - 11:00 PM; SA 8:00 AM - 9:00 PM


问:
Why does DragDrop.DoDragDrop squash the DataGridHyperlinkColumn click event?
I am having a conflict between two features that I want in my DataGrid.  The definition of the DataGrid is as follows:

```<code><DataGrid x:Name="dgSalesOrders" IsReadOnly="True" SelectionMode="Single" SelectionUnit="FullRow"  PreviewMouseLeftButtonDown="dgSalesOrders_PreviewMouseLeftButtonDown">
    <DataGrid.Columns>
        <DataGridHyperlinkColumn Header="Order #" Binding="{Binding SalesOrderNumber}" IsReadOnly="True">
            <DataGridHyperlinkColumn.ElementStyle>
                <Style TargetType="TextBlock">
                    <EventSetter Event="Hyperlink.Click" Handler="colOrderNumber_Click"/>
                </Style>
            </DataGridHyperlinkColumn.ElementStyle>
        </DataGridHyperlinkColumn>
    </DataGrid.Columns>
</DataGrid>
</code>```

dgSalesOrders_PreviewMouseLeftButtonDown is as follows:

```<code>private void dgSalesOrders_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
    prevRowIndex = getDataGridItemCurrentRowIndex(e.GetPosition, dgSalesOrders);
    if (prevRowIndex < 0 || dgSalesOrders.SelectedItems.Count == 0)
        return;
    dgSalesOrders.SelectedIndex = prevRowIndex;

    List<SalesOrder> selectedOrders = new List<SalesOrder>();
    foreach (ThinSalesOrder salesOrder in dgSalesOrders.SelectedItems)
        selectedOrders.Add(salesOrder);

    ThinSalesOrder selectedOrder = (ThinSalesOrder)dgSalesOrders.Items[prevRowIndex];
    if (selectedOrder == null)
        return;

    DataObject data = new DataObject(salesOrdersFormat, selectedOrders.ToArray());

    if (DragDrop.DoDragDrop(dgSalesOrders, data, DragDropEffects.Move) != DragDropEffects.None)
        dgSalesOrders.SelectedItem = selectedOrder;

}//dgSalesOrders_PreviewMouseLeftButtonDown
</code>```

My issue is that the hyperlink click event (colOrderNumber_Click) does not fire if DragDrop.DoDragDrop(dgSalesOrders, data, DragDropEffects.Move) is called.

Is there some way that this method squashes the click event?  If e.Handled is not being set to true, why does colOrderNumber_Click not fire?

答:
Your problems are partly because DoDragDrop is synchronous.

http://www.csharp411.com/dodragdrop-is-synchronous/

Whilst you're drag dropping then that's all you're doing.

You should also avoid accidentally starting drag by checking the amount they moved the mouse after preview mouse down.

Mixing the two pieces of functionality in one control doesn't seem like a good idea.

I suggest you give them another column or row header they use for dragging.

Body:
I am having a conflict between two features that I want in my DataGrid.  The definition of the DataGrid is as follows:

<DataGrid x:Name="dgSalesOrders" IsReadOnly="True" SelectionMode="Single" SelectionUnit="FullRow"  PreviewMouseLeftButtonDown="dgSalesOrders_PreviewMouseLeftButtonDown">
    <DataGrid.Columns>
        <DataGridHyperlinkColumn Header="Order #" Binding="{Binding SalesOrderNumber}" IsReadOnly="True">
            <DataGridHyperlinkColumn.ElementStyle>

            </DataGridHyperlinkColumn.ElementStyle>
        </DataGridHyperlinkColumn>
    </DataGrid.Columns>
</DataGrid>

dgSalesOrders_PreviewMouseLeftButtonDown is as follows:

private void dgSalesOrders_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
    prevRowIndex = getDataGridItemCurrentRowIndex(e.GetPosition, dgSalesOrders);
    if (prevRowIndex < 0 || dgSalesOrders.SelectedItems.Count == 0)
        return;
    dgSalesOrders.SelectedIndex = prevRowIndex;

    List<SalesOrder> selectedOrders = new List<SalesOrder>();
    foreach (ThinSalesOrder salesOrder in dgSalesOrders.SelectedItems)
        selectedOrders.Add(salesOrder);

    ThinSalesOrder selectedOrder = (ThinSalesOrder)dgSalesOrders.Items[prevRowIndex];
    if (selectedOrder == null)
        return;

    DataObject data = new DataObject(salesOrdersFormat, selectedOrders.ToArray());

    if (DragDrop.DoDragDrop(dgSalesOrders, data, DragDropEffects.Move) != DragDropEffects.None)
        dgSalesOrders.SelectedItem = selectedOrder;

}//dgSalesOrders_PreviewMouseLeftButtonDown

My issue is that the hyperlink click event (colOrderNumber_Click) does not fire if DragDrop.DoDragDrop(dgSalesOrders, data, DragDropEffects.Move) is called.

Is there some way that this method squashes the click event?  If e.Handled is not being set to true, why does colOrderNumber_Click not fire?


问:
creating and dropping dynamically db_link each time connecting various DBs after updating table
I want to create PL-SQL procedure which connect and update various DBs remotely from one db and update table on each DBs by creating dynamic db_link and this db_link should be created and dropped each time after updating the tables in all DBs. How can we do it? Please help.</p>

答:
Warning: There is a security breach about creating and dropping dynamically  db links because a table must store passwords for every remote account.

1-Create a table

```<code>Table name: REMOTE_INFO

host_name        varchar2(25) primary_key,
username_remote  varchar2(30),
password_remote  varchar2(30),
host_connection  varchar2(30),
table_local      varchar2(30),
schema_remote    varchar2(30),
table_remote     varchar2(30),
condition        varchar2(4000)
</code>```

2-Package specification

```<code>create or replace package pk_remote
is
  /* ====================================================================================================
  -- ref: question on
  -- https://stackoverflow.com/questions/56339278/creating-and-dropping-dynamically-db-link-each-time-connecting-various-dbs-after
  -- 2019-05-30 by alvalongo
  ==================================================================================================== */
  kLINE_FEED   constant varchar2(1):=chr(10);
  --
  procedure pr_copy(p_iHost        varchar2,
                    p_oError   out number,
                    p_oMessage out varchar2
                   );
End pk_remote;
</code>```

3-Package body

```<code>create or replace package body pk_remote
is
  /* ====================================================================================================
  -- ref: question on
  -- https://stackoverflow.com/questions/56339278/creating-and-dropping-dynamically-db-link-each-time-connecting-various-dbs-after
  -- 2019-05-30 by alvalongo
  ==================================================================================================== */
  --
  procedure pr_copy(p_iHost        varchar2,
                    p_oError   out number,
                    p_oMessage out varchar2
                   )
  is
    rcRemote   remote_info%rowtype;
    vLink_name varchar2(30);
    vSentence  varchar2(2000);
    ex_exit    exception;
  Begin
    p_oError:=0;
    p_oMessage:=null;
    if p_iHost is null then
       p_oError:=100;
       p_oMessage:='HOST cannot be null';
       raise ex_exit;
    End if;
    Begin
      select a.*
      into rcRemote
      from remote_info a
      where a.host_name=upper(trim(p_iHost));
    Exception
      when no_data_found then
           p_oError:=sqlcode;
           p_oMessage:='There is no host='||upper(trim(p_iHost));
           raise ex_exit;
    end;
    --
    vLink_name:=upper('DBL_'||rcRemote.host_name);
    --
    vSentence:=  'CREATE DATABASE LINK '||vLink_name||kLINE_FEED
               ||'CONNECT TO '||rcRemote.username_remote||kLINE_FEED
               ||'IDENTIFIED BY '||rcRemote.password_remote||kLINE_FEED
               ||'USING '||rcRemote.host_connection;
     --
     Begin
      execute immediate vSentence;
     Exception
      when others then
           p_oError:=sqlcode;
           p_oMessage:='Error creating db link:'||sqlerrm;
           raise ex_exit;
     end;
    --
    vSentence:=  'insert into '||rcRemote.schema_remote||','||rcRemote.table_remote||'@'||vLink_name||kLINE_FEED
               ||'select *'||kLINE_FEED
               ||'from '||rcRemote.table_local||' a'||kLINE_FEED
               ||'where '||rcRemote.condition;
     Begin
      execute immediate vSentence;
     Exception
      when others then
           p_oError:=sqlcode;
           p_oMessage:='Error inserting:'||sqlerrm;
           raise ex_exit;
     end;
    --
    vSentence:=  'drop DATABASE LINK '||vLink_name;
     --
     Begin
      execute immediate vSentence;
     Exception
      when others then
           p_oError:=sqlcode;
           p_oMessage:='Error dropping db link:'||sqlerrm;
           raise ex_exit;
     end;
  Exception
    when ex_exit then
         null;
    when others then
         p_oError:=sqlcode;
         p_oMessage:=sqlerrm;
  End pr_copy;
  --
End pk_remote;
</code>```

Body:
Warning: There is a security breach about creating and dropping dynamically  db links because a table must store passwords for every remote account.

1-Create a table

Table name: REMOTE_INFO

host_name        varchar2(25) primary_key,
username_remote  varchar2(30),
password_remote  varchar2(30),
host_connection  varchar2(30),
table_local      varchar2(30),
schema_remote    varchar2(30),
table_remote     varchar2(30),
condition        varchar2(4000)

2-Package specification

create or replace package pk_remote
is
  /* ====================================================================================================
  -- ref: question on
  -- https://stackoverflow.com/questions/56339278/creating-and-dropping-dynamically-db-link-each-time-connecting-various-dbs-after
  -- 2019-05-30 by alvalongo
  ==================================================================================================== */
  kLINE_FEED   constant varchar2(1):=chr(10);
  --
  procedure pr_copy(p_iHost        varchar2,
                    p_oError   out number,
                    p_oMessage out varchar2
                   );
End pk_remote;

3-Package body

create or replace package body pk_remote
is
  /* ====================================================================================================
  -- ref: question on
  -- https://stackoverflow.com/questions/56339278/creating-and-dropping-dynamically-db-link-each-time-connecting-various-dbs-after
  -- 2019-05-30 by alvalongo
  ==================================================================================================== */
  --
  procedure pr_copy(p_iHost        varchar2,
                    p_oError   out number,
                    p_oMessage out varchar2
                   )
  is
    rcRemote   remote_info%rowtype;
    vLink_name varchar2(30);
    vSentence  varchar2(2000);
    ex_exit    exception;
  Begin
    p_oError:=0;
    p_oMessage:=null;
    if p_iHost is null then
       p_oError:=100;
       p_oMessage:='HOST cannot be null';
       raise ex_exit;
    End if;
    Begin
      select a.*
      into rcRemote
      from remote_info a
      where a.host_name=upper(trim(p_iHost));
    Exception
      when no_data_found then
           p_oError:=sqlcode;
           p_oMessage:='There is no host='||upper(trim(p_iHost));
           raise ex_exit;
    end;
    --
    vLink_name:=upper('DBL_'||rcRemote.host_name);
    --
    vSentence:=  'CREATE DATABASE LINK '||vLink_name||kLINE_FEED
               ||'CONNECT TO '||rcRemote.username_remote||kLINE_FEED
               ||'IDENTIFIED BY '||rcRemote.password_remote||kLINE_FEED
               ||'USING '||rcRemote.host_connection;
     --
     Begin
      execute immediate vSentence;
     Exception
      when others then
           p_oError:=sqlcode;
           p_oMessage:='Error creating db link:'||sqlerrm;
           raise ex_exit;
     end;
    --
    vSentence:=  'insert into '||rcRemote.schema_remote||','||rcRemote.table_remote||'@'||vLink_name||kLINE_FEED
               ||'select *'||kLINE_FEED
               ||'from '||rcRemote.table_local||' a'||kLINE_FEED
               ||'where '||rcRemote.condition;
     Begin
      execute immediate vSentence;
     Exception
      when others then
           p_oError:=sqlcode;
           p_oMessage:='Error inserting:'||sqlerrm;
           raise ex_exit;
     end;
    --
    vSentence:=  'drop DATABASE LINK '||vLink_name;
     --
     Begin
      execute immediate vSentence;
     Exception
      when others then
           p_oError:=sqlcode;
           p_oMessage:='Error dropping db link:'||sqlerrm;
           raise ex_exit;
     end;
  Exception
    when ex_exit then
         null;
    when others then
         p_oError:=sqlcode;
         p_oMessage:=sqlerrm;
  End pr_copy;
  --
End pk_remote;


问:
Unable to upload and download attachment in corda 4.0 ( java) showing null
uploading and downloading zip attachment containing a text file in corda not working

Tried  to attach and download a zip file manually and also tried to send the attachment using client RPC using proxy.

flow code:

```<code>public class IOUFlow extends FlowLogic<Void> {
    private final Integer iouValue;
    private final Party otherParty;
    private final SecureHash attachmentHash;

    public IOUFlow(Integer iouValue, Party otherParty,SecureHash attachmentHash) {
        this.iouValue = iouValue;
        this.otherParty = otherParty;
        this.attachmentHash=attachmentHash;
    }

    @Override
    public ProgressTracker getProgressTracker() {
        return progressTracker;
    }
    private static final Step ID_OTHER_NODES = new Step("Identifying other nodes on the network.");
    private static final Step SENDING_AND_RECEIVING_DATA = new Step("Sending data between parties.");
    private static final Step EXTRACTING_VAULT_STATES = new Step("Extracting states from the vault.");
    private static final Step OTHER_TX_COMPONENTS = new Step("Gathering a transaction's other components.");
    private static final Step TX_BUILDING = new Step("Building a transaction.");
    private static final Step TX_SIGNING = new Step("Signing a transaction.");
    private static final Step TX_VERIFICATION = new Step("Verifying a transaction.");
    private static final Step SIGS_GATHERING = new Step("Gathering a transaction's signatures.") {
        // Wiring up a child progress tracker allows us to see the
        // subflow's progress steps in our flow's progress tracker.
        @Override
        public ProgressTracker childProgressTracker() {
            return CollectSignaturesFlow.tracker();
        }
    };
    private static final Step VERIFYING_SIGS = new Step("Verifying a transaction's signatures.");
    private static final Step FINALISATION = new Step("Finalising a transaction.") {
        @Override
        public ProgressTracker childProgressTracker() {
            return FinalityFlow.tracker();
        }
    };

    private final ProgressTracker progressTracker = new ProgressTracker(
            ID_OTHER_NODES,
            SENDING_AND_RECEIVING_DATA,
            EXTRACTING_VAULT_STATES,
            OTHER_TX_COMPONENTS,
            TX_BUILDING,
            TX_SIGNING,
            TX_VERIFICATION,
            SIGS_GATHERING,
            FINALISATION
    );

    @Suspendable
    @Override
    public Void call() throws FlowException {
        progressTracker.setCurrentStep(ID_OTHER_NODES);
        // We retrieve the notary identity from the network map.
        Party notary = getServiceHub().getNetworkMapCache().getNotaryIdentities().get(0);

        progressTracker.setCurrentStep(SENDING_AND_RECEIVING_DATA);
        // We create the transaction components.
                IOUState outputState = new IOUState(iouValue, getOurIdentity(), otherParty);
                List<PublicKey> requiredSigners = Arrays.asList(getOurIdentity().getOwningKey(), otherParty.getOwningKey());
                Command command = new Command<>(new IOUContract.Create(), requiredSigners);

        TimeWindow ourAfter = TimeWindow.fromOnly(Instant.MIN);
        progressTracker.setCurrentStep(TX_BUILDING);
        // We create a transaction builder and add the components.
                TransactionBuilder txBuilder = new TransactionBuilder(notary)
                        .addOutputState(outputState, IOUContract.ID)
                        .addCommand(command)
                        .addAttachment(attachmentHash);

        // Verifying the transaction.
                txBuilder.verify(getServiceHub());

        progressTracker.setCurrentStep(TX_SIGNING);
        // Signing the transaction.
                SignedTransaction signedTx = getServiceHub().signInitialTransaction(txBuilder);

        // Creating a session with the other party.
                FlowSession otherPartySession = initiateFlow(otherParty);

        // Obtaining the counterparty's signature.
                SignedTransaction fullySignedTx = subFlow(new CollectSignaturesFlow(
                        signedTx, Arrays.asList(otherPartySession), CollectSignaturesFlow.tracker()));
        progressTracker.setCurrentStep(TX_VERIFICATION);

        // Finalising the transaction.
                subFlow(new FinalityFlow(fullySignedTx, otherPartySession));

                return null;
    }
}
</code>```

client code:

```<code>public class Client {
    private static final Logger logger = LoggerFactory.getLogger(Client.class);

    public static void main(String[] args) throws Exception {
        // Create an RPC connection to the node.
        if (args.length != 3) throw new IllegalArgumentException("Usage: Client <node address> <rpc username> <rpc password>");
        final NetworkHostAndPort nodeAddress = parse(args[0]);
        final String rpcUsername = args[1];
        final String rpcPassword = args[2];
        final CordaRPCClient client = new CordaRPCClient(nodeAddress);
        final CordaRPCOps proxy = client.start(rpcUsername, rpcPassword).getProxy();

        // Interact with the node.
        // For example, here we print the nodes on the network.
        final List<NodeInfo> nodes = proxy.networkMapSnapshot();
        logger.info("{}", nodes);
        InputStream inputstream = new FileInputStream("corda.zip");

        SecureHash hashId= proxy.uploadAttachment(inputstream);
        System.out.println(hashId);

        CordaX500Name x500Name = CordaX500Name.parse("O=ICICI,L=New York,C=US");
        final Party otherParty = proxy.wellKnownPartyFromX500Name(x500Name);

       /* proxy
                .startFlowDynamic(IOUFlow.class, "10", otherParty,hashId)
                .getReturnValue()
                .get();*/

        InputStream stream = proxy.openAttachment(hashId);

        JarInputStream in = new JarInputStream(stream);
        BufferedReader br =new BufferedReader(new InputStreamReader(in));
        System.out.println("Output from attachment :   "+br.readLine());

    }
}
</code>```

Output:

Task :clients:runTemplateClient
  I 16:36:28 1 RPCClient.logElapsedTime - Startup took 2066 msec
  I 16:36:28 1 Client.main - [NodeInfo(addresses=[localhost:10005], legalIdentitiesAndCerts=[O=PNB, L=London, C=GB], platformVersion=4, serial=1559037129874), NodeInfo(addresses=[localhost:10002], legalIdentitiesAndCerts=[O=Notary, L=London, C=GB], platformVersion=4, serial=1559037126875), NodeInfo(addresses=[localhost:10008], legalIdentitiesAndCerts=[O=ICICI, L=New York, C=US], platformVersion=4, serial=1559037128218)]

DF3C198E05092E52F47AE8EAA0D5D26721F344B3F5E0DF80B5A53CA2B7104C9C
Output from attachment :   null

Another output:when tried to send the attachment from client using RPC

Task :clients:runTemplateClient
  I 16:41:46 1 RPCClient.logElapsedTime - Startup took 2045 msec
  I 16:41:47 1 Client.main - [NodeInfo(addresses=[localhost:10005], legalIdentitiesAndCerts=[O=PNB, L=London, C=GB], platformVersion=4, serial=1559037129874), NodeInfo(addresses=[localhost:10002], legalIdentitiesAndCerts=[O=Notary, L=London, C=GB], platformVersion=4, serial=1559037126875), NodeInfo(addresses=[localhost:10008], legalIdentitiesAndCerts=[O=ICICI, L=New York, C=US], platformVersion=4, serial=1559037128218)]
  B7F5F70FC9086ED594883E6EB8B0B53B666B92CC4412E27FF3D6531446E9E40C
  Exception in thread "main" net.corda.core.CordaRuntimeException: net.corda.core.flows.IllegalFlowLogicException: A FlowLogicRef cannot be constructed for FlowLogic of type com.template.flows.IOUFlow: due to missing constructor for arguments: [class java.lang.String, class net.corda.core.identity.Party, class net.corda.core.crypto.SecureHash$SHA256]

答:
```<code>A FlowLogicRef cannot be constructed for FlowLogic of type com.template.flows.IOUFlow: due to missing constructor for arguments: [class java.lang.String, class net.corda.core.identity.Party, class net.corda.core.crypto.SecureHash$SHA256]
</code>```

startFlowDynamic(IOUFlow.class, "10", otherParty,hashId)

It looks like your IOUFlow expects an Integer, and you are sending a String instead?

Body:
uploading and downloading zip attachment containing a text file in corda not working

Tried  to attach and download a zip file manually and also tried to send the attachment using client RPC using proxy.

flow code:

public class IOUFlow extends FlowLogic<Void> {
    private final Integer iouValue;
    private final Party otherParty;
    private final SecureHash attachmentHash;

    public IOUFlow(Integer iouValue, Party otherParty,SecureHash attachmentHash) {
        this.iouValue = iouValue;
        this.otherParty = otherParty;
        this.attachmentHash=attachmentHash;
    }

    @Override
    public ProgressTracker getProgressTracker() {
        return progressTracker;
    }
    private static final Step ID_OTHER_NODES = new Step("Identifying other nodes on the network.");
    private static final Step SENDING_AND_RECEIVING_DATA = new Step("Sending data between parties.");
    private static final Step EXTRACTING_VAULT_STATES = new Step("Extracting states from the vault.");
    private static final Step OTHER_TX_COMPONENTS = new Step("Gathering a transaction's other components.");
    private static final Step TX_BUILDING = new Step("Building a transaction.");
    private static final Step TX_SIGNING = new Step("Signing a transaction.");
    private static final Step TX_VERIFICATION = new Step("Verifying a transaction.");
    private static final Step SIGS_GATHERING = new Step("Gathering a transaction's signatures.") {
        // Wiring up a child progress tracker allows us to see the
        // subflow's progress steps in our flow's progress tracker.
        @Override
        public ProgressTracker childProgressTracker() {
            return CollectSignaturesFlow.tracker();
        }
    };
    private static final Step VERIFYING_SIGS = new Step("Verifying a transaction's signatures.");
    private static final Step FINALISATION = new Step("Finalising a transaction.") {
        @Override
        public ProgressTracker childProgressTracker() {
            return FinalityFlow.tracker();
        }
    };

    private final ProgressTracker progressTracker = new ProgressTracker(
            ID_OTHER_NODES,
            SENDING_AND_RECEIVING_DATA,
            EXTRACTING_VAULT_STATES,
            OTHER_TX_COMPONENTS,
            TX_BUILDING,
            TX_SIGNING,
            TX_VERIFICATION,
            SIGS_GATHERING,
            FINALISATION
    );

    @Suspendable
    @Override
    public Void call() throws FlowException {
        progressTracker.setCurrentStep(ID_OTHER_NODES);
        // We retrieve the notary identity from the network map.
        Party notary = getServiceHub().getNetworkMapCache().getNotaryIdentities().get(0);

        progressTracker.setCurrentStep(SENDING_AND_RECEIVING_DATA);
        // We create the transaction components.
                IOUState outputState = new IOUState(iouValue, getOurIdentity(), otherParty);
                List<PublicKey> requiredSigners = Arrays.asList(getOurIdentity().getOwningKey(), otherParty.getOwningKey());
                Command command = new Command<>(new IOUContract.Create(), requiredSigners);

        TimeWindow ourAfter = TimeWindow.fromOnly(Instant.MIN);
        progressTracker.setCurrentStep(TX_BUILDING);
        // We create a transaction builder and add the components.
                TransactionBuilder txBuilder = new TransactionBuilder(notary)
                        .addOutputState(outputState, IOUContract.ID)
                        .addCommand(command)
                        .addAttachment(attachmentHash);

        // Verifying the transaction.
                txBuilder.verify(getServiceHub());

        progressTracker.setCurrentStep(TX_SIGNING);
        // Signing the transaction.
                SignedTransaction signedTx = getServiceHub().signInitialTransaction(txBuilder);

        // Creating a session with the other party.
                FlowSession otherPartySession = initiateFlow(otherParty);

        // Obtaining the counterparty's signature.
                SignedTransaction fullySignedTx = subFlow(new CollectSignaturesFlow(
                        signedTx, Arrays.asList(otherPartySession), CollectSignaturesFlow.tracker()));
        progressTracker.setCurrentStep(TX_VERIFICATION);

        // Finalising the transaction.
                subFlow(new FinalityFlow(fullySignedTx, otherPartySession));

                return null;
    }
}

client code:

public class Client {
    private static final Logger logger = LoggerFactory.getLogger(Client.class);

    public static void main(String[] args) throws Exception {
        // Create an RPC connection to the node.
        if (args.length != 3) throw new IllegalArgumentException("Usage: Client <node address> <rpc username> <rpc password>");
        final NetworkHostAndPort nodeAddress = parse(args[0]);
        final String rpcUsername = args[1];
        final String rpcPassword = args[2];
        final CordaRPCClient client = new CordaRPCClient(nodeAddress);
        final CordaRPCOps proxy = client.start(rpcUsername, rpcPassword).getProxy();

        // Interact with the node.
        // For example, here we print the nodes on the network.
        final List<NodeInfo> nodes = proxy.networkMapSnapshot();
        logger.info("{}", nodes);
        InputStream inputstream = new FileInputStream("corda.zip");

        SecureHash hashId= proxy.uploadAttachment(inputstream);
        System.out.println(hashId);

        CordaX500Name x500Name = CordaX500Name.parse("O=ICICI,L=New York,C=US");
        final Party otherParty = proxy.wellKnownPartyFromX500Name(x500Name);

       /* proxy
                .startFlowDynamic(IOUFlow.class, "10", otherParty,hashId)
                .getReturnValue()
                .get();*/

        InputStream stream = proxy.openAttachment(hashId);

        JarInputStream in = new JarInputStream(stream);
        BufferedReader br =new BufferedReader(new InputStreamReader(in));
        System.out.println("Output from attachment :   "+br.readLine());

    }
}

Output:

Task :clients:runTemplateClient
  I 16:36:28 1 RPCClient.logElapsedTime - Startup took 2066 msec
  I 16:36:28 1 Client.main - [NodeInfo(addresses=[localhost:10005], legalIdentitiesAndCerts=[O=PNB, L=London, C=GB], platformVersion=4, serial=1559037129874), NodeInfo(addresses=[localhost:10002], legalIdentitiesAndCerts=[O=Notary, L=London, C=GB], platformVersion=4, serial=1559037126875), NodeInfo(addresses=[localhost:10008], legalIdentitiesAndCerts=[O=ICICI, L=New York, C=US], platformVersion=4, serial=1559037128218)]

DF3C198E05092E52F47AE8EAA0D5D26721F344B3F5E0DF80B5A53CA2B7104C9C
Output from attachment :   null

Another output:when tried to send the attachment from client using RPC

Task :clients:runTemplateClient
  I 16:41:46 1 RPCClient.logElapsedTime - Startup took 2045 msec
  I 16:41:47 1 Client.main - [NodeInfo(addresses=[localhost:10005], legalIdentitiesAndCerts=[O=PNB, L=London, C=GB], platformVersion=4, serial=1559037129874), NodeInfo(addresses=[localhost:10002], legalIdentitiesAndCerts=[O=Notary, L=London, C=GB], platformVersion=4, serial=1559037126875), NodeInfo(addresses=[localhost:10008], legalIdentitiesAndCerts=[O=ICICI, L=New York, C=US], platformVersion=4, serial=1559037128218)]
  B7F5F70FC9086ED594883E6EB8B0B53B666B92CC4412E27FF3D6531446E9E40C
  Exception in thread "main" net.corda.core.CordaRuntimeException: net.corda.core.flows.IllegalFlowLogicException: A FlowLogicRef cannot be constructed for FlowLogic of type com.template.flows.IOUFlow: due to missing constructor for arguments: [class java.lang.String, class net.corda.core.identity.Party, class net.corda.core.crypto.SecureHash$SHA256]

Body:
A FlowLogicRef cannot be constructed for FlowLogic of type com.template.flows.IOUFlow: due to missing constructor for arguments: [class java.lang.String, class net.corda.core.identity.Party, class net.corda.core.crypto.SecureHash$SHA256]

startFlowDynamic(IOUFlow.class, "10", otherParty,hashId)

It looks like your IOUFlow expects an Integer, and you are sending a String instead?


问:
Cron isn't running when I start my docker container
To preface, I have been referencing these two articles for help:

Run a cron job with Docker - Julien Boulay

Running cron jobs inside a Docker container - Chris S.

My goal is to have a cron job automatically start when I start my docker container. Currently, it doesn't automatically start, but I can manually go into my container and run service cron start, which starts the job, and it works correctly.

So the problem is: How do I get my cron job to start automatically when my container starts up?

Dockerfile

```<code>FROM microsoft/dotnet:latest
RUN apt-get update && apt-get install -y cron

COPY . /app

WORKDIR /app

ADD crontab /etc/cron.d/crontab
RUN chmod 0600 /etc/cron.d/crontab
RUN crontab -u root /etc/cron.d/crontab
RUN touch /var/log/cron.log

RUN ["dotnet", "restore"]

RUN ["dotnet", "build"]

EXPOSE 5000/tcp

CMD cron && tail -f /var/log/cron.log
CMD service cron start
</code>```

crontab

```<code>* * * * * echo "Hello world" >> /var/log/cron.log 2>&1
# Empty space
</code>```

Though I wasn't able to get cron working in that particular container, I was able to create a standalone docker container specifically for cron, and was successful in getting it to run automatically.

As far as setup for the cron container, I followed the linked article, Run a cron job with Docker - Julien Boulay, and was able to get it working.

答:
I know this is an old question but I found a fix to this on Debian and it solved my problem. Cron pam auth with uid was breaking my cron from being able to run.</p>

```<code>RUN sed -i '/session    required     pam_loginuid.so/c\#session    required     pam_loginuid.so/' /etc/pam.d/cron
</code>```

Body:
To preface, I have been referencing these two articles for help:

Run a cron job with Docker - Julien Boulay

Running cron jobs inside a Docker container - Chris S.

My goal is to have a cron job automatically start when I start my docker container. Currently, it doesn't automatically start, but I can manually go into my container and run service cron start, which starts the job, and it works correctly.

So the problem is: How do I get my cron job to start automatically when my container starts up?

Dockerfile

FROM microsoft/dotnet:latest
RUN apt-get update && apt-get install -y cron

COPY . /app

WORKDIR /app

ADD crontab /etc/cron.d/crontab
RUN chmod 0600 /etc/cron.d/crontab
RUN crontab -u root /etc/cron.d/crontab
RUN touch /var/log/cron.log

RUN ["dotnet", "restore"]

RUN ["dotnet", "build"]

EXPOSE 5000/tcp

CMD cron && tail -f /var/log/cron.log
CMD service cron start

crontab

* * * * * echo "Hello world" >> /var/log/cron.log 2>&1
# Empty space

Though I wasn't able to get cron working in that particular container, I was able to create a standalone docker container specifically for cron, and was successful in getting it to run automatically.

As far as setup for the cron container, I followed the linked article, Run a cron job with Docker - Julien Boulay, and was able to get it working.

Body:
I know this is an old question but I found a fix to this on Debian and it solved my problem. Cron pam auth with uid was breaking my cron from being able to run.

RUN sed -i '/session    required     pam_loginuid.so/c\#session    required     pam_loginuid.so/' /etc/pam.d/cron