问:
Show play timing, remaining time of play
I use the following code to play the recorded audio file, it works fine. I have a seekbar which shows the progress of the play. I have two static text called start and end. I need to show the duration of the play (00.00 to max duration) in the start text and decrement the time from max duration to 00.00. I need to show the progressing time, remaining time... Any suggestion..</p>

<p>```
private void playAudio() {
        // TODO Auto-generated method stub
        start.setVisibility(View.VISIBLE);
        end.setVisibility(View.VISIBLE);
        Context context = getApplicationContext();
        CharSequence text1 = "Your audio will play";
        int duration = Toast.LENGTH_SHORT;
        Toast toast1 = Toast.makeText(context, text1, duration);
        toast1.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast1.show();</p>

<code>    String newFolderName = "/ComAudioRecorder";
    String extstoredir = Environment.getExternalStorageDirectory()
            .toString();
    String filename = "/combinedrecaudio.wav";
    String path1 = extstoredir + newFolderName + filename;
    Log.d("path1", path1);
    /*
     * String path=path2; Log.d("path",path);
     */
     mPlayer = new MediaPlayer();
    try {
        mPlayer.setDataSource(path1);
        mPlayer.prepare();
        mPlayer.start();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mSeekBar.setMax(mPlayer.getDuration());
    new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (mPlayer != null
                    && mPlayer.getCurrentPosition() < mPlayer.getDuration()) {
                Log.d("Indide Run Method",Integer.toString(mPlayer.getCurrentPosition()));
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                mSeekBar.setProgress(mPlayer.getCurrentPosition());
      start.setText(Long.toString(startTime));
                //end.setText(Double.toString());
            }
        }

    }).start();
     pos=mPlayer.getCurrentPosition();
    mSeekBar.setProgress(mPlayer.getCurrentPosition());
    // mPlay.setVisibility(View.INVISIBLE);
    pauseRecord.setVisibility(View.INVISIBLE);
    resumeRec.setVisibility(View.VISIBLE);
    /*start.setText(Double.toString(starttext));
    starttext=starttext+00.01;*/
    // start.setText((int) (mPlayer.getCurrentPosition()/100000.0));
    // end.setText(currentTime);

    // start.setText();
    // mDelete.setVisibility(View.INVISIBLE);

}
</code>```

答:
you cann't update the UI in the thread.you can post them to Runnable.

in the run method() put the following code.

```<code>mHandler.post(updateUI);
</code>```

then use handler to update the ui

```<code> private final Runnable updateUI= new Runnable()
        {
            public void run()
            {
                try
                {
                    //update ur ui here
                      start.setText((mPlayer.getCurrentPosition()/mPlayer.getDuration())*100);  end.setText(mPlayer.getDuration()-mPlayer.getCurrentPosition())

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        };
        private final Handler mHandler = new Handler();
</code>```

Body:
I use the following code to play the recorded audio file, it works fine. I have a seekbar which shows the progress of the play. I have two static text called start and end. I need to show the duration of the play (00.00 to max duration) in the start text and decrement the time from max duration to 00.00. I need to show the progressing time, remaining time... Any suggestion..

private void playAudio() {
        // TODO Auto-generated method stub
        start.setVisibility(View.VISIBLE);
        end.setVisibility(View.VISIBLE);
        Context context = getApplicationContext();
        CharSequence text1 = "Your audio will play";
        int duration = Toast.LENGTH_SHORT;
        Toast toast1 = Toast.makeText(context, text1, duration);
        toast1.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast1.show();

    String newFolderName = "/ComAudioRecorder";
    String extstoredir = Environment.getExternalStorageDirectory()
            .toString();
    String filename = "/combinedrecaudio.wav";
    String path1 = extstoredir + newFolderName + filename;
    Log.d("path1", path1);
    /*
     * String path=path2; Log.d("path",path);
     */
     mPlayer = new MediaPlayer();
    try {
        mPlayer.setDataSource(path1);
        mPlayer.prepare();
        mPlayer.start();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mSeekBar.setMax(mPlayer.getDuration());
    new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (mPlayer != null
                    && mPlayer.getCurrentPosition() < mPlayer.getDuration()) {
                Log.d("Indide Run Method",Integer.toString(mPlayer.getCurrentPosition()));
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                mSeekBar.setProgress(mPlayer.getCurrentPosition());
      start.setText(Long.toString(startTime));
                //end.setText(Double.toString());
            }
        }

    }).start();
     pos=mPlayer.getCurrentPosition();
    mSeekBar.setProgress(mPlayer.getCurrentPosition());
    // mPlay.setVisibility(View.INVISIBLE);
    pauseRecord.setVisibility(View.INVISIBLE);
    resumeRec.setVisibility(View.VISIBLE);
    /*start.setText(Double.toString(starttext));
    starttext=starttext+00.01;*/
    // start.setText((int) (mPlayer.getCurrentPosition()/100000.0));
    // end.setText(currentTime);

    // start.setText();
    // mDelete.setVisibility(View.INVISIBLE);

}

Body:
you cann't update the UI in the thread.you can post them to Runnable.

in the run method() put the following code.

mHandler.post(updateUI);

then use handler to update the ui

 private final Runnable updateUI= new Runnable()
        {
            public void run()
            {
                try
                {
                    //update ur ui here
                      start.setText((mPlayer.getCurrentPosition()/mPlayer.getDuration())*100);  end.setText(mPlayer.getDuration()-mPlayer.getCurrentPosition())

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        };
        private final Handler mHandler = new Handler();


来源: stackexchange

问:
How to hide endpoints from OpenAPI documentation with Springdoc
Springdoc automatically generates a API documentation for all handler methods. Even if there are no OpenAPI annotations.

How can I hide endpoints from the API documentation?

答:
The @io.swagger.v3.oas.annotations.Hidden annotation can be used at the method or class level of a controller to hide one or all endpoints.

(See: https://springdoc.org/faq.html#how-can-i-hide-an-operation-or-a-controller-from-documentation)

Example:

@Hidden // Hide all endpoints
@RestController
@RequestMapping(path = "/test")
public class TestController {

    private String test = "Test";

    @Operation(summary = "Get test string", description = "Returns a test string", tags = { "test" })
    @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Success" ) })
    @GetMapping(value = "", produces = MediaType.TEXT_PLAIN_VALUE)
    public @ResponseBody String getTest() {
        return test;
    }

    @Hidden // Hide this endpoint
    @PutMapping(value = "", consumes = MediaType.TEXT_PLAIN_VALUE)
    @ResponseStatus(HttpStatus.OK)
    public void setTest(@RequestBody String test) {
        this.test = test;
    }

}
```

<p><strong>Edit:</strong></p>

<p>Its also possible to generate the API documentation only for controllers of specific packages.</p>

<p>Add following to your <code>application.properties</code> file:</p>

```springdoc.packagesToScan=package1, package2
```

(See: https://springdoc.org/faq.html#how-can-i-explicitly-set-which-packages-to-scan)

ContentLicense: CC BY-SA 4.0

Body:
The @io.swagger.v3.oas.annotations.Hidden annotation can be used at the method or class level of a controller to hide one or all endpoints.

(See: https://springdoc.org/faq.html#how-can-i-hide-an-operation-or-a-controller-from-documentation)

Example:

@Hidden // Hide all endpoints
@RestController
@RequestMapping(path = "/test")
public class TestController {

    private String test = "Test";

    @Operation(summary = "Get test string", description = "Returns a test string", tags = { "test" })
    @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Success" ) })
    @GetMapping(value = "", produces = MediaType.TEXT_PLAIN_VALUE)
    public @ResponseBody String getTest() {
        return test;
    }

    @Hidden // Hide this endpoint
    @PutMapping(value = "", consumes = MediaType.TEXT_PLAIN_VALUE)
    @ResponseStatus(HttpStatus.OK)
    public void setTest(@RequestBody String test) {
        this.test = test;
    }

}

Edit:

Its also possible to generate the API documentation only for controllers of specific packages.

Add following to your application.properties file:

springdoc.packagesToScan=package1, package2

(See: https://springdoc.org/faq.html#how-can-i-explicitly-set-which-packages-to-scan)


问:
Github Organization "remote: Repository not found." via Https Clone
I have been using Github as an individual for some time. Now I need to create an organization and start a repo in the organization.

So, logged in to Github as myself, I created the new organization. I then created a repo. Viewing the repo I can see that I am a contributor to the repo. The repo is, and needs to be, private.

When I try to clone:

```<code>$ git clone https://github.com/my-organization/my-repo.git my-repo-folder
Cloning into 'my-repo-folder'...
remote: Repository not found.
fatal: repository 'https://github.com/my-organization/my-repo.git/' not found
</code>```

Locally git is remembering my credentials, so for example, if I have a repository in my personal Github repos, which is private, then
git clone https://github.com/Webern/my-personal-private-repo.git works without requesting that I re-enter my Github username and password.

What is going on with the organization? How do I clone my newly-formed organizations private repo?

答:
In case you have access tokens enabled for your GitHub account, make sure to tick the entire repo setting under Developer settings -> Personal access tokens as shown here (Step 7). Enabling all suboptions in the repo category is not enough.

That did the trick for me. No need to reset your credentials anywhere.

I had only the public_repo option enabled and that was sufficient to clone and push to my public repos but not to private repos in the organization where I even had an admin role.

The error is quite cryptic and misleading, especially when you are sure to have all the access rights.

ContentLicense: CC BY-SA 3.0

Body:
I have been using Github as an individual for some time. Now I need to create an organization and start a repo in the organization.

So, logged in to Github as myself, I created the new organization. I then created a repo. Viewing the repo I can see that I am a contributor to the repo. The repo is, and needs to be, private.

When I try to clone:

$ git clone https://github.com/my-organization/my-repo.git my-repo-folder
Cloning into 'my-repo-folder'...
remote: Repository not found.
fatal: repository 'https://github.com/my-organization/my-repo.git/' not found

Locally git is remembering my credentials, so for example, if I have a repository in my personal Github repos, which is private, then
git clone https://github.com/Webern/my-personal-private-repo.git works without requesting that I re-enter my Github username and password.

What is going on with the organization? How do I clone my newly-formed organizations private repo?


问:
How to insert arrays into objects that are inside an array? For ng2-charts / Charts.js
Let's say I have 2 arrays:

```<code>var array1 = [1,1,1];
var array2 = [2,2,2];
</code>```

How do I create the parent array with the 2 objects shown below?

(I'm trying to insert the given arrays above into a parent array with 2 objects, but I also still need to create the objects so that they include the keys shown.  This is to comply with the ng2-charts ChartDataSets type.)

```<code>// below is what I'm trying to accomplish, but I only have the 2 arrays above so far
[
  { data : array1, label: 'some label1' },
  { data : array2, label: 'some label2' },
]
</code>```

答:
use map and spread operator </p>

```<code>const array1 = [1,1,1];
const array2 = [2,2,2];

const parentArr = [
  { label: 'some label1' },
  { label: 'some label2' },
]

function a (array) {
  return parentArr1 = parentArr.map(it => {
    return {...it, data: array }
  })
}

console.log(a(array1))
console.log(a(array2))
</code>```

Body:
Let's say I have 2 arrays:

var array1 = [1,1,1];
var array2 = [2,2,2];

How do I create the parent array with the 2 objects shown below?

(I'm trying to insert the given arrays above into a parent array with 2 objects, but I also still need to create the objects so that they include the keys shown.  This is to comply with the ng2-charts ChartDataSets type.)

// below is what I'm trying to accomplish, but I only have the 2 arrays above so far
[
  { data : array1, label: 'some label1' },
  { data : array2, label: 'some label2' },
]

Body:
use map and spread operator

const array1 = [1,1,1];
const array2 = [2,2,2];

const parentArr = [
  { label: 'some label1' },
  { label: 'some label2' },
]

function a (array) {
  return parentArr1 = parentArr.map(it => {
    return {...it, data: array }
  })
}

console.log(a(array1))
console.log(a(array2))


问:
can i Change jitsi front-end and download from own repository
I want to some changes in jitsi and install from my own repository.
Actually after some changes, i want to install it in many servers with each servers have unique domain.</p>

答:
You can change the front-end with two options :

Option 1 (recommended)

Follow the manual installation documentation and replace «jitsi-meet» component which is in /srv/jitsi-meet

This directory must contain your version of jitsi-meet (you must build the project, follow this step but clone your repository instead official repository)

Option 2 (not recommended)

Follow the quick installation then replace the /usr/share/jitsi-meet

This is the same step but in another directory

Be careful, this option is faster but each update on jisti-meet package (apt) can break your installation and override the /usr/share/jitsi-meet directory


问:
Only allowing consumers from certain hosts/IPs access to kafka topics
We have a Kafka-based system, and a large team of devs who are working on this system. We are still in development and testing phase, and have not gone to production yet. For majority of local dev testing, we do not need to consume Kafka messages, but we do need to interact with databases and other applications in the QA environment, so devs will use the QA profile properties when running their application (these are Java Spring Boot apps).

The problem is when a dev runs an application locally with a QA profile, the local app is consuming messages from the QA environment and disrupting testing. We have a larger concern too that when we go to production, a dev might run with a production profile to be able to look at some production data, and unintentionally consume production messages, causing significant problems.

Is there a way to configure Kafka to only allow certain hosts/IPs to consume it's messages?

答:
You need to configure Authorisation using ACL.

How to enable ACL:

In your server.properties file, you need to create an Authorizer by adding the following line:

```<code>authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer
</code>```

Now you need to follow the docs in order to properly configure ACL based on your use cases.

Adding ACLs

Now once everything is in place, let's assume you have a topic called testTopic to which you want to grant read and write access only to user called Bob from a host with IP 197.5.6.1:

```<code>bin/kafka-acls \
  --authorizer-properties zookeeper.connect=localhost:2181 \
  --add \
  --allow-principal User:'Bob' --allow-host '197.5.6.1' \
  --operation Read --operation Write \
  --topic testTopic \
</code>```

Body:
You need to configure Authorisation using ACL.

How to enable ACL:

In your server.properties file, you need to create an Authorizer by adding the following line:

authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer

Now you need to follow the docs in order to properly configure ACL based on your use cases.

Adding ACLs

Now once everything is in place, let's assume you have a topic called testTopic to which you want to grant read and write access only to user called Bob from a host with IP 197.5.6.1:

bin/kafka-acls \
  --authorizer-properties zookeeper.connect=localhost:2181 \
  --add \
  --allow-principal User:'Bob' --allow-host '197.5.6.1' \
  --operation Read --operation Write \
  --topic testTopic \


问:
cannot send mail using php mail function
Im trying to use PHP mail on my local computer,  but its just not working. I am using the standard script from the php website:

PHP error I'm getting

```<code>SMTP server response: 550 Error sending message: Error: FROM address is invalid
</code>```

actual PHP

```<code>$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
</code>```

i downloaded a local mail server, argosoft.  it says the service URL is http://services.argosoft.com/RelayService/Service.asmx . I assume this is what i put in php.ini.

php ini.

```<code> For Win32 only.
 SMTP = services.argosoft.com/RelayService/Service.asmx
 smtp_port = 25
</code>```

答:
Replace @example.com with real email addresses.

and in PHP.ini set

```<code>SMTP = localhost
</code>```

Body:
Im trying to use PHP mail on my local computer,  but its just not working. I am using the standard script from the php website:

PHP error I'm getting

SMTP server response: 550 Error sending message: Error: FROM address is invalid

actual PHP

$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

i downloaded a local mail server, argosoft.  it says the service URL is http://services.argosoft.com/RelayService/Service.asmx . I assume this is what i put in php.ini.

php ini.

 For Win32 only.
 SMTP = services.argosoft.com/RelayService/Service.asmx
 smtp_port = 25

Body:
Replace @example.com with real email addresses.

and in PHP.ini set

SMTP = localhost


问:
Why is border collapse and spacing not working when you target only the Table Head (TH) inside a Table?
My HTML:

```<code><table style="width:100%">

    <tr>
        <th>First name</th>
        <th>Last name</th>
        <th>Age</th>

    </tr>

    <tr>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>

    </tr>

    <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>

    </tr>

</table>
</code>```

My CSS:

```<code>table, th, td {
margin-top:150px;
margin-bottom:150px;
border:1px solid black;

}

th, td {
    padding:15px;
}

th {

    text-align:left;
    border-collapse:collapse;

}
</code>```

I want to collapse the borders of the TH only, but it's not working. Border collapse and border spacing aren't working when i target only the TH. I can change the background color and the padding and do other changes to TH only, but border changes seems to not work. Why is that?

Note: Before you tell me how it can be done using other ways, please tell me why THIS way isn't working.

答:
as everybody told you , border-collapse is a rule set for the whole table, it tells how  cells should be printed at screen side by sides.

A work around could be to fake borders with a box-shadow.

inside tds :

table {
  border-collapse: collapse;
}

th {
  border: solid 2px;
  box-shadow: inset 0 -2px;
}

td {
  border: solid transparent;
  box-shadow: inset 0 0 0 2px;
  padding:3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> Cell 1 </td>
      <td> Cell 2 </td>
    </tr>
    <tr>
      <td> Cell 3 </td>
      <td> Cell 4 </td>
    </tr>
  </tbody>
</table></code>```

outside th

thead {
  padding-bottom: 2px;
}

th {
  border: 0;
  box-shadow: 0 -2px, inset 0 -2px, 2px 0, -2px 0, 2px -2px, -2px -2px;
  padding: 2px;
}

td {
  border: solid 2px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> Cell 1 </td>
      <td> Cell 2 </td>
    </tr>
    <tr>
      <td> Cell 3 </td>
      <td> Cell 4 </td>
    </tr>
  </tbody>
</table></code>```

Body:
My HTML:

        First name
        Last name
        Age

        Jill
        Smith
        50

        Eve
        Jackson
        94

My CSS:

table, th, td {
margin-top:150px;
margin-bottom:150px;
border:1px solid black;

}

th, td {
    padding:15px;
}

th {

    text-align:left;
    border-collapse:collapse;

}

I want to collapse the borders of the TH only, but it's not working. Border collapse and border spacing aren't working when i target only the TH. I can change the background color and the padding and do other changes to TH only, but border changes seems to not work. Why is that?

Note: Before you tell me how it can be done using other ways, please tell me why THIS way isn't working.

Body:
as everybody told you , border-collapse is a rule set for the whole table, it tells how  cells should be printed at screen side by sides.

A work around could be to fake borders with a box-shadow.

inside tds :

table {
  border-collapse: collapse;
}

th {
  border: solid 2px;
  box-shadow: inset 0 -2px;
}

td {
  border: solid transparent;
  box-shadow: inset 0 0 0 2px;
  padding:3px;
}

<table>
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> Cell 1 </td>
      <td> Cell 2 </td>
    </tr>
    <tr>
      <td> Cell 3 </td>
      <td> Cell 4 </td>
    </tr>
  </tbody>
</table>

outside th

thead {
  padding-bottom: 2px;
}

th {
  border: 0;
  box-shadow: 0 -2px, inset 0 -2px, 2px 0, -2px 0, 2px -2px, -2px -2px;
  padding: 2px;
}

td {
  border: solid 2px;
}

<table>
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> Cell 1 </td>
      <td> Cell 2 </td>
    </tr>
    <tr>
      <td> Cell 3 </td>
      <td> Cell 4 </td>
    </tr>
  </tbody>
</table>


问:
How to preconfigure a SharePoint WebPart?
What is the best way to preconfigure a custom SharePoint WebPart?

Is it e.g. possible to add a textfile to the WSP package and simply read the file from the WebPart? I couldn't figure out a way to retrieve the path of the textfile after the deployment.

Or can I somehow add key value pairs to the .webpart file and access them from my WebPart?

答:
The schema for .webpart files is here:

http://msdn.microsoft.com/en-us/library/ms227561.aspx

and allows for you to set default value properties for your WebPart.

Also, since you are running in the context of an assembly, you could read a file of config data from inside that assembly.  The first answer to this question shows you how:

How to read embedded resource text file


问:
Java set different IP address on DatagramSocket
I want to simulate a network on my computer.
I want to send each packet with a different IP address.
How do I set the IP address on the Socket?

For example, I want to set my IP address is 192.168.1.1 or 192.168.1.1/24.
How do I do?

I only know how to set the port number.

private static DatagramSocket socket;
socket = new DatagramSocket(1024);

Can I use
DatagramSocket(int port, InetAddress laddr)
to initial my socket?

if yes, what should I input in the parameter "laddr"?

答:
Assuming you mean set the source IP address - you can't.  A UDP socket is bound to a particular IP interface (or interfaces) on your computer.  The IP interface is what 'has' the address. A program using IP sockets only gets to choose which existing interface to use.

Note that even if you could arbitrarily set the source-address field in an outgoing datagram, there would be no simple way to receive any reply - because there's nothing on your computer responding to your chosen address (there is no IP interface at that address).

If you want to simulate having different IP addresses in a program,, you'll need to simulate IP. That would involve using raw sockets, but there does not seem to be a Java implementation for that.


问:
Failed to deploy Spring Boot application to WildFly
When I tried to deploy a Spring Boot application, in war packaging, to WildFly, errors came up as:

```<code>21:20:58,211 ERROR [org.springframework.boot.SpringApplication] (ServerService Thread Pool -- 24) Application run failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field "MAX_HEADER_SIZE" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:603)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:152)
    at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:132)
    at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:92)
    at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:172)
    at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:204)
    at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:186)
    at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)
    at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
    at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:252)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:96)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:78)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266)
    at java.util.concurrent.FutureTask.run(FutureTask.java)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
    at java.lang.Thread.run(Thread.java:748)
    at org.jboss.threads.JBossThread.run(JBossThread.java:485)
Caused by: java.lang.LinkageError: loader constraint violation: when resolving field "MAX_HEADER_SIZE" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type
    at org.springframework.boot.autoconfigure.web.embedded.UndertowWebServerFactoryCustomizer.customize(UndertowWebServerFactoryCustomizer.java:79)
    at org.springframework.boot.autoconfigure.web.embedded.UndertowWebServerFactoryCustomizer.customize(UndertowWebServerFactoryCustomizer.java:57)
    at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.lambda$postProcessBeforeInitialization$0(WebServerFactoryCustomizerBeanPostProcessor.java:72)
    at org.springframework.boot.util.LambdaSafe$Callbacks.lambda$null$0(LambdaSafe.java:287)
    at org.springframework.boot.util.LambdaSafe$LambdaSafeCallback.invoke(LambdaSafe.java:159)
    at org.springframework.boot.util.LambdaSafe$Callbacks.lambda$invoke$1(LambdaSafe.java:286)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1082)
    at org.springframework.boot.util.LambdaSafe$Callbacks.invoke(LambdaSafe.java:286)
    at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.postProcessBeforeInitialization(WebServerFactoryCustomizerBeanPostProcessor.java:72)
    at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.postProcessBeforeInitialization(WebServerFactoryCustomizerBeanPostProcessor.java:58)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:416)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1795)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595)
    ... 38 more
</code>```

I studies some similar reported issues, and set the spring-boot-starter-undertow to provided. HOwvwer, I still got errors. Here are pom contents:

```<code>        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <!-- exclude spring default logging to add log4j 2 -->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-juli</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-ldap</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>

        <dependency>
            <groupId>org.reactivestreams</groupId>
            <artifactId>reactive-streams</artifactId>
        </dependency>

        <!-- WildFly ejb client support -->
        <dependency>
            <groupId>org.wildfly</groupId>
            <artifactId>wildfly-ejb-client-bom</artifactId>
            <version>19.1.0.Final</version>
            <type>pom</type>
            <scope>compile</scope>
        </dependency>
</code>```

I also tried to set wildfly-ejb-client-bom to provided, errors were still there. Please kindly advise. The WildFly is 19.1.0.

答:
Wrong BOM usage.

It should be used in dependencyManagement:

```<code>  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.wildfly</groupId>
        <artifactId>wildfly-ejb-client-bom</artifactId>
        <version>19.1.0.Final</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    ...
  </dependencies>
</code>```

Body:
When I tried to deploy a Spring Boot application, in war packaging, to WildFly, errors came up as:

21:20:58,211 ERROR [org.springframework.boot.SpringApplication] (ServerService Thread Pool -- 24) Application run failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field "MAX_HEADER_SIZE" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:603)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:152)
    at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:132)
    at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:92)
    at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:172)
    at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:204)
    at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:186)
    at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)
    at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
    at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:252)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:96)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:78)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266)
    at java.util.concurrent.FutureTask.run(FutureTask.java)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
    at java.lang.Thread.run(Thread.java:748)
    at org.jboss.threads.JBossThread.run(JBossThread.java:485)
Caused by: java.lang.LinkageError: loader constraint violation: when resolving field "MAX_HEADER_SIZE" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type
    at org.springframework.boot.autoconfigure.web.embedded.UndertowWebServerFactoryCustomizer.customize(UndertowWebServerFactoryCustomizer.java:79)
    at org.springframework.boot.autoconfigure.web.embedded.UndertowWebServerFactoryCustomizer.customize(UndertowWebServerFactoryCustomizer.java:57)
    at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.lambda$postProcessBeforeInitialization$0(WebServerFactoryCustomizerBeanPostProcessor.java:72)
    at org.springframework.boot.util.LambdaSafe$Callbacks.lambda$null$0(LambdaSafe.java:287)
    at org.springframework.boot.util.LambdaSafe$LambdaSafeCallback.invoke(LambdaSafe.java:159)
    at org.springframework.boot.util.LambdaSafe$Callbacks.lambda$invoke$1(LambdaSafe.java:286)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1082)
    at org.springframework.boot.util.LambdaSafe$Callbacks.invoke(LambdaSafe.java:286)
    at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.postProcessBeforeInitialization(WebServerFactoryCustomizerBeanPostProcessor.java:72)
    at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.postProcessBeforeInitialization(WebServerFactoryCustomizerBeanPostProcessor.java:58)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:416)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1795)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595)
    ... 38 more

I studies some similar reported issues, and set the spring-boot-starter-undertow to provided. HOwvwer, I still got errors. Here are pom contents:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>

            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-juli</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-ldap</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>

        <dependency>
            <groupId>org.reactivestreams</groupId>
            <artifactId>reactive-streams</artifactId>
        </dependency>

        <dependency>
            <groupId>org.wildfly</groupId>
            <artifactId>wildfly-ejb-client-bom</artifactId>
            <version>19.1.0.Final</version>
            <type>pom</type>
            <scope>compile</scope>
        </dependency>

I also tried to set wildfly-ejb-client-bom to provided, errors were still there. Please kindly advise. The WildFly is 19.1.0.

Body:
Wrong BOM usage.

It should be used in dependencyManagement:

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.wildfly</groupId>
        <artifactId>wildfly-ejb-client-bom</artifactId>
        <version>19.1.0.Final</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    ...
  </dependencies>


问:
How to use case statement in select into clause while creating stored procedure
I am trying to create a Stored Procedure using below code. But i am getting compilation error.

```<code>create or replace procedure sp(enm number, com_stat out varhar2)
as
begin
select
(case
when (sal > 2000 and comm is not null) then ('High Sal')
when (sal < 2000 and comm is null) then ('No Comm')
end) into com_stat
from emp1 ;
dbms_output.put_line(com_stat);
end;
</code>```

Can anyone please help me on this issue.

Thanks,
Subash

答:
Datatype is varchar2, not varhar2.

Apart from that, you can omit those brackets.

```<code>SQL> create or replace procedure sp(enm number, com_stat out varchar2)
  2  as
  3  begin
  4    select case when sal > 2000 and comm is not null then 'High Sal'
  5                when sal < 2000 and comm is null     then 'No Comm'
  6           end
  7      into com_stat
  8      from emp1 ;
  9  end;
 10  /

Procedure created.

SQL>
</code>```

However, there's high possibility that procedure will raise too_man_rows as there's no WHERE clause which would restrict select to return a single value. It is probably

```<code>where emp1.empno = enm
</code>```

or something like that, missing after line #8.

Body:
I am trying to create a Stored Procedure using below code. But i am getting compilation error.

create or replace procedure sp(enm number, com_stat out varhar2)
as
begin
select
(case
when (sal > 2000 and comm is not null) then ('High Sal')
when (sal < 2000 and comm is null) then ('No Comm')
end) into com_stat
from emp1 ;
dbms_output.put_line(com_stat);
end;

Can anyone please help me on this issue.

Thanks,
Subash

Body:
Datatype is varchar2, not varhar2.

Apart from that, you can omit those brackets.

SQL> create or replace procedure sp(enm number, com_stat out varchar2)
  2  as
  3  begin
  4    select case when sal > 2000 and comm is not null then 'High Sal'
  5                when sal < 2000 and comm is null     then 'No Comm'
  6           end
  7      into com_stat
  8      from emp1 ;
  9  end;
 10  /

Procedure created.

SQL>

However, there's high possibility that procedure will raise too_man_rows as there's no WHERE clause which would restrict select to return a single value. It is probably

where emp1.empno = enm

or something like that, missing after line #8.


问:
Need DOM selector for class and attribute
```<code><div class="ag-header-cell ag-header-cell-sortable grid-column-header-forecast" col-id="AD" >

<div class="ag-header-cell ag-header-cell-sortable grid-column-header" col-id="AD" >
</code>```

I have divs that are like above. Some have 'forecast' at end of class name, some don't.

I would like a document.querySelector that would yield col-id attribute of the first forecast div.

答:
```<code>const forecast = document.querySelector('div.grid-column-header-forecast');
const colId = forecast.getAttribute('col-id');
</code>```


问:
do you know of any python component(s) for syntax highlighting?
Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) .</p>

答: You can use StyledTextCtrl in wxPython. Check out the official demo for an example (The demo code tab for any demo).

OwnerDisplayName: Geo

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Toni Ruža


问:
Altering Web.Config SessionTimeout value from within application
I am trying to work out a way to alter the session timeout dynamically, as my customer has requested that this be a value they can easily change (as though it were a database transaction). Here is a truncated version of the value I am trying to change:

```<code><appSettings>
   <add key="SessionTimeout" value="20"/>
</appsettings>
</code>```

I'm working with C#/.Net 3.5 with all of this.

For the record, I am aware that altering the web.config file will cause a restart of the application. What I am going for is to give the administrator of the program the ability to alter the timeout on the fly. If, for example, one of the forms they are requiring people to fill out is taking longer than 20 minutes, and they need to bump the time up to a half hour, or if they want it shortened for some other reason. Since we want to keep the users (including admins) out of the code files, the goal is to create this as part of the site's admin page.

The problem is, I have no idea how to do this, or if it's even possible (much less a good idea). I've given google the run around and come up with nothing.

Is there a way to make these alterations, or even potentially to dynamically change the timeout on the fly (overriding the contents of the web.config)?

Thanks for the help.

答:
Instead of trying to change web.config, how about changing Session.Timeout in code at runtime ?

More info :

http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.timeout.aspx

Body:
I am trying to work out a way to alter the session timeout dynamically, as my customer has requested that this be a value they can easily change (as though it were a database transaction). Here is a truncated version of the value I am trying to change:

<appSettings>
   <add key="SessionTimeout" value="20"/>
</appsettings>

I'm working with C#/.Net 3.5 with all of this.

For the record, I am aware that altering the web.config file will cause a restart of the application. What I am going for is to give the administrator of the program the ability to alter the timeout on the fly. If, for example, one of the forms they are requiring people to fill out is taking longer than 20 minutes, and they need to bump the time up to a half hour, or if they want it shortened for some other reason. Since we want to keep the users (including admins) out of the code files, the goal is to create this as part of the site's admin page.

The problem is, I have no idea how to do this, or if it's even possible (much less a good idea). I've given google the run around and come up with nothing.

Is there a way to make these alterations, or even potentially to dynamically change the timeout on the fly (overriding the contents of the web.config)?

Thanks for the help.


问:
Everytime data is inserted in branch table i want to create a table. but the name should come from branch table ifsccode column
To create branch table:

```<code>CREATE TABLE Branch
(
    bId int PRIMARY KEY,
    bName varchar(20),
    bCity varchar(20),
    ifscCode varchar(15)
)
</code>```

Procedure so to create a table with dynamic table name. Table name is the last inserted value of ifsccode column inserted in branch table. So that every time data is inserted into the Branch table, another table with that ifscCode name should get created:

```<code>CREATE PROCEDURE spName
AS
    DECLARE @tableName VARCHAR(200), @Query VARCHAR(7000)

    SET @tableName = 'SELECT TOP 1 ifscCode FROM Branch ORDER BY bId DESC'

BEGIN
    SET @Query = 'create table ' + @tableName + ' ( bId int, tokenDate date,
slot int, uToken int,username varchar(30),
FOREIGN KEY (username) REFERENCES UserDetails(username),
FOREIGN KEY (bId) REFERENCES Branch(bId)
)'

    EXECUTE (@Query)
END
</code>```

Insert data:

```<code>INSERT INTO Branch
VALUES (1, 'Bandra', 'Mumbai', 'BOI650011')
</code>```

Error:

Msg 156, Level 15, State 1, Line 1

  Incorrect syntax near the keyword 'SELECT'.

Msg 102, Level 15, State 1, Line 1

  Incorrect syntax near 'bId'

答:
Storing table names in columns is generally a bad idea.  My general thoughts on the matter are that if you do it, you should have such a strong understanding of SQL that a question like this would never occur.

In any case, you would see your problem immediately if you printed out the SQL.  It would look something like this:

```<code>'CREATE TABLE SELECT TOP 1 ifscCode FROM Branch ORDER BY bId DESC . . . '
</code>```

The issue is this line:

```<code>set @tableName = 'SELECT TOP 1 ifscCode FROM Branch ORDER BY bId DESC';
</code>```

You are setting the value of @tableName to a string.  You want the actual value:

```<code>set @tableName = (SELECT TOP 1 ifscCode FROM Branch ORDER BY bId DESC);
</code>```

Body:
To create branch table:

CREATE TABLE Branch
(
    bId int PRIMARY KEY,
    bName varchar(20),
    bCity varchar(20),
    ifscCode varchar(15)
)

Procedure so to create a table with dynamic table name. Table name is the last inserted value of ifsccode column inserted in branch table. So that every time data is inserted into the Branch table, another table with that ifscCode name should get created:

CREATE PROCEDURE spName
AS
    DECLARE @tableName VARCHAR(200), @Query VARCHAR(7000)

    SET @tableName = 'SELECT TOP 1 ifscCode FROM Branch ORDER BY bId DESC'

BEGIN
    SET @Query = 'create table ' + @tableName + ' ( bId int, tokenDate date,
slot int, uToken int,username varchar(30),
FOREIGN KEY (username) REFERENCES UserDetails(username),
FOREIGN KEY (bId) REFERENCES Branch(bId)
)'

    EXECUTE (@Query)
END

Insert data:

INSERT INTO Branch
VALUES (1, 'Bandra', 'Mumbai', 'BOI650011')

Error:

Msg 156, Level 15, State 1, Line 1

  Incorrect syntax near the keyword 'SELECT'.

Msg 102, Level 15, State 1, Line 1

  Incorrect syntax near 'bId'

Body:
Storing table names in columns is generally a bad idea.  My general thoughts on the matter are that if you do it, you should have such a strong understanding of SQL that a question like this would never occur.

In any case, you would see your problem immediately if you printed out the SQL.  It would look something like this:

'CREATE TABLE SELECT TOP 1 ifscCode FROM Branch ORDER BY bId DESC . . . '

The issue is this line:

set @tableName = 'SELECT TOP 1 ifscCode FROM Branch ORDER BY bId DESC';

You are setting the value of @tableName to a string.  You want the actual value:

set @tableName = (SELECT TOP 1 ifscCode FROM Branch ORDER BY bId DESC);


问:
How to set the width and height of a button in Flutter?
I have seen that I can't set the width of a ElevatedButton in Flutter. If I have well understood, I should put the ElevatedButton into a SizedBox. I will then be able to set the width or height of the box. Is it correct? Is there another way to do it?

This is a bit tedious to create a SizedBox around every buttons so I'm wondering why they have chosen to do it this way. I'm pretty sure that they have a good reason to do so but I don't see it.
The scaffolding is pretty difficult to read and to build for a beginner.

```<code>new SizedBox(
  width: 200.0,
  height: 100.0,
  child: ElevatedButton(
    child: Text('Blabla blablablablablablabla bla bla bla'),
    onPressed: _onButtonPressed,
  ),
),
</code>```

答:
Use Media Query to use width wisely for your solution which will run the same for small and large screen

```<code>  Container(
            width: MediaQuery.of(context).size.width * 0.5, // Will take 50% of screen space
            child: RaisedButton(
              child: Text('Go to screen two'),
              onPressed: () => null
            ),
          )
</code>```

You can apply a similar solution to SizeBox also.

Body:
I have seen that I can't set the width of a ElevatedButton in Flutter. If I have well understood, I should put the ElevatedButton into a SizedBox. I will then be able to set the width or height of the box. Is it correct? Is there another way to do it?

This is a bit tedious to create a SizedBox around every buttons so I'm wondering why they have chosen to do it this way. I'm pretty sure that they have a good reason to do so but I don't see it.
The scaffolding is pretty difficult to read and to build for a beginner.

new SizedBox(
  width: 200.0,
  height: 100.0,
  child: ElevatedButton(
    child: Text('Blabla blablablablablablabla bla bla bla'),
    onPressed: _onButtonPressed,
  ),
),

Body:
Use Media Query to use width wisely for your solution which will run the same for small and large screen

  Container(
            width: MediaQuery.of(context).size.width * 0.5, // Will take 50% of screen space
            child: RaisedButton(
              child: Text('Go to screen two'),
              onPressed: () => null
            ),
          )

You can apply a similar solution to SizeBox also.


问:
How to write a script to open a PDF file in Unity when image target is tracked?
I want to open a pdf file whenever my image target is tracked.
I know that if i want to open a pdf file with Unity i need to write this: Application.OpenURL("file:///c:/filename.PDF"); but i want it to open only if the image target is tracked.

I think one possible way to solve this would be to change the DefaultTrackableEventHandler.cs so it will contain a boolean that will change when  tracking is found=true \ lost=false.

Anybody here know how to achieve this with Unity and Vuforia?Thanks guys

答:
In DefaultTrackableEventHandler.cs you will find a function onTrackingFound()
add your code in this function and it will run whenever a target is found.</p>


问:
matplotlib line that follows point
How to make line that follows points. Shadow of move.
Something like that: https://www.youtube.com/watch?v=pEjZd-AvPco
Pastebin with code: https://pastebin.com/AkHaEM4i

Everything is in the link, so I can't add some more details. Gonna paste lorem ipsum...
It looks like your post is mostly code; please add some more details.

```<code>
class DoublePendulum:
    def __init__(self,
                init_state = [120,0,-20,0],
                L1 = .5,
                L2 = .5,
                M1 = 1.0,
                M2 = 2.0,
                G = 9.8,
                origin=(0,0)):
        self.init_state = np.asarray(init_state,dtype='float')
        self.params = (L1,L2,M1,M2,G)
        self.origin = origin
        self.time_elapsed = 0
        self.state = self.init_state * np.pi/180

    def position(self):
        (L1, L2, M1, M2, G) = self.params
        x = np.cumsum([self.origin[0],
                        L1 * sin(self.state[0]),
                        L2 * sin(self.state[2])])
        y = np.cumsum([self.origin[1],
                        -L1 * cos(self.state[0]),
                        -L2 * cos(self.state[2])])
        return (-x,-y)

    def dstate_dt(self,state,t):
        (M1,M2,L1,L2,G)=self.params
        dydx = np.zeros_like(state)
        dydx[0] = state[1]
        dydx[2] = state[3]

        cos_delta = cos(state[2] - state[0])
        sin_delta = sin(state[2] - state[0])

        den1 = (M1 + M2)  * L1 - M2 * L1 * cos_delta * cos_delta
        dydx[1] = (M2 * L1 * state[1] * state[1] * sin_delta * cos_delta
                + M2 * G * sin(state[2]) * cos_delta
                + M2 * L2 * state[3] * state[3] * sin_delta
                - (M1+M2) * G * sin(state[0])) / den1
        den2 = (L2 / L1) * den1
        dydx[3] = (-M2 * L2 * state[3] * state[3] * sin_delta * cos_delta
                + (M1 + M2) * G * sin(state[0]) * cos_delta
                - (M1 + M2) * L1 * state[1] * state[1] * sin_delta
                - (M1 + M2) * G * sin(state[2])) / den2

        return dydx
    def step(self,dt):
        self.state = integrate.odeint(self.dstate_dt, self.state, [0,dt])[1]
        self.time_elapsed += dt

pendulum = DoublePendulum([120.,0.0,180.,0.0],.5,.5,10,10,10)
dt = 1./30 #fps
fig = plt.figure(1)
lim1,lim2 = 2,-2

ax = fig.add_subplot(111,aspect='equal', autoscale_on=False,
                    xlim=(lim1,lim2),ylim=(lim1,lim2),alpha=0.5)

ax.grid()
line, = ax.plot([],[],'o-',lw=2)
time_text = ax.text(0.02,0.95,'', transform=ax.transAxes)

def init():
    line.set_data([],[])
    time_text.set_text('')

    return line, time_text

def animate(i):
    global pendulum, dt
    pendulum.step(dt)
    line.set_data(*pendulum.position())
    time_text.set_text('time = %.1f' % pendulum.time_elapsed)

    return line, time_text

from time import time
t0 = time()
animate(0)
t1 = time()
interval = 100 * dt - (t1-t0)

ani = animation.FuncAnimation(fig,animate,frames=150,
                            interval=interval, blit=True, init_func=init)

fig.set_size_inches(6.5, 6.5)
plt.show()
</code>```

答:
I think the referred youtube-video uses code very similiar to the code I published here:
https://github.com/jonas37/double_pendulum/</p>

Title: matplotlib line that follows point

Body:
How to make line that follows points. Shadow of move.
Something like that: https://www.youtube.com/watch?v=pEjZd-AvPco
Pastebin with code: https://pastebin.com/AkHaEM4i

Everything is in the link, so I can't add some more details. Gonna paste lorem ipsum...
It looks like your post is mostly code; please add some more details.

class DoublePendulum:
    def __init__(self,
                init_state = [120,0,-20,0],
                L1 = .5,
                L2 = .5,
                M1 = 1.0,
                M2 = 2.0,
                G = 9.8,
                origin=(0,0)):
        self.init_state = np.asarray(init_state,dtype='float')
        self.params = (L1,L2,M1,M2,G)
        self.origin = origin
        self.time_elapsed = 0
        self.state = self.init_state * np.pi/180

    def position(self):
        (L1, L2, M1, M2, G) = self.params
        x = np.cumsum([self.origin[0],
                        L1 * sin(self.state[0]),
                        L2 * sin(self.state[2])])
        y = np.cumsum([self.origin[1],
                        -L1 * cos(self.state[0]),
                        -L2 * cos(self.state[2])])
        return (-x,-y)

    def dstate_dt(self,state,t):
        (M1,M2,L1,L2,G)=self.params
        dydx = np.zeros_like(state)
        dydx[0] = state[1]
        dydx[2] = state[3]

        cos_delta = cos(state[2] - state[0])
        sin_delta = sin(state[2] - state[0])

        den1 = (M1 + M2)  * L1 - M2 * L1 * cos_delta * cos_delta
        dydx[1] = (M2 * L1 * state[1] * state[1] * sin_delta * cos_delta
                + M2 * G * sin(state[2]) * cos_delta
                + M2 * L2 * state[3] * state[3] * sin_delta
                - (M1+M2) * G * sin(state[0])) / den1
        den2 = (L2 / L1) * den1
        dydx[3] = (-M2 * L2 * state[3] * state[3] * sin_delta * cos_delta
                + (M1 + M2) * G * sin(state[0]) * cos_delta
                - (M1 + M2) * L1 * state[1] * state[1] * sin_delta
                - (M1 + M2) * G * sin(state[2])) / den2

        return dydx
    def step(self,dt):
        self.state = integrate.odeint(self.dstate_dt, self.state, [0,dt])[1]
        self.time_elapsed += dt

pendulum = DoublePendulum([120.,0.0,180.,0.0],.5,.5,10,10,10)
dt = 1./30 #fps
fig = plt.figure(1)
lim1,lim2 = 2,-2

ax = fig.add_subplot(111,aspect='equal', autoscale_on=False,
                    xlim=(lim1,lim2),ylim=(lim1,lim2),alpha=0.5)

ax.grid()
line, = ax.plot([],[],'o-',lw=2)
time_text = ax.text(0.02,0.95,'', transform=ax.transAxes)

def init():
    line.set_data([],[])
    time_text.set_text('')

    return line, time_text

def animate(i):
    global pendulum, dt
    pendulum.step(dt)
    line.set_data(*pendulum.position())
    time_text.set_text('time = %.1f' % pendulum.time_elapsed)

    return line, time_text

from time import time
t0 = time()
animate(0)
t1 = time()
interval = 100 * dt - (t1-t0)

ani = animation.FuncAnimation(fig,animate,frames=150,
                            interval=interval, blit=True, init_func=init)

fig.set_size_inches(6.5, 6.5)
plt.show()


问:
Scipy Optimize Minimize missing 1 required positional argument
I'm trying to learn how to use scipy.optimize.minimize. I'm going to need it for functions of two variables with around a thousand terms each; so I came up with an easy example first:

```<code>from scipy.optimize import minimize

def test_function(x,y):
    return x*(x-1)+y*(y-1)

mins=minimize(test_function,x0=(0,0),bounds=[(0,1),(0,1)])
</code>```

So I expect an answer of x=0.5, y=0.5.

Unfortunately, I instead get the following error:

```<code>TypeError: test_function() missing 1 required positional argument: 'y'
</code>```

What does it mean by my test function missing a positional argument?

答:
The design vector needs to be an iterable. You can unpack it within the objective function to your x and y variables. The below example assumes that x and y are scalars as in your code snippet, if they are vectors, you need to get the slices of design_variables corresponding to the length of your variables.

```<code>from scipy.optimize import minimize

def test_function(design_variables):
    x = design_variables[0]
    y = design_variables[1]
    return x*(x-1)*y*(y-1)

mins = minimize(test_function, x0=(0,0), bounds=[(0,1),(0,1)])
print(mins)
</code>```

Optimization result:

```<code>     fun: 0.0
     jac: array([0., 0.])
 message: 'Optimization terminated successfully.'
    nfev: 4
     nit: 1
    njev: 1
  status: 0
 success: True
       x: array([0., 0.])
</code>```

Body:
I'm trying to learn how to use scipy.optimize.minimize. I'm going to need it for functions of two variables with around a thousand terms each; so I came up with an easy example first:

from scipy.optimize import minimize

def test_function(x,y):
    return x*(x-1)+y*(y-1)

mins=minimize(test_function,x0=(0,0),bounds=[(0,1),(0,1)])

So I expect an answer of x=0.5, y=0.5.

Unfortunately, I instead get the following error:

TypeError: test_function() missing 1 required positional argument: 'y'

What does it mean by my test function missing a positional argument?

Body:
The design vector needs to be an iterable. You can unpack it within the objective function to your x and y variables. The below example assumes that x and y are scalars as in your code snippet, if they are vectors, you need to get the slices of design_variables corresponding to the length of your variables.

from scipy.optimize import minimize

def test_function(design_variables):
    x = design_variables[0]
    y = design_variables[1]
    return x*(x-1)*y*(y-1)

mins = minimize(test_function, x0=(0,0), bounds=[(0,1),(0,1)])
print(mins)

Optimization result:

     fun: 0.0
     jac: array([0., 0.])
 message: 'Optimization terminated successfully.'
    nfev: 4
     nit: 1
    njev: 1
  status: 0
 success: True
       x: array([0., 0.])


问:
How to pass params to Action Method from ASPX based view using window.location.href
I am trying to pass string param to Action Method using Window.location.href but its not getting passed. I am having aspx based view without codebehind. Action Method gets called but with no param value. Developer tools showing params with Status Cancelled. Please Help (Using MVC 1)

//My AccrualController

```<code>public partial class AccrualsController : BaseController
{
 public ActionResult Test(string YearAndMonth)
    {
           //Code
    }
}
</code>```

//This is how i am passing params from javascript function in Index.aspx view

```<code> window.location.href = "Accruals/Test?YearAndMonth=testvalue";
</code>```

答:
Tested the code below in an ASP.NET MVC 5 application and it works fine.

Controller:

```<code>public class AccrualsController : Controller
{
    public ActionResult Test(string YearAndMonth)
    {
        return View();
    }
}
</code>```

Home Index View:

```<code><a id="btn" href="#" class="btn btn-primary">Click Me</a>

<script>

    var btn = document.getElementById("btn");

    btn.addEventListener("click", function (e) {
        e.preventDefault();

        window.location.href = "Accruals/Test?YearAndMonth=testvalue";
    });

</script>
</code>```

Suspect it may be something to do with the way ASP.NET MVC 1.0 is configured. Which is going to be hard to work out because ASP.NET MVC 1.0 is now over 10 years old, documentation is sparse and many people will have moved on to newer versions.

Bottom line

You are using an incredibly old version of ASP.NET MVC and should consider if possible upgrading to ASP.NET MVC 5, where the code you have shown will work

Body:
I am trying to pass string param to Action Method using Window.location.href but its not getting passed. I am having aspx based view without codebehind. Action Method gets called but with no param value. Developer tools showing params with Status Cancelled. Please Help (Using MVC 1)

//My AccrualController

public partial class AccrualsController : BaseController
{
 public ActionResult Test(string YearAndMonth)
    {
           //Code
    }
}

//This is how i am passing params from javascript function in Index.aspx view

 window.location.href = "Accruals/Test?YearAndMonth=testvalue";

Body:
Tested the code below in an ASP.NET MVC 5 application and it works fine.

Controller:

public class AccrualsController : Controller
{
    public ActionResult Test(string YearAndMonth)
    {
        return View();
    }
}

Home Index View:

<a id="btn" href="#" class="btn btn-primary">Click Me</a>

<script>

    var btn = document.getElementById("btn");

    btn.addEventListener("click", function (e) {
        e.preventDefault();

        window.location.href = "Accruals/Test?YearAndMonth=testvalue";
    });

</script>

Suspect it may be something to do with the way ASP.NET MVC 1.0 is configured. Which is going to be hard to work out because ASP.NET MVC 1.0 is now over 10 years old, documentation is sparse and many people will have moved on to newer versions.

Bottom line

You are using an incredibly old version of ASP.NET MVC and should consider if possible upgrading to ASP.NET MVC 5, where the code you have shown will work


问:
Why is it bad to pause/abort threads?
My model of how threads work is that some ThreadManager gives each thread a turn.  When it's a thread's turn, it gets to execute a few lines of code.

To pause a thread, couldn't one just have the ThreadManager (momentarily) stop allowing that thread to have a turn?

To abort a thread, couldn't the ThreadManager just never give that thread another turn?

What's the problem?

答:
I agree with Alex, but to elaborate further, if you need to "pause" a thread, it will probably be better to look at some sort of locking mechanism like Semaphores, Mutexes, or one of the many other ones available.

But, without knowing your code, Windows is a preemptive multitasking environment. Usually this is not needed, just let your threads run and the underlying OS and scheduler will make sure all your tasks get a fair turn.

Title: Why is it bad to pause/abort threads?


问:
How to predict a time series set with statsmodels Holt-Winters
I have a set of data from January 2012 to December 2014 that show some trend and seasonality. I want to make a prediction for the next 2 years (from January 2015 to December 2017), by using the Holt-Winters method from statsmodels.
The data set is the following one:

```<code>date,Data
Jan-12,153046
Feb-12,161874
Mar-12,226134
Apr-12,171871
May-12,191416
Jun-12,230926
Jul-12,147518
Aug-12,107449
Sep-12,170645
Oct-12,176492
Nov-12,180005
Dec-12,193372
Jan-13,156846
Feb-13,168893
Mar-13,231103
Apr-13,187390
May-13,191702
Jun-13,252216
Jul-13,175392
Aug-13,150390
Sep-13,148750
Oct-13,173798
Nov-13,171611
Dec-13,165390
Jan-14,155079
Feb-14,172438
Mar-14,225818
Apr-14,188195
May-14,193948
Jun-14,230964
Jul-14,172225
Aug-14,129257
Sep-14,173443
Oct-14,188987
Nov-14,172731
Dec-14,211194
</code>```

Which looks like follows:

I'm trying to build the Holt-Winters model, in order to improve the prediction performance of the past data (it means, a new graph where I can see if my parameters perform a good prediction of the past) and later on forecast the next years. I made the prediction with the following code, but I'm not able to do the forecast.

```<code># Data loading
data = pd.read_csv('setpoints.csv', parse_dates=['date'], index_col=['date'])
df_data = pd.DataFrame(datos_matric, columns=['Data'])

df_data['Data'].index.freq = 'MS'
train, test = df_data['Data'], df_data['Data']
model = ExponentialSmoothing(train, trend='add', seasonal='add', seasonal_periods=12).fit()
period = ['Jan-12', 'Dec-14']
pred = model.predict(start=period[0], end=period[1])

df_data['Data'].plot(label='Train')
test.plot(label='Test')
pred.plot(label='Holt-Winters')
plt.legend(loc='best')
plt.show()
</code>```

Which looks like:

Does anyone now how to forecast it?

答:
I think you are making a misconception here. You shouldnt use the same data for train and test. The test data are datapoints which your model "has not seen yet". This way you can test how well your model is performing. So I used the last three months of your data as test.

As for the prediction, we can use different start and end points.

Also notice I used mul as seasonal component, which performs better on your data:

```<code># read in data and convert date column to MS frequency
df = pd.read_csv(data)
df['date'] = pd.to_datetime(df['date'], format='%b-%y')
df = df.set_index('date').asfreq('MS')

# split data in train, test
train = df.loc[:'2014-09-01']
test = df.loc['2014-10-01':]

# train model and predict
model = ExponentialSmoothing(train, seasonal='mul', seasonal_periods=12).fit()
#model = ExponentialSmoothing(train, trend='add', seasonal='add', seasonal_periods=12).fit()
pred_test = model.predict(start='2014-10-01', end='2014-12-01')
pred_forecast = model.predict(start='2015-01-01', end='2017-12-01')

# plot data and prediction
df.plot(figsize=(15,9), label='Train')
pred_test.plot(label='Test')
pred_forecast.plot(label='Forecast')
plt.legend()
plt.show()
plt.savefig('figure.png')
</code>```

Body:
I have a set of data from January 2012 to December 2014 that show some trend and seasonality. I want to make a prediction for the next 2 years (from January 2015 to December 2017), by using the Holt-Winters method from statsmodels.
The data set is the following one:

date,Data
Jan-12,153046
Feb-12,161874
Mar-12,226134
Apr-12,171871
May-12,191416
Jun-12,230926
Jul-12,147518
Aug-12,107449
Sep-12,170645
Oct-12,176492
Nov-12,180005
Dec-12,193372
Jan-13,156846
Feb-13,168893
Mar-13,231103
Apr-13,187390
May-13,191702
Jun-13,252216
Jul-13,175392
Aug-13,150390
Sep-13,148750
Oct-13,173798
Nov-13,171611
Dec-13,165390
Jan-14,155079
Feb-14,172438
Mar-14,225818
Apr-14,188195
May-14,193948
Jun-14,230964
Jul-14,172225
Aug-14,129257
Sep-14,173443
Oct-14,188987
Nov-14,172731
Dec-14,211194

Which looks like follows:

I'm trying to build the Holt-Winters model, in order to improve the prediction performance of the past data (it means, a new graph where I can see if my parameters perform a good prediction of the past) and later on forecast the next years. I made the prediction with the following code, but I'm not able to do the forecast.

# Data loading
data = pd.read_csv('setpoints.csv', parse_dates=['date'], index_col=['date'])
df_data = pd.DataFrame(datos_matric, columns=['Data'])

df_data['Data'].index.freq = 'MS'
train, test = df_data['Data'], df_data['Data']
model = ExponentialSmoothing(train, trend='add', seasonal='add', seasonal_periods=12).fit()
period = ['Jan-12', 'Dec-14']
pred = model.predict(start=period[0], end=period[1])

df_data['Data'].plot(label='Train')
test.plot(label='Test')
pred.plot(label='Holt-Winters')
plt.legend(loc='best')
plt.show()

Which looks like:

Does anyone now how to forecast it?

Body:
I think you are making a misconception here. You shouldnt use the same data for train and test. The test data are datapoints which your model "has not seen yet". This way you can test how well your model is performing. So I used the last three months of your data as test.

As for the prediction, we can use different start and end points.

Also notice I used mul as seasonal component, which performs better on your data:

# read in data and convert date column to MS frequency
df = pd.read_csv(data)
df['date'] = pd.to_datetime(df['date'], format='%b-%y')
df = df.set_index('date').asfreq('MS')

# split data in train, test
train = df.loc[:'2014-09-01']
test = df.loc['2014-10-01':]

# train model and predict
model = ExponentialSmoothing(train, seasonal='mul', seasonal_periods=12).fit()
#model = ExponentialSmoothing(train, trend='add', seasonal='add', seasonal_periods=12).fit()
pred_test = model.predict(start='2014-10-01', end='2014-12-01')
pred_forecast = model.predict(start='2015-01-01', end='2017-12-01')

# plot data and prediction
df.plot(figsize=(15,9), label='Train')
pred_test.plot(label='Test')
pred_forecast.plot(label='Forecast')
plt.legend()
plt.show()
plt.savefig('figure.png')


问:
How to customize Room Database Query results that we can achieve in normal SQLite Open helper class
In Room database we write queries as DAO to get results from database. In normal SQLite OpenHelper class we can customize the query results as per our need.

```<code>public ArrayList<MyData> getMyData(String id) {
        ArrayList<MyData> entries=new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM " + MYDATA + " WHERE " + ID + " = ?";
        Cursor c1 = db.rawQuery(query, new String[]{id});
        List<String> business=new ArrayList<>();
        if(c2.moveToFirst()){
                MyData entry=new MyData();
                entry.setId(c2.getString(0));
                String dataValue=c2.getString(1);
                String val="";
                if(dataValue.contains("__")){
                    String[] valueSplit =dataValue.split("__");
                    if(valueSplit[0]!=null){
                        val=address[0];
                    }
                }else{
                    val="";
                }
                entries.add(entry);
            }
        return entries;
    }
</code>```

In this query, results obtained from Database is customized based on some condition, added in ArrayList MyData object and then final result is returned. How it can be done in Room Database

答:
If i understand your question correctly you can use @query in your DAO like this

```<code>@Query("SELECT * FROM MYDATA WHERE id = :id")
public ArrayList<MyData> getMyData(String id);
</code>```

Then in your database view model expose getMyData(String id) and process your data

Body:
In Room database we write queries as DAO to get results from database. In normal SQLite OpenHelper class we can customize the query results as per our need.

public ArrayList<MyData> getMyData(String id) {
        ArrayList<MyData> entries=new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM " + MYDATA + " WHERE " + ID + " = ?";
        Cursor c1 = db.rawQuery(query, new String[]{id});
        List<String> business=new ArrayList<>();
        if(c2.moveToFirst()){
                MyData entry=new MyData();
                entry.setId(c2.getString(0));
                String dataValue=c2.getString(1);
                String val="";
                if(dataValue.contains("__")){
                    String[] valueSplit =dataValue.split("__");
                    if(valueSplit[0]!=null){
                        val=address[0];
                    }
                }else{
                    val="";
                }
                entries.add(entry);
            }
        return entries;
    }

In this query, results obtained from Database is customized based on some condition, added in ArrayList MyData object and then final result is returned. How it can be done in Room Database

Body:
If i understand your question correctly you can use @query in your DAO like this

@Query("SELECT * FROM MYDATA WHERE id = :id")
public ArrayList<MyData> getMyData(String id);

Then in your database view model expose getMyData(String id) and process your data


问:
Enabling/Disabling IntelliJ's fancy ≠ (not equal to) operator
I witnessed this in the GOTO 2016 • Kotlin - Ready for Production conference by Hadi Hariri.

In some of his code, what would normally look like:

if (x != y) { /* do some stuff */ }
```
<p>Is being displayed in an elegant style:</p>
<pre class="lang-none prettyprint-override"><code>if (x ≠ y) { /* do some stuff */ }
</code>```

The code uses the regular != operator, and the IDEA takes care of the rest.

So, how can I enable/disable this?

答:
I use Material Design Theme with Android Studio 4.0, navigate to:

File->Settings->Editor->Color Scheme->Color Scheme Font

and check Enable Font Ligatures.Do the same for:

File->Settings->Editor->Color Scheme->Console Font.

This is after choosing FiraCode as your font in inteliJ. Find it here and install it as a normal font.

Body:
I witnessed this in the GOTO 2016 • Kotlin - Ready for Production conference by Hadi Hariri.

In some of his code, what would normally look like:

if (x != y) { /* do some stuff */ }

Is being displayed in an elegant style:

if (x ≠ y) { /* do some stuff */ }

The code uses the regular != operator, and the IDEA takes care of the rest.

So, how can I enable/disable this?


问:
How to combine two flat lists into one nested object
I have three lists which contains three same properties in each collection. I want to combine a result into one collection. Ex classes structure is as below

```<code>public class Order
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }

    // Few other Properties of OrderDetail
}
public class PaymentDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form PaymentDetail
}

public class CouponUsageDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form CouponUsageDetail
}
</code>```

This type of output is coming from one API service where each class is in form of list object (JSON format) and we need to perform some operations on this. All three properties (ProductId,CustomerId, OrderId) contains same values in each collection which means all three properties are repeated in each collection. We need to perform some look ups on these collections. So in normal way what we can do with it is as - start a foreach from Order list and filter all three matching properties of PaymentDetail and CouponUsageDetail. But it would be costlier in term of performance when the data size is increased. So thought of making nesting structure upfront and avoid lookups. If we make the output nested as below this will help to avoid lookups on PaymentDetail and CouponUsageDetail.
Ex - we are receiving JOSN in below format

```<code>{"Orders":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"PaymentDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"CouponUsageDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}]}
</code>```

and with this output we want to form object as

```<code>public class OrderDetails
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties of OrderDetail

    List<PaymentDetail> PaymentDetail { get; set; }
    List<CouponUsageDetail> CouponUsageDetail { get; set; }
}
</code>```

Can you guide, what would be the best optimum usage of linq where we can combine all these three matching properties and make it just one nested structure better?
Thank You!
 Note: I know this structure needs to be normalized but please ignore the normalization rule here as this is not in our control.

答:
I have solution, but i am not sure if it's ok for you. It depends on data format that you have on the begining.

solution:

```<code>class Program
{
    static void Main(string[] args)
    {
        var collection1 = new Collection1() { PropId1 = 1, PropId2 = 2, PropId3 = 3 };

        var list2 = new List<Collection2>()
        {
            new Collection2
            {
                PropId1 = 11,
                PropId2 = 22,
                PropId3 = 33
            },
            new Collection2
            {
                PropId1 = 22,
                PropId2 = 33,
                PropId3 = 44
            }
        };
        var list3 = new List<Collection3>()
        {
            new Collection3
            {
                PropId1 = 111,
                PropId2 = 222,
                PropId3 = 333
            },
            new Collection3
            {
                PropId1 = 222,
                PropId2 = 333,
                PropId3 = 444
            }
        };

        var result = new ResultCollection(collection1, list2, list3);
        //or
        var result2 = new ResultCollection(collection1) //but in this case you have to change your constructor
        {
            Collection2s = list2,
            Collection3s = list3
        };
        Console.ReadLine();
    }
}

public class Collection1
{
    public int? PropId1 { get; set; }
    public int? PropId2 { get; set; }
    public int? PropId3 { get; set; }
}
public class Collection2
{
    public int? PropId1 { get; set; }
    public int? PropId2 { get; set; }
    public int? PropId3 { get; set; }
}
public class Collection3
{
    public int? PropId1 { get; set; }
    public int? PropId2 { get; set; }
    public int? PropId3 { get; set; }
}

public class ResultCollection : Collection1
{
    public ResultCollection() { }

    public ResultCollection(Collection1 collection, List<Collection2> list2, List<Collection3> list3)
    {
        foreach (PropertyInfo prop in collection.GetType().GetProperties())
        {
            PropertyInfo prop2 = collection.GetType().GetProperty(prop.Name);
            if (prop2.CanWrite)
                prop2.SetValue(this, prop.GetValue(collection, null), null);
        }
        Collection2s = list2;
        Collection3s = list3;
    }

    public List<Collection2> Collection2s { get; set; }

    public List<Collection3> Collection3s { get; set; }
}
</code>```

But can you give an example of input data?

Body:
I have three lists which contains three same properties in each collection. I want to combine a result into one collection. Ex classes structure is as below

public class Order
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }

    // Few other Properties of OrderDetail
}
public class PaymentDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form PaymentDetail
}

public class CouponUsageDetail
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties form CouponUsageDetail
}

This type of output is coming from one API service where each class is in form of list object (JSON format) and we need to perform some operations on this. All three properties (ProductId,CustomerId, OrderId) contains same values in each collection which means all three properties are repeated in each collection. We need to perform some look ups on these collections. So in normal way what we can do with it is as - start a foreach from Order list and filter all three matching properties of PaymentDetail and CouponUsageDetail. But it would be costlier in term of performance when the data size is increased. So thought of making nesting structure upfront and avoid lookups. If we make the output nested as below this will help to avoid lookups on PaymentDetail and CouponUsageDetail.
Ex - we are receiving JOSN in below format

{"Orders":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"PaymentDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}],"CouponUsageDetails":[{"ProductId":301,"CustomerId":101,"OrderId":201},{"ProductId":701,"CustomerId":501,"OrderId":601}]}

and with this output we want to form object as

public class OrderDetails
{
    public int ProductId { get; set; }
    public int CustomerId { get; set; }
    public int OrderId { get; set; }
    // Few other Properties of OrderDetail

    List<PaymentDetail> PaymentDetail { get; set; }
    List<CouponUsageDetail> CouponUsageDetail { get; set; }
}

Can you guide, what would be the best optimum usage of linq where we can combine all these three matching properties and make it just one nested structure better?
Thank You!
 Note: I know this structure needs to be normalized but please ignore the normalization rule here as this is not in our control.

Body:
I have solution, but i am not sure if it's ok for you. It depends on data format that you have on the begining.

solution:

class Program
{
    static void Main(string[] args)
    {
        var collection1 = new Collection1() { PropId1 = 1, PropId2 = 2, PropId3 = 3 };

        var list2 = new List<Collection2>()
        {
            new Collection2
            {
                PropId1 = 11,
                PropId2 = 22,
                PropId3 = 33
            },
            new Collection2
            {
                PropId1 = 22,
                PropId2 = 33,
                PropId3 = 44
            }
        };
        var list3 = new List<Collection3>()
        {
            new Collection3
            {
                PropId1 = 111,
                PropId2 = 222,
                PropId3 = 333
            },
            new Collection3
            {
                PropId1 = 222,
                PropId2 = 333,
                PropId3 = 444
            }
        };

        var result = new ResultCollection(collection1, list2, list3);
        //or
        var result2 = new ResultCollection(collection1) //but in this case you have to change your constructor
        {
            Collection2s = list2,
            Collection3s = list3
        };
        Console.ReadLine();
    }
}

public class Collection1
{
    public int? PropId1 { get; set; }
    public int? PropId2 { get; set; }
    public int? PropId3 { get; set; }
}
public class Collection2
{
    public int? PropId1 { get; set; }
    public int? PropId2 { get; set; }
    public int? PropId3 { get; set; }
}
public class Collection3
{
    public int? PropId1 { get; set; }
    public int? PropId2 { get; set; }
    public int? PropId3 { get; set; }
}

public class ResultCollection : Collection1
{
    public ResultCollection() { }

    public ResultCollection(Collection1 collection, List<Collection2> list2, List<Collection3> list3)
    {
        foreach (PropertyInfo prop in collection.GetType().GetProperties())
        {
            PropertyInfo prop2 = collection.GetType().GetProperty(prop.Name);
            if (prop2.CanWrite)
                prop2.SetValue(this, prop.GetValue(collection, null), null);
        }
        Collection2s = list2;
        Collection3s = list3;
    }

    public List<Collection2> Collection2s { get; set; }

    public List<Collection3> Collection3s { get; set; }
}

But can you give an example of input data?