问:
Help in sql query
I have a table:

```<code>ID  Title   Date
30   1     10/10/2010
20   1     10/11/2010
40   2     01/01/2010
</code>```

i need a way to select distinct titles with max dates.

so when title is 1, i should have the second row selected since the date in the 1st row is smaller than the date in the second row.

as a result the query should return:

```<code>20 1 10/11/2010
40 2 01/01/2010
</code>```

答:
```<code>select
max(ID), Title , max(Date)
from
table
group by
Title
</code>```

Title: Help in sql query

Body:
I have a table:

ID  Title   Date
30   1     10/10/2010
20   1     10/11/2010
40   2     01/01/2010

i need a way to select distinct titles with max dates.

so when title is 1, i should have the second row selected since the date in the 1st row is smaller than the date in the second row.

as a result the query should return:

20 1 10/11/2010
40 2 01/01/2010


来源: stackexchange

问:
ActiveRecord Query to identify orphan child records
I have Post and User models. Every post belongs to a user. However, during database import, some erroneous user_ids have been entered on some posts. What would be the query to get posts whose user_ids don't refer to any user? Thanks.</p>

答:
Sanjay,

all the solutions proposed works fine for small tables, but depending on the size of the tables involved, and the amount of memory and processing power available, for performance reasons, you might want to use a LEFT OUTER JOIN, like this:

```<code>Post.joins("LEFT OUTER JOIN users ON posts.user_id = user.id")
    .where("user.id IS NULL")
</code>```

In Rails 5, there is support for LEFT OUTER JOIN in ActiveRecord.

Regards

ContentLicense: CC BY-SA 3.0

Body:
Sanjay,

all the solutions proposed works fine for small tables, but depending on the size of the tables involved, and the amount of memory and processing power available, for performance reasons, you might want to use a LEFT OUTER JOIN, like this:

Post.joins("LEFT OUTER JOIN users ON posts.user_id = user.id")
    .where("user.id IS NULL")

In Rails 5, there is support for LEFT OUTER JOIN in ActiveRecord.

Regards


问:
Update buffer and reset the locking-mode back to original one
Lets say we have a procedure which takes in a buffer-parameter:

myprocedure.p:

```<code>DEF PARAM BUFFER bufferParameter FOR DatabaseTable.

/* Get the same buffer in EXCLUSIVE-LOCK for updating */
FIND CURRENT bufferParameter EXCLUSIVE-LOCK.

/* Update the value */
ASSIGN bufferParameter.MyField = "new value".

/* Reset the locking mode back to the original one? */
FIND CURRENT bufferParameter NO-LOCK.
</code>```

The problem with this approach is that it is possibly changing the original locking-mode of the passed buffer parameter. It is possible that the buffer was in EXCLUSIVE-LOCK or f.ex in NO-LOCK. By changing the locking-mode, this procedure could invoke updating errors in some other programs using this same buffer.

Another solution would be to create a new temporary buffer for the same table, and then update the database thru that buffer (without touching the passed parameter buffer). The con of this approach is that the original passed buffer parameter will become 'out-of-date'. It would require a new database query to update it's 'MyField' value to match the one in the database.

How I could reset the buffer's locking-mode back to the original one after updating it's fields?

答:
So I figured out that I was wrong when I thought that the original buffer was not updated when another buffer with that same record has updated the same record.

So a good way to update a passed buffer is to get the same record by ROWID and update it in another buffer separately:

```<code>DEF BUFFER myFirstBuffer FOR MyTable.
DEF BUFFER mySecondBuffer FOR MyTable.

FIND FIRST myFirstBuffer WHERE myFirstBuffer.MyField = "myvalue" NO-LOCK.

/* At this moment myFirstBuffer.MyField is "myvalue" */

FIND FIRST mySecondBuffer WHERE ROWID(mySecondBuffer) = ROWID(myFirstBuffer) EXCLUSIVE-LOCK.
ASSIGN mySecondBuffer.MyField = "mynewvalue".

/* Now both 'myFirstBuffer.MyField' and 'mySecondBuffer.MyField' match ("mynewvalue")! */
</code>```

The Progress seems to handle all of the data changes and updates the buffers accordingly. However, I believe that this doesn't work if there are 2 separate programs running, f.ex myprogram1.p and myprogram2.p and they both update the same record at a different time (though this is another story...).
Earlier we had some problems with TRIGGERs when the trigger affected fields were not updated on the buffer.

But in a nutshell, I think it's best to query the record separately with the ROWID and update it that way. I do believe that the developer shouldn't use FIND CURRENT myBuffer NO-LOCK. as that will change the locking-mode of the record and could break logics using myBuffer later.

Body:
Lets say we have a procedure which takes in a buffer-parameter:

myprocedure.p:

DEF PARAM BUFFER bufferParameter FOR DatabaseTable.

/* Get the same buffer in EXCLUSIVE-LOCK for updating */
FIND CURRENT bufferParameter EXCLUSIVE-LOCK.

/* Update the value */
ASSIGN bufferParameter.MyField = "new value".

/* Reset the locking mode back to the original one? */
FIND CURRENT bufferParameter NO-LOCK.

The problem with this approach is that it is possibly changing the original locking-mode of the passed buffer parameter. It is possible that the buffer was in EXCLUSIVE-LOCK or f.ex in NO-LOCK. By changing the locking-mode, this procedure could invoke updating errors in some other programs using this same buffer.

Another solution would be to create a new temporary buffer for the same table, and then update the database thru that buffer (without touching the passed parameter buffer). The con of this approach is that the original passed buffer parameter will become 'out-of-date'. It would require a new database query to update it's 'MyField' value to match the one in the database.

How I could reset the buffer's locking-mode back to the original one after updating it's fields?

Body:
So I figured out that I was wrong when I thought that the original buffer was not updated when another buffer with that same record has updated the same record.

So a good way to update a passed buffer is to get the same record by ROWID and update it in another buffer separately:

DEF BUFFER myFirstBuffer FOR MyTable.
DEF BUFFER mySecondBuffer FOR MyTable.

FIND FIRST myFirstBuffer WHERE myFirstBuffer.MyField = "myvalue" NO-LOCK.

/* At this moment myFirstBuffer.MyField is "myvalue" */

FIND FIRST mySecondBuffer WHERE ROWID(mySecondBuffer) = ROWID(myFirstBuffer) EXCLUSIVE-LOCK.
ASSIGN mySecondBuffer.MyField = "mynewvalue".

/* Now both 'myFirstBuffer.MyField' and 'mySecondBuffer.MyField' match ("mynewvalue")! */

The Progress seems to handle all of the data changes and updates the buffers accordingly. However, I believe that this doesn't work if there are 2 separate programs running, f.ex myprogram1.p and myprogram2.p and they both update the same record at a different time (though this is another story...).
Earlier we had some problems with TRIGGERs when the trigger affected fields were not updated on the buffer.

But in a nutshell, I think it's best to query the record separately with the ROWID and update it that way. I do believe that the developer shouldn't use FIND CURRENT myBuffer NO-LOCK. as that will change the locking-mode of the record and could break logics using myBuffer later.


问:
JavaScript transfering one element to another (multiple times) by using event
I want to transfer multiple times after click on "przenieś" the whole li from one div class="listContainer two" to another, and back again (and again) using JavaScript. How should I prepare the JavaScript code for the most efficient way?

Item 1 z listy 1 Przenieś

Item 2 z listy 1 Przenieś

Item 1 z listy 2 Przenieś

Item 2 z listy 2 Przenieś

```

答:
Add an onlclick listener to your button.  Have it run a javascript function that moves the li items to the other ul.

Item 1 z listy 1 <button type="button" onclick="buttonClick(this.parentNode);">PrzenieśMe!</button>

Item 2 z listy 1 <button type="button" onclick="buttonClick(this.parentNode);">PrzenieśMe!</button>

Item 1 z listy 2 <button type="button" onclick="buttonClick(this.parentNode);">PrzenieśMe!</button>

Item 2 z listy 2 <button type="button" onclick="buttonClick(this.parentNode);">PrzenieśMe!</button>

```

Body:
Add an onlclick listener to your button.  Have it run a javascript function that moves the li items to the other ul.

<div class="listContainer two">
  <ul id="list1">
    <li>Item 1 z listy 1 <button type="button" onclick="buttonClick(this.parentNode);">PrzenieśMe!</button></li>
    <li>Item 2 z listy 1 <button type="button" onclick="buttonClick(this.parentNode);">PrzenieśMe!</button></li>
  </ul>
</div>

<div  class="listContainer two">
  <ul id="list2">
    <li>Item 1 z listy 2 <button type="button" onclick="buttonClick(this.parentNode);">PrzenieśMe!</button></li>
    <li>Item 2 z listy 2 <button type="button" onclick="buttonClick(this.parentNode);">PrzenieśMe!</button></li>
  </ul>
</div>

<script>
function buttonClick(li) {
  var ul = li.parentNode
  var listOfUl = document.getElementsByTagName('ul');
  for(var i = 0; i < listOfUl.length; i++) {
     if(listOfUl[i].id != ul.id) {
       listOfUl[i].appendChild(li);
     }
   }
}
</script>


问:
Access builds from Parallel execution in Jenkins 2.0 Pipeline
I'm currently using the Build Flow plugin, which seems to have been abandoned in favor of Pipelines in Jenkins 2.0.

Running into some problems re-building our existing jobs using the new pipelines.

Currently, I have code similar to this:

```<code>ignore(FAILURE) {
  join = parallel([
    job1: {build('job1')},
    job2: {build('job2')},
    job3: {build('job3')}
  ])
}
results = [join.job1.result.toString(), join.job2.result.toString(), join.job2.result.toString()]

if(join.job1.result.toString() == 'SUCCESS') {
  buildList << join.job1.lastBuild.getDisplayName()
}
</code>```

The goal here is to run multiple existing jobs in parallel, and then access information about the builds that completed. This has been working without issue in the Build Flow plugin.

I have been unable find a way to access this data using the new Pipelines.

```<code>echo 'Checking streams for latest builds'
join = [:]

join['Job1'] = { build job: 'Job1', parameters: [[$class: 'StringParameterValue', name: 'TimeWindow', value: '1200']], propagate: false}
join['Job2'] = { build job: 'Job2', parameters: [[$class: 'StringParameterValue', name: 'TimeWindow', value: '1200']], propagate: false}
join['Job3'] = { build job: 'Job3', parameters: [[$class: 'StringParameterValue', name: 'TimeWindow', value: '1200']], propagate: false}

parallel join
</code>```

A dump of join['Job1'] doesn't give access to an AbstractBuild or similar, the way the Build Flow plugin does. Instead, it shows:

```<code><org.jenkinsci.plugins.workflow.cps.CpsClosure2@2eac6ed9
def=com.cloudbees.groovy.cps.impl.CpsClosureDef@59647704
delegate=WorkflowScript@3aa1807f
owner=WorkflowScript@3aa1807f
thisObject=WorkflowScript@3aa1807f
resolveStrategy=0
directive=0
parameterTypes=null
maximumNumberOfParameters=0
bcw=null>
</code>```

Using the new Pipelines, is there a way to access data like job1.result, job1.lastBuild, job1.lastBuild.getDisplayName()?

答:
a little late but you can also define the runWrapper object returned by build command in your closure and place it in a map defined outside of the parallel command.

Here's an example. Note: I am using propagate: false so that exceptions (JUnit test failures, etc) are not thrown. You would have to decide how you want to handle exceptions, try/catch/finally, etc.

Example Pipeline Job to execute (needs to be parameterized with a string param commandStr):

```<code>env.PASSED_CMD="${params.commandStr}"
stage('command-exec') {
    node {
        sh "${commandStr}"
    }
}
</code>```

Executing job (config):

```<code>buildRuns = [:]
buildResults = [:]
def buildClosure(String jobKey, String paramAValue) {
    return {
        def runWrapper = build(
            job: 'command-test-job',
            propagate: false,
            parameters: [[$class: 'StringParameterValue', name: 'commandStr', value: paramAValue]]
        )
        buildResults."$jobKey" = runWrapper
    }
}
buildRuns."job1" = buildClosure("job1", "echo 'HI' && exit 0")
buildRuns."job2" = buildClosure("job2", "echo 'HO' && exit 0")
parallel buildRuns
for(k in buildRuns.keySet()) {
    def runResult = buildResults."$k"
    echo "$k -> ${runResult.result}"
    echo "$k -> ${runResult.buildVariables.PASSED_CMD}"
}
</code>```

The build log shows:

```<code>[Pipeline] parallel
[Pipeline] [job1] { (Branch: job1)
[Pipeline] [job2] { (Branch: job2)
[Pipeline] [job1] build (Building command-test-job)
[job1] Scheduling project: command-test-job
[Pipeline] [job2] build (Building command-test-job)
[job2] Scheduling project: command-test-job
[job1] Starting building: command-test-job #7
[job2] Starting building: command-test-job #8
[Pipeline] [job2] }
[Pipeline] [job1] }
[Pipeline] // parallel
[Pipeline] echo
job1 -> SUCCESS
[Pipeline] echo
job1 -> echo 'HI' && exit 0
[Pipeline] echo
job2 -> SUCCESS
[Pipeline] echo
job2 -> echo 'HO' && exit 0
[Pipeline] End of Pipeline
Finished: SUCCESS
</code>```

Body:
I'm currently using the Build Flow plugin, which seems to have been abandoned in favor of Pipelines in Jenkins 2.0.

Running into some problems re-building our existing jobs using the new pipelines.

Currently, I have code similar to this:

ignore(FAILURE) {
  join = parallel([
    job1: {build('job1')},
    job2: {build('job2')},
    job3: {build('job3')}
  ])
}
results = [join.job1.result.toString(), join.job2.result.toString(), join.job2.result.toString()]

if(join.job1.result.toString() == 'SUCCESS') {
  buildList << join.job1.lastBuild.getDisplayName()
}

The goal here is to run multiple existing jobs in parallel, and then access information about the builds that completed. This has been working without issue in the Build Flow plugin.

I have been unable find a way to access this data using the new Pipelines.

echo 'Checking streams for latest builds'
join = [:]

join['Job1'] = { build job: 'Job1', parameters: [[$class: 'StringParameterValue', name: 'TimeWindow', value: '1200']], propagate: false}
join['Job2'] = { build job: 'Job2', parameters: [[$class: 'StringParameterValue', name: 'TimeWindow', value: '1200']], propagate: false}
join['Job3'] = { build job: 'Job3', parameters: [[$class: 'StringParameterValue', name: 'TimeWindow', value: '1200']], propagate: false}

parallel join

A dump of join['Job1'] doesn't give access to an AbstractBuild or similar, the way the Build Flow plugin does. Instead, it shows:

<org.jenkinsci.plugins.workflow.cps.CpsClosure2@2eac6ed9
def=com.cloudbees.groovy.cps.impl.CpsClosureDef@59647704
delegate=WorkflowScript@3aa1807f
owner=WorkflowScript@3aa1807f
thisObject=WorkflowScript@3aa1807f
resolveStrategy=0
directive=0
parameterTypes=null
maximumNumberOfParameters=0
bcw=null>

Using the new Pipelines, is there a way to access data like job1.result, job1.lastBuild, job1.lastBuild.getDisplayName()?

Body:
a little late but you can also define the runWrapper object returned by build command in your closure and place it in a map defined outside of the parallel command.

Here's an example. Note: I am using propagate: false so that exceptions (JUnit test failures, etc) are not thrown. You would have to decide how you want to handle exceptions, try/catch/finally, etc.

Example Pipeline Job to execute (needs to be parameterized with a string param commandStr):

env.PASSED_CMD="${params.commandStr}"
stage('command-exec') {
    node {
        sh "${commandStr}"
    }
}

Executing job (config):

buildRuns = [:]
buildResults = [:]
def buildClosure(String jobKey, String paramAValue) {
    return {
        def runWrapper = build(
            job: 'command-test-job',
            propagate: false,
            parameters: [[$class: 'StringParameterValue', name: 'commandStr', value: paramAValue]]
        )
        buildResults."$jobKey" = runWrapper
    }
}
buildRuns."job1" = buildClosure("job1", "echo 'HI' && exit 0")
buildRuns."job2" = buildClosure("job2", "echo 'HO' && exit 0")
parallel buildRuns
for(k in buildRuns.keySet()) {
    def runResult = buildResults."$k"
    echo "$k -> ${runResult.result}"
    echo "$k -> ${runResult.buildVariables.PASSED_CMD}"
}

The build log shows:

[Pipeline] parallel
[Pipeline] [job1] { (Branch: job1)
[Pipeline] [job2] { (Branch: job2)
[Pipeline] [job1] build (Building command-test-job)
[job1] Scheduling project: command-test-job
[Pipeline] [job2] build (Building command-test-job)
[job2] Scheduling project: command-test-job
[job1] Starting building: command-test-job #7
[job2] Starting building: command-test-job #8
[Pipeline] [job2] }
[Pipeline] [job1] }
[Pipeline] // parallel
[Pipeline] echo
job1 -> SUCCESS
[Pipeline] echo
job1 -> echo 'HI' && exit 0
[Pipeline] echo
job2 -> SUCCESS
[Pipeline] echo
job2 -> echo 'HO' && exit 0
[Pipeline] End of Pipeline
Finished: SUCCESS


问:
How to convert a column of a dataframe from char to ascii integers? [Pandas]
I have a dataframe in which one columns called 'label' holds values like 'b', 'm', 'n' etc.

I want 'label' to instead hold the ascii equivalent of the letter.
How do I do it?

答:
IIUC:

```<code>In [81]:
df = pd.DataFrame({'label':list('bmn')})
df

Out[81]:
  label
0     b
1     m
2     n

In [82]:
df['ascii'] = df['label'].apply(ord)
df

Out[82]:
  label  ascii
0     b     98
1     m    109
2     n    110
</code>```

It maybe quicker to do a list comprehension:

```<code>In [83]:
df['ascii'] = [ord(x) for x in df['label']]
df

Out[83]:
  label  ascii
0     b     98
1     m    109
2     n    110
</code>```

You can also use map:

```<code>In [85]:
df['ascii'] = df['label'].map(ord)
df

Out[85]:
  label  ascii
0     b     98
1     m    109
2     n    110
</code>```

Timings

for a small df:

```<code>In [87]:
%timeit [ord(x) for x in df['label']]
%timeit df['label'].map(ord)
%timeit df['label'].apply(ord)

100000 loops, best of 3: 14 µs per loop
10000 loops, best of 3: 123 µs per loop
10000 loops, best of 3: 146 µs per loop
</code>```

For a 3K df:

```<code>In [89]:
%timeit [ord(x) for x in df['label']]
%timeit df['label'].map(ord)
%timeit df['label'].apply(ord)

1000 loops, best of 3: 246 µs per loop
1000 loops, best of 3: 1 ms per loop
1000 loops, best of 3: 1.02 ms per loop
</code>```

So here the list comprehension scales better than the other methods

Body:
IIUC:

In [81]:
df = pd.DataFrame({'label':list('bmn')})
df

Out[81]:
  label
0     b
1     m
2     n

In [82]:
df['ascii'] = df['label'].apply(ord)
df

Out[82]:
  label  ascii
0     b     98
1     m    109
2     n    110

It maybe quicker to do a list comprehension:

In [83]:
df['ascii'] = [ord(x) for x in df['label']]
df

Out[83]:
  label  ascii
0     b     98
1     m    109
2     n    110

You can also use map:

In [85]:
df['ascii'] = df['label'].map(ord)
df

Out[85]:
  label  ascii
0     b     98
1     m    109
2     n    110

Timings

for a small df:

In [87]:
%timeit [ord(x) for x in df['label']]
%timeit df['label'].map(ord)
%timeit df['label'].apply(ord)

100000 loops, best of 3: 14 µs per loop
10000 loops, best of 3: 123 µs per loop
10000 loops, best of 3: 146 µs per loop

For a 3K df:

In [89]:
%timeit [ord(x) for x in df['label']]
%timeit df['label'].map(ord)
%timeit df['label'].apply(ord)

1000 loops, best of 3: 246 µs per loop
1000 loops, best of 3: 1 ms per loop
1000 loops, best of 3: 1.02 ms per loop

So here the list comprehension scales better than the other methods


问:
Directline 3.0 API, StreamUrl with ClientWebSocket
I creating a bot connector using Directline 3.0 API. After starting a new Conversation using DirectlineClient object, I get the StreamUrl. How can I use it to communicate with the Bot? I tried one sample given here.(http://itq.nl/net-4-5-websocket-client-without-a-browser/) but it does not work. #botframework</p>

答:
A new sample using C# + DirectLine v3.0 + WebSockets is currently under review and will soon be merged into the BotBuilder-samples repository.

Take a look to this Pull Request to see the code of the new sample.


问:
agent-based simulation of software engineering problems?
Has there been any agent-based simulation models built for investigating software engineering processes or problems? (e.g. collaboration in agile vs. traditional warefall, QA defect trends, open source project growth...etc)</p>

答:
In case you didn't find anything, there's some academic work that's related -- for example
this by Madey, Freeh and Tynan which discusses OSS development as social network, and this by the same authors who then go on to model it using Swarm</p>

ContentLicense: CC BY-SA 2.5


问:
Target bytecode always drop back to 1.5 in IntelliJ
I have a collection of "Samples" projects. The toplevel project is empty, while it contains a lot of modules.

Unfortunately, I am often required to set target bytecode to 1.5.

I did that many times from the beginning of the project, but it still drops back to 1.5.

How to stuck with 1.8 forever?

答:
You can use this in your pom:

(https://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html)

```<code>  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
      <source>1.8</source>
      <target>1.8</target>
    </configuration>
  </plugin>
</code>```

Body:
You can use this in your pom:

(https://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html)

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
      <source>1.8</source>
      <target>1.8</target>
    </configuration>
  </plugin>


问:
How to validate a user chose at least one checkbox in a CheckBoxList?
I've got a CheckBoxList control that I want to require the user to check at least ONE box, it does not matter if they check every single one, or 3, or even just one.

In the spirit of asp.net's validation controls, what can I use to enforce this? I'm also using the Ajax validation extender, so it would be nice if it could look like other controls, and not some cheesy server validate method in the codebehind.

```<code><asp:CheckBoxList RepeatDirection="Horizontal" RepeatLayout="Table" RepeatColumns="3" ID="ckBoxListReasons" runat="server">
    <asp:ListItem Text="Preliminary Construction" Value="prelim_construction" />
    <asp:ListItem Text="Final Construction" Value="final_construction" />
    <asp:ListItem Text="Construction Alteration" Value="construction_alteration" />
    <asp:ListItem Text="Remodel" Value="remodel" />
    <asp:ListItem Text="Color" Value="color" />
    <asp:ListItem Text="Brick" Value="brick" />
    <asp:ListItem Text="Exterior Lighting" Value="exterior_lighting" />
    <asp:ListItem Text="Deck/Patio/Flatwork" Value="deck_patio_flatwork" />
    <asp:ListItem Text="Fence/Screening" Value="fence_screening" />
    <asp:ListItem Text="Landscape - Front" Value="landscape_front" />
    <asp:ListItem Text="Landscape - Side/Rear" Value="landscape_side_rear" />
    <asp:ListItem Text="Other" Value="other" />
</asp:CheckBoxList>
</code>```

答:
You can use a CustomValidator for that with a little bit of javascript.

```<code><asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Select at least one"
    ClientValidationFunction="checkCheckBoxList"></asp:CustomValidator>

<script type="text/javascript">
    function checkCheckBoxList(oSrc, args) {
        var isValid = false;
        $("#<%= CheckBoxList1.ClientID %> input[type='checkbox']:checked").each(function (i, obj) {
            isValid = true;
        });
        args.IsValid = isValid;
    }
</script>
</code>```

And for a RadioButtonList

```<code><asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Select at least one" ClientValidationFunction="checkRadioButtonList"></asp:CustomValidator>

<script type="text/javascript">
    function checkRadioButtonList(oSrc, args) {
        if ($("input[name='<%= RadioButtonList1.UniqueID %>']:checked").val() == null) {
            args.IsValid = false;
        } else {
            args.IsValid = true;
        }
    }
</script>
</code>```

Body:
I've got a CheckBoxList control that I want to require the user to check at least ONE box, it does not matter if they check every single one, or 3, or even just one.

In the spirit of asp.net's validation controls, what can I use to enforce this? I'm also using the Ajax validation extender, so it would be nice if it could look like other controls, and not some cheesy server validate method in the codebehind.

<asp:CheckBoxList RepeatDirection="Horizontal" RepeatLayout="Table" RepeatColumns="3" ID="ckBoxListReasons" runat="server">
    <asp:ListItem Text="Preliminary Construction" Value="prelim_construction" />
    <asp:ListItem Text="Final Construction" Value="final_construction" />
    <asp:ListItem Text="Construction Alteration" Value="construction_alteration" />
    <asp:ListItem Text="Remodel" Value="remodel" />
    <asp:ListItem Text="Color" Value="color" />
    <asp:ListItem Text="Brick" Value="brick" />
    <asp:ListItem Text="Exterior Lighting" Value="exterior_lighting" />
    <asp:ListItem Text="Deck/Patio/Flatwork" Value="deck_patio_flatwork" />
    <asp:ListItem Text="Fence/Screening" Value="fence_screening" />
    <asp:ListItem Text="Landscape - Front" Value="landscape_front" />
    <asp:ListItem Text="Landscape - Side/Rear" Value="landscape_side_rear" />
    <asp:ListItem Text="Other" Value="other" />
</asp:CheckBoxList>

Body:
You can use a CustomValidator for that with a little bit of javascript.

<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Select at least one"
    ClientValidationFunction="checkCheckBoxList"></asp:CustomValidator>

<script type="text/javascript">
    function checkCheckBoxList(oSrc, args) {
        var isValid = false;
        $("#<%= CheckBoxList1.ClientID %> input[type='checkbox']:checked").each(function (i, obj) {
            isValid = true;
        });
        args.IsValid = isValid;
    }
</script>

And for a RadioButtonList

<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Select at least one" ClientValidationFunction="checkRadioButtonList"></asp:CustomValidator>

<script type="text/javascript">
    function checkRadioButtonList(oSrc, args) {
        if ($("input[name='<%= RadioButtonList1.UniqueID %>']:checked").val() == null) {
            args.IsValid = false;
        } else {
            args.IsValid = true;
        }
    }
</script>


问:
How can realize border radius like egg
Can I realize this style of image with css3?

I have set this style of border in

```<code>.image img {border-radius: 40% 60% 60% 40%/50%; }
</code>```

, but I think that isn't right one.

答:
You could create something similar with pseudo-elemnts. First to create that shape you can use border-radius and then you can add large box-shadow for gray area and one more for that blue shadow.

.egg {
  position: relative;
  overflow: hidden;
  height: 400px;
  width: 400px;
}

.egg:after {
  content: '';
  width: 250px;
  position: absolute;
  top: 0;
  left: 0;
  height: 200px;
  margin: 50px;
  transform: rotate(-135deg);
  box-shadow: -7px -7px 0px 0px #67BEF9, 0px 0px 0px 400px #ECECEC;
  border-radius: 204px 109px 106px 212px / 125px 110px 110px 125px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="egg">
  <img src="https://st.hzcdn.com/simgs/25e1d6580f5a3538_4-1972/traditional-staircase.jpg" alt="">
</div></code>```

Title: How can realize border radius like egg

Body:
Can I realize this style of image with css3?

I have set this style of border in

.image img {border-radius: 40% 60% 60% 40%/50%; }

, but I think that isn't right one.

Body:
You could create something similar with pseudo-elemnts. First to create that shape you can use border-radius and then you can add large box-shadow for gray area and one more for that blue shadow.

.egg {
  position: relative;
  overflow: hidden;
  height: 400px;
  width: 400px;
}

.egg:after {
  content: '';
  width: 250px;
  position: absolute;
  top: 0;
  left: 0;
  height: 200px;
  margin: 50px;
  transform: rotate(-135deg);
  box-shadow: -7px -7px 0px 0px #67BEF9, 0px 0px 0px 400px #ECECEC;
  border-radius: 204px 109px 106px 212px / 125px 110px 110px 125px;
}

<div class="egg">
  <img src="https://st.hzcdn.com/simgs/25e1d6580f5a3538_4-1972/traditional-staircase.jpg" alt="">
</div>


问:
Error 401: Firebase push notification getting 401 error
I'm facing the following issue with firebase when tried to access through https:// URI but same code works fine with http:// URI:

Error 401: Invalid (legacy) Server-key delivered or Sender is not authorized to perform a request.

//firebase server url to send the curl request.

```<code>    $url = 'https://fcm.googleapis.com/fcm/send';

    //building headers for the request
    $headers = array(
        'Authorization: key=' . FIREBASE_API_KEY,
        'Content-Type: application/json'
    );

    //Initializing curl to open a connection
    $ch = curl_init();
    //Setting the curl url
    curl_setopt($ch, CURLOPT_URL, $url);
    //setting the method as post
    curl_setopt($ch, CURLOPT_PORT, 443);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //disabling ssl support
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    //adding headers
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    //adding the fields in json format
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    //finally executing the curl request
    $result = curl_exec($ch);
    /*if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }*/
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($status != 201) {
        echo "Error123: call to URL $url failed with status $status, response $result, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch) . '<br>';
    }

    //Now close the connection
    curl_close($ch);
</code>```

答: Got the solution from firebase(Domain SSL issue)...and working perfectly!</p>

Body:
I'm facing the following issue with firebase when tried to access through https:// URI but same code works fine with http:// URI:

Error 401: Invalid (legacy) Server-key delivered or Sender is not authorized to perform a request.

//firebase server url to send the curl request.

    $url = 'https://fcm.googleapis.com/fcm/send';

    //building headers for the request
    $headers = array(
        'Authorization: key=' . FIREBASE_API_KEY,
        'Content-Type: application/json'
    );

    //Initializing curl to open a connection
    $ch = curl_init();
    //Setting the curl url
    curl_setopt($ch, CURLOPT_URL, $url);
    //setting the method as post
    curl_setopt($ch, CURLOPT_PORT, 443);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //disabling ssl support
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    //adding headers
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    //adding the fields in json format
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    //finally executing the curl request
    $result = curl_exec($ch);
    /*if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }*/
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($status != 201) {
        echo "Error123: call to URL $url failed with status $status, response $result, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch) . '
';
    }

    //Now close the connection
    curl_close($ch);


问:
Making sure the ships do not overlap
I have been stuck on this task for a long time now, so I thought it was about time to ask for some help. I am making a game of battle ship and I am currently writing a function where the ships are randomly placed on the 10 x 10 grid. I have this completed, but my problem is when they overlap.

I cannot figure out a way to get coordinates where they don't overlap with a previously randomly placed ship. In my current code I am trying to figure out a way to make it so that if a coordinate overlaps it will loop the ship over again until it has the right amount of cells that do not overlap with any other ship. I am writing in a 3 file format, so I will include the needed code from each file.

In the function, the up down left or right is random, so in the battle ship I have direction = 0 so that I am only working with up

Here is the header file

```<code>typedef struct game_board
{
    int board[10][10];
    int row;
    int col;
    char symbol;
}Game_Board;

Game_Board initalize_game_board(Game_Board *player);

//Game_Board manually_place_ships_on_board(Game_Board *player);
Game_Board randomlly_place_ships_on_board(Game_Board *player);
</code>```

Main

```<code>Game_Board person, computer;
    int who_goes_first = 0;

    person.symbol = '~';
    person.row = 10;
    person.col = 10;
    computer.symbol = '-';
    computer.row = 10;
    computer.col = 10;

    welcome_screen(outfile);

    printf("Player 1\n");
    initalize_game_board(&person);
    printf("\nPlayer 2\n");
    initalize_game_board(&computer);
    who_goes_first = select_who_starts_first();
    //manually_place_ships_on_board(&person);
    randomlly_place_ships_on_board(&computer);
</code>```

The function. I am only including the first 2 ship for redundancy reasons

```<code>int direction = 0, i = 0, cell_row = 0, cell_col = 0;

    //Carrier
    printf("CARRIER\n");
    direction = rand() % 4;
    printf("Direction: %d\n", direction);
    player->symbol = 'c';
    if (direction == 0) // up
    {
        cell_row = rand() % 10;
        if (cell_row <= 4)
        {
            cell_row += 4;
        }
        cell_col = rand() % 10;
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("UP: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row -= 1;
        }
    }
    else if (direction == 1) // down
    {
        cell_row = rand() % 6;
        cell_col = rand() % 10;
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("DOWN: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row += 1;
        }
    }
    else if (direction == 2) // left
    {
        cell_row = rand() % 10;
        cell_col = rand() % 10;
        if (cell_col <= 4)
        {
            cell_col += 4;
        }
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            cell_col -= 1;
            printf("LEFT: Row:%d Col:%d\n", cell_row, cell_col);
        }
    }
    else if (direction == 3) // right
    {
        cell_row = rand() % 10;
        cell_col = rand() % 6;
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("RIGHT: row:%d Col:%d\n", cell_row, cell_col);
            cell_col += 1;
        }
    }

    //Battle Ship
    printf("BATTLE SHIP\n");

    direction = rand() % 4;
    printf("Direction: %d\n", direction);
    player->symbol = 'b';
    if (direction == 0) // up
    {

        cell_row = rand() % 10;

        if (cell_row <= 3)
        {
            cell_row += 3;
        }

        cell_col = rand() % 10;

        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("UP: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row -= 1;
        }
    }
    else if (direction == 1) // down
    {
        cell_row = rand() % 7;
        cell_col = rand() % 10;
        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("DOWN: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row += 1;
        }
    }
    else if (direction == 2) // left
    {
        cell_row = rand() % 10;
        cell_col = rand() % 10;
        if (cell_col <= 3)
        {
            cell_col += 3;
        }
        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("LEFT: Row:%d Col:%d\n", cell_row, cell_col);
            cell_col -= 1;
        }
    }
    else if (direction == 3) // right
    {
        cell_row = rand() % 10;
        cell_col = rand() % 7;
        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("RIGHT: row:%d Col:%d\n", cell_row, cell_col);
            cell_col += 1;
        }
    }
</code>```

I have tried a combination of do while, while and for loops to try and get the ship to reset, but I can just not figure out a way to make this work

I could really use some guidance or a step in the right direction in order to fix this task. Thanks so much in advance!

答:
I like Joud's answer. In addition, make a "ship" struct with name and length fields. Then you can have an array of ships and in a for loop pass each ship to function:

```<code>loop(i) //pseudocode
{
   randomlly_place_ship_on_board(&computer, &ship[i])
}
...
randomlly_place_ship_on_board(Game_Board *player, Ship * sh)
{
   // Only takes care of one ship, sh.
   // Call isAvailableCells to determine placement, like
   while (!isAvailableCells...)
         // re-attempt placement
}
</code>```

Pseudocode may help. Check the gameboard->board for if that cell is available or not.

Title: Making sure the ships do not overlap

Body:
I have been stuck on this task for a long time now, so I thought it was about time to ask for some help. I am making a game of battle ship and I am currently writing a function where the ships are randomly placed on the 10 x 10 grid. I have this completed, but my problem is when they overlap.

I cannot figure out a way to get coordinates where they don't overlap with a previously randomly placed ship. In my current code I am trying to figure out a way to make it so that if a coordinate overlaps it will loop the ship over again until it has the right amount of cells that do not overlap with any other ship. I am writing in a 3 file format, so I will include the needed code from each file.

In the function, the up down left or right is random, so in the battle ship I have direction = 0 so that I am only working with up

Here is the header file

typedef struct game_board
{
    int board[10][10];
    int row;
    int col;
    char symbol;
}Game_Board;

Game_Board initalize_game_board(Game_Board *player);

//Game_Board manually_place_ships_on_board(Game_Board *player);
Game_Board randomlly_place_ships_on_board(Game_Board *player);

Main

Game_Board person, computer;
    int who_goes_first = 0;

    person.symbol = '~';
    person.row = 10;
    person.col = 10;
    computer.symbol = '-';
    computer.row = 10;
    computer.col = 10;

    welcome_screen(outfile);

    printf("Player 1\n");
    initalize_game_board(&person);
    printf("\nPlayer 2\n");
    initalize_game_board(&computer);
    who_goes_first = select_who_starts_first();
    //manually_place_ships_on_board(&person);
    randomlly_place_ships_on_board(&computer);

The function. I am only including the first 2 ship for redundancy reasons

int direction = 0, i = 0, cell_row = 0, cell_col = 0;

    //Carrier
    printf("CARRIER\n");
    direction = rand() % 4;
    printf("Direction: %d\n", direction);
    player->symbol = 'c';
    if (direction == 0) // up
    {
        cell_row = rand() % 10;
        if (cell_row <= 4)
        {
            cell_row += 4;
        }
        cell_col = rand() % 10;
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("UP: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row -= 1;
        }
    }
    else if (direction == 1) // down
    {
        cell_row = rand() % 6;
        cell_col = rand() % 10;
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("DOWN: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row += 1;
        }
    }
    else if (direction == 2) // left
    {
        cell_row = rand() % 10;
        cell_col = rand() % 10;
        if (cell_col <= 4)
        {
            cell_col += 4;
        }
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            cell_col -= 1;
            printf("LEFT: Row:%d Col:%d\n", cell_row, cell_col);
        }
    }
    else if (direction == 3) // right
    {
        cell_row = rand() % 10;
        cell_col = rand() % 6;
        for (i = 0; i < 5; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("RIGHT: row:%d Col:%d\n", cell_row, cell_col);
            cell_col += 1;
        }
    }

    //Battle Ship
    printf("BATTLE SHIP\n");

    direction = rand() % 4;
    printf("Direction: %d\n", direction);
    player->symbol = 'b';
    if (direction == 0) // up
    {

        cell_row = rand() % 10;

        if (cell_row <= 3)
        {
            cell_row += 3;
        }

        cell_col = rand() % 10;

        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("UP: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row -= 1;
        }
    }
    else if (direction == 1) // down
    {
        cell_row = rand() % 7;
        cell_col = rand() % 10;
        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("DOWN: Row:%d Col:%d\n", cell_row, cell_col);
            cell_row += 1;
        }
    }
    else if (direction == 2) // left
    {
        cell_row = rand() % 10;
        cell_col = rand() % 10;
        if (cell_col <= 3)
        {
            cell_col += 3;
        }
        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("LEFT: Row:%d Col:%d\n", cell_row, cell_col);
            cell_col -= 1;
        }
    }
    else if (direction == 3) // right
    {
        cell_row = rand() % 10;
        cell_col = rand() % 7;
        for (i = 0; i < 4; i++)
        {
            player->board[cell_row][cell_col] = player->symbol;
            printf("RIGHT: row:%d Col:%d\n", cell_row, cell_col);
            cell_col += 1;
        }
    }

I have tried a combination of do while, while and for loops to try and get the ship to reset, but I can just not figure out a way to make this work

I could really use some guidance or a step in the right direction in order to fix this task. Thanks so much in advance!

Body:
I like Joud's answer. In addition, make a "ship" struct with name and length fields. Then you can have an array of ships and in a for loop pass each ship to function:

loop(i) //pseudocode
{
   randomlly_place_ship_on_board(&computer, &ship[i])
}
...
randomlly_place_ship_on_board(Game_Board *player, Ship * sh)
{
   // Only takes care of one ship, sh.
   // Call isAvailableCells to determine placement, like
   while (!isAvailableCells...)
         // re-attempt placement
}

Pseudocode may help. Check the gameboard->board for if that cell is available or not.


问:
Openedge Progress 4GL Table join
any advise from progress 4GL guru to take a peek on the block of 4GL code bellow and see if it is overly done ? can it be done so that it is easier to follow / more readable?

I have TblA

```<code>Report
6998077
6998078
6998097
7062816
</code>```

And TblB

```<code>+-----------+------------+-----------+
| ID        |      Source|    Report |
+-----------+------------+-----------+
|   4976117 |    6998077 |   6998077 |
|   4976118 |    6998078 |   6998078 |
|   4976137 |    6998097 |   6998097 |
|   5107798 |    7062816 |   6998078 |
|   5107799 |    7062816 |   6998097 |
+-----------+------------+-----------+
</code>```

and I have, in my opinion, a complicated Progress 4GL loop :

```<code>def temp-table TblTemp no-undo
field cTypeOfRec     as char
field Report         as int
field Source         as int
field ID             as int
index key is unique primary Report Source ID.

procedure SOOptimize:
  output stream dOut1 to value("/OutPut.txt").
  export stream dOut1 delimiter "|"
    "Report"
    "Source"
    "ID".
  for each TblA no-lock
           on error undo, return error on stop undo, return error:
    for each TblB no-lock where
             TblB.Source = TblA.Report
             on error undo, return error on stop undo, return error:

      find TblTemp exclusive-lock where
           TblTemp.SrcPltSeq = TblA.Report and
           TblTemp.RptPltSeq = TblB.Report and
           TblTemp.ID        = TblB.ID
           no-error.
      if NOT available TblTemp
      then do:
        create TblTemp.
        assign
          TblTemp.cTypeOfRec = "From LoopA"
          TblTemp.SrcPltSeq  = TblA.Report
          TblTemp.RptPltSeq  = TblB.Report
          TblTemp.ID         = TblB.ID.
      end.
    end.
    for each TblB no-lock where
             TblB.Report = TblA.Report
             on error undo, return error on stop undo, return error:
      find TblTemp exclusive-lock where
           TblTemp.SrcPltSeq = TblB.Source     and
           TblTemp.RptPltSeq = TblA.Report     and
           TblTemp.ID        = TblB.ID
           no-error.

      if NOT available TblTemp
      then do:
        create TblTemp.
        assign
          TblTemp.cTypeOfRec = "From LoopB"
          TblTemp.SrcPltSeq    = TblB.Source
          TblTemp.RptPltSeq    = TblA.Report
          TblTemp.ID           = TblB.PltSrcSeq.
      end.
    end.
  end.
  for each TblTemp no-lock
  on error undo, return error on stop undo, return error:
    export stream dOut1 delimiter "|"
      TblTemp.
  end.
end procedure.
</code>```

Then the output of my progress Code is:

```<code>+------------+---------+---------+---------+
| cTypeOfRec | Source  | Report  |   ID    |
+------------+---------+---------+---------+
| From LoopA | 6998077 | 6998077 | 4976117 |
| From LoopA | 6998078 | 6998078 | 4976118 |
| From LoopB | 7062816 | 6998078 | 5107798 |
| From LoopA | 6998097 | 6998097 | 4976137 |
| From LoopB | 7062816 | 6998097 | 5107799 |
+------------+---------+---------+---------+
</code>```

I have a very limited knowledge of Progress 4GL. Does this code seems overly done? can it be simpler?

I come from SQL background. So in SQL, I can solve this rather quickly and easily. And what I mean by that is, ALL this Block of Progress code is doing basically just saying, say "From LoopA" if NULL in LoopB, otherwise say "from LoopB"

Here is the SQL equivalent that I come up with:

```<code>Select
case when B.ID is null then 'From LoopA'
else B.cTypeOfRec
End "cTypeOfRec"
, A.*
from #TblTemp A
left join (
    select A.*, 'From LoopB'  "cTypeOfRec" from ( select * from #TblTemp)A
    left join (
        select B.Source, A.Report, B.ID  from #TblA A
        Inner join #TblB B
        on B.Report=A.Report)B
    on A.Source = B.Report
    where B.Source is null) B
on A.Report=B.Report
and a.ID = b.ID
and a.Source= b.Source
order by A.Report
, case when B.ID is null then 'From LoopA'
else B.cTypeOfRec
End
</code>```

any advise from progress 4GL guru to take a peek on the block of 4GL code above and see if it is overly done ?  can it be done so that it is easier to follow / readable?

But I am open to any answer, if that is the proper way to code in 4GL to achieve the end result then I am ok.

Thank you Thank you

答:
You could write something like the following

```<code>for each TblA no-lock,
  each TblB no-lock where
           TblB.Source = TblA.Report
        or TblB.Report = TblA.Report
           on error undo, return error on stop undo, return error:
  /* ... */
end.
</code>```

I don't know if this already helps, ie. if you could skip the temp-table. At least for one TblA record you shouldn't see the same TblB record twice (which otherwise would occur for records with TblB.Source = TblB.Report).
If I replace TblA.Report with TblB.Source in the first for each TblB and TblA.Report with TblB.Report then the only differences seem to be TblTemp.cTypeOfRec and TblTemp.ID so you should be able to shorten the code.

Title: Openedge Progress 4GL Table join

Body:
any advise from progress 4GL guru to take a peek on the block of 4GL code bellow and see if it is overly done ? can it be done so that it is easier to follow / more readable?

I have TblA

Report
6998077
6998078
6998097
7062816

And TblB

+-----------+------------+-----------+
| ID        |      Source|    Report |
+-----------+------------+-----------+
|   4976117 |    6998077 |   6998077 |
|   4976118 |    6998078 |   6998078 |
|   4976137 |    6998097 |   6998097 |
|   5107798 |    7062816 |   6998078 |
|   5107799 |    7062816 |   6998097 |
+-----------+------------+-----------+

and I have, in my opinion, a complicated Progress 4GL loop :

def temp-table TblTemp no-undo
field cTypeOfRec     as char
field Report         as int
field Source         as int
field ID             as int
index key is unique primary Report Source ID.

procedure SOOptimize:
  output stream dOut1 to value("/OutPut.txt").
  export stream dOut1 delimiter "|"
    "Report"
    "Source"
    "ID".
  for each TblA no-lock
           on error undo, return error on stop undo, return error:
    for each TblB no-lock where
             TblB.Source = TblA.Report
             on error undo, return error on stop undo, return error:

      find TblTemp exclusive-lock where
           TblTemp.SrcPltSeq = TblA.Report and
           TblTemp.RptPltSeq = TblB.Report and
           TblTemp.ID        = TblB.ID
           no-error.
      if NOT available TblTemp
      then do:
        create TblTemp.
        assign
          TblTemp.cTypeOfRec = "From LoopA"
          TblTemp.SrcPltSeq  = TblA.Report
          TblTemp.RptPltSeq  = TblB.Report
          TblTemp.ID         = TblB.ID.
      end.
    end.
    for each TblB no-lock where
             TblB.Report = TblA.Report
             on error undo, return error on stop undo, return error:
      find TblTemp exclusive-lock where
           TblTemp.SrcPltSeq = TblB.Source     and
           TblTemp.RptPltSeq = TblA.Report     and
           TblTemp.ID        = TblB.ID
           no-error.

      if NOT available TblTemp
      then do:
        create TblTemp.
        assign
          TblTemp.cTypeOfRec = "From LoopB"
          TblTemp.SrcPltSeq    = TblB.Source
          TblTemp.RptPltSeq    = TblA.Report
          TblTemp.ID           = TblB.PltSrcSeq.
      end.
    end.
  end.
  for each TblTemp no-lock
  on error undo, return error on stop undo, return error:
    export stream dOut1 delimiter "|"
      TblTemp.
  end.
end procedure.

Then the output of my progress Code is:

+------------+---------+---------+---------+
| cTypeOfRec | Source  | Report  |   ID    |
+------------+---------+---------+---------+
| From LoopA | 6998077 | 6998077 | 4976117 |
| From LoopA | 6998078 | 6998078 | 4976118 |
| From LoopB | 7062816 | 6998078 | 5107798 |
| From LoopA | 6998097 | 6998097 | 4976137 |
| From LoopB | 7062816 | 6998097 | 5107799 |
+------------+---------+---------+---------+

I have a very limited knowledge of Progress 4GL. Does this code seems overly done? can it be simpler?

I come from SQL background. So in SQL, I can solve this rather quickly and easily. And what I mean by that is, ALL this Block of Progress code is doing basically just saying, say "From LoopA" if NULL in LoopB, otherwise say "from LoopB"

Here is the SQL equivalent that I come up with:

Select
case when B.ID is null then 'From LoopA'
else B.cTypeOfRec
End "cTypeOfRec"
, A.*
from #TblTemp A
left join (
    select A.*, 'From LoopB'  "cTypeOfRec" from ( select * from #TblTemp)A
    left join (
        select B.Source, A.Report, B.ID  from #TblA A
        Inner join #TblB B
        on B.Report=A.Report)B
    on A.Source = B.Report
    where B.Source is null) B
on A.Report=B.Report
and a.ID = b.ID
and a.Source= b.Source
order by A.Report
, case when B.ID is null then 'From LoopA'
else B.cTypeOfRec
End

any advise from progress 4GL guru to take a peek on the block of 4GL code above and see if it is overly done ?  can it be done so that it is easier to follow / readable?

But I am open to any answer, if that is the proper way to code in 4GL to achieve the end result then I am ok.

Thank you Thank you

Body:
You could write something like the following

for each TblA no-lock,
  each TblB no-lock where
           TblB.Source = TblA.Report
        or TblB.Report = TblA.Report
           on error undo, return error on stop undo, return error:
  /* ... */
end.

I don't know if this already helps, ie. if you could skip the temp-table. At least for one TblA record you shouldn't see the same TblB record twice (which otherwise would occur for records with TblB.Source = TblB.Report).
If I replace TblA.Report with TblB.Source in the first for each TblB and TblA.Report with TblB.Report then the only differences seem to be TblTemp.cTypeOfRec and TblTemp.ID so you should be able to shorten the code.


问:
How to use Spring integration sftp outbound gateway with java config
I'm new to Spring integration sftp.Now,I want to download files from multiple directories.then it seems that SFTP Outbound Gateway is my chocie,but I only find examples using XML config.How can this be done using Java config?
My configuration class:

```<code>@Configuration
public class SftpConfig {
    @Bean
    public SessionFactory<LsEntry> sftpSessionFactory(){
        DefaultSftpSessionFactory defaultSftpSessionFactory = new DefaultSftpSessionFactory();
        ...
        return new CachingSessionFactory<LsEntry>(defaultSftpSessionFactory);
    }
    @Bean
    @InboundChannelAdapter(channel = "sftpChannel",autoStartup = "false", poller = @Poller(fixedDelay = "5000"))
    public MessageSource<File> sftpMessageSource() {
    ...
    }
    @Bean(name = "lsGateway")
    @ServiceActivator(inputChannel = "sftpChannel")
    public MessageHandler handlerLs(){
        SftpOutboundGateway sftpOutboundGateway = new SftpOutboundGateway(sftpSessionFactory(),"ls","payload");
        sftpOutboundGateway.setLocalDirectory(new File("sftp-gateway"));
        return sftpOutboundGateway;
    }
}

@MessagingGateway
public interface OutboundGatewayOption {
    @Gateway(requestChannel = "sftpChannel")
    public List<Boolean> lsGetAndRmFiles(String dir);

}
</code>```

but when I start the app,nothing happens,where is wrong?

----update---
My test class

```<code>@SpringBootTest(classes = Application.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@Configuration
@EnableIntegration
@Slf4j
@MessageEndpoint
public class SftpConfigTest{
    @Autowired
    private OutboundGatewayOption gatewayOption;
    @Test
    public void test(){
        gatewayOption.lsGetAndRmFiles("/");
    }
}
</code>```

答:
It's not clear what you mean by "nothing happens". It appears you have two ways to trigger the LS request - a messaging gateway (which you have to call) and an inbound channel adapter, which has autoStartup = "false" - it won't invoke the gateway until it is started.

Also, when using that as the trigger, you will need an output channel on the SFTP gateway (where to send the result). When invoking the gateway by calling the messaging gateway, the result will be returned to the gateway (since the SFTP gateway has no output channel).

Body:
I'm new to Spring integration sftp.Now,I want to download files from multiple directories.then it seems that SFTP Outbound Gateway is my chocie,but I only find examples using XML config.How can this be done using Java config?
My configuration class:

@Configuration
public class SftpConfig {
    @Bean
    public SessionFactory<LsEntry> sftpSessionFactory(){
        DefaultSftpSessionFactory defaultSftpSessionFactory = new DefaultSftpSessionFactory();
        ...
        return new CachingSessionFactory<LsEntry>(defaultSftpSessionFactory);
    }
    @Bean
    @InboundChannelAdapter(channel = "sftpChannel",autoStartup = "false", poller = @Poller(fixedDelay = "5000"))
    public MessageSource<File> sftpMessageSource() {
    ...
    }
    @Bean(name = "lsGateway")
    @ServiceActivator(inputChannel = "sftpChannel")
    public MessageHandler handlerLs(){
        SftpOutboundGateway sftpOutboundGateway = new SftpOutboundGateway(sftpSessionFactory(),"ls","payload");
        sftpOutboundGateway.setLocalDirectory(new File("sftp-gateway"));
        return sftpOutboundGateway;
    }
}

@MessagingGateway
public interface OutboundGatewayOption {
    @Gateway(requestChannel = "sftpChannel")
    public List<Boolean> lsGetAndRmFiles(String dir);

}

but when I start the app,nothing happens,where is wrong?

----update---
My test class

@SpringBootTest(classes = Application.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@Configuration
@EnableIntegration
@Slf4j
@MessageEndpoint
public class SftpConfigTest{
    @Autowired
    private OutboundGatewayOption gatewayOption;
    @Test
    public void test(){
        gatewayOption.lsGetAndRmFiles("/");
    }
}


问:
Access subclass type from its superclasses function
Is there a way to have a function in a superclass, that can (when called through a subclass) access said subclasses type?

I want a universal info() in my masterclass that can be called an give information about the type of the subclass.

答:
It's not entirely clear to me what you want, but self always returns the currently instantiated class - see below

```<code>class A {
    init() { }

    func whatClassAmI() -> String {
        return "\(type(of: self))"
    }
}

class B: A { }

let a = A()
let sa = a.whatClassAmI() // "A", of course

let b = B()
let sb = b.whatClassAmI() // "B", as required
</code>```

Body:
It's not entirely clear to me what you want, but self always returns the currently instantiated class - see below

class A {
    init() { }

    func whatClassAmI() -> String {
        return "\(type(of: self))"
    }
}

class B: A { }

let a = A()
let sa = a.whatClassAmI() // "A", of course

let b = B()
let sb = b.whatClassAmI() // "B", as required


问:
How could I implement a serial communication protocol in a object-oriented form?
I’m working on with an embedded device that is connected to PC using RS232.

I need to do a software to communicate with this embedded device.

I program in Delphi. I never used to use object-oriented in the past. But I'm trying to change this.

I am not able to think in an object oriented manner to solve this problem.

I have this protocol:

```<code><STX><STX><COMMAND>[<DATA><DATA>...]<CHKSUM><ETX>
</code>```

where:

```<code><STX> is the Start of TeXt (0x55);
<COMMAND> can be 0x01 for read, 0x02 for write, etc;
<DATA> is any value;
<CHKSUM> is the checksum;
<ETX> is the End of TeXt (0x04).
</code>```

The software computer will send a command via serial, and the device will answer, using the same protocol.

For example:

```<code>Reset command
PC sends     : <STX><STX><0x09><0x00><CHKSUM><ETX>
Device answer: <STX><STX><0x09><0x00><CHKSUM><ETX>

Get Version
PC sends     : <STX><STX><0x00><0x02><CHKSUM><ETX>
Device answer: <STX><STX><0x00><0x00><VER_L><VER_H><CHKSUM><ETX>
</code>```

I have to send a file stream to the device.

I'd like to obtain suggestions and/or examples of the best way to implement this in an object oriented manner. I'd like to be able to do unit-test too.

Thanks

答:
Well, I guess there are as many solutions as there are programmers. Without knowing more about your system I would probably go with this approach:

Create a base command class, lets say; TBaseCommand. Define your common interface at this level, like Send(), Receive(), Run() etc...

Only fill in code for functions common for all commands, such as sending, receiving etc...

Functions that will differ in execution are made virtual to be defined in the next layer.
From this derive a new class for each command and fill in the command specific code, such as Run().

Having a Run() will easily allow you to simulate your commands on screen by overriding the Run() function.

,  and  are your transport protocol and should be applied and stripped of by your communication interface (separate protocol class?). Your protocol class can also handle checksum errors and try to resend etc.. If it can't be solved, signal error.

This was only a few things on top of my head with your limited description...

Body:
I’m working on with an embedded device that is connected to PC using RS232.

I need to do a software to communicate with this embedded device.

I program in Delphi. I never used to use object-oriented in the past. But I'm trying to change this.

I am not able to think in an object oriented manner to solve this problem.

I have this protocol:

<STX><STX><COMMAND>[<DATA><DATA>...]<CHKSUM><ETX>

where:

<STX> is the Start of TeXt (0x55);
<COMMAND> can be 0x01 for read, 0x02 for write, etc;
<DATA> is any value;
<CHKSUM> is the checksum;
<ETX> is the End of TeXt (0x04).

The software computer will send a command via serial, and the device will answer, using the same protocol.

For example:

Reset command
PC sends     : <STX><STX><0x09><0x00><CHKSUM><ETX>
Device answer: <STX><STX><0x09><0x00><CHKSUM><ETX>

Get Version
PC sends     : <STX><STX><0x00><0x02><CHKSUM><ETX>
Device answer: <STX><STX><0x00><0x00><VER_L><VER_H><CHKSUM><ETX>

I have to send a file stream to the device.

I'd like to obtain suggestions and/or examples of the best way to implement this in an object oriented manner. I'd like to be able to do unit-test too.

Thanks


问:
Can't make SQL query from three tables
I Can't make a SQL query for:

I have the following tables:

User which have two columns namely: user_id and user_name.

Group which has three columns namely : id, group_name and created_date.

Records which has five columns namely : id, group_id, user_id, record_content and record_type.

record_user which has three columns namely : user_id, record_id and liked

Now I want a query which could execute on all 4 tables something like:

select user_id, user_name, group_id, record_content

Also I need in this table - the liked field for each record based on user_id (which mean that this user is authenticated).

The thing that I try to get all messages(records) of definite group and information regarding like of each record by user which is currently reading this messages(records).

答:
Please try the following...

```<code>SELECT User.user_id AS user_id,
       User.user_name AS user_name,
       Group.id AS group_id,
       Group.group_name AS gorup_name,
       Records.record_content AS record_content,
       record_user.liked AS liked
FROM User
JOIN Records ON User.user_id = Records.user_id
JOIN Group ON Group.id = Records.group_id
JOIN record_user.record_id ON Records.id
GROUP BY User.user_id,
         Group.id;
</code>```

The AS's are not required, they just are useful for giving the output fields more convenient names.  You can change them to pretty much whatever you want.

Please see https://www.w3schools.com/sql/sql_join.asp for more on JOIN's - look for the Venn diagram as well as read the explanation.

The GROUP BY clauses may not be needed, but you have not explained how you wish the output to be sorted and grouped, so I have chosen those as a suggestion.

Note : In the future it will help if you present us with sample data and desired output.

If you have any questions or comments, then please feel free to post a Comment accordingly.

Title: Can't make SQL query from three tables

Body:
Please try the following...

SELECT User.user_id AS user_id,
       User.user_name AS user_name,
       Group.id AS group_id,
       Group.group_name AS gorup_name,
       Records.record_content AS record_content,
       record_user.liked AS liked
FROM User
JOIN Records ON User.user_id = Records.user_id
JOIN Group ON Group.id = Records.group_id
JOIN record_user.record_id ON Records.id
GROUP BY User.user_id,
         Group.id;

The AS's are not required, they just are useful for giving the output fields more convenient names.  You can change them to pretty much whatever you want.

Please see https://www.w3schools.com/sql/sql_join.asp for more on JOIN's - look for the Venn diagram as well as read the explanation.

The GROUP BY clauses may not be needed, but you have not explained how you wish the output to be sorted and grouped, so I have chosen those as a suggestion.

Note : In the future it will help if you present us with sample data and desired output.

If you have any questions or comments, then please feel free to post a Comment accordingly.


答:
You could use something like this. It has no dependencies on jQuery, If you need it to run on older browsers you can change const to var and change matches to checking the targets className.

const list1 = document.querySelector('#list1')
const list2 = document.querySelector('#list2')

const swapListItem = function(e) {
  // only continue execution if the target is a .moveBtn
  if (e.target.matches('.moveBtn')) {
    e.preventDefault()
    const item = e.target.parentNode
    const parent = item.parentNode
    parent.removeChild(item)
    if (parent === list1) {
      list2.appendChild(item)
    }
    else {
      list1.appendChild(item)
    }
  }
}
// bind a single event to the window
window.addEventListener('click', swapListItem, false)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { font-family: sans-serif }
.list { width 40%; float: left; padding: 0; list-style-type: none; color: white }
li { padding: 0.5em }
#list1 { background: #BADA55 }
#list2 { background: #1CE1CE }</code>```

Item 1 z listy 1 Przenieś

Item 2 z listy 1 Przenieś

Item 1 z listy 2 Przenieś

Item 2 z listy 2 Przenieś

```

Title: JavaScript transfering one element to another (multiple times) by using event

Body:
I want to transfer multiple times after click on "przenieś" the whole li from one div class="listContainer two" to another, and back again (and again) using JavaScript. How should I prepare the JavaScript code for the most efficient way?

Item 1 z listy 1 Przenieś

Item 2 z listy 1 Przenieś

Item 1 z listy 2 Przenieś

Item 2 z listy 2 Przenieś

Body:
You could use something like this. It has no dependencies on jQuery, If you need it to run on older browsers you can change const to var and change matches to checking the targets className.

const list1 = document.querySelector('#list1')
const list2 = document.querySelector('#list2')

const swapListItem = function(e) {
  // only continue execution if the target is a .moveBtn
  if (e.target.matches('.moveBtn')) {
    e.preventDefault()
    const item = e.target.parentNode
    const parent = item.parentNode
    parent.removeChild(item)
    if (parent === list1) {
      list2.appendChild(item)
    }
    else {
      list1.appendChild(item)
    }
  }
}
// bind a single event to the window
window.addEventListener('click', swapListItem, false)

body { font-family: sans-serif }
.list { width 40%; float: left; padding: 0; list-style-type: none; color: white }
li { padding: 0.5em }
#list1 { background: #BADA55 }
#list2 { background: #1CE1CE }

<ul class="list" id="list1">
    <li>Item 1 z listy 1 <a href="#" class="moveBtn">Przenieś</a></li>
    <li>Item 2 z listy 1 <a href="#" class="moveBtn">Przenieś</a></li>
</ul>

<ul class="list" id="list2">
    <li>Item 1 z listy 2 <a href="#" class="moveBtn">Przenieś</a></li>
    <li>Item 2 z listy 2 <a href="#" class="moveBtn">Przenieś</a></li>
</ul>


问:
Mininet-wifi custom topology
At first I want wanted to create a complex topology (more switches connected to each other) but even this simple one is not working. I am not able to get a working connection eg. 'h1 ping h2'

Here is the topology:

He is the script that should create the equivalent topology:

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

"""
Setting the position of Nodes (only for Stations and Access Points) and providing mobility.

"""

from mininet.net import Mininet
from mininet.node import Controller, RemoteController, OVSKernelAP
from mininet.link import TCLink
from mininet.cli import CLI
from mininet.log import setLogLevel

def topology():

    "Create a network."
    net = Mininet( controller=Controller, link=TCLink, accessPoint=OVSKernelAP )

    print "*** Creating nodes"
    h1 = net.addHost( 'h1', mac='00:00:00:00:00:01', ip='10.0.0.1/8' )
    h2 = net.addHost( 'h2', mac='00:00:00:00:00:11', ip='10.0.1.1/8' )

    sta1 = net.addStation( 'sta1', mac='00:00:00:00:00:02', ip='10.0.0.2/8', position='50,50,0' )
    sta2 = net.addStation( 'sta2', mac='00:00:00:00:00:03', ip='10.0.0.3/8', position='40,50,0')
    sta3 = net.addStation( 'sta3', mac='00:00:00:00:00:04', ip='10.0.0.4/8', position='20,50,0' )

    ap1 = net.addAccessPoint( 'ap1', ssid= 'new-ssid', mode= 'g', channel= '5', position='25,50,0', range='35' )
    ap2 = net.addAccessPoint( 'ap2', ssid= 'new-ssid', mode= 'g', channel= '5', position='75,50,0', range='35' )

    c1 = net.addController( 'c1' )

    s1 = net.addSwitch('s1')

    #net.runAlternativeModule('../module/mac80211_hwsim.ko')

    print "*** Configuring wifi nodes"
    net.configureWifiNodes()

    print "*** Associating and Creating links"

    net.addLink(ap1, s1)
    net.addLink(ap2, s1)
    net.addLink(s1, c1)
    #net.addLink(ap1, ap2)

    net.addLink(s1, h1)
    net.addLink(s1, h2)

    net.addLink(ap1, sta1)
    net.addLink(ap1, sta2)
    net.addLink(ap1, sta3)

    print "*** Starting network"
    net.build()
    c1.start()
    ap1.start( [c1] )
    ap2.start( [c1] )

    """uncomment to plot graph"""
    net.plotGraph(max_x=100, max_y=100)

    net.startMobility(startTime=0)
    net.mobility(sta1, 'start', time=1, position='0.0,50.0,0.0')
    net.mobility(sta1, 'stop', time=30, position='100.0,50.0,0.0')
    net.stopMobility(stopTime=31)

    print "*** Running CLI"
    CLI( net )

    print "*** Stopping network"
    net.stop()

if __name__ == '__main__':
    setLogLevel( 'info' )
    topology()
</code>```

As already said, I am not able to even ping h1 and h2 :(
I even tried to use RemoteController but got the same result.
Any idea what might be wrong?

答:
Please consider the changes below:

```<code>from mininet.node import Controller, RemoteController, OVSKernelAP, OVSSwitch
net = Mininet( controller=Controller, link=TCLink, accessPoint=OVSKernelAP, switch=OVSSwitch )
c1 = net.addController( 'c1', controller=Controller )
s3 = net.addSwitch('s3')
</code>```

Remove:

net.addLink(s1, c1)

Add:

s3.start( [c1] )

Please note that if you set both ap and switch with the same ID (e.g. s1, ap1), they will have the same DPID by default. So, I had to rename s1 to s3. On the other hand you may define the DPID as a parameter when you add the node whether you want.

Title: Mininet-wifi custom topology

Body:
At first I want wanted to create a complex topology (more switches connected to each other) but even this simple one is not working. I am not able to get a working connection eg. 'h1 ping h2'

Here is the topology:

He is the script that should create the equivalent topology:

!/usr/bin/python

"""
Setting the position of Nodes (only for Stations and Access Points) and providing mobility.

"""

from mininet.net import Mininet
from mininet.node import Controller, RemoteController, OVSKernelAP
from mininet.link import TCLink
from mininet.cli import CLI
from mininet.log import setLogLevel

def topology():

    "Create a network."
    net = Mininet( controller=Controller, link=TCLink, accessPoint=OVSKernelAP )

    print "*** Creating nodes"
    h1 = net.addHost( 'h1', mac='00:00:00:00:00:01', ip='10.0.0.1/8' )
    h2 = net.addHost( 'h2', mac='00:00:00:00:00:11', ip='10.0.1.1/8' )

    sta1 = net.addStation( 'sta1', mac='00:00:00:00:00:02', ip='10.0.0.2/8', position='50,50,0' )
    sta2 = net.addStation( 'sta2', mac='00:00:00:00:00:03', ip='10.0.0.3/8', position='40,50,0')
    sta3 = net.addStation( 'sta3', mac='00:00:00:00:00:04', ip='10.0.0.4/8', position='20,50,0' )

    ap1 = net.addAccessPoint( 'ap1', ssid= 'new-ssid', mode= 'g', channel= '5', position='25,50,0', range='35' )
    ap2 = net.addAccessPoint( 'ap2', ssid= 'new-ssid', mode= 'g', channel= '5', position='75,50,0', range='35' )

    c1 = net.addController( 'c1' )

    s1 = net.addSwitch('s1')

    #net.runAlternativeModule('../module/mac80211_hwsim.ko')

    print "*** Configuring wifi nodes"
    net.configureWifiNodes()

    print "*** Associating and Creating links"

    net.addLink(ap1, s1)
    net.addLink(ap2, s1)
    net.addLink(s1, c1)
    #net.addLink(ap1, ap2)

    net.addLink(s1, h1)
    net.addLink(s1, h2)

    net.addLink(ap1, sta1)
    net.addLink(ap1, sta2)
    net.addLink(ap1, sta3)

    print "*** Starting network"
    net.build()
    c1.start()
    ap1.start( [c1] )
    ap2.start( [c1] )

    """uncomment to plot graph"""
    net.plotGraph(max_x=100, max_y=100)

    net.startMobility(startTime=0)
    net.mobility(sta1, 'start', time=1, position='0.0,50.0,0.0')
    net.mobility(sta1, 'stop', time=30, position='100.0,50.0,0.0')
    net.stopMobility(stopTime=31)

    print "*** Running CLI"
    CLI( net )

    print "*** Stopping network"
    net.stop()

if __name__ == '__main__':
    setLogLevel( 'info' )
    topology()

As already said, I am not able to even ping h1 and h2 :(
I even tried to use RemoteController but got the same result.
Any idea what might be wrong?

Body:
Please consider the changes below:

from mininet.node import Controller, RemoteController, OVSKernelAP, OVSSwitch
net = Mininet( controller=Controller, link=TCLink, accessPoint=OVSKernelAP, switch=OVSSwitch )
c1 = net.addController( 'c1', controller=Controller )
s3 = net.addSwitch('s3')

Remove:

net.addLink(s1, c1)

Add:

s3.start( [c1] )

Please note that if you set both ap and switch with the same ID (e.g. s1, ap1), they will have the same DPID by default. So, I had to rename s1 to s3. On the other hand you may define the DPID as a parameter when you add the node whether you want.


问:
Injections are stopping after adding @Transactional annotation
I have created a class that makes easy to add and update Employees. I have added @Transactional annotation to the createEmployee method, then my instances started to give error while I try to retrieve data.

```<code>    @Transactional
    @Override
    public void createEmployee(Employee employee) {
        internalCreateEmployee(employee);
    }
</code>```

without @Transactional everything works but I can save anything to the database. When I add this annotation I got this error.

java.lang.IllegalAccessError: tried to access method
  rd.EmployeeManagerImpl.(Lrd./EmployeeDao;Lrd./DepartmentDao;)V
  from class rd.EmployeeManagerImpl$$EnhancerByGuice$$5db9fd74

Inside the EmployeemanagerImpl I am also injecting my DAO objects in the constructor.

```<code>    @Inject
    EmployeeManagerImpl(EmployeeDao employeeDao, DepartmentDao departmentDao){
        this.employeeDao = employeeDao;
        this.departmentDao = departmentDao;
    }
</code>```

What can be the reason for that @Transactional breaks things?

I just don't know which information is necessary to provide, If you need any further information just ask.

Note: Employee is a hibernate entity class. EmployeeDao, DepartmentDao and EmployeeManagerImpl are all have the @Singleton annotation.

Note2: In the stack trace, It seems like EmployeeManager instance can't be initialized.

```<code>com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:987)
    com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1009)
    org.apache.wicket.guice.GuiceProxyTargetLocator.locateProxyTarget(GuiceProxyTargetLocator.java:105)
    org.apache.wicket.proxy.LazyInitProxyFactory$JdkHandler.invoke(LazyInitProxyFactory.java:430)
    com.sun.proxy.$Proxy133.getDepartmentList(Unknown Source)
    rd.EmployeeFormComponent.addDepartmentDropDown(EmployeeFormComponent.java:59)
    rd.EmployeeFormComponent.<init>(EmployeeFormComponent.java:47)
    rd.EmployeeAddPanel.<init>(EmployeeAddPanel.java:61)
    rd.EmployeeAddModalWindow$1.<init>(EmployeeAddModalWindow.java:20)
    rd.EmployeeAddModalWindow.<init>(EmployeeAddModalWindow.java:20)
    rd.ManageEmployeePage$1.<init>(ManageEmployeePage.java:49)
    rd.ManageEmployeePage.<init>(ManageEmployeePage.java:49)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    java.lang.reflect.Constructor.newInstance(Constructor.java:526)
</code>```

答: When you add the @Transactional annotation, a proxy class will be generated to handle the transaction magic. It appears the proxy class is unable to call the EmployeeManager constructor due to access restrictions. I would try making the constructor public.

Body:
I have created a class that makes easy to add and update Employees. I have added @Transactional annotation to the createEmployee method, then my instances started to give error while I try to retrieve data.

    @Transactional
    @Override
    public void createEmployee(Employee employee) {
        internalCreateEmployee(employee);
    }

without @Transactional everything works but I can save anything to the database. When I add this annotation I got this error.

java.lang.IllegalAccessError: tried to access method
  rd.EmployeeManagerImpl.(Lrd./EmployeeDao;Lrd./DepartmentDao;)V
  from class rd.EmployeeManagerImpl$$EnhancerByGuice$$5db9fd74

Inside the EmployeemanagerImpl I am also injecting my DAO objects in the constructor.

    @Inject
    EmployeeManagerImpl(EmployeeDao employeeDao, DepartmentDao departmentDao){
        this.employeeDao = employeeDao;
        this.departmentDao = departmentDao;
    }

What can be the reason for that @Transactional breaks things?

I just don't know which information is necessary to provide, If you need any further information just ask.

Note: Employee is a hibernate entity class. EmployeeDao, DepartmentDao and EmployeeManagerImpl are all have the @Singleton annotation.

Note2: In the stack trace, It seems like EmployeeManager instance can't be initialized.

com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:987)
    com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1009)
    org.apache.wicket.guice.GuiceProxyTargetLocator.locateProxyTarget(GuiceProxyTargetLocator.java:105)
    org.apache.wicket.proxy.LazyInitProxyFactory$JdkHandler.invoke(LazyInitProxyFactory.java:430)
    com.sun.proxy.$Proxy133.getDepartmentList(Unknown Source)
    rd.EmployeeFormComponent.addDepartmentDropDown(EmployeeFormComponent.java:59)
    rd.EmployeeFormComponent.<init>(EmployeeFormComponent.java:47)
    rd.EmployeeAddPanel.<init>(EmployeeAddPanel.java:61)
    rd.EmployeeAddModalWindow$1.<init>(EmployeeAddModalWindow.java:20)
    rd.EmployeeAddModalWindow.<init>(EmployeeAddModalWindow.java:20)
    rd.ManageEmployeePage$1.<init>(ManageEmployeePage.java:49)
    rd.ManageEmployeePage.<init>(ManageEmployeePage.java:49)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    java.lang.reflect.Constructor.newInstance(Constructor.java:526)


问:
Recursively find nth to last element in linked list
I'm practicing basic data structure stuff and I'm having some difficulties with recursion. I understand how to do this through iteration but all of my attempts to return the nth node from the last of a linked list via recursion result in null. This is my code so far:

```<code>public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
    if(node == null) return null;
    else{
    findnthToLastRecursion(node.next(), pos);
    if(++i == pos) return node;
    return null;
    }
</code>```

Can anyone help me understand where I'm going wrong here?

This is my iterative solution which works fine, but I'd really like to know how to translate this into recursion:

```<code>public static Link.Node findnthToLast(Link.Node head, int n) {
    if (n < 1 || head == null) {
        return null;
    }
    Link.Node pntr1 = head, pntr2 = head;
    for (int i = 0; i < n - 1; i++) {
        if (pntr2 == null) {
            return null;
        } else {
            pntr2 = pntr2.next();
        }
    }
    while (pntr2.next() != null) {
        pntr1 = pntr1.next();
        pntr2 = pntr2.next();
    }
    return pntr1;
}
</code>```

答:
You'll have make slight changes in the code:</p>

```<code>public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
    if(node == null) return null;
    else{
        **Link.Node temp = findnthToLastRecursion(node.next(), pos);
        if(temp!=null)
            return temp;**
        if(++i == pos) return node;
          return null;
    }
}
</code>```

Body:
I'm practicing basic data structure stuff and I'm having some difficulties with recursion. I understand how to do this through iteration but all of my attempts to return the nth node from the last of a linked list via recursion result in null. This is my code so far:

public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
    if(node == null) return null;
    else{
    findnthToLastRecursion(node.next(), pos);
    if(++i == pos) return node;
    return null;
    }

Can anyone help me understand where I'm going wrong here?

This is my iterative solution which works fine, but I'd really like to know how to translate this into recursion:

public static Link.Node findnthToLast(Link.Node head, int n) {
    if (n < 1 || head == null) {
        return null;
    }
    Link.Node pntr1 = head, pntr2 = head;
    for (int i = 0; i < n - 1; i++) {
        if (pntr2 == null) {
            return null;
        } else {
            pntr2 = pntr2.next();
        }
    }
    while (pntr2.next() != null) {
        pntr1 = pntr1.next();
        pntr2 = pntr2.next();
    }
    return pntr1;
}

Body:
You'll have make slight changes in the code:

public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
    if(node == null) return null;
    else{
        **Link.Node temp = findnthToLastRecursion(node.next(), pos);
        if(temp!=null)
            return temp;**
        if(++i == pos) return node;
          return null;
    }
}


问:
Using Notepad++ to compile Java code
I've been trying to set up Notepad++ as a little Java environment, mainly for learning Java as I was having some difficulty getting a simple program to work with NetBeans, unfortunately all the advice on setting up Notepad++ to call the Java code is not working.

I guess notepad++ has changed or the Java development Kit has been massively modified because all examples I have used result in errors, even though there is little room for error.

to begin I found this site:
http://blog.sanaulla.info/2008/07/25/using-notepad-to-compile-and-run-java-programs/

this is the code to run Javac to compile the code:

```<code>javac “$(FILE_NAME)”
</code>```

and

```<code>java “$(NAME_PART)”
</code>```

to run the resulted byte code, however this has absolutely no success at all anymore. Java is properly setup and I can call the Java program to do its thing through CMD.

Using a plugin called npp and called through F6 and run with this code (given in the comments) succeeds in compiling the Java program into the correct .class file, however the command failed in running the program

```<code>cd “$(CURRENT_DIRECTORY)”
javac $(FILE_NAME)
java $(NAME_PART)
</code>```

errors from the console in Notepad++ are:

```<code>java.lang.NoClassDefFoundError: first
Caused by: java.lang.ClassNotFoundException: first
  at java.net.URLClassLoader$1.run(Unknown Source)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.net.URLClassLoader.findClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
  at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: first.  Program will exit.
Exception in thread "main"
</code>```

I figured setting up Notepad++ to compile and run the code would be easy and fun, but its seems all documentation on the internet is outdated as nothing works.

I would like a easy way to compile and run Java code from within Notepad++

I could just used CMD but i'd rather it be more integrated into notepad++

Thanks for any possible help. cheers :)

EDIT: I'm using the latest version of Java, notepad++ and have Windows 7

EDIT 2: the code:

```<code> //A Very Simple Example
 class ExampleProgram {

   public static void main(String[] args){

        System.out.println("I'm a Simple Program");
   }
 }
</code>```

答:
Set the classpath in the java command like this:</p>

```<code>java -classpath “$(CURRENT_DIRECTORY)” “$(NAME_PART)”
</code>```

Title: Using Notepad++ to compile Java code

Body:
I've been trying to set up Notepad++ as a little Java environment, mainly for learning Java as I was having some difficulty getting a simple program to work with NetBeans, unfortunately all the advice on setting up Notepad++ to call the Java code is not working.

I guess notepad++ has changed or the Java development Kit has been massively modified because all examples I have used result in errors, even though there is little room for error.

to begin I found this site:
http://blog.sanaulla.info/2008/07/25/using-notepad-to-compile-and-run-java-programs/

this is the code to run Javac to compile the code:

javac “$(FILE_NAME)”

and

java “$(NAME_PART)”

to run the resulted byte code, however this has absolutely no success at all anymore. Java is properly setup and I can call the Java program to do its thing through CMD.

Using a plugin called npp and called through F6 and run with this code (given in the comments) succeeds in compiling the Java program into the correct .class file, however the command failed in running the program

cd “$(CURRENT_DIRECTORY)”
javac $(FILE_NAME)
java $(NAME_PART)

errors from the console in Notepad++ are:

java.lang.NoClassDefFoundError: first
Caused by: java.lang.ClassNotFoundException: first
  at java.net.URLClassLoader$1.run(Unknown Source)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.net.URLClassLoader.findClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
  at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: first.  Program will exit.
Exception in thread "main"

I figured setting up Notepad++ to compile and run the code would be easy and fun, but its seems all documentation on the internet is outdated as nothing works.

I would like a easy way to compile and run Java code from within Notepad++

I could just used CMD but i'd rather it be more integrated into notepad++

Thanks for any possible help. cheers :)

EDIT: I'm using the latest version of Java, notepad++ and have Windows 7

EDIT 2: the code:

 //A Very Simple Example
 class ExampleProgram {

   public static void main(String[] args){

        System.out.println("I'm a Simple Program");
   }
 }

Body:
Set the classpath in the java command like this:

java -classpath “$(CURRENT_DIRECTORY)” “$(NAME_PART)”


问:
Select many-to-many relation with "owns" column
I put my efforts to solve following problem:
I have 2 tables in my database:
videos and users_videos as pivot between videos and users (i receive user_id from token, so users table is in another db)

Having an user id, i want to select all videos and attach column containing true or false whether user owns a video.

So far i realized this with following query:

```<code> SELECT v.*, TRUE AS has_video FROM users_videos AS uv
 RIGHT JOIN videos AS v
 ON uv.video_id = v.id
 WHERE (uv.user_id = 1)
 UNION
 (
    SELECT v.*, FALSE AS has_video FROM videos AS v

    EXCEPT

    SELECT v.*, FALSE AS has_video FROM users_videos AS uv
    RIGHT JOIN videos AS v
    ON uv.video_id = v.id
    WHERE (uv.user_id = 1)
  )
</code>```

Although it selects all videos 3 times. Is there any more optimal solution for such kind of problems?

@EDIT ---

Tables structure

```<code>users_videos:
id integer
user_id integer
video_id integer

videos:
id: integer
title: string
</code>```

Example data:

users_videos

```<code>| id | user_id | video_id
-------------------------
  1    1          1
</code>```

videos

```<code>| id | title   |
----------------
  1  | Example 1
-----------------
  2  | Example 2
-----------------
</code>```

Desired result:

```<code>| id | title      | has_video
------------------------------
  1  | Example 1  |   true
------------------------------
  2  | Example 2  |   false
------------------------------
</code>```

@UPDATE --

Used @Stefano Zanini approach:

```<code>SELECT DISTINCT
        v.*,
        CASE
            WHEN uv.user_id IS NULL OR uv.user_id <> 1 THEN FALSE
            ELSE TRUE
        END has_video
FROM    videos v
LEFT JOIN
        users_videos uv
ON      uv.video_id = v.id
</code>```

But one more question came to my mind:

What if i want to display videos in specific category?
Let's say it's another many to many relation on

videos and categories tables with pivot videos_categories

答:
You want to select all videos and say for each video whether user 1 owns it. So select from videos and look up the user's videos:</p>

```<code>select
  v.*,
  id in (select video_id from users_videos where user_id = 1) as has_video
from videos v;
</code>```

Body:
I put my efforts to solve following problem:
I have 2 tables in my database:
videos and users_videos as pivot between videos and users (i receive user_id from token, so users table is in another db)

Having an user id, i want to select all videos and attach column containing true or false whether user owns a video.

So far i realized this with following query:

 SELECT v.*, TRUE AS has_video FROM users_videos AS uv
 RIGHT JOIN videos AS v
 ON uv.video_id = v.id
 WHERE (uv.user_id = 1)
 UNION
 (
    SELECT v.*, FALSE AS has_video FROM videos AS v

    EXCEPT

    SELECT v.*, FALSE AS has_video FROM users_videos AS uv
    RIGHT JOIN videos AS v
    ON uv.video_id = v.id
    WHERE (uv.user_id = 1)
  )

Although it selects all videos 3 times. Is there any more optimal solution for such kind of problems?

@EDIT ---

Tables structure

users_videos:
id integer
user_id integer
video_id integer

videos:
id: integer
title: string

Example data:

users_videos

| id | user_id | video_id
-------------------------
  1    1          1

videos

| id | title   |
----------------
  1  | Example 1
-----------------
  2  | Example 2
-----------------

Desired result:

| id | title      | has_video
------------------------------
  1  | Example 1  |   true
------------------------------
  2  | Example 2  |   false
------------------------------

@UPDATE --

Used @Stefano Zanini approach:

SELECT DISTINCT
        v.*,
        CASE
            WHEN uv.user_id IS NULL OR uv.user_id <> 1 THEN FALSE
            ELSE TRUE
        END has_video
FROM    videos v
LEFT JOIN
        users_videos uv
ON      uv.video_id = v.id

But one more question came to my mind:

What if i want to display videos in specific category?
Let's say it's another many to many relation on

videos and categories tables with pivot videos_categories

Body:
You want to select all videos and say for each video whether user 1 owns it. So select from videos and look up the user's videos:

select
  v.*,
  id in (select video_id from users_videos where user_id = 1) as has_video
from videos v;


问:
Database (database/database.sqlite) does not exist. Database works from artisan tinker
I created my database.sqlite file in the database folder. My .env file contents are :

```<code>DB_CONNECTION=sqlite
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=absolute\path\to\database\database.sqlite
DB_USERNAME=admin
DB_PASSWORD=
</code>```

When I run php artisan tinker and DB::table('users')->get(); I get the info from the database.

My DatabaseController is:

```<code>class DatabaseController extends Controller
{
    public function main()
    {
        $users = DB::table('users')->get();

        return view('database',compact($users));
    }
}
</code>```

Yet when I request /database path I get the error:

QueryException in Connection.php line 647:
Database (database/database.sqlite) does not exist. (SQL: select * from "users")

UPDATE:
A temporary fix is to change the database.php from the config folder:

```<code>  'connections' => [

    'sqlite' => [
        'driver' => 'sqlite',
        'database' => 'absolute\path\database\database.sqlite',
        'prefix' => '',
    ],
</code>```

Instead of using env('DB_DATABASE', database_path('database.sqlite')), which returns database/database.sqlite not my absolute path.

答:
You need to use full path, something like:</p>

```<code>DB_DATABASE=/home/laravel-project/database/database.sqlite
</code>```

Body:
I created my database.sqlite file in the database folder. My .env file contents are :

DB_CONNECTION=sqlite
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=absolute\path\to\database\database.sqlite
DB_USERNAME=admin
DB_PASSWORD=

When I run php artisan tinker and DB::table('users')->get(); I get the info from the database.

My DatabaseController is:

class DatabaseController extends Controller
{
    public function main()
    {
        $users = DB::table('users')->get();

        return view('database',compact($users));
    }
}

Yet when I request /database path I get the error:

QueryException in Connection.php line 647:
Database (database/database.sqlite) does not exist. (SQL: select * from "users")

UPDATE:
A temporary fix is to change the database.php from the config folder:

  'connections' => [

    'sqlite' => [
        'driver' => 'sqlite',
        'database' => 'absolute\path\database\database.sqlite',
        'prefix' => '',
    ],

Instead of using env('DB_DATABASE', database_path('database.sqlite')), which returns database/database.sqlite not my absolute path.

Body:
You need to use full path, something like:

DB_DATABASE=/home/laravel-project/database/database.sqlite


问:
How to get the same out of php hash with C#
I have been working, trying to get a C# equivalent of a PHP API, I was getting error message as invalid hash, so I decided to break the code in parts and check the out put of the individual part for both PHP and C#.
Below is what I got:

The code and out put of php ref:

```<code>$ref = time().mt_rand(0,9999999);

----Out put as at the time it was tested----
14909496966594256
</code>```

In my C# code for ref is as follows:

```<code>string refl = (DateTime.UtcNow .Subtract( new DateTime(1970, 1, 1, 0, 0, 0, 0))).TotalSeconds + rnd.Next(0, 9999999).ToString();

----Out put as at the time it was tested----

1490602845.686821282389
</code>```

The php hash out put with the following variables is as follows:

```<code>$task = 'pay';
$merchant_email_on_voguepay = 'merchant@example.com';
$ref = '14909496966594256';
$command_api_token = '9ufkS6FJffGplu9t7uq6XPPVQXBpHbaN';
$hash = hash('sha512',$command_api_token.$task.$merchant_email_on_voguepay.$ref);

----Out put ----
1cee97da4c0b742b6d5cdc463914fe07c04c6aff8d999fb7ce7aaa05076ea17577752ecf8947e5b98e7305ef09e0de2fed73e4817d906d6b123e54c1f9b15e74
</code>```

Then the C# out put using the same variables and the same PHP ref out put

```<code> const string task = "Pay";
 const string command_api_token = "9ufkS6FJffGplu9t7uq6XPPVQXBpHbaN";
 const string merchant_email_on_voguepay = "merchant@example.com";

     Random rnd = new Random();
     string refl = "14909496966594256";
     string hash_target = (command_api_token + task + merchant_email_on_voguepay + refl);

     SHA512 sha512 = new System.Security.Cryptography.SHA512Managed();

     var bytes = UTF8Encoding.UTF8.GetBytes(hash_target);
     string cryString = BitConverter.ToString(sha512.ComputeHash(bytes));
     string hashD = (cryString).Replace("-", string.Empty).ToLower();

  ----Out put ----
 551b057b64f49fc6bd7d428a8e3c36ddaab5e468fd5f9042ad5d4a4fa50349e5312ad2097b4e46d1e74a5a3f4e843848352edb0ea7073dd1cd53b1c4c14ab286
</code>```

Here I discovered that the out put of my C# is different from that of php. so what could be the problem with my code, I will like to get the same out put of that of php using the same variables.

Any good idea to resolve this is welcome.

答:
In your C# code, the value of task is "Pay".
In the PHP code it's "pay".

Different input values will, naturally, not hash the same.

Body:
I have been working, trying to get a C# equivalent of a PHP API, I was getting error message as invalid hash, so I decided to break the code in parts and check the out put of the individual part for both PHP and C#.
Below is what I got:

The code and out put of php ref:

$ref = time().mt_rand(0,9999999);

----Out put as at the time it was tested----
14909496966594256

In my C# code for ref is as follows:

string refl = (DateTime.UtcNow .Subtract( new DateTime(1970, 1, 1, 0, 0, 0, 0))).TotalSeconds + rnd.Next(0, 9999999).ToString();

----Out put as at the time it was tested----

1490602845.686821282389

The php hash out put with the following variables is as follows:

$task = 'pay';
$merchant_email_on_voguepay = 'merchant@example.com';
$ref = '14909496966594256';
$command_api_token = '9ufkS6FJffGplu9t7uq6XPPVQXBpHbaN';
$hash = hash('sha512',$command_api_token.$task.$merchant_email_on_voguepay.$ref);

----Out put ----
1cee97da4c0b742b6d5cdc463914fe07c04c6aff8d999fb7ce7aaa05076ea17577752ecf8947e5b98e7305ef09e0de2fed73e4817d906d6b123e54c1f9b15e74

Then the C# out put using the same variables and the same PHP ref out put

 const string task = "Pay";
 const string command_api_token = "9ufkS6FJffGplu9t7uq6XPPVQXBpHbaN";
 const string merchant_email_on_voguepay = "merchant@example.com";

     Random rnd = new Random();
     string refl = "14909496966594256";
     string hash_target = (command_api_token + task + merchant_email_on_voguepay + refl);

     SHA512 sha512 = new System.Security.Cryptography.SHA512Managed();

     var bytes = UTF8Encoding.UTF8.GetBytes(hash_target);
     string cryString = BitConverter.ToString(sha512.ComputeHash(bytes));
     string hashD = (cryString).Replace("-", string.Empty).ToLower();

  ----Out put ----
 551b057b64f49fc6bd7d428a8e3c36ddaab5e468fd5f9042ad5d4a4fa50349e5312ad2097b4e46d1e74a5a3f4e843848352edb0ea7073dd1cd53b1c4c14ab286

Here I discovered that the out put of my C# is different from that of php. so what could be the problem with my code, I will like to get the same out put of that of php using the same variables.

Any good idea to resolve this is welcome.